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' Yo...
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 instal...
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...
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 "_____in...
[ "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...
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 the...
[ "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...
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 ...
[ "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: ...
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() ...
[ "@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 ...
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....
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 tr...
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 i...
[ "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 ...
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 f...
[ "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. H...
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...
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 uni...
[ "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 represen...
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 'an...
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 ...
[ "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 the...
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...
[ "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 modifi...
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 cre...
[ "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 ...
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 M...
[ "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...
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 ...
[ "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, ...
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, ...
[ "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 boo...
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 P...
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 i...
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(obje...
[ "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 ...
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 sm...
[ "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...
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 e...
[ "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 does...
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 Reasona...
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 ...
[ "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? ...
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'...
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 include...
[ "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 th...
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 initiali...
[ "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") ...
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(...
[ "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.C...
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...
[ "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 inte...
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...
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 progr...
[ "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 ...
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 interi...
[ "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 ab...
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 wou...
[ "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? >...
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 >...
[ "\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...
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 ...
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 t...
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__": ...
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...
[ "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....
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...
[ "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 ...
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 oth...
[ "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 ...
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 f...
[ "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 di...
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. How...
[ "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 ...
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 c...
[ "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'), ...
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_le...
[ "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() ...
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 successfu...
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.goo...
[ "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 predictab...
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: asd4sa5d8s5s5d5s...
[ "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....
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, ...
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 def...
[ "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_nu...
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]...
[ "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_an...
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 tha...
[ "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 b...
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 grou...
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 s...
[ "\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: '...
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 sequ...
[ "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 nu...
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 d...
[ "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 ...
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 ...
[ "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...
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...
[ "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 ...
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 defin...
[ "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,...
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, si...
[ "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...
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...
[ "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('u...
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 p...
[ "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/...
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. ...
[ "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 fir...
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: ...
[ "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. Anyon...
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 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...
[ 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 disp...
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 t...
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]; ...
[ "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 ...
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 ...
[ "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 ...
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 filena...
[ "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", Inte...
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):...
[ "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 b...
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...
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 firs...
[ "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 ...
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__ =...
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__ func...
[ "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: P...
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, ...
[ "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.To...
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'...
[ "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...
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 m...
[ "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 th...
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 trie...
[ "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 ...
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,...
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]) ...
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 t...
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 ...
[ "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....
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...
[ "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 "|". A...
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 a...
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'...
[ "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'<.*?...
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 EV...
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 overwhelmi...
[ "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 fro...
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 ...
[ "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] ho...
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...
[ "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 s...
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" len...
[ "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 ...
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 t...
[ "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 ...
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...
[ "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...
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 the...
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 ...
[ "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 " + s...
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: ...
[ "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(...
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 ...
[ "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 t...
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 ...
[ "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 meth...
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 t...
[ "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 you...
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