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: PHP and Python unpack return different results from same source I cannot seem to get even vaguely the same data from the Python (Which I would prefer to use) and PHP (Which works fine, coded by the host of the website) scripts. PHP connects to the same location as the Python script. And before anyone jumps the gun...
PHP and Python unpack return different results from same source
I cannot seem to get even vaguely the same data from the Python (Which I would prefer to use) and PHP (Which works fine, coded by the host of the website) scripts. PHP connects to the same location as the Python script. And before anyone jumps the gun, I know the python script only retrieves a part of the data. But I c...
[ "You're not sending the same query to your server in python.\nIn python you're sending status\nIn PHP you're sending something like \\x00\\x83\\x00\\x0d\\x00\\x00\\x00\\x00\\x00\\x00?status\\x00 \nIf you change your python to more closely imitate the PHP then it works a lot better:\nimport socket, struct\n\nhost,po...
[ 2, 0 ]
[]
[]
[ "php", "python", "sockets", "struct", "unpack" ]
stackoverflow_0008342702_php_python_sockets_struct_unpack.txt
Q: Create an instance, I already have the type class ClassA: pass mytype = type(ClassA) Using mytype, how do you create an instance of ClassA? Note that I'm NOT looking for this as my answer :) instance = ClassA() I know that in this example, that's all you need to do but suppose that you have this type (mytype), y...
Create an instance, I already have the type
class ClassA: pass mytype = type(ClassA) Using mytype, how do you create an instance of ClassA? Note that I'm NOT looking for this as my answer :) instance = ClassA() I know that in this example, that's all you need to do but suppose that you have this type (mytype), you don't know anything about it, and you need to ...
[ "If you use a new style class it, this will work:\nclass ClassA(object):\n pass\n\no = ClassA()\nmytype = type(o)\nnew_object = mytype()\n\n", "Is lazyr says, it is not possible with type. Maybe what you could use is something like\nclass ClassA: pass\nmyclass = ClassA\ninstance = myclass()\n\n", "This quest...
[ 42, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008421199_python.txt
Q: Number bound to function name There is code: def somefun(): print "hi" print somefun Result is: <function somefun at 0x0153DDF0> What's 0x0153DDF0? A: This is the result of a call to repr - the number in question is the address of the function in memory. According to the doc for repr: [...] the representa...
Number bound to function name
There is code: def somefun(): print "hi" print somefun Result is: <function somefun at 0x0153DDF0> What's 0x0153DDF0?
[ "This is the result of a call to repr - the number in question is the address of the function in memory.\nAccording to the doc for repr:\n\n[...] the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name a...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008421407_python.txt
Q: what is pythonic way to communicate between modules? let's assume following C code: // events.h enum Events {eOne, eTwo, eThree}; enum Events getEvent(void); ... //ctrl.c #include "events.h" void ctrl(void) { switch(getEvent()) { case eOne: // ... break; case eTwo: // .....
what is pythonic way to communicate between modules?
let's assume following C code: // events.h enum Events {eOne, eTwo, eThree}; enum Events getEvent(void); ... //ctrl.c #include "events.h" void ctrl(void) { switch(getEvent()) { case eOne: // ... break; case eTwo: // ... break; case eThree: // ... b...
[ "class Animal:\n DOG=1\n CAT=2\n\nx = Animal.DOG\n\nsource: How can I represent an 'Enum' in Python?\n", "The following Python code is similar to how your C code interacts. To use variables from another module you need to first import that module.\n// events.py\nclass Events:\n eOne, eTwo, eThree = rang...
[ 2, 2, 0 ]
[]
[]
[ "implementation", "interface", "python" ]
stackoverflow_0008421624_implementation_interface_python.txt
Q: Numpy with python 3.0 NumPy installer can't find python path in the registry. Cannot install Python version 2.6 required, which was not found in the registry. Is there a numpy build which can be used with python 3.0? A: Guido van Rossum (creator of Python) says he is keen to see NumPy work in Python 3.x, bec...
Numpy with python 3.0
NumPy installer can't find python path in the registry. Cannot install Python version 2.6 required, which was not found in the registry. Is there a numpy build which can be used with python 3.0?
[ "Guido van Rossum (creator of Python) says he is keen to see NumPy work in Python 3.x, because it would enable many dependent libraries to move to 3.x.\nUpdate 2010-08-05: NumPy version 1.5 supports Python 3.x, and SciPy will soon. NumPy 1.5 beta is available for download now.\nUpdate 2012-05-31: SciPy 0.10.0 added...
[ 46, 11, 7, 7 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0002231842_numpy_python_python_3.x.txt
Q: Creating Lists in Python I can parse a file that looks like: <a href="http://www.youtube.com/watch?v=DpQNMBzwShs"></a> but when I give it just: http://www.youtube.com/watch?v=DpQNMBzwShs It errors. How do I turn soup into a list skipping the # extract youtube video urls process entirely, which is what I think I ...
Creating Lists in Python
I can parse a file that looks like: <a href="http://www.youtube.com/watch?v=DpQNMBzwShs"></a> but when I give it just: http://www.youtube.com/watch?v=DpQNMBzwShs It errors. How do I turn soup into a list skipping the # extract youtube video urls process entirely, which is what I think I need to do? # parse bookmarks....
[ "Your question - as it is - is quite puzzling: beautifulsoup is used to parse an XML trees, but you seem you are trying to parse a simple text file instead?\nIf this is the case, assuming the file has one URL per line you simply have to load it line by line and assign its content to urls\nurls = open('<your-filenam...
[ 2 ]
[]
[]
[ "beautifulsoup", "list", "python", "youtube", "youtube_api" ]
stackoverflow_0008421796_beautifulsoup_list_python_youtube_youtube_api.txt
Q: Python: PyPy: SciPy/Chi-square distribution? I have a Python project where performance is fairly important. Honestly, I know Python (at least pure Python) isn't the best tool for the job, but I'm using it anyhow because I want to distribute a very simple pure python version of some research code so that people ca...
Python: PyPy: SciPy/Chi-square distribution?
I have a Python project where performance is fairly important. Honestly, I know Python (at least pure Python) isn't the best tool for the job, but I'm using it anyhow because I want to distribute a very simple pure python version of some research code so that people can modify it, etc. without having to set up a compl...
[ "SciPy does not work on PyPy yet, although there is some work to make it happen relatively soonish, provided you're willing to use nightly and make little adjustments so you use only the supported subset of numpy (that expands rapidly anyway). I would suggest you simply try porting the SciPy functions to Python for...
[ 5 ]
[]
[]
[ "libraries", "performance", "pypy", "python", "statistics" ]
stackoverflow_0008420627_libraries_performance_pypy_python_statistics.txt
Q: Error when installing ssdeep on windows I try to install the ssdeep python bindings on windows, but it crashes when running build_ext. Any idea what I'm missing? >c:\Python26\python.exe setup.py install running install running bdist_egg running egg_info writing ssdeep.egg-info\PKG-INFO writ...
Error when installing ssdeep on windows
I try to install the ssdeep python bindings on windows, but it crashes when running build_ext. Any idea what I'm missing? >c:\Python26\python.exe setup.py install running install running bdist_egg running egg_info writing ssdeep.egg-info\PKG-INFO writing top-level names to ssdeep.egg-info\top_le...
[ ". is the command to source a file in a POSIX-compatible shell. Either install cygwin to get bash or another POSIX-compatible shell, or manually rewrite depcomp (and potentially configure) to work with your shell.\n" ]
[ 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0008421971_python_windows.txt
Q: Xpath select attribute of current node? I use python with lxml to process the xml. After I query/filter to get to a nodes I want but I have some problem. How to get its attribute's value by xpath ? Here is my input example. >print(etree.tostring(node, pretty_print=True )) <rdf:li xmlns:rdf="http://www.w3.org/1999/...
Xpath select attribute of current node?
I use python with lxml to process the xml. After I query/filter to get to a nodes I want but I have some problem. How to get its attribute's value by xpath ? Here is my input example. >print(etree.tostring(node, pretty_print=True )) <rdf:li xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" rdf:resource="urn:miri...
[ "Prefix the attribute name with @ in the XPath query:\n>>> from lxml import etree\n>>> xml = \"\"\"\\\n... <?xml version=\"1.0\" encoding=\"utf8\"?>\n... <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n... <rdf:li rdf:resource=\"urn:miriam:obo.chebi:CHEBI%3A37671\"/>\n... </rdf:RDF>\n... \"...
[ 3, 1, 0 ]
[]
[]
[ "attributes", "python", "sbml", "xpath" ]
stackoverflow_0008409306_attributes_python_sbml_xpath.txt
Q: Eventlet and Python daemon, Foo not called? I am trying to build a Python deamon which listen to a queue (Redis Kombu). Grab the task and spawn a greenthread to process this task. I can receive the task and consume it without trouble but when I try to spawn a GreenThread with eventlet it does not seem to be doing ...
Eventlet and Python daemon, Foo not called?
I am trying to build a Python deamon which listen to a queue (Redis Kombu). Grab the task and spawn a greenthread to process this task. I can receive the task and consume it without trouble but when I try to spawn a GreenThread with eventlet it does not seem to be doing anything at all. No print, no logging is shown. c...
[ "I needed to call eventlet.monkey_patch() for sleep() call to trigger context switching.\n", "You just need to use eventlet.sleep as described here:\nhttp://eventlet.net/doc/basic_usage.html#eventlet.sleep\n" ]
[ 3, 2 ]
[]
[]
[ "coroutine", "eventlet", "python", "queue" ]
stackoverflow_0006595317_coroutine_eventlet_python_queue.txt
Q: How to implement tags in webapp? I am trying to make a basic quotation-sharing app using Webapp. Obviously it is crucial to be able to give arbitrary tags to each quote. So here are the relevant code that I've come up with: (Mostly from the example chat app in the great introductory book 'Using Google App Engine'...
How to implement tags in webapp?
I am trying to make a basic quotation-sharing app using Webapp. Obviously it is crucial to be able to give arbitrary tags to each quote. So here are the relevant code that I've come up with: (Mostly from the example chat app in the great introductory book 'Using Google App Engine' ) class Quote(db.Model): user = d...
[ "Try using split() to turn tgs into a list of words before creating your Quote. Tags should be separated by whitespace in your form, otherwise you can add an argument to split if you'd rather separate them by something else.\n...\ntgs = self.request.get('tags').split()\nnewq = Quote(user = self.session['userkey'], ...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "tags", "web_applications" ]
stackoverflow_0008422220_google_app_engine_python_tags_web_applications.txt
Q: Can I Increase the Number of Log Entries in Google App Engine? (python) Is it possible to increase the number of log "entries" that google app engine stores? I mean the entries that are available in the online dashboard under the "Logs" link. I can roll my own logging system using the database, but it's not my pre...
Can I Increase the Number of Log Entries in Google App Engine? (python)
Is it possible to increase the number of log "entries" that google app engine stores? I mean the entries that are available in the online dashboard under the "Logs" link. I can roll my own logging system using the database, but it's not my preference, as using the built in logging module is easiest by far.
[ "There's no setting to increase the amount of history App Engine will store for logs. You could, however, run a local cron job to pull logs down from the server. appcfg.py will download the logs, eg.\nappcfg.py request_logs appid/ appidlogs.txt\n\nDocs are here: http://code.google.com/appengine/docs/python/tools/up...
[ 2 ]
[]
[]
[ "google_app_engine", "logging", "python" ]
stackoverflow_0008421056_google_app_engine_logging_python.txt
Q: Force python to ignore pyc files when dynamically loading modules from filepaths I need to import python modules by filepath (e.g., "/some/path/to/module.py") known only at runtime and ignore any .pyc files should they exist. This previous question suggests the use of imp.load_module as a solution but this approac...
Force python to ignore pyc files when dynamically loading modules from filepaths
I need to import python modules by filepath (e.g., "/some/path/to/module.py") known only at runtime and ignore any .pyc files should they exist. This previous question suggests the use of imp.load_module as a solution but this approach also appears to use a .pyc version if it exists. importme.py SOME_SETTING = 4 main....
[ "load_source does the right thing for me, i.e. \ndir, name = os.path.split(path)\nmod = imp.load_source(name, path)\n\nuses the .py variant even if a pyc file is available - name ends in .py under python3. The obvious solution is obviously to delete all .pyc files before loading the file - the race condition may be...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008421773_python.txt
Q: Python YouTube Gdata API broken after small change I changed how my script was getting it's list and somehow I broke the Gdata-API sys.argv[1] is a text file of urls like this The error starts when I comment out Part 1 & 2 and Add 3. When I Remove 3 and Uncomment Part 1 & 2 it works again. Relevant code: # PART 1...
Python YouTube Gdata API broken after small change
I changed how my script was getting it's list and somehow I broke the Gdata-API sys.argv[1] is a text file of urls like this The error starts when I comment out Part 1 & 2 and Add 3. When I Remove 3 and Uncomment Part 1 & 2 it works again. Relevant code: # PART 1 - parse bookmarks.html #with open(sys.argv[1]) as bookm...
[ "I assigned urls to be:\nurls = ['http://www.youtube.com/watch?v=_wmD3M-BfVo']\n\n(Yeah, it's T-Pain music video)\nAnd it worked just fine. You most likely have a problem with the file you're opening or the parsing of the contents of that file. Or you just plain aren't parsing it right. In any event, you're getting...
[ 1 ]
[]
[]
[ "python", "youtube", "youtube_api" ]
stackoverflow_0008422302_python_youtube_youtube_api.txt
Q: tastypie authentication / custom response Are there any examples of using the APIKey authentication in tastypie. The example provided doesn't really go into detail on how it works. Also I was looking through the cookbook trying to find where there is a hook for returning custom messages on a post. For example some...
tastypie authentication / custom response
Are there any examples of using the APIKey authentication in tastypie. The example provided doesn't really go into detail on how it works. Also I was looking through the cookbook trying to find where there is a hook for returning custom messages on a post. For example someone does a post to try to create a user but the...
[ "you can do that this way:\nfrom tastypie.exceptions import ImmediateHttpResponse\nfrom tastypie.http import HttpBadRequest\n\nif test_fails:\n raise ImmediateHttpResponse(HttpBadRequest(\"User already exists\"))\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "rest", "tastypie" ]
stackoverflow_0007424703_django_python_rest_tastypie.txt
Q: using python 2.7 : sh: -c: line 0: syntax error near unexpected token `(' Python 2.7 I am getting the following error message. Not clear as to why this is. I have searched and no luck. Fairly basic script. Has worked across all our windows environments #!/usr/bin/env python import os import time import subprocess...
using python 2.7 : sh: -c: line 0: syntax error near unexpected token `('
Python 2.7 I am getting the following error message. Not clear as to why this is. I have searched and no luck. Fairly basic script. Has worked across all our windows environments #!/usr/bin/env python import os import time import subprocess import platform #Log Files source = ['"/home/datatec/ds/datos"' ] #Backup t...
[ "os.system executes an argument in a subshell, where braces have special meanings. You should use subprocess instead.\nBut the immediate error is caused by the quotes in\ntarget = \"target_dir + os.sep + time.strftime('%Y%m%d') + platform.node() + '.zip'\"\n\nThis line should almost certainly be\ntarget = target_di...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008422758_python.txt
Q: Converting a list of tuples of different sizes into a dictionary I have a list of tuples and want to turn this list into a dictionary. However, the tuples can be larger than 2 and not the same size. I would like the first element of each tuple to be the key and the rest to be stored as a array for the value. l = ...
Converting a list of tuples of different sizes into a dictionary
I have a list of tuples and want to turn this list into a dictionary. However, the tuples can be larger than 2 and not the same size. I would like the first element of each tuple to be the key and the rest to be stored as a array for the value. l = [(1,'a','b'),(2,'c'),(3,'d','e','f')] Just doing d=dict(l) doesn't wo...
[ "d = dict( (v[0], v[1:]) for v in arr )\n\n", "Winston Ewert has the best (most portable) answer. As an alternative — if you have a recent version of Python — you can use dictionary comprehensions:\nd = { t[0]:t[1:] for t in arr }\n\n" ]
[ 8, 7 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0008423003_data_structures_python.txt
Q: Topia Term Extract - Italian Lexicon I'm looking for a tool to extract topic keywords from text. Topia seems to be a good solutions, anyway it does not came with an italian-lexicon file. Searching on the web i couldn't find a precompiled file, so I guess I need to build my own. Does anyone have suggestion on how t...
Topia Term Extract - Italian Lexicon
I'm looking for a tool to extract topic keywords from text. Topia seems to be a good solutions, anyway it does not came with an italian-lexicon file. Searching on the web i couldn't find a precompiled file, so I guess I need to build my own. Does anyone have suggestion on how to build it without spending a lifetime? Th...
[ "NLP resources for Italian:\n\nhttp://aclweb.org/aclwiki/index.php?title=Resources_for_Italian\n\nOf special interest to you are the lexicons and taggers.\nAnother lexicon:\n\nhttp://aune.lpl.univ-aix.fr/projects/multext/LEX/LEX.SmpIt.html\n\n" ]
[ 1 ]
[]
[]
[ "nlp", "pos_tagger", "python" ]
stackoverflow_0008416433_nlp_pos_tagger_python.txt
Q: Django - consume XML - RESTful I have a python script running fine on my localhost. Its not an enterprise app or anything, just something I'm playing around with. It uses the "bottle" library. The app basically consumes an XML file (stored either locally or online) which contains elements with their own unique IDs...
Django - consume XML - RESTful
I have a python script running fine on my localhost. Its not an enterprise app or anything, just something I'm playing around with. It uses the "bottle" library. The app basically consumes an XML file (stored either locally or online) which contains elements with their own unique IDs, as well as some coordinates, eg my...
[ "I took your question as an opportunity to learn a bit more about Django. I used The Django Book as a reference.\nStarting with an empty Django site (django-admin.py startproject testsite), I've changed urls.py to this:\nfrom django.conf.urls.defaults import patterns, include, url\nfrom testsite.views import index\...
[ 1 ]
[]
[]
[ "bottle", "django", "python", "rest" ]
stackoverflow_0005464450_bottle_django_python_rest.txt
Q: How to tell whether imaplib2 idle response resulted from timeout I'm using imaplib2 (docs) to interact with an IMAP server. I'm using the idle command, with a timeout and a callback. The problem is, I don't see any way of telling if the callback was triggered by the timeout being reached, or if there was a change ...
How to tell whether imaplib2 idle response resulted from timeout
I'm using imaplib2 (docs) to interact with an IMAP server. I'm using the idle command, with a timeout and a callback. The problem is, I don't see any way of telling if the callback was triggered by the timeout being reached, or if there was a change on the server that I need to check out. I just get ('OK', ['IDLE termi...
[ "Piers Lauder (author of imaplib2) just answered this question on the imaplib2-devel mailing list. He said:\n\nI think the way to test if an IDLE has timed out is to execute:\ninstance.response('IDLE')\n\nwhich will return:\n('IDLE', ['TIMEOUT'])\n\nif the reason that the idle returned as a timeout, rather than\n ...
[ 4, 0 ]
[]
[]
[ "imap", "imaplib", "python", "python_idle", "timeout" ]
stackoverflow_0005359134_imap_imaplib_python_python_idle_timeout.txt
Q: Seed() and Random Numbers in Python Today, I was just told about the seed() function from a programmer much more experienced than me. I normally just call choice() with a list as an argument, as I don't need anymore random number functionality than that. My programmer friend told me that calling seed is necessary ...
Seed() and Random Numbers in Python
Today, I was just told about the seed() function from a programmer much more experienced than me. I normally just call choice() with a list as an argument, as I don't need anymore random number functionality than that. My programmer friend told me that calling seed is necessary because otherwise Python always begins ra...
[ "Your friend is dead wrong, and would know so if he read the documentation for the seed() function:\n\nInitialize the basic random number generator. Optional argument x can be any hashable object. If x is omitted or None, current system time is used; current system time is also used to initialize the generator when...
[ 29 ]
[]
[]
[ "python", "random" ]
stackoverflow_0008423288_python_random.txt
Q: PySide application isn't working on other computers when bundled with py2app I have a small application I'm trying to bundle with py2app. At first I ran into a problem with PySide not linking correctly once bundled, but I fixed that (locally, at least) by adding sys.path.insert(0, os.path.join(os.getcwd(), 'lib', ...
PySide application isn't working on other computers when bundled with py2app
I have a small application I'm trying to bundle with py2app. At first I ran into a problem with PySide not linking correctly once bundled, but I fixed that (locally, at least) by adding sys.path.insert(0, os.path.join(os.getcwd(), 'lib', 'python2.6','lib-dynload')) to __boot__.py in the final build's container. Once bu...
[ "In options, you should add\n'includes': 'PySide'\nIf this doesn't work, sometimes I find importing the needed modules at the top of the setup script helps.\nSo change:\nfrom setuptools import setup\n\nto\nfrom setuptools import setup\nimport PySide\n\n" ]
[ 0 ]
[]
[]
[ "macos", "py2app", "pyside", "python" ]
stackoverflow_0008423396_macos_py2app_pyside_python.txt
Q: Remap inferior-python-mode C-z key to python quit rather than emacs suspend or undo So here's a technical question on how to exit from the current job of the inferior-python interpreter. Normally, C-z does the trick if I run the interpreter in a regular command shell. This calls python exit and whatever is runnin...
Remap inferior-python-mode C-z key to python quit rather than emacs suspend or undo
So here's a technical question on how to exit from the current job of the inferior-python interpreter. Normally, C-z does the trick if I run the interpreter in a regular command shell. This calls python exit and whatever is running stops. The interpreter process is still alive. However, in emacs when I press C-z in th...
[ "When running an inferior process, you generally can send control sequences with the C-c prefix. With that in mind, try\nC-c C-z\n\nWhich, for me, is bound to comint-stop-subjob.\n" ]
[ 1 ]
[]
[]
[ "emacs", "python", "python_mode" ]
stackoverflow_0008421295_emacs_python_python_mode.txt
Q: Better way of passing form parameters into hidden form in Pyramid In a previous question, I was trying to figure out the right strategy for to passing data between forms in Pyramid. Based on the answer I received, I decided the approach of using a hidden form. I started implementing this and think there must be a...
Better way of passing form parameters into hidden form in Pyramid
In a previous question, I was trying to figure out the right strategy for to passing data between forms in Pyramid. Based on the answer I received, I decided the approach of using a hidden form. I started implementing this and think there must be a better way of passing along the data. Specifically, passing parameters...
[ "The idea with this method is:\n\nClient visits page.\nServer renders the form.\nClient fills in form and POSTs to URL.\nServer renders a new page that contains a hidden form with all of the data it just received in the POST.\nClient POSTs to a URL, confirming the submission.\nServer persists the data from the hidd...
[ 4 ]
[]
[]
[ "forms", "pyramid", "python" ]
stackoverflow_0008423679_forms_pyramid_python.txt
Q: websocket handshake problem I'm using python to implement a simple websocket server. The handshake I'm using comes from http://en.wikipedia.org/w/index.php?title=WebSockets&oldid=372387414. The handshake itself seems to work, but when I hit send, I get a javascript error: Uncaught Error: INVALID_STATE_ERR: DOM Ex...
websocket handshake problem
I'm using python to implement a simple websocket server. The handshake I'm using comes from http://en.wikipedia.org/w/index.php?title=WebSockets&oldid=372387414. The handshake itself seems to work, but when I hit send, I get a javascript error: Uncaught Error: INVALID_STATE_ERR: DOM Exception 11 Here's the html: <!do...
[ "I tested your code on Firefox 4 and got the same error upon hitting send, however before that I got \n\nFirefox can't establish a connection\n to the server at ws://localhost:8888/.\n\nwhich is probably why the WebSocket object was destroyed. I suspect your handshake response is missing something, so Firefox is c...
[ 6, 0 ]
[]
[]
[ "javascript", "python", "websocket" ]
stackoverflow_0003220547_javascript_python_websocket.txt
Q: Avoid 0 and others to count as False In Python, there are several values that count as False: >>> if False or None or 0 or 0.0 or '' or [] or {} or set(): ... print 'True :)' ... else: ... print 'False :(' ... False :( So, somewhere in my code I'm doing something like this: some_var = other_var or 'defau...
Avoid 0 and others to count as False
In Python, there are several values that count as False: >>> if False or None or 0 or 0.0 or '' or [] or {} or set(): ... print 'True :)' ... else: ... print 'False :(' ... False :( So, somewhere in my code I'm doing something like this: some_var = other_var or 'default' # Some default value other_var could ...
[ "There is the Conditional Expression (aka the \"ternary operator\") syntax:\nsome_var = 'default' if other_var is None else other_var\n\nHappy coding.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0008423957_python.txt
Q: SPARQL parameterized queries Good day! I apply rdflib for python. I have a question. How can I put variable into SPARQL's query ? Instead of 'OSPF' in course:OSPF! qres = g.query( """SELECT ?x ?z ?y WHERE { course:OSPF course:termName ?x. course:OSPF ?s ?t. ?s ?d ?z. ...
SPARQL parameterized queries
Good day! I apply rdflib for python. I have a question. How can I put variable into SPARQL's query ? Instead of 'OSPF' in course:OSPF! qres = g.query( """SELECT ?x ?z ?y WHERE { course:OSPF course:termName ?x. course:OSPF ?s ?t. ?s ?d ?z. ?t course:termName ?y. ...
[ "If you mean a Python variable in the query you could do just ...\nqres = g.query(\n \"\"\"SELECT ?x ?z ?y\n WHERE {\n \"\"\"+some_uri+\"\"\" course:termName ?x.\n \"\"\"+some_uri+\"\"\" ?s ?t.\n ?s ?d ?z.\n ?t course:termName ?y.\n FILTER (regex(?z,\"[^a-...
[ 3 ]
[]
[]
[ "parameterized_query", "python", "rdflib", "sparql" ]
stackoverflow_0008422401_parameterized_query_python_rdflib_sparql.txt
Q: Accessing return value of function passed directly into another in Python I'm testing out a simple sample PyGTK application based on the code in another SO question: How to set default button in PyGTK?. However, I'm trying to figure out how to access the value that the run() function returns. I know that it is pas...
Accessing return value of function passed directly into another in Python
I'm testing out a simple sample PyGTK application based on the code in another SO question: How to set default button in PyGTK?. However, I'm trying to figure out how to access the value that the run() function returns. I know that it is passed into button.connect() and the other arguments are passed to run() when it i...
[ "You should use class. Something like this (this is not complete code):\nclass Demo:\n def __init__(self):\n self.__snooze_time = None\n self.window = gtk.Window()\n self.window.connect(\"destroy\", gtk.main_quit)\n self.button = gtk.Button(stock = gtk.STOCK_SAVE)\n\n self.button.co...
[ 2 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0008424257_pygtk_python.txt
Q: How to get text from dialog box in unix using pexpect? I have a shell script script here as below: #!/bin/bash CPUSELECTION="1 386SX off \ 2 386DX on \ 3 486SX off \ 4 486DX off " #dialog --backtitle "Select CPU" --radiolist "Select the cpu" 10 40 4 $CPUSELECTION echo $CPU...
How to get text from dialog box in unix using pexpect?
I have a shell script script here as below: #!/bin/bash CPUSELECTION="1 386SX off \ 2 386DX on \ 3 486SX off \ 4 486DX off " #dialog --backtitle "Select CPU" --radiolist "Select the cpu" 10 40 4 $CPUSELECTION echo $CPUSELECTION now my py file is import pexpect child = pexpect...
[ "The junk output that you're seeing is ANSI escape codes. You can strip them out with something like this:\nansi_codes = re.compile('\\033\\[[0-9;]+m')\ndef strip_ansi(with_ansi):\n return ansi_codes.sub('', with_ansi)\n\nthen, you can use\nstrip_ansi(child.before)\n\nand you'll just see the text. It will still ...
[ 3 ]
[]
[]
[ "dialog", "pexpect", "python", "shell", "unix" ]
stackoverflow_0008395839_dialog_pexpect_python_shell_unix.txt
Q: Extract just email headers in python I'm having some issues trying to extract all the email headers in python. I know how to get the ones I'm looking for but I want to save all the headers and I'm not sure how to do that. I have it loaded into a email object import email f = open(kwargs['opt_emailfile']) msg = ema...
Extract just email headers in python
I'm having some issues trying to extract all the email headers in python. I know how to get the ones I'm looking for but I want to save all the headers and I'm not sure how to do that. I have it loaded into a email object import email f = open(kwargs['opt_emailfile']) msg = email.message_from_file(f) f.close() So I ca...
[ "Using HeaderParser perhaps:\nfrom email.parser import HeaderParser\nparser = HeaderParser()\nh = parser.parsestr(email)\n\nprint h.keys()\n\nI just noticed you edited your question. You can actually get the same information from what you had without using HeaderParser. e.g. headers.items() will return list of 2-tu...
[ 26 ]
[]
[]
[ "email", "header", "python" ]
stackoverflow_0008424317_email_header_python.txt
Q: python string formatting fixed width I want to put a bunch of floating point numbers into a fixed-width table. That is, I want a maximum of 12 characters used. I want a minimum of 10 decimals used (if available); however, if 10 decimals makes it take up more than 12 characters, then round. My original thought was ...
python string formatting fixed width
I want to put a bunch of floating point numbers into a fixed-width table. That is, I want a maximum of 12 characters used. I want a minimum of 10 decimals used (if available); however, if 10 decimals makes it take up more than 12 characters, then round. My original thought was to try something like this # I only want 1...
[ "I'm not sure this is what you are looking for, since it's not accomplished entirely with the format string, however, you could just use string slicing to lop-off the trailing chars when things get too long:\nnum1 = 0.04154721841\nnum2 = 10.04154721841\nnum3 = 1002.04154721841\n\nprint \"{0:<12.11g}\".format(num1)[...
[ 6 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0008424474_formatting_python_string.txt
Q: Why can't I properly read 32bit registry values in HKCU on 64bit machine? I'm stumped on a windows 7 registry problem and while various questions and answers get me some of the way there, nothings I've seen addresses my particular issue. I don't know if other windows versions affects this problem, but we all have...
Why can't I properly read 32bit registry values in HKCU on 64bit machine?
I'm stumped on a windows 7 registry problem and while various questions and answers get me some of the way there, nothings I've seen addresses my particular issue. I don't know if other windows versions affects this problem, but we all have win7x64 machines. We have a wide variety of tools at our work, some C++, some ...
[ "I understand from the comments on the question that this issue has gone away, for anyone else that encounters this question, you can use Microsoft.Win32.OpenBaseKey to specify whether to open the 64 or 32-bit portion of the registry when running on a 64-bit machine even if your process is running as a 32-bit proce...
[ 4 ]
[]
[]
[ "c#", "python", "registry", "windows_7" ]
stackoverflow_0008216472_c#_python_registry_windows_7.txt
Q: Python curl usage inconsistency I have a python script that is using curl to post a file into a SOLR collection. The command looks like this, solrURL = "http://mySolr:8983/solr/solrdatabase/update/csv?commit=true --data-binary @+"fileName" -H 'Content-type:text/xml; charset=utf-8'" print "=====SOLR URL=====" print...
Python curl usage inconsistency
I have a python script that is using curl to post a file into a SOLR collection. The command looks like this, solrURL = "http://mySolr:8983/solr/solrdatabase/update/csv?commit=true --data-binary @+"fileName" -H 'Content-type:text/xml; charset=utf-8'" print "=====SOLR URL=====" print solrURL print "=====SENDING TO SOLR=...
[ "If you're passing a list into subprocess.call, you should separate the args into individual elements in the string:\nsolrURL = \"http://mySolr:8983/solr/solrdatabase/update/csv?commit=true\"\nsubprocess.call(['curl', '-v', solrURL, '--data-binary', '@+\"fileName\"', '-H', 'Content-type:text/xml; charset=utf-8'])\...
[ 2 ]
[]
[]
[ "python", "python_2.x", "solr" ]
stackoverflow_0008424642_python_python_2.x_solr.txt
Q: How to ignore blank rows in a csv file I'm using dictreader to open some csv files, adding them to one big list of dictionaries, and then using dictwriter to write the list of dictionaries out to one csv file. The problem I'm having is that the resultant csv file has a bunch of blank rows between rows with data. I...
How to ignore blank rows in a csv file
I'm using dictreader to open some csv files, adding them to one big list of dictionaries, and then using dictwriter to write the list of dictionaries out to one csv file. The problem I'm having is that the resultant csv file has a bunch of blank rows between rows with data. I guess when the csv files are being read, it...
[ "You can read a fake file object that skips the blank lines in the real file. I'm not familiar with exactly what you're doing, but this will work better than mac's answer if the blank lines are making your reading process crash, or you really don't want the blank lines ever in there.\nclass BlankLineSkipper(object)...
[ 4, 3, 0 ]
[]
[]
[ "csv", "file", "python" ]
stackoverflow_0008422250_csv_file_python.txt
Q: Weirdness with mongoengine ReferenceField This is a puzzling problem that's difficult even to name, let alone describe. I'll start with the essential facts and then give what background information might be relevant. Consider two mongoengine document models: class Bar(Document): # ... # field definitions ...
Weirdness with mongoengine ReferenceField
This is a puzzling problem that's difficult even to name, let alone describe. I'll start with the essential facts and then give what background information might be relevant. Consider two mongoengine document models: class Bar(Document): # ... # field definitions # ... def bar_func(self): pass ...
[ "Are you using embedded mode or daemon mode of mod_wsgi? If using daemon mode of mod_wsgi are you delegating each site to a different daemon process group and then in turn forcing the application to run in main Python interpreter?\nIt may be the case that mongodb Python client module may not work properly in Python...
[ 4 ]
[]
[]
[ "django", "mod_wsgi", "mongoengine", "python" ]
stackoverflow_0008424033_django_mod_wsgi_mongoengine_python.txt
Q: The best way to filter a dictionary in Python I have a dictionary of string keys and float values. mydict = {} mydict["joe"] = 20 mydict["bill"] = 20.232 mydict["tom"] = 0.0 I want to filter the dictionary to only include pairs that have a value greater than zero. In C#, I would do something like this: di...
The best way to filter a dictionary in Python
I have a dictionary of string keys and float values. mydict = {} mydict["joe"] = 20 mydict["bill"] = 20.232 mydict["tom"] = 0.0 I want to filter the dictionary to only include pairs that have a value greater than zero. In C#, I would do something like this: dict = dict.Where(r=>r.Value > 0); What is the equiv...
[ "d = dict((k, v) for k, v in d.iteritems() if v > 0)\n\nIn Python 2.7 and up, there's nicer syntax for this:\nd = {k: v for k, v in d.items() if v > 0}\n\nNote that this is not strictly a filter because it does create a new dictionary.\n", "Assuming your original dictionary is d1 you could use something like:\nd2...
[ 45, 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "lambda", "python" ]
stackoverflow_0008425046_dictionary_lambda_python.txt
Q: Python - Read in binary file over SSH With Python, I need to read a file into a script similar to open(file,"rb"). However, the file is on a server that I can access through SSH. Any suggestions on how I can easily do this? I am trying to avoid paramiko and am using pexpect to log into the SSH server, so a method ...
Python - Read in binary file over SSH
With Python, I need to read a file into a script similar to open(file,"rb"). However, the file is on a server that I can access through SSH. Any suggestions on how I can easily do this? I am trying to avoid paramiko and am using pexpect to log into the SSH server, so a method using pexpect would be ideal. Thanks, Eric
[ "You can mount the remote file system to local by using sshfs, then you can use is like normal file. The fuse module is needed by the sshfs.\n", "If it's a short file you can get output of ssh command using subprocess.Popen\nssh root@ip_address_of_the_server 'cat /path/to/your/file'\nNote: Password less setup usi...
[ 1, 0 ]
[]
[]
[ "pexpect", "python", "ssh" ]
stackoverflow_0008425089_pexpect_python_ssh.txt
Q: Python XML-RPC server as a Windows service I'm trying to create an XML-RPC server as a windows service. The XML-RPC server is able to get and put files (like FTP) and also execute commands via os.system() that the remote client sends to it. I'm trying the encapsulate the server in the windows service event loop....
Python XML-RPC server as a Windows service
I'm trying to create an XML-RPC server as a windows service. The XML-RPC server is able to get and put files (like FTP) and also execute commands via os.system() that the remote client sends to it. I'm trying the encapsulate the server in the windows service event loop. When creating the service there is no problem...
[ "It looks like you are missing a call to self.ReportServiceStatus(win32service.SERVICE_STOPPED) at the end of your SvcStop method.\n", "David K. Hess deserves credit for this one.\nHe suggested I add the following after line 142 in class XMLRPCServerService, def SvcStop: \n self.ReportServiceStatus(win32s...
[ 4, 3 ]
[]
[]
[ "http", "python", "xml_rpc" ]
stackoverflow_0008409608_http_python_xml_rpc.txt
Q: Biomorph Implementation in Python I'm trying to create a Python implementation of Dawkins' biomorphs as described in his book, The Blind Watchmaker. It works like this: A parent organism is displayed, as well as its offspring which are just mutated versions of the parent. Then the user clicks on a descendant it wa...
Biomorph Implementation in Python
I'm trying to create a Python implementation of Dawkins' biomorphs as described in his book, The Blind Watchmaker. It works like this: A parent organism is displayed, as well as its offspring which are just mutated versions of the parent. Then the user clicks on a descendant it wants to breed, and all the offspring wil...
[ "Depending on graphical requirements, I would say that for a lightweight app you could get away with PyQt or PyGame. For more demanding real-time graphical requirements you could use something like PyOgre or PyOpenGL.\nYou may need to also research graph-layout/data-visualisation algorithms or libraries (e.g. dot) ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008299966_python.txt
Q: Indefinite daemonized process spawning in Python I'm trying to build a Python daemon that launches other fully independent processes. The general idea is for a given shell command, poll every few seconds and ensure that exactly k instances of the command are running. We keep a directory of pidfiles, and when we p...
Indefinite daemonized process spawning in Python
I'm trying to build a Python daemon that launches other fully independent processes. The general idea is for a given shell command, poll every few seconds and ensure that exactly k instances of the command are running. We keep a directory of pidfiles, and when we poll we remove pidfiles whose pids are no longer runnin...
[ "Thanks to your list of processes I'm willing to say that this is because you have hit one of a number of fundamental limitations:\n\nrlimit nproc maximum number of processes a given user is allowed to execute -- see setrlimit(2), the bash(1) ulimit built-in, and /etc/security/limits.conf for details on per-user pr...
[ 5, 3 ]
[]
[]
[ "daemon", "fork", "python", "spawn", "subprocess" ]
stackoverflow_0008425116_daemon_fork_python_spawn_subprocess.txt
Q: Ordered classes in Python 3 I am trying to use an 'ordered class' as described in PEP 3115 (that is, a class whose members can be accessed in the order they were declared). The implementation given there is # The custom dictionary class member_table(dict): def __init__(self): self.member_names = [] ...
Ordered classes in Python 3
I am trying to use an 'ordered class' as described in PEP 3115 (that is, a class whose members can be accessed in the order they were declared). The implementation given there is # The custom dictionary class member_table(dict): def __init__(self): self.member_names = [] def __setitem__(self, key, val...
[ "\nFirstly, is there a reason why __prepare__ is a classmethod? The definition doesn't use metacls - is this just a convention?\n\nAs pointed out in the comments, when __prepare__ is called the class itself is not yet instantiated. That means, if it where an ordinary method (with self as the first parameter) - the...
[ 5 ]
[]
[]
[ "metaclass", "prepare", "python", "python_3.x" ]
stackoverflow_0008249312_metaclass_prepare_python_python_3.x.txt
Q: PySide: Can't get QPainter() to save it's state and restore it on new paintEvent I'm trying to make a very basic image creator using PySide. But I'm having some troubles to draw things. This is the portion of my script responsible for the draw area: class Area(QWidget): global x1 global y1 global x2 g...
PySide: Can't get QPainter() to save it's state and restore it on new paintEvent
I'm trying to make a very basic image creator using PySide. But I'm having some troubles to draw things. This is the portion of my script responsible for the draw area: class Area(QWidget): global x1 global y1 global x2 global y2 try: x1 except NameError: x1=0 try: y1 except N...
[ "The paintEvent() method is repainting the entire widget every time it is called. The drawing from the previous calls is completely replaced with the results of each future paintEvent() call.\nIf you want the effect you are describing, you will need to accumulate the points and draw the entire sequence of them each...
[ 1, 1 ]
[]
[]
[ "pyside", "python", "qt" ]
stackoverflow_0008425218_pyside_python_qt.txt
Q: Get raw input as an option? So I'm fairly new to python in general, mostly use it to move files around easily, and what I've been doing lately was using raw_input to get a name to pass on as a directory name variable. But I say getopt and figured it would save time and effort to just try and get that variable that...
Get raw input as an option?
So I'm fairly new to python in general, mostly use it to move files around easily, and what I've been doing lately was using raw_input to get a name to pass on as a directory name variable. But I say getopt and figured it would save time and effort to just try and get that variable that raw_input prompts the user for a...
[ "If you have Python >= 2.7, use the argparse module (it's part of the standard library).\nIf you have 2.3 <= Python < 2.7 install the argparse module. \nSince the future of Python is headed toward or already using the argparse module, it would behoove you to use that instead of one of the older modules (like optpar...
[ 3, 2 ]
[]
[]
[ "getopt", "python" ]
stackoverflow_0008425602_getopt_python.txt
Q: reassigning row/list in a 2d list in python I was trying to create an 2d list in python that was x + 1,y + 1 sized and had some initial values. Those initial values are that the first row contains the numbers 0 to 'x' and the first column contains the numbers 0 to 'y' (both inclusively) Lets say x and y were 3 and...
reassigning row/list in a 2d list in python
I was trying to create an 2d list in python that was x + 1,y + 1 sized and had some initial values. Those initial values are that the first row contains the numbers 0 to 'x' and the first column contains the numbers 0 to 'y' (both inclusively) Lets say x and y were 3 and 4. So I went: listName = [range(0, x + 1)] *...
[ "Slice-assign in order to modify the existing list, instead of just rebinding the name.\nrow[:] = ...\n\nAlso, you're constructing it incorrectly.\nlistName = [range(0, x + 1) for z in range(y + 1)]\n\n", "When you assign a list to a name you're effectively instantiating a new list. Python has a special syntax th...
[ 1, 0, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0008425720_list_comprehension_python.txt
Q: Highlighting a clicked line in an unfocused Tkinter text widget I'd like to keep focus on the entry text widget, which will pass whatever's entered into a separate display text widget. I have that part working. I can't figure out how to make it so that when someone clicks on the display text widget the line click...
Highlighting a clicked line in an unfocused Tkinter text widget
I'd like to keep focus on the entry text widget, which will pass whatever's entered into a separate display text widget. I have that part working. I can't figure out how to make it so that when someone clicks on the display text widget the line clicked is highlighted (or the line changes background color) but focus is...
[ "You can get the index of the start of the line where you clicked by using something like this:\nline_start = self.OutWidget.index(\"@%s,%s linestart\" % (event.x, event.y))\n\nYou can add highlighting by applying a tag to that line with something like this:\nline_end = self.OutWidget.index(\"%s lineend\" % line_st...
[ 4 ]
[]
[]
[ "python", "tkinter", "widget" ]
stackoverflow_0008422942_python_tkinter_widget.txt
Q: python multithreading and print for Windows I have been directed to turn code which has been using threading.Thread to now use multiprocessing.Process my main problem is I am using Windows and these subfunctions expect to be able to print on to the Python Shell (IDLE) does anyone have experience of how to do it? m...
python multithreading and print for Windows
I have been directed to turn code which has been using threading.Thread to now use multiprocessing.Process my main problem is I am using Windows and these subfunctions expect to be able to print on to the Python Shell (IDLE) does anyone have experience of how to do it? my thoughts at the moment: subclass the multiproce...
[ "Do you need the output interleaved as it happens, or is it okay for the output to come in a single lump? If the latter, then you can write something which captures stdout/stderr and sends the result back as in:\nclass CapturedException(Exception):\n def __init__(self, stdout_text, stderr_text, exc):\n self.std...
[ 0 ]
[]
[]
[ "multiprocessing", "pipe", "python", "stdout", "windows" ]
stackoverflow_0008424956_multiprocessing_pipe_python_stdout_windows.txt
Q: Check for Event Daily, and Send Notification Messages What is the best way to set up a system that checks for events daily and sends messages via email, Twitter, SMS, and possibly Facebook? Keep in mind, that I do not have access to a web server with root access (Using Rackspace Cloud). Would PHP have a solution f...
Check for Event Daily, and Send Notification Messages
What is the best way to set up a system that checks for events daily and sends messages via email, Twitter, SMS, and possibly Facebook? Keep in mind, that I do not have access to a web server with root access (Using Rackspace Cloud). Would PHP have a solution for this? Would there be any drawbacks to using Google App E...
[ "If you are using Google App Engine with Python you could use \"Cron\" to schedule a task to automatically run each day.\nGAE also allows you to send emails, just a little tip: make sure that you 'invite' the email address used to send mail to the application as an administrator so that you can programatically send...
[ 1 ]
[]
[]
[ "google_app_engine", "php", "python" ]
stackoverflow_0007535544_google_app_engine_php_python.txt
Q: Convert HTML to PDF in python on Google App Engine I have had a look at this thread: How to dynamically generate a pdf from Google's appengine? I know we can use ReportLab, however, I am not sure how i can give it a HTML file and get a PDF. Basically, HTML in and PDF out A: if you can use an external lib, there ...
Convert HTML to PDF in python on Google App Engine
I have had a look at this thread: How to dynamically generate a pdf from Google's appengine? I know we can use ReportLab, however, I am not sure how i can give it a HTML file and get a PDF. Basically, HTML in and PDF out
[ "if you can use an external lib, there is xhtml2pdf\n", "Try this: html-2-pdf.com\nIt's build in top of: wkhtmltopdf\nIt's really easy to use it. It's stand-alone so just upload a file on your (Linux) system and you are ready to produce PDFs\n", "xhtml2pdf states that the source is pure python. you should be ab...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "html", "pdf_generation", "python" ]
stackoverflow_0003351490_google_app_engine_html_pdf_generation_python.txt
Q: Using MOUSEBUTTONDOWN in pygame So I am trying to do some very basic things in pygame. It is my first few days using it so I am a beginner. I am trying to change the color of something whenever I press it with the mouse. I know how to change the colors by timing which is what I have my code down below. I am tr...
Using MOUSEBUTTONDOWN in pygame
So I am trying to do some very basic things in pygame. It is my first few days using it so I am a beginner. I am trying to change the color of something whenever I press it with the mouse. I know how to change the colors by timing which is what I have my code down below. I am trying to change the color of the cloud...
[ "You've already discovered how to test for the type of an event (checking whether event.type == QUIT).\nYou can extend this to check whether it's a mouse button click. Stick this in your for event in pygame.event.get() loop:\nif event.type == MOUSEBUTTONDOWN:\n flag = not flag # This will swap the value of the f...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008425801_pygame_python.txt
Q: How can I remove date exception from OpenERP? I am digging through OpenERP web to find how I can remove the exception of date from it. eg I want to insert a date like 12/12/1523. with Current functionality it will show me an error message if i will enter a date less then 1900. I have checked it with _calendar.py, ...
How can I remove date exception from OpenERP?
I am digging through OpenERP web to find how I can remove the exception of date from it. eg I want to insert a date like 12/12/1523. with Current functionality it will show me an error message if i will enter a date less then 1900. I have checked it with _calendar.py, format.py, validates.py. but i didn't succeed. If a...
[ "I found two problems in openerp-web:\n1 - The date control calendar is restricted and cannot go below\n01/01/1900\n\n2 - There are validation errors raised from openerp/i18n/format.py when\ntrying to save\nPoint 1, the javascript widget can be easily fixed in\nopenerp/static/calandar/calendar.js\n\n=> find:\n\n ...
[ 3, 0 ]
[]
[]
[ "openerp", "python" ]
stackoverflow_0008257221_openerp_python.txt
Q: Installing MatplotLib in mac osx lion I was trying to install matplotlib in Mac OSX Lion. Tried to used the binary that is in the sourcefourge site, but I got this error: "matplotlib requires System Python 2.7 to install". I went to the Terminal and typed python --version and its check the requirements. After this...
Installing MatplotLib in mac osx lion
I was trying to install matplotlib in Mac OSX Lion. Tried to used the binary that is in the sourcefourge site, but I got this error: "matplotlib requires System Python 2.7 to install". I went to the Terminal and typed python --version and its check the requirements. After this I tried to used the pip, and while doing s...
[ "This is because of a change in the API for libpng v1.5 (which is included with Mac OSX Lion). The changes has already been pushed upstream, so you will need to compile from the upstream repository until the next release.\nYou can follow the instructions on http://jholewinski.wordpress.com/2011/07/21/installing-mat...
[ 9, 5, 4, 3, 1, 0 ]
[]
[]
[ "macos", "matplotlib", "osx_lion", "python" ]
stackoverflow_0006800488_macos_matplotlib_osx_lion_python.txt
Q: Python: Nested For Loops I have a question I need to ask you. Here is part of my script: scan=file('indice.txt','r') for i_L in range(10): for line in scan: a,b,c=line.split() do something ... ... ... print something scan.close() indice.txt is a file containing 3 columns of real nu...
Python: Nested For Loops
I have a question I need to ask you. Here is part of my script: scan=file('indice.txt','r') for i_L in range(10): for line in scan: a,b,c=line.split() do something ... ... ... print something scan.close() indice.txt is a file containing 3 columns of real numbers. The main problem is th...
[ "Before you start looping over the lines in the file again, you should seek the file to the beginning:\nscan=file('indice.txt','r')\nfor i_L in range(10):\n for line in scan:\n a,b,c=line.split()\n do something ...\n\n\n\n ...\n print something\n scan.seek(0)\nscan.close()\n\nSee file....
[ 3, 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0006818462_for_loop_python.txt
Q: Scipy - Executing part of function only when function input values change I have been trying to optimize this code: def spectra(mE, a): pdf = lambda E: np.exp(-(a+1)*E/mE)*(((a+1)*E/mE)**(a+1))/(scipy.special.gamma(a+1)*E) u=[] n=np.random.uniform() E=np.arange(0.01,150, 0.1) for i in E: ...
Scipy - Executing part of function only when function input values change
I have been trying to optimize this code: def spectra(mE, a): pdf = lambda E: np.exp(-(a+1)*E/mE)*(((a+1)*E/mE)**(a+1))/(scipy.special.gamma(a+1)*E) u=[] n=np.random.uniform() E=np.arange(0.01,150, 0.1) for i in E: u.append(scipy.integrate.quad(pdf,0,i)[0]) f=interp1d(u, E) return ...
[ "It sounds like what you want to do is return a known value if the function is re-called with the same (mE, a) values, and perform the calculation if the input is new.\nThat is called memoization. See for example What is memoization and how can I use it in Python? . Note that in modern versions of Python, you can c...
[ 2, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0008426318_numpy_python_scipy.txt
Q: script to replace first line of file if it DOESN"T match a certain pattern I would like to add some license text to all files that do not have a license. So, I want to check the first line of the file, and if it doesn't have the text "#region License" in it, to insert some text. Thanks. A: The following one-line...
script to replace first line of file if it DOESN"T match a certain pattern
I would like to add some license text to all files that do not have a license. So, I want to check the first line of the file, and if it doesn't have the text "#region License" in it, to insert some text. Thanks.
[ "The following one-liner will insert the text #region License on the first line of files that don't already start with that text:\nperl -i.bckp -ne 'print && next if $. > 1;/^#region License/?print:print\"#region License\\n$_\"' filename.txt\n\nIt also makes backup files with the .bckp extension of your files.\n", ...
[ 3, 0, 0 ]
[]
[]
[ "perl", "python", "ruby", "sed" ]
stackoverflow_0008422394_perl_python_ruby_sed.txt
Q: Error setting up mercurial on apache with win7 - DLL load failed I am trying to setup Mercurial, publishing it through Apache on a Windows7 machine . These are the steps I have followed: Installed Mercurial mercurial-2.0.0-x86.msi Installed Apache Server - httpd-2.2.21-win32-x86-openssl-0.9.8r.msi Installed Pytho...
Error setting up mercurial on apache with win7 - DLL load failed
I am trying to setup Mercurial, publishing it through Apache on a Windows7 machine . These are the steps I have followed: Installed Mercurial mercurial-2.0.0-x86.msi Installed Apache Server - httpd-2.2.21-win32-x86-openssl-0.9.8r.msi Installed Python python-2.6.1.msi Set up Apache to use Python through mod_wsgi - mod_...
[ "Giving up after spending days trying to figure out a solution. \nI have also tried building mercurial for windows without success. \nI ran the same commands that are in hgweb.wsgi from python shell and I do not get the DLL errors.I think this thread outlines the issue which lies in the python distribution and not ...
[ 1, 0 ]
[]
[]
[ "apache", "mercurial", "python" ]
stackoverflow_0008385553_apache_mercurial_python.txt
Q: Trying to index data from a CSV I started working on a simple program some time ago, and I have gotten back into it. What I am trying to do here is use an index to manipulate the order in which data from a CSV prints. When I run this code, I get "IndexError: list index is out of range". What am I doing wrong or mi...
Trying to index data from a CSV
I started working on a simple program some time ago, and I have gotten back into it. What I am trying to do here is use an index to manipulate the order in which data from a CSV prints. When I run this code, I get "IndexError: list index is out of range". What am I doing wrong or missing? Thanks in advance. import csv ...
[ "According to documentation in csv.reader() each row read from the csv file is returned as a list of strings. I guess that in your file you have empty fields or lines.\nSo you should do something like:\nmembers = csv.reader(open(\"mags.csv\",\"rU\"))\nfor row in members:\n for index in (1, 0):\n if index < len(ro...
[ 1, 1 ]
[]
[]
[ "indexing", "python" ]
stackoverflow_0008426816_indexing_python.txt
Q: Center a formatted row of integers in Python? I am a bit new to Python, having dabbled in VB.NET, C, and a few other odd languages, so I am finding the approaches used before don't always apply to Python. In this case, I want to print out a series of integer values into columns and center them in as small amount ...
Center a formatted row of integers in Python?
I am a bit new to Python, having dabbled in VB.NET, C, and a few other odd languages, so I am finding the approaches used before don't always apply to Python. In this case, I want to print out a series of integer values into columns and center them in as small amount of code as possible. With plain strings, this is ea...
[ "ints = [1, 2, 3, 4]\nwidths = [(4, w), (2, x), (2, y), (8, z)]\nfor i in ints:\n print \"%s|%s|%s|%s\" % tuple((((\"%0.\" + str(padding) + \"d\") % (i)).center(width)) for padding, width in widths)\n\nEach tuple in widths is (padding, width), where each padding associated with a width is used in the string form...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008427160_python.txt
Q: how to solve AttributeError: '_Environ' object has no attribute 'has_key' def _is_dev_mode(): # quick hack to check if the program is running in dev mode. # if 'has_key' in os.environ if os.environ.has_key('SERVER_SOFTWARE') \ or os.environ.has_key('PHP_FCGI_CHILDREN') \ or 'fcgi' in ...
how to solve AttributeError: '_Environ' object has no attribute 'has_key'
def _is_dev_mode(): # quick hack to check if the program is running in dev mode. # if 'has_key' in os.environ if os.environ.has_key('SERVER_SOFTWARE') \ or os.environ.has_key('PHP_FCGI_CHILDREN') \ or 'fcgi' in sys.argv or 'fastcgi' in sys.argv \ or 'mod_wsgi' in sys.argv: ...
[ "I supose you are working on python 3. In Python 2, dictionaries had a has_key() method. In Python 3, as the exception says, it no longer exists. You need to use the in operator:\nif 'SERVER_SOFTWARE' in os.environ\n\nhere you have an example (py3k):\n>>> import os\n>>> if 'PROCESSOR_LEVEL' in os.environ: print(os....
[ 20 ]
[]
[]
[ "eclipse", "python", "web_services" ]
stackoverflow_0008427352_eclipse_python_web_services.txt
Q: How to select a random portion from an image in python Suppose I have a large image (5000 x 5000), how can I randomly select a portion ( 200 x 200 square) from this large image? Also I want to set boundary so the selection won't take any area outside the image. If anyone has any idea, please shed some light. A: ...
How to select a random portion from an image in python
Suppose I have a large image (5000 x 5000), how can I randomly select a portion ( 200 x 200 square) from this large image? Also I want to set boundary so the selection won't take any area outside the image. If anyone has any idea, please shed some light.
[ "import random\n\nimage_size = (5000,5000)\nportion_size = (200, 200)\n\nx1 = random.randint(0, image_size[0]-portion_size[0]-1)\ny1 = random.randint(0, image_size[1]-portion_size[1]-1)\n\nx2, y2 = x1+portion_size[0]-1, y1+portion_size[1]-1\n\n# Grab the area of the image that is the rectangle defined by (x1,y1) an...
[ 5 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0008427497_image_processing_python.txt
Q: Merging a list of lists such that unique values overwrite nonunique ones? After searching around for quite a while and trying to come up with a solution on my own with list comprehensions, I feel like I've been completely stumped on how to solve the following problem: Given a list: crazy_list = [a, b] Where: a =...
Merging a list of lists such that unique values overwrite nonunique ones?
After searching around for quite a while and trying to come up with a solution on my own with list comprehensions, I feel like I've been completely stumped on how to solve the following problem: Given a list: crazy_list = [a, b] Where: a = [['*'], ['*', '34', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '102',...
[ "Assuming that your progress on just two lists so far works, you can try this.\ndef merge(a, b):\n return [a[item_indx] if item != '*' else b[item_indx] for item_indx, item in enumerate(a)]\n\nreduce(merge, crazy_list)\n\nWhat reduce does in this case is take the resulting list of the last merge and then does it...
[ 4, 3, 2, 1 ]
[]
[]
[ "list", "merge", "multidimensional_array", "python" ]
stackoverflow_0008427330_list_merge_multidimensional_array_python.txt
Q: what is exactly Tornado? Possible Duplicate: What is Facebook's new Tornado framework? sorry for that question, but when using a python file on internet, we use: CGI (non supported by Nginx) or WSGI (which is the standard for python) and uWSGI (which Ngnix supports) for Fast-CGI (the CGI with on long process) an...
what is exactly Tornado?
Possible Duplicate: What is Facebook's new Tornado framework? sorry for that question, but when using a python file on internet, we use: CGI (non supported by Nginx) or WSGI (which is the standard for python) and uWSGI (which Ngnix supports) for Fast-CGI (the CGI with on long process) and SCGI (simple CGI).... but H...
[ "Already had a look at the documentation ?\ntornado.wsgi — Interoperability with other Python frameworks and servers\nWhat else do you need to know?\n" ]
[ 2 ]
[]
[]
[ "cgi", "python", "tornado", "uwsgi", "wsgi" ]
stackoverflow_0008427830_cgi_python_tornado_uwsgi_wsgi.txt
Q: Finding a specific Window using its title hashed value I've been decompiling a piece of code I believe is malware and I'm trying to figure out what it does. It searches for a specific window title and uses the name of that window to decode the rest of its instructions. I've tried just running lists of common windo...
Finding a specific Window using its title hashed value
I've been decompiling a piece of code I believe is malware and I'm trying to figure out what it does. It searches for a specific window title and uses the name of that window to decode the rest of its instructions. I've tried just running lists of common windows titles (Notepad, Document1 - Microsoft Word, etc) through...
[ "If the window title is long enough you won't find it with a brute force attack and probably it would not even help you to find a title which matches the hash. The malware could just check if there is another instance of itself.\nI would suggest running the malware in a vm or even better dedicated computer (probabl...
[ 0 ]
[]
[]
[ "encryption", "hash", "malware", "python", "reverse_engineering" ]
stackoverflow_0008403203_encryption_hash_malware_python_reverse_engineering.txt
Q: Python List comprehension one declaration and 2 Comprehensions How can I combine this: ipaddresses = [ipadr['ip'] for ipadr in hosts] for ipadr in ipaddresses: ips = '.'.join(str(i) for i in ipadr) Into One declaration with 2 list comprehensions? I just don't get it. Thanks ipaddresses will print something l...
Python List comprehension one declaration and 2 Comprehensions
How can I combine this: ipaddresses = [ipadr['ip'] for ipadr in hosts] for ipadr in ipaddresses: ips = '.'.join(str(i) for i in ipadr) Into One declaration with 2 list comprehensions? I just don't get it. Thanks ipaddresses will print something like this: [[10, 10, 10, 10], [10, 20, 20, 20]]
[ "You only need 1 LC, not 2.\n['.'.join(str(octet) for octet in addr['ip']) for addr in hosts]\n\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0008428122_python.txt
Q: Python GUI for accessibility Application I am to develop a Python-based Application for people with motion problems. I have read a few posts here about general characteristics of the most used Toolkits for creating GUIs with Python, but hope you can give me some advice according to my requirements. 1) Basically th...
Python GUI for accessibility Application
I am to develop a Python-based Application for people with motion problems. I have read a few posts here about general characteristics of the most used Toolkits for creating GUIs with Python, but hope you can give me some advice according to my requirements. 1) Basically the persons who will use the program, will commu...
[ "Checkout Kivy. You can prototype your application very fast. It's a NUI framework, so some concept are totally adaptable, like double-click: it's named doubletap, and implemented as a input post processor. For example, you can change the timeout between the double tap (or even the distance between 2 tap) for your ...
[ 5 ]
[]
[]
[ "accessibility", "python" ]
stackoverflow_0008427744_accessibility_python.txt
Q: Logging in to vBulletin I am trying to do a program in Python which logs in to a vBulletin forum. I need to access only one page, but in order to view that page I must be logged in. Here is my code: #-*- coding:utf-8 -*- import urllib, urllib2, cookielib, hashlib, time def variables(): domain = "www.example....
Logging in to vBulletin
I am trying to do a program in Python which logs in to a vBulletin forum. I need to access only one page, but in order to view that page I must be logged in. Here is my code: #-*- coding:utf-8 -*- import urllib, urllib2, cookielib, hashlib, time def variables(): domain = "www.example.com" uname = "UserName" ...
[ "1) you need to send vb_login_name and vb_login_password to login.php?do=login\n2) you need to send below values to login.php?do=login too (view html code)\n<input type=\"hidden\" name=\"s\" value=\"215c619cb0227a30bab788ca0adb1c42\" />\n<input type=\"hidden\" name=\"securitytoken\" value=\"guest\" />\n<input type=...
[ 0 ]
[]
[]
[ "authentication", "python", "vbulletin" ]
stackoverflow_0008427289_authentication_python_vbulletin.txt
Q: What is the equivalent to python equivalent to using Class.getResource() In java if I want to read a file that contains resource data for my algorithms how do I do it so the path is correctly referenced. Clarification I am trying to understand how in the Python world one packages data along with code in a module. ...
What is the equivalent to python equivalent to using Class.getResource()
In java if I want to read a file that contains resource data for my algorithms how do I do it so the path is correctly referenced. Clarification I am trying to understand how in the Python world one packages data along with code in a module. For example I might be writing some code that looks at a string and tries to c...
[ "I think you may be looking for pkgutil.get_data(). The docs for this say:\npkgutil.get_data(package, resource)\n\n\nGet a resource from a package.\nThis is a wrapper for the PEP 302 loader get_data() API. The package\n argument should be the name of a package, in standard module format\n (foo.bar). The resource ...
[ 2, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0008426196_java_python.txt
Q: How to insert the group_id of a user to 'auth_user_groups' table I need to insert the group_id of a user(user in auth_user table) to auth_user_groups table. How can we achieve this? To insert into auth_user table we can do details = User(username = "somename",password = "somepassword", email = "email", first_na...
How to insert the group_id of a user to 'auth_user_groups' table
I need to insert the group_id of a user(user in auth_user table) to auth_user_groups table. How can we achieve this? To insert into auth_user table we can do details = User(username = "somename",password = "somepassword", email = "email", first_name = "firstname", last_name = "lastname", is_staff = 0, is_active = ...
[ "user = User.objects.get(id=1)\ngroup = Group.objects.get(id=5)\n\nuser.groups.add(group)\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008428871_django_django_models_python.txt
Q: Preventing imports in Python I have python embedded in an application as a scripting platform so the users can write python scripts. I am trying to prevent imports so they cannot cause damage in anyway and have to stick to the provided API. I have come up with the following Python code: __builtins__ .__import__= ...
Preventing imports in Python
I have python embedded in an application as a scripting platform so the users can write python scripts. I am trying to prevent imports so they cannot cause damage in anyway and have to stick to the provided API. I have come up with the following Python code: __builtins__ .__import__= None reload = None This seems to...
[ "What you probably want is to run Python in a sandbox. There are a number of ways of doing this, for example PyPy has sandboxing support.\nYou could also try sandboxing the Python process itself using external tools, but I suppose this is dependent on the operating system.\n" ]
[ 3 ]
[]
[]
[ "import", "python", "scripting" ]
stackoverflow_0008428618_import_python_scripting.txt
Q: omniORBpy terminating the server I'm working on python client-server application that uses omniORBpy and I'm trying to figure out how to correctly terminate the server. I have this method to do so: def shutdown(self): print "---------------------------------------" print "shutdown" orb.shutdown(False) ...
omniORBpy terminating the server
I'm working on python client-server application that uses omniORBpy and I'm trying to figure out how to correctly terminate the server. I have this method to do so: def shutdown(self): print "---------------------------------------" print "shutdown" orb.shutdown(False) quit() But when I send a message ...
[ "Did you make the shutdown method an oneway method in IDL?\n", "You cannot shutdown the server (even not in a oneway call). You have to change a \"flag\" so that it is checked frequently. If it is set, shutdown the server.\nE.g., in pseudocode:\ndef shutdown():\n self.shutdown = True\n\ndef run():\n while not s...
[ 0, 0 ]
[]
[]
[ "corba", "python" ]
stackoverflow_0008418695_corba_python.txt
Q: UnboundLocalError: local variable 'prod_Available' referenced before assignment I am developing a reservation system, and i have a function that save the quantity of a product... My question is why I got this problem ? when i `curl -l -X POST -d "product=3&client=1&function=insert_booking&check_in=2011-12-15&chec...
UnboundLocalError: local variable 'prod_Available' referenced before assignment
I am developing a reservation system, and i have a function that save the quantity of a product... My question is why I got this problem ? when i `curl -l -X POST -d "product=3&client=1&function=insert_booking&check_in=2011-12-15&check_out=2011-12-10&no_of_adult=2&no_of_kid=1&quantity=2&first_name=asda&last_name=sdsd&...
[ "Sometimes you loop is not entered, so prod_Available is not created, but you try to reference it.\nBefore the loop put prod_Available = 0:\n prod = Product.objects.get(id=product_id)\n\n prod_Available = 0 # !\n\n for x in range(start_date,end_date + 1):\n x = x - start_date\n delta = dateti...
[ 1, 1, 1 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0008429407_django_django_piston_python.txt
Q: How to get a type of the variable from the Python's AST? Suppose I want to get the type of all variables from the AST tree that I have generated from some source code -- how would I go about doing that? For example, suppose in my source code I have something like i = 5. How would I determine, from the abstract syn...
How to get a type of the variable from the Python's AST?
Suppose I want to get the type of all variables from the AST tree that I have generated from some source code -- how would I go about doing that? For example, suppose in my source code I have something like i = 5. How would I determine, from the abstract syntax tree, that the type of i is integer? I tried the type() fu...
[ "As explained in other posts, there isn't easy way to achieve this without heavy analysis of the syntax tree, for which python ast module provides no facilities.\nYou can still use logilab's astng1, which is the basis for pylint2 and provides static inference capabilities.\nHere is a quick example :\nfrom logilab.a...
[ 3, 2, 1 ]
[]
[]
[ "abstract_syntax_tree", "python", "types" ]
stackoverflow_0008425371_abstract_syntax_tree_python_types.txt
Q: Python trim whitespace in a list I have this string: "3a.24.5t.5a 4 1743 3150924 2786 0" With this code: for i in flines: ll = re.findall(r'\.?\w+', i) print ll I get: ['3a.', '24.', '5t.', '5a', '4', '1743', '3150924', '2786', '0'] I need: ['3a.24.5t.5a', '4', '1743', '3150924', '2786', '0'] ...
Python trim whitespace in a list
I have this string: "3a.24.5t.5a 4 1743 3150924 2786 0" With this code: for i in flines: ll = re.findall(r'\.?\w+', i) print ll I get: ['3a.', '24.', '5t.', '5a', '4', '1743', '3150924', '2786', '0'] I need: ['3a.24.5t.5a', '4', '1743', '3150924', '2786', '0'] Thanks
[ "Have you tried without regex for ex using split?\n>>> x=\"3a.24.5t.5a 4 1743 3150924 2786 0\"\n>>> x.split()\n['3a.24.5t.5a', '4', '1743', '3150924', '2786', '0']\n\nor as per your code\nfor i in flines:\n ll = i.split()\n print ll\n\n", "Use split(): \n>>> ll = \"3a.24.5t.5a 4 1743 3150924 ...
[ 7, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008429803_python.txt
Q: bcrypt mechanism in auth (no match hashes) i'm trying to implement a login method for mongodb , using python (pymongo) and bcrypt. the problem comes when i try to compare hashes , they always are different :$ . This is my test code( First of all i put into mongodb an user with a password hashed ): using pythons sc...
bcrypt mechanism in auth (no match hashes)
i'm trying to implement a login method for mongodb , using python (pymongo) and bcrypt. the problem comes when i try to compare hashes , they always are different :$ . This is my test code( First of all i put into mongodb an user with a password hashed ): using pythons scrypt : bcrypt.hashpw('testpassword', bcrypt.gens...
[ "For a password check you need to pass the hash itself as the salt, as it contains the salt as a prefix. This is a little confusing, but since you absolutely must use the same salt to get the same hash as before, that's the only way: \n>>> myhash = bcrypt.hashpw('testpassword', bcrypt.gensalt(12))\n>>> myhash \n...
[ 2 ]
[]
[]
[ "bcrypt", "mongodb", "python" ]
stackoverflow_0008429888_bcrypt_mongodb_python.txt
Q: Modules, classes and namespaces in Python I have the following scenario: I have abstract classes A and B, and A uses B to perform some tasks. In both classes, there are some "constant" parameters (right now implemented as class attributes) to be set by concrete classes extending those abstract classes, and some o...
Modules, classes and namespaces in Python
I have the following scenario: I have abstract classes A and B, and A uses B to perform some tasks. In both classes, there are some "constant" parameters (right now implemented as class attributes) to be set by concrete classes extending those abstract classes, and some of the parameters are shared (they should have t...
[ "Here are a few things I could suggest:\n\nLink each body to its group, so that the body accesses the constant from the group when it calculates its force. For example:\nclass NbodyGroup(object):\n def __init__(self, constant):\n self.bodies = []\n self.constant = constant\n\n def step(self):\n ...
[ 1, 1, 1, 0 ]
[]
[]
[ "class", "module", "namespaces", "python" ]
stackoverflow_0008429613_class_module_namespaces_python.txt
Q: Using TimedRotatingFileHandler logging with a logging.config I'm trying to test using a TimedRotatingFileHandler with a logging.config file, nothing that complicated but it should roll over every 10 seconds into a new log file. However I'm getting the following Traceback (most recent call last): File "testLoggin...
Using TimedRotatingFileHandler logging with a logging.config
I'm trying to test using a TimedRotatingFileHandler with a logging.config file, nothing that complicated but it should roll over every 10 seconds into a new log file. However I'm getting the following Traceback (most recent call last): File "testLogging.py", line 6, in <module> logging.config.fileConfig(logDir+'l...
[ "args=('./logs/log.out', 'when=\\'S\\'', 'interval=10', 'backupCount=5')\n\nDoesn't look right. Try this\nargs=('./logs/log.out', when='S', interval=10, backupCount=5)\n\nOr possibly this\nargs=('./logs/log.out','S',10,5)\n\n" ]
[ 17 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0008430136_logging_python.txt
Q: Jython Swing: Randomly Occurring Java ImageIO IOException I've built a Jython swing app using eclipse and pydev. I've used simple images for the backgrounds of all of the buttons. 95% of the time, everything works wonderfully. However, about 5% of the time when adding or removing content from the screen, this occu...
Jython Swing: Randomly Occurring Java ImageIO IOException
I've built a Jython swing app using eclipse and pydev. I've used simple images for the backgrounds of all of the buttons. 95% of the time, everything works wonderfully. However, about 5% of the time when adding or removing content from the screen, this occurs: Exception in thread "AWT-EventQueue-0" at com.sun.imageio....
[ "\nWhat's a more practical solution: having a thread cache all of the images somewhere accessible on application start-up or sending a thread for each individual image. I use roughly 2-3 MBs of images throughout the application.\n\nMuch depends on the anticipated latency and image size. This simple example caches i...
[ 3 ]
[]
[]
[ "java", "jython", "python", "swing" ]
stackoverflow_0008425304_java_jython_python_swing.txt
Q: Python Stacktrace: calledfuncs dictionary with strange syntax: "Class'>.method" When I look at the dictionary generated with: import trace tracer = trace.Trace(countfuncs=True) tracer.runfunc(callableObj, *args, **kwargs) print tracer.results().calledfuncs on one machine (python 1.3) I get a strange syntax for th...
Python Stacktrace: calledfuncs dictionary with strange syntax: "Class'>.method"
When I look at the dictionary generated with: import trace tracer = trace.Trace(countfuncs=True) tracer.runfunc(callableObj, *args, **kwargs) print tracer.results().calledfuncs on one machine (python 1.3) I get a strange syntax for the keys of the printed dictionary; a key looks like: ('/path/to/file.py', 'module', "...
[ "Are you sure you didn't mean Python 2.3?\nIn trace.py, the classname is calculated from:\n ...\n clsname = str(classes[0])\n ...\n if clsname is not None:\n # final hack - module name shows up in str(cls), but we've already\n # computed module name, so remove it\n clsname = cls...
[ 0 ]
[]
[]
[ "python", "stack_trace", "syntax", "trace" ]
stackoverflow_0008430256_python_stack_trace_syntax_trace.txt
Q: The difference between 'from pylons import config' and 'import pylons.config' Im trying to import a company module into my software and I get the error: ImportError: No module named config from: from pylons.config import config So obviously, the module that im importing requires pylons.config but cant find it in...
The difference between 'from pylons import config' and 'import pylons.config'
Im trying to import a company module into my software and I get the error: ImportError: No module named config from: from pylons.config import config So obviously, the module that im importing requires pylons.config but cant find it in my virtual environment. If I go to the terminal and try some Python scripts I can ...
[ "There is a diffrence between two usages...\nimport loads a Python module into its own namespace, while from loads a Python module into the current namespace.\nSo, using from pylons import config imports config to to your current namespace. But trying to import a class or function using import is not possible since...
[ 4 ]
[]
[]
[ "configuration_files", "import", "pylons", "python" ]
stackoverflow_0008430823_configuration_files_import_pylons_python.txt
Q: Improving Python execution speed with parallel threads Let's say I have this sample code: x = foo1(something1) y = foo2(something2) z = max(x, y) I want to improve the execution time of this code by using threads (hope it helps isn't it?). I'd like to keep things as simple as possible so basically what I'd like ...
Improving Python execution speed with parallel threads
Let's say I have this sample code: x = foo1(something1) y = foo2(something2) z = max(x, y) I want to improve the execution time of this code by using threads (hope it helps isn't it?). I'd like to keep things as simple as possible so basically what I'd like to do is creating two threads working at the same time which...
[ "Assuming foo1 or foo2 is CPU-bound, threading doesn't improve the execution time... in fact, it normally makes it worse... for more information, see David Beazley's PyCon2010 presentation on the Global Interpreter Lock / Pycon2010 GIL slides. This presentation is very informative, I highly recommend it to anyone ...
[ 8, 0, 0 ]
[ "It won't help. Read the Python FAQ.\n" ]
[ -1 ]
[ "gil", "multiprocessing", "multithreading", "performance", "python" ]
stackoverflow_0008430899_gil_multiprocessing_multithreading_performance_python.txt
Q: What RPC module works over SSH, telnet and HTTP? Possible Duplicate: What RPC module should I use to implement RCP in Python and be able to change connection method later? I am looking for RPC solution that can be used over different protocols like SSH, telnet and HTTP. It has to be Python 2.5 compatible. A: Y...
What RPC module works over SSH, telnet and HTTP?
Possible Duplicate: What RPC module should I use to implement RCP in Python and be able to change connection method later? I am looking for RPC solution that can be used over different protocols like SSH, telnet and HTTP. It has to be Python 2.5 compatible.
[ "You're likely going to have to roll your own, but much of the heavy lifting in transport code could be done in other modules:\n\nparamiko for ssh\ntelnetlib for telnet\nurllib(2) for http.\n\nYou'll still have to address the issue of data format, but that is independent of transport protocol (feel free to deliver ...
[ 4 ]
[]
[]
[ "python", "rpc" ]
stackoverflow_0008431024_python_rpc.txt
Q: extracting specific data from a table I have table which looks like this (tab separated): Ron Rob rock bammy m f m f florida Atlanta florida texas This table is of order 5*512 and based on row 3 data, I want to extract the values in row1. for example: I want to have names of all person living in flori...
extracting specific data from a table
I have table which looks like this (tab separated): Ron Rob rock bammy m f m f florida Atlanta florida texas This table is of order 5*512 and based on row 3 data, I want to extract the values in row1. for example: I want to have names of all person living in florida and texas, in a table of 2 columns and n...
[ "awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida|texas/)print $i\"\\t\"n[i];}}' yourFile\n\nsee the test below:\nkent$ echo \"Ron Rob rock bammy\nm f m f\nflorida Atlanta florida texas\"|awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida|texas/)print $i\"\...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "bash", "perl", "python", "shell" ]
stackoverflow_0008429759_bash_perl_python_shell.txt
Q: Simultaneus threads Ok. Maybe you get mad at me for not showing what I've tried. But I'm really confused with threads. What would be the simpliest possible way to run three threads simultaneously and after they all finished run a forth one? This would run inside a wx application so I want a way that would not lock...
Simultaneus threads
Ok. Maybe you get mad at me for not showing what I've tried. But I'm really confused with threads. What would be the simpliest possible way to run three threads simultaneously and after they all finished run a forth one? This would run inside a wx application so I want a way that would not lock up my program. Edit: Wel...
[ "I haven't tested this, but the basic idea would be something like this:\nfrom threading import Thread\n\nthreads = [Thread(target=f1), Thread(target=f2), Thread(target=f3)]\n\nfor thread in threads:\n thread.start()\n\n# Wait for all of them\nfor thread in threads:\n thread.join()\n\n# Do stuff afterwards\n\...
[ 5 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008431366_multithreading_python.txt
Q: retrieve the Package.Module.Class name from a (Python) class/type Right, say I've got this structure: (Which I happen to actually have) Interface (folder/Package) Test.py (module) Test (class) Now I want to get this whole structure (Interface.Test.Test) as a string stored somewhere. I know I can use type(myTes...
retrieve the Package.Module.Class name from a (Python) class/type
Right, say I've got this structure: (Which I happen to actually have) Interface (folder/Package) Test.py (module) Test (class) Now I want to get this whole structure (Interface.Test.Test) as a string stored somewhere. I know I can use type(myTestObjectInstance) or myTestObjectInstance.__class__ But that retrieves...
[ "Using inspect.getmodule you can (sometimes) find the module in which an object was defined, e.g.\n>>> from collections import defaultdict\n>>> import inspect\n>>> inspect.getmodule(defaultdict)\n<module 'collections' from '/usr/lib/python2.6/collections.pyc'>\n\nThe module name can be found using __name__. Note th...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008431654_python.txt
Q: How to store data with large number (constant) of properties in SQL I am parsing the USDA's food database and storing it in SQLite for query purposes. Each food has associated with it the quantities of the same 162 nutrients. It appears that the list of nutrients (name and units) has not changed in quite a while...
How to store data with large number (constant) of properties in SQL
I am parsing the USDA's food database and storing it in SQLite for query purposes. Each food has associated with it the quantities of the same 162 nutrients. It appears that the list of nutrients (name and units) has not changed in quite a while, and since this is a hobby project I don't expect to follow any sudden c...
[ "You should read up a bit on database normalization. Most of the normalization stuff is quite intuitive, but really going through the definition of the steps and seeing an example helps understanding the concepts and will help you greatly if you want to design a database in the future.\nAs for this problem, I would...
[ 6, 4 ]
[]
[]
[ "c++", "python", "sql", "sqlite" ]
stackoverflow_0008431451_c++_python_sql_sqlite.txt
Q: How can lxml validate some XML against both an XSD file while also loading an inline schema too? I'm having problems getting lxml to successfully validate some xml. The XSD schema and XML file are both from Amazon documentation so should be compatible. But the XML itself refers to another schema that's not being l...
How can lxml validate some XML against both an XSD file while also loading an inline schema too?
I'm having problems getting lxml to successfully validate some xml. The XSD schema and XML file are both from Amazon documentation so should be compatible. But the XML itself refers to another schema that's not being loaded. Here is my code, which is based on the lxml validation tutorial: xsd_doc = etree.parse('Product...
[ "The answer is I should validate by the parent schema file, which as mentioned at the top of the XML file is amzn-envelope.xsd as this contains the line:\n<xsd:include schemaLocation=\"ProductImage.xsd\"/>\n\nIn general then, lxml won't read such a declaration as xsi:noNamespaceSchemaLocation=\"amzn-envelope.xsd\" ...
[ 2 ]
[]
[]
[ "lxml", "python", "xml", "xsd" ]
stackoverflow_0008424457_lxml_python_xml_xsd.txt
Q: djangoappengine User Creation and Data Persistence is Broken I recently updated to appengine SDK 1.6 and I'm having trouble with persisting data on my dev environment. I have everything setup according to the official installation guide. Even though I had a super user account setup for my app previously, it no lo...
djangoappengine User Creation and Data Persistence is Broken
I recently updated to appengine SDK 1.6 and I'm having trouble with persisting data on my dev environment. I have everything setup according to the official installation guide. Even though I had a super user account setup for my app previously, it no longer works. I created the account again with manage.py createsuper...
[ "is it possible that you fire up a new issue at the issue tracker https://github.com/django-nonrel/djangoappengine/issues or at the mailing list http://groups.google.com/group/django-non-relational ? I think there might be a bug somewhere.\n", "Depending on what you upgraded from, it's possible that you previousl...
[ 0, 0, 0 ]
[]
[]
[ "django", "djangoappengine", "python" ]
stackoverflow_0008410052_django_djangoappengine_python.txt
Q: Can Blender generate a scene based off of a text file? I have written a program in Python that generates a 10,000 tile coordinate plane with each tile having characteristics such as texture, temperature, elevation etc. I am doing this for a project and thought a much better way to show this part of the project wou...
Can Blender generate a scene based off of a text file?
I have written a program in Python that generates a 10,000 tile coordinate plane with each tile having characteristics such as texture, temperature, elevation etc. I am doing this for a project and thought a much better way to show this part of the project would be to show a 3d rendering of it and the best program i kn...
[ "You will have to make a Python script for that - that would read your text file and use blender API internally to create the tiles and the scene. Blender can only render files if it does have programs (plug-ins) that do that. Actually most file-formats can be read by blender just due to plug-ins implemented in Pyt...
[ 1 ]
[]
[]
[ "blender", "python", "render_to_texture" ]
stackoverflow_0008350067_blender_python_render_to_texture.txt
Q: Django - Checking the type of Multi-table inheritence Querysets I'm trying to hold a kind of table of contents structure in my database. Simplified example: models.py class Section (models.Model): title = models.CharField(max_length=80) order = models.IntegerField() class SectionClickable(Section): li...
Django - Checking the type of Multi-table inheritence Querysets
I'm trying to hold a kind of table of contents structure in my database. Simplified example: models.py class Section (models.Model): title = models.CharField(max_length=80) order = models.IntegerField() class SectionClickable(Section): link = models.CharField(max_length=80) class SectionHeading(Section): ...
[ "well you could check the type:\nif isinstance(section, SectionHeading)\n\nbut duck typing is generally preferred\nedit:\nactually, that probably won't work. the object will be a Section. but you can look for the attribute:\nif hasattr(section, 'sectionheading')\n\nor\ntry:\n do_something_with(section.sectionhea...
[ 2, 1, 0, 0 ]
[]
[]
[ "database_design", "django", "python" ]
stackoverflow_0008334007_database_design_django_python.txt
Q: from elements in a line to key and values I have a file with lines like this: no.3 normal yes 54 0,543 12 And I should end up with ("normal", yes, 54, 0.543, 12) when I print info(no.3) I have started by splitting up in lines. But now I'm not sure what to do? As I can see, I need to use the first eleme...
from elements in a line to key and values
I have a file with lines like this: no.3 normal yes 54 0,543 12 And I should end up with ("normal", yes, 54, 0.543, 12) when I print info(no.3) I have started by splitting up in lines. But now I'm not sure what to do? As I can see, I need to use the first element as key, and the remaining as value. But I'm ...
[ "mydict = {}\nfor line in myfile:\n items = line.split() # split line on whitespace\n mydict[items[0]] = items[1:] # first item: key, rest: values\n\nThen you can do\nprint mydict[\"no.3\"]\n\nand get \n['normal', 'yes', '54', '0,543', '12']\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008432659_python.txt
Q: how to remove table row based on contents of one of the cells in the row using python? I have html document with table like: <tr> <td width="3%"><input type="checkbox", name="chk"></td> <td width="10%">101</td> <td width="4%">Fix</td> <td width="5%">2.00</td> <td width="6%">09:28:03</td> <td width="5%">5</td> <td ...
how to remove table row based on contents of one of the cells in the row using python?
I have html document with table like: <tr> <td width="3%"><input type="checkbox", name="chk"></td> <td width="10%">101</td> <td width="4%">Fix</td> <td width="5%">2.00</td> <td width="6%">09:28:03</td> <td width="5%">5</td> <td width="9%">6026866.421</td> <td width="9%">6525118.804</td> <td width="5%">149.124</td> <td ...
[ "You might want to look at Beautiful Soup, a python parser for HTML and XML.\n", "Using Beautiful Soup (this is just a start, there's much to improve, like how to check for zero and you also have to make up your mind if you want to check the third or the fourth cell):\nsoup = BeautifulSoup(open('yourhtml.html').r...
[ 3, 3 ]
[]
[]
[ "html", "python" ]
stackoverflow_0008432769_html_python.txt
Q: Setup run configurations for every script for project in Eclipse I work in eclipse+pydev. In my projects I have approximately 100-200 files and every script can be execute. Eclipse can setup run configuration for every one by one. But I'd like to setup one run configuration for project and I'd like to use this con...
Setup run configurations for every script for project in Eclipse
I work in eclipse+pydev. In my projects I have approximately 100-200 files and every script can be execute. Eclipse can setup run configuration for every one by one. But I'd like to setup one run configuration for project and I'd like to use this configuration for every script for launch. I needed this because I have c...
[ "Right now that's not possible in PyDev, and I'm not sure it'd be so useful -- if there's some parameter you have to pass to 200 scripts, the usual way to have that configuration would not be as command line arguments, but usually through an environment variables or some configuration file (whose default location w...
[ 0 ]
[]
[]
[ "aptana", "eclipse", "pydev", "python" ]
stackoverflow_0008427030_aptana_eclipse_pydev_python.txt
Q: python gtk loop ascii spinner I am trying (for testing) to have a little ascii spinner object being printed on the screen during a gtk.main() loop. Currently, I have this code which prints a dot every two seconds. gobject.timeout_add(2 * 1000, lambda : (sys.stdout.write('.'), sys.stdout.flush()) ...
python gtk loop ascii spinner
I am trying (for testing) to have a little ascii spinner object being printed on the screen during a gtk.main() loop. Currently, I have this code which prints a dot every two seconds. gobject.timeout_add(2 * 1000, lambda : (sys.stdout.write('.'), sys.stdout.flush()) ) gtk.main() However, I would ...
[ "Why are you limiting yourself to a lambda? To do a spinner, it's easiest to maintain state:\nclass Spinner(object):\n def __init__(self):\n self._chars = r\"-\\|/-\\|/\"\n self._pos = 0\n\n def spin(self):\n sys.stdout.write(self._chars[self._pos])\n sys.stdout.write(\"\\r\")\n sys.stdout.flush()\...
[ 2, 2 ]
[]
[]
[ "lambda", "pygtk", "python" ]
stackoverflow_0008432790_lambda_pygtk_python.txt
Q: Comparing two database entries with sqlalchemy I've a table of Users with a one-to-many relationship on a table of Visits (each User had two Visits). In Visits are multiple columns, including Score. For each User, I'd like to calculate the difference in their Score across the two Visits. What is the most sane way...
Comparing two database entries with sqlalchemy
I've a table of Users with a one-to-many relationship on a table of Visits (each User had two Visits). In Visits are multiple columns, including Score. For each User, I'd like to calculate the difference in their Score across the two Visits. What is the most sane way to do this with SQLAlchemy? In lieu of calculating ...
[ "The following code will return the list of (User.id, Score1-Score2) pairs for users that have (at least) 2 visits:\nfrom sqlalchemy.orm import aliased\n\nVisit1 = aliased(Visit)\nVisit2 = aliased(Visit)\nsession.query(User)\\\n .join(Visit1, (Visit1.user_id==User.id) & (Visit1.visit_number==1))\\\n .join(Vis...
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0008420778_python_sql_sqlalchemy.txt
Q: Waf: How to output a generated file? I have a file I want to send to the build directory after it's been pushed through a python script. How would I do this in waf? For example, if I had a file like this: VERSION=%%VERSION%% DATADIR=%%DATADIR%% And wanted to replace %%VERSION%% and %%DATADIR%% before outputing...
Waf: How to output a generated file?
I have a file I want to send to the build directory after it's been pushed through a python script. How would I do this in waf? For example, if I had a file like this: VERSION=%%VERSION%% DATADIR=%%DATADIR%% And wanted to replace %%VERSION%% and %%DATADIR%% before outputing that to the waf build directory, how woul...
[ "If you simply want to substitute an input file your versionfile.ver should look like this\nVERSION=@VERSION@\nDATADIR=@DATADIR@\n\nNow you can use the following task so the values will be substituted\nbld.new_task_gen (\n features = \"subst\",\n source= \"versionfile.ver\",\n target= \"versionfile.out\",\n VER...
[ 4 ]
[]
[]
[ "build", "python", "waf" ]
stackoverflow_0008422308_build_python_waf.txt
Q: How to shutdown and start a server in Python Twisted? My client (based on twisted) is supposed to automatically reconnect to server when connection is lost, i need to make a test of this feature, here's my test method where the @todo comment is very clear about what behaviour is expected: @defer.inlineCallbacks de...
How to shutdown and start a server in Python Twisted?
My client (based on twisted) is supposed to automatically reconnect to server when connection is lost, i need to make a test of this feature, here's my test method where the @todo comment is very clear about what behaviour is expected: @defer.inlineCallbacks def test_reconnect_on_connection_loss(self): client = SMP...
[ "Your server is still running (as far as anyone can tell from the code in your question). Closing one connection to a client doesn't stop the server from accepting new connections.\nThe way to stop a listening port from listening is with port.stopListening() (note that it returns a Deferred). You can start listen...
[ 2 ]
[]
[]
[ "python", "trial", "twisted" ]
stackoverflow_0008424007_python_trial_twisted.txt
Q: n-dimensional traverse I'm implementing the longest common subsequence for n dimensions. Current problem: how do I traverse the n strings? Simply nesting for loops won't work anymore, because I need n of them. What's the nice solution for that problem? Loops + recursion, I suppose, but how exactly? I'm not asking ...
n-dimensional traverse
I'm implementing the longest common subsequence for n dimensions. Current problem: how do I traverse the n strings? Simply nesting for loops won't work anymore, because I need n of them. What's the nice solution for that problem? Loops + recursion, I suppose, but how exactly? I'm not asking for the complete algorithm, ...
[ "If you don't want to do it by recursion, \nyou can implement n nested \"for\" loops, like this\n(the \"for\" loops aren't literally for loops any more, though):\ni is the array of indices.\nm is the array of upper limits of each i\nii is the index of the i indices (range(n))\nn=4 # just an example\nm=[3 for ii in ...
[ 2, 1 ]
[]
[]
[ "n_dimensional", "python", "traversal" ]
stackoverflow_0008431902_n_dimensional_python_traversal.txt
Q: How to map the most "similar" strings from one list to another in python? Given are two lists containing strings. One contains the name of organisations (mostly universitys) all around the world - not only written in english but always using latin alphabet. The other list contains mostly full addresses in which s...
How to map the most "similar" strings from one list to another in python?
Given are two lists containing strings. One contains the name of organisations (mostly universitys) all around the world - not only written in english but always using latin alphabet. The other list contains mostly full addresses in which strings (organisations) from the first list may occur. An Example: addresses = ...
[ "Use the following as your string distance function (instead of plain levenshtein distance):\ndef strdist(s1, s2):\n words1 = set(w for w in s1.split() if len(w) > 3)\n words2 = set(w for w in s2.split() if len(w) > 3)\n\n scores = [min(levenshtein(w1, w2) for w2 in words2) for w1 in words1]\n n_shared_...
[ 2, 0 ]
[]
[]
[ "python", "string_matching" ]
stackoverflow_0008432799_python_string_matching.txt
Q: Complex grouping and averages in Django I have a model structure like this: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Book(models.Model): published = models.DateTimeField() name = models.CharField(max_length=300, unique=True) authors = mod...
Complex grouping and averages in Django
I have a model structure like this: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Book(models.Model): published = models.DateTimeField() name = models.CharField(max_length=300, unique=True) authors = models.ForeignKey(Author) category = models.F...
[ "Ouch, hard ones.\nSince these are not informations that you will need often to be refreshed, I would suggest you add 3 fields to the Author model, then attach a post_save signal on the Book model: every time a book is created, you just calculate those values and store them in the Author model.\nYou will then be ab...
[ 2 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0008404236_django_django_queryset_python.txt
Q: Using my own gensalt() - Is it safe enough? Since the mechanism of bcrypt is: >>> myhash = bcrypt.hashpw('testpassword', bcrypt.gensalt(12)) >>> myhash '$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi' >>> bcrypt.hashpw('testpassword', myhash) '$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8x...
Using my own gensalt() - Is it safe enough?
Since the mechanism of bcrypt is: >>> myhash = bcrypt.hashpw('testpassword', bcrypt.gensalt(12)) >>> myhash '$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi' >>> bcrypt.hashpw('testpassword', myhash) '$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi' I want to use it for auth. The problem ...
[ "The short answer is: No, what you are describing isn't secure at all. \nFirst of all, bcrypt is not an encryption function and there for its results of this function cannot be \"decrypted\". bcrypt is a message digest function built using blowfish. Hashes produced by a message digest function are cracked.\nIt i...
[ 1 ]
[]
[]
[ "bcrypt", "python", "security" ]
stackoverflow_0008433475_bcrypt_python_security.txt
Q: Multiprocessing in following python code does not work I'm trying to increase the execution time of my python program by using some multiprocessing. Suppose I have this sample code: def foo(q,x,y): .... q.put(result) def parallel_funtion(x): q1 = Queue(); q2 = Queue() p1 = Process(target=foo, ...
Multiprocessing in following python code does not work
I'm trying to increase the execution time of my python program by using some multiprocessing. Suppose I have this sample code: def foo(q,x,y): .... q.put(result) def parallel_funtion(x): q1 = Queue(); q2 = Queue() p1 = Process(target=foo, args=[q1,x,0]) p2 = Process(target=foo...
[ "The question is short on specifics, but this works for me... I modified your use of list, since that appears to destroy python's list method (although as you say, the code still executes):\nfrom multiprocessing import Process, Queue\nimport time\n\ndef foo1(queue, procid, arg1, arg2):\n # Measure execution time...
[ 2 ]
[]
[]
[ "cycle", "multiprocessing", "python" ]
stackoverflow_0008433592_cycle_multiprocessing_python.txt