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: python: getting substring within element in list row=['alex','liza','hello **world**','blah'] i do i get everything in row[2] that is between the ** characters? A: You could do it by hand and search for the * , but regex work too. print re.search(r'\*\*(.*)\*\*', 'hello **world**').group(1) # prints 'world' You need to know exactly what you're looking for with regex, so think about what **asd**dfe** and similar edge cases should return. A: import re print re.findall(r"\*\*(.*)\*\*", row[2]) will give you a list of every match in row[2] which is between **. Fine tune the regex as necessary A: Let's say that you don't know which element has the stars, you could use this: row=['alex','liza','hello **world**','blah'] for staritem in (item for item in row if '**' in item): print(staritem) _,_, staritem = staritem.partition('**') staritem,_,_ = staritem.partition('**') print(staritem) A: row[2].strip('*') Don't use a chainsaw when a knife will do.
python: getting substring within element in list
row=['alex','liza','hello **world**','blah'] i do i get everything in row[2] that is between the ** characters?
[ "You could do it by hand and search for the * , but regex work too.\nprint re.search(r'\\*\\*(.*)\\*\\*', 'hello **world**').group(1) # prints 'world'\n\nYou need to know exactly what you're looking for with regex, so think about what **asd**dfe** and similar edge cases should return.\n", "import re\nprint re.fin...
[ 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003390970_python.txt
Q: How to setup amazon s3 module on ubuntu? I am looking at the readme and there isn't any instructions on how to install it locally on my ubuntu machine (curious, is it different on a mac os?) http://github.com/boto/boto/blob/master/README A: There is a package on pypi: http://pypi.python.org/pypi/boto Just install like any other python package using easy_install: easy_install boto Or download the package manually and run python setup.py install. A: Amazon's documentation should help. Here's the getting started guide for S3 and Python. It's in the cheese shop, so it's as easy as sudo pip install -U boto or sudo easy_install boto
How to setup amazon s3 module on ubuntu?
I am looking at the readme and there isn't any instructions on how to install it locally on my ubuntu machine (curious, is it different on a mac os?) http://github.com/boto/boto/blob/master/README
[ "There is a package on pypi:\nhttp://pypi.python.org/pypi/boto\nJust install like any other python package using easy_install:\neasy_install boto\n\nOr download the package manually and run python setup.py install.\n", "Amazon's documentation should help. Here's the getting started guide for S3 and Python. It's i...
[ 1, 0 ]
[]
[]
[ "amazon_s3", "python" ]
stackoverflow_0003390880_amazon_s3_python.txt
Q: Python Path import problems I added a folder to my PYTHONPATH where I can put all of my Django Apps. I print sys.path, and everything looks good, the folder I want is there. However, when I go to import a module, it tells me that there's no module by that name. All the site-packages modules work fine. In all of my Django apps, there's an "_____init_____.py" like there's supposed to be. I heard that if those are created on windows there can be problems, but I couldn't dig up much more than that. A: Fixed it. Sorry Santa for not including the console print out. Windows was dumb and added an extra .py to the file when I created it. So everything was actually "pythonfile.py.py". Awesome.
Python Path import problems
I added a folder to my PYTHONPATH where I can put all of my Django Apps. I print sys.path, and everything looks good, the folder I want is there. However, when I go to import a module, it tells me that there's no module by that name. All the site-packages modules work fine. In all of my Django apps, there's an "_____init_____.py" like there's supposed to be. I heard that if those are created on windows there can be problems, but I couldn't dig up much more than that.
[ "Fixed it. Sorry Santa for not including the console print out. Windows was dumb and added an extra .py to the file when I created it. So everything was actually \"pythonfile.py.py\". Awesome.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003391368_python.txt
Q: How do I write an installer for a Windows SDK in Python? I understand that NSIS supports plugins, but I can't find an NsPython tutorial. Maybe first I should ask: if I can run Python code from NSIS, is it a good idea to script my installer in Python (instead of explicitly managing a stack in an NSIS script)? And secondly: are there any good tutorials? Alternatively: Is there another appropriate Windows installer scripting environment? I don't think wix will do the trick. A: If you download the plugin archive that you linked, there is a readme file that describes the plugin's API as well as an example NSIS installer that uses the plugin.
How do I write an installer for a Windows SDK in Python?
I understand that NSIS supports plugins, but I can't find an NsPython tutorial. Maybe first I should ask: if I can run Python code from NSIS, is it a good idea to script my installer in Python (instead of explicitly managing a stack in an NSIS script)? And secondly: are there any good tutorials? Alternatively: Is there another appropriate Windows installer scripting environment? I don't think wix will do the trick.
[ "If you download the plugin archive that you linked, there is a readme file that describes the plugin's API as well as an example NSIS installer that uses the plugin.\n" ]
[ 1 ]
[]
[]
[ "installation", "nsis", "python", "windows_installer" ]
stackoverflow_0003390203_installation_nsis_python_windows_installer.txt
Q: How do I eliminate Windows consoles from spawned processes in Python (2.7)? Possible Duplicate: Running a process in pythonw with Popen without a console I'm using python 2.7 on Windows to automate batch RAW conversions using dcraw and PIL. The problem is that I open a windows console whenever I run dcraw (which happens every couple of seconds). If I run the script using as a .py it's less annoying as it only opens the main window, but I would prefer to present only the GUI. I'm involving it like so: args = [this.dcraw] + shlex.split(DCRAW_OPTS) + [rawfile] proc = subprocess.Popen(args, -1, stdout=subprocess.PIPE) ppm_data, err = proc.communicate() image = Image.open(StringIO.StringIO(ppm_data)) Thanks to Ricardo Reyes Minor revision to that recipe, in 2.7 it appears that you need to get STARTF_USESHOWWINDOW from _subprocess (you could also use pywin32 if you want something that might be a little less prone to change), so for posterity: suinfo = subprocess.STARTUPINFO() suinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW proc = subprocess.Popen(args, -1, stdout=subprocess.PIPE, startupinfo=suinfo) A: You need to set the startupinfo parameter when calling Popen. Here's an example from an Activestate.com Recipe: import subprocess def launchWithoutConsole(command, args): """Launches 'command' windowless and waits until finished""" startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return subprocess.Popen([command] + args, startupinfo=startupinfo).wait() if __name__ == "__main__": # test with "pythonw.exe" launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])
How do I eliminate Windows consoles from spawned processes in Python (2.7)?
Possible Duplicate: Running a process in pythonw with Popen without a console I'm using python 2.7 on Windows to automate batch RAW conversions using dcraw and PIL. The problem is that I open a windows console whenever I run dcraw (which happens every couple of seconds). If I run the script using as a .py it's less annoying as it only opens the main window, but I would prefer to present only the GUI. I'm involving it like so: args = [this.dcraw] + shlex.split(DCRAW_OPTS) + [rawfile] proc = subprocess.Popen(args, -1, stdout=subprocess.PIPE) ppm_data, err = proc.communicate() image = Image.open(StringIO.StringIO(ppm_data)) Thanks to Ricardo Reyes Minor revision to that recipe, in 2.7 it appears that you need to get STARTF_USESHOWWINDOW from _subprocess (you could also use pywin32 if you want something that might be a little less prone to change), so for posterity: suinfo = subprocess.STARTUPINFO() suinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW proc = subprocess.Popen(args, -1, stdout=subprocess.PIPE, startupinfo=suinfo)
[ "You need to set the startupinfo parameter when calling Popen. \nHere's an example from an Activestate.com Recipe:\nimport subprocess\n\ndef launchWithoutConsole(command, args):\n \"\"\"Launches 'command' windowless and waits until finished\"\"\"\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFla...
[ 6 ]
[]
[]
[ "popen", "python", "subprocess", "windows" ]
stackoverflow_0003390762_popen_python_subprocess_windows.txt
Q: Creating an event filter I am trying to enable the delete key in my treeview. This is what I have so far: class delkeyFilter(QObject): delkeyPressed = pyqtSignal() def eventFilter(self, obj, event): if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Delete: self.delkeyPressed.emit() print 'delkey pressed' return True return False I connect the eventfilter like this: filter = delkeyFilter(self.dataTreeView) self.dataTreeView.installEventFilter(filter) Why do I need to pass self.dataTreeview when I create the filter? It doesn't work without it. A: @balpha is correct. The simple answer is that if you don't pass in a parent or otherwise ensure that the filter instance has a live reference, it will be garbage collected. PyQt uses SIP to bind to Qt's C++ implementation. From the SIP documentation: When a C++ instance is wrapped a corresponding Python object is created. The Python object behaves as you would expect in regard to garbage collection - it is garbage collected when its reference count reaches zero. What then happens to the corresponding C++ instance? The obvious answer might be that the instance’s destructor is called. However the library API may say that when the instance is passed to a particular function, the library takes ownership of the instance, i.e. responsibility for calling the instance’s destructor is transferred from the SIP generated module to the library. Ownership of an instance may also be associated with another instance. The implication being that the owned instance will automatically be destroyed if the owning instance is destroyed. SIP keeps track of these relationships to ensure that Python’s cyclic garbage collector can detect and break any reference cycles between the owning and owned instances. The association is implemented as the owning instance taking a reference to the owned instance. The above implies that if you pass a Python object to a Qt object that takes ownership, everything will also work, even though you haven't guaranteed that a reference to the specific object was maintained. So, to restate what @balpha said in his comment, here's one workaround for the case when you don't want to pass in an object to the constructor: self.filter = delkeyFilter() self.dataTreeView.installEventFilter(self.filter) A: Key handling is already implimented in QAbstractItemView. All you have to do is subclass the treeview, then implement keyPressEvent. class MyTreeView(QTreeView): delkeyPressed = pyqtSignal() def __init__(self): QTreeView.__init__(self) def keyPressEvent(self, event): #QKeyEvent if event.key() == Qt.Key_Delete: self.delkeyPressed.emit() print 'del key pressed' # pass the event up the chain or we will eat the event QTreeView.keyPressEvent(self, event) `
Creating an event filter
I am trying to enable the delete key in my treeview. This is what I have so far: class delkeyFilter(QObject): delkeyPressed = pyqtSignal() def eventFilter(self, obj, event): if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Delete: self.delkeyPressed.emit() print 'delkey pressed' return True return False I connect the eventfilter like this: filter = delkeyFilter(self.dataTreeView) self.dataTreeView.installEventFilter(filter) Why do I need to pass self.dataTreeview when I create the filter? It doesn't work without it.
[ "@balpha is correct. The simple answer is that if you don't pass in a parent or otherwise ensure that the filter instance has a live reference, it will be garbage collected.\nPyQt uses SIP to bind to Qt's C++ implementation. From the SIP documentation:\n\nWhen a C++ instance is wrapped a corresponding Python object...
[ 12, 4 ]
[]
[]
[ "events", "pyqt", "python", "qt" ]
stackoverflow_0003308013_events_pyqt_python_qt.txt
Q: Internal Server Error on Django Deploy Im getting 500 internal server error everytime I try access my admin or login page. There's nothing in my error.log Any ideas ? A: Set DEBUG = True so that you can see the Django traceback A: My DEBUG was set True. I found the error on my apache_log. The problem was that my sqlite3 database was a read only file.
Internal Server Error on Django Deploy
Im getting 500 internal server error everytime I try access my admin or login page. There's nothing in my error.log Any ideas ?
[ "Set DEBUG = True so that you can see the Django traceback\n", "My DEBUG was set True. I found the error on my apache_log. The problem was that my sqlite3 database was a read only file.\n" ]
[ 3, 3 ]
[]
[]
[ "apache", "deployment", "django", "django_admin", "python" ]
stackoverflow_0003322052_apache_deployment_django_django_admin_python.txt
Q: PyObjC giving strange error - [OC_PythonUnicode representations]: unrecognized selector sent to instance 0x258ae2a0 I have this line: NSWorkspace.sharedWorkspace().setIcon_forFile_options_(unicode(icon),unicode(target),0) Why does it give that error and how do I fix it? Thank you. A: I misread the documentation. I need to do this: NSWorkspace.sharedWorkspace().setIcon_forFile_options_(NSImage.alloc().initWithContentsOfFile_(icon),target,0) Unfortunately the error is what confused me.
PyObjC giving strange error - [OC_PythonUnicode representations]: unrecognized selector sent to instance 0x258ae2a0
I have this line: NSWorkspace.sharedWorkspace().setIcon_forFile_options_(unicode(icon),unicode(target),0) Why does it give that error and how do I fix it? Thank you.
[ "I misread the documentation. I need to do this:\nNSWorkspace.sharedWorkspace().setIcon_forFile_options_(NSImage.alloc().initWithContentsOfFile_(icon),target,0)\nUnfortunately the error is what confused me.\n" ]
[ 1 ]
[]
[]
[ "objective_c", "pyobjc", "python", "unicode" ]
stackoverflow_0003391692_objective_c_pyobjc_python_unicode.txt
Q: How to get audio file metadata in python beyond regexes and id3 tags Right now I'm working on a script that needs to extract the artist, album, and title from all these audio files. At the moment, I first try to extract them with regular expressions, and if the files aren't named nicely I go the slow route and try to get the information with id3 tags. The files then just get ignored if neither works. Id3 tags only work with mp3 files though, so I was wondering if anyone knew any good id3 equivalent tag reading python libraries for some of the other popular audio file extensions. Thanks! Grant A: Use mutagen. It's a multi-format tag reading (and writing) library.
How to get audio file metadata in python beyond regexes and id3 tags
Right now I'm working on a script that needs to extract the artist, album, and title from all these audio files. At the moment, I first try to extract them with regular expressions, and if the files aren't named nicely I go the slow route and try to get the information with id3 tags. The files then just get ignored if neither works. Id3 tags only work with mp3 files though, so I was wondering if anyone knew any good id3 equivalent tag reading python libraries for some of the other popular audio file extensions. Thanks! Grant
[ "Use mutagen. It's a multi-format tag reading (and writing) library.\n" ]
[ 3 ]
[]
[]
[ "audio", "id3", "mp4", "python" ]
stackoverflow_0003177238_audio_id3_mp4_python.txt
Q: global variables in python class AlphaBetaAgent(MultiAgentSearchAgent): def action(self,gamestate): self.alpha= -9999 self.beta = 9999 def abc(gamestate, depth, alpha, beta): def bvc(gamestate, depth, alpha, beta): return abc(gamestate, 0, alpha, beta) I am calling the getAction function which itself calling the abc funct and abc function calling the bvc funct. The functions abc and bvc are working in recursive way. I need to modify the values of alpha and beta as per the situation demands so I made them local. BUt it is not letting me to do that. Error occurs Error occurs:- global name 'alpha' is not defined A: In Python, global variables must be declared outside of the function. Then, any function can read that variable without any problems, but if a function wants to write to it it has to declare it global. Example: def fun1(): print a def fun2(): a = 3 def fun3(): global a a = 3 a = 0 fun1() # <- Will work fun2() # <- Will raise exception fun3() # <- Will work A: Use a class. Storing state & behaviour is what classes are for. A: If you want functions like abc and bvc to use common variables, you generally want to define an object for them to be methods of, like so: class ActionState(object): def abc(self, gamestate, depth): self.alpha = -9999 self.beta = 9999 def bvc(self, gamestate, depth): self.alpha = -9999 self.beta = 99999 def action(self, gamestate): state = ActionState() state.abc(gamestate, 0) Alternatively, if you really want to, you can enclose a mutable object like a dict around to hold your data: def action(self, gamestate): actionstate = { 'alpha': 0, 'beta': 0 } def abc(gamestate, depth): actionstate['alpha'] = -9999 actionstate['beta'] = 9999 def bvc(gamestate, depth): actionstate['alpha'] = -9999 actionstate['beta'] = 9999 abc(gamestate, 0) Note that the actionstate parameter isn't passed here -- it's inherited from the enclosing scope. You can pass it explicity instead if you want, in which case abc and bvc no longer need to be defined inside of action. The reason this works and your example doesn't is that Python binds any primitive identifier lexically to the most-local function where it is assigned. So when you assign to alpha in abc, Python defines an alpha as local to abc, not action. I believe the only way to get a closure in Python is not to assign to the enclosed variable within the inner function. A: To use a global variable you have to do something like: global alpha alpha = -9999
global variables in python
class AlphaBetaAgent(MultiAgentSearchAgent): def action(self,gamestate): self.alpha= -9999 self.beta = 9999 def abc(gamestate, depth, alpha, beta): def bvc(gamestate, depth, alpha, beta): return abc(gamestate, 0, alpha, beta) I am calling the getAction function which itself calling the abc funct and abc function calling the bvc funct. The functions abc and bvc are working in recursive way. I need to modify the values of alpha and beta as per the situation demands so I made them local. BUt it is not letting me to do that. Error occurs Error occurs:- global name 'alpha' is not defined
[ "In Python, global variables must be declared outside of the function. Then, any function can read that variable without any problems, but if a function wants to write to it it has to declare it global. Example:\ndef fun1():\n print a\ndef fun2():\n a = 3\ndef fun3():\n global a\n a = 3\na = 0\nfun1...
[ 3, 2, 1, 0 ]
[]
[]
[ "function", "python", "variables" ]
stackoverflow_0003391658_function_python_variables.txt
Q: if I run a .py script, can I open a new terminal, modify the file and run it also? if I run a .py script, can I open a new terminal, modify the file and run it also? i.e. does the file that I run get loaded in memory, such that I can modify the file and run it at the same time in a different terminal? A: Yes. Here's my original test code. while 1: print "This is the original." Here's the modified code: while 1: print "This is modified." A: Yes you can. Is this a hard thing to test yourself?
if I run a .py script, can I open a new terminal, modify the file and run it also?
if I run a .py script, can I open a new terminal, modify the file and run it also? i.e. does the file that I run get loaded in memory, such that I can modify the file and run it at the same time in a different terminal?
[ "Yes. \nHere's my original test code.\nwhile 1:\n print \"This is the original.\"\n\nHere's the modified code:\nwhile 1:\n print \"This is modified.\"\n\n", "Yes you can. Is this a hard thing to test yourself?\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003391920_python.txt
Q: Different instance-method behavior between Python 2.5 and 2.6 Trying to change the __unicode__ method on an instance after it's created produces different results on Python 2.5 and 2.6. Here's a test script: class Dummy(object): def __unicode__(self): return u'one' def two(self): return u'two' d = Dummy() print unicode(d) d.__unicode__ = d.two print unicode(d) print d.__unicode__() On Python 2.5, this produces one two two That is, changing the instance's __unicode__ also changes unicode(instance) On Python 2.6, this produces one one two So, after a change, unicode(instance) and instance.__unicode__() return different results. Why? How can I get this working on Python 2.6? (For what it's worth, the use case here is that I want to append something to the output of __unicode__ for all subclasses of a given class, without having to modify the code of the subclasses.) Edit to make the use case a little clearer I have Class A, which has many subclasses. Those subclasses define simple __unicode__ methods. I want to add logic so that, for instances of a Class A subclass, unicode(instance) gets something tacked on to the end. To keep the code simple, and because there are many subclasses I don't want to change, I'd prefer to avoid editing subclass code. This is actually existing code that works in Python 2.5. It's something like this: class A(object): def __init__(self): self._original_unicode = self.__unicode__ self.__unicode__ = self.augmented_unicode def augmented_unicode(self): return self._original_unicode() + u' EXTRA' It's this code that no longer works on 2.6. Any suggestions on how to achieve this without modifying subclass code? (If the answer involves metaclasses, note that class A is itself a subclass of another class -- django.db.models.Model -- with a pretty elaborate metaclass.) A: Edit: In response to the OP's comment: Adding a layer of indirection can allow you to change the behavior of unicode on a per-instance basis: class Dummy(object): def __unicode__(self): return self._unicode() def _unicode(self): return u'one' def two(self): return u'two' d = Dummy() print unicode(d) # one d._unicode = d.two print unicode(d) # two print d.__unicode__() # two A: It appears that you are not allowed to monkey-patch protocol methods (those that begin and end with double underscores) : Note In practise there is another exception that we haven't handled here. Although you can override methods with instance attributes (very useful for monkey patching methods for test purposes) you can't do this with the Python protocol methods. These are the 'magic methods' whose names begin and end with double underscores. When invoked by the Python interpreter they are looked up directly on the class and not on the instance (however if you look them up directly - e.g. x.repr - normal attribute lookup rules apply). That being the case, you may be stuck unless you can go with ~unutbu's answer. EDIT: Or, you can have the base class __unicode__ method search the instance object's dict for a __unicode__ attribute. If it's present, then __unicode__ is defined on the instance object, and the class method calls the instance method. Otherwise, we fall back to the class definition of __unicode__. I think that this could allow your existing subclass code to work without any changes. However, it gets ugly if the derived class wants to invoke the class implementation -- you need to be careful to avoid infinite loops. I haven't implemented such hacks in this example; merely commented about them. import types class Dummy(object): def __unicode__(self): func = self.__dict__.get("__unicode__", None) if func: // WARNING: if func() invokes this __unicode__ method directly, // an infinite loop could result. You may need an ugly hack to guard // against this. (E.g., set a flag on entry / unset the flag on exit, // using a try/finally to protect against exceptions.) return func() return u'one' def two(self): return u'two' d = Dummy() print unicode(d) funcType = type(Dummy.__unicode__) d.__unicode__ = types.MethodType(Dummy.two, d) print unicode(d) print d.__unicode__() Testing with Python 2.6 produces the following output: > python dummy.py one two two A: Looks like Dan is correct about monkey-patching protocol methods, and that this was a change between Python 2.5 and Python 2.6. My fix ended up being making the change on the classes rather the instances: class A(object): def __init__(self): self.__class__.__unicode__ = self.__class__.augmented_unicode
Different instance-method behavior between Python 2.5 and 2.6
Trying to change the __unicode__ method on an instance after it's created produces different results on Python 2.5 and 2.6. Here's a test script: class Dummy(object): def __unicode__(self): return u'one' def two(self): return u'two' d = Dummy() print unicode(d) d.__unicode__ = d.two print unicode(d) print d.__unicode__() On Python 2.5, this produces one two two That is, changing the instance's __unicode__ also changes unicode(instance) On Python 2.6, this produces one one two So, after a change, unicode(instance) and instance.__unicode__() return different results. Why? How can I get this working on Python 2.6? (For what it's worth, the use case here is that I want to append something to the output of __unicode__ for all subclasses of a given class, without having to modify the code of the subclasses.) Edit to make the use case a little clearer I have Class A, which has many subclasses. Those subclasses define simple __unicode__ methods. I want to add logic so that, for instances of a Class A subclass, unicode(instance) gets something tacked on to the end. To keep the code simple, and because there are many subclasses I don't want to change, I'd prefer to avoid editing subclass code. This is actually existing code that works in Python 2.5. It's something like this: class A(object): def __init__(self): self._original_unicode = self.__unicode__ self.__unicode__ = self.augmented_unicode def augmented_unicode(self): return self._original_unicode() + u' EXTRA' It's this code that no longer works on 2.6. Any suggestions on how to achieve this without modifying subclass code? (If the answer involves metaclasses, note that class A is itself a subclass of another class -- django.db.models.Model -- with a pretty elaborate metaclass.)
[ "Edit: In response to the OP's comment: Adding a layer of indirection can allow you to change the behavior of unicode on a per-instance basis:\nclass Dummy(object):\n\n def __unicode__(self):\n return self._unicode()\n\n def _unicode(self):\n return u'one'\n\n def two(self):\n return u...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003391293_python.txt
Q: Python : define a list of a specific type of object I would like to inherit from a list to produce the myList class, that only accepts one specific type of object (say ints). I am sure decorators can do that elegantly. A: What about using arrays? This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:
Python : define a list of a specific type of object
I would like to inherit from a list to produce the myList class, that only accepts one specific type of object (say ints). I am sure decorators can do that elegantly.
[ "What about using arrays?\n\nThis module defines an object type\n which can compactly represent an array\n of basic values: characters, integers,\n floating point numbers. Arrays are\n sequence types and behave very much\n like lists, except that the type of\n objects stored in them is constrained.\n The typ...
[ 4 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003391995_list_python.txt
Q: soaplib problems with XML characters in string payload I've created a simple SOAP web service using soaplib and run into an issue in which SOAP parameters sent including ampersands or angle brackets are ignored, even when escaped. Whether the method is set up to accept a primitive string or a primitive of type 'any', any of those characters introduced result in a webfault (using suds) of this type: suds.WebFault: Server raised fault: 'my_method() takes exactly 2 arguments (1 given)' For now, here's the method, having removing addition code used to store the result: @soapmethod(soap_types.String, _returns=soap_types.Boolean) def my_method_(self, sample): return True Calling this method with any simple string works just fine, e.g. in suds, suds_object.service.my_method('Hello World') results in "true". But add in any ampersand or angle bracket, e.g. suds_object.service.my_method('Hello & World') and the exception is raised. With logging turned on I can see that suds is escaping these characters. So far I've been able to figure out that the problem is not down at the primitive level and I can't figure out where or what the problem is. It makes it rather difficult to send XML payloads through the service. The class used is a subclass of SimpleWSGISoapApp, and the method is served as a Django view. I noticed that when attempting to use the Hello World example using the soaplib client library that it worked just fine. A: I had problems with "easier" soap libs in python (esp. suds). I had a question a while ago that led me to use soapPy instead, and a problem similar to yours just vanished. Suds + JIRA = SAXException That question also had good suggestions on using, e.g., wireshark (or google "soap debugger") to see what was happening at a lower level. A: The problem was absolutely NOT soaplib, but the Django code. That code was reading request.POST.items() for some reason which chopped up the SOAP request at any special character (e.g. =, &, >). Switched to soaplib trunk, updated the Django code, and that solved both the arguments error raised and related Unicode ValueErrors that lxml was raising.
soaplib problems with XML characters in string payload
I've created a simple SOAP web service using soaplib and run into an issue in which SOAP parameters sent including ampersands or angle brackets are ignored, even when escaped. Whether the method is set up to accept a primitive string or a primitive of type 'any', any of those characters introduced result in a webfault (using suds) of this type: suds.WebFault: Server raised fault: 'my_method() takes exactly 2 arguments (1 given)' For now, here's the method, having removing addition code used to store the result: @soapmethod(soap_types.String, _returns=soap_types.Boolean) def my_method_(self, sample): return True Calling this method with any simple string works just fine, e.g. in suds, suds_object.service.my_method('Hello World') results in "true". But add in any ampersand or angle bracket, e.g. suds_object.service.my_method('Hello & World') and the exception is raised. With logging turned on I can see that suds is escaping these characters. So far I've been able to figure out that the problem is not down at the primitive level and I can't figure out where or what the problem is. It makes it rather difficult to send XML payloads through the service. The class used is a subclass of SimpleWSGISoapApp, and the method is served as a Django view. I noticed that when attempting to use the Hello World example using the soaplib client library that it worked just fine.
[ "I had problems with \"easier\" soap libs in python (esp. suds). I had a question a while ago that led me to use soapPy instead, and a problem similar to yours just vanished.\nSuds + JIRA = SAXException\nThat question also had good suggestions on using, e.g., wireshark (or google \"soap debugger\") to see what was...
[ 1, 0 ]
[]
[]
[ "django", "python", "soap", "wsgi" ]
stackoverflow_0003346504_django_python_soap_wsgi.txt
Q: Standard way of generating/ writing XML files For a project, I need to generate XML files which adhere to a specific format. I was wondering, what is the standard way of doing this? For my part I am using lxml and then writing the XML files. For this, I wrote a small script that takes in XML data as input and then generates the files. Is this way of doing it 'OK'? Cause I am new to all this and I have seen many people use TeX and then convert it to XML. Or is there a better of way doing it altogether? EDIT: Note that I have to allow the end user to generate these files without any effort required from them. A: For python 3: http://diveintopython3.org/xml.html#xml-parse
Standard way of generating/ writing XML files
For a project, I need to generate XML files which adhere to a specific format. I was wondering, what is the standard way of doing this? For my part I am using lxml and then writing the XML files. For this, I wrote a small script that takes in XML data as input and then generates the files. Is this way of doing it 'OK'? Cause I am new to all this and I have seen many people use TeX and then convert it to XML. Or is there a better of way doing it altogether? EDIT: Note that I have to allow the end user to generate these files without any effort required from them.
[ "For python 3: http://diveintopython3.org/xml.html#xml-parse\n" ]
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003392007_python_xml.txt
Q: Implementing a per-model table modification time in Django? I have a Django application which edits a database table, which another application polls and uses to update a downstream system. In order to minimize processing when the database has not been altered in between polls, I would like to use a global modification time for a model, which is updated every time a row is created/deleted/modified. How can I do this within the Django ORM? A: Django does not give you access, nor does it maintain, a "last modified" date on a table (model). You need to implement this by yourself, but this isn't complicated. The easiest way would be to catch the necessary signals in your model by implementing the post_save() and post_delete() model signals (hooks, basically), and maintaining a static date field which represents the "last modified" date you are looking for.
Implementing a per-model table modification time in Django?
I have a Django application which edits a database table, which another application polls and uses to update a downstream system. In order to minimize processing when the database has not been altered in between polls, I would like to use a global modification time for a model, which is updated every time a row is created/deleted/modified. How can I do this within the Django ORM?
[ "Django does not give you access, nor does it maintain, a \"last modified\" date on a table (model). You need to implement this by yourself, but this isn't complicated.\nThe easiest way would be to catch the necessary signals in your model by implementing the post_save() and post_delete() model signals (hooks, basi...
[ 2 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0003391999_django_python_sql.txt
Q: how to export images from an openstreetmap server? Good morning everyone, i'll try to explain the whole situation here: I have a website (django-python) that shows a map using Openlayers. The map has two layers: a background that shows the city names and streets and for that i use openstreetmaps; the second layer contains some greographic information , for that i use MapServer (more specifically,i send the bbox parameter and other stuff to my server and generates the map via mapscript for python). Now i want to have an "export" button in my website, that must create a .zip file containing an image of the map (among charts and files included in the .zip), so i have to be able to generate the same map that was shown in the openlayers and save it into a file or directly into the .zip. My first guess was that i could get the coordinates (BBOX) from the openlayers, send those coordinates to python and via url and python could call both servers (mapserver an openmapstreets), save the image in the .zip file... but life is not that easy isn't it? Well it works fine for the mapserver layer, the urls is something like: http://myserver/mapscript/?LAYERS=selection&FORMAT=png&BBOX=466501.93337405,6631240.3024181,750661.93337405,6853960.3024181&WIDTH=555&HEIGHT=435 but when i try to call the openstreetmaps with the same coordinates, it gives me an error : http://openstreetmapserver/?LAYERS=osm_l93&FORMAT=png&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A2154&BBOX=466501.93337405,6631240.3024181,750661.93337405,6853960.3024181&WIDTH=256&HEIGHT=256 An error occurred: can't find resolution index for 1110.000000. Available resolutions are: [4096.0, 2048.0, 1024.0, 512.0, 256.0, 128.0, 64.0, 32.0, 16.0, 8.0, 4.0, 2.0, 1.0, 0.5, 0.25] so now... i dont know how to call the OSM to generate an image for the coordinates that i give him.. i looked in the openstreetmaps an exemple of export an i think they use the coordinates in some other format maybe?? http://tile.openstreetmap.org/cgi-bin/export?bbox=-1.81,44.71,9.26,50.53&scale=3500000&format=png If you have any idea how to proceed i'd be great!!!! A: Maybe this example can be what you need: OpenLayers Export Map Example
how to export images from an openstreetmap server?
Good morning everyone, i'll try to explain the whole situation here: I have a website (django-python) that shows a map using Openlayers. The map has two layers: a background that shows the city names and streets and for that i use openstreetmaps; the second layer contains some greographic information , for that i use MapServer (more specifically,i send the bbox parameter and other stuff to my server and generates the map via mapscript for python). Now i want to have an "export" button in my website, that must create a .zip file containing an image of the map (among charts and files included in the .zip), so i have to be able to generate the same map that was shown in the openlayers and save it into a file or directly into the .zip. My first guess was that i could get the coordinates (BBOX) from the openlayers, send those coordinates to python and via url and python could call both servers (mapserver an openmapstreets), save the image in the .zip file... but life is not that easy isn't it? Well it works fine for the mapserver layer, the urls is something like: http://myserver/mapscript/?LAYERS=selection&FORMAT=png&BBOX=466501.93337405,6631240.3024181,750661.93337405,6853960.3024181&WIDTH=555&HEIGHT=435 but when i try to call the openstreetmaps with the same coordinates, it gives me an error : http://openstreetmapserver/?LAYERS=osm_l93&FORMAT=png&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&SRS=EPSG%3A2154&BBOX=466501.93337405,6631240.3024181,750661.93337405,6853960.3024181&WIDTH=256&HEIGHT=256 An error occurred: can't find resolution index for 1110.000000. Available resolutions are: [4096.0, 2048.0, 1024.0, 512.0, 256.0, 128.0, 64.0, 32.0, 16.0, 8.0, 4.0, 2.0, 1.0, 0.5, 0.25] so now... i dont know how to call the OSM to generate an image for the coordinates that i give him.. i looked in the openstreetmaps an exemple of export an i think they use the coordinates in some other format maybe?? http://tile.openstreetmap.org/cgi-bin/export?bbox=-1.81,44.71,9.26,50.53&scale=3500000&format=png If you have any idea how to proceed i'd be great!!!!
[ "Maybe this example can be what you need:\nOpenLayers Export Map Example\n" ]
[ 1 ]
[]
[]
[ "export", "image", "mapserver", "openstreetmap", "python" ]
stackoverflow_0003360950_export_image_mapserver_openstreetmap_python.txt
Q: help with IOError for reading files for subdir, dirs, files in os.walk(crawlFolder): for file in files: print os.getcwd() f=open(file,'r') lines=f.readlines() writeFile.write(lines) f.close() writeFile.close() I get the error as:- IOError: [Errno 2] No such file or directory In reference to my partial python code above:- print os.getcwd() --> C:\search engine\taxonomy however, the file is located in the directory "C:\search engine\taxonomy\testFolder" I know the error is because it works in the current directory and I need to append the directory testFolder with file somehow. Could someone please correct my code and help me out with this? Thank you. A: The subdir variable gives you the path from crawlFolder to the directory containing file, so you just need to pass os.path.join(crawlFolder, subdir, file) to open instead of a bare file. Like so: for subdir, dirs, files in os.walk(crawlFolder): for file in files: print os.getcwd() f=open(os.path.join(crawlFolder, subdir, file),'r') lines=f.readlines() writeFile.write(lines) f.close() writeFile.close() Incidentally, this is a more efficient way to copy a file into another file: for subdir, dirs, files in os.walk(crawlFolder): for file in files: print os.getcwd() f=open(os.path.join(crawlFolder, subdir, file),'r') writeFile.writelines(f) f.close() writeFile.close() [EDIT: Can't resist the temptation to play golf: for subdir, dirs, files in os.walk(crawlFolder): for file in files: writeFile.writelines(open(os.path.join(crawlFolder, subdir, file))) writeFile.close() ]
help with IOError for reading files
for subdir, dirs, files in os.walk(crawlFolder): for file in files: print os.getcwd() f=open(file,'r') lines=f.readlines() writeFile.write(lines) f.close() writeFile.close() I get the error as:- IOError: [Errno 2] No such file or directory In reference to my partial python code above:- print os.getcwd() --> C:\search engine\taxonomy however, the file is located in the directory "C:\search engine\taxonomy\testFolder" I know the error is because it works in the current directory and I need to append the directory testFolder with file somehow. Could someone please correct my code and help me out with this? Thank you.
[ "The subdir variable gives you the path from crawlFolder to the directory containing file, so you just need to pass os.path.join(crawlFolder, subdir, file) to open instead of a bare file. Like so:\nfor subdir, dirs, files in os.walk(crawlFolder):\n for file in files:\n print os.getcwd()\n f=open...
[ 3 ]
[]
[]
[ "directory", "file", "ioerror", "python" ]
stackoverflow_0003392152_directory_file_ioerror_python.txt
Q: python: getting rid of values from a list drug_input=['MORPHINE','CODEINE'] def some_function(drug_input) generic_drugs_mapping={'MORPHINE':0, 'something':1, 'OXYCODONE':2, 'OXYMORPHONE':3, 'METHADONE':4, 'BUPRENORPHINE':5, 'HYDROMORPHONE':6, 'CODEINE':7, 'HYDROCODONE':8} row is a list. I would like to set all the members of row[..]='' EXCEPT for those that drug_input defines, in this case it is 0, and 7. So row[1,2,3,4,5,6,8]='' If row is initially: row[0]='blah' row[1]='bla1' ... ... row[8]='bla8' I need: row[0]='blah' (same as before) row[1]='' row[2]='' row[3]='' ... ... row[7]='bla7' row[8]='' How do I do this? A: I'd set up a defaultdict unless you really need it to be a list: from collections import defaultdict # put this at the top of the file class EmptyStringDict(defaultdict): __missing__ = lambda self, key: '' newrow = EmptyStringDict() for drug in drug_input: keep = generic_drugs_mapping[drug] newrow[keep] = row[keep] saved_len = len(row) # use this later if you need the old row length row = newrow Having a list that's mostly empty strings is wasteful. This will build an object that returns '' for every value except the ones actually inserted. However, you'd need to change any iterating code to use xrange(saved_len). Ideally, though, you would just modify the code that uses the list so as not to need such a thing. If you really want to build the list: newrow = [''] * len(row) # build a list of empty strings for drug in drug_input: keep = generic_drugs_mapping[drug] newrow[keep] = row[keep] # fill it in where we need to row = newrow # throw the rest away A: You could first create a set of all the indexes that should be kept, and then set all the other ones to '': keep = set(generic_drugs_mapping[drug] for drug in drug_input) for i in range(len(row)): if i not in keep: row[i] = ''
python: getting rid of values from a list
drug_input=['MORPHINE','CODEINE'] def some_function(drug_input) generic_drugs_mapping={'MORPHINE':0, 'something':1, 'OXYCODONE':2, 'OXYMORPHONE':3, 'METHADONE':4, 'BUPRENORPHINE':5, 'HYDROMORPHONE':6, 'CODEINE':7, 'HYDROCODONE':8} row is a list. I would like to set all the members of row[..]='' EXCEPT for those that drug_input defines, in this case it is 0, and 7. So row[1,2,3,4,5,6,8]='' If row is initially: row[0]='blah' row[1]='bla1' ... ... row[8]='bla8' I need: row[0]='blah' (same as before) row[1]='' row[2]='' row[3]='' ... ... row[7]='bla7' row[8]='' How do I do this?
[ "I'd set up a defaultdict unless you really need it to be a list:\nfrom collections import defaultdict # put this at the top of the file\n\nclass EmptyStringDict(defaultdict):\n __missing__ = lambda self, key: ''\n\nnewrow = EmptyStringDict()\nfor drug in drug_input:\n keep = generic_drugs_mapping[drug] ...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003392232_python.txt
Q: Linux kernel that runs python file for init Would it be possible and not incredibly difficult to build a linux kernel, with a python interpreter built in or accessible from the kernel, that could run a python file as it's init process? A: Can't you just replace /sbin/init or provide an init=... option to the boot loader? Just make sure you put python + libs on the root filesystem. edit I didn't feel like thrashing a system, so it is untested, but looking at linux/init/main.c: static void run_init_process(char *init_filename) { argv_init[0] = init_filename; kernel_execve(init_filename, argv_init, envp_init); } I see no reason why a (python) script cannot replace the init process; execve is the same call that fires any normal process. And I think stdin and stdout are just connected to /dev/console, for init=/bin/sh also works. (but why on earth would you?!) A: I don't think init needs to be a C binary; it can be a script with a #! at the beginning; if that is the case, then you can have it be a python program with little effort. Having said that, it is pretty trivial to write an inittab where init just runs a single program once (Although it's usually more useful to do other stuff too). Given that you will probably want to do some things on your system which can't easily be done with python (for example, try mounting filesystems without a "mount" binary), you will probably need a busybox (for example) anyway; adding "init" to a busybox binary increases its size very little.
Linux kernel that runs python file for init
Would it be possible and not incredibly difficult to build a linux kernel, with a python interpreter built in or accessible from the kernel, that could run a python file as it's init process?
[ "Can't you just replace /sbin/init or provide an init=... option to the boot loader? Just make sure you put python + libs on the root filesystem.\nedit I didn't feel like thrashing a system, so it is untested, but looking at linux/init/main.c:\nstatic void run_init_process(char *init_filename)\n{\n argv_init[0] ...
[ 6, 2 ]
[]
[]
[ "init", "kernel", "linux", "python" ]
stackoverflow_0003392203_init_kernel_linux_python.txt
Q: Python - Library that compute relevance score for text search My idea is to achieve an execution similar to the MySQL MATCH / AGAINST keywords. Do you know a python library that compute relevance score for text searches? If not satisfying answers I am going to use a Python connector to MySQL. A: Have a look at PyLucene http://lucene.apache.org/pylucene/ import os, sys, unittest, lucene lucene.initVM() baseDir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path.append(baseDir) import lia.searching.ScoreTest from lucene import System System.setProperty("index.dir", os.path.join(baseDir, 'index')) unittest.main(lia.searching.ScoreTest) You can found more examples and lia at http://svn.apache.org/viewvc/lucene/pylucene/trunk/samples/LuceneInAction/
Python - Library that compute relevance score for text search
My idea is to achieve an execution similar to the MySQL MATCH / AGAINST keywords. Do you know a python library that compute relevance score for text searches? If not satisfying answers I am going to use a Python connector to MySQL.
[ "Have a look at PyLucene http://lucene.apache.org/pylucene/\nimport os, sys, unittest, lucene\nlucene.initVM()\n\nbaseDir = os.path.dirname(os.path.abspath(sys.argv[0]))\nsys.path.append(baseDir)\n\nimport lia.searching.ScoreTest\nfrom lucene import System\n\nSystem.setProperty(\"index.dir\", os.path.join(baseDir, ...
[ 1 ]
[]
[]
[ "mysql", "python", "text_search" ]
stackoverflow_0003392303_mysql_python_text_search.txt
Q: Python ABCs: registering vs. subclassing (I am using python 2.7) The python documentation indicates that you can pass a mapping to the dict builtin and it will copy that mapping into the new dict: http://docs.python.org/library/stdtypes.html#mapping-types-dict I have a class that implements the Mapping ABC, but it fails: import collections class Mapping(object): def __init__(self, dict={}): self.dict=dict def __iter__(self): return iter(self.dict) def __iter__(self): return iter(self.dict) def __len__(self): return len(self.dict) def __contains__(self, value): return value in self.dict def __getitem__(self, name): return self.dict[name] m=Mapping({5:5}) dict(m) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: cannot convert dictionary update sequence element #0 to a sequence collections.Mapping.register(Mapping) dict(m) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: cannot convert dictionary update sequence element #0 to a sequence However, if my class subclasses collections.Mapping then it works fine: import collections class Mapping(collections.Mapping): def __init__(self, dict={}): self.dict=dict def __iter__(self): return iter(self.dict) def __iter__(self): return iter(self.dict) def __len__(self): return len(self.dict) def __contains__(self, value): return value in self.dict def __getitem__(self, name): return self.dict[name] m=Mapping({5:5}) dict(m) # {5: 5} I thought the whole point of the ABCs was to allow registration to work the same as subclassing (for isinstance and issubclass anyway). So what's up here? A: Registration does not give you the "missing methods" implemented on top of those you define: in fact, registration is non-invasive with respect to the type you're registering -- nothing gets added to it, nothing gets removed, nothing gets altered. It only affects isinstance and issubclass checks: nothing more, nothing less. Subclassing an ABC can and does give you plenty of methods implemented "for free" by the ABC on top of those you're having to define yourself. The semantics of an operation that's totally non-invasive like registering, compared to those of an operation that's intended to enrich a class, like subclassing, obviously cannot be identical; so your understanding of "the whole point of the ABCs" is imperfect -- ABCs have two points, one obtained by subclassing ("invasive"), one by registering (non-invasive). Note that you can always multiply-inherit if you already have a class like your original Mapping: class GoogMapping(Mapping, collections.Mapping): ... will give you the same results as inheriting Mapping directly from collections.Mapping -- a new type with all the auxiliary methods added by collections.Mapping.
Python ABCs: registering vs. subclassing
(I am using python 2.7) The python documentation indicates that you can pass a mapping to the dict builtin and it will copy that mapping into the new dict: http://docs.python.org/library/stdtypes.html#mapping-types-dict I have a class that implements the Mapping ABC, but it fails: import collections class Mapping(object): def __init__(self, dict={}): self.dict=dict def __iter__(self): return iter(self.dict) def __iter__(self): return iter(self.dict) def __len__(self): return len(self.dict) def __contains__(self, value): return value in self.dict def __getitem__(self, name): return self.dict[name] m=Mapping({5:5}) dict(m) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: cannot convert dictionary update sequence element #0 to a sequence collections.Mapping.register(Mapping) dict(m) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: cannot convert dictionary update sequence element #0 to a sequence However, if my class subclasses collections.Mapping then it works fine: import collections class Mapping(collections.Mapping): def __init__(self, dict={}): self.dict=dict def __iter__(self): return iter(self.dict) def __iter__(self): return iter(self.dict) def __len__(self): return len(self.dict) def __contains__(self, value): return value in self.dict def __getitem__(self, name): return self.dict[name] m=Mapping({5:5}) dict(m) # {5: 5} I thought the whole point of the ABCs was to allow registration to work the same as subclassing (for isinstance and issubclass anyway). So what's up here?
[ "Registration does not give you the \"missing methods\" implemented on top of those you define: in fact, registration is non-invasive with respect to the type you're registering -- nothing gets added to it, nothing gets removed, nothing gets altered. It only affects isinstance and issubclass checks: nothing more, ...
[ 12 ]
[ "Ah, looks like dict() is looking for the keys method... It doesn't use the ABCs.\n" ]
[ -1 ]
[ "abstract_base_class", "python", "subclass" ]
stackoverflow_0003392352_abstract_base_class_python_subclass.txt
Q: How to scale down the y-axis in matplotlib/python? This is more of a math question than a matplotlib question but if there is a way to do this specifically in matplotlib that would be great. I have a set of points with the max-y-value and the min-y-value can have a difference anywhere from a few hundred to a few thousand. I am trying to plot these points in a very small scale on the y-axis (maybe a span of 2 units). For example, I have the points (10, 20) (11, 123) (12, 77) (13, 124) and I want to plot them inbetween the y_values of 0-2. How would I scale this down? Either mathematically or a built-in matplotlib way. A: You can just do a simple linear transformation, for all y's: ynew= 2*(y-ymin)/(ymax-ymin) The fraction (y-ymin)/(ymax-ymin) first gives you the percentage of the y coordinate in the range you are interested in, and then to get it from range 0-1 into range 0-2, you just multiply by 2.
How to scale down the y-axis in matplotlib/python?
This is more of a math question than a matplotlib question but if there is a way to do this specifically in matplotlib that would be great. I have a set of points with the max-y-value and the min-y-value can have a difference anywhere from a few hundred to a few thousand. I am trying to plot these points in a very small scale on the y-axis (maybe a span of 2 units). For example, I have the points (10, 20) (11, 123) (12, 77) (13, 124) and I want to plot them inbetween the y_values of 0-2. How would I scale this down? Either mathematically or a built-in matplotlib way.
[ "You can just do a simple linear transformation, for all y's:\nynew= 2*(y-ymin)/(ymax-ymin)\n\nThe fraction (y-ymin)/(ymax-ymin) first gives you the percentage of the y coordinate in the range you are interested in, and then to get it from range 0-1 into range 0-2, you just multiply by 2.\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003392687_matplotlib_python.txt
Q: Learning Python; How can I make this more Pythonic? I am a PHP developer exploring the outside world. I have decided to start learning Python. The below script is my first attempt at porting a PHP script to Python. Its job is to take tweets from a Redis store. The tweets are coming from Twitter's Streaming API and stored as JSON objects. Then the information needed is extracted and dumped into a CSV file to be imported into MySQL using the LOAD DATA LOCAL INFILE that is hosted on a different server. So, the question is: Now that I have my first Python script running, how can I make it more Pythonic? Are there any suggestions that you guys have? Make it better? Tricks I should know about? Constructive Criticism? Update: Having taken everyone's suggestions thus far, here is the updated version: Update2: Ran the code through pylint. Now scores a 9.89/10. Any other suggestions? # -*- coding: utf-8 -*- """Redis IO Loop for Tweelay Bot""" from __future__ import with_statement import simplejson import re import datetime import time import csv import hashlib # Bot Modules import tweelay.red as red import tweelay.upload as upload import tweelay.openanything as openanything __version__ = "4" def process_tweets(): """Processes 0-20 tweets from Redis store""" data = [] last_id = 0 for i in range(20): last = red.pop_tweet() if not last: break t = TweetHandler(last) t.cleanup() t.extract() if t.get_tweet_id() == last_id: break tweet = t.proc() if tweet: data = data + [tweet] last_id = t.get_tweet_id() time.sleep(0.01) if not data: return False ch = CSVHandler(data) ch.pack_csv() ch.uploadr() source = "http://bot.tweelay.net/tweets.php" openanything.openAnything( source, etag=None, lastmodified=None, agent="Tweelay/%s (Redis)" % __version__ ) class TweetHandler: """Cleans, Builds and returns needed data from Tweet""" def __init__(self, json): self.json = json self.tweet = None self.tweet_id = 0 self.j = None def cleanup(self): """Takes JSON encoded tweet and cleans it up for processing""" self.tweet = unicode(self.json, "utf-8") self.tweet = re.sub('^s:[0-9]+:["]+', '', self.tweet) self.tweet = re.sub('\n["]+;$', '', self.tweet) def extract(self): """Takes cleaned up JSON encoded tweet and extracts the datas we need""" self.j = simplejson.loads(self.tweet) def proc(self): """Builds the datas from the JSON object""" try: return self.build() except KeyError: if 'delete' in self.j: return None else: print ";".join(["%s=%s" % (k, v) for k, v in self.j.items()]) return None def build(self): """Builds tuple from JSON tweet""" return ( self.j['user']['id'], self.j['user']['screen_name'].encode('utf-8'), self.j['text'].encode('utf-8'), self.j['id'], self.j['in_reply_to_status_id'], self.j['in_reply_to_user_id'], self.j['created_at'], __version__ ) def get_tweet_id(self): """Return Tweet ID""" if 'id' in self.j: return self.j['id'] if 'delete' in self.j: return self.j['delete']['status']['id'] class CSVHandler: """Takes list of tweets and saves them to a CSV file to be inserted into MySQL data store""" def __init__(self, data): self.data = data self.file_name = self.gen_file_name() def gen_file_name(self): """Generate unique file name""" now = datetime.datetime.now() hashr = hashlib.sha1() hashr.update(str(now)) hashr.update(str(len(self.data))) hash_str = hashr.hexdigest() return hash_str+'.csv' def pack_csv(self): """Save tweet data to CSV file""" with open('tmp/'+self.file_name, mode='ab') as ofile: writer = csv.writer( ofile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerows(self.data) def uploadr(self): """Upload file to remote host""" url = "http://example.com/up.php?filename="+self.file_name uploadr = upload.upload_file(url, 'tmp/'+self.file_name) if uploadr[0] == 200: print "Upload: 200 - ("+str(len(self.data))+")", self.file_name print "-------" #os.remove('tmp/'+self.file_name) else: print "Upload Error:", uploadr[0] if __name__ == "__main__": while True: process_tweets() time.sleep(1) A: Instead of: i=0 end=20 last_id=0 data=[] while(i<=end): i = i + 1 ... code: last_id=0 data=[] for i in xrange(1, 22): ... Same semantics, more compact and Pythonic. Instead of if not last or last == None: do just if not last: since None is false-ish anyway (so not last is True when last is None). In general, when you want to check if something isNone, codeis None, not== None`. In if(j['id'] <> last_id): lose the redundant parentheses and the obsolete <> operator and code instead if j['id'] != last_id: and also remove the redundant parentheses from other if statements. Instead of: if len(data) == 0: code: if not data: since any empty container is false-ish. In hash_str = str(hash.hexdigest()) code instead hash_str = hash.hexdigest() since the method already returns a string, making the str call redundant. Instead of: for item in data: writer.writerow(item) use writer.writerows(data) which does the loop on your behalf. Instead of ofile = open('tmp/'+file_name, mode='ab') ... ofile.close() use (in Python 2.6 or better, or in 2.5 by starting the module with from __future__ import with_statement to "import from the future" the with statement feature): with open('tmp/'+file_name, mode='ab') as ofile: ... which guarantees to do the close for you (including in cases where an exception might be raised). Instead of print "Upload Error: "+uploadr[0] use print "Upload Error:", uploadr[0] and similarly for other print statements -- the comma inserts a space for you. I'm sure there are more such little things, but these are a few that "jumped to the eye" as I was scanning your code. A: Pythonic python does not use integer flow control very much. The idiom is almost always for item in container:. Also, I would use a class to hold a 'User object'. It will be a lot easier to use than simple container types likes lists and dictionaries (And arrange your code into to a more OO style.) You can compile reg-exes before hand for a little more performance. class MyTweet(object): def __init__(self, data): # ...process json here # ... self.user = user for data in getTweets(): tweet = MyTweet(data) A: # Bot Modules import red #Simple Redis API functions import upload #pycurl script to upload to remote server If your app is going to be used and maintained, its better to pack all these modules in the package. A: Instead of .... i=0 end=20 last_id=0 data=[] while(i<=end): i = i + 1 you can use... for i in range(20): but overall, it's not very clear where this 20 comes from?? magic #? A: If you have a method that won't fit in the view pane you really want to shorten it. Say 15 lines or so. I see what looks like at least 3 methods: print_tweet, save_csv, and upload_data. It's a bit hard to say exactly what they should be named but there do seem to be three distinct sections of code that you should try to break out. A: Run your code through pylint. A: Every method variable name I've ever seen in Python was lowercase with no underscores. (I don't think this is a requirement and may not be standard practice.) You should really break up the logic into multiple, single-purpose methods. Take 2 a step further and create some classes to encapsulate related methods together.
Learning Python; How can I make this more Pythonic?
I am a PHP developer exploring the outside world. I have decided to start learning Python. The below script is my first attempt at porting a PHP script to Python. Its job is to take tweets from a Redis store. The tweets are coming from Twitter's Streaming API and stored as JSON objects. Then the information needed is extracted and dumped into a CSV file to be imported into MySQL using the LOAD DATA LOCAL INFILE that is hosted on a different server. So, the question is: Now that I have my first Python script running, how can I make it more Pythonic? Are there any suggestions that you guys have? Make it better? Tricks I should know about? Constructive Criticism? Update: Having taken everyone's suggestions thus far, here is the updated version: Update2: Ran the code through pylint. Now scores a 9.89/10. Any other suggestions? # -*- coding: utf-8 -*- """Redis IO Loop for Tweelay Bot""" from __future__ import with_statement import simplejson import re import datetime import time import csv import hashlib # Bot Modules import tweelay.red as red import tweelay.upload as upload import tweelay.openanything as openanything __version__ = "4" def process_tweets(): """Processes 0-20 tweets from Redis store""" data = [] last_id = 0 for i in range(20): last = red.pop_tweet() if not last: break t = TweetHandler(last) t.cleanup() t.extract() if t.get_tweet_id() == last_id: break tweet = t.proc() if tweet: data = data + [tweet] last_id = t.get_tweet_id() time.sleep(0.01) if not data: return False ch = CSVHandler(data) ch.pack_csv() ch.uploadr() source = "http://bot.tweelay.net/tweets.php" openanything.openAnything( source, etag=None, lastmodified=None, agent="Tweelay/%s (Redis)" % __version__ ) class TweetHandler: """Cleans, Builds and returns needed data from Tweet""" def __init__(self, json): self.json = json self.tweet = None self.tweet_id = 0 self.j = None def cleanup(self): """Takes JSON encoded tweet and cleans it up for processing""" self.tweet = unicode(self.json, "utf-8") self.tweet = re.sub('^s:[0-9]+:["]+', '', self.tweet) self.tweet = re.sub('\n["]+;$', '', self.tweet) def extract(self): """Takes cleaned up JSON encoded tweet and extracts the datas we need""" self.j = simplejson.loads(self.tweet) def proc(self): """Builds the datas from the JSON object""" try: return self.build() except KeyError: if 'delete' in self.j: return None else: print ";".join(["%s=%s" % (k, v) for k, v in self.j.items()]) return None def build(self): """Builds tuple from JSON tweet""" return ( self.j['user']['id'], self.j['user']['screen_name'].encode('utf-8'), self.j['text'].encode('utf-8'), self.j['id'], self.j['in_reply_to_status_id'], self.j['in_reply_to_user_id'], self.j['created_at'], __version__ ) def get_tweet_id(self): """Return Tweet ID""" if 'id' in self.j: return self.j['id'] if 'delete' in self.j: return self.j['delete']['status']['id'] class CSVHandler: """Takes list of tweets and saves them to a CSV file to be inserted into MySQL data store""" def __init__(self, data): self.data = data self.file_name = self.gen_file_name() def gen_file_name(self): """Generate unique file name""" now = datetime.datetime.now() hashr = hashlib.sha1() hashr.update(str(now)) hashr.update(str(len(self.data))) hash_str = hashr.hexdigest() return hash_str+'.csv' def pack_csv(self): """Save tweet data to CSV file""" with open('tmp/'+self.file_name, mode='ab') as ofile: writer = csv.writer( ofile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) writer.writerows(self.data) def uploadr(self): """Upload file to remote host""" url = "http://example.com/up.php?filename="+self.file_name uploadr = upload.upload_file(url, 'tmp/'+self.file_name) if uploadr[0] == 200: print "Upload: 200 - ("+str(len(self.data))+")", self.file_name print "-------" #os.remove('tmp/'+self.file_name) else: print "Upload Error:", uploadr[0] if __name__ == "__main__": while True: process_tweets() time.sleep(1)
[ "Instead of:\n i=0\n end=20\n last_id=0\n data=[]\n while(i<=end):\n i = i + 1\n ...\n\ncode:\n last_id=0\n data=[]\n for i in xrange(1, 22):\n ...\n\nSame semantics, more compact and Pythonic.\nInstead of\nif not last or last == None:\n\ndo just\nif not last:\n\nsince None is false-ish anyway (so ...
[ 19, 6, 2, 2, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003384010_python.txt
Q: python: append a list of values into a list c1=[] for row in c: c1.append(row[0:13]) c is a variable containing a csv file i am going through every row in it and i want only the first 14 elements to be in the c1 what am i doing wrong? A: Nicer: c1= [row[:13] for row in c.readlines()] if that doesn't work, you may not assigning to c properly. Also keep in mind that if you want first 14 characters, you actually want to do row[:14] Then you get characters 0->13 inclusively, or 14 total. A: That will not include the element indexed at [13]. c1=[] for row in c: c1.append(row[:14]) If you want the individual elements (the above code will append a list, much like a 2D array) you should append it in the following way: c1 += row[:14]
python: append a list of values into a list
c1=[] for row in c: c1.append(row[0:13]) c is a variable containing a csv file i am going through every row in it and i want only the first 14 elements to be in the c1 what am i doing wrong?
[ "Nicer:\nc1= [row[:13] for row in c.readlines()]\n\nif that doesn't work, you may not assigning to c properly.\nAlso keep in mind that if you want first 14 characters, you actually want to do row[:14]\nThen you get characters 0->13 inclusively, or 14 total.\n", "That will not include the element indexed at [13].\...
[ 2, 2 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0003392722_csv_list_python.txt
Q: Python: OSX Library for fast full screen jpg/png display Frustrated by lack of a simple ACDSee equivalent for OS X, I'm looking to hack one up for myself. I'm looking for a gui library that accommodates: Full screen image display High quality image fit-to-screen (for display) Low memory usage Fast display Reasonable learning curve (the simpler the better) Looks like there are several choices, so which is the best? Here are some I've run across: PyOpenGL PyGame PyQT wxpython I don't have any particular experience with any of these, nor any strong desire to become an expert - I'm looking for the simplest solution. What do you recommend? [Update] For those not familiar with ACDSee, here's what it does that I care about: Simple list/thubmnail display of images in a directory Sort by name/size/type Ability to view images full screen Single-key delete while viewing full screen Move to next/previous image while viewing full screen Ability to select a group of images for: move to / copy to directory delete resize ACDSee has a bunch of niceties as well, such as remembering directories you've moved images to in the past, remembering your resize settings, displaying the total size of the images you've selected, etc. I've tried most of the options I could find (including Xee) and none of them quite get there. Please keep in mind that this is a programming/library question, not a criticism of any of the existing tools. A: I will recommend using wxPython to create such a viewer, wxPython is easy to learn, free, cross platform and blends well in OSX. Even if you want to use pyopengl, wxPython would be good with pyopengl. see such tutorials http://showmedo.com/videotutorials/video?name=1790000&fromSeriesID=179 and there is already cornice written in wxpython/PIL, may be you can modify that. It has been inspired by the famous Windows-only ACDSee :) A: it's not an answer to your coding question but for (a big part of) the lack of ACDsee equivalent (requires OSX 10.5+): Simple list/thubmnail display of images in a directory: Finder.app Sort by name/size/type: Finder.app will do name & type, not image size (but does file size) Ability to view images full screen: quick preview (spacebar / eye icon) Single-key delete while viewing full screen: command-backspace while viewing in quickpreview, both windowed and fullscreen Move to next/previous image while viewing full screen: both quickprewiew (after selecting a group of images or whole directory with cmd-a) and Preview.app Ability to select a group of images for[...]: Finder.app will does all but resize seems like you have everything except resize just pressing the spacebar while in finder. Preview.app will resize both a single image or multiple ones in one batch. A: Use an App like Picasa (now available on mac). Use AppleScript through Python to control it from your application. Failing that, use PyObjC to create Cocoa image display component and dialogs, and so on. A: I ended up using PyGame, has been pretty good so far.
Python: OSX Library for fast full screen jpg/png display
Frustrated by lack of a simple ACDSee equivalent for OS X, I'm looking to hack one up for myself. I'm looking for a gui library that accommodates: Full screen image display High quality image fit-to-screen (for display) Low memory usage Fast display Reasonable learning curve (the simpler the better) Looks like there are several choices, so which is the best? Here are some I've run across: PyOpenGL PyGame PyQT wxpython I don't have any particular experience with any of these, nor any strong desire to become an expert - I'm looking for the simplest solution. What do you recommend? [Update] For those not familiar with ACDSee, here's what it does that I care about: Simple list/thubmnail display of images in a directory Sort by name/size/type Ability to view images full screen Single-key delete while viewing full screen Move to next/previous image while viewing full screen Ability to select a group of images for: move to / copy to directory delete resize ACDSee has a bunch of niceties as well, such as remembering directories you've moved images to in the past, remembering your resize settings, displaying the total size of the images you've selected, etc. I've tried most of the options I could find (including Xee) and none of them quite get there. Please keep in mind that this is a programming/library question, not a criticism of any of the existing tools.
[ "I will recommend using wxPython to create such a viewer, wxPython is easy to learn, free, cross platform and blends well in OSX. Even if you want to use pyopengl, wxPython would be good with pyopengl.\nsee such tutorials http://showmedo.com/videotutorials/video?name=1790000&fromSeriesID=179\nand there is already ...
[ 1, 0, 0, 0 ]
[]
[]
[ "macos", "opengl", "pyqt", "python", "wxpython" ]
stackoverflow_0002634119_macos_opengl_pyqt_python_wxpython.txt
Q: Do dictionaries have a has key method? I'm checking for 'None' and I'm having issues I have 2 dictionaries, and I want to check if a key is in either of the dictionaries. I am trying: if dic1[p.sku] is not None: I wish there was a hasKey method, anyhow. I am getting an error if the key isn't found, why is that? A: Use the in operator: if p.sku in dic1: ... (Incidentally, you can also use the has_key method, but the use of in is preferred.) A: They do: if dic1.has_key(p.sku): A: if dic1.get(p.sku) is None: is the exact equivalent of what you're trying except for no KeyError -- since get returns None if the key is absent or a None has explicitly been stored as the corresponding value, which can be useful as a way to "logically delete" a key without actually altering the set of keys (you can't alter the set of keys if you're looping on the dict, nor is it thread-safe to do so without a lock or the like, etc etc, while assigning a value of None to an already-existing key is allowed in loops and threadsafe). Unless you have this kind of requirement, if p.sku not in dic1:, as @Michael suggests, is vastly preferable on all planes (faster, more concise, more readable, and so on;-).
Do dictionaries have a has key method? I'm checking for 'None' and I'm having issues
I have 2 dictionaries, and I want to check if a key is in either of the dictionaries. I am trying: if dic1[p.sku] is not None: I wish there was a hasKey method, anyhow. I am getting an error if the key isn't found, why is that?
[ "Use the in operator:\nif p.sku in dic1:\n ...\n\n(Incidentally, you can also use the has_key method, but the use of in is preferred.)\n", "They do:\nif dic1.has_key(p.sku):\n\n", "if dic1.get(p.sku) is None: is the exact equivalent of what you're trying except for no KeyError -- since get returns None if th...
[ 13, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003392637_dictionary_python.txt
Q: Installing Python extensions on OS X, missing MacOSX10.4u.sdk error I'm attempting to install various python extensions on OS X (10.6.4), with a python.org python (Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)). Consistently running into a problem on the gcc step. Here's a sample from compiling Cython (btw, I'm attempting to install Cython in order to install lxml): In file included from /usr/include/architecture/i386/math.h:626, from /usr/include/math.h:28, from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyport.h:235, from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:58, from /tmp/easy_install-Sgn5ep/Cython-0.12.1/Cython/Plex/Scanners.c:4: /usr/include/AvailabilityMacros.h:108:14: warning: #warning Building for Intel with Mac OS X Deployment Target < 10.4 is invalid. Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk Please check your Xcode installation ld: library not found for -lbundle1.o ld: library not found for collect2: -lbundle1.o collect2: ld returned 1 exit status I get a similar error when attempting to install lxml in various ways. I've tried the winning recipe from Simon's question, as well as the installation instructions from the lxml site and they both end up with the same problem. Do I really need to install an old OS X SDK? If so, where do I find it (a search didn't seem to turn up any official download locations). Or is there a better workaround that doesn't require the old SDK? A: After an unneccessary amount of pain, mostly brought about by my own stubbornness, this was solved by uninstalling xcode and reinstalling, this time with SDK 10.4 support checked during installation.
Installing Python extensions on OS X, missing MacOSX10.4u.sdk error
I'm attempting to install various python extensions on OS X (10.6.4), with a python.org python (Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)). Consistently running into a problem on the gcc step. Here's a sample from compiling Cython (btw, I'm attempting to install Cython in order to install lxml): In file included from /usr/include/architecture/i386/math.h:626, from /usr/include/math.h:28, from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyport.h:235, from /Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:58, from /tmp/easy_install-Sgn5ep/Cython-0.12.1/Cython/Plex/Scanners.c:4: /usr/include/AvailabilityMacros.h:108:14: warning: #warning Building for Intel with Mac OS X Deployment Target < 10.4 is invalid. Compiling with an SDK that doesn't seem to exist: /Developer/SDKs/MacOSX10.4u.sdk Please check your Xcode installation ld: library not found for -lbundle1.o ld: library not found for collect2: -lbundle1.o collect2: ld returned 1 exit status I get a similar error when attempting to install lxml in various ways. I've tried the winning recipe from Simon's question, as well as the installation instructions from the lxml site and they both end up with the same problem. Do I really need to install an old OS X SDK? If so, where do I find it (a search didn't seem to turn up any official download locations). Or is there a better workaround that doesn't require the old SDK?
[ "After an unneccessary amount of pain, mostly brought about by my own stubbornness, this was solved by uninstalling xcode and reinstalling, this time with SDK 10.4 support checked during installation.\n" ]
[ 0 ]
[]
[]
[ "cython", "lxml", "python" ]
stackoverflow_0003390751_cython_lxml_python.txt
Q: The "right" way to add python scripting to a non-python application I'm currently in the process of adding the ability for users to extend the functionality of my desktop application (C++) using plugins scripted in python. The naive method is easy enough. Embed the python static library and follow any number of the dozens of tutorials scattered around the web describing how to initialize and call python files, and you're pretty much done. However... What I'm looking for is more like what Blender does. Blender is completely customizable through python scripts, and it requires an external python executable. (Ie. python isn't actually embedded in the blender executable at all.) So, naturally, you can include any modules you already have in your site-packages directory when you are writing blender scripts. Not that that's advised, since that would limit the portability of your script. So, what I want to know is if there is already a way to have your cake and eat it too. I want a plugin system that uses: An embedded python interpreter. The downside of Blender's approach is that it forces you to have a specific, possibly outdated version of python installed globally on your system. Having an embedded interpreter allows me to control what version of python is being used. Firewall plugins. Some equivalent of a virtualenv for each plugin; allowing them to install all the modules they need or want, but keeping them seperated from possible conflicts in other plugins. Maybe zc.buildout is a better candidate here, but, again, I'm very open to suggestion. I'm a bit at a loss as to the best way to accomplish this. As painless as possible... For the user. I'm willing to go the extra mile, just so long as most of the above is as transparent to the plugin writer as possible. If any of you folks out there have any experience with this sort of thing, your help would be much appreciated. :) Edit: Basically, the short version of what I want is the simplicity of virtualenv, but without the bundled python interpreter, and a way to activate a specific "virtual environment" programmatically, like zc.buildout does with sys.path manipulation (the sys.path[0:0] = [...] trick). Both virtualenv and zc.buildout contain portions of what I want, but neither produce relocatable builds that I, or a plugin developer can simply zip up and send to another computer. Simply manipulating .pth files, or manipulating sys.path directly in a script, executed from my application gets me half-way there. But it is not enough when compiled modules are necessary, such as the PIL. A: One effective way to accomplish this is to use a message-passing/communicating processes architecture, allowing you to accomplish your goal with Python, but not limiting yourself to Python. ------------------------------------ | App <--> Ext. API <--> Protocol | <--> (Socket) <--> API.py <--> Script ------------------------------------ This diagram attempts to show the following: Your application communicates with external processes (for example Python) using message passing. This is efficient on a local machine, and can be portable because you define your own protocol. The only thing that you have to give your users is a Python library that implements your custom API, and communicates using a Send-Receive communication loop between your user's script and your application. Define Your Application's External API Your application's external API describes all of the functions that an external process must be able to interact with. For example, if you wish for your Python script to be able to draw a red circle in your application, your external API may include Draw(Object, Color, Position). Define A Communication Protocol This is the protocol that external processes use to communicate with your application through it's external API. Popular choices for this might be XML-RPC, SunRPC, JSON, or your own custom protocol and data format. The choice here needs to be sufficient for your API. For example, if you are going to be transferring binary data then JSON might require base64 encoding, while SunRPC assumes binary communication. Build Your Application's Messaging System This is as simple as an infinite loop receiving messages in your communication protocol, servicing the request within your application, and replying over the same socket/channel. For example, if you chose JSON then you would receive a message containing instructions to execute Draw(Object, Color, Position). After executing the request, you would reply to the request. Build A Messaging Library For Python (or whatever else) This is even simpler. Again, this is a loop sending and receiving messages on behalf the library user (i.e. your users writing Python scripts). The only thing this library must do is provide a programmatic interface to your Application's External API and translate requests into your communication protocol, all hidden from your users. Using Unix Sockets, for example, will be extremely fast. Plugin/Application Rendezvous A common practice for discovering application plugins is to specify a "well known" directory where plugins should be placed. This might be, for example: ~/.myapp/plugins The next step is for your application to look into this directory for plugins that exist. Your application should have a some smarts to be able to distinguish between Python scripts that are, and are not, real scripts for your application. Let's assume that your communication protocol specifies that each script will communicate using JSON over StdInput/StdOuput. A simple, effective approach is to specify in your protocol that the first time a script runs it sends a MAGIC_ID to standard out. That is, your application reads the first, say, 8 bytes, and looks for a specific 64-bit value that identifies it as a script. Additionally, you should include in your External API methods that allow your scripts to identify themselves. For example, a script should be able to inform the application through the External API things such as Name, Description, Capabilities, Expectations, essentially informing the application what it is, and what it will be doing. A: I don't see the problem with embedding Python with, for example, Boost.Python. You'll get everything you ask for: It will be embedded, and it will be an interpreter (with enough access to implement auto-completion and such) You can create a new interpreter per-script and have completely separated python environments ... and as transparent as it's possible I mean, you'll still have to expose and implement an API, but 1) this is a good thing, 2) Blender does it too and 3) I really can't think of another way that leverages you from this work... PS: I have little experience with Python / Boost.Python but have worked extensively with Lua / LuaBind, which is kinda the same A: If you really want to be as painless as possible for you and your users, consider extending python rather than embedding. embedding doesn't allow easy integration with other software -- only one program that embeds python can be used at once by a python script. OTOH extending means the user can use your software anywhere python runs; To make stuff available for the script writer, you don't have to initialize an interpreter. the interpreter will be already initialized for you, saving you work. You don't have to create special built-in variables and fake modules to inject into your embedded interpreter. Just give them a real extension module instead, and you can initialize everything when your module is first imported. You can use distutils to distribute your software Tools like virtualenv can be used as-is -- you or the user don't have to come up with new tools. Your user can also use her IDE/debug tool/testing framework of choice Embedding really buys nothing to you and your users.
The "right" way to add python scripting to a non-python application
I'm currently in the process of adding the ability for users to extend the functionality of my desktop application (C++) using plugins scripted in python. The naive method is easy enough. Embed the python static library and follow any number of the dozens of tutorials scattered around the web describing how to initialize and call python files, and you're pretty much done. However... What I'm looking for is more like what Blender does. Blender is completely customizable through python scripts, and it requires an external python executable. (Ie. python isn't actually embedded in the blender executable at all.) So, naturally, you can include any modules you already have in your site-packages directory when you are writing blender scripts. Not that that's advised, since that would limit the portability of your script. So, what I want to know is if there is already a way to have your cake and eat it too. I want a plugin system that uses: An embedded python interpreter. The downside of Blender's approach is that it forces you to have a specific, possibly outdated version of python installed globally on your system. Having an embedded interpreter allows me to control what version of python is being used. Firewall plugins. Some equivalent of a virtualenv for each plugin; allowing them to install all the modules they need or want, but keeping them seperated from possible conflicts in other plugins. Maybe zc.buildout is a better candidate here, but, again, I'm very open to suggestion. I'm a bit at a loss as to the best way to accomplish this. As painless as possible... For the user. I'm willing to go the extra mile, just so long as most of the above is as transparent to the plugin writer as possible. If any of you folks out there have any experience with this sort of thing, your help would be much appreciated. :) Edit: Basically, the short version of what I want is the simplicity of virtualenv, but without the bundled python interpreter, and a way to activate a specific "virtual environment" programmatically, like zc.buildout does with sys.path manipulation (the sys.path[0:0] = [...] trick). Both virtualenv and zc.buildout contain portions of what I want, but neither produce relocatable builds that I, or a plugin developer can simply zip up and send to another computer. Simply manipulating .pth files, or manipulating sys.path directly in a script, executed from my application gets me half-way there. But it is not enough when compiled modules are necessary, such as the PIL.
[ "One effective way to accomplish this is to use a message-passing/communicating processes architecture, allowing you to accomplish your goal with Python, but not limiting yourself to Python.\n------------------------------------\n| App <--> Ext. API <--> Protocol | <--> (Socket) <--> API.py <--> Script\n----------...
[ 9, 4, 4 ]
[]
[]
[ "c++", "desktop_application", "plugins", "python", "scripting" ]
stackoverflow_0003374801_c++_desktop_application_plugins_python_scripting.txt
Q: Nothing executes in code Possible Duplicate: Python Application does nothing #Dash Shell import os import datetime class LocalComputer: pass def InitInformation(): Home = LocalComputer() #Acquires user information if (os.name == "nt"): Home.ComputerName = os.getenv("COMPUTERNAME") Home.Username = os.getenv("USERNAME") Home.Homedir = os.getenv("HOMEPATH") else: Home.ComputerName = os.getenv("HOSTNAME") Home.Username = os.getenv("USER") Home.Homedir = os.getenv("HOME") return Home def MainShellLoop(): print ("--- Dash Shell ---") Home = InitInformation() userinput = None currentdir = Home.Homedir while (userinput != "exit"): rightnow = datetime.datetime.now() try: userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "@" + str(currentdir)) except: print("Invalid Command specified, please try again") MainShellLoop() The input() is supposed to execute and it stopped working after changing something I dont remember It's coded under Python 3.1.2 with Windows 7, I know the Unix Hostname global variable is wrong I know userinput does nothing, I want to get this part working before I continue on Thanks It outputs nothing A: You define a class and two functions, but you don't seem to call any of them anywhere. Are you missing a call to MainShellLoop() in the end? A: I think you need a call to MainShellLoop.
Nothing executes in code
Possible Duplicate: Python Application does nothing #Dash Shell import os import datetime class LocalComputer: pass def InitInformation(): Home = LocalComputer() #Acquires user information if (os.name == "nt"): Home.ComputerName = os.getenv("COMPUTERNAME") Home.Username = os.getenv("USERNAME") Home.Homedir = os.getenv("HOMEPATH") else: Home.ComputerName = os.getenv("HOSTNAME") Home.Username = os.getenv("USER") Home.Homedir = os.getenv("HOME") return Home def MainShellLoop(): print ("--- Dash Shell ---") Home = InitInformation() userinput = None currentdir = Home.Homedir while (userinput != "exit"): rightnow = datetime.datetime.now() try: userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "@" + str(currentdir)) except: print("Invalid Command specified, please try again") MainShellLoop() The input() is supposed to execute and it stopped working after changing something I dont remember It's coded under Python 3.1.2 with Windows 7, I know the Unix Hostname global variable is wrong I know userinput does nothing, I want to get this part working before I continue on Thanks It outputs nothing
[ "You define a class and two functions, but you don't seem to call any of them anywhere. Are you missing a call to MainShellLoop() in the end?\n", "I think you need a call to MainShellLoop.\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003392911_python.txt
Q: Python Application does nothing This code stopped doing anything at all after I changed something that I no longer remember #Dash Shell import os import datetime class LocalComputer: pass def InitInformation(): Home = LocalComputer() #Acquires user information if (os.name == "nt"): Home.ComputerName = os.getenv("COMPUTERNAME") Home.Username = os.getenv("USERNAME") Home.Homedir = os.getenv("HOMEPATH") else: Home.ComputerName = os.getenv() Home.Username = os.getenv("USER") Home.Homedir = os.getenv("HOME") return Home def MainShellLoop(): print ("--- Dash Shell ---") Home = InitInformation() userinput = None currentdir = Home.Homedir while (userinput != "exit"): rightnow = datetime.datetime.now() try: userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "@" + str(currentdir)) except: print("Invalid Command specified, please try again") MainShellLoop() edit: Lol sorry guys forgot to say its supposed to run the input A: You should better describe your problem. Does it print the input prompt? Does it output anything? Does it exit or just sit there? I noticed a few issues while reading over this code that might help. You should be using raw_input(), not input(). Also, you don't actually do anything with userinput unless it == 'exit'. Which is won't, because you are just using input(), not raw_input(), so the person would have to enter 'exit' (including quotes) or else the loop will never exit. (Assuming it's not Python 3 Code) A: It's doing nothing because there's no code to make it do anything. Try inserting a line like print("You entered:", userinput) at an appropriate place in your loop. A: os.getenv() must have at least one param. Try os.getenv("HOST") or something.
Python Application does nothing
This code stopped doing anything at all after I changed something that I no longer remember #Dash Shell import os import datetime class LocalComputer: pass def InitInformation(): Home = LocalComputer() #Acquires user information if (os.name == "nt"): Home.ComputerName = os.getenv("COMPUTERNAME") Home.Username = os.getenv("USERNAME") Home.Homedir = os.getenv("HOMEPATH") else: Home.ComputerName = os.getenv() Home.Username = os.getenv("USER") Home.Homedir = os.getenv("HOME") return Home def MainShellLoop(): print ("--- Dash Shell ---") Home = InitInformation() userinput = None currentdir = Home.Homedir while (userinput != "exit"): rightnow = datetime.datetime.now() try: userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "@" + str(currentdir)) except: print("Invalid Command specified, please try again") MainShellLoop() edit: Lol sorry guys forgot to say its supposed to run the input
[ "You should better describe your problem. Does it print the input prompt? Does it output anything? Does it exit or just sit there? I noticed a few issues while reading over this code that might help. You should be using raw_input(), not input(). Also, you don't actually do anything with userinput unless it == 'exit...
[ 2, 2, 1 ]
[]
[]
[ "null", "python" ]
stackoverflow_0003391518_null_python.txt
Q: Extracting tokens where some are optional I need to parse out time tokens from a string where the tokens are optional. Samples given: tt-5d10h tt-5d10h30m tt-5d30m tt-10h30m tt-5d tt-10h tt-30m How can I, in Python, parse this out preferably as the set (days, hours, minutes)? A: This program returns three integers (days, hours, seconds) for each input: import re samples = ['tt-5d10h', 'tt-5d10h30m', 'tt-5d30m', 'tt-10h30m', 'tt-5d', 'tt-10h', 'tt-30m',] def parse(text): match = re.match('tt-(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?', text) values = [int(x) for x in match.groups(0)] return values for sample in samples: print parse(sample) Output: [5, 10, 0] [5, 10, 30] [5, 0, 30] [0, 10, 30] [5, 0, 0] [0, 10, 0] [0, 0, 30] A: >>> pattern = re.compile("tt-(\d+d)?(\d+h)?(\d+m)?") >>> results = pattern.match("tt-5d10h") >>> days, hours, minutes = results.groups() >>> days, hours, minutes ('5d', '10h', None) A: Similar to compie's answer, but making the end result nicer to deal with: re.match('tt-(?:(?P<days>\d+)d)?(?:(?P<hours>\d+)h)?(?:(?P<minutes>\d+)m)?', text).groupdict() Example: >>> import re >>> s = ['tt-5d10h', 'tt-5d10h30m', 'tt-5d30m', 'tt-10h30m', 'tt-5d', 'tt-10h', 'tt-30m'] >>> for text in s: print(re.match('tt-(?:(?P<days>\d+)d)?(?:(?P<hours>\d+)h)?(?:(?P<minutes>\d+)m)?', text).groupdict()) {'hours': '10', 'minutes': None, 'days': '5'} {'hours': '10', 'minutes': '30', 'days': '5'} {'hours': None, 'minutes': '30', 'days': '5'} {'hours': '10', 'minutes': '30', 'days': None} {'hours': None, 'minutes': None, 'days': '5'} {'hours': '10', 'minutes': None, 'days': None} {'hours': None, 'minutes': '30', 'days': None} If you want to substitute 0 for the left-out tokens instead, just use groupdict(0) instead of groupdict(). A: By partition: inputstring="""tt-5d10h tt-5d10h30m tt-5d30m tt-10h30m tt-5d tt-10h tt-30m """ separators=('d','h','m') result=[] for text in (item.lstrip('t-') for item in inputstring.splitlines()): data=[] for sep in separators: d,found,text = text.partition(sep) if found: data.append(int(d.rstrip(sep))) else: data.append(0) text=d result.append(data) # show input and result for respairs in zip(inputstring.splitlines(),result): print(respairs) """ Output: ('tt-5d10h', [5, 10, 0]) ('tt-5d10h30m', [5, 10, 30]) ('tt-5d30m', [5, 0, 30]) ('tt-10h30m', [0, 10, 30]) ('tt-5d', [5, 0, 0]) ('tt-10h', [0, 10, 0]) ('tt-30m', [0, 0, 30]) """ A: Here's a pyparsing approach to your problem: tests = """tt-5d10h tt-5d10h30m tt-5d30m tt-10h30m tt-5d tt-10h tt-30m""".splitlines() from pyparsing import Word,nums,Optional integer = Word(nums).setParseAction(lambda t:int(t[0])) timeFormat = "tt-" + ( Optional(integer("days") + "d") + Optional(integer("hrs") + "h") + Optional(integer("mins") + "m") ) def normalizeTime(tokens): return tuple(tokens[field] if field in tokens else 0 for field in "days hrs mins".split()) timeFormat.setParseAction(normalizeTime) for test in tests: print "%-12s ->" % test, print "%d %02d:%02d" % timeFormat.parseString(test)[0] Prints: tt-5d10h -> 5 10:00 tt-5d10h30m -> 5 10:30 tt-5d30m -> 5 00:30 tt-10h30m -> 0 10:30 tt-5d -> 5 00:00 tt-10h -> 0 10:00 tt-30m -> 0 00:30 Or to preserve the named results: def normalizeTime(tokens): for field in "days hrs mins".split(): if field not in tokens: tokens[field] = 0 timeFormat.setParseAction(normalizeTime) for test in tests: print "%-12s ->" % test, print "%(days)d %(hrs)02d:%(mins)02d" % timeFormat.parseString(test)
Extracting tokens where some are optional
I need to parse out time tokens from a string where the tokens are optional. Samples given: tt-5d10h tt-5d10h30m tt-5d30m tt-10h30m tt-5d tt-10h tt-30m How can I, in Python, parse this out preferably as the set (days, hours, minutes)?
[ "This program returns three integers (days, hours, seconds) for each input:\nimport re\nsamples = ['tt-5d10h', 'tt-5d10h30m', 'tt-5d30m', 'tt-10h30m', 'tt-5d', 'tt-10h', 'tt-30m',]\n\ndef parse(text):\n match = re.match('tt-(?:(\\d+)d)?(?:(\\d+)h)?(?:(\\d+)m)?', text)\n values = [int(x) for x in match.groups(...
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0003391261_python_regex_string.txt
Q: Lazy Evaluation for iterating through NumPy arrays I have a Python program that processes fairly large NumPy arrays (in the hundreds of megabytes), which are stored on disk in pickle files (one ~100MB array per file). When I want to run a query on the data I load the entire array, via pickle, and then perform the query (so that from the perspective of the Python program the entire array is in memory, even if the OS is swapping it out). I did this mainly because I believed that being able to use vectorized operations on NumPy arrays would be substantially faster than using for loops through each item. I'm running this on a web server which has memory limits that I quickly run up against. I have many different kinds of queries that I run on the data so writing "chunking" code which loads portions of the data from separate pickle files, processes them, and then proceeds to the next chunk would likely add a lot of complexity. It'd definitely be preferable to make this "chunking" transparent to any function that processes these large arrays. It seems like the ideal solution would be something like a generator which periodically loaded a block of the data from the disk and then passed the array values out one by one. This would substantially reduce the amount of memory required by the program without requiring any extra work on the part of the individual query functions. Is it possible to do something like this? A: PyTables is a package for managing hierarchical datasets. It is designed to solve this problem for you. A: NumPy's memory-mapped data structure (memmap) might be a good choice here. You access your NumPy arrays from a binary file on disk, without loading the entire file into memory at once. (Note, i believe, but i am not certain, that Numpys memmap object is not the same as Pythons--in particular, NumPys is array-like, Python's is file-like.) The method signature is: A = NP.memmap(filename, dtype, mode, shape, order='C') All of the arguments are straightforward (i.e., they have the same meaning as used elsewhere in NumPy) except for 'order', which refers to order of the ndarray memory layout. I believe the default is 'C', and the (only) other option is 'F', for Fortran--as elsewhere, these two options represent row-major and column-major order, respectively. The two methods are: flush (which writes to disk any changes you make to the array); and close (which writes the data to the memmap array, or more precisely to an array-like memory-map to the data stored on disk) example use: import numpy as NP from tempfile import mkdtemp import os.path as PH my_data = NP.random.randint(10, 100, 10000).reshape(1000, 10) my_data = NP.array(my_data, dtype="float") fname = PH.join(mkdtemp(), 'tempfile.dat') mm_obj = NP.memmap(fname, dtype="float32", mode="w+", shape=1000, 10) # now write the data to the memmap array: mm_obj[:] = data[:] # reload the memmap: mm_obj = NP.memmap(fname, dtype="float32", mode="r", shape=(1000, 10)) # verify that it's there!: print(mm_obj[:20,:]) A: It seems like the ideal solution would be something like a generator which periodically loaded a block of the data from the disk and then passed the array values out one by one. This would substantially reduce the amount of memory required by the program without requiring any extra work on the part of the individual query functions. Is it possible to do something like this? Yes, but not by keeping the arrays on disk in a single pickle -- the pickle protocol just isn't designed for "incremental deserialization". You can write multiple pickles to the same open file, one after the other (use dump, not dumps), and then the "lazy evaluator for iteration" just needs to use pickle.load each time. Example code (Python 3.1 -- in 2.any you'll want cPickle instead of pickle and a -1 for protocol, etc, of course;-): >>> import pickle >>> lol = [range(i) for i in range(5)] >>> fp = open('/tmp/bah.dat', 'wb') >>> for subl in lol: pickle.dump(subl, fp) ... >>> fp.close() >>> fp = open('/tmp/bah.dat', 'rb') >>> def lazy(fp): ... while True: ... try: yield pickle.load(fp) ... except EOFError: break ... >>> list(lazy(fp)) [range(0, 0), range(0, 1), range(0, 2), range(0, 3), range(0, 4)] >>> fp.close()
Lazy Evaluation for iterating through NumPy arrays
I have a Python program that processes fairly large NumPy arrays (in the hundreds of megabytes), which are stored on disk in pickle files (one ~100MB array per file). When I want to run a query on the data I load the entire array, via pickle, and then perform the query (so that from the perspective of the Python program the entire array is in memory, even if the OS is swapping it out). I did this mainly because I believed that being able to use vectorized operations on NumPy arrays would be substantially faster than using for loops through each item. I'm running this on a web server which has memory limits that I quickly run up against. I have many different kinds of queries that I run on the data so writing "chunking" code which loads portions of the data from separate pickle files, processes them, and then proceeds to the next chunk would likely add a lot of complexity. It'd definitely be preferable to make this "chunking" transparent to any function that processes these large arrays. It seems like the ideal solution would be something like a generator which periodically loaded a block of the data from the disk and then passed the array values out one by one. This would substantially reduce the amount of memory required by the program without requiring any extra work on the part of the individual query functions. Is it possible to do something like this?
[ "PyTables is a package for managing hierarchical datasets. It is designed to solve this problem for you.\n", "NumPy's memory-mapped data structure (memmap) might be a good choice here.\nYou access your NumPy arrays from a binary file on disk, without loading the entire file into memory at once.\n(Note, i believe,...
[ 9, 4, 2 ]
[]
[]
[ "lazy_evaluation", "memory_management", "numpy", "python" ]
stackoverflow_0003392877_lazy_evaluation_memory_management_numpy_python.txt
Q: Creating ScrolledWindow in wxPython I am trying to make a ScrolledWindow that can scroll over a grid of images, but the scrollbar isn't appearing. wxWidgets documentation says: The most automatic and newest way [to set the scrollbars in wxScrolledWindow] is to simply let sizers determine the scrolling area. This is now the default when you set an interior sizer into a wxScrolledWindow with wxWindow::SetSizer. The scrolling area will be set to the size requested by the sizer and the scrollbars will be assigned for each orientation according to the need for them and the scrolling increment set by wxScrolledWindow::SetScrollRate So I try to set the sizer of my ScrolledWindow with a GridSizer but it's not working. The code: import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self,parent,id,title,pos,size,style,name) self.panel = wx.ScrolledWindow(self,wx.ID_ANY) menuBar = wx.MenuBar() menu1 = wx.Menu() m = menu1.Append(wx.NewId(), "&Blah", "Show Pictures") menuBar.Append(menu1,"&Blah") self.Bind(wx.EVT_MENU,self.OnInit,m) self.SetMenuBar(menuBar) def OnInit(self, event): sizer = wx.GridSizer(rows=7,cols=3) filenames = [] for i in range(20): filenames.append("img"+str(i)+".png") for fn in filenames: img = wx.Image(fn,wx.BITMAP_TYPE_ANY) sizer.Add(wx.StaticBitmap(self.panel,wx.ID_ANY,wx.BitmapFromImage(img))) self.panel.SetSizer(sizer) class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(parent=None,title="Frame") self.frame.Show() self.SetTopWindow(self.frame) return True if __name__ == "__main__": app = MyApp() app.MainLoop() A: Insert this self.panel.SetScrollbars(1, 1, 1, 1) after self.panel = wx.ScrolledWindow(self,wx.ID_ANY) If you want some info on the SetScrollBars method then look at this wxwidgets documentation page
Creating ScrolledWindow in wxPython
I am trying to make a ScrolledWindow that can scroll over a grid of images, but the scrollbar isn't appearing. wxWidgets documentation says: The most automatic and newest way [to set the scrollbars in wxScrolledWindow] is to simply let sizers determine the scrolling area. This is now the default when you set an interior sizer into a wxScrolledWindow with wxWindow::SetSizer. The scrolling area will be set to the size requested by the sizer and the scrollbars will be assigned for each orientation according to the need for them and the scrolling increment set by wxScrolledWindow::SetScrollRate So I try to set the sizer of my ScrolledWindow with a GridSizer but it's not working. The code: import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self,parent,id,title,pos,size,style,name) self.panel = wx.ScrolledWindow(self,wx.ID_ANY) menuBar = wx.MenuBar() menu1 = wx.Menu() m = menu1.Append(wx.NewId(), "&Blah", "Show Pictures") menuBar.Append(menu1,"&Blah") self.Bind(wx.EVT_MENU,self.OnInit,m) self.SetMenuBar(menuBar) def OnInit(self, event): sizer = wx.GridSizer(rows=7,cols=3) filenames = [] for i in range(20): filenames.append("img"+str(i)+".png") for fn in filenames: img = wx.Image(fn,wx.BITMAP_TYPE_ANY) sizer.Add(wx.StaticBitmap(self.panel,wx.ID_ANY,wx.BitmapFromImage(img))) self.panel.SetSizer(sizer) class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(parent=None,title="Frame") self.frame.Show() self.SetTopWindow(self.frame) return True if __name__ == "__main__": app = MyApp() app.MainLoop()
[ "Insert this \nself.panel.SetScrollbars(1, 1, 1, 1)\n\nafter self.panel = wx.ScrolledWindow(self,wx.ID_ANY)\nIf you want some info on the SetScrollBars method then look at this wxwidgets documentation page\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003392631_python_wxpython.txt
Q: Flash video record on website tutorial I wanted to make a website that would let users record a small video message through their broswer and save it to my website. As I have never used flash, i wanted to know what softwares would be required and what programming languages would I need? I mean, what should I go about learning to implement such a site. I would prefer open-source solutions wherever possible. Can something like this be implemented using python and html5? A: There are many video solutions. Here are two: Take a look at Flash Media Server (FMS). You will need to some server-side code to place the video into a folder as it streams up. Also, if you're looking into free open-source take a look at Red5.
Flash video record on website tutorial
I wanted to make a website that would let users record a small video message through their broswer and save it to my website. As I have never used flash, i wanted to know what softwares would be required and what programming languages would I need? I mean, what should I go about learning to implement such a site. I would prefer open-source solutions wherever possible. Can something like this be implemented using python and html5?
[ "There are many video solutions. Here are two:\nTake a look at Flash Media Server (FMS). You will need to some server-side code to place the video into a folder as it streams up. \nAlso, if you're looking into free open-source take a look at Red5. \n" ]
[ 1 ]
[]
[]
[ "flash", "html5_video", "python", "video_capture" ]
stackoverflow_0003391222_flash_html5_video_python_video_capture.txt
Q: Why is class variable accessible at the instance without the __class__ prefix? See example below. Using the __class__ prefix with the class instance 'object' gives the expected result. Why is the class variable even available at the class instance 'c()' without the __class__ prefix? In what situation is it used? >>> class c: x=0 >>> c.x 0 >>> c().x 0 >>> c().__class__.x 0 >>> c.x += 1 >>> c.x 1 >>> c().x += 1 >>> c.x 1 >>> c().__class__.x += 1 >>> c.x 2 >>> A: Why is the class variable even available at the class instance 'c()' without the class prefix? You can usefully think of it as instances "inheriting from" their class. IOW, when an attribute named 'atr' is looked up on the instance x (e.g. by x.atr), unless found in the instance itself it's next looked up in the class (which in turn may cause lookup in the class's bases, up the mro chain). In what situation is it used? Most common single case: class sic(object): def foo(self): ... x = sic() x.foo() You may not think of foo as a "class variable", but that's because the term "variable" is really pretty meaningless in Python, which rather deals with names and attributes. There is no separate namespace for callable and non-callable objects at a given lexical scope: they all share the same namespace. So, for example, if you did x.foo = 23 then you couldn't call x.foo() any more -- because the lookup for x.foo would give you the value 23, and that's an int, not callable. Another way to look at this is that class one(object): foo = lambda self: ... class two(object): def foo(self): ... class three(object): foo = 23 present no deep difference -- they're all way to set class attribute foo (one is not callable, two are; one is bound with a def statement, two with assignments; there differences are not deep in terms of attribute lookup on instances of these classes). A typical use for non-callable attributes might be: class zap(zop): zep = None def blub(self): if self.zep is None: self.zep = 23 ...&c... No need to give zap an __init__ with self.zep = None and a delegation to the superclass's __init__ (if any) -- simpler to just inherit zop's __init__ (if any) and use a class attribute as long as feasible (it will become an instance attribute instead if and only if blub is called on that instance -- also may save a tiny bit of memory for instances on which blub is never called;-).
Why is class variable accessible at the instance without the __class__ prefix?
See example below. Using the __class__ prefix with the class instance 'object' gives the expected result. Why is the class variable even available at the class instance 'c()' without the __class__ prefix? In what situation is it used? >>> class c: x=0 >>> c.x 0 >>> c().x 0 >>> c().__class__.x 0 >>> c.x += 1 >>> c.x 1 >>> c().x += 1 >>> c.x 1 >>> c().__class__.x += 1 >>> c.x 2 >>>
[ "\nWhy is the class variable even\n available at the class instance 'c()'\n without the class prefix?\n\nYou can usefully think of it as instances \"inheriting from\" their class. IOW, when an attribute named 'atr' is looked up on the instance x (e.g. by x.atr), unless found in the instance itself it's next look...
[ 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003393146_oop_python.txt
Q: Prevent A User From Downloading Files from Python? I am working on a project that requires password protected downloading, but I'm not exactly sure how to implement that. If the target file has a specific extension (.exe, .mp3, .mp4, etc), I want to prompt the user for a username and password. Any ideas on this? I am using Python 26 on Windows XP. A: This is best implemented at the web server level. If you are using Apache, this can be done by placing the files you desire to protect in a directory with an htaccess file which requires user authentication. Then, implement HTTP Basic Auth in your Python script to download the files. Make sure to use an SSL connection; basic auth sends the user's password over the wire in the clear. A: Use HTTP's basic authentication (shown in the URL I've quoted from the client side): whenever a "sensitive" page or file is requested, and no Authorization header is part of the request (or it's invalid, see below), return a 401 status code instead, with a header WWW-Authenticate: Basic realm=XXXX (where XXXX is a hash of the URL, e.g. with MD5 or SHA1, to make it essentially unique per-file) the user will then need to enter username and password at his browser, which will send them back to the server you're implementing with the simple algorithm shown at that URL, namely: import base64 base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header("Authorization", "Basic %s" % base64string) when the Authorization header is present in the request, decode the base64 string it presents after 'Basic ' and check that it has the username:password you want You can use more sophisticated authentication, of course, but this may get you started unless the user's connection can (or so you suspect) be "sniffed" by evil third parties (in which case you'll want to use HTTPS anyway, so that basic auth becomes OK again;-).
Prevent A User From Downloading Files from Python?
I am working on a project that requires password protected downloading, but I'm not exactly sure how to implement that. If the target file has a specific extension (.exe, .mp3, .mp4, etc), I want to prompt the user for a username and password. Any ideas on this? I am using Python 26 on Windows XP.
[ "This is best implemented at the web server level.\nIf you are using Apache, this can be done by placing the files you desire to protect in a directory with an htaccess file which requires user authentication.\nThen, implement HTTP Basic Auth in your Python script to download the files. Make sure to use an SSL con...
[ 2, 1 ]
[]
[]
[ "download", "passwords", "python", "windows" ]
stackoverflow_0003393314_download_passwords_python_windows.txt
Q: E-mail traceback on errors in Bottle framework I am using the Bottle framework. I have set the @error decorator so I am able to display my customized error page, and i can also send email if any 500 error occurs, but I need the complete traceback to be sent in the email. Does anyone know how to have the framework include that in the e-mail? A: in the error500 function written after the @error decorator to serve my customized error page, wrote error.exception and error.traceback, these two give the exception and complete traceback of the error message. A: Debugging mode enables full tracebacks: from bottle import debug debug(True) From there, you will need to pipe stderr to a file, then send it.
E-mail traceback on errors in Bottle framework
I am using the Bottle framework. I have set the @error decorator so I am able to display my customized error page, and i can also send email if any 500 error occurs, but I need the complete traceback to be sent in the email. Does anyone know how to have the framework include that in the e-mail?
[ "in the error500 function written after the @error decorator to serve my customized error page, wrote error.exception and error.traceback, these two give the exception and complete traceback of the error message.\n", "Debugging mode enables full tracebacks:\nfrom bottle import debug\ndebug(True)\n\nFrom there, yo...
[ 3, 2 ]
[]
[]
[ "bottle", "error_handling", "python" ]
stackoverflow_0003363167_bottle_error_handling_python.txt
Q: Why does this do what it does? I found this interesting item in a blog today: def abc(): try: return True finally: return False print "abc() is", abc() Can anyone tell why it does what it does? Thanks, KR A: If the finally block contains a return or break statement the result from the try block is discarded it's explained in detail in the python docu A: Go to the try statement area: http://docs.python.org/reference/compound_stmts.html The finally statement is still executed. Really interesting situation though. I learned something new. :) A: Thanks for pointer to the docs. I could not get past the 'return True' to even think of looking there. Part of the documentation reads: If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed,... which suggests that the return True is executed. However, this is later clarified: When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out.’ Which explains the observed behavior. What kind of mind would think up some code like this in the first place? ;)
Why does this do what it does?
I found this interesting item in a blog today: def abc(): try: return True finally: return False print "abc() is", abc() Can anyone tell why it does what it does? Thanks, KR
[ "If the finally block contains a return or break statement the result from the try\nblock is discarded\nit's explained in detail in the python docu\n", "Go to the try statement area:\nhttp://docs.python.org/reference/compound_stmts.html\nThe finally statement is still executed. Really interesting situation thoug...
[ 10, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003390310_python_syntax.txt
Q: Python property and method override issue: why subclass property still calls the base class's method Here is an example class A(object): def f1(self): return [] test1 = property(f1) class B(A): def f1(self): return [1, 2] if __name__ == "__main__": b = B() print b.test1 I expect the output to be [1, 2], but it prints [] instead. It is contrary to my expectation. Did I make any mistake in the code? If not, I suppose it works this way because when the property test1 is created, it is bound to the f1 function of the base class A. What is a possible alternative implementation to achieve what I want? A: You can defer the lookup of f1 with a lambda function if you don't wish to pollute the class namespace class A(object): def f1(self): return [] test1 = property(lambda x:x.f1()) A: I suppose it works this way because when the property test1 is created, it is bound to the f1 function of the base class A. Exactly correct. What is a possible alternative implementation to achieve what I want? One more level of indirection: class A(object): def f1(self): return [] def _f1(self): return self.f1() test1 = property(_f1) class B(A): def f1(self): return [1, 2] A: A couple of alternatives I can think of: either repeat the call to property in the subclass, class B(A): def f1(self): return [1,2] test1 = property(f1) or base the property on another method which calls f1: class A(object): def f1(self): return [] def _f1(self): return self.f1() test1 = property(_f1)
Python property and method override issue: why subclass property still calls the base class's method
Here is an example class A(object): def f1(self): return [] test1 = property(f1) class B(A): def f1(self): return [1, 2] if __name__ == "__main__": b = B() print b.test1 I expect the output to be [1, 2], but it prints [] instead. It is contrary to my expectation. Did I make any mistake in the code? If not, I suppose it works this way because when the property test1 is created, it is bound to the f1 function of the base class A. What is a possible alternative implementation to achieve what I want?
[ "You can defer the lookup of f1 with a lambda function if you don't wish to pollute the class namespace\nclass A(object):\n\n def f1(self):\n return []\n\n test1 = property(lambda x:x.f1())\n\n", "\nI suppose it works this way because\n when the property test1 is created, it\n is bo...
[ 6, 3, 1 ]
[]
[]
[ "inheritance", "properties", "python" ]
stackoverflow_0003393534_inheritance_properties_python.txt
Q: Django users: get list of group, or how to convert MultipleChoiceField to ChoiceField I've searched similar topics but haven't found what I need.. I extended Users model with UserAttributes model, some additional fields added and etc.. now I'm trying to make ModelForm out this.. so I have a little problem in here.. I WANT TO list groups as a ChoiceField not a MultipleChoiceField.. It's a requirement by specification so it must be so. so here's the code.. from django.forms import ModelForm from django.contrib.auth.models import User from helpdesk.models.userattributes import * from django.utils.translation import ugettext as _ class SettingsOperatorsForm(ModelForm): groups = forms.ChoiceField( label=_(u'Rights'), required=True, choices=["what's in here?"] ) class Meta: model = UserAttributes fields = ('first_name', 'last_name', 'job_title', 'email', 'password', 'is_active', 'groups' ) there's auth_group table in database, so i tried to make it like this , but I've got a no form displayed at all: from django.contrib.auth.models import User, Group groups = forms.ChoiceField( label=_(u'Rights'), required=True, choices=Group.objects.all() ) I think it's better would be just to convert multipleChoiceField to ChoiceField in plain talk: should become just SELECT box. A: Setting the choices at form definition time, as you do in your answer, will mean that the form will never see any new Groups that are defined. Rather than using a ChoiceField with a list comprehension for choices, you should use a ModelChoiceField with a queryset parameter: groups = forms.ModelChoiceField(queryset=Group.objects.all()) A: Just a feedback, because 2hours no answers, so thnx to freenode #django =) http://docs.djangoproject.com/en/dev/topics/forms/modelforms/ It's possible to override widgets for any field in Meta Class like this: from django.forms import ModelForm class AuthorForm(ModelForm): class Meta: model = Author widgets = { 'groups': forms.Select(),} DOESN'T WORK forms.ChoiceField() too.. nothing changed.. still displaying multichoice select.. UPDATE from django.contrib.auth.models import User, Group groups = forms.ChoiceField( required=True, choices = [ [g.id, g.name] for g in Group.objects.filter() ] ) This works.. it's ok but, why the hell widget override doesn't work???? RESOLVED because I have django 1.1 =( my stupidity.. A: it appears that it's that modelchoice would be wrong because current group in edit form will not be selected="Selected" so this is solution FINALLY: groups = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=GroupsSelect, ) def __init__(self, *args, **kw): super(ModelForm, self).__init__(*args, **kw) self.fields['groups'].queryset=Group.objects.filter(user=self.instance.id) #view op = UserAttributes.objects.get(id=operator_id) form = SettingsOperatorsForm(instance=op)
Django users: get list of group, or how to convert MultipleChoiceField to ChoiceField
I've searched similar topics but haven't found what I need.. I extended Users model with UserAttributes model, some additional fields added and etc.. now I'm trying to make ModelForm out this.. so I have a little problem in here.. I WANT TO list groups as a ChoiceField not a MultipleChoiceField.. It's a requirement by specification so it must be so. so here's the code.. from django.forms import ModelForm from django.contrib.auth.models import User from helpdesk.models.userattributes import * from django.utils.translation import ugettext as _ class SettingsOperatorsForm(ModelForm): groups = forms.ChoiceField( label=_(u'Rights'), required=True, choices=["what's in here?"] ) class Meta: model = UserAttributes fields = ('first_name', 'last_name', 'job_title', 'email', 'password', 'is_active', 'groups' ) there's auth_group table in database, so i tried to make it like this , but I've got a no form displayed at all: from django.contrib.auth.models import User, Group groups = forms.ChoiceField( label=_(u'Rights'), required=True, choices=Group.objects.all() ) I think it's better would be just to convert multipleChoiceField to ChoiceField in plain talk: should become just SELECT box.
[ "Setting the choices at form definition time, as you do in your answer, will mean that the form will never see any new Groups that are defined.\nRather than using a ChoiceField with a list comprehension for choices, you should use a ModelChoiceField with a queryset parameter:\ngroups = forms.ModelChoiceField(querys...
[ 4, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003384119_django_python.txt
Q: How to enlarge subplot matplotlib? I currently have two subplots. Note: this is in matplotlib v0.99.3 on Mac OS X 10.6.x I have an event-handler that when one of the subplots are clicked, it prints something. This is only a temporary place holder. What I want to happen is when the subplot is clicked, I want it to take up the whole figure (delete the other subplot and maximize to fill up the whole figure). How would I go about doing this? A: You can do this by modifying the axes that subplot returns. That is, axes can be positioned and sized in any desired way, and subplot is just a function that returns axes positioned in a uniform grid; but once you have these axes from subplot you can arbitrarily resize and reposition them. Here's an example: from pylab import * axes = [None, None] def make(): figure() axes[0] = subplot(1, 2, 1) axes[1] = subplot(1, 2, 2) show() def re_form(): xmax = axes[1].get_position().get_points()[1][0] axes[1].set_axis_off() (x0, y0), (x1, y1) = axes[0].get_position().get_points() # xmin, ymin, xmax, ymax axes[0].set_position([x0, y0, xmax-x0, y1-y0]) # x, y, width, height show() Here I used show() to update the plot, but you'll want to use something more appropriate for your event handler. This demo works with iPython: first run the file, then call make(), which draws the two axes, and then re_form(), which removes the second axis and widens the first.
How to enlarge subplot matplotlib?
I currently have two subplots. Note: this is in matplotlib v0.99.3 on Mac OS X 10.6.x I have an event-handler that when one of the subplots are clicked, it prints something. This is only a temporary place holder. What I want to happen is when the subplot is clicked, I want it to take up the whole figure (delete the other subplot and maximize to fill up the whole figure). How would I go about doing this?
[ "You can do this by modifying the axes that subplot returns. That is, axes can be positioned and sized in any desired way, and subplot is just a function that returns axes positioned in a uniform grid; but once you have these axes from subplot you can arbitrarily resize and reposition them. Here's an example:\nfr...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003390568_matplotlib_python.txt
Q: Vibrate window in wxPython How would I vibrate a window in wxPython. I'd like some way of specifying how long to do it for and distance and stuff like that. Is there a builtin function I'm not noticing or would I have to code it myself? (I'm thinking of moving the window sideways a few times but I'd rather have a builtin function that might be faster.) A: I don't think there is any such function, but you can easily do it using win.SetPosition e.g. click inside frame to vibrate import wx def vibrate(win, count=20, delay=50): if count == 0: return x, y = win.GetPositionTuple() dx = 2*count*(.5-count%2) win.SetPosition((x+dx,y)) wx.CallLater(delay, vibrate, win, count-1, delay) app = wx.PySimpleApp() frame = wx.Frame(None, title="Vibrator") frame.Show() frame.Bind(wx.EVT_LEFT_DOWN, lambda e:wx.CallAfter(vibrate, frame)) app.SetTopWindow(frame) app.MainLoop() A: Until people answered my question, I was working on my own method of doing it. I've only started GUI programming so I don't know all the features of wx so I ended up using the time module. Anurag's method is probably better since it uses wx functions, but I'll post this here anyways as another way of doing it. NOTE: This may not always work (I'm having trouble getting it to work with diff interpreters on same OS). So use Anurag's method. import wx def vibrate(windowName, distance=15, times=5, speed=0.05, direction='horizontal'): #Speed is the number of seconds between movements #If times is odd, it increments so that window ends up in same location import time if not times % 2 == 0: times += 1 location = windowName.GetPositionTuple() if direction == 'horizontal': newLoc = (location[0] + distance, location[1]) elif direction == 'vertical': newLoc = (location[0], location[1] + distance) for x in range(times): time.sleep(speed) windowName.Move(wx.Point(newLoc[0], newLoc[1])) time.sleep(speed) windowName.Move(wx.Point(location[0], location[1])) app = wx.App() frame = wx.Frame(None, -1, 'Vibrator') frame.Show() vibrate(frame) app.MainLoop()
Vibrate window in wxPython
How would I vibrate a window in wxPython. I'd like some way of specifying how long to do it for and distance and stuff like that. Is there a builtin function I'm not noticing or would I have to code it myself? (I'm thinking of moving the window sideways a few times but I'd rather have a builtin function that might be faster.)
[ "I don't think there is any such function, but you can easily do it using win.SetPosition\ne.g. click inside frame to vibrate\nimport wx\n\ndef vibrate(win, count=20, delay=50):\n if count == 0: return\n x, y = win.GetPositionTuple()\n dx = 2*count*(.5-count%2)\n win.SetPosition((x+dx,y))\n wx.CallLa...
[ 5, 0 ]
[]
[]
[ "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0003393478_python_user_interface_wxpython_wxwidgets.txt
Q: Configure Django URLS.py to keep #anchors in URL after it rewrites it with a end / In my django application I have my URLS.PY configured to accept requests to /community/user/id and /community/user/id/ with: url(r'^(?P<username>[\w-]+)/(?P<cardId>\d+)/$', 'singleCard.views.singleCard', name='singleCardView'), I did this as some times people will add an ending "/" and I didn't want to raise a 404. However parts of my javascript application sometime add a anchor tag in the form of: /community/user/id#anchorIuseInJavscriptToDoSomething The problem I have is Django will instantly rewrite the URL to: /community/user/id/ with an ending / and remove the #anchorIuseInJavscriptToDoSomething Id like it to rewrite it to: /community/user/id#anchorIuseInJavscriptToDoSomething/ This way my javascript in the page can still see the anchor and work. How can adapt this regex to do this? I'm not very good at regex, and learnt this one by example... A: you could make the trailing slash optional: url(r'^(?P<username>[\w-]+)/(?P<cardId>\d+)/?$', 'singleCard.views.singleCard', name='singleCardView'), A: The Browser should handle re-appending the anchor after the redirect. Your problem has nothing to do with Django. A: Why do you want to change it to /community/user/id#anchorIuseInJavscriptToDoSomething/? This is invalid. It should be /community/user/id/#anchorIuseInJavscriptToDoSomething. The element after the hash is not part of the URL and is not sent to the server.
Configure Django URLS.py to keep #anchors in URL after it rewrites it with a end /
In my django application I have my URLS.PY configured to accept requests to /community/user/id and /community/user/id/ with: url(r'^(?P<username>[\w-]+)/(?P<cardId>\d+)/$', 'singleCard.views.singleCard', name='singleCardView'), I did this as some times people will add an ending "/" and I didn't want to raise a 404. However parts of my javascript application sometime add a anchor tag in the form of: /community/user/id#anchorIuseInJavscriptToDoSomething The problem I have is Django will instantly rewrite the URL to: /community/user/id/ with an ending / and remove the #anchorIuseInJavscriptToDoSomething Id like it to rewrite it to: /community/user/id#anchorIuseInJavscriptToDoSomething/ This way my javascript in the page can still see the anchor and work. How can adapt this regex to do this? I'm not very good at regex, and learnt this one by example...
[ "you could make the trailing slash optional:\nurl(r'^(?P<username>[\\w-]+)/(?P<cardId>\\d+)/?$', 'singleCard.views.singleCard', name='singleCardView'),\n\n", "The Browser should handle re-appending the anchor after the redirect. Your problem has nothing to do with Django.\n", "Why do you want to change it to /c...
[ 2, 0, 0 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0003367194_django_django_urls_python_regex.txt
Q: I need to free up RAM by storing a Python dictionary on the hard drive, not in RAM. Is it possible? In my case, I have a dictionary of about 6000 instantiated classes, where each class has 1000 attributed variables all of type string or list of strings. As I build this dictionary up, my RAM goes up super high. Is there a way to write the dictionary as it is being built to the harddrive rather than the RAM so that I can save some memory? I've heard of something called "pickle" but I don't know if this is a feasible method for what I am doing. Thanks for your help! A: Maybe you should be using a database, but check out the shelve module If shelve isn't powerful enough for you, there is always the industrial strength ZODB A: shelve, as @gnibbler recommends, is what I would no doubt be using, but watch out for two traps: a simple one (all keys must be strings) and a subtle one (as the values don't normally exist in memory, calling mutators on them may not work as you expect). For the simple problem, it's normally easy to find a workaround (and you do get a clear exception if you forget and try e.g. using an int or whatever as the key, so it's not hard t remember that you do need a workaround either). For the subtle problem, consider for example: x = d['foo'] x.amutatingmethod() ...much later... y = d['foo'] # is y "mutated" or not now? the answer to the question in the last comment depends on whether d is a real dict (in which case y will be mutated, and in fact exactly the same object as x) or a shelf (in which case y will be a distinct object from x, and in exactly the state you last saved to d['foo']!). To get your mutations to persist, you need to "save them to disk" by doing d['foo'] = x after calling any mutators you want on x (so in particular you cannot just do d['foo'].mutator() and expect the mutation to "stick", as you would if d were a dict). shelve does have an option to cache all fetched items in memory, but of course that can fill up the memory again, and result in long delays when you finally close the shelf object (since all the cached items must be saved back to disk then, just in case they had been mutated). That option was something I originally pushed for (as a Python core committer), but I've since changed my mind and I now apologize for getting it in (ah well, at least it's not the default!-), since the cases it should be used in are rare, and it can often trap the unwary user... sorry. BTW, in case you don't know what a mutator, or "mutating method", is, it's any method that alters the state of the object you call it on -- e.g. .append if the object is a list, .pop if the object is any kind of container, and so on. No need to worry if the object is immutable, of course (numbers, strings, tuples, frozensets, ...), since it doesn't have mutating methods in that case;-). A: Pickling an entire hash over and over again is bound to run into the same memory pressures that you're facing now -- maybe even worse, with all the data marshaling back and forth. Instead, using an on-disk database that acts like a hash is probably the best bet; see this page for a quick introduction to using dbm-style databases in your program: http://docs.python.org/library/dbm They act enough like hashes that it should be a simple transition for you. A: """I have a dictionary of about 6000 instantiated classes, where each class has 1000 attributed variables all of type string or list of strings""" ... I presume that you mean: """I have a class with about 1000 attributes all of type str or list of str. I have a dictionary mapping about 6000 keys of unspecified type to corresponding instances of that class.""" If that's not a reasonable translation, please correct it. For a start, 1000 attributes in a class is mindboggling. You must be treating the vast majority generically using value = getattr(obj, attr_name) and setattr(obj, attr_name, value). Consider using a dict instead of an instance: value = obj[attr_name] and obj[attr_name] = value. Secondly, what percentage of those 6 million attributes are ""? If sufficiently high, you might like to consider implementing a sparse dict which doesn't physically have entries for those attributes, using the __missing__ hook -- docs here.
I need to free up RAM by storing a Python dictionary on the hard drive, not in RAM. Is it possible?
In my case, I have a dictionary of about 6000 instantiated classes, where each class has 1000 attributed variables all of type string or list of strings. As I build this dictionary up, my RAM goes up super high. Is there a way to write the dictionary as it is being built to the harddrive rather than the RAM so that I can save some memory? I've heard of something called "pickle" but I don't know if this is a feasible method for what I am doing. Thanks for your help!
[ "Maybe you should be using a database, but check out the shelve module\nIf shelve isn't powerful enough for you, there is always the industrial strength ZODB\n", "shelve, as @gnibbler recommends, is what I would no doubt be using, but watch out for two traps: a simple one (all keys must be strings) and a subtle o...
[ 6, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003392663_python.txt
Q: Group Input in Forms I've this django form class CustomerForm(forms.Form): first_name = forms.CharField(label=_('Nome'), max_length=30) last_name = forms.CharField(label=_('Cognome'), max_length=30) business_name = forms.CharField(label=_('Ragione Sociale'), max_length=100) vat_number = forms.CharField(label=_('Partita iva'), max_length=11, required=False) and I want to group the inputs (first_name and last_name, business_name and vat_number) so that when I display the form I get first_name and last_name in a div and business_name and vat_number in a another div is this possible? Thanks :) A: There's nothing to stop you doing this in your template. Remember, as the documentation says, the {{ form.as_p }} etc are just shortcuts. As soon as you need to do something different, you can just fall back to iterating through the fields in your template, or even listing them individually. A: have a look at the Stacked/Grouped Forms snippet, where you can define "Stacks" (Groups) of fields in your Form.
Group Input in Forms
I've this django form class CustomerForm(forms.Form): first_name = forms.CharField(label=_('Nome'), max_length=30) last_name = forms.CharField(label=_('Cognome'), max_length=30) business_name = forms.CharField(label=_('Ragione Sociale'), max_length=100) vat_number = forms.CharField(label=_('Partita iva'), max_length=11, required=False) and I want to group the inputs (first_name and last_name, business_name and vat_number) so that when I display the form I get first_name and last_name in a div and business_name and vat_number in a another div is this possible? Thanks :)
[ "There's nothing to stop you doing this in your template. Remember, as the documentation says, the {{ form.as_p }} etc are just shortcuts. As soon as you need to do something different, you can just fall back to iterating through the fields in your template, or even listing them individually.\n", "have a look at ...
[ 1, 1 ]
[]
[]
[ "django", "django_forms", "input", "python" ]
stackoverflow_0001385766_django_django_forms_input_python.txt
Q: Proper way to process html form in BaseHTTPHandler I know that I am supposed to use cgi.FieldStorage for that. But what do I initialize it with? def do_GET(self): form = cgi.FieldStorage(WHAT SHOULD BE HERE?!) thanks! I did search, but didn't find an answer :( A: usually nothing! form = cgi.FieldStorage() From the source def __init__(self, fp=None, headers=None, outerboundary="", environ=os.environ, keep_blank_values=0, strict_parsing=0): """Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in URL encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. """
Proper way to process html form in BaseHTTPHandler
I know that I am supposed to use cgi.FieldStorage for that. But what do I initialize it with? def do_GET(self): form = cgi.FieldStorage(WHAT SHOULD BE HERE?!) thanks! I did search, but didn't find an answer :(
[ "usually nothing!\nform = cgi.FieldStorage() \n\nFrom the source\ndef __init__(self, fp=None, headers=None, outerboundary=\"\",\n environ=os.environ, keep_blank_values=0, strict_parsing=0):\n \"\"\"Constructor. Read multipart/* until last part.\n\n Arguments, all optional:\n\n fp ...
[ 1 ]
[]
[]
[ "basehttpserver", "forms", "http", "python" ]
stackoverflow_0003394075_basehttpserver_forms_http_python.txt
Q: Backup Google Calendar programmatically: https://www.google.com/calendar/exporticalzip I'm struggling with writing a python script that automatically grabs the zip fail containing all my google calendars and stores it (as a backup) on my harddisk. I'm using ClientLogin to get an authentication token (and successfully can obtain the token). Unfortunately, i'm unable to retrieve the file at https://www.google.com/calendar/exporticalzip It always asks me for the login credentials again by returning a login page as html (instead of the zip). Here's the critical code: post_data = post_data = urllib.urlencode({ 'auth': token, 'continue': zip_url}) request = urllib2.Request('https://www.google.com/calendar', post_data, header) try: f = urllib2.urlopen(request) result = f.read() except: print "Error" Anyone any ideas or done that before? Or an alternative idea how to backup all my calendars (automatically!) A: You could write a script with mechanize to walk through google login process before downloading Calendar from your preferred url. So try with: import mechanize br=mechanize.Browser() br.open('https://www.google.com/calendar/exporticalzip') br.select_form(nr=0) br['Email']='Username@gmail.com' br['Passwd']='Password' br.submit() br.retrieve('https://www.google.com/calendar/exporticalzip','exportical.zip') It worked for me, i downloaded my zipped ical calendar succesfully. A: Calendars have an URL which allows you to download it without authentication (see Google Calendar's UI, Calendar settings, under Private URL). You should be able to download the iCal or XML file using urllib without problems. A: Great solution systempuntoout! For those of you using Google Apps, just needs a tweak to the URLs and the Email. import mechanize br=mechanize.Browser() br.open('https://www.google.com/calendar/hosted/yourdomain.com/exporticalzip') br.select_form(nr=0) br['Email']='Username' br['Passwd']='Password' br.submit() br.retrieve('https://www.google.com/calendar/hosted/yourdomain.com/exporticalzip','exportical.zip')
Backup Google Calendar programmatically: https://www.google.com/calendar/exporticalzip
I'm struggling with writing a python script that automatically grabs the zip fail containing all my google calendars and stores it (as a backup) on my harddisk. I'm using ClientLogin to get an authentication token (and successfully can obtain the token). Unfortunately, i'm unable to retrieve the file at https://www.google.com/calendar/exporticalzip It always asks me for the login credentials again by returning a login page as html (instead of the zip). Here's the critical code: post_data = post_data = urllib.urlencode({ 'auth': token, 'continue': zip_url}) request = urllib2.Request('https://www.google.com/calendar', post_data, header) try: f = urllib2.urlopen(request) result = f.read() except: print "Error" Anyone any ideas or done that before? Or an alternative idea how to backup all my calendars (automatically!)
[ "You could write a script with mechanize to walk through google login process before downloading Calendar from your preferred url.\nSo try with:\nimport mechanize\nbr=mechanize.Browser()\nbr.open('https://www.google.com/calendar/exporticalzip')\nbr.select_form(nr=0)\nbr['Email']='Username@gmail.com'\nbr['Passwd']='...
[ 5, 0, 0 ]
[]
[]
[ "authentication", "calendar", "python" ]
stackoverflow_0002524011_authentication_calendar_python.txt
Q: How to sync up random generation of strings in Python How could I ensure that a randomizing algorithm would produce the same random number for two different programs. I am trying to make a chat program that utilizes a shared password, or key and then uses that key to generate a random string that is only predictable to both programs. For example Person A: asd4sa5d8s5s5d5sd Person B: asd4sa5d8s5s5d5sd Person A: 2SDASD5545S Person B: 2SDASD5545S A: If you want a predictable secure string based on a password why not just use a hash? You can encode the hash into a string using Base64 encoding. If you add a salt to the string before hashing it will make it much harder for people to use a brute force or rainbow table attack to go from the hash back to the password. >>> password = "asd4sa5d8s5s5d5sd" >>> import hashlib, base64 >>> salt = "mysecretstring" >>> m = hashlib.md5() >>> m.update(salt) >>> m.update(password) >>> base64.b64encode(m.digest()) 'NR6jEKdkVcfcT4pgBnF96A==' A: Use random.seed, giving the same value to the function in both clients. A: You should make a private instance of Random(). If you just use the random module the usual way, you will get unpredictable results if random numbers are consumed anywhere else in your program from md5 import md5 from random import Random hsh=md5("passphrase").hexdigest() seed = long(hsh,16) myrandom = Random() myrandom.seed(seed) print myrandom.randint(0,100)
How to sync up random generation of strings in Python
How could I ensure that a randomizing algorithm would produce the same random number for two different programs. I am trying to make a chat program that utilizes a shared password, or key and then uses that key to generate a random string that is only predictable to both programs. For example Person A: asd4sa5d8s5s5d5sd Person B: asd4sa5d8s5s5d5sd Person A: 2SDASD5545S Person B: 2SDASD5545S
[ "If you want a predictable secure string based on a password why not just use a hash? You can encode the hash into a string using Base64 encoding.\nIf you add a salt to the string before hashing it will make it much harder for people to use a brute force or rainbow table attack to go from the hash back to the pass...
[ 3, 2, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003393986_python_random.txt
Q: File Downloader with GUI progress display? I am trying to write a file downloader that has a GUI and displays the progress of the file being downloaded. I would like it to either display a text percentage, a progress bar or both. I am sure this can be done in Python, but I'm just not sure how. I am using Python 2.6 on MS Windows XP. A: The easiest progress bar dialog would probably be with EasyDialogs for Windows (follows the same api as the EasyDialogs module that is included with the mac version of python) For determining the progress of the download, use urllib.urlretrieve() with a "reporthook". Something like this: import sys from EasyDialogs import ProgressBar from urllib import urlretrieve def download(url, filename): bar = ProgressBar(title='Downloading...', label=url) def report(block_count, block_size, total_size): if block_count == 0: bar.set(0, total_size) bar.inc(block_size) urlretrieve(url, filename, reporthook=report) if __name__ == '__main__': url = sys.argv[1] filename = sys.argv[2] download(url, filename) There are of course other libraries available for richer GUI interfaces (but they are larger or more difficult if this is all you need). The same goes for the downloads: there are probably faster things than urllib, but this one is easy and included in the stdlib.
File Downloader with GUI progress display?
I am trying to write a file downloader that has a GUI and displays the progress of the file being downloaded. I would like it to either display a text percentage, a progress bar or both. I am sure this can be done in Python, but I'm just not sure how. I am using Python 2.6 on MS Windows XP.
[ "The easiest progress bar dialog would probably be with EasyDialogs for Windows (follows the same api as the EasyDialogs module that is included with the mac version of python)\nFor determining the progress of the download, use urllib.urlretrieve() with a \"reporthook\".\nSomething like this:\nimport sys\nfrom Easy...
[ 3 ]
[]
[]
[ "download", "progress_bar", "python", "user_interface", "windows" ]
stackoverflow_0003394345_download_progress_bar_python_user_interface_windows.txt
Q: sending colored text to a TextCtrl in wxpython I'm trying to send colored text to a TextCtrl widget, but don't know how style = wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|wx.TE_RICH2 self.status_area = wx.TextCtrl(self.panel, -1, pos=(10, 270),style=style, size=(380,150)) basically that snippet defines a status box in my window, and I want to write colored log messages to it. If I just do self.status_area.AppendText("blah") it will append text like I want, but it will always be black. I can't find the documentation on how to do this. A: You need to call SetStyle to change the text behavior. import wx class F(wx.Frame): def __init__(self, *args, **kw): wx.Frame.__init__(self, None) style = wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|wx.TE_RICH2 self.status_area = wx.TextCtrl(self, -1, pos=(10, 270),style=style, size=(380,150)) self.status_area.AppendText("blahblahhblah") fg = wx.Colour(200,80,100) at = wx.TextAttr(fg) self.status_area.SetStyle(3, 5, at) app = wx.PySimpleApp() f = F() f.Show() app.MainLoop() A: documentation of wxwidgets has this to say (you can also look up wxPython docs, but it points to wxwidgets anyway): either use SetDefaultStyle before you append text to your textctrl, or after inserting text use SetStyle. According to docs, the first solution is more efficient (and sounds easier to me.)
sending colored text to a TextCtrl in wxpython
I'm trying to send colored text to a TextCtrl widget, but don't know how style = wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|wx.TE_RICH2 self.status_area = wx.TextCtrl(self.panel, -1, pos=(10, 270),style=style, size=(380,150)) basically that snippet defines a status box in my window, and I want to write colored log messages to it. If I just do self.status_area.AppendText("blah") it will append text like I want, but it will always be black. I can't find the documentation on how to do this.
[ "You need to call SetStyle to change the text behavior.\nimport wx\n\nclass F(wx.Frame):\n def __init__(self, *args, **kw):\n wx.Frame.__init__(self, None)\n style = wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|wx.TE_RICH2\n self.status_area = wx.TextCtrl(self, -1,\n ...
[ 3, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003394850_python_wxpython.txt
Q: Can this Python code be written more efficiently? So I have this code in python that writes some values to a Dictionary where each key is a student ID number and each value is a Class (of type student) where each Class has some variables associated with it. ' Code try: if ((str(i) in row_num_id.iterkeys()) and (row_num_id[str(i)]==varschosen[1])): valuetowrite=str(row[i]) if students[str(variablekey)].var2 != []: students[str(variablekey)].var2.append(valuetowrite) else: students[str(variablekey)].var2=([valuetowrite]) except: two=1#This is just a dummy assignment because I #can't leave it empty... I don't need my program to do anything if the "try" doesn't work. I just want to prevent a crash. #Assign var3 try: if ((str(i) in row_num_id.iterkeys()) and (row_num_id[str(i)]==varschosen[2])): valuetowrite=str(row[i]) if students[str(variablekey)].var3 != []: students[str(variablekey)].var3.append(valuetowrite) else: students[str(variablekey)].var3=([valuetowrite]) except: two=1 #Assign var4 try: if ((str(i) in row_num_id.iterkeys()) and (row_num_id[str(i)]==varschosen[3])): valuetowrite=str(row[i]) if students[str(variablekey)].var4 != []: students[str(variablekey)].var4.append(valuetowrite) else: students[str(variablekey)].var4=([valuetowrite]) except: two=1 ' The same code repeats many, many times for each variable that the student has (var5, var6,....varX). However, the RAM spike in my program comes up as I execute the function that does this series of variable assignments. I wish to find out a way to make this more efficient in speed or more memory efficient because running this part of my program takes up around half a gig of memory. :( Thanks for your help! EDIT: Okay let me simplify my question: In my case, I have a dictionary of about 6000 instantiated classes, where each class has 1000 attributed variables all of type string or list of strings. I don't really care about the number of lines my code is or the speed at which it runs (Right now, my code is at almost 20,000 lines and is about a 1 MB .py file!). What I am concerned about is the amount of memory it is taking up because this is the culprit in throttling my CPU. The ultimate question is: does the number of code lines by which I build up this massive dictionary matter so much in terms of RAM usage? My original code functions fine, but the RAM usage is high. I'm not sure if that is "normal" with the amount of data I am collecting. Does writing the code in a condensed fashion (as shown by the people who helped me below) actually make a noticeable difference in the amount of RAM I am going to eat up? Sure there are X ways to build a dictionary, but does it even affect the RAM usage in this case? A: Edit: The suggested code-refactoring below won't reduce the memory consumption very much. 6000 classes each with 1000 attributes may very well consume half a gig of memory. You might be better off storing the data in a database and pulling out the data only as you need it via SQL queries. Or you might use shelve or marshal to dump some or all of the data to disk, where it can be read back in only when needed. A third option would be to use a numpy array of strings. The numpy array will hold the strings more compactly. (Python strings are objects with lots of methods which make them bulkier memory-wise. A numpy array of strings loses all those methods but requires relatively little memory overhead.) A fourth option might be to use PyTables. And lastly (but not leastly), there might be ways to re-design your algorithm to be less memory intensive. We'd have to know more about your program and the problem it's trying to solve to give more concrete advice. Original suggestion: for v in ('var2','var3','var4'): try: if row_num_id.get(str(i))==varschosen[1]: valuetowrite=str(row[i]) value=getattr(students[str(variablekey)],v) if value != []: value.append(valuetowrite) else: value=[valuetowrite] except PUT_AN_EXPLICT_EXCEPTION_HERE: pass PUT_AN_EXPLICT_EXCEPTION_HERE should be replaced with something like AttributeError or TypeError, or ValueError, or maybe something else. It's hard to guess what to put here because I don't know what kind of values the variables might have. If you run the code without the try...exception block, and your program crashes, take note of the traceback error message you receive. The last line will say something like TypeError: ... In that case, replace PUT_AN_EXPLICT_EXCEPTION_HERE with TypeError. If your code can fail in a number of ways, say, with TypeError or ValueError, then you can replace PUT_AN_EXPLICT_EXCEPTION_HERE with (TypeError,ValueError) to catch both kinds of error. Note: There is a little technical caveat that should be mentioned regarding row_num_id.get(str(i))==varschosen[1]. The expression row_num_id.get(str(i)) returns None if str(i) is not in row_num_id. But what if varschosen[1] is None and str(i) is not in row_num_id? Then the condition is True, when the longer original condition returned False. If that is a possibility, then the solution is to use a sentinal default value like row_num_id.get(str(i),object())==varschosen[1]. Now row_num_id.get(str(i),object()) returns object() when str(i) is not in row_num_id. Since object() is a new instance of object there is no way it could equal varschosen[1]. A: You've spelled this wrong two=1#This is just a dummy assignment because I #can't leave it empty... I don't need my program to do anything if the "try" doesn't work. I just want to prevent a crash. It's spelled pass You should read a tutorial on Python. Also, except: Is a bad policy. Your program will fail to crash when it's supposed to crash. Names like var2 and var3 are evil. They are intentionally misleading. Don't repeat str(variablekey) over and over again. I wish to find out a way to make this more efficient in speed or more memory efficient because running this part of my program takes up around half a gig of memory. :( This request is unanswerable because we don't know what it's supposed to do. Intentionally obscure names like var1 and var2 make it impossible to understand. A: "6000 instantiated classes, where each class has 1000 attributed variables" So. 6 million objects? That's a lot of memory. A real lot of memory. What I am concerned about is the amount of memory it is taking up because this is the culprit in throttling my CPU Really? Any evidence? but the RAM usage is high Compared with what? What's your basis for this claim? A: Python dicts use a surprisingly large amount of memory. Try: import sys for i in range( 30 ): d = dict( ( j, j ) for j in range( i ) ) print "dict with", i, "elements is", sys.getsizeof( d ), "bytes" for an illustration of just how expensive they are. Note that this is just the size of the dict itself: it doesn't include the size of the keys or values stored in the dict. By default, an instance of a Python class stores its attributes in a dict. Therefore, each of your 6000 instances is using a lot of memory just for that dict. One way that you could save a lot of memory, provided that your instances all have the same set of attributes, is to use __slots__ (see http://docs.python.org/reference/datamodel.html#slots). For example: class Foo( object ): __slots__ = ( 'a', 'b', 'c' ) Now, instances of class Foo have space allocated for precisely three attributes, a, b, and c, but no instance dict in which to store any other attributes. This uses only 4 bytes (on a 32-bit system) per attribute, as opposed to perhaps 15-20 bytes per attribute using a dict. Another way in which you could be wasting memory, given that you have a lot of strings, is if you're storing multiple identical copies of the same string. Using the intern function (see http://docs.python.org/library/functions.html#intern) could help if this turns out to be a problem.
Can this Python code be written more efficiently?
So I have this code in python that writes some values to a Dictionary where each key is a student ID number and each value is a Class (of type student) where each Class has some variables associated with it. ' Code try: if ((str(i) in row_num_id.iterkeys()) and (row_num_id[str(i)]==varschosen[1])): valuetowrite=str(row[i]) if students[str(variablekey)].var2 != []: students[str(variablekey)].var2.append(valuetowrite) else: students[str(variablekey)].var2=([valuetowrite]) except: two=1#This is just a dummy assignment because I #can't leave it empty... I don't need my program to do anything if the "try" doesn't work. I just want to prevent a crash. #Assign var3 try: if ((str(i) in row_num_id.iterkeys()) and (row_num_id[str(i)]==varschosen[2])): valuetowrite=str(row[i]) if students[str(variablekey)].var3 != []: students[str(variablekey)].var3.append(valuetowrite) else: students[str(variablekey)].var3=([valuetowrite]) except: two=1 #Assign var4 try: if ((str(i) in row_num_id.iterkeys()) and (row_num_id[str(i)]==varschosen[3])): valuetowrite=str(row[i]) if students[str(variablekey)].var4 != []: students[str(variablekey)].var4.append(valuetowrite) else: students[str(variablekey)].var4=([valuetowrite]) except: two=1 ' The same code repeats many, many times for each variable that the student has (var5, var6,....varX). However, the RAM spike in my program comes up as I execute the function that does this series of variable assignments. I wish to find out a way to make this more efficient in speed or more memory efficient because running this part of my program takes up around half a gig of memory. :( Thanks for your help! EDIT: Okay let me simplify my question: In my case, I have a dictionary of about 6000 instantiated classes, where each class has 1000 attributed variables all of type string or list of strings. I don't really care about the number of lines my code is or the speed at which it runs (Right now, my code is at almost 20,000 lines and is about a 1 MB .py file!). What I am concerned about is the amount of memory it is taking up because this is the culprit in throttling my CPU. The ultimate question is: does the number of code lines by which I build up this massive dictionary matter so much in terms of RAM usage? My original code functions fine, but the RAM usage is high. I'm not sure if that is "normal" with the amount of data I am collecting. Does writing the code in a condensed fashion (as shown by the people who helped me below) actually make a noticeable difference in the amount of RAM I am going to eat up? Sure there are X ways to build a dictionary, but does it even affect the RAM usage in this case?
[ "Edit: The suggested code-refactoring below won't reduce the memory consumption very much. 6000 classes each with 1000 attributes may very well consume half a gig of memory.\nYou might be better off storing the data in a database and pulling out the data only as you need it via SQL queries. Or you might use shelve ...
[ 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003391701_python.txt
Q: Python check first and last index of a list Assuming I have object_list list which contains objects. I want to check if my current iteration is is at the first or the last. for object in object_list: do_something if first_indexed_element: do_something_else if last_indexed_element: do_another_thing How can this be achieved? I know that I can use range and count index but if feels clumsy. Regards A: You can use enumerate(): for i, obj in enumerate(object_list): do_something if i == 0: do_something_else if i == len(object_list) - 1: do_another_thing But instead of checking in every iteration which object you are dealing with, maybe something like this is better: def do_with_list(object_list): for obj in object_list: do_something(obj) do_something_else(object_list[0]) do_another_thing(object_list[-1]) Imagine you have a list of 100 objects, then you make 198 unnecessary comparisons, because the current element cannot be the first or last element in the list. But it depends on whether the statements have to be executed in a certain order and what they are doing. Btw. don't shadow object, it is already an identifier in Python ;) A: li = iter(object_list) obj = next(li) do_first_thing_with(obj) while True: try: do_something_with(obj) obj = next(li) except StopIteration: do_final_thing_with(obj) break A: for index, obj in enumerate(object_list): do_something if index == 0: do_something_else if index == len(object_list)-1: do_another_thing A: first = True for o in object_list: do_something(o) if first: first = False do_something_with_first(o) if 'o' in locals(): do_something_with_last(o) A: You just have to use a counter, no need for range : Let's say your counter is cpt. if cpt == 0: print "first" if cpt == len(object_list) - 1: print "last" edit : the enumerate solution may be more elegant. A: You can make i = 0 and then i++ in iterations. So if i==0 it is first iteration, if i == list.size()-1 than it is last iteration. There must be smth like indexOf(object), which returns position of element in list. if 0 - than first iteration, if size()-1 than last. But it is expensive. use enumerate. See Amber or Felix posts. compare current element to list[0] and to list[-1]. in first case - first iteration, in last case - last iteration. It is expensive too. So i'd choose 1 or 3. PS: list.size() is len(list) of course.
Python check first and last index of a list
Assuming I have object_list list which contains objects. I want to check if my current iteration is is at the first or the last. for object in object_list: do_something if first_indexed_element: do_something_else if last_indexed_element: do_another_thing How can this be achieved? I know that I can use range and count index but if feels clumsy. Regards
[ "You can use enumerate():\nfor i, obj in enumerate(object_list):\n do_something\n if i == 0:\n do_something_else\n if i == len(object_list) - 1:\n do_another_thing\n\nBut instead of checking in every iteration which object you are dealing with, maybe something like this is better:\ndef do_wit...
[ 16, 13, 3, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003394687_list_python.txt
Q: using c# inside an apache python script I have a c# application that defines a membership provider used in a Asp.Net MVC application. And i have an apache httpd server that does authentication with mod_wsgi. The objective is to share the membership provider between the two, so that the authentication information be the same. How can i achieve this behaviour ? A: Trivially. Apache serves static content. Certain URI's will be routed to mod_wsgi to Python. Python will then execute (via subprocess) a C# program, providing command-line arguments, and reading the standard output response from the C# program. Python does whatever else is required to serve the web pages. This presumes your C# application runs at the command line, reads command-line parameters and writes its result to standard output. This is an easy thing to build. It may not be the way it works today, but any program that runs from the command line is trivial to integrate. Your C# application, BTW, can also be rewritten into Python. It isn't magic. It's just code. Read the code, understand the code, and translate the code. You'll be a lot happier replacing the C# with something simpler. A: Several ways: COM interface (if Windows OS), although this would be a bit slow (make a COM-compatible library, register it with regasm, use it). Using Gearman (not sure if faster than COM and whether it has Python and C# support, the investigation is up to you) http://gearman.org/ Using the method described by S.Lott Using SOAP (slow, big)
using c# inside an apache python script
I have a c# application that defines a membership provider used in a Asp.Net MVC application. And i have an apache httpd server that does authentication with mod_wsgi. The objective is to share the membership provider between the two, so that the authentication information be the same. How can i achieve this behaviour ?
[ "Trivially.\n\nApache serves static content.\nCertain URI's will be routed to mod_wsgi to Python.\nPython will then execute (via subprocess) a C# program, providing command-line arguments, and reading the standard output response from the C# program.\nPython does whatever else is required to serve the web pages.\n\...
[ 1, 0 ]
[]
[]
[ "apache", "c#", "mod_wsgi", "python" ]
stackoverflow_0003395409_apache_c#_mod_wsgi_python.txt
Q: In Django, searching and filter by searchbox and categories in one go? I wonder if you could help me. I have a list of data that will be displayed on one page. There is a simple search box, a list of categories and a list of tags that can all be used to filter the list of data. I'm trying to built it from the ground up (so it doesn't require JavaScript) but eventually it will submit the search criteria and return back a new list using Ajax. So I have a list of categories in my database ('large', 'small', etc), and I have a list of tags in my database ('wooden', 'brass'). Tags are used to filter down more of what's in the categories. I then have a search box. Ideally, I want the user to effectively tick which categories they want, tick what tags they want and possibly put a search for keywords, and then submit all of that data so it can be queried and a new list of the filtered data can be returned. I'm not a Django expert, and I'm stuck on how and where to do this... What is the Django way of spitting out the categories as a checkbox list, the tags as a checkbox list and the search box with a submit button... Which when submitted, I can take all that data and do the necessary queries on the database? I don't quite understand how I'd do this... I've been looking at the Django Docs and the Django Book for a few days and the way I'm doing things doesn't seem to be listed. Please, any help at all would be fantastic. A: spitting out the categories as a checkbox list, the tags as a checkbox list and the search box with a submit button... This is a <form> in your HTML page. It probably doesn't match anything in the Django model very well. It's a unique form built more-or-less manually. I can take all that data and do the necessary queries on the database? That's a view function. You'll probably have something like this. objects= SomeModel.objects if request.GET ... has categories ... objects = objects.filter( ... categories ... ) if request.GET ... has tags ... objects = objects.filter( ... tags ... ) if request.GET ... has search ... objects = objects.filter( something__contains( search ) ) return render_to_response( ... etc. ... ) the way I'm doing things doesn't seem to be listed. You're beyond the tutorial here. What to do? Do the ENTIRE tutorial. All the way through. Every step. It doesn't seem like it solves your problem, but you MUST do the ENTIRE tutorial. Design your model. You didn't mention the model in the question. It's the absolutely most important and fundamental thing. Create the default admin interface for that model. Get the default admin interface to work and do the kinds of things you'd like to do. It has great search, category and tag filtering. In order to get the default admin to work, you'll need to design fairly sophisticated model and form features. You'll probably have to add method functions to your model as well as choice items and other goodness. AFTER you have the admin page pretty close to what you want, you can write you own customized view. each single checkbox has a different name ('category_option_1', 'category_option_2', etc.) ... How do I read these? I can't just put request.POST['category_option_n']? Really? Why didn't your question say that? Are you asking about this? for k in range(1024): name = 'category_option_{0}'.format(k) # Use request.POST.get(name,None) to build a `Q` object
In Django, searching and filter by searchbox and categories in one go?
I wonder if you could help me. I have a list of data that will be displayed on one page. There is a simple search box, a list of categories and a list of tags that can all be used to filter the list of data. I'm trying to built it from the ground up (so it doesn't require JavaScript) but eventually it will submit the search criteria and return back a new list using Ajax. So I have a list of categories in my database ('large', 'small', etc), and I have a list of tags in my database ('wooden', 'brass'). Tags are used to filter down more of what's in the categories. I then have a search box. Ideally, I want the user to effectively tick which categories they want, tick what tags they want and possibly put a search for keywords, and then submit all of that data so it can be queried and a new list of the filtered data can be returned. I'm not a Django expert, and I'm stuck on how and where to do this... What is the Django way of spitting out the categories as a checkbox list, the tags as a checkbox list and the search box with a submit button... Which when submitted, I can take all that data and do the necessary queries on the database? I don't quite understand how I'd do this... I've been looking at the Django Docs and the Django Book for a few days and the way I'm doing things doesn't seem to be listed. Please, any help at all would be fantastic.
[ "\nspitting out the categories as a checkbox list,\nthe tags as a checkbox list and the\nsearch box with a submit button...\n\nThis is a <form> in your HTML page. It probably doesn't match anything in the Django model very well. It's a unique form built more-or-less manually.\n\nI can take all that data and do th...
[ 1 ]
[]
[]
[ "categories", "django", "filter", "python", "search" ]
stackoverflow_0003395467_categories_django_filter_python_search.txt
Q: Python: hexadecimal regular expression question I want to parse the output of a serial monitoring program called Docklight (I highly recommend it) It outputs 'hexadecimal' strings: or a sequence of (two capital hex digits followed by a space). the corresponding regular expression is: ([0-9A-F]{2} )+ for example: '05 03 DA 4B 3F ' When program detects particular sequences of characters it places comments in the 'hexadecimal ' string. for example: '05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer' comments are strings of the following format ' .+ ' (a sequence of characters preceded by a space and followed by a space) I want to get rid of the comments. for example, the 'hexadecimal' string above filtered would be: '05 03 04 01 0A 03 08 0B BD AF 0D 0A ' how do i go about doing this with A regular expression? A: You could try re.findall(): >>> a='05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer' >>> re.findall(r"\b[0-9A-F]{2}\b", a) ['05', '03', '04', '01', '0A', '03', '08', '0B', 'BD', 'AF', '0D', '0A'] The \b in the regular expression matches a "word boundary". Of course, your input is ambiguous if the serial monitor inserts something like THIS BE THE HEADER. A: It might be easier to find all the hexadecimal numbers, assuming the inserted strings won't contain a match: >>> data = '05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer' >>> import re >>> pattern = re.compile("[0-9A-F]{2} ") >>> "".join(pattern.findall(data)) '05 03 04 01 0A 03 08 0B BD AF AD 0D 0A ' Otherwise you could use the fact that the inserted strings are preceed by two spaces: >>> data = '05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer' >>> re.sub("( .*?)(?=( [0-9A-F]{2} |$))","",data) '05 03 04 01 0A 03 08 0B BD AF 0D 0A' This uses a look ahead to work out when the inserted string ends. It looks for either a hexadecimal string surround by spaces or the end of the source string. A: Using your regex hexa = '([0-9A-F]{2} )+' " ".join(re.findall(hexa, line)) A: While you already received two answers that find you all hexadecimal numbers, here's the same with a direct regular expression that finds you all text that does not look like a hexadecimal number (assuming that's two letter/digits in uppercase / lowercase 0-9 and A-F range, followed by a space). Something like this (sorry, I'm not a pythoneer, but you get the idea): newstring = re.sub(r"[^ ]+(?<![0-9A-Fa-f ]{2}|^.)", "", yourstring) It works by "looking back". It finds every consecutive non-space substring, then negatively looks back with (?<!....). It says: "if the previous two characters were not a hex number, then succeed". The little ^. at the end prevents to incorrectly match the first character of the string. Edit As suggested by Alan Moore, here's the same idea with a positive lookahead expression: newstring = re.sub(r"(?>\b[0-9A-Fa-f ]{2}\b)", "", yourstring) A: Why regexp? More pythonic for me is (fixed for hexdigit not regular digit): command='05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer' print ' '.join(com for com in command.split() if len(com)==2 and all(c.upper() in '0123456789ABCDEF' for c in com)) A: How about a solution that actually uses regex negation? ;) result = re.sub(r"[ ]+(?:(?!\b[0-9A-F]{2}\b).)+", "", subject)
Python: hexadecimal regular expression question
I want to parse the output of a serial monitoring program called Docklight (I highly recommend it) It outputs 'hexadecimal' strings: or a sequence of (two capital hex digits followed by a space). the corresponding regular expression is: ([0-9A-F]{2} )+ for example: '05 03 DA 4B 3F ' When program detects particular sequences of characters it places comments in the 'hexadecimal ' string. for example: '05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer' comments are strings of the following format ' .+ ' (a sequence of characters preceded by a space and followed by a space) I want to get rid of the comments. for example, the 'hexadecimal' string above filtered would be: '05 03 04 01 0A 03 08 0B BD AF 0D 0A ' how do i go about doing this with A regular expression?
[ "You could try re.findall():\n>>> a='05 03 04 01 0A The Header 03 08 0B BD AF The PAYLOAD 0D 0A The Footer'\n>>> re.findall(r\"\\b[0-9A-F]{2}\\b\", a)\n['05', '03', '04', '01', '0A', '03', '08', '0B', 'BD', 'AF', '0D', '0A']\n\nThe \\b in the regular expression matches a \"word boundary\".\nOf course, your input...
[ 4, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex", "regex_negation" ]
stackoverflow_0003395656_python_regex_regex_negation.txt
Q: Way to query database with SQLAlchemy where a date is a particular day of the week? I have a table (called 'entry') which has a datetime column (called 'access_date'), and I want to do an SQLAlchemy query that only produces results where entry.access_date is a Monday (or any other day of the week specified by a number [0..6]). Is this possible? I am using sqlite & SQLalchemy 0.5.8 if that makes any difference. A: Further from Daniel Kluev's answer, I found another way of saying the same thing (possibly nicer looking?) query.filter(func.strftime('%w', Entry.access_date) == str(weekday)).all() Where weekday is a number [0..6] A: There is no generic DAYOFWEEK() function supported by SQLAlchemy, so you will have to use dialect-specific sql in the where clause. For MySQL, you would go with custom func 'weekday' or 'dayofweek', but since sqlite has neither datetime type nor weekday()/dayofweek(), you need some raw sql there. http://www.mail-archive.com/sqlite-users@sqlite.org/msg51116.html here are examples for this query. In SQLA, this will look like query.filter("strftime('%w', access_date) = :dow").params(dow=0).all() A: I'm not an expert on SQLAlchemy, so await others' views. I've adapted an example from http://www.sqlalchemy.org/docs/ormtutorial.html#common-filter-operators. This may be worth testing & experimenting with while you wait for others' answers.: query.filter(entry.access_date.in_([0,1,2,3,4,5,6]))
Way to query database with SQLAlchemy where a date is a particular day of the week?
I have a table (called 'entry') which has a datetime column (called 'access_date'), and I want to do an SQLAlchemy query that only produces results where entry.access_date is a Monday (or any other day of the week specified by a number [0..6]). Is this possible? I am using sqlite & SQLalchemy 0.5.8 if that makes any difference.
[ "Further from Daniel Kluev's answer, I found another way of saying the same thing (possibly nicer looking?)\nquery.filter(func.strftime('%w', Entry.access_date) == str(weekday)).all()\n\nWhere weekday is a number [0..6]\n", "There is no generic DAYOFWEEK() function supported by SQLAlchemy, so you will have to use...
[ 3, 2, 0 ]
[]
[]
[ "datetime", "python", "sqlalchemy" ]
stackoverflow_0003371292_datetime_python_sqlalchemy.txt
Q: interesting project that I can implement with fuse-python I was thinking of improving my python and just recently read an article about the python-fuse library. I'm always interested about filesystem stuff so I thought this would be a good library to hack on. What I can't come up with is an idea of what I should implement with this. Do you guys have any suggestions or ideas that you can share? A: The typical 'cool' things with FUSE are exposing in a filesystem interface things that aren't files, and usually are stored somewhere else. Existing examples: Gmail filesystem, SSH filesystem. Non existing (that I know of) examples: a Twitter filesystem, that shows tweets as files. Or a Stack Overflow filesystem, questions and answers as files. A: What about a versioned file-system? It has always seemed like a cool idea since I read about the implementation in Plan 9. You wouldn't have to write the versioning part as you could use an off-the-shelf version control like git. The contents of the repository could be exposed as a file hierarchy, older versions could be read-only directories and write access to files in the repository could trigger a commit. The original versions of sshfs used a FUSE frontend that fired shell commands out the back to move around in the target file-system. You could implement something similar quite easily to output git commands and act on the repository. A: Mounting an xml file as a filesystem, where elements are directories, and their contents is stored as a plain file. The attributes are stored in an "attributes" file as newline separated name: value pairs in each directory. This would allow XML to be modified using the common shell tools. (sed, grep, mkdir, rm, rmdir, cat, vim, etc...) An elegant solution would have to be found for multiple elements with the same name. So it's a bit far field. You never said that it had to be a good idea. A: I do not know if python is appropriate, but maybe you can provide URL handlers for fuse in Firefox. for example: sshfs://host/path would allow to explore remote ssh host via Firefox browser. A: Maybe a filesystem where files behave like directories, so you can store files in files. Or a filesystem where you can store files with the same name in 1 directory.
interesting project that I can implement with fuse-python
I was thinking of improving my python and just recently read an article about the python-fuse library. I'm always interested about filesystem stuff so I thought this would be a good library to hack on. What I can't come up with is an idea of what I should implement with this. Do you guys have any suggestions or ideas that you can share?
[ "The typical 'cool' things with FUSE are exposing in a filesystem interface things that aren't files, and usually are stored somewhere else.\nExisting examples: Gmail filesystem, SSH filesystem.\nNon existing (that I know of) examples: a Twitter filesystem, that shows tweets as files. Or a Stack Overflow filesystem...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "fuse", "project", "python" ]
stackoverflow_0003278567_fuse_project_python.txt
Q: process_file(sys.argv[1]) IndexError: list index out of range This is the code I am working with that comes from Practical Programming: import sys def process_file(filename): '''Open, read, and print a file.''' input_file = open(filename, "r") for line in input_file: line = line.strip() print line input_file.close() if __name__ == "__main__": process_file(sys.argv[1]) After import this module in IDLE and pass a text file argument through process_file(), I receive this error: Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> process_file("data.txt") File "C:\Python26\read_file_2.py", line 14, in process_file process_file(sys.argv[1]) IndexError: list index out of range How can I get this program to work without receiving this error? Any help is appreciated. A: you should move if __name__ == "__main__": process_file(sys.argv[1]) out of the process_file function. When importing into IDLE make sure process_file is available and pass file name to it. A: It looks like you've got the if __name__ == "__main__": process_file(sys.argv[1]) block at the same indentation level as the rest of the process_file definition, so it's being run when you call process_file from another module. I suspect that might be causing your problem - unindent it so the if is in line with the def.
process_file(sys.argv[1]) IndexError: list index out of range
This is the code I am working with that comes from Practical Programming: import sys def process_file(filename): '''Open, read, and print a file.''' input_file = open(filename, "r") for line in input_file: line = line.strip() print line input_file.close() if __name__ == "__main__": process_file(sys.argv[1]) After import this module in IDLE and pass a text file argument through process_file(), I receive this error: Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> process_file("data.txt") File "C:\Python26\read_file_2.py", line 14, in process_file process_file(sys.argv[1]) IndexError: list index out of range How can I get this program to work without receiving this error? Any help is appreciated.
[ "you should move \nif __name__ == \"__main__\":\n process_file(sys.argv[1])\n\nout of the process_file function. When importing into IDLE make sure process_file is available and pass file name to it.\n", "It looks like you've got the\nif __name__ == \"__main__\":\n process_file(sys.argv[1])\n\nblock at the sa...
[ 0, 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0003396895_python_python_idle.txt
Q: Django object extension / one to one relationship issues Howdy. I'm working on migrating an internal system to Django and have run into a few wrinkles. Intro Our current system (a billing system) tracks double-entry bookkeeping while allowing users to enter data as invoices, expenses, etc. Base Objects So I have two base objects/models: JournalEntry JournalEntryItems defined as follows: class JournalEntry(models.Model): gjID = models.AutoField(primary_key=True) date = models.DateTimeField('entry date'); memo = models.CharField(max_length=100); class JournalEntryItem(models.Model): journalEntryID = models.AutoField(primary_key=True) gjID = models.ForeignKey(JournalEntry, db_column='gjID') amount = models.DecimalField(max_digits=10,decimal_places=2) So far, so good. It works quite smoothly on the admin side (inlines work, etc.) On to the next section. We then have two more models InvoiceEntry InvoiceEntryItem An InvoiceEntry is a superset of / it inherits from JournalEntry, so I've been using a OneToOneField (which is what we're using in the background on our current site). That works quite smoothly too. class InvoiceEntry(JournalEntry): invoiceID = models.AutoField(primary_key=True, db_column='invoiceID', verbose_name='') journalEntry = models.OneToOneField(JournalEntry, parent_link=True, db_column='gjID') client = models.ForeignKey(Client, db_column='clientID') datePaid = models.DateTimeField(null=True, db_column='datePaid', blank=True, verbose_name='date paid') Where I run into problems is when trying to add an InvoiceEntryItem (which inherits from JournalEntryItem) to an inline related to InvoiceEntry. I'm getting the error: <class 'billing.models.InvoiceEntryItem'> has more than 1 ForeignKey to <class 'billing.models.InvoiceEntry'> The way I see it, InvoiceEntryItem has a ForeignKey directly to InvoiceEntry. And it also has an indirect ForeignKey to InvoiceEntry through the JournalEntry 1->M JournalEntryItems relationship. Here's the code I'm using at the moment. class InvoiceEntryItem(JournalEntryItem): invoiceEntryID = models.AutoField(primary_key=True, db_column='invoiceEntryID', verbose_name='') invoiceEntry = models.ForeignKey(InvoiceEntry, related_name='invoiceEntries', db_column='invoiceID') journalEntryItem = models.OneToOneField(JournalEntryItem, db_column='journalEntryID') I've tried removing the journalEntryItem OneToOneField. Doing that then removes my ability to retrieve the dollar amount for this particular InvoiceEntryItem (which is only stored in journalEntryItem). I've also tried removing the invoiceEntry ForeignKey relationship. Doing that removes the relationship that allows me to see the InvoiceEntry 1->M InvoiceEntryItems in the admin inline. All I see are blank fields (instead of the actual data that is currently stored in the DB). It seems like option 2 is closer to what I want to do. But my inexperience with Django seems to be limiting me. I might be able to filter the larger pool of journal entries to see just invoice entries. But it would be really handy to think of these solely as invoices (instead of a subset of journal entries). Any thoughts on how to do what I'm after? A: First, inheriting from a model creates an automatic OneToOneField in the inherited model towards the parents so you don't need to add them. Remove them if you really want to use this form of model inheritance. If you only want to share the member of the model, you can use Meta inheritance which will create the inherited columns in the table of your inherited model. This way would separate your JournalEntry in 2 tables though but it would be easy to retrieve only the invoices. A: All fields in the superclass also exist on the subclass, so having an explicit relation is unnecessary. Model inheritance in Django is terrible. Don't use it. Python doesn't need it anyway.
Django object extension / one to one relationship issues
Howdy. I'm working on migrating an internal system to Django and have run into a few wrinkles. Intro Our current system (a billing system) tracks double-entry bookkeeping while allowing users to enter data as invoices, expenses, etc. Base Objects So I have two base objects/models: JournalEntry JournalEntryItems defined as follows: class JournalEntry(models.Model): gjID = models.AutoField(primary_key=True) date = models.DateTimeField('entry date'); memo = models.CharField(max_length=100); class JournalEntryItem(models.Model): journalEntryID = models.AutoField(primary_key=True) gjID = models.ForeignKey(JournalEntry, db_column='gjID') amount = models.DecimalField(max_digits=10,decimal_places=2) So far, so good. It works quite smoothly on the admin side (inlines work, etc.) On to the next section. We then have two more models InvoiceEntry InvoiceEntryItem An InvoiceEntry is a superset of / it inherits from JournalEntry, so I've been using a OneToOneField (which is what we're using in the background on our current site). That works quite smoothly too. class InvoiceEntry(JournalEntry): invoiceID = models.AutoField(primary_key=True, db_column='invoiceID', verbose_name='') journalEntry = models.OneToOneField(JournalEntry, parent_link=True, db_column='gjID') client = models.ForeignKey(Client, db_column='clientID') datePaid = models.DateTimeField(null=True, db_column='datePaid', blank=True, verbose_name='date paid') Where I run into problems is when trying to add an InvoiceEntryItem (which inherits from JournalEntryItem) to an inline related to InvoiceEntry. I'm getting the error: <class 'billing.models.InvoiceEntryItem'> has more than 1 ForeignKey to <class 'billing.models.InvoiceEntry'> The way I see it, InvoiceEntryItem has a ForeignKey directly to InvoiceEntry. And it also has an indirect ForeignKey to InvoiceEntry through the JournalEntry 1->M JournalEntryItems relationship. Here's the code I'm using at the moment. class InvoiceEntryItem(JournalEntryItem): invoiceEntryID = models.AutoField(primary_key=True, db_column='invoiceEntryID', verbose_name='') invoiceEntry = models.ForeignKey(InvoiceEntry, related_name='invoiceEntries', db_column='invoiceID') journalEntryItem = models.OneToOneField(JournalEntryItem, db_column='journalEntryID') I've tried removing the journalEntryItem OneToOneField. Doing that then removes my ability to retrieve the dollar amount for this particular InvoiceEntryItem (which is only stored in journalEntryItem). I've also tried removing the invoiceEntry ForeignKey relationship. Doing that removes the relationship that allows me to see the InvoiceEntry 1->M InvoiceEntryItems in the admin inline. All I see are blank fields (instead of the actual data that is currently stored in the DB). It seems like option 2 is closer to what I want to do. But my inexperience with Django seems to be limiting me. I might be able to filter the larger pool of journal entries to see just invoice entries. But it would be really handy to think of these solely as invoices (instead of a subset of journal entries). Any thoughts on how to do what I'm after?
[ "First, inheriting from a model creates an automatic OneToOneField in the inherited model towards the parents so you don't need to add them. Remove them if you really want to use this form of model inheritance. \nIf you only want to share the member of the model, you can use Meta inheritance which will create the i...
[ 1, 0 ]
[]
[]
[ "admin", "django", "inheritance", "inline", "python" ]
stackoverflow_0003376479_admin_django_inheritance_inline_python.txt
Q: wxPython wx.Close create runtime error When I try to call self.Close(True) in the top level Frame's EVT_CLOSE event handler, it raises a RuntimeError: maximum recursion depth exceeded. Here's the code: from PicEvolve import PicEvolve import wx class PicEvolveFrame(wx.Frame): def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self,parent,id,title,pos,size,style,name) self.panel = wx.ScrolledWindow(self) self.panel.SetScrollbars(1,1,600,400) statusBar = self.CreateStatusBar() menuBar = wx.MenuBar() menu1 = wx.Menu() m = menu1.Append(wx.NewId(), "&Initialize", "Initialize population with random images") menuBar.Append(menu1,"&Tools") self.Bind(wx.EVT_MENU,self.OnInit,m) self.Bind(wx.EVT_CLOSE,self.OnClose) self.SetMenuBar(menuBar) def OnInit(self, event): dlg = wx.TextEntryDialog(None,"Enter Population Size:","Population Size") popSize = 0 if dlg.ShowModal() == wx.ID_OK: popSize = int(dlg.GetValue()) self.pEvolver = PicEvolve(popSize,(200,200),True) box = wx.BoxSizer(wx.VERTICAL) filenames = [] for i in range(popSize): filenames.append("img"+str(i)+".png") for fn in filenames: img = wx.Image(fn,wx.BITMAP_TYPE_ANY) box.Add(wx.StaticBitmap(self.panel,wx.ID_ANY,wx.BitmapFromImage(img)), 0,wx.BOTTOM) self.panel.SetSizer(box) def OnClose(self,event): self.Close(True) class PicEvolveApp(wx.App): def OnInit(self): self.frame = PicEvolveFrame(parent=None,title="PicEvolve") self.frame.Show() self.SetTopWindow(self.frame) return True if __name__ == "__main__": app = PicEvolveApp() app.MainLoop() A: When you call window.Close it triggers EVT_CLOSE. Quoted from http://www.wxpython.org/docs/api/wx.CloseEvent-class.html The handler function for EVT_CLOSE is called when the user has tried to close a a frame or dialog box using the window manager controls or the system menu. It can also be invoked by the application itself programmatically, for example by calling the wx.Window.Close function. so obviously you will go into a infinite recursive loop. Instead in handler of EVT_CLOSE either destroy the window def OnClose(self,event): self.Destroy() or Skip the event def OnClose(self,event): event.Skip(True) or do not catch the EVT_CLOSE. Edit: Btw why you want to catch the event, in other question you have put some comment, you should update the question accordingly, so that people can give better answers. e.g when your program is still waiting on command prompt after close, it may mean you have some top level window still not closed. To debug which one is still open, try this for w in wx.GetTopLevelWindows(): print w A: def OnClose(self,event): event.Skip() see http://wiki.wxpython.org/EventPropagation A: You don't need to catch EVT_CLOSE unless you want to do something special, like prompt the user to save. If you do that sort of thing, then call self.Destroy() instead. Right now you call OnClose when you hit the upper right "x", which then calls "Close", which fires the OnClose event....that's why you get the recursion error. If you don't catch EVT_CLOSE and use self.Close() it should work. When it doesn't, then that usually means you have a timer, thread or hidden top-level window somewhere that also needs to be stopped or closed. I hope that made sense.
wxPython wx.Close create runtime error
When I try to call self.Close(True) in the top level Frame's EVT_CLOSE event handler, it raises a RuntimeError: maximum recursion depth exceeded. Here's the code: from PicEvolve import PicEvolve import wx class PicEvolveFrame(wx.Frame): def __init__(self, parent, id=-1,title="",pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="frame"): wx.Frame.__init__(self,parent,id,title,pos,size,style,name) self.panel = wx.ScrolledWindow(self) self.panel.SetScrollbars(1,1,600,400) statusBar = self.CreateStatusBar() menuBar = wx.MenuBar() menu1 = wx.Menu() m = menu1.Append(wx.NewId(), "&Initialize", "Initialize population with random images") menuBar.Append(menu1,"&Tools") self.Bind(wx.EVT_MENU,self.OnInit,m) self.Bind(wx.EVT_CLOSE,self.OnClose) self.SetMenuBar(menuBar) def OnInit(self, event): dlg = wx.TextEntryDialog(None,"Enter Population Size:","Population Size") popSize = 0 if dlg.ShowModal() == wx.ID_OK: popSize = int(dlg.GetValue()) self.pEvolver = PicEvolve(popSize,(200,200),True) box = wx.BoxSizer(wx.VERTICAL) filenames = [] for i in range(popSize): filenames.append("img"+str(i)+".png") for fn in filenames: img = wx.Image(fn,wx.BITMAP_TYPE_ANY) box.Add(wx.StaticBitmap(self.panel,wx.ID_ANY,wx.BitmapFromImage(img)), 0,wx.BOTTOM) self.panel.SetSizer(box) def OnClose(self,event): self.Close(True) class PicEvolveApp(wx.App): def OnInit(self): self.frame = PicEvolveFrame(parent=None,title="PicEvolve") self.frame.Show() self.SetTopWindow(self.frame) return True if __name__ == "__main__": app = PicEvolveApp() app.MainLoop()
[ "When you call window.Close it triggers EVT_CLOSE.\nQuoted from http://www.wxpython.org/docs/api/wx.CloseEvent-class.html\n\nThe handler function for EVT_CLOSE is\n called when the user has tried to\n close a a frame or dialog box using\n the window manager controls or the\n system menu. It can also be invoked ...
[ 1, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003391223_python_wxpython.txt
Q: How can I combine the awesomness of SQLAlchemy and EAV DB schemas? I've been doing some work with Pylons recently and quite like the SQLAlchemy model for database interaction. There's one section of my website though which I think could benefit from an EAV schema. Using this as my table example: id | userid | type | value ---+--------+--------|------------ 1 | 1 | phone | 111 111 111 ---+--------+--------|------------ 2 | 1 | age | 40 I can manually run queries like the following to extract and update data: SELECT value FROM table WHERE userid=1 AND type='phone' UPDATE table SET value=41 WHERE userid=1 AND type='age' That's easy and works... But manually constructing queries is not my preferred approach. I want to use SQLAlchemy to create my table model and let it do all the leg work. If I were to use a standard schema where each type had it's own column, I could do the following: class People(Base): __tablename__ = 'people' id = Column(Integer, primary_key=True) userid = Column(Integer, ForeignKey('users.id')) phone = Column(Unicode(40)) age = Column(Integer) Then I could pull out the data using: data = Session.query(People).filter_by(id=1).first() print data.age I want to be able to do the same for my EAV schema. So basically, I need a way to extend SQLAlchemy and tell it that when I call data.age that in fact means, I want SELECT value FROM table WHERE id=1 AND type='age'. Is this doable? Or will I be forced to clutter my code with manually issued queries? A: Have a look at the examples for vertical attribute mapping. I think this is more or less what you're after. The examples present a dict-like interface rather than attributes as in your example (probably better for arbitrary metadata keys, rather than a few specific attributes). If you'd rather map each attribute separately: stuff in the docs that might be of interest: sql expressions as mapped attributes: how you can indeed map an attribute to an arbitrary sql expression (read-only) changing attribute behaviour, esp. using descriptors and custom comparators: this boils down to just using normal python properties for your attributes, and doing whatever you need on get/set + optionally prescribing how comparison with other values (for queries) needs to work. associationproxy: basically provides a simpler view on a relation. For example, in your case, you could make _age a relation to your KeyValue (or whatever you want to call it), using a custom join condition (not only userid but also specifying the type "age"), and using uselist=False (because there is only one age per user, you want a single value, not a list). You could then use age = association_proxy('_age', 'value') to make it "show" only the value, rather than an entire KeyValue object. I suppose I'd go with either something based on the vertical attribute mapping example, or with associationproxy/
How can I combine the awesomness of SQLAlchemy and EAV DB schemas?
I've been doing some work with Pylons recently and quite like the SQLAlchemy model for database interaction. There's one section of my website though which I think could benefit from an EAV schema. Using this as my table example: id | userid | type | value ---+--------+--------|------------ 1 | 1 | phone | 111 111 111 ---+--------+--------|------------ 2 | 1 | age | 40 I can manually run queries like the following to extract and update data: SELECT value FROM table WHERE userid=1 AND type='phone' UPDATE table SET value=41 WHERE userid=1 AND type='age' That's easy and works... But manually constructing queries is not my preferred approach. I want to use SQLAlchemy to create my table model and let it do all the leg work. If I were to use a standard schema where each type had it's own column, I could do the following: class People(Base): __tablename__ = 'people' id = Column(Integer, primary_key=True) userid = Column(Integer, ForeignKey('users.id')) phone = Column(Unicode(40)) age = Column(Integer) Then I could pull out the data using: data = Session.query(People).filter_by(id=1).first() print data.age I want to be able to do the same for my EAV schema. So basically, I need a way to extend SQLAlchemy and tell it that when I call data.age that in fact means, I want SELECT value FROM table WHERE id=1 AND type='age'. Is this doable? Or will I be forced to clutter my code with manually issued queries?
[ "Have a look at the examples for vertical attribute mapping. I think this is more or less what you're after. The examples present a dict-like interface rather than attributes as in your example (probably better for arbitrary metadata keys, rather than a few specific attributes).\nIf you'd rather map each attribute ...
[ 6 ]
[]
[]
[ "entity_attribute_value", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003395355_entity_attribute_value_pylons_python_sqlalchemy.txt
Q: Basic Python question: referencing original variable inside for loop? Quick, newbie Python scoping question. How can I make sure that the original variables get changed in the for-loop below? for name in [name_level_1, name_level_2, name_level_3, name_level_4]: name = util.translate("iw", "en", name.encode('utf-8')) print name_level_1 In other words, I want the print statement to print out the changed variable, not the original. Python doesn't have pointers, right? Thanks! A: I don't think you can do what you want to do. To do something similar you can use indexing into the array: names = [name_level_1, name_level_2, name_level_3, name_level_4] for i in range(len(names)): names[i] = util.translate("iw", "en", names[i].encode('utf-8')) print names[0] But normally for this sort of thing you would just use a list comprehension: names = [name_level_1, name_level_2, name_level_3, name_level_4] names = [util.translate("iw", "en", name.encode('utf-8')) for name in names] A: make name_level_1 an object: class LevelOne(object): def __init__(self): self.x = 3 name_level_1 = LevelOne() count = 0 for name in [name_level_1, LevelOne(), LevelOne()]: name.x = count print name_level_1.x A: Python has references and objects instead of pointers (from a conceptual level). What you want to do is assign the new value of name_level_1 to some name that exists after the loop. So, either unwrap the loop and use each name where you need it, e.g. name_level_1_translated = util.translate("iw", "en", name_level_1.encode('utf-8')) print name_level_1_translated name_level_2_translated = util.translate("iw", "en", name_level_2.encode('utf-8')) do_stuff(name_level_2_translated) or, if you're going to use each name the same way, just create a list and use that everywhere. names = [name_level_1, name_level_2, name_level_3, name_level_4] translated_names = [util.translate("iw", "en", name.encode('utf-8')) for name in names] for name in translated_names: print name You can also access them by index: print names[0] A: You can manipulate the names in the global namespace using globals(): for name,value in globals().items(): if name.startswith("name_level_"): globals()[name] = util.translate("iw", "en", value.encode('utf-8')) However, storing the names in an array or dict is probably a better idea. A: Avoid polluting your namespace with lots of related variables, group them together in a dictionary or a list. e.g. NAMES = { 'level_1': 'something', 'level_2': 'something else', 'level_3': 'whatever', 'level_4': 'and so on' } for name in NAMES: NAMES[name] = util.translate("iw", "en", NAMES[name].encode('utf-8')) print NAMES['level_1']
Basic Python question: referencing original variable inside for loop?
Quick, newbie Python scoping question. How can I make sure that the original variables get changed in the for-loop below? for name in [name_level_1, name_level_2, name_level_3, name_level_4]: name = util.translate("iw", "en", name.encode('utf-8')) print name_level_1 In other words, I want the print statement to print out the changed variable, not the original. Python doesn't have pointers, right? Thanks!
[ "I don't think you can do what you want to do.\nTo do something similar you can use indexing into the array:\nnames = [name_level_1, name_level_2, name_level_3, name_level_4]\nfor i in range(len(names)):\n names[i] = util.translate(\"iw\", \"en\", names[i].encode('utf-8'))\nprint names[0]\n\nBut normally for th...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003397530_python.txt
Q: How to get started with a bare-bones Eclipse + PyDev I am planning to move from SPE to Eclipse + PyDev for better code completion. I think SPE's code completion is rather weird. Anyway, how should I get started with Eclipse + PyDev? I browsed http://www.eclipse.org and I found that Eclipse is made up of some base/core system and plugins are added for more functionality. I also stumbled upon http://www.easyeclipse.org which offers a ready-to-use Eclipse + PyDev distribution. I have two options: the easy way and the hard way. EASY WAY Just download from http://www.easyeclipse.org. Problem is, I can't decide which version to use, v1.2.2.2 or v1.3.1? HARD WAY I want to keep a lean Eclipse installation, so I want to start out with a bare-bones download, then add plug-ins as I advance in skill. As of the moment, all I want in an IDE is the following: Proper code completion, and An easy shortcut key to run the current program. It should be something like F5 or F9. Eventually, I will want to use more advanced tools, but I want to add plug-ins when I need or want to learn them: Debugging Unit testing Version control What plug-ins should I install to get the specific features I just mentioned? A: The leanest Eclipse installation is the Platform Runtime Binary at around 50MB (look for it in the middle of the page). Install it and then once in eclipse go to Help->Install New Software... and use http://pydev.org/updates as link to install PyDev and you are done. Not very hard at all. A: I've never really used the PyDev with Eclipse, but Eclipse comes with shortcut keys - you can change them to whatever suits you. If you install the standard version of Eclipse (which isn't exactly "lean", you know) with PyDev, you should have debugging built in. You can get Eclipse plugins for virtually any VCS you like, whether that's git or bazaar, subversion or CVS. Just check out the list. edit: and it doesn't look like there's any reason not to use the newest stable version of Easyclipse, if that's what you decide. A: I have used EasyEclipse for a while, but though less errors and incompatibilities occurred than in the standard version at that time, I didn't like that some modules were either too old or not supported at all. Meanwhile the standard distribution is stable enough. Debugging and unit testing are integrated in PyDev. You must configure the Python interpreter in the preferences, "Auto config" should do, then choose "Run as..." "Python unit-test" on a Python module, and for debugging see the "Run" menu. Version control depends on what you use, I think CVS is already integrated, but I use Subversion, and for that you need to install the Subversive plugin (meanwhile available from the Eclipse repositories, but you must still install it).
How to get started with a bare-bones Eclipse + PyDev
I am planning to move from SPE to Eclipse + PyDev for better code completion. I think SPE's code completion is rather weird. Anyway, how should I get started with Eclipse + PyDev? I browsed http://www.eclipse.org and I found that Eclipse is made up of some base/core system and plugins are added for more functionality. I also stumbled upon http://www.easyeclipse.org which offers a ready-to-use Eclipse + PyDev distribution. I have two options: the easy way and the hard way. EASY WAY Just download from http://www.easyeclipse.org. Problem is, I can't decide which version to use, v1.2.2.2 or v1.3.1? HARD WAY I want to keep a lean Eclipse installation, so I want to start out with a bare-bones download, then add plug-ins as I advance in skill. As of the moment, all I want in an IDE is the following: Proper code completion, and An easy shortcut key to run the current program. It should be something like F5 or F9. Eventually, I will want to use more advanced tools, but I want to add plug-ins when I need or want to learn them: Debugging Unit testing Version control What plug-ins should I install to get the specific features I just mentioned?
[ "The leanest Eclipse installation is the Platform Runtime Binary at around 50MB (look for it in the middle of the page). Install it and then once in eclipse go to Help->Install New Software... and use http://pydev.org/updates as link to install PyDev and you are done. Not very hard at all. \n", "I've never really...
[ 8, 0, 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0003397343_eclipse_pydev_python.txt
Q: python: list index of out of range for row in c: c1.append(row[0:13]) for row in c1: row.append(float(row[13])/100) row.append(float(row[12])/float(row[13])/100) row.append(math.log10(float(row[12]))) c contains a csv file with many rows and columns c1 is a subset of c containing only the first 14 elements i am getting IndexError: list index out of range on row.append(float(row[13])/100) does anyone know what i am doing wrong? A: The rows in c1 don't actually contain 14 elements, they contain 13. The second index in a slice is non-inclusive. When you append row[0:13] to c1 you are appending from element 0 to the element before 13. Hence, there are only 13 elements. This is why you get IndexError: list index out of range on row.append(float(row[13])/100). row[13] is an attempt to access a non-existent 14th element.
python: list index of out of range
for row in c: c1.append(row[0:13]) for row in c1: row.append(float(row[13])/100) row.append(float(row[12])/float(row[13])/100) row.append(math.log10(float(row[12]))) c contains a csv file with many rows and columns c1 is a subset of c containing only the first 14 elements i am getting IndexError: list index out of range on row.append(float(row[13])/100) does anyone know what i am doing wrong?
[ "The rows in c1 don't actually contain 14 elements, they contain 13.\nThe second index in a slice is non-inclusive. When you append row[0:13] to c1 you are appending from element 0 to the element before 13. Hence, there are only 13 elements.\nThis is why you get IndexError: list index out of range on row.append(f...
[ 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003397943_csv_python.txt
Q: IPC solutions for Python processes on POSIX compliant system I have two Python processes that need to communicate with each other on POSIX complaint system, as an IPC I thought that using a named pipe would be the easiest solution, however since I'm new with Python I suspect there are more options available. Anyone care to make a recommendation, besides a named pipe? Thanks in advance, John A: I would recommend you sticking with named pipes, if the system is POSIX compliant. That being said, there are plenty of options, you could, open a tcp socket and send pickled data, but performance, you would not beat shared memory/named pipe, and why look for a "new" solution if there already exists well defined working solutions? You could also look at this module, seems to be using shared memory, I have not tried it but it looks like an option.
IPC solutions for Python processes on POSIX compliant system
I have two Python processes that need to communicate with each other on POSIX complaint system, as an IPC I thought that using a named pipe would be the easiest solution, however since I'm new with Python I suspect there are more options available. Anyone care to make a recommendation, besides a named pipe? Thanks in advance, John
[ "I would recommend you sticking with named pipes, if the system is POSIX compliant. That being said, there are plenty of options, you could, open a tcp socket and send pickled data, but performance, you would not beat shared memory/named pipe, and why look for a \"new\" solution if there already exists well defined...
[ 1 ]
[]
[]
[ "ipc", "posix", "python" ]
stackoverflow_0003397325_ipc_posix_python.txt
Q: Windows 7 taskbar Does anyone know how to set a custom icon for a program in the taskbar? I know that you can make a shortcut to a program to get whatever icon you want in the top left corner of the program (see image below for refrance) but how do I make a program get a new icon in the taskbar? A: The icon displayed in the taskbar is of the executable. When you invoke a python script, it runs the Python interpreter which has that icon you want to replace. You could use something like PyInstaller to build an executable with a custom icon or if you were using a GUI toolkit you could set the icon of the interface (for example SetIcon() in wxWidgets).
Windows 7 taskbar
Does anyone know how to set a custom icon for a program in the taskbar? I know that you can make a shortcut to a program to get whatever icon you want in the top left corner of the program (see image below for refrance) but how do I make a program get a new icon in the taskbar?
[ "The icon displayed in the taskbar is of the executable. When you invoke a python script, it runs the Python interpreter which has that icon you want to replace. You could use something like PyInstaller to build an executable with a custom icon or if you were using a GUI toolkit you could set the icon of the interf...
[ 1 ]
[]
[]
[ "python", "windows_7" ]
stackoverflow_0003390336_python_windows_7.txt
Q: python: is there a frequency function? in excel there is a frequency function: The Excel FREQUENCY function This useful function can analyse a series of values and summarise them into a number of specified ranges. For example the heights of some children can be grouped in to four categories of [Less than 150cm]; [151 - 160cm]; [161 - 170cm]; [More than 170cm]. Would you like to learn more? Excel 2003 Formulas by John Walkenbach (with CD) FREQUENCY() is an unusual array function and it works differently to most other normal functions. It can not simply be typed into a cell or even entered properly using the Excel Function Wizard. Note that this function does not analyse values into categories e.g. household expenditure into groups such as gas, electricity, water, rates etc. To perform this kind of analysis an Advanced Filter may be appropriate. The frequency function has two arguments - the first is the range of cells containing values to be analysed; the second is the range of cells containing the upper values of each group banding. e.g. =FREQUENCY(A3:A120, B6:B10) The second argument (the group upper limits) will exclude any values which exceed the highest category or banding. The function allows you to take account of this and extend the range of analysis to an additional category which contains all values that exceed the specified upper limit. http://www.meadinkent.co.uk/xlfreq.htm is there such a thing in python? A: import numpy numpy.histogram( [ <data> ], [ <bins> ] ) Docs: numpy.histogram(a, bins=10, range=None, normed=False, weights=None) Compute the histogram of a set of data. Parameters: a : array_like Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars, optional If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. range : (float, float), optional The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. normed : bool, optional If False, the result will contain the number of samples in each bin. If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability mass function. weights : array_like, optional An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). If normed is True, the weights are normalized, so that the integral of the density over the range remains 1 Returns: hist : array The values of the histogram. See normed and weights for a description of the possible semantics. bin_edges : array of dtype float Return the bin edges (length(hist)+1). You may have to install numpy first. A: The best option is to use numpy.histogram, but if you don't want to install numpy, here is one that works just like Excel: def frequency(data, bins): # work with local sorted copy of bins for performance bins = bins[:] bins.sort() freqs = [0] * (len(bins)+1) for item in data: for i, bin_val in enumerate(bins): if item <= bin_val: freqs[i] += 1 break else: freqs[len(bins)] += 1 return freqs Here's the example in Excel's help translated to python: >>> data = [79, 85, 78, 85, 50, 81, 95, 88, 97] ... bins = [70, 79, 89] ... print frequency(data, bins) [1, 2, 4, 2] There is one minor difference. In Excel, if bins is empty, the length of data is returned as an integer. This python version returns that integer in a list. The reason for this is that the Python version will return a consistent data type (and still give the correct answer). A: based on what the referenced page http://www.meadinkent.co.uk/xlfreq.htm states i wrote a function i'm sure that there are faster ways to do it but i'm sure this one is correct def FREQUENCY(values, bands, max=None): counts = [0]*(len(bands)+1) for v in values: for i,b in enumerate(bands): if v <= b: counts[i] += 1 break else if v > max: counts[-1] += 1 break return counts A: I don't know whether there is such function in Python, but obviously you can write it: def frequency(values, groups): # Build the solution toret = dict() toret[ None ] = list() # Sort them values.sort() groups.sort() # Run over groups i = 0 for maxValue in groups: while ( ( values[ i ] < maxValue ) and ( i < len( values ) ) ): if ( toret.get( maxValue ) == None ): toret[ maxValue ] = list() toret[ maxValue ].append( values[ i ] ) i += 1 if ( i >= len( values ) ): break if ( i < len( values ) ): while( i < len( values ) ): toret[ None ].append( values[ i ] ) i += 1 return toret l=[ 15,9,3,5,6,4,8,2,1,7,11,12 ] g=[ 3,6,9 ] print( frequency( l, g ) ) The result here is a dictionary, in which each element is one of the max values in the groups list. You can find the frequency by computing the length of each list. The result is: {None: [9, 11, 12, 15], 9: [6, 7, 8], 3: [1, 2], 6: [3, 4, 5]}
python: is there a frequency function?
in excel there is a frequency function: The Excel FREQUENCY function This useful function can analyse a series of values and summarise them into a number of specified ranges. For example the heights of some children can be grouped in to four categories of [Less than 150cm]; [151 - 160cm]; [161 - 170cm]; [More than 170cm]. Would you like to learn more? Excel 2003 Formulas by John Walkenbach (with CD) FREQUENCY() is an unusual array function and it works differently to most other normal functions. It can not simply be typed into a cell or even entered properly using the Excel Function Wizard. Note that this function does not analyse values into categories e.g. household expenditure into groups such as gas, electricity, water, rates etc. To perform this kind of analysis an Advanced Filter may be appropriate. The frequency function has two arguments - the first is the range of cells containing values to be analysed; the second is the range of cells containing the upper values of each group banding. e.g. =FREQUENCY(A3:A120, B6:B10) The second argument (the group upper limits) will exclude any values which exceed the highest category or banding. The function allows you to take account of this and extend the range of analysis to an additional category which contains all values that exceed the specified upper limit. http://www.meadinkent.co.uk/xlfreq.htm is there such a thing in python?
[ "import numpy\nnumpy.histogram( [ <data> ], [ <bins> ] )\n\nDocs:\n\nnumpy.histogram(a, bins=10, range=None, normed=False, weights=None)\n\nCompute the histogram of a set of data.\n Parameters: \na : array_like\n Input data. The histogram is computed over the flattened array.\nbins : int or sequence of scalars,...
[ 4, 3, 1, 1 ]
[]
[]
[ "excel", "python", "vba" ]
stackoverflow_0003398072_excel_python_vba.txt
Q: Get the current date as the default argument for a method I've got a method: def do_something(year=?, month=?): pass I want the year and month arguments to be optional but I want their default to equal the current year and month. I've thought about setting two variables just before the method declaration but the process this is part of can run for months. It needs to be dynamic. Seems like it shouldn't be hard but I'm having a mental block today so how would you do it? A: The idiomatic approach here would be to assign None as the default value, and then reassign within the method if the values are still None: def do_something(year=None, month=None): if year is None: year = datetime.date.today().year if month is None: month = datetime.date.today().month # do stuff... You might think that you can do def do_something(year=datetime.date.today().year), but that would cache the value so that year would be the same across all calls to do_something. To demonstrate that concept: >>> def foo(x=time.time()): print x ... >>> foo() 1280853111.26 >>> # wait a second at the prompt >>> foo() 1280853111.26
Get the current date as the default argument for a method
I've got a method: def do_something(year=?, month=?): pass I want the year and month arguments to be optional but I want their default to equal the current year and month. I've thought about setting two variables just before the method declaration but the process this is part of can run for months. It needs to be dynamic. Seems like it shouldn't be hard but I'm having a mental block today so how would you do it?
[ "The idiomatic approach here would be to assign None as the default value, and then reassign within the method if the values are still None:\ndef do_something(year=None, month=None):\n if year is None:\n year = datetime.date.today().year\n if month is None:\n month = datetime.date.today().month\...
[ 11 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003398562_datetime_python.txt
Q: Python Watch Folder - interrogating list for filesize I'm trying to get the following code to watch a folder for changes and return the filename (preferably a full path) as a string once it's checked that the filesize hasn't increased recently, to stop the rest of my script inspecting incomplete files. I'm having difficulty with sending my filesize timer function a filename because i'm collecting the detected files as a list. If i'm barking up the wrong tree feel free to tell me, and thanks for any help! Stewart import os, time def watch(path_to_watch): before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while watch_active == 1: time.sleep (10) after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if added: filesizechecker(added) return added if removed: print "Removed: ", ", ".join (removed) before = after def filesizechecker(filepath): # Checks filesize of input file and # returns 1 when file hasn't changed for 3 seconds fnow = open(filepath, "rb") fthen = 1 while fnow != fthen: time.sleep(3) fthen = len(f.read()) watch_active = 1 watch("/home/stewart/Documents") A: You could also check how lsof works. It lists the open files. If the file you're watching (or want) isn't open it is also not probable that it is being changed. You're on Linux so you can always check the /proc filesystem for information on processes and files. I don't know the details, so it's upt o you weather this line of thinking is worth your time:) A: I did some more research and discovered the pyinotify library was much more suited to my needs. Specifically the IN_CLOSE_WRITE Event Code returns when an application (in my case, a file copy) closes a writable file.
Python Watch Folder - interrogating list for filesize
I'm trying to get the following code to watch a folder for changes and return the filename (preferably a full path) as a string once it's checked that the filesize hasn't increased recently, to stop the rest of my script inspecting incomplete files. I'm having difficulty with sending my filesize timer function a filename because i'm collecting the detected files as a list. If i'm barking up the wrong tree feel free to tell me, and thanks for any help! Stewart import os, time def watch(path_to_watch): before = dict ([(f, None) for f in os.listdir (path_to_watch)]) while watch_active == 1: time.sleep (10) after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] removed = [f for f in before if not f in after] if added: filesizechecker(added) return added if removed: print "Removed: ", ", ".join (removed) before = after def filesizechecker(filepath): # Checks filesize of input file and # returns 1 when file hasn't changed for 3 seconds fnow = open(filepath, "rb") fthen = 1 while fnow != fthen: time.sleep(3) fthen = len(f.read()) watch_active = 1 watch("/home/stewart/Documents")
[ "You could also check how lsof works. It lists the open files. If the file you're watching (or want) isn't open it is also not probable that it is being changed.\nYou're on Linux so you can always check the /proc filesystem for information on processes and files.\nI don't know the details, so it's upt o you weather...
[ 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003397079_linux_python.txt
Q: To select only some columns from some tables using session object I have these classe where items (class Item) is related to channel object: channel_items = Table( "channel_items", metadata, Column("channel_id", Integer, ForeignKey("channels.id")), Column("item_id", Integer, ForeignKey(Item.id)) ) class Channel(rdb.Model): """ Set up channels table in the database """ rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) items = relation(Item, secondary=channel_items, backref="channels") class Item(rdb.Model): """ Set up items table in the database """ rdb.metadata(metadata) rdb.tablename("items") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) I know how to get all the columns using something like: session = rdb.Session() channels = session.query(Channel).order_by(Channel.title) However, I'd like to get some columns from both tables and the field items in channel object to be related to Item class because I've tried something like this: session = rdb.Session() channels = session.query(Channel.title, Item.title).order_by(Channel.title) I got the channel title and item title, but I just get one item from every channel. I'd like to get all the items related to every channel. Thanks in advance! A: You want join here, not Cartesian product. If I understand you correctly, and you want to select only titles, w/out building actual instances, it can be done like this: session = rdb.Session() result = session.query(Channel).join(Channel.items).values(Channel.title, Item.title) Result is generator, which will provide you (Channel.title, Item.title) tuples. So if you have some 'channel1' which has two items 'item1' and 'item2', you will receive [('channel1', 'item1'), ('channel1', 'item2')] If you need to just load channels with their items associated, you would probably want this instead: from sqlalchemy.orm import eagerload channels = session.query(Channel).options(eagerload('items')).all() channels[0].items[0].title
To select only some columns from some tables using session object
I have these classe where items (class Item) is related to channel object: channel_items = Table( "channel_items", metadata, Column("channel_id", Integer, ForeignKey("channels.id")), Column("item_id", Integer, ForeignKey(Item.id)) ) class Channel(rdb.Model): """ Set up channels table in the database """ rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) items = relation(Item, secondary=channel_items, backref="channels") class Item(rdb.Model): """ Set up items table in the database """ rdb.metadata(metadata) rdb.tablename("items") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) I know how to get all the columns using something like: session = rdb.Session() channels = session.query(Channel).order_by(Channel.title) However, I'd like to get some columns from both tables and the field items in channel object to be related to Item class because I've tried something like this: session = rdb.Session() channels = session.query(Channel.title, Item.title).order_by(Channel.title) I got the channel title and item title, but I just get one item from every channel. I'd like to get all the items related to every channel. Thanks in advance!
[ "You want join here, not Cartesian product.\nIf I understand you correctly, and you want to select only titles, w/out building actual instances, it can be done like this:\nsession = rdb.Session()\nresult = session.query(Channel).join(Channel.items).values(Channel.title, Item.title)\n\nResult is generator, which wil...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003389393_python_sqlalchemy.txt
Q: Django Error "no such column: tagging_tag.name" I got this after installing the tagging application. I've installed it via settings.py as well as placing it on the import path so I think I've done everything right there. This is what turns up. You can see my error log here. I've run syncdb, so my database should be synced up. A: Have you checked output of syncdb and actually seen, that table was created? Take a look into your database and check, whether the table is created. If not, run syncdb again and if this doesn't help, create the table by hand (or drop the database and create it again from scratch).
Django Error "no such column: tagging_tag.name"
I got this after installing the tagging application. I've installed it via settings.py as well as placing it on the import path so I think I've done everything right there. This is what turns up. You can see my error log here. I've run syncdb, so my database should be synced up.
[ "Have you checked output of syncdb and actually seen, that table was created? Take a look into your database and check, whether the table is created. If not, run syncdb again and if this doesn't help, create the table by hand (or drop the database and create it again from scratch).\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003398914_django_python.txt
Q: Sorting a list of lists in Python c2=[] row1=[1,22,53] row2=[14,25,46] row3=[7,8,9] c2.append(row2) c2.append(row1) c2.append(row3) c2 is now: [[14, 25, 46], [1, 22, 53], [7, 8, 9]] how do i sort c2 in such a way that for example: for row in c2: sort on row[2] the result would be: [[7,8,9],[14,25,46],[1,22,53]] the other question is how do i first sort by row[2] and within that set by row[1] A: The key argument to sort specifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple lambda that returns the last element from each row to be used in the sort: c2.sort(key = lambda row: row[2]) A lambda is a simple anonymous function. It's handy when you want to create a simple single use function like this. The equivalent code not using a lambda would be: def sort_key(row): return row[2] c2.sort(key = sort_key) If you want to sort on more entries, just make the key function return a tuple containing the values you wish to sort on in order of importance. For example: c2.sort(key = lambda row: (row[2],row[1])) or: c2.sort(key = lambda row: (row[2],row[1],row[0])) A: >>> import operator >>> c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]] >>> c2.sort(key=itemgetter(2)) >>> c2 [[7, 8, 9], [14, 25, 46], [1, 22, 53]] A: Well, your desired example seems to indicate that you want to sort by the last index in the list, which could be done with this: sorted_c2 = sorted(c2, lambda l1, l2: l1[-1] - l2[-1])
Sorting a list of lists in Python
c2=[] row1=[1,22,53] row2=[14,25,46] row3=[7,8,9] c2.append(row2) c2.append(row1) c2.append(row3) c2 is now: [[14, 25, 46], [1, 22, 53], [7, 8, 9]] how do i sort c2 in such a way that for example: for row in c2: sort on row[2] the result would be: [[7,8,9],[14,25,46],[1,22,53]] the other question is how do i first sort by row[2] and within that set by row[1]
[ "The key argument to sort specifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple lambda that returns the last element from each row to be used in the sort:\nc2.sort(key = lambda row: row[2])\n\nA lambda is a simple anonymous function. It's h...
[ 22, 4, 3 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0003398589_list_python_sorting.txt
Q: Need to create thumbnail, how to ensure proportions and set fixed width? I want to create a thumbnail, and the width has to be either fixed or no bigger than 200 pixels wide (the length can be anything). The images are either .jpg or .png or .gif I am using python. The reason it has to be fixed is so that it fits inside a html table cell. A: To keep proportions the same, you need to multiply both the width and the height by the same scaling factor. Calculate each independently to fit inside your space, then choose the smallest of the two. You say you don't care about the height, but you might want to set a bound on it anyway in case someone feeds you a really skinny image. In the code below, I've added two additional constraints: the resulting thumbnail width or height will always be >= 1, and the scaling factor will will always be <= 1 (so that the thumbnail isn't larger than the original). scale_x = max_width / image_width scale_y = max_height / image_height scale = min(scale_x, scale_y, 1) thumb_width = max(round(image_width * scale), 1) thumb_height = max(round(image_height * scale), 1) A: Look at PyMagick, the python interface for the ImageMagick libraries. It's fairly simple to resize an image, retaining proportion, while limiting the longest side. edit: when I say fairly simple, I mean you can describe your resize in terms of the longest acceptable values for each side, and ImageMagick will preserve the proportions automatically. A: Support suggestion of using PIL. However, the calculation is actually much simpler: from PIL import Image as PILImage imageObj = PILImage.open(image_filename,'r') iwidth, iheight = imageObj.size # pixels size_proportion = iheight / iwidth # make sure your "limiter" is the denominator newheight = size_proportion * 200 # resize the image to (newheight, 200) and save it Alternatively, just call out to subprocess and use ImageMagic or GraphicsMagic (i use latter) These libs give you very good scaling algorithms, are written in lower level language and are very much optimized. One extra nice thing IM and GM do is mass processing of images. Another nice thing is that in some modes you don't need to give GraphicsMagic the needed size, just give maximums, and it will scale the picture down based on whichever constraint exceeds your given maximums. Check it out.
Need to create thumbnail, how to ensure proportions and set fixed width?
I want to create a thumbnail, and the width has to be either fixed or no bigger than 200 pixels wide (the length can be anything). The images are either .jpg or .png or .gif I am using python. The reason it has to be fixed is so that it fits inside a html table cell.
[ "To keep proportions the same, you need to multiply both the width and the height by the same scaling factor. Calculate each independently to fit inside your space, then choose the smallest of the two. You say you don't care about the height, but you might want to set a bound on it anyway in case someone feeds you ...
[ 4, 3, 1 ]
[]
[]
[ "image", "python" ]
stackoverflow_0003391558_image_python.txt
Q: How can i change the __cmp__ function of an instance (not in class)? How can i change the __cmp__ function of an instance (not in class)? Ex: class foo: def __init__(self, num): self.num = num def cmp(self, other): return self.num - other.num # Change __cmp__ function in class works foo.__cmp__ = cmp a = foo(1) b = foo(1) # returns True a == b # Change __cmp__ function in instance that way doesnt work def cmp2(self, other): return -1 a.__cmp__ = cmp2 b.__cmp__ = cmp2 # Raise error a == b #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #TypeError: cmp2() takes exactly 2 arguments (1 given) A: DO NOT DO THIS It will make your code buggy and hard to maintain. The reason it is difficult is because the right way to do it is to subclass foo: class FunkyCmpFoo( foo ): def __cmp__( self, other ): return -1 &c., &c. This way, you know that all foos compare in the same way, and all FunkyCmpFoos compare in the same way. If you don't, you will eventually end up comparing a modified foo with an original foo, and Cthulhu himself will rise from the depths to punish you. I'm not sure whether I should say this, but it is possible, by creating your own instance methods: funcType = type( foo.__cmp__ ) # Alternatively: import new cmp2 = new.instancemethod( func, a, foo ) a.__cmp__ = funcType( cmp2, a, foo ) b.__cmp__ = funcType( cmp2, b, foo ) I can think of one good reason to do this, and that is if your archenemy has to debug the code. In fact, I can think of some quite fun things to do with that in mind (how would you like sys.maxint to compare less than all even numbers?). Apart from that, it's a nightmare. A: Edit: This is the part where I'm supposed to say you're a bad person if you do this in production code. All your hair and teeth will fall out, and you'll be cursed to walk the stack forever during your afterlife. Add an extra bit of indirection so you're not mixing up bound/unbound methods: class foo(object): def __init__(self, num): self.num = num self.comparer = self._cmp def __cmp__(self, other): return self.comparer(self, other) @staticmethod def _cmp(this, that): print 'in foo._cmp' return id(this) == id(that) def setcmp(self, f): self.comparer = f def cmp2(self, other): print 'in cmp2' return -1 a = foo(1) b = foo(1) print a == b a.setcmp(cmp2) b.setcmp(cmp2) print a == b A: * You can use the anti-polymorphon pattern: class foo(object): def __init__(self, num, i_am_special=None): self.num = num self.special = i_am_special def __cmp__(self, other): if self.special is not None: return -1 else: return cmp(self.num, other.num) def __hash__(self): if self.special is not None: # TODO: figure out a non-insane value return 0 Which gives sensible results like: >>> a = foo(1) >>> b = foo(2, 'hi mom') >>> a > b False >>> b > a False >>> a == b False >>> b == b False I mostly posted this answer because I liked how "anti-polymorphon" sounded. Don't do this at home, kids without proper adult supervision. [* coding horror logo used without permission of Jeff Atwood or the rights holder Steven C. McConnell who I'm sure are swell guys and don't need their mark sullied like this.] A: While it is bad practice to change the comparison function for different instances of a class in general, sometimes you may want to use a different comparison function for a group of instances for which you want to do a common operation. An example is when you want to sort them according to different criteria. The standard example would be sorted(list_of_foos, cmp = foocmp). Notwithstanding that it is currently preferred to use the key parameter and in fact Python 3.x doesn't support the cmp parameter anyway (you would want to use cmp_to_key). In this case the best way is usually to make the comparison function a parameter of the function operating on the group of instances, exactly as sorted does.
How can i change the __cmp__ function of an instance (not in class)?
How can i change the __cmp__ function of an instance (not in class)? Ex: class foo: def __init__(self, num): self.num = num def cmp(self, other): return self.num - other.num # Change __cmp__ function in class works foo.__cmp__ = cmp a = foo(1) b = foo(1) # returns True a == b # Change __cmp__ function in instance that way doesnt work def cmp2(self, other): return -1 a.__cmp__ = cmp2 b.__cmp__ = cmp2 # Raise error a == b #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #TypeError: cmp2() takes exactly 2 arguments (1 given)
[ "DO NOT DO THIS\nIt will make your code buggy and hard to maintain. The reason it is difficult is because the right way to do it is to subclass foo:\nclass FunkyCmpFoo( foo ):\n def __cmp__( self, other ):\n return -1\n\n&c., &c. This way, you know that all foos compare in the same way, and all FunkyCmpFo...
[ 5, 2, 2, 0 ]
[]
[]
[ "cmp", "metaprogramming", "python" ]
stackoverflow_0003397778_cmp_metaprogramming_python.txt
Q: SqlAlchemy Mapper not returning clean UUIDs I have a table which is being mapped with SqlAlchemy. In that table is a UUID column. When I try to query that table, I get the uuid in bytes_le format. Is there some way I can tell the mapper to return a clean string representation instead? Code for the mapper is: Practice = Table('Practice',metadata, schema='pulse',autoload=True, autoload_with=engine, quote_schema=True) class PracticeMap(object): def __str__(self): return "%s" % self.Name def __repr__(self): return "Name: %s, UUID: %s" % (self.Name, self.uuid) mapper(PracticeMap,Practice) Thanks. A: You can always reformat the uuid using the python uuid library: import uuid uuid_string = str(uuid.UUID(bytes_le=self.uuid)) If you only need the string representation for __repr__ that should do the trick. If you want the uuid property of your object to live in string-land, you'll want to rename the column property and provide your own uuid property to wrap it.
SqlAlchemy Mapper not returning clean UUIDs
I have a table which is being mapped with SqlAlchemy. In that table is a UUID column. When I try to query that table, I get the uuid in bytes_le format. Is there some way I can tell the mapper to return a clean string representation instead? Code for the mapper is: Practice = Table('Practice',metadata, schema='pulse',autoload=True, autoload_with=engine, quote_schema=True) class PracticeMap(object): def __str__(self): return "%s" % self.Name def __repr__(self): return "Name: %s, UUID: %s" % (self.Name, self.uuid) mapper(PracticeMap,Practice) Thanks.
[ "You can always reformat the uuid using the python uuid library:\nimport uuid\nuuid_string = str(uuid.UUID(bytes_le=self.uuid))\n\nIf you only need the string representation for __repr__ that should do the trick. If you want the uuid property of your object to live in string-land, you'll want to rename the column ...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003398806_python_sqlalchemy.txt
Q: How to handle tokenization errors? Please find below the piece of code that I use to tokenize a string. strList = list(token[STRING] for token in generate_tokens(StringIO(line).readline) if token[STRING]) I get an error that reads like:- raise TokenError, ("EOF in multi-line statement", (lnum, 0)) tokenize.TokenError: ('EOF in multi-line statement', (2, 0)) I wish to ignore such errors and be able to complete the tokenization process. I have a lot of data, so I am okay with loosing a part of the data to these errors. However, I am not sure how to write the piece of code that would enable be to implement the desired functionality. Could some one help me out with the code please? Thank you. Edit1:- on trying the except tokenize.TokenError: pass I get the following error message except tokenize.TokenError: NameError: name 'tokenize' is not defined A: Notice that your error message says tokenize.TokenError. That is the type of Exception your code is raising. To catch the error, you use a try...except block. To skip the error you simply put pass in the except block. import tokenize try: strList = list(token[STRING] for token in tokenize.generate_tokens(StringIO(line).readline) if token[STRING]) except tokenize.TokenError: pass
How to handle tokenization errors?
Please find below the piece of code that I use to tokenize a string. strList = list(token[STRING] for token in generate_tokens(StringIO(line).readline) if token[STRING]) I get an error that reads like:- raise TokenError, ("EOF in multi-line statement", (lnum, 0)) tokenize.TokenError: ('EOF in multi-line statement', (2, 0)) I wish to ignore such errors and be able to complete the tokenization process. I have a lot of data, so I am okay with loosing a part of the data to these errors. However, I am not sure how to write the piece of code that would enable be to implement the desired functionality. Could some one help me out with the code please? Thank you. Edit1:- on trying the except tokenize.TokenError: pass I get the following error message except tokenize.TokenError: NameError: name 'tokenize' is not defined
[ "Notice that your error message says tokenize.TokenError. That is the type of Exception your code is raising. To catch the error, you use a try...except block. To skip the error you simply put pass in the except block.\nimport tokenize\ntry:\n strList = list(token[STRING] for token in tokenize.generate_tokens(St...
[ 3 ]
[]
[]
[ "python", "stringio", "tokenize" ]
stackoverflow_0003399306_python_stringio_tokenize.txt
Q: Calling in functions in another function I created a function to read in a csv file and then write some of the data from the csv file into another file. I had to manipulate some of the data in the original csv file before I write it. I will probably have to do that manipulation a lot during the next couple months so I wrote another function to just do that manipulation, but I am having trouble calling in the function in my other function. this is the function I am trying to call in: import sys import math def convLatLon(measurement): # should be in '##.####' format tpoint=float(measurement) point_deg=math.floor(measurement) # find the degree for lat and lon dpoint=tpoint-point_deg #subtract the lat value from just the degs to get the decimal fraction pointmin=dpoint * 60 # find the degree mins npoint= str(point_deg) + str(pointmin) print(npoint) How do I call in this function in another function? They are currently in the same directory. I am used to Matlab and thought it would be a simple call in command but I can not seem to figure it out. Any help will be greatly apprectiated. Shay A: You can import the file (same as you imported sys and math). If your function is in a file called util.py: import util util.convLatLon(37.76) If the file is in another directory, the directory must be in your PYTHONPATH. A: Is: from <filename> import convLatLon What you're looking for? A: Sounds like you need to import the file. If your function is defined in file myfile.py and you wan`t to use it from myotherfile.py, you should import myfile.py, like this: import myfile and then you can use the function like this: result = myfile.myfunc(myparms) If you want to get rid of the myfile prefix, import it like this: from myfile import myfunc A: If you have this function saved in a file called myconv.py from myconv.py import convLatLon convLatLon("12.3456")
Calling in functions in another function
I created a function to read in a csv file and then write some of the data from the csv file into another file. I had to manipulate some of the data in the original csv file before I write it. I will probably have to do that manipulation a lot during the next couple months so I wrote another function to just do that manipulation, but I am having trouble calling in the function in my other function. this is the function I am trying to call in: import sys import math def convLatLon(measurement): # should be in '##.####' format tpoint=float(measurement) point_deg=math.floor(measurement) # find the degree for lat and lon dpoint=tpoint-point_deg #subtract the lat value from just the degs to get the decimal fraction pointmin=dpoint * 60 # find the degree mins npoint= str(point_deg) + str(pointmin) print(npoint) How do I call in this function in another function? They are currently in the same directory. I am used to Matlab and thought it would be a simple call in command but I can not seem to figure it out. Any help will be greatly apprectiated. Shay
[ "You can import the file (same as you imported sys and math). If your function is in a file called util.py:\nimport util\nutil.convLatLon(37.76)\n\nIf the file is in another directory, the directory must be in your PYTHONPATH.\n", "Is:\nfrom <filename> import convLatLon\n\nWhat you're looking for?\n", "Sounds ...
[ 3, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003399291_python_python_3.x.txt
Q: how can i verify all links on a page as a black-box tester I'm tryng to verify if all my page links are valid, and also something similar to me if all the pages have a specified link like contact. i use python unit testing and selenium IDE to record actions that need to be tested. So my question is can i verify the links in a loop or i need to try every link on my own? i tried to do this with __iter__ but it didn't get any close ,there may be a reason that i'm poor at oop, but i still think that there must me another way of testing links than clicking them and recording one by one. A: Though the tool is in Perl, have you checked out linklint? It's a tool which should fit your needs exactly. It will parse links in an HTML doc and will tell you when they are broken. If you're trying to automate this from a Python script, you'd need to run it as a subprocess and get the results, but I think it would get you what you're looking for. A: I would just use standard shell commands for this: You can use wget to detect broken links If you use wget to download the pages, you can then scan the resulting files with grep --files-without-match to find those that don't have a contact link. If you're on windows, you can install cygwin or install the win32 ports of these tools. EDIT: Embed Info from the use wget to detect broken links link above: When ever we release a public site its always a good idea to run a spider on it, this way we can check for broken pages and bad urls. WGET has a recursive download command and mixed with --spider option it will just crawl the site. 1) Download WGET Mac: http://www.statusq.org/archives/2008/07/30/1954/ Or use macports and download wget. Windows: http://gnuwin32.sourceforge.net/packages/wget.htm Linux: Comes built in ---------------------------------------- 2) In your console / terminal, run (without the $): $ wget --spider -r -o log.txt http://yourdomain.com 3) After that just locate you "log.txt" file and at the very bottom of the file will be a list of broken links, how many links there are, etc. A: What exactly is "Testing links"? If it means they lead to non-4xx URIs, I'm afraid You must visit them. As for existence of given links (like "Contact"), You may look for them using xpath. A: You could (as yet another alternative), use BeautifulSoup to parse the links on your page and try to retrieve them via urllib2.
how can i verify all links on a page as a black-box tester
I'm tryng to verify if all my page links are valid, and also something similar to me if all the pages have a specified link like contact. i use python unit testing and selenium IDE to record actions that need to be tested. So my question is can i verify the links in a loop or i need to try every link on my own? i tried to do this with __iter__ but it didn't get any close ,there may be a reason that i'm poor at oop, but i still think that there must me another way of testing links than clicking them and recording one by one.
[ "Though the tool is in Perl, have you checked out linklint? It's a tool which should fit your needs exactly. It will parse links in an HTML doc and will tell you when they are broken.\nIf you're trying to automate this from a Python script, you'd need to run it as a subprocess and get the results, but I think it ...
[ 1, 1, 0, 0 ]
[]
[]
[ "black_box", "python", "testing" ]
stackoverflow_0003397850_black_box_python_testing.txt
Q: python: using numpy.histogram i am using this: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html i have an list a that i want to use like this: numpy.histogram(a,bins=[0.1,0.2,0.3,0.4...6], range=[0:6]) how do i include a set of bins 0.1 through 6 in 0.1 intervals? how do i specify a range of 0 through 6? A: Perhaps you are looking for np.linspace(0,6,num=61) or np.arange(0,6.1,0.1): import numpy as np a=np.random.random(100)*6 hist=np.histogram(a,bins=np.linspace(0,6,num=61)) A: If you're ok with floating point numbers, you can do: [x/10.0 for x in range(61)] gives you (middle elements omitted) [0.0, 0.10000000000000001, 0.20000000000000001, ... 5.7000000000000002, 5.7999999999999998, 5.9000000000000004, 6.0] Otherwise, see the decimal module. range(7) Here's an example: pop contains 1000 random numbers from the sequence 0, 0.01, 0.02, ..., 5.99, 6. Bins are as you specified. You may add a range, or not -- in any event, the end points are easy in this case. >>> import numpy >>> import random >>> pop = [] >>> for i in range(1000): ... pop.extend([random.choice(range(600))/100.0]) ... >>> bins = [x/10.0 for x in range(61)] >>> hist, bin_edges = numpy.histogram(pop, bins) >>> bin_edges array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5. , 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6. ]) >>> hist array([20, 11, 22, 17, 25, 11, 15, 15, 13, 18, 21, 21, 16, 13, 12, 18, 16, 19, 11, 14, 15, 20, 20, 9, 13, 16, 20, 19, 23, 11, 19, 12, 21, 15, 16, 24, 24, 16, 19, 18, 10, 14, 29, 11, 16, 15, 14, 19, 11, 15, 16, 12, 17, 18, 12, 14, 27, 12, 21, 19])
python: using numpy.histogram
i am using this: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html i have an list a that i want to use like this: numpy.histogram(a,bins=[0.1,0.2,0.3,0.4...6], range=[0:6]) how do i include a set of bins 0.1 through 6 in 0.1 intervals? how do i specify a range of 0 through 6?
[ "Perhaps you are looking for np.linspace(0,6,num=61) or np.arange(0,6.1,0.1):\nimport numpy as np\na=np.random.random(100)*6\nhist=np.histogram(a,bins=np.linspace(0,6,num=61))\n\n", "\nIf you're ok with floating point numbers, you can do: [x/10.0 for x in range(61)] gives you (middle elements omitted) [0.0, 0.10...
[ 5, 2 ]
[]
[]
[ "arrays", "histogram", "list", "python" ]
stackoverflow_0003399210_arrays_histogram_list_python.txt
Q: python: generating a histogram this: numpy.histogram([1,3,2,3,1,1,1,1,2,3,2,5,6,6],bins=numpy.arange(0,7,1)) yields: (array([0, 5, 3, 3, 0, 3]), array([0, 1, 2, 3, 4, 5, 6])) why does it count three 6's? there are only 2! A: because bins defines the bin edges you need to add one more bin numpy.histogram([1,3,2,3,1,1,1,1,2,3,2,5,6,6],bins=numpy.arange(0,8,1)) A: There is one 5 and two 6's in the last bin. Quoting the doc "All but the last (righthand-most) bin is half-open", so the last bin includes the 2 6's. A: It looks like it's lumping the 5's and 6's together - maybe the last bin is 5 to 6, inclusive? Edit: Looking at the docs, I'm guessing that 6 is the rightmost edge, so values between five and six are in that final bin. A: I believe this is related to the semantics of the first and last bins being underflow and overflow. Your total bucket count is correct.
python: generating a histogram
this: numpy.histogram([1,3,2,3,1,1,1,1,2,3,2,5,6,6],bins=numpy.arange(0,7,1)) yields: (array([0, 5, 3, 3, 0, 3]), array([0, 1, 2, 3, 4, 5, 6])) why does it count three 6's? there are only 2!
[ "because bins defines the bin edges you need to add one more bin\nnumpy.histogram([1,3,2,3,1,1,1,1,2,3,2,5,6,6],bins=numpy.arange(0,8,1))\n\n", "There is one 5 and two 6's in the last bin. Quoting the doc \"All but the last (righthand-most) bin is half-open\", so the last bin includes the 2 6's.\n", "It looks ...
[ 4, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003399783_python.txt
Q: python: what does array([...]) mean? i am working with lists, and there is a function that is returning something that looks like this: array([0, 5, 3, 3, 0, 1, 2]) how do i cast those values into a list? what does array mean? A: array most likely refers to a numpy.array myarray = array([0, 5, 3, 3, 0, 1, 2]) mylist = list(myarray)
python: what does array([...]) mean?
i am working with lists, and there is a function that is returning something that looks like this: array([0, 5, 3, 3, 0, 1, 2]) how do i cast those values into a list? what does array mean?
[ "array most likely refers to a numpy.array \nmyarray = array([0, 5, 3, 3, 0, 1, 2])\nmylist = list(myarray)\n\n" ]
[ 8 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0003399895_arrays_list_python.txt
Q: How do I maximize efficiency with numpy arrays? I am just getting to know numpy, and I am impressed by its claims of C-like efficiency with memory access in its ndarrays. I wanted to see the differences between these and pythonic lists for myself, so I ran a quick timing test, performing a few of the same simple tasks with numpy without it. Numpy outclassed regular lists by an order of magnitude in the allocation of and arithmetic operations on arrays, as expected. But this segment of code, identical in both tests, took about 1/8 of a second with a regular list, and slightly over 2.5 seconds with numpy: file = open('timing.log','w') for num in a2: if num % 1000 == 0: file.write("Multiple of 1000!\r\n") file.close() Does anyone know why this might be, and if there is some other syntax i should be using for operations like this to take better advantage of what the ndarray can do? Thanks... EDIT: To answer Wayne's comment... I timed them both repeatedly and in different orders and got pretty much identical results each time, so I doubt it's another process. I put start = time() at the top of the file after the numpy import and then I have statements like print 'Time after traversal:\t',(time() - start) throughout. A: a2 is a NumPy array, right? One possible reason it might be taking so long in NumPy (if other processes' activity don't account for it as Wayne Werner suggested) is that you're iterating over the array using a Python loop. At every step of the iteration, Python has to fetch a single value out of the NumPy array and convert it to a Python integer, which is not a particularly fast operation. NumPy works much better when you are able to perform operations on the whole array as a unit. In your case, one option (maybe not even the fastest) would be file.write("Multiple of 1000!\r\n" * (a2 % 1000 == 0).sum()) Try comparing that to the pure-Python equivalent, file.write("Multiple of 1000!\r\n" * sum(filter(lambda i: i % 1000 == 0, a2))) or file.write("Multiple of 1000!\r\n" * sum(1 for i in a2 if i % 1000 == 0)) A: I'm not surprised that NumPy does poorly w/r/t Python built-ins when using your snippet. A large fraction of the performance benefit in NumPy arises from avoiding the loops and instead access the array by indexing: In NumPy, it's more common to do something like this: A = NP.random.randint(10, 100, 100).reshape(10, 10) w = A[A % 2 == 0] NP.save("test_file.npy", w) A: Per-element access is very slow for numpy arrays. Use vector operations: $ python -mtimeit -s 'import numpy as np; a2=np.arange(10**6)' ' > sum(1 for i in a2 if i % 1000 == 0)' 10 loops, best of 3: 1.53 sec per loop $ python -mtimeit -s 'import numpy as np; a2=np.arange(10**6)' ' > (a2 % 1000 == 0).sum()' 10 loops, best of 3: 22.6 msec per loop $ python -mtimeit -s 'import numpy as np; a2= range(10**6)' ' > sum(1 for i in a2 if i % 1000 == 0)' 10 loops, best of 3: 90.9 msec per loop
How do I maximize efficiency with numpy arrays?
I am just getting to know numpy, and I am impressed by its claims of C-like efficiency with memory access in its ndarrays. I wanted to see the differences between these and pythonic lists for myself, so I ran a quick timing test, performing a few of the same simple tasks with numpy without it. Numpy outclassed regular lists by an order of magnitude in the allocation of and arithmetic operations on arrays, as expected. But this segment of code, identical in both tests, took about 1/8 of a second with a regular list, and slightly over 2.5 seconds with numpy: file = open('timing.log','w') for num in a2: if num % 1000 == 0: file.write("Multiple of 1000!\r\n") file.close() Does anyone know why this might be, and if there is some other syntax i should be using for operations like this to take better advantage of what the ndarray can do? Thanks... EDIT: To answer Wayne's comment... I timed them both repeatedly and in different orders and got pretty much identical results each time, so I doubt it's another process. I put start = time() at the top of the file after the numpy import and then I have statements like print 'Time after traversal:\t',(time() - start) throughout.
[ "a2 is a NumPy array, right? One possible reason it might be taking so long in NumPy (if other processes' activity don't account for it as Wayne Werner suggested) is that you're iterating over the array using a Python loop. At every step of the iteration, Python has to fetch a single value out of the NumPy array an...
[ 10, 6, 5 ]
[]
[]
[ "numpy", "performance", "python" ]
stackoverflow_0003399361_numpy_performance_python.txt
Q: Invoking a python script from a makefile in another directory I have a makefile that invokes a python script that lives in the same directory as the makefile. It works just fine. In makefile #1: auto: ./myscript.py Now, I have another makefile, in another directory, and wish to call the first makefile from it. In makefile #2: target: cd $(DIR); $(MAKE) auto; The problem is, when the script runs, it runs as though it's in the same dir as makefile #2. On stdout, I see "make[3]: Leaving directory" and the path to #1, just after the make is executed and before the script is run. On a suggestion I tried modifying makefile #2 to: target: ( cd $DIR; $MAKE auto; ) but that's interpreted as "cd IR; AKE auto". When I replace the parentheses around DIR and MAKE, I get the same behavior as before. I've tried modifying the python script by having it assume it's in dir #2 and giving it a path to #1, but the behavior doesn't change. What's going on, and what should I do? Update: My comment below messed up code formatting so it's here: I tried this out and got essentially what you describe. Might it have anything to do with the fact that target auto invokes a "makefile.rules" file? auto: @echo this is makefile \#1 making $@ in $(PWD) FLAG=1 $(MAKE) -f makefile.rules rulestargetA FLAG=2 $(MAKE) -f makefile.rules rulestargetB ./myscript.py I omitted that fact for simplicity, but now I wonder. Update 2: I don't understand why the makefiles aren't causing myscript.py to be run as though it's in the directory in which it resides, but I have been trying to get the script to operate correctly even when invoked from a different directory. It opens a couple of subprocesses, runs an executable in each subprocess, and saves the stdout from each subprocess to files. Python's subprocess.Popen passes in the current working directory, which would be where the script is invoked from, not where it resides, by default. I've added script to pass in the residential directory as cwd into the Popen call. For some reason, though, when I run myscript.py in its own directory it works, but when I invoke it from elsewhere (from the command line) it hangs in proc.communicate(). I should solve this python issue, but I'd still like to know why the external makefile can't invoke this script as from its own directory. A: This is very strange. First the easy part: target: ( cd $DIR; $MAKE auto; ) The parentheses do nothing here, and Make interprets $DIR as $D followed by the letter 'I' and the letter 'R'. Since the variable D is not defined, this works out to 'IR'. Same for $MAKE. Now for the real problem. The makefiles as written should work. And you say it leaves directory #1 before the script runs? All I can suggest is that you try a simpler problem first. Put this in Makefile #1: auto: @echo this is makefile \#1 making $@ in $(PWD) And then use Makefile #2 to make target. This should produce make[1]: Entering directory 'path-to-one' this is makefile #1 making auto in path-to-one make[1]: Leaving directory 'path-to-one' If this is what it says, then there's something screwy about your script. If it produces nothing like this, you're failing to reach Makefile #1 at all, and maybe your DIR isn't right. If it works but says it's in directory #2, then my best guess is that you have another rule referring to Makefile #1. Try the experiment and let us know. EDIT: Well, that probably explains how it can leave directory #1 before the script runs. I suggest you comment out those lines and see if the problem is still there. Now about this script: what does it do and how do you know where it's running?
Invoking a python script from a makefile in another directory
I have a makefile that invokes a python script that lives in the same directory as the makefile. It works just fine. In makefile #1: auto: ./myscript.py Now, I have another makefile, in another directory, and wish to call the first makefile from it. In makefile #2: target: cd $(DIR); $(MAKE) auto; The problem is, when the script runs, it runs as though it's in the same dir as makefile #2. On stdout, I see "make[3]: Leaving directory" and the path to #1, just after the make is executed and before the script is run. On a suggestion I tried modifying makefile #2 to: target: ( cd $DIR; $MAKE auto; ) but that's interpreted as "cd IR; AKE auto". When I replace the parentheses around DIR and MAKE, I get the same behavior as before. I've tried modifying the python script by having it assume it's in dir #2 and giving it a path to #1, but the behavior doesn't change. What's going on, and what should I do? Update: My comment below messed up code formatting so it's here: I tried this out and got essentially what you describe. Might it have anything to do with the fact that target auto invokes a "makefile.rules" file? auto: @echo this is makefile \#1 making $@ in $(PWD) FLAG=1 $(MAKE) -f makefile.rules rulestargetA FLAG=2 $(MAKE) -f makefile.rules rulestargetB ./myscript.py I omitted that fact for simplicity, but now I wonder. Update 2: I don't understand why the makefiles aren't causing myscript.py to be run as though it's in the directory in which it resides, but I have been trying to get the script to operate correctly even when invoked from a different directory. It opens a couple of subprocesses, runs an executable in each subprocess, and saves the stdout from each subprocess to files. Python's subprocess.Popen passes in the current working directory, which would be where the script is invoked from, not where it resides, by default. I've added script to pass in the residential directory as cwd into the Popen call. For some reason, though, when I run myscript.py in its own directory it works, but when I invoke it from elsewhere (from the command line) it hangs in proc.communicate(). I should solve this python issue, but I'd still like to know why the external makefile can't invoke this script as from its own directory.
[ "This is very strange. First the easy part:\ntarget:\n ( cd $DIR; $MAKE auto; )\n\nThe parentheses do nothing here, and Make interprets $DIR as $D followed by the letter 'I' and the letter 'R'. Since the variable D is not defined, this works out to 'IR'. Same for $MAKE.\nNow for the real problem. The makefiles as ...
[ 0 ]
[]
[]
[ "makefile", "python" ]
stackoverflow_0003398178_makefile_python.txt
Q: pyparsing matching any combination of specified Literals Example: I have the literals "alpha", "beta", "gamma". How do I make pyparsing parse the following inputs: alpha alpha|beta beta|alpha|gamma The given input can be constructed by using one or more non-repeating literals from a given set, separated by "|". Advice on setting up pyparsing will be appreciated. A: Use the '&' operator for Each, instead of '+ or '|'. If you must have all, but in unpredicatable order use: Literal('alpha') & 'beta' & 'gamma' If some may be missing, but each used at most once, then use Optionals: Optional('alpha') & Optional('beta') & Optional('gamma') Oops, I forgot the '|' delimiters. One lenient parser would be to use a delimitedList: delimitedList(oneOf("alpha beta gamma"), '|') This would allow any or all of your choices, but does not guard against duplicates. May be simplest to use a parse action: itemlist = delimitedList(oneOf("alpha beta gamma"), '|') def ensureNoDuplicates(tokens): if len(set(tokens)) != len(tokens): raise ParseException("duplicate list entries found") itemlist.setParseAction(ensureNoDuplicates) This feels like the simplest approach to me. EDIT: Recent versions of pyparsing have introduced parse-time conditions to make this kind of parse action easier to write: itemlist = delimitedList(oneOf("alpha beta gamma"), '|') itemlist.addCondition(lambda tokens: len(set(tokens)) == len(tokens), "duplicate list entries found")
pyparsing matching any combination of specified Literals
Example: I have the literals "alpha", "beta", "gamma". How do I make pyparsing parse the following inputs: alpha alpha|beta beta|alpha|gamma The given input can be constructed by using one or more non-repeating literals from a given set, separated by "|". Advice on setting up pyparsing will be appreciated.
[ "Use the '&' operator for Each, instead of '+ or '|'. If you must have all, but in unpredicatable order use:\nLiteral('alpha') & 'beta' & 'gamma'\n\nIf some may be missing, but each used at most once, then use Optionals:\nOptional('alpha') & Optional('beta') & Optional('gamma')\n\nOops, I forgot the '|' delimiters...
[ 4 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0003398660_pyparsing_python.txt
Q: python: simple approach to killing children or reporting their success? I want to call shell commands (for example 'sleep' below) in parallel, report on their individual starts and completions and be able to kill them with 'kill -9 parent_process_pid'. There is already a lot written on these kinds of things already but I feel like I haven't quite found the elegant pythonic solution I'm looking for. I'm also trying to keep things relatively readable (and short) for someone completely unfamiliar with python. My approach so far (see code below) has been: put subprocess.call(unix_command) in a wrapper function that reports the start and completion of the command. call the wrapper function with multiprocess.Process. track the appropriate pids, store them globally, and kill them in the signal_handler. I was trying to avoid a solution that periodically polled the processes but I'm not sure why. Is there a better approach? import subprocess,multiprocessing,signal import sys,os,time def sigterm_handler(signal, frame): print 'You killed me!' for p in pids: os.kill(p,9) sys.exit(0) def sigint_handler(signal, frame): print 'You pressed Ctrl+C!' sys.exit(0) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigterm_handler) def f_wrapper(d): print str(d) + " start" p=subprocess.call(["sleep","100"]) pids.append(p.pid) print str(d) + " done" print "Starting to run things." pids=[] for i in range(5): p=multiprocessing.Process(target=f_wrapper,args=(i,)) p.daemon=True p.start() print "Got things running ..." while pids: print "Still working ..." time.sleep(1) A: Once subprocess.call returns, the sub-process is done -- and call's return value is the sub-process's returncode. So, accumulating those return codes in list pids (which btw is not synced between the multi-process appending it, and the "main" process) and sending them 9 signals "as if" they were process ids instead of return codes, is definitely wrong. Another thing with the question that's definitely wrong is the spec: be able to kill them with 'kill -9 parent_process_pid'. since the -9 means the parent process can't possibly intercept the signal (that's the purpose of explicitly specifying -9) -- I imagine the -9 is therefore spurious here. You should be using threading instead of multiprocessing (each "babysitter" thread, or process, does essentially nothing but wait for its sub-process, so why waste processes on such a lightweight task?-); you should also call suprocess.Process in the main thread (to get the sub-process started and be able to obtain its .pid to put in the list) and pass the resulting process object to the babysitter thread which waits for it (and when it's done reports and removes it from the list). The list of subprocess ids should be guarded by a lock, since the main thread and several babysitter threads can all access it, and a set would probably be a better choice than a list (faster removals) since you don't care about ordering nor about avoiding duplicates. So, roughly (no testing, so there might be bugs;-) I'd change your code to s/thing like: import subprocess, threading, signal import sys, time pobs = set() pobslock = threading.Lock() def numpobs(): with pobslock: return len(pobs) def sigterm_handler(signal, frame): print 'You killed me!' with pobslock: for p in pobs: p.kill() sys.exit(0) def sigint_handler(signal, frame): print 'You pressed Ctrl+C!' sys.exit(0) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigterm_handler) def f_wrapper(d, p): print d, 'start', p.pid rc = p.wait() with pobslock: pobs.remove(p) print d, 'done, rc =', rc print "Starting to run things." for i in range(5): p = subprocess.Popen(['sleep', '100']) with pobslock: pobs.add(p) t = threading.Thread(target=f_wrapper, args=(i, p)) t.daemon=True t.start() print "Got things running ..." while numpobs(): print "Still working ..." time.sleep(1) A: This code (code below) seems to work for me, killing from "top" or ctrl-c from the command line. The only real change from Alex's suggestions was to replace subprocess.Process with a subprocess.Popen call (I don't think subprocess.Process exists). The code here could also be improved by somehow locking stdout so that there is no chance of printing overlap between processes. import subprocess, threading, signal import sys, time pobs = set() # set to hold the active-process objects pobslock = threading.Lock() # a Lock object to make sure only one at a time can modify pobs def numpobs(): with pobslock: return len(pobs) # signal handlers def sigterm_handler(signal, frame): print 'You killed me! I will take care of the children.' with pobslock: for p in pobs: p.kill() sys.exit(0) def sigint_handler(signal, frame): print 'You pressed Ctrl+C! The children will be dealt with automatically.' sys.exit(0) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigterm_handler) # a function to watch processes def p_watch(d, p): print d, 'start', p.pid rc = p.wait() with pobslock: pobs.remove(p) print d, 'done, rc =', rc # the main code print "Starting to run things ..." for i in range(5): p = subprocess.Popen(['sleep', '4']) with pobslock: pobs.add(p) # create and start a "daemon" to watch and report the process p. t = threading.Thread(target=p_watch, args=(i, p)) t.daemon=True t.start() print "Got things running ..." while numpobs(): print "Still working ..." time.sleep(1)
python: simple approach to killing children or reporting their success?
I want to call shell commands (for example 'sleep' below) in parallel, report on their individual starts and completions and be able to kill them with 'kill -9 parent_process_pid'. There is already a lot written on these kinds of things already but I feel like I haven't quite found the elegant pythonic solution I'm looking for. I'm also trying to keep things relatively readable (and short) for someone completely unfamiliar with python. My approach so far (see code below) has been: put subprocess.call(unix_command) in a wrapper function that reports the start and completion of the command. call the wrapper function with multiprocess.Process. track the appropriate pids, store them globally, and kill them in the signal_handler. I was trying to avoid a solution that periodically polled the processes but I'm not sure why. Is there a better approach? import subprocess,multiprocessing,signal import sys,os,time def sigterm_handler(signal, frame): print 'You killed me!' for p in pids: os.kill(p,9) sys.exit(0) def sigint_handler(signal, frame): print 'You pressed Ctrl+C!' sys.exit(0) signal.signal(signal.SIGINT, sigint_handler) signal.signal(signal.SIGTERM, sigterm_handler) def f_wrapper(d): print str(d) + " start" p=subprocess.call(["sleep","100"]) pids.append(p.pid) print str(d) + " done" print "Starting to run things." pids=[] for i in range(5): p=multiprocessing.Process(target=f_wrapper,args=(i,)) p.daemon=True p.start() print "Got things running ..." while pids: print "Still working ..." time.sleep(1)
[ "Once subprocess.call returns, the sub-process is done -- and call's return value is the sub-process's returncode. So, accumulating those return codes in list pids (which btw is not synced between the multi-process appending it, and the \"main\" process) and sending them 9 signals \"as if\" they were process ids i...
[ 4, 2 ]
[]
[]
[ "multiprocessing", "parent_child", "python", "subprocess" ]
stackoverflow_0003399246_multiprocessing_parent_child_python_subprocess.txt
Q: using python, Remove HTML tags/formatting from a string I have a string that contains html markup like links, bold text, etc. I want to strip all the tags so I just have the raw text. What's the best way to do this? regex? A: If you are going to use regex: import re def striphtml(data): p = re.compile(r'<.*?>') return p.sub('', data) >>> striphtml('<a href="foo.com" class="bar">I Want This <b>text!</b></a>') 'I Want This text!' A: AFAIK using regex is a bad idea for parsing HTML, you would be better off using a HTML/XML parser like beautiful soup. A: Use lxml.html. It's much faster than BeautifulSoup and raw text is a single command. >>> import lxml.html >>> page = lxml.html.document_fromstring('<!DOCTYPE html>...</html>') >>> page.cssselect('body')[0].text_content() '...' A: Use SGMLParser. regex works in simple case. But there are a lot of intricacy with HTML you rather not have to deal with. >>> from sgmllib import SGMLParser >>> >>> class TextExtracter(SGMLParser): ... def __init__(self): ... self.text = [] ... SGMLParser.__init__(self) ... def handle_data(self, data): ... self.text.append(data) ... def getvalue(self): ... return ''.join(ex.text) ... >>> ex = TextExtracter() >>> ex.feed('<html>hello &gt; world</html>') >>> ex.getvalue() 'hello > world' A: Depending on whether the text will contain '>' or '<' I would either just make a function to remove anything between those, or use a parsing lib def cleanStrings(self, inStr): a = inStr.find('<') b = inStr.find('>') if a < 0 and b < 0: return inStr return cleanString(inStr[a:b-a])
using python, Remove HTML tags/formatting from a string
I have a string that contains html markup like links, bold text, etc. I want to strip all the tags so I just have the raw text. What's the best way to do this? regex?
[ "If you are going to use regex:\nimport re\ndef striphtml(data):\n p = re.compile(r'<.*?>')\n return p.sub('', data)\n\n>>> striphtml('<a href=\"foo.com\" class=\"bar\">I Want This <b>text!</b></a>')\n'I Want This text!'\n\n", "AFAIK using regex is a bad idea for parsing HTML, you would be better off\n usin...
[ 63, 12, 12, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003398852_python_regex.txt
Q: Overloading twisted.client.getPage to set the client socket's bindaddress ! For the past 10 hours I've been trying to accomplish this: Translation of my blocking httpclient using standard lib... Into a twisted nonblocking/async version of it. 10 hours later... scoring through their APIs-- it appears no one has EVER needed to do be able to do that. Nice framework, but seems ...a bit overwhelming to just set a socket to a different interface. Can any python gurus shed some light on this and/or send me in the right direction? or any docs that I could have missed? THANKS! A: Well, it doesn't look like you've missed anything. client.getPage doesn't directly support setting the bind address. I'm just guessing here but I would suspect it's one of those cases where it just never occured to the original developer that someone would want to specify the bind address. Even though there isn't built-in support for doing this, it should be pretty easy to do. The way you specify binding addresses for outgoing connections in twisted is by passing the bind address to the reactor.connectXXX() functions. Fortunately, the code for getPage() is really simple. I'd suggest three things: Copy the code for getPage() and it's associated helper function into your project Modify them to pass through the bind address Create a patch to fix this oversight and send it to the Twisted folks :)
Overloading twisted.client.getPage to set the client socket's bindaddress !
For the past 10 hours I've been trying to accomplish this: Translation of my blocking httpclient using standard lib... Into a twisted nonblocking/async version of it. 10 hours later... scoring through their APIs-- it appears no one has EVER needed to do be able to do that. Nice framework, but seems ...a bit overwhelming to just set a socket to a different interface. Can any python gurus shed some light on this and/or send me in the right direction? or any docs that I could have missed? THANKS!
[ "Well, it doesn't look like you've missed anything. client.getPage doesn't directly support setting the bind address. I'm just guessing here but I would suspect it's one of those cases where it just never occured to the original developer that someone would want to specify the bind address. \nEven though there isn'...
[ 0 ]
[]
[]
[ "python", "twisted.web" ]
stackoverflow_0003399185_python_twisted.web.txt
Q: In Django, correctly making a queryset with multiple categories, multiple tags and search? I have a list of data. This data model has many-to-many fields to both a categories model and a keywords model. The data model itself has a name and description. The data can have multiple categories and keywords. On the front end, the user can select a number of categories to filter down the data or do a search... So the data shown should be any data with any of the categories selected. If 'Test Data 1' has the category 'A' and 'Test Data 2' has the category 'B', if the user selects to see category 'A' and 'B', then both the pieces of data will show. The search is meant to search for data within the title, description and the keywords associated with the data, if any categories are selected, it will search within what data is left after the categories have been queried. I'm not an expert at Django here... I'm trying to work out the best way to do this. I don't want to resort to using something like Haystack etc, as my data is pretty simple really. I've found that doing .filter() on objects is basically giving me an AND in the underlying SQL, which is not ideal for the way the categories work. It seems I need some sort of OR... maybe? The category selection on the front end is done with a form and so the data that comes back is basically a list of the categories selected ['A', 'B', 'C']... is there no way I can drop that into a queryset in Django and returns all the data that has one or any of these categories? Many thanks! A: Not sure what you mean here. You can try something along these lines: from django.db.models import Q query = 'fun' books = Fun.objects.filter(Q(categories__id__in=[1,2,3]), Q(name__icontains=query) | \ Q(description__icontains=query) | \ Q(keywords__title__icontains=query)) http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
In Django, correctly making a queryset with multiple categories, multiple tags and search?
I have a list of data. This data model has many-to-many fields to both a categories model and a keywords model. The data model itself has a name and description. The data can have multiple categories and keywords. On the front end, the user can select a number of categories to filter down the data or do a search... So the data shown should be any data with any of the categories selected. If 'Test Data 1' has the category 'A' and 'Test Data 2' has the category 'B', if the user selects to see category 'A' and 'B', then both the pieces of data will show. The search is meant to search for data within the title, description and the keywords associated with the data, if any categories are selected, it will search within what data is left after the categories have been queried. I'm not an expert at Django here... I'm trying to work out the best way to do this. I don't want to resort to using something like Haystack etc, as my data is pretty simple really. I've found that doing .filter() on objects is basically giving me an AND in the underlying SQL, which is not ideal for the way the categories work. It seems I need some sort of OR... maybe? The category selection on the front end is done with a form and so the data that comes back is basically a list of the categories selected ['A', 'B', 'C']... is there no way I can drop that into a queryset in Django and returns all the data that has one or any of these categories? Many thanks!
[ "Not sure what you mean here. You can try something along these lines:\nfrom django.db.models import Q\n\nquery = 'fun'\nbooks = Fun.objects.filter(Q(categories__id__in=[1,2,3]),\n Q(name__icontains=query) | \\\n Q(description__icontains=query) | \\\n Q(ke...
[ 1 ]
[]
[]
[ "django", "django_queryset", "python", "sql" ]
stackoverflow_0003397170_django_django_queryset_python_sql.txt
Q: python: comparing this row with next row c1 is a list of lists like this: c1=[[1,2,3],[1,2,6],[7,8,6]] for row in c1: i want to keep track of whether there is a change in row[0] for example: in [1, 2, 3] and [1, 2, 6] there is no change in row[0] however in [1, 2, 6] and [ 7, 8, 6] there is a change in row[0] how do i catch this change? also i would like to know which row this changed occurred at A: If you had matrix data you basically want a diff of the first "column". You probably want to report the changes and the location of the changes and probably want to store them sparsely: c1=[[1,2,3],[1,2,6],[7,8,6]] ans=[] # a list of [indices,differences] col=0 for i in range(len(c1)-1): diff = c1[i+1][col]-c1[i][col] if diff!=0: ans.append([i,diff]) A: Use a variable to keep track of the previous item. prev = None for row in c1: if prev is not None and prev != row[0]: # there is a change prev = row[0] ...just make sure you use a nonexistent value as the starting value (if your lists may contain anything, use an extra flag for the first item). If you want the first row to be considered a change, change the if to: if prev is None or prev != row[0]: A: >>> from operator import itemgetter >>> from itertools import groupby >>> c1=[[1,2,3],[1,2,6],[7,8,6]] >>> list(groupby(c1,itemgetter(0))) [(1, <itertools._grouper object at 0xa6f8d0>), (7, <itertools._grouper object at 0xa6f890>)] this is simply saying group the elements of c1 by the first item of each element You can also expand the result as a nested list to see how the items are grouped >>> [(x,list(y)) for x,y in (groupby(c1,itemgetter(0)))] [(1, [[1, 2, 3], [1, 2, 6]]), (7, [[7, 8, 6]])] to get the row of the change, you can look at the length of the first element of the result >>> len(list(next(groupby(c1,itemgetter(0)))[1])) 2 A: I've posted this as a separate answer to avoid making the other answer too jumbled >>> for i in range(1,len(c1)): ... if c1[i-1][0]!=c[i][0]: break ... >>> print i 2 A: Print a list of all rows with a different first element than its predecessor: import itertools c1=[[1,2,3],[1,2,6],[7,8,6]] xs, ys = itertools.tee(c1) next(ys) print [y for x, y in itertools.izip(xs, ys) if x[0] != y[0]]
python: comparing this row with next row
c1 is a list of lists like this: c1=[[1,2,3],[1,2,6],[7,8,6]] for row in c1: i want to keep track of whether there is a change in row[0] for example: in [1, 2, 3] and [1, 2, 6] there is no change in row[0] however in [1, 2, 6] and [ 7, 8, 6] there is a change in row[0] how do i catch this change? also i would like to know which row this changed occurred at
[ "If you had matrix data you basically want a diff of the first \"column\". \nYou probably want to report the changes and the location of the changes and probably want to store them sparsely:\nc1=[[1,2,3],[1,2,6],[7,8,6]]\nans=[] # a list of [indices,differences]\ncol=0\nfor i in range(len(c1)-1):\n diff = c1[...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003398879_list_python.txt
Q: How do I emulate a dynamically sized C structure in Python using ctypes I'm writing some python code to interact with a C DLL that uses structures extensively. One of those structures contains nested structures. I know that this is not a problem for the ctypes module. The problem is that there is an often used structure that, in C, is defined via macro because it contains an "static" length array that can vary. That is confusing so here's some code struct VarHdr { int size; } #define VAR(size) \ struct Var { VarHdr hdr; unsigned char Array[(size)]; } Then it is used in other structures like this struct MySruct { int foo; VAR(20) stuffArray; } The question then becomes how can I emulate this in Python in a way that the resulting structure can be passed back and forth between my pythong script and the DLL. BTW, I know that I can just hardcode the number in there but there are several instances of this "VAR" throughout that have different sizes. A: Just use a factory to define the structure once the size is known. http://docs.python.org/library/ctypes.html#variable-sized-data-types: Another way to use variable-sized data types with ctypes is to use the dynamic nature of Python, and (re-)define the data type after the required size is already known, on a case by case basis. (untested) Example: def define_var_hdr(size): class Var(Structure): fields = [("size", c_int), ("Array", c_ubyte * size)] return Var var_class_10 = define_var_hdr(10) var_class_20 = define_var_hdr(20) var_instance_10 = var_class_10() var_instance_20 = var_class_20()
How do I emulate a dynamically sized C structure in Python using ctypes
I'm writing some python code to interact with a C DLL that uses structures extensively. One of those structures contains nested structures. I know that this is not a problem for the ctypes module. The problem is that there is an often used structure that, in C, is defined via macro because it contains an "static" length array that can vary. That is confusing so here's some code struct VarHdr { int size; } #define VAR(size) \ struct Var { VarHdr hdr; unsigned char Array[(size)]; } Then it is used in other structures like this struct MySruct { int foo; VAR(20) stuffArray; } The question then becomes how can I emulate this in Python in a way that the resulting structure can be passed back and forth between my pythong script and the DLL. BTW, I know that I can just hardcode the number in there but there are several instances of this "VAR" throughout that have different sizes.
[ "Just use a factory to define the structure once the size is known.\nhttp://docs.python.org/library/ctypes.html#variable-sized-data-types:\n\nAnother way to use variable-sized data\n types with ctypes is to use the\n dynamic nature of Python, and\n (re-)define the data type after the\n required size is already ...
[ 7 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0003400495_c_ctypes_python.txt
Q: How to perform: Upload Image > Recognize Text > Make Image Searchable > Store into DB? I need to know how to perform the procedure, you already have read in the title. You'll upload an image (e.g. a piece of text, an article) and on server-side the text will be recognized via OCR and stored into a database. Which would be the best programming language for it? It should be a browser application. I found the ocropus project, but how can I combine it to common web scripting languages like PHP? Is it possible at all? Didn't have worked with Python yet. Or a totally different approach..? Java Enterprise? Let's rock that, Chris A: maybe you can use this php library i use for recognize text from images and store the text readed into database http://www.phpclasses.org/browse/package/2874/download/targz.html download the rar package and run example.php and then example1.php to see how it works here you have an image upload example: http://www.reconn.us/content/view/30/51/ hope this helps
How to perform: Upload Image > Recognize Text > Make Image Searchable > Store into DB?
I need to know how to perform the procedure, you already have read in the title. You'll upload an image (e.g. a piece of text, an article) and on server-side the text will be recognized via OCR and stored into a database. Which would be the best programming language for it? It should be a browser application. I found the ocropus project, but how can I combine it to common web scripting languages like PHP? Is it possible at all? Didn't have worked with Python yet. Or a totally different approach..? Java Enterprise? Let's rock that, Chris
[ "maybe you can use this php library i use for recognize text from images and store the text readed into database\nhttp://www.phpclasses.org/browse/package/2874/download/targz.html\ndownload the rar package and run example.php and then example1.php to see how it works\nhere you have an image upload example:\nhttp://...
[ 1 ]
[]
[]
[ "java", "ocr", "php", "python" ]
stackoverflow_0003399738_java_ocr_php_python.txt
Q: Simultaneous eval and exec Is there a way to get python to do an evaluation and execution on a string? I have a file which contains a bunch of expressions that need to be calculated, maybe something like this. f1(ifilter(myfilter,x)) f2(x)*f3(f4(x)+f5(x)) I run through the file and eval the expressions. Some of the expressions may want to save their work after doing an expensive operation y = g(x); h(y)+j(y) Unfortunately, y=g(x) requires an exec, but getting the value of h+j is an eval. How does this work? A: Try using the builtin compile(). When you use it in single mode it handles both of the cases that you want. For example: compile('3+4','<dummy>','single') will return a compiled code object. You can execute it with exec() or eval() : >>> exec(compile('3+4','<dummy>','single')) 7 >>> exec(compile('x=3+4','<dummy>','single')) >>> print x 7
Simultaneous eval and exec
Is there a way to get python to do an evaluation and execution on a string? I have a file which contains a bunch of expressions that need to be calculated, maybe something like this. f1(ifilter(myfilter,x)) f2(x)*f3(f4(x)+f5(x)) I run through the file and eval the expressions. Some of the expressions may want to save their work after doing an expensive operation y = g(x); h(y)+j(y) Unfortunately, y=g(x) requires an exec, but getting the value of h+j is an eval. How does this work?
[ "Try using the builtin compile(). When you use it in single mode it handles both of the cases that you want. For example:\ncompile('3+4','<dummy>','single')\n\nwill return a compiled code object. You can execute it with exec() or eval() :\n>>> exec(compile('3+4','<dummy>','single'))\n7\n>>> exec(compile('x=3+4','<d...
[ 1 ]
[]
[]
[ "eval", "exec", "python" ]
stackoverflow_0003400738_eval_exec_python.txt
Q: Getting only 1 decimal place How do I convert 45.34531 to 45.3? A: Are you trying to represent it with only one digit: print("{:.1f}".format(number)) # Python3 print "%.1f" % number # Python2 or actually round off the other decimal places? round(number,1) or even round strictly down? math.floor(number*10)/10 A: >>> "{:.1f}".format(45.34531) '45.3' Or use the builtin round: >>> round(45.34531, 1) 45.299999999999997 A: round(number, 1)
Getting only 1 decimal place
How do I convert 45.34531 to 45.3?
[ "Are you trying to represent it with only one digit:\nprint(\"{:.1f}\".format(number)) # Python3\nprint \"%.1f\" % number # Python2\n\nor actually round off the other decimal places?\nround(number,1)\n\nor even round strictly down?\nmath.floor(number*10)/10\n\n", ">>> \"{:.1f}\".format(45.34531)\n'45.3'\...
[ 225, 37, 17 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0003400965_python_rounding.txt
Q: Prototyping a filesystem What are some best practises for prototyping a filesystem? I've had an attempt in Python using fusepy, and now I'm curious: In the long run, should any respectable filesystem implementation be in C? Will not being in C hamper portability, or eventually cause performance issues? Are there other implementations like FUSE? Evidently core filesystem technology moves slowly (fat32, ext3, ntfs, everything else is small fish), what debugging techniques are employed? What is the general course filesystem development takes in arriving at a highly optimized, fully supported implementation in major OSs? A: A filesystem that lives in userspace (be that in FUSE or the Mac version thereof) is a very handy thing indeed, but will not have the same performance as a traditional one that lives in kernel space (and thus must be in C). You could say that's the reason that microkernel systems (where filesystems and other things live in userspace) never really "left monolithic kernels in the dust" as A. Tanenbaum so assuredly stated when he attacked Linux in a famous posting on the Minix mailing list almost twenty years ago (as a CS professor, he said he'd fail Linus for choosing a monolithic architecture for his OS -- Linus of course responded spiritedly, and the whole exchange is now pretty famous and can be found in many spots on the web;-). Portability's not really a problem, unless perhaps you're targeting "embedded" devices with very limited amounts of memory -- with the exception of such devices, you can run Python where you can run C (if anything it's the availability of FUSE that will limit you, not that of a Python runtime). But performance could definitely be. A: In the long run, should any respectable filesystem implementation be in C? Will not being in C hamper portability, or eventually cause performance issues? Not necessarily, there are plenty of performing languages different to C (O'Caml, C++ are the first that come to mind.) In fact, I expect NTFS to be written in C++. Thing is you seem to come from a Linux background, and as the Linux kernel is written in C, any filesystem with hopes to be merged into the kernel has to be written in C as well. Are there other implementations like FUSE? There are a couple for Windows, for example, http://code.google.com/p/winflux/ and http://dokan-dev.net/en/ in various maturity levels Evidently core filesystem technology moves slowly (fat32, ext3, ntfs, everything else is small fish), what debugging techniques are employed? Again, that is mostly true in Windows, in Solaris you have ZFS, and in Linux ext4 and btrfs exist. Debugging techniques usually involve turning machines off in the middle of various operations and see in what state data is left, storing huge amounts of data and see performance. What is the general course filesystem development takes in arriving at a highly optimized, fully supported implementation in major OSs? Again, this depends on which OS, but it does involve a fair amount of testing, especially making sure that failures do not lose data. A: I recommend you create a mock object for the kernel block device API layer. The mock layer should use a mmap'd file as a backing store for the file system. There are a lot of benefits for doing this: Extremely fast FS performance for running unit test cases. Ability to insert debug code/break points into the mock layer to check for failure conditions. Easy to save multiple copies of the file system state for study or running test cases. Ability to deterministically introduce block device errors or other system events that the file system will have to handle. A: Respectable filesystems will be fast and efficient. For Linux, that will basically mean writing in C, because you won't be taken seriously if you're not distributed with the kernel. As for other tools like Fuse, There's MacFUSE, which will allow you to use the same code on macs as well as linux.
Prototyping a filesystem
What are some best practises for prototyping a filesystem? I've had an attempt in Python using fusepy, and now I'm curious: In the long run, should any respectable filesystem implementation be in C? Will not being in C hamper portability, or eventually cause performance issues? Are there other implementations like FUSE? Evidently core filesystem technology moves slowly (fat32, ext3, ntfs, everything else is small fish), what debugging techniques are employed? What is the general course filesystem development takes in arriving at a highly optimized, fully supported implementation in major OSs?
[ "A filesystem that lives in userspace (be that in FUSE or the Mac version thereof) is a very handy thing indeed, but will not have the same performance as a traditional one that lives in kernel space (and thus must be in C). You could say that's the reason that microkernel systems (where filesystems and other thin...
[ 4, 2, 1, 0 ]
[]
[]
[ "c", "filesystems", "fuse", "python" ]
stackoverflow_0003340945_c_filesystems_fuse_python.txt
Q: Way in Python to make vars visible in calling method scope? I find myself doing something like this constantly to pull GET args into vars: some_var = self.request.get('some_var', None) other_var = self.request.get('other_var', None) if None in [some_var, other_var]: logging.error("some arg was missing in " + self.request.path) exit() What I would really want to do is: pull_args('some_var', 'other_var') And that would somehow pull these variables to be available in current scope, or log an error and exit if not (or return to calling method if possible). Is this possible in Python? A: No it's not and also pointless. Writing to outer namespaces completely destroys the purpose of namespaces, which is having only the things around that you explicitly set. Use lists! def pull_args(*names): return [self.request.get(name, None) for name in names] print None in pull_args('some_var', 'other_var') Probably this works too, to check if all _var are set: print all(name in self.request for name in ('some_var', 'other_var')) A: First, a disclaimer: "pulling" variables into the local scope in any way other than var = something is really really really not recommended. It tends to make your code really confusing for someone who isn't intimately familiar with what you're doing (i.e. anyone who isn't you, or who is you 6 months in the future, etc.) That being said, for educational purposes only, there is a way. Your pull_args function could be implemented like this: def pull_args(request, *args): pulled = {} try: for a in args: pulled[a] = request[a] except AttributeError: logging.error("some arg was missing in " + self.request.path) exit() else: caller = inspect.stack()[1][0] caller.f_locals.update(pulled) At least, something to that effect worked when I came up with it probably about a year ago. I wouldn't necessarily count on it continuing to work in future Python versions. (Yet another reason not to do it) I personally have never found a good reason to use this code snippet.
Way in Python to make vars visible in calling method scope?
I find myself doing something like this constantly to pull GET args into vars: some_var = self.request.get('some_var', None) other_var = self.request.get('other_var', None) if None in [some_var, other_var]: logging.error("some arg was missing in " + self.request.path) exit() What I would really want to do is: pull_args('some_var', 'other_var') And that would somehow pull these variables to be available in current scope, or log an error and exit if not (or return to calling method if possible). Is this possible in Python?
[ "No it's not and also pointless. Writing to outer namespaces completely destroys the purpose of namespaces, which is having only the things around that you explicitly set. Use lists!\ndef pull_args(*names):\n return [self.request.get(name, None) for name in names]\n\nprint None in pull_args('some_var', 'other_va...
[ 3, 3 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0003401048_python_scope.txt
Q: need help with sort function in python The contents of my dictionary is like so:- >>> dict {'6279': '45', '15752': '47', '5231': '30', '475': '40'} I tried using the sort function on the keys. I noticed that the sort function doesn't work for the key -- 15752. Please find below:- >>> [k for k in sorted(dict.keys())] ['15752', '475', '5231', '6279'] Could someone point out a way for me to work around this? Thanks My expected output is:- ['475', '5231', '6279', '15752'] A: ah you want to sort by the numeric value not the string so you should convert the strings to numbers using int(s) at some point prior or just use sorted(dict.keys(), key=int) A: If they're ALL ints, sorted(dict, lambda x, y: cmp(int(x), int(y))) A: If my guess in my comment was right and you want the numeric keys sorted change your line of code to this: sorted([int(k) for k in test.keys()]) # returns [475, 5231, 6279, 15752] A: If you want to sort numerically then store numbers in your dictionary not strings then it will just work >>> dict {6279: '45', 15752: '47', 5231: '30', 475: '40'}
need help with sort function in python
The contents of my dictionary is like so:- >>> dict {'6279': '45', '15752': '47', '5231': '30', '475': '40'} I tried using the sort function on the keys. I noticed that the sort function doesn't work for the key -- 15752. Please find below:- >>> [k for k in sorted(dict.keys())] ['15752', '475', '5231', '6279'] Could someone point out a way for me to work around this? Thanks My expected output is:- ['475', '5231', '6279', '15752']
[ "ah you want to sort by the numeric value not the string so you should convert the strings to numbers using int(s) at some point prior or just use sorted(dict.keys(), key=int)\n", "If they're ALL ints,\nsorted(dict, lambda x, y: cmp(int(x), int(y)))\n\n", "If my guess in my comment was right and you want the nu...
[ 10, 3, 2, 1 ]
[]
[]
[ "dictionary", "key", "python", "sorting" ]
stackoverflow_0003401123_dictionary_key_python_sorting.txt
Q: A python module for global parameters - is this good practice? I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: main.py callback.py helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: main.py callback.py helper.py parameters.py and all scripts have: import parameters and use: parameters.foo or parameters.bar. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav A: Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code from becoming a tangled mess. Clear communication between files makes them easier to understand and makes what's going on more obvious. When you're using variables and nobody knows where they came from, things can get pretty annoying. :) A: Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure. A: I try to design my code so that it looks much like a pyramid. That, I have found, leads to cleaner code. A: I'm not too sure about if that's good practice but if you use classes, I don't see why there should be a problem. Or am I missing something? If you want to be able to just run each script independently too, and that's what is keeping you from going object oriented then you could do something like the following at the end of your script. if __name__ == '__main__': # Code that you want to run when the script is executed. # This block will not be executed if the script is imported. Read more about classes in Python here. A: You should probably read up on Dependency Inversion. A: Seems like what you want is to organize various dependencies between components. You will be better off expressing these dependencies in an object-oriented manner. Rather than doing it by importing modules and global states, encode these states in objects and pass those around. Read up on objects and classes and how to write them in Python; I'd probably start there.
A python module for global parameters - is this good practice?
I'm a mechanical engineering student, and I'm building a physical simulation using PyODE. instead of running everything from one file, I wanted to organize stuff in modules so I had: main.py callback.py helper.py I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper! so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random). so I now have: main.py callback.py helper.py parameters.py and all scripts have: import parameters and use: parameters.foo or parameters.bar. Is this an acceptable practice or is this a sure fire way to make python programmers puke? :) Please let me know if this makes sense, or if there is a more sensible way of doing it! Thanks, -Leav
[ "Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your c...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003400847_python.txt
Q: Splitting a list I've scoured various resources and can't figure out how to do a rather simple operation. Right now, I have a list as follows: li = [['a=b'],['c=d']] I want to transform this into: li = [['a','b'],['c','d']] As I understand it, split("=") only applies to string types. Is there an equivalent method for lists? Pardon the simplicity of my question... -Dan A: You want this: [x[0].split('=') for x in li] # prints [['a', 'b'], ['c', 'd']] To grab a question from a comment further down the post, the reason split works for x[0] is that x represents the inner list. That's accomplished by the for x in li. Also, I fixed mine to read for x in li and not for x in test as I had assigned your examples to a variable called 'test' on my system. A: You can use map(): >>> li = [['a=b'],['c=d']] >>> map(lambda x: x[0].split('='), li) [['a', 'b'], ['c', 'd']] This traverses the list li and applies the lambda function to every element. As every element of the list is again a list with one element, x[0] takes this element, which is a string, splits it and returns a new list with both values. A: Warning - its been a while since I did any python, but your issue is more general. You are correct in that split applies to strings. What you need to do is split the VALUE contained in your list not the list itself. So you would do something like newValue = split('=', li[0][0]) li[0] = newValue A: Is this what you are looking for ? map(lambda y:y.split('='),map(lambda x:x[0], li)) A: Presuming each sublist consists of individual strings of the form a=b: >>> [el[i].split('=') for el in li for i in range(len(el))] [['a', 'b'], ['c', 'd']] (Indeed, what you're splitting is the inner string a=b. So the split() string method works fine.) EDIT: A much more elegant way of doing this double list comprehension is: >>> [a.split('=') for el in li for a in el] [['a', 'b'], ['c', 'd']] There have been a number of good suggestions made, so the OP should be able to learn a good amount of Python for it. Important to remember is that what is being split is li[i][j], ie an item of the list that is an item of the list li. A: You can do it with this: [k[0].split("=") for k in li]
Splitting a list
I've scoured various resources and can't figure out how to do a rather simple operation. Right now, I have a list as follows: li = [['a=b'],['c=d']] I want to transform this into: li = [['a','b'],['c','d']] As I understand it, split("=") only applies to string types. Is there an equivalent method for lists? Pardon the simplicity of my question... -Dan
[ "You want this:\n[x[0].split('=') for x in li]\n# prints [['a', 'b'], ['c', 'd']]\n\nTo grab a question from a comment further down the post, the reason split works for x[0] is that x represents the inner list. That's accomplished by the for x in li. Also, I fixed mine to read for x in li and not for x in test as...
[ 9, 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003401154_python.txt
Q: How do I disable default Tkinter key commands? I'd like to implement my own key command. However when I do, it does both what I tell it and the default command. How do I disable the default command, so that my command is the only one that runs? This is on Windows 7, BTW. A: Put return 'break' at the end of your event handling function. This tells Tkinter not to propagate the event to default handlers.
How do I disable default Tkinter key commands?
I'd like to implement my own key command. However when I do, it does both what I tell it and the default command. How do I disable the default command, so that my command is the only one that runs? This is on Windows 7, BTW.
[ "Put return 'break' at the end of your event handling function. This tells Tkinter not to propagate the event to default handlers.\n" ]
[ 2 ]
[]
[]
[ "keyboard_shortcuts", "python", "tkinter", "windows" ]
stackoverflow_0003400622_keyboard_shortcuts_python_tkinter_windows.txt