content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python: detecting install location of python tools Python's installation comes with some handy tools, located under $YOUR_PYTHON/Tools/Scripts. Is there a platform-independent way to find out where on a system they are located? I want to use ftpmirror.py as part of a shell script. A: I see you are talking about...
Python: detecting install location of python tools
Python's installation comes with some handy tools, located under $YOUR_PYTHON/Tools/Scripts. Is there a platform-independent way to find out where on a system they are located? I want to use ftpmirror.py as part of a shell script.
[ "I see you are talking about the source bundle of Python, which includes Tools/Scripts, a set of helpful scripts for working with Python Source. It should be noted that they are not a part of Python Standard Library and installers are not obliged to bundle them with their distribution, for e.g in Ubuntu, I don't fi...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0004722072_python.txt
Q: Heavy usage of Python at Google Google's heavy usage of Python, is it just a matter of taste or does it give them a competitive advantage? A: I can't really give a definitive answer, because by the time I interviewed at Google in 2004 Python was already prominent at Google. Indeed, there's one apparently attract...
Heavy usage of Python at Google
Google's heavy usage of Python, is it just a matter of taste or does it give them a competitive advantage?
[ "I can't really give a definitive answer, because by the time I interviewed at Google in 2004 Python was already prominent at Google.\nIndeed, there's one apparently attractive explanation that I can definitely deny: it's not that Google uses Python because it employs so many prominent Pythonistas -- rather, most \...
[ 303, 35, 28, 20 ]
[]
[]
[ "python" ]
stackoverflow_0002560310_python.txt
Q: custom signals in django am having problem with django custom signals not being able to see signals across application. I made a simple call in my core/signals.py from django.dispatch.dispatcher import Signal # Signal-emitting code... emits whenever a file upload is received # ------------------------------------...
custom signals in django
am having problem with django custom signals not being able to see signals across application. I made a simple call in my core/signals.py from django.dispatch.dispatcher import Signal # Signal-emitting code... emits whenever a file upload is received # ---------------------------------------------------------------- ...
[ "You haven't imported the upload_recieved name into your admin.py.\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004722255_django_python.txt
Q: Python Twisted receive command from TCP write to Serial device return response I've managed to connect to usb modem and a client can connect via tcp to my reactor.listenTCP,the data received from modem will be send back to client. I'm want to take dataReceived from client and send this to modem..I'm struggling to ...
Python Twisted receive command from TCP write to Serial device return response
I've managed to connect to usb modem and a client can connect via tcp to my reactor.listenTCP,the data received from modem will be send back to client. I'm want to take dataReceived from client and send this to modem..I'm struggling to get this to work.Any help will be highly appreciated! the code: from twisted.interne...
[ "Your problem is not about twisted, but about python. Read this FAQ entry:\n\nHow do I make input on one connection result in output on another?\n\nThing is, if you want to send stuff to a TCP-connected client in your serial-connected protocol, just pass to the protocol a reference to the factory, so you can use th...
[ 5, 0 ]
[]
[]
[ "python", "serial_port", "twisted" ]
stackoverflow_0004715340_python_serial_port_twisted.txt
Q: Freeze of pip requirements, NumPy and SciPy on OS X I've got a pip requirements file that I'm using with virtualenv to automatically grab dependencies for my application. The application depends on both NumPy and SciPy and as such my pip requirements file includes: numpy==1.5.0 scipy==0.8.0 However, when running ...
Freeze of pip requirements, NumPy and SciPy on OS X
I've got a pip requirements file that I'm using with virtualenv to automatically grab dependencies for my application. The application depends on both NumPy and SciPy and as such my pip requirements file includes: numpy==1.5.0 scipy==0.8.0 However, when running this pip in a new virtualenv, the installation fails with...
[ "I don't think you can. Pip and setuptools are not standard tools - we try to support them on a good-will basis, but it is brittle. In particular, because scipy setup.py needs numpy to run, it cannot work using the install_requires argument. \n", "I just ran into the exact same problem! Luckily the latest develop...
[ 4, 1 ]
[]
[]
[ "numpy", "pip", "python", "scipy", "virtualenv" ]
stackoverflow_0004155888_numpy_pip_python_scipy_virtualenv.txt
Q: Can I do custom complicated group by in a Django QuerySet? I need to do a sum of a certain column grouped by date and month. In SQL (postgres), it would look something like this: select sum(amount) from somewhere group by extract(year from date), extract(month from date) Can this be expressed as a Django QuerySet...
Can I do custom complicated group by in a Django QuerySet?
I need to do a sum of a certain column grouped by date and month. In SQL (postgres), it would look something like this: select sum(amount) from somewhere group by extract(year from date), extract(month from date) Can this be expressed as a Django QuerySet? Seems to me like it can't, but I don't really want to resort t...
[ "You can use the extra method to add in the year and date values before doing the aggregation.\nSomewhere.objects.extra(select={'year': 'EXTRACT(year FROM date)',\n 'month': 'EXTRACT(month FROM date)'}\n ).values_list('year', 'month').annotate(Sum('amount'))\n\n"...
[ 9, 1 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0004722605_django_django_queryset_python.txt
Q: How to not display script name when looping on command line argument? I am not familiar at all with Python. I am just trying to create a basic script where I would like to get all the command line argument without the script name. When I do for arg in sys.argv: print arg I get the following oupu...
How to not display script name when looping on command line argument?
I am not familiar at all with Python. I am just trying to create a basic script where I would like to get all the command line argument without the script name. When I do for arg in sys.argv: print arg I get the following ouput : <scriptname> <arg1> <arg2> <argn> So : How can I skip the scriptname ...
[ "for arg in sys.argv[1:]: \n print arg\n\nThis is called slicing and is supported for any list-like structure including strings. More examples:\n>>> s = \"Hello\"\n>>> s[1:]\n'ello'\n>>> s[:2]\n'He'\n\nSlicing also supports negative indices:\n>>> s[:-1]\n'Hell'\n>>> s[:-2]\n'Hel'\n\n" ]
[ 13 ]
[]
[]
[ "python" ]
stackoverflow_0004723254_python.txt
Q: Python: Regular expression to match alpha-numeric not working? I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore. My code: if re.match('[a-zA-Z0-9_]',playerName): # do stuff For some reason, this matches with crazy chars for...
Python: Regular expression to match alpha-numeric not working?
I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore. My code: if re.match('[a-zA-Z0-9_]',playerName): # do stuff For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆ I only want regular A-Z and 0-9 and _ matchi...
[ "Python has a special sequence \\w for matching alphanumeric and underscore when the LOCALE and UNICODE flags are not specified. So you can modify your pattern as,\npattern = '^\\w+$'\n", "Your regex only matches one character. Try this instead:\nif re.match('^[a-zA-Z0-9_]+$',playerName): \n\n", "\n…check if is...
[ 65, 47, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004722998_python_regex.txt
Q: Logging between classes in python I have three classes in python and they run in different threads. I would like to have output to the same file from all classes. Right now I created output method in main class and passing it through constructors to other classes. Is there way to handle it better? How I can pass t...
Logging between classes in python
I have three classes in python and they run in different threads. I would like to have output to the same file from all classes. Right now I created output method in main class and passing it through constructors to other classes. Is there way to handle it better? How I can pass the logger between classes except using ...
[ "import logging\nlog = logging.getLogger(\"mylog\")\nlog.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter(\n \"%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s\")\n# Alternative formatting available on python 3.2+:\n# formatter = logging.Formatter(\n# \"{asctime} {threadName:>11} {levelname...
[ 25 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0004722745_logging_python.txt
Q: Cron works on local host but not when deployed Appengine I have a cron job in python that works on my localhost but when it is deployed to appengine, it no longer works. pl = db.Query(Venue).order("id") list = pl.fetch(limit=0) for p in pl: base_url = 'http://search.twitter.com/search.json?rpp=1...
Cron works on local host but not when deployed Appengine
I have a cron job in python that works on my localhost but when it is deployed to appengine, it no longer works. pl = db.Query(Venue).order("id") list = pl.fetch(limit=0) for p in pl: base_url = 'http://search.twitter.com/search.json?rpp=100&q=4sq.com/' query = p.twitter_ID url_string...
[ "The JSON 'results' field is not returned because the requests per Ip that Twitter allows has reached the max quota of available requests; this explains why from your domestic IP you don't have any problem and you don't get an HTTP 420 response code. \nUnluckily Google App Engine uses a shared pool of IP addresses...
[ 3 ]
[]
[]
[ "cron", "google_app_engine", "python" ]
stackoverflow_0004722315_cron_google_app_engine_python.txt
Q: How to fix a python egg? I added a jabber support to my python bot by importing the xmppy library. However calling "import xmpp" attracts a few warnings: /usr/lib/python2.6/site-packages/xmpp/auth.py:24: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha,base64,ra...
How to fix a python egg?
I added a jabber support to my python bot by importing the xmppy library. However calling "import xmpp" attracts a few warnings: /usr/lib/python2.6/site-packages/xmpp/auth.py:24: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha,base64,random,dispatcher,re /usr/li...
[ "First of all the message that you saw above are just some warning, DeprecationWarning to be exact that mean that some of the module that xmpp library use are deprecate (old module that will be remove in new version of python so they should be replaced by the new ones), and you shouldn't try to fix it, it's not you...
[ 2 ]
[]
[]
[ "egg", "macos", "python" ]
stackoverflow_0004723484_egg_macos_python.txt
Q: Using paste.progress In A Pyramid Project I need to keep track of a file's upload progress and found the paste.progress middleware. It seems like what I want. How would I add and use the paste.progress middleware in a Pyramid project? A: File uploads with WSGI middleware were recently commented at Pylons user gr...
Using paste.progress In A Pyramid Project
I need to keep track of a file's upload progress and found the paste.progress middleware. It seems like what I want. How would I add and use the paste.progress middleware in a Pyramid project?
[ "File uploads with WSGI middleware were recently commented at Pylons user group.\n" ]
[ 2 ]
[]
[]
[ "middleware", "paste", "pyramid", "python", "wsgi" ]
stackoverflow_0004720318_middleware_paste_pyramid_python_wsgi.txt
Q: Python memory array shared among multiple threads (think memcached in process space) So I have a program that is multi threaded, in a nutshell it downloads web pages, processes them and stores the results. The rules and whatnot it uses to process the web pages are stored within a database. Initially the database w...
Python memory array shared among multiple threads (think memcached in process space)
So I have a program that is multi threaded, in a nutshell it downloads web pages, processes them and stores the results. The rules and whatnot it uses to process the web pages are stored within a database. Initially the database was absolutely hammered (1-50 requests to the database were needed to process each web page...
[ "If I understood correctly, the problem is that multiple threads tend to retrieve the same data from memcached simultaneously. You'd like to coordinate the threads so that one thread retrieves the data, while others wait, and share the data after it has arrived.\nMake a wrapper class for the objects you want to cac...
[ 1, 0 ]
[]
[]
[ "locking", "memcached", "multithreading", "python" ]
stackoverflow_0004721285_locking_memcached_multithreading_python.txt
Q: How to intercept instance method calls? I am looking for a way to intercept instance method calls in class MyWrapper below: class SomeClass1: def a1(self): self.internal_z() return "a1" def a2(self): return "a2" def internal_z(self): return "z" class SomeClass2(SomeCla...
How to intercept instance method calls?
I am looking for a way to intercept instance method calls in class MyWrapper below: class SomeClass1: def a1(self): self.internal_z() return "a1" def a2(self): return "a2" def internal_z(self): return "z" class SomeClass2(SomeClass1): pass class MyWrapper(SomeClass2): ...
[ "Some quick and dirty code:\nclass Wrapper:\n def __init__(self, obj):\n self.obj = obj\n self.callable_results = []\n\n def __getattr__(self, attr):\n print(\"Getting {0}.{1}\".format(type(self.obj).__name__, attr))\n ret = getattr(self.obj, attr)\n if hasattr(ret, \"__call...
[ 7, 2, 2 ]
[]
[]
[ "call", "function", "getattr", "instance", "python" ]
stackoverflow_0004723717_call_function_getattr_instance_python.txt
Q: How to write a auto suggestion search in python? How to write a database driven auto-suggestion search using python, mysql and jquery? Are there any relevant tutorials. Because Googling just gave me several results for PHP but not anything relevant to Python. A: There is a nice jQuery plugin for this, http://do...
How to write a auto suggestion search in python?
How to write a database driven auto-suggestion search using python, mysql and jquery? Are there any relevant tutorials. Because Googling just gave me several results for PHP but not anything relevant to Python.
[ "There is a nice jQuery plugin for this, http://docs.jquery.com/Plugins/autocomplete.\nTo use your data with it, you need to write a controller in python that returns the autocomplete data as a JSON structure. \nYou also need to pick a good framework for writing the actual controller in, check this question for som...
[ 2, 2 ]
[]
[]
[ "jquery", "python", "search" ]
stackoverflow_0004722726_jquery_python_search.txt
Q: How to decode JSON to str and not unicode in Python (2.6)? I have a configuration file in JSON that contains a few variables as strings (always ascii). These strings are decoded to unicode by default but since I have to pass these variables to my Python C Extensions I need them as normal Python strings. At the mom...
How to decode JSON to str and not unicode in Python (2.6)?
I have a configuration file in JSON that contains a few variables as strings (always ascii). These strings are decoded to unicode by default but since I have to pass these variables to my Python C Extensions I need them as normal Python strings. At the moment I'm using str(unicode) to convert the JSON strings but a mor...
[ "Not if you're not willing to lose some speed. If being somewhat slower is OK, you have to consider that using plain json.loads and recursively converting to str is probably cheaper and maybe faster. \nWith all that said, if you do want a loads that returns strings badly enough to accept going through extending cod...
[ 1, 0 ]
[]
[]
[ "json", "python", "unicode" ]
stackoverflow_0004723535_json_python_unicode.txt
Q: Problem with an integer in Python 3.1 My problem is in line 13(else). I get the error "invalid syntax" Answer = 23 Guess = () Gender = input("Are you a boy, a girl or an alien? ") if Gender == 'boy' or 'Boy': print("Nice!", Gender) if Gender == 'girl' or 'Girl': print("Prepare do die!", Gender) if Gende...
Problem with an integer in Python 3.1
My problem is in line 13(else). I get the error "invalid syntax" Answer = 23 Guess = () Gender = input("Are you a boy, a girl or an alien? ") if Gender == 'boy' or 'Boy': print("Nice!", Gender) if Gender == 'girl' or 'Girl': print("Prepare do die!", Gender) if Gender == 'alien' or 'Alien': print("AWESOM...
[ "Your problem is indentation. The if has to line-up with the else. You also seem to have a leading space before the while which must go.\nif Guess < Answer:\n print(\"Too low! try again\")\n else:\n print(\"too high\")\n\nshould be\nif Guess < Answer:\n print(\"Too low! try again\")\nelse:\n pri...
[ 4, 0, 0 ]
[]
[]
[ "integer", "python", "python_3.x" ]
stackoverflow_0004717956_integer_python_python_3.x.txt
Q: Is there any *testability-explorer* like tool for Python? testability-explorer is a tool for measuring how hard to unit test java program. Is there any tool like this for Python? A: Since Python is a dynamic language, "examining" the bytecode may reveal approximately nothing useful. A Python program can use exe...
Is there any *testability-explorer* like tool for Python?
testability-explorer is a tool for measuring how hard to unit test java program. Is there any tool like this for Python?
[ "Since Python is a dynamic language, \"examining\" the bytecode may reveal approximately nothing useful. A Python program can use exec, execfile() and __import__() to introduce code \"on-the-fly\", defeating bytecode analysis.\nNon-Mockable Total Recursive Cyclomatic Complexity. Assuming the bytecode is actually ...
[ 2 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0004722766_python_unit_testing.txt
Q: Best way to write a Python function that integrates a gaussian? In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone h...
Best way to write a Python function that integrates a gaussian?
In attempting to use scipy's quad method to integrate a gaussian (lets say there's a gaussian method named gauss), I was having problems passing needed parameters to gauss and leaving quad to do the integration over the correct variable. Does anyone have a good example of how to use quad w/ a multidimensional function?...
[ "Okay, you appear to be pretty confused about several things. Let's start at the beginning: you mentioned a \"multidimensional function\", but then go on to discuss the usual one-variable Gaussian curve. This is not a multidimensional function: when you integrate it, you only integrate one variable (x). The distinc...
[ 34, 16, 4, 3, 3 ]
[]
[]
[ "gaussian", "integral", "python", "scipy" ]
stackoverflow_0000509994_gaussian_integral_python_scipy.txt
Q: assign references Is there a way to assign references in python? For example, in php i can do this: $a = 10; $b = &$a; $a = 20; echo $a." ".$b; // 20, 20 how can i do same thing in python? A: In python, if you're doing this with non-primitive types, it acts exactly like you want: assigning is done using refer...
assign references
Is there a way to assign references in python? For example, in php i can do this: $a = 10; $b = &$a; $a = 20; echo $a." ".$b; // 20, 20 how can i do same thing in python?
[ "In python, if you're doing this with non-primitive types, it acts exactly like you want: assigning is done using references. That's why, when you run the following:\n>>> a = {'key' : 'value'}\n>>> b = a\n>>> b['key'] = 'new-value'\n>>> print a['key']\n\nyou get 'new-value'.\nStrictly saying, if you do the followin...
[ 12, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004724757_python.txt
Q: Safely interrupt a program with threaded downloading I have a (commandline/terminal) program that scrapes a website with worker threads that do the downloading from a queue and a main thread that downloads the index files (50 entries per page). How can I make the program check for an interrupt (either CTRL+C or my...
Safely interrupt a program with threaded downloading
I have a (commandline/terminal) program that scrapes a website with worker threads that do the downloading from a queue and a main thread that downloads the index files (50 entries per page). How can I make the program check for an interrupt (either CTRL+C or my own defined one), and when it catches such interrupt it w...
[ "Wrap the main function that's waiting for the threads to complete with an exception handler like this:\ntry:\n main()\nexcept KeyboardInterrupt:\n stop()\n\ndef stop():\n for t in threads:\n t.my_stop_function()\n # wait for threads to stop here...\n\nclass MyThread(threading.Thread):\n def _...
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "web_scraping" ]
stackoverflow_0004725105_multithreading_python_web_scraping.txt
Q: split text into lines by the number of characters I have some text for example: 'This is a line of text over 10 characters' That I need to be broken into lines consisting of no more than 10 characters without breaking words unless I need to (for example a line with work containing more than 10 characters). The li...
split text into lines by the number of characters
I have some text for example: 'This is a line of text over 10 characters' That I need to be broken into lines consisting of no more than 10 characters without breaking words unless I need to (for example a line with work containing more than 10 characters). The line above would turn into: 'This is a\nline of\ntext ove...
[ "You need textwrap\n>>> import textwrap\n>>> s = 'This is a line of text over 10 characters'\n>>> textwrap.fill(s, width=10)\n'This is a\\nline of\\ntext over\\n10\\ncharacters'\n\n" ]
[ 16 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004725249_python_string.txt
Q: RC variables in matplotlib doesn't apply to graphs, axes in web app I'm trying to set line widths for matplotlib in a web application that generates graphs using matplotlib.rc('lines', linewidth=0.5) This works fine when working with matplotlib in interactive mode, but in my web application it has no effect, and...
RC variables in matplotlib doesn't apply to graphs, axes in web app
I'm trying to set line widths for matplotlib in a web application that generates graphs using matplotlib.rc('lines', linewidth=0.5) This works fine when working with matplotlib in interactive mode, but in my web application it has no effect, and the only way I can get the correct line widths is by supplying the argum...
[ "What you've posted should work. Just as a reference, the following works perfectly for me using python 2.6 and matplotlib 1.0. \nfrom contextlib import contextmanager\n\nimport matplotlib as mpl\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\n...
[ 1 ]
[]
[]
[ "matplotlib", "pylons", "python" ]
stackoverflow_0004723271_matplotlib_pylons_python.txt
Q: Python binary executable with MSAA hangs on exit I'm using python comtypes to get access to IAccessible interface for MSAA (Microsoft Active Accessibility) usage. After that we create binary executable using pyinstaller, so the problem is that on specific platform - Windows XP x64 our executable hangs on exit. It ...
Python binary executable with MSAA hangs on exit
I'm using python comtypes to get access to IAccessible interface for MSAA (Microsoft Active Accessibility) usage. After that we create binary executable using pyinstaller, so the problem is that on specific platform - Windows XP x64 our executable hangs on exit. It hangs on WaitFotMultipleObjectsEx in ole32.dll after t...
[ "I'm not able to clearly understood the root reason of this issue currently. But the solution was found, even two.\nFirst: to add an additional call to CoUninitialize function.\nDon't know why it works as the comtypes calls CoUninitialize the same times as CoInitialize.\nSecond: to change CoInitializeEx flags, caus...
[ 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0004707661_pyinstaller_python.txt
Q: Detect wrong character encodings using python I'm new to serious programming and I was trying to write a python program where I encountered strings in this form while reading from a file: Îêåàí Åëüçè - Ìàéæå âåñíà Ëÿïèñ Òðóáåöêîé - Ñâÿùåííûé Îãîíü which is actually supposed to be in cyrillic (cp-1251), so this str...
Detect wrong character encodings using python
I'm new to serious programming and I was trying to write a python program where I encountered strings in this form while reading from a file: Îêåàí Åëüçè - Ìàéæå âåñíà Ëÿïèñ Òðóáåöêîé - Ñâÿùåííûé Îãîíü which is actually supposed to be in cyrillic (cp-1251), so this string is the victim of wrong encoding (I found it aft...
[ "Well, that Cyrillic string isn't in cp-1251. As you seem to have found out, it has been encoded \"twice\". Most likely somebody took a binary string in cp1251 believed it was in utf8 and encoded it in cp1252, or something like that. \nNo automatic check could figure that out.\n>>> print 'Îêåàí Åëüçè - Ìàéæå âåñíà'...
[ 4 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0004725274_character_encoding_python.txt
Q: py.test how to run a method before every test I used unittest and nose for unit-testing in Python but now I'm using py.test. unittest and nose always call class.setUp before executing every method in the TestCase. How can I do this with py.test? EDIT: If I add this: def setup_class(cls): cls.a = pypol.polyno...
py.test how to run a method before every test
I used unittest and nose for unit-testing in Python but now I'm using py.test. unittest and nose always call class.setUp before executing every method in the TestCase. How can I do this with py.test? EDIT: If I add this: def setup_class(cls): cls.a = pypol.polynomial('x^3 - 2x^2 + x -5') cls.b = pypol.polynom...
[ "Sounds like you need to define setup_method on the test class:\nhttps://codespeak.net/py/0.9.2/test.html#managing-test-state-across-test-modules-classes-and-methods\n" ]
[ 1 ]
[]
[]
[ "pytest", "python", "unit_testing" ]
stackoverflow_0004725948_pytest_python_unit_testing.txt
Q: Parsing an XML file using Element Tree I have a large number of .xml files (about 70) and i need to extract some co-ordinates from them. Apparently the best way to do this is to parse the xml file using element tree. I am new to python (very very new!) and am having a difficult time understanding all of the docum...
Parsing an XML file using Element Tree
I have a large number of .xml files (about 70) and i need to extract some co-ordinates from them. Apparently the best way to do this is to parse the xml file using element tree. I am new to python (very very new!) and am having a difficult time understanding all of the documentation which comes with element tree! I w...
[ "ElementTree can be tricky when namespaces are involved. The element you are looking for are named <gml:lowerCorner> and <gml:upperCorner>. Searching higher in the XML data, gml is defined as an XML namespace: xmlns:gml=\"http://www.opengis.net/gml\". The way to find a subelement of the XML tree is as follows:\n...
[ 11, 2 ]
[]
[]
[ "elementtree", "parsing", "python", "xml" ]
stackoverflow_0004722794_elementtree_parsing_python_xml.txt
Q: Parsing command line input for numbers I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example: $ myapp -n 3,4,5,6 or $ myapp -n 3-6 I would like my app to put these into a Python list e.g., [3, 4, 5, 6] I'm using optparse, b...
Parsing command line input for numbers
I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example: $ myapp -n 3,4,5,6 or $ myapp -n 3-6 I would like my app to put these into a Python list e.g., [3, 4, 5, 6] I'm using optparse, but am not sure how to create the list from t...
[ "import argparse\n\ndef parse_range(astr):\n result = set()\n for part in astr.split(','):\n x = part.split('-')\n result.update(range(int(x[0]), int(x[-1]) + 1))\n return sorted(result)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-n', type=parse_range)\nargs = parser.parse_ar...
[ 15, 3, 2, 1, 1 ]
[]
[]
[ "command_line", "parsing", "python" ]
stackoverflow_0004726168_command_line_parsing_python.txt
Q: Can you help me with linear activation of my Simple Classifier Neural Network in pyBrain? I'm trying a very simple case using a Python library called pyBrain and I can't get it to work. There is likely to be a very simple reason, so, I hope someone can help! 1) A simple XOR works fine. 2) Classifying the led'...
Can you help me with linear activation of my Simple Classifier Neural Network in pyBrain?
I'm trying a very simple case using a Python library called pyBrain and I can't get it to work. There is likely to be a very simple reason, so, I hope someone can help! 1) A simple XOR works fine. 2) Classifying the led's displayed on a digital clock to the numerical output value works fine. e.g. [ 1. 1. 1. 0...
[ "A linear activation is fine when you're doing regression (single output node representing a range of values) but for classification (binary outputs representing matches) you're better off using an activation that limits the range of values. Something like a sigmoid or tanh.\n", "I think rather than SO, MetaOpti...
[ 1, 0 ]
[]
[]
[ "artificial_intelligence", "classification", "neural_network", "python" ]
stackoverflow_0004726180_artificial_intelligence_classification_neural_network_python.txt
Q: effective use of python shutil copy2 if we take a look at a file copy function, we can see there are several exceptions to handle. A good example is here: http://msdn.microsoft.com/en-us/library/9706cfs5.aspx my question is if i use python shutil copy2, what should I pay attention to cope with various exceptions (...
effective use of python shutil copy2
if we take a look at a file copy function, we can see there are several exceptions to handle. A good example is here: http://msdn.microsoft.com/en-us/library/9706cfs5.aspx my question is if i use python shutil copy2, what should I pay attention to cope with various exceptions (source file not found, access not authoriz...
[ "You may just need handle the IOError exception that may be caused due to any permissions or Invalid destination name issue.\ntry:\n shutil.copy(src,dst)\nexcept IOError as e:\n print e\n\nThe other exceptions mentioned in the MSDN article seems to fall under the same IOError in python. The FileNotFound and D...
[ 9 ]
[]
[]
[ "copy", "exception_handling", "file", "python", "shutil" ]
stackoverflow_0004726260_copy_exception_handling_file_python_shutil.txt
Q: Is python exception handling more efficient than PHP and/or other languages? I have it drilled into my head that (at least in PHP) it is badbadmojo to use try... catch blocks for flow control. What I've learned is to use them only to handle unexpected errors, not determine the logic flow of the program, because c...
Is python exception handling more efficient than PHP and/or other languages?
I have it drilled into my head that (at least in PHP) it is badbadmojo to use try... catch blocks for flow control. What I've learned is to use them only to handle unexpected errors, not determine the logic flow of the program, because catch blocks are expensive. Now that I'm learning python, I see a lot of exceptions...
[ "Historically, in languages like C++, exceptions have been very slow compared to other forms of flow control in the same language.\nIn C++, there are two things at work:\n\nThrowing an exception is very complex. The stack needs to be unwound, and doing so in native code is much harder than in a high-level VM-based...
[ 15, 7, 3, 2, 0, 0 ]
[]
[]
[ "exception", "php", "programming_languages", "python" ]
stackoverflow_0004717484_exception_php_programming_languages_python.txt
Q: Python example of Joe's Erlang websocket example I've just been working through the erlang websockets example from Joe Armstrong's blog I'm still quite new to erlang so I decided to write a simple server in python that would help teach me about websockets (and hopefully some erlang by interpreting joe's code). I'm...
Python example of Joe's Erlang websocket example
I've just been working through the erlang websockets example from Joe Armstrong's blog I'm still quite new to erlang so I decided to write a simple server in python that would help teach me about websockets (and hopefully some erlang by interpreting joe's code). I'm having two issues: 1) Data I receive from the page in...
[ "For those who are interested this was the solution\nimport threading\nimport socket\n\ndef start_server():\n tick = 0\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind(('localhost', 1234))\n sock.listen(100)\n while True:\n print 'listening...'\n csock, address = s...
[ 10, 0, 0 ]
[]
[]
[ "python", "websocket" ]
stackoverflow_0002153294_python_websocket.txt
Q: I/O intensive serial port application: Porting from Threading, Queue based design to Asynchronous (ala Twisted) So, I've been working on an application for a client that communicates with wireless devices via a Serial (RS-232) "Master". I've currently written the core of the app using threading (below). I've been ...
I/O intensive serial port application: Porting from Threading, Queue based design to Asynchronous (ala Twisted)
So, I've been working on an application for a client that communicates with wireless devices via a Serial (RS-232) "Master". I've currently written the core of the app using threading (below). I've been noticing on #python that the consensus seems to be to NOT use threads and to use Twisted's asynchronous communication...
[ "It is very difficult (if not impossible) to write a direct one-to-one mapping program between threading/queue approach and one that uses twisted.\nI would suggest that, get a hang of twisted and its reactor way it's use of Protocol and the protocol specific methods. Think about it as as all the asynchronous things...
[ 7 ]
[]
[]
[ "multithreading", "python", "serial_port", "twisted" ]
stackoverflow_0004726391_multithreading_python_serial_port_twisted.txt
Q: Using muliple forms in the same view I am trying to learn django framework with few sample applications. Currently, I am working on a feedback/survey application. It uses the following models: class Survey(models.Model): title = models.CharField(_(max_length=255) slug = models.SlugField(_(max_length=255, u...
Using muliple forms in the same view
I am trying to learn django framework with few sample applications. Currently, I am working on a feedback/survey application. It uses the following models: class Survey(models.Model): title = models.CharField(_(max_length=255) slug = models.SlugField(_(max_length=255, unique=True) description= models.TextFi...
[ "The reason is probably that the names of the form fields clash.\nYou could work around that issue, but did you already have a look at the Formsets Documentation?\n\nA formset is a layer of abstraction to working with multiple forms on the same page.\n\n", "you can't get from request object, how many form there w...
[ 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004723688_django_python.txt
Q: Creating objects during runtime in Python I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person() What I have trouble understandin...
Creating objects during runtime in Python
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person() What I have trouble understanding now is how I would design a model that create...
[ "Things like lists or dictionaries are great for storing dynamically generated sets of values/objects:\nclass Person(object):\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n print \"A person named %s\" % self.name\n\npeople = {}\nwhile True:\n print \"Enter a name:\",\n...
[ 8, 2, 1, 1, 0 ]
[]
[]
[ "concept", "oop", "python" ]
stackoverflow_0004726501_concept_oop_python.txt
Q: Python currency codes into a list Does anyone have a nifty way to get all the three letter alphabetic currency codes (an example of the ones I mean is at http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm) into a list in Python 2.5? ...
Python currency codes into a list
Does anyone have a nifty way to get all the three letter alphabetic currency codes (an example of the ones I mean is at http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm) into a list in Python 2.5? Note I don't want to do a screen scrapi...
[ "Not very elegant or nifty, but you can generate the list once and save to use it later:\nimport urllib, re\nurl = \"http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/currency_codes/currency_codes_list-1.htm\"\nprint re.findall(r'\\<td valign\\=\"top\"\\>\\s+([A-WYZ][A-Z]{2}...
[ 1, 1 ]
[]
[]
[ "currency", "internationalization", "python" ]
stackoverflow_0004726558_currency_internationalization_python.txt
Q: Approximating a sphere in OpenGL I am trying to approximate a sphere using the instructions at http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/sphere_cylinder/, but it doesn't look right at all. This is my code: def draw_sphere(facets, radius=100): """approximate a sphere using a certain number of facets""...
Approximating a sphere in OpenGL
I am trying to approximate a sphere using the instructions at http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/sphere_cylinder/, but it doesn't look right at all. This is my code: def draw_sphere(facets, radius=100): """approximate a sphere using a certain number of facets""" dtheta = 180.0 / facets dph...
[ "I don't have a system here that can run Python and OpenGL together, but I can see a few issues anyway:\nYou're rounding dphi and dtheta in the range statements. This means that the facets will always start on a whole degree, but then when you add the unrounded delta values the far edge isn't guaranteed to do so. ...
[ 4 ]
[]
[]
[ "geometry", "opengl", "python" ]
stackoverflow_0004727048_geometry_opengl_python.txt
Q: Using Python and Mechanize to submit form data and authenticate I want to submit login to the website Reddit.com, navigate to a particular area of the page, and submit a comment. I don't see what's wrong with this code, but it is not working in that no change is reflected on the Reddit site. import mechanize impo...
Using Python and Mechanize to submit form data and authenticate
I want to submit login to the website Reddit.com, navigate to a particular area of the page, and submit a comment. I don't see what's wrong with this code, but it is not working in that no change is reflected on the Reddit site. import mechanize import cookielib def main(): #Browser br = mechanize.Browser() # Coo...
[ "I would definitely suggest trying to use the API if possible, but this works for me (not for your example post, which has been deleted, but for any active one):\n#!/usr/bin/env python\n\nimport mechanize\nimport cookielib\nimport urllib\nimport logging\nimport sys\n\ndef main():\n\n br = mechanize.Browser()\n ...
[ 19 ]
[]
[]
[ "mechanize", "networking", "python", "screen_scraping" ]
stackoverflow_0004720470_mechanize_networking_python_screen_scraping.txt
Q: django auto filling some data based on model attribute am working on a concept in which I want to capture certain information when a model is saved. To understand the full picture, I have a app core with the following model core/models.py from django.db import models from django.contrib.auth.models import User fr...
django auto filling some data based on model attribute
am working on a concept in which I want to capture certain information when a model is saved. To understand the full picture, I have a app core with the following model core/models.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType fro...
[ "I'd just create a function in my model class or Manager and call it from my form save (wherever yours might be)\nclass AuditManager(models.Manager):\n def save_from_object(self, request, obj):\n audit = Audit()\n audit.object_id = obj.id\n audit.operation_by = request.user\n # ...\n\...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004725685_django_python.txt
Q: python implemented in assembly Am just being curious but I would like to know whether python can be implemented in assembly and if not why has it not been done to help for speed issues. forgive my naivete in matters of programming languages. A: The main implementation is written in C, and that's compiled to mach...
python implemented in assembly
Am just being curious but I would like to know whether python can be implemented in assembly and if not why has it not been done to help for speed issues. forgive my naivete in matters of programming languages.
[ "The main implementation is written in C, and that's compiled to machine code (i.e. assembly made readable for the CPU). So writing it assembly is certainly possible, and if it's possible for a compiler, it's possible for humans - in theory. In practice, it is not even remotely practical. Not only asm is even more ...
[ 15, 6 ]
[]
[]
[ "python" ]
stackoverflow_0004727351_python.txt
Q: Accessing Python instance variables with __dict__- Is it wrong? If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys(). I want to use this attribute to print out all instance variables of an object. I am hesitant to do this because __dict__ is a "secret" attribute, a...
Accessing Python instance variables with __dict__- Is it wrong?
If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys(). I want to use this attribute to print out all instance variables of an object. I am hesitant to do this because __dict__ is a "secret" attribute, and I do not understand what this footnote means. So is it wrong to us...
[ "That footnote is in reference to the __dict__ attribute of a module. The __dict__ attribute of an object carries no such warning (documentation).\n", "What the footnote means is that you shouldn't try to access __dict__ directly but instead check if the feature/behavior you want is available.\nSo instead of doin...
[ 6, 6, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004727551_python.txt
Q: Is there an analogue of this function in Python standard modules? I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function: def defaulted(func, defaultVal): try: result = func() except: result = defaultVal return result Thanks...
Is there an analogue of this function in Python standard modules?
I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function: def defaulted(func, defaultVal): try: result = func() except: result = defaultVal return result Thanks!
[ "There's nothing like that in the stdlib (to the best of my knowledge). For one thing, it's bad practice: you should never use a bare except. (Instead, specify the exceptions you want to catch; that way, you won't catch everything!)\nHere's a decorator:\n>>> def defaultval(error, value):\n... def decorator(func...
[ 5, 3 ]
[]
[]
[ "exception", "python", "standard_library" ]
stackoverflow_0004727742_exception_python_standard_library.txt
Q: Dynamically add ManyToMany relationship to Django objects My Company class have multiple M2M relationship with itself class Company(models.Model): divisions = models.ManyToManyField('self', symmetrical=False, related_name="parent_companies") parents = models.ManyToManyField('self', symmetrical=False, related_nam...
Dynamically add ManyToMany relationship to Django objects
My Company class have multiple M2M relationship with itself class Company(models.Model): divisions = models.ManyToManyField('self', symmetrical=False, related_name="parent_companies") parents = models.ManyToManyField('self', symmetrical=False, related_name="divisions_companies") comp = models.ManyToManyField('self', ...
[ "Got it. Simply have to pass a list instead..\n company, was_created = Company.objects.get_or_create(name=info)\n setattr(self,key, [company,])\n\n", "The syntax is for adding M2M is field.add(obj_pk or obj)\ncompany, was_created = Company.objects.get_or_create(name=info)\nself.comp.add(com...
[ 6, 2 ]
[]
[]
[ "django", "dynamic", "python" ]
stackoverflow_0004727859_django_dynamic_python.txt
Q: What is the proper way to make a Python frozen binaries for OSX that can accept arguments? I've made a .app bundle from a python script using py2app. The issue is twofold: Argument emulation doesn't appear to work correctly because it doesn't accept the arguments that work on the original python script. The .app ...
What is the proper way to make a Python frozen binaries for OSX that can accept arguments?
I've made a .app bundle from a python script using py2app. The issue is twofold: Argument emulation doesn't appear to work correctly because it doesn't accept the arguments that work on the original python script. The .app bundle format needs to be opened by "open". "open" only supports passing arguments from OSX 10.6...
[ "In general, OS X app bundles are not designed to be started from a command line and passed arguments from a command line (as you note, OS X 10.6 added some support for this). The standard mechanism for passing files to an app is through Apple Events; this is used for the Finder's Open command of a document file w...
[ 2, 1 ]
[]
[]
[ "py2app", "python" ]
stackoverflow_0004586501_py2app_python.txt
Q: how to access derived class methods from another derived class I'm using wxpython to generate a GUI. The structure of the program I'm doing is shown below. I have a class for each section of the GUI (class1 and class2). I'm using the Panel class to create these sections. class1 and class2 are derived from another ...
how to access derived class methods from another derived class
I'm using wxpython to generate a GUI. The structure of the program I'm doing is shown below. I have a class for each section of the GUI (class1 and class2). I'm using the Panel class to create these sections. class1 and class2 are derived from another class (the Group class). I want to access the methods of a derived c...
[ "I's assuming you want to call the class method, not the method of an instance of that class.\nFrom ClassA.method1(), ClassB be should be a global, so all you have to do is:\nclass ClassA(Group):\n\n def method1(self):\n classB.method3(someclass)\n\nNow all you have to do is figure out what you want to pu...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004725859_python_wxpython.txt
Q: My auto suggestion is not working properly? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax Auto Suggest</t...
My auto suggestion is not working properly?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax Auto Suggest</title> <script type="text/javascript" src="{{ MED...
[ "This isn't a direct answer to your question, but have you tried using the 'official' jquery autocomplete? http://jqueryui.com/demos/autocomplete/\n" ]
[ 1 ]
[]
[]
[ "javascript", "jquery", "python" ]
stackoverflow_0004728412_javascript_jquery_python.txt
Q: CherryPy + Apache2 - Response cached I'm trying to develop a CherryPy based system. I'm actually using Apache2 web server + mod_python. I have the next problem: When I update the code of my cherrypy app, refresh several times the browser, and the result is the same as before editing. It seems to be caching the res...
CherryPy + Apache2 - Response cached
I'm trying to develop a CherryPy based system. I'm actually using Apache2 web server + mod_python. I have the next problem: When I update the code of my cherrypy app, refresh several times the browser, and the result is the same as before editing. It seems to be caching the response somewhere. When I restart the Apache...
[ "It's not from the cherrypy docs (but from Django's Running a development server with mod_python), but maybe it helps:\n\nJust set MaxRequestsPerChild 1 in your httpd.conf file to force Apache to reload everything for each request.\n\n" ]
[ 2 ]
[]
[]
[ "apache", "cherrypy", "mod_python", "python" ]
stackoverflow_0004728501_apache_cherrypy_mod_python_python.txt
Q: Reformating an external file and then saving it, from inside a python code Sorry for the basic question, but my python is a bit rusty after having not worked with it for a few months! Basically I am trying to run a python code over a list of files which are the output of another code (which unfortunately I cannot...
Reformating an external file and then saving it, from inside a python code
Sorry for the basic question, but my python is a bit rusty after having not worked with it for a few months! Basically I am trying to run a python code over a list of files which are the output of another code (which unfortunately I cannot alter). The problem is that the code I have written requires the files in "inpu...
[ "def generateFromFile ( fileName ):\n for line in open( fileName ):\n for segment in line.split( ',' ):\n yield segment\n\nfor ln in generateFromFile( \"input.txt\" ):\n ch.Add( ln.strip() )\n\n", "for x in files.split(','):\n print >> input, x\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004729373_python.txt
Q: Python dict question. How to group similar strings? for i in names: dict[i] = {'firstname': name[i]['firstname'], 'lastname': name[i]['lastname']} print dict[0]['firstname'] # John print dict[0]['lastname'] # Doe # group similar lastnames, along with their firstnames # ... retur...
Python dict question. How to group similar strings?
for i in names: dict[i] = {'firstname': name[i]['firstname'], 'lastname': name[i]['lastname']} print dict[0]['firstname'] # John print dict[0]['lastname'] # Doe # group similar lastnames, along with their firstnames # ... return render_to_response('index.html', dict) I want to group...
[ "You mean something like this:\nimport collections\n\ndata = [\n {'firstname': 'John', 'lastname': 'Smith'}, \n {'firstname': 'Samantha', 'lastname': 'Smith'}, \n {'firstname': 'shawn', 'lastname': 'Spencer'},\n]\n\nnew_data = collections.defaultdict(list)\n\nfor d in data:\n new_data[d['lastname']].app...
[ 6, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004729331_django_python.txt
Q: How do I use a MD5 hash (or other binary data) as a key name? I've been trying to use a MD5 hash as a key name on AppEngine, but the code I wrote raises a UnicodeDecodeError from google.appengine.ext import db import hashlib key = db.Key.from_path('Post', hashlib.md5('thecakeisalie').digest()) I don't want to use...
How do I use a MD5 hash (or other binary data) as a key name?
I've been trying to use a MD5 hash as a key name on AppEngine, but the code I wrote raises a UnicodeDecodeError from google.appengine.ext import db import hashlib key = db.Key.from_path('Post', hashlib.md5('thecakeisalie').digest()) I don't want to use hexdigest() as that is not only a kludge, but an inferior one too ...
[ "The App Engine Python docs says:\n\nA key_name is stored as a Unicode\n string (with str values converted as\n ASCII text).\n\nThe key has to be an unicode-encodeable-string. You need to change the digest() call to hexdigest(), ie:\nk = hashlib.md5('thecakeisalie').hexdigest()\n\n", "decode the bytestring with...
[ 12, 5, 4, 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004508155_google_app_engine_google_cloud_datastore_python.txt
Q: Not recognized non existant file im getting a weird error using this code (part of a class): from sys import path as workingDIR from os import system, path image = '' # some jpeg image data keep = 0 DIR = workingDIR[0] + '\\image' if path.isfile(DIR + '.jpeg'): # adding numbers to end of file name...
Not recognized non existant file
im getting a weird error using this code (part of a class): from sys import path as workingDIR from os import system, path image = '' # some jpeg image data keep = 0 DIR = workingDIR[0] + '\\image' if path.isfile(DIR + '.jpeg'): # adding numbers to end of file name like how windows prevents multiple fi...
[ "You have an extra white space in the image filename - \"..\\image (1).jpeg\"\nso when you call system(DIR), \"..\\image\" becomes the command and \"(1).jpeg\" is the first argument. \n" ]
[ 3 ]
[]
[]
[ "cmd", "image", "python", "windows" ]
stackoverflow_0004729270_cmd_image_python_windows.txt
Q: How can I determine what my database's connection limits should be? At my organization, PostgreSQL databases are created with a 20-connection limit as a matter of policy. This tends to interact poorly when multiple applications are in play that use connection pools, since many of those open up their full suite of ...
How can I determine what my database's connection limits should be?
At my organization, PostgreSQL databases are created with a 20-connection limit as a matter of policy. This tends to interact poorly when multiple applications are in play that use connection pools, since many of those open up their full suite of connections and hold them idle. As soon as there are more than a couple o...
[ "I think it's reasonable to require one connection per concurrent activity, and it's reasonable to assume that concurrent HTTP requests are concurrently executed.\nNow, the number of concurrent HTTP requests you want to process should scale with a) the load on your server, and b) the number of CPUs you have availab...
[ 2 ]
[]
[]
[ "connection_pooling", "database", "pylons", "python", "sqlalchemy" ]
stackoverflow_0004729361_connection_pooling_database_pylons_python_sqlalchemy.txt
Q: Python shell automatically load changes I really love python because I love interactive development. There's one area where python appears to fall short, however, and that's in the area of automatically reloading changed files. Basically, what I want to have happen is to be able to modify a python file on-disk and...
Python shell automatically load changes
I really love python because I love interactive development. There's one area where python appears to fall short, however, and that's in the area of automatically reloading changed files. Basically, what I want to have happen is to be able to modify a python file on-disk and then have my running python instance automat...
[ "Something like tail -f in python + reload().\nI really think they should make the tags OS and Python version mandatory though.\n", "If you're trying to \"test out\" your code, perhaps you should be looking into doing automated unit tests instead of testing your code repeatedly and manually. It'll allow you to te...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004729321_python.txt
Q: Python Multidimensional Array as a single List Sure, you can have nested lists to represent multidimensional arrays, but that seems costly... [[0, 1], [2, 3]] Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element? [0, 1, 2, 3] This...
Python Multidimensional Array as a single List
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly... [[0, 1], [2, 3]] Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element? [0, 1, 2, 3] This needs to work with n-dimensions, not just two, and ...
[ "Are you avoiding the obvious answer (i.e. [[1, 2], [3, 4]]) because of concerns about its performance? If so and you're working with numberes, look at NumPy arrays. The best solution would be to not reinvent your own wheel.\nEdit:\nIf you do feel the need to do it your own way, you could follow a strided index s...
[ 3, 1, 0, 0 ]
[]
[]
[ "list", "multidimensional_array", "python" ]
stackoverflow_0004729420_list_multidimensional_array_python.txt
Q: Python/mySQL on an Embedded ARM9 Device? I have an application where a small embedded ARM9 device (running Linux) must gather information from sensors and then connect to a remote mySQL database and INSERT the data. I have Python 2.5 running on the ARM9 device fine. I have developed a prototype application in Pyth...
Python/mySQL on an Embedded ARM9 Device?
I have an application where a small embedded ARM9 device (running Linux) must gather information from sensors and then connect to a remote mySQL database and INSERT the data. I have Python 2.5 running on the ARM9 device fine. I have developed a prototype application in Python 2.5 running on x86 Windows and it connects ...
[ "It should compile on ARM just fine, but first you should check that your platform's Linux distribution doesn't simply have packages for MySQL (if it has packages, it probably has those). If there are no packages it should be no big deal to compile it yourself. How's your cross compiler? Or is the platform big enou...
[ 1 ]
[ "I suggest using SQLite. I have an application running Python+SQLite for telemetry purposes and it works like a charm. It's much easier than MySQL.\n" ]
[ -1 ]
[ "arm", "embedded", "python" ]
stackoverflow_0001246235_arm_embedded_python.txt
Q: Typing Casting in Python Question Im a AS3 developer, currently learning Python In AS3 Id quite often do this: for ( var foo in fooArray ) { trace(FooObject(foo).name); } Typing casting the objects in the array, so that I get code hinting in my IDE How would I do this in Python? A: There is no type casting i...
Typing Casting in Python Question
Im a AS3 developer, currently learning Python In AS3 Id quite often do this: for ( var foo in fooArray ) { trace(FooObject(foo).name); } Typing casting the objects in the array, so that I get code hinting in my IDE How would I do this in Python?
[ "There is no type casting in Python, as types are dynamic, so casting is completely pointless. Your IDE will give hints if it can figure out what type it is, which it often can't.\n", "Your best bet is to use logging. Python has a default logging module (with five strict levels: debug, info, error, etc), but I p...
[ 1, 0, 0, 0 ]
[]
[]
[ "casting", "pydev", "python" ]
stackoverflow_0004726106_casting_pydev_python.txt
Q: Sometimes scripts idle and require me to press RETURN in order to unlock them - Python this has been happening quite a few times, and have not been able to explain this behaviour in any way. Often I write quick Python scripts for some quick tasks, often these tasks are row iterations using Django's ORM. example: f...
Sometimes scripts idle and require me to press RETURN in order to unlock them - Python
this has been happening quite a few times, and have not been able to explain this behaviour in any way. Often I write quick Python scripts for some quick tasks, often these tasks are row iterations using Django's ORM. example: from core.models import MyModel ITEM_IDS = [...] for index, item_id in enumerate(ITEM_IDS):...
[ "Is there any chance it is the terminal window (or \"dos box\", or whatever) that is to blame?\nFor example, in many terminal windows, if there is a scroll bar, and you are scrolled anywhere but the bottom, it will stay there; thus, it will seem that nothing is happening. But when you press a key, the terminal win...
[ 0 ]
[]
[]
[ "django", "python", "sql", "sql_server", "windows" ]
stackoverflow_0004725829_django_python_sql_sql_server_windows.txt
Q: Can't get an object's class name in Python I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object: >>> import re >>> x = re.compile('test') >>> x.__class__.__name__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: __class__ ....
Can't get an object's class name in Python
I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object: >>> import re >>> x = re.compile('test') >>> x.__class__.__name__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: __class__ ... >>> type(x) <type '_sre.SRE_Pattern'> >>> isi...
[ "You could do this:\nimport re\n\npattern_type = type(re.compile(\"foo\"))\n\nif isinstance(your_object, pattern_type):\n print \"It's a pattern object!\"\n\nThe idiomatic way would be to try to use it as a pattern object, and then handle the resulting exception if it is not.\n", "In : x = re.compile('test')\nI...
[ 4, 0 ]
[]
[]
[ "class", "isinstance", "object", "python", "types" ]
stackoverflow_0004730121_class_isinstance_object_python_types.txt
Q: wxReactor Problem I am developing a program that uses Twisted and wxReactor. Everytime I try to exit the application, it hangs, and I have to force quit it. My wxPython OnClose() event does call reactor.stop(), which to my knowledge should fix this issue. In my quest for an answer, I've come across this ticket: ww...
wxReactor Problem
I am developing a program that uses Twisted and wxReactor. Everytime I try to exit the application, it hangs, and I have to force quit it. My wxPython OnClose() event does call reactor.stop(), which to my knowledge should fix this issue. In my quest for an answer, I've come across this ticket: www.twistedmatrix.com/tra...
[ "This will work for you:\ndef OnClose(self, evt):\n # ugly hack until wxreactor is patched:\n reactor._stopping = True\n reactor.callFromThread(_threadedselect.ThreadedSelectReactor.stop, reactor)\n\n", "I had the same problem in one of my projects.\nI just need to remove following code:\n\nsys.exit() fr...
[ 2, 0 ]
[]
[]
[ "python", "twisted", "wxpython" ]
stackoverflow_0004190120_python_twisted_wxpython.txt
Q: Django data logging front end - phidgets What would the best method be to use Django for creating an application similar to say OpenNMS or any comparable network management tool? The Django app needs to be constantly polling 1 or more devices, with each device having 1 or more analog and digital inputs. Basicall...
Django data logging front end - phidgets
What would the best method be to use Django for creating an application similar to say OpenNMS or any comparable network management tool? The Django app needs to be constantly polling 1 or more devices, with each device having 1 or more analog and digital inputs. Basically, how do you integrate the necessary polling ...
[ "How you handle data logging really depends on how you want to present the data. However, unless you are only interested in a real time display (i.e. no charting), whatever code which is responsible for the logging will have to run outside the HTTP request/response cycle, and therefore outside of Django.\nProbably ...
[ 2 ]
[]
[]
[ "django", "embedded_linux", "python" ]
stackoverflow_0004728779_django_embedded_linux_python.txt
Q: List of References in Google App Engine for Python In Google App Engine, there is such a thing as a ListProperty that allows you to hold a list (array) of items. You may also specify the type of the item being held, for instance string, integer, or whatever. Google App Engine also allows you to have a ReferencePr...
List of References in Google App Engine for Python
In Google App Engine, there is such a thing as a ListProperty that allows you to hold a list (array) of items. You may also specify the type of the item being held, for instance string, integer, or whatever. Google App Engine also allows you to have a ReferenceProperty. A ReferenceProperty "contains" a reference to an...
[ "Step one:\nUse db.ListProperty(db.Key) to create the relationship. You want the ListProp to be on the Entity that will have the fewer references in the Many to Many relationship. This will also give you a back reference. So:\nclass Spam\n prop1 = db.String\n eggs = db.List\n\nclass Eggs\n prop1 = db.string\n...
[ 13, 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004719700_google_app_engine_python.txt
Q: Django: Why 'Class' object is not iterable I built a dictionary list like this lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \ {'name': nameobj, Classobj1: "string", Classobj2: "string"}] and I'm using for dic in lst: for k,v in dic: # here is the line has probloem! What it happens? ...
Django: Why 'Class' object is not iterable
I built a dictionary list like this lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \ {'name': nameobj, Classobj1: "string", Classobj2: "string"}] and I'm using for dic in lst: for k,v in dic: # here is the line has probloem! What it happens? #process The error message is like "Classna...
[ "Iterating over a dictionary just iterates over the keys, not key-value pairs. So on the line\nfor k,v in dic:\n\nPython is taking just a key, such as Classobj1, and trying to unpack it to match it to the tuple k,v. Since Classobj1 can't be iterated over, it can't be unpacked to match two items, which is why you ge...
[ 5, 1, 0, 0 ]
[]
[]
[ "dictionary", "django", "list", "python" ]
stackoverflow_0004730434_dictionary_django_list_python.txt
Q: "None" included in program output... why? i've searched the forum and found similar questions, but no luck in solving my problem. My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and...
"None" included in program output... why?
i've searched the forum and found similar questions, but no luck in solving my problem. My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix... here's the code: d...
[ "Add return \"\" to the function definition, that is\ndef encryptLine(line, count):\n headline = line[count:]\n\n if length(headline) > 0:\n if count == length(line) - 1:\n new = headline\n return new\n elif count <= length(line):\n new = head(tail(headline)) + h...
[ 8, 2 ]
[]
[]
[ "function", "python", "return_value" ]
stackoverflow_0004730494_function_python_return_value.txt
Q: Python gamepad input? Is there any good alternative to pygame for gamepad input? Crossplatform would be nice too. A: There's gamepad support in myro. I've dealt with the robotic functionality of the library, but not directly with the gamepad stuff. My encounters and the documentation indicate that myro is suppor...
Python gamepad input?
Is there any good alternative to pygame for gamepad input? Crossplatform would be nice too.
[ "There's gamepad support in myro. I've dealt with the robotic functionality of the library, but not directly with the gamepad stuff. My encounters and the documentation indicate that myro is supported on windows, mac, and linux distributions.\n" ]
[ 2 ]
[]
[]
[ "joystick", "python" ]
stackoverflow_0004731522_joystick_python.txt
Q: Updating div page coordinates in the datastore I'm currently making a webapp in App Engine where users can create multiple "boxes" (divs) with text inside of them. These "boxes" can be dragged around the page. I implemented the drag and drop functionality using the JQuery UI Draggable plugin. I can easily displ...
Updating div page coordinates in the datastore
I'm currently making a webapp in App Engine where users can create multiple "boxes" (divs) with text inside of them. These "boxes" can be dragged around the page. I implemented the drag and drop functionality using the JQuery UI Draggable plugin. I can easily display the current coordinate of each box on mouseup usi...
[ "You need to use JQuery to capture the 'drop' event, and fire off an AJAX request to your app, POSTing the ID of the box and the new coordinates, so it can update them in the datastore.\n" ]
[ 2 ]
[]
[]
[ "datastore", "google_app_engine", "jquery_ui", "python" ]
stackoverflow_0004731573_datastore_google_app_engine_jquery_ui_python.txt
Q: Have different initial_data fixtures for different stages (testing v. production) I have an initial_data fixture that I want to load everytime except for production. I already have different settings file for production and non-production deployments. Any suggestions on how to accomplish this? Clarification: I do ...
Have different initial_data fixtures for different stages (testing v. production)
I have an initial_data fixture that I want to load everytime except for production. I already have different settings file for production and non-production deployments. Any suggestions on how to accomplish this? Clarification: I do not want test fixtures. Basically, I just need the fixture to be loaded based on a sett...
[ "You can actually setup different test fixtures for each test if you want:\nhttp://docs.djangoproject.com/en/dev/topics/testing/#topics-testing-fixtures\nIf you only want to load the fixtures in one time, you can also write a custom TestRunner that will allow you to do that setup at the beginning:\ndocs.djangoproje...
[ 1, 0 ]
[]
[]
[ "django", "django_fixtures", "django_models", "django_settings", "python" ]
stackoverflow_0004731352_django_django_fixtures_django_models_django_settings_python.txt
Q: python key in dict.keys() performance for large dictionaries I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better. I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it ap...
python key in dict.keys() performance for large dictionaries
I was wondering if you guys might be able to give me some advice in regards to making the performance of my code much better. I have a set of for loops which look to see if a key is in a dictionary of which its values are a list, if the key exists, it appends to the list and if it doesnt it adds a new list in for that ...
[ "Don't do this:\nvalue.key in dict.keys()\n\nThat--in Python 2, at least--creates a list containing every key. That gets more and more expensive as the dictionary gets larger, and performs an O(n) search on the list to find the key, which defeats the purpose of using a dict.\nInstead, just do:\nvalue.key in dict\n...
[ 47, 4, 4, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004730993_python.txt
Q: Django, full state name from USStateField When I try and access the variable initialized to a USStateField in Django, it gives me the two letter normalization. I realize this is the behavior that Django intends but there must be some way to access the full name since Django can populate the menu with the full sta...
Django, full state name from USStateField
When I try and access the variable initialized to a USStateField in Django, it gives me the two letter normalization. I realize this is the behavior that Django intends but there must be some way to access the full name since Django can populate the menu with the full state names
[ " >>>from django.contrib.localflavor.us.us_states import US_STATES\n >>>dict(US_STATES)['AL']\n 'Alabama'\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004731848_django_django_forms_python.txt
Q: Regular expressions to select text from string in Python I have formatted lines of the text, i.e. [[item1 *,* {_item2*} *;{item3*}* ;{item4*}*]] where * means any text between the words and brackets. Is it possible to collect text from * to variables? item1, after1, before2, item2, after2, item3, after3, item4, a...
Regular expressions to select text from string in Python
I have formatted lines of the text, i.e. [[item1 *,* {_item2*} *;{item3*}* ;{item4*}*]] where * means any text between the words and brackets. Is it possible to collect text from * to variables? item1, after1, before2, item2, after2, item3, after3, item4, after4, afterall = re. ???
[ "You should be able to do it with regular expressions.\nhttp://docs.python.org/library/re.html\nYou can put parenthesis around parts of the expression you want to pull out later.\nAre you trying to grab the * parts or the item parts? If you trying to grab the * parts it shouldn't be too hard.\nimport re\n\nreg = r'...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004731851_python_regex.txt
Q: chardet apparently wrong on Big5 I'm decoding a large (about a gigabyte) flat file database, which mixes character encodings willy nilly. The python module chardet is doing a good job, so far, of identifying the encodings, but if hit a stumbling block... In [428]: badish[-3] Out[428]: '\t\t\t"Kuzey r\xfczgari" (...
chardet apparently wrong on Big5
I'm decoding a large (about a gigabyte) flat file database, which mixes character encodings willy nilly. The python module chardet is doing a good job, so far, of identifying the encodings, but if hit a stumbling block... In [428]: badish[-3] Out[428]: '\t\t\t"Kuzey r\xfczgari" (2007) {(#1.2)} [Kaz\xc4\xb1m]\n' In ...
[ "A point that can't be stressed too strongly: You should not expect any reasonable encoding guess from a piece of text that is so short and has such a high percentage of plain old ASCII characters in it.\nAbout big5: chardet casts a very wide net when checking CJK encodings. There are lots of unused slots in big5, ...
[ 4 ]
[]
[]
[ "big5", "chardet", "python", "unicode" ]
stackoverflow_0004731684_big5_chardet_python_unicode.txt
Q: Python, using Full .NET? I was trying out python in my browser using silverlight which is cool. Can i use python with .NET in a console or winform app? I hear silverlight is a stripped down .NET so it will load (or have a smaller download) on client machines. Can i use python with the full power of .NET? (perhaps ...
Python, using Full .NET?
I was trying out python in my browser using silverlight which is cool. Can i use python with .NET in a console or winform app? I hear silverlight is a stripped down .NET so it will load (or have a smaller download) on client machines. Can i use python with the full power of .NET? (perhaps outside of silver light)
[ "Yep, check out IronPython: http://ironpython.codeplex.com/\nIt will work in any .NET app.\n", "You might try looking at IronPython.\nAdditionally, there's the Python for .NET project, but I haven't read much on it. \n", "IronPython, maybe? It's a CLR implementation of Python. Totally .NET and totally cool.\nFr...
[ 3, 3, 2 ]
[]
[]
[ ".net", "dynamic_language_runtime", "python" ]
stackoverflow_0004732323_.net_dynamic_language_runtime_python.txt
Q: Cython's calculations are incorrect I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version: from __future__ import division pi = 0 l = 1 x = True while True: if x: pi += 4/l else: pi -= 4/l x = not x l += 2 ...
Cython's calculations are incorrect
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version: from __future__ import division pi = 0 l = 1 x = True while True: if x: pi += 4/l else: pi -= 4/l x = not x l += 2 print str(pi) The Cython version: cdef ...
[ "You are using float in the Cython version -- that's single precision! Use double instead, which corresponds to Python's float (funnily enough). The C type float only has about 8 significant decimal digits, whereas double or Python's float have about 16 digits.\n", "If you want to increase speed, note that you ...
[ 18, 0 ]
[ "How do you know when it's finished? Have you considered that the value for pi would oscillate about the true value, and you would expect that if you stopped the code at some point, you could have a value that is too high (or too low)?\n" ]
[ -1 ]
[ "cython", "pi", "python" ]
stackoverflow_0004730898_cython_pi_python.txt
Q: Is there a way to keep docstrings separate from the functions they document? I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code. ...
Is there a way to keep docstrings separate from the functions they document?
I'm working on a module with many small functions but whose docstrings tend to be quite long. The docstrings make working on the module irritating as I have to constantly scroll over a long docstring to find a little bit of actual code. Is there a way to keep docstrings separate from the functions they document? I'd r...
[ "The docstring for a function is available as the special attribute __doc__.\n>>> def f(x):\n... \"return the square of x\"\n... return x * x\n>>> f.__doc__\n'return the square of x'\n>>> help(f)\n(help page with appropriate docstring)\n>>> f.__doc__ = \"Return the argument squared\"\n>>> help(f)\n(help pag...
[ 12 ]
[]
[]
[ "docstring", "python" ]
stackoverflow_0004732850_docstring_python.txt
Q: What is the purpose of python 2.7's download package "Windows x86 MSI program database"? Upgrading from python 2.5/2.6 to python 2.7 on WinXP, I've found new download package forms for python at http://www.python.org/download/releases/2.7.1/. So I'm wondering what is the purpose of python 2.7's download package "W...
What is the purpose of python 2.7's download package "Windows x86 MSI program database"?
Upgrading from python 2.5/2.6 to python 2.7 on WinXP, I've found new download package forms for python at http://www.python.org/download/releases/2.7.1/. So I'm wondering what is the purpose of python 2.7's download package "Windows x86 MSI program database"? Searching on web didn't bring me clarifications on this. Act...
[ "It is the Python windows executable with debugging extensions. Having it as part of standard release was costly in terms of size and It was made available because in Windows due to differences in Windows versions and Visual studio versions and updates, building one by the user may not represent the DLL that distri...
[ 11, 3 ]
[]
[]
[ "file_format", "python", "release" ]
stackoverflow_0004732940_file_format_python_release.txt
Q: XML serialization library interoperability between Java and Python I have been searching for an xml serialization library that can serialize and deserialize an (Java/Python) object into xml and back. I am using XStream right now for Java. If XStream had a python version to deserialize from xml generated by Xstream...
XML serialization library interoperability between Java and Python
I have been searching for an xml serialization library that can serialize and deserialize an (Java/Python) object into xml and back. I am using XStream right now for Java. If XStream had a python version to deserialize from xml generated by Xstream that would have done it for me. Thrift or such other libraries is not g...
[ "Since Java and Python objects are so different in themselves, it's almost impossible to do this, unless you on both sides restrict the types allowed and such things.\nAnd in that case, I'd recommend you use JSON, which is a nice interoperability format, even though it's not XML.\nOtherwise you could easily write a...
[ 1, 0, 0, 0 ]
[]
[]
[ "java", "python", "serialization", "xml" ]
stackoverflow_0004730082_java_python_serialization_xml.txt
Q: PEP8 - 80 Characters - Big Integers This is somehow related to question about big strings and PEP8. How can I make my script that has the following line PEP8 compliant ("Maximum Line Length" rule)? pub_key = { 'e': 3226833362680126101036263622033066816222202666130162062116461326212012222403311326222666622610430...
PEP8 - 80 Characters - Big Integers
This is somehow related to question about big strings and PEP8. How can I make my script that has the following line PEP8 compliant ("Maximum Line Length" rule)? pub_key = { 'e': 3226833362680126101036263622033066816222202666130162062116461326212012222403311326222666622610430466620224662364142L, 'n': 226421003861...
[ "\nBut most importantly: know when to be\n inconsistent -- sometimes the style\n guide just doesn't apply. When in\n doubt, use your best judgment.\n\nsource\nIn this case, I would just leave the big integers as is.\n", "'e': 3226833362680126101036263622033066816222202666130162062116461326212012L \\\n * 1...
[ 22, 5, 5, 2, 2, 1 ]
[]
[]
[ "coding_style", "pep8", "python" ]
stackoverflow_0002045968_coding_style_pep8_python.txt
Q: How to determine from which class a method was inherited from? Is it possible to tell, from which class an method was inherited from. take an example below class A: def foo(): pass class B(A): def boo(A): pass class C(B): def coo() pass class D(C): def doo() pass >>> dir (D) ['_...
How to determine from which class a method was inherited from?
Is it possible to tell, from which class an method was inherited from. take an example below class A: def foo(): pass class B(A): def boo(A): pass class C(B): def coo() pass class D(C): def doo() pass >>> dir (D) ['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo'] Is there any met...
[ "Use the inspect module:\nclass A:\n def foo(self):\n pass\nclass B(A):\n def boo(Aself):\n pass\nclass C(B):\n def coo(self):\n pass\nclass D(C):\n def doo(self):\n pass \n\nimport inspect \ninspect.classify_class_attrs(D)\n\n[('__doc__', 'data', <class __main__.D at 0x85fb8fc>, None),\n ...
[ 6 ]
[]
[]
[ "multiple_inheritance", "python" ]
stackoverflow_0004733220_multiple_inheritance_python.txt
Q: Django's BooleanField showing incorrect value in edit mode DJango: 1.24 DB: MySQL Column Type: Bit Code: models.BooleanField(db_column='InStock') The checkbox always shows checked no matter what the value is (1 or 0). The value gets saved correctly but when it renders the edit page, it always checked. Any pointer...
Django's BooleanField showing incorrect value in edit mode
DJango: 1.24 DB: MySQL Column Type: Bit Code: models.BooleanField(db_column='InStock') The checkbox always shows checked no matter what the value is (1 or 0). The value gets saved correctly but when it renders the edit page, it always checked. Any pointers?
[ "You haven't provided much details so I'm guessing that you mean that you have a form and it doesn't have required=False set for the BooleanField.\n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0004728983_django_mysql_python.txt
Q: Comparing 40 million lines in a file with 6 million list items in Python I have a file with 40 million entries in the form of: #No Username And I have a list with 6 million items, where each item is a username. I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far: import os...
Comparing 40 million lines in a file with 6 million list items in Python
I have a file with 40 million entries in the form of: #No Username And I have a list with 6 million items, where each item is a username. I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far: import os usernames=[] common=open('/path/to/filf','w') f=open('/path/to/6 million','r'...
[ "I see two obvious improvements: first, make usernames a set. Then, create a result list and write '\\n'.join(resultlist) to file once.\nimport os\n\nusernames = []\n\nfor l in os.listdir('/path/to/directory/with/usernames/'):\n usernames.append(l)\n\nusernames = set(usernames)\n\nf = open('/path/to/6 million','...
[ 2, 0, 0 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0004733537_performance_python.txt
Q: How to perform TDD when developing a Django API When doing TDD on a Django app API, I write tests demonstrating that when proper constraints are provided, expected results are achieved. How do I write tests for the infinite permutations of cases where inputs are 'wrong'. Two things come to mind: 1) I shouldn't bre...
How to perform TDD when developing a Django API
When doing TDD on a Django app API, I write tests demonstrating that when proper constraints are provided, expected results are achieved. How do I write tests for the infinite permutations of cases where inputs are 'wrong'. Two things come to mind: 1) I shouldn't break the dynamic aspect of python by type-checking ever...
[ "With TDD, a good way to stay sane is to write tests that cover the required number of valid inputs, have the tests fail because there's no code yet, write as little code as possible to make them pass, then refactor that code into something production-ready, while ensuring your tests still pass. Sounds like you've ...
[ 3 ]
[]
[]
[ "django", "python", "tdd" ]
stackoverflow_0004731978_django_python_tdd.txt
Q: Dealing with bugs that only appear right after boot I dealt with a bug today that only appeared when I ran my program right after booting my computer. The cold start exposed a race condition which triggered the bug. I managed to fix it, but it took a long time because I had to reboot my machine several times to ...
Dealing with bugs that only appear right after boot
I dealt with a bug today that only appeared when I ran my program right after booting my computer. The cold start exposed a race condition which triggered the bug. I managed to fix it, but it took a long time because I had to reboot my machine several times to figure out what was going on. Can anybody suggest better...
[ "Run it inside a virtual machine.\n", "Use virtual machine (f.e. VirtualBox) and save state (make snapshot) just before booting is finished. Test freely and restore just booted state according to your needs.\n" ]
[ 3, 2 ]
[]
[]
[ "boot", "debugging", "python", "race_condition", "windows" ]
stackoverflow_0004733886_boot_debugging_python_race_condition_windows.txt
Q: How do I do this in Javascript and Django? I'm used to putting my javascripts in the top of my page in the head section. In my javascript, I use a lot of template stuff from Django like: {{ user.id }} {{ post.body }} I decided to move my javascript into another file, and then import it using: script src= But sin...
How do I do this in Javascript and Django?
I'm used to putting my javascripts in the top of my page in the head section. In my javascript, I use a lot of template stuff from Django like: {{ user.id }} {{ post.body }} I decided to move my javascript into another file, and then import it using: script src= But since my javascript is in another file now it can't...
[ "You can generate your javascript as a template too! But that requires serving your dynamic javascript via Django.\nFor instance..\n#views\ndef some_js(request):\n return render_to_response('js/some_dynamic_js.js', {}, mimetype='text/javascript')\n\nThere is nothing that says that Django templates must be HTML. ...
[ 2, 1, 0 ]
[]
[]
[ "django", "javascript", "jquery", "python", "templates" ]
stackoverflow_0004733658_django_javascript_jquery_python_templates.txt
Q: Why am I getting this javascript error when I'm doing my Django? I have valid json according to jsonlint.com In my javascript, I do this: var params = JSON.parse('{{ all_params_in_json }}'); And I get this error: Uncaught SyntaxError: Unexpected token ILLEGAL (anonymous function) Why? My json is valid. I'm usin...
Why am I getting this javascript error when I'm doing my Django?
I have valid json according to jsonlint.com In my javascript, I do this: var params = JSON.parse('{{ all_params_in_json }}'); And I get this error: Uncaught SyntaxError: Unexpected token ILLEGAL (anonymous function) Why? My json is valid. I'm using the standard json2 library. My json is this: { "browser_location...
[ "You have to do:\nvar params = JSON.parse('{{ all_params_in_json|escapejs }}');\n\nOtherwise e.g ' char inside all_params_in_json variable terminates string and all hell breaks loose.\n", "Sounds like you use invalid characters for label's inside the JSON. Check this, it may be browser-dependent what's legal or n...
[ 2, 0 ]
[]
[]
[ "django", "javascript", "jquery", "json", "python" ]
stackoverflow_0004734046_django_javascript_jquery_json_python.txt
Q: Why does python __file__ variable returns errorneous path when used in DJango? I was trying to retrieve the file path using python __file__ variable under django though i am getting correct path. It's behavior is little weird. Here is my attached sample code please let me know why is the behavior so. from django.s...
Why does python __file__ variable returns errorneous path when used in DJango?
I was trying to retrieve the file path using python __file__ variable under django though i am getting correct path. It's behavior is little weird. Here is my attached sample code please let me know why is the behavior so. from django.shortcuts import render_to_response import datetime class WebServer(): def ...
[ "As far as I can see, C:\\Django_example\\MySample\\webserver.py and C:\\Django_example\\MySample\\..\\MySample\\webserver.py points to the same file, so it isn't errorneous. \nIf you want a more succinct representation of the path, try:\nimport os\nprint \"File Path: \", os.path.realpath(__file__)\n\nupdate (an at...
[ 6, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0004733679_django_django_views_python.txt
Q: Write to a FIFO from a Python program I a trying to control the volume of mplayer from a python program. The mplayer program gets started from a bash script: #!/bin/bash mkfifo /home/administrator/files/mplayer-control.pipe /usr/bin/mplayer -slave -input file=/home/administrator/files/mplayer-control.pipe /home/ad...
Write to a FIFO from a Python program
I a trying to control the volume of mplayer from a python program. The mplayer program gets started from a bash script: #!/bin/bash mkfifo /home/administrator/files/mplayer-control.pipe /usr/bin/mplayer -slave -input file=/home/administrator/files/mplayer-control.pipe /home/administrator/music/file.mp3 Then I have a G...
[ "You don't need to call os.system and invoke a shell to write that line to the FIFO from your Python script- you can just do:\nnew_volume = 50\nwith open(\"/home/administrator/files/mplayer-control.pipe\",\"w\") as fp:\n fp.write(\"set_property volume %d\\n\" % (new_volume,))\n\nIt's not clear to me what you exp...
[ 7 ]
[]
[]
[ "bash", "fifo", "pipe", "python" ]
stackoverflow_0004734054_bash_fifo_pipe_python.txt
Q: Is there an open source tool based on perl or python to generate the summary of mindmap of documents I am really looking for a toolkit or readymade tool which will parse a given document and then generate a brief summary of better still a mindmap of the document. I know Python has ntlk and perl has quite a few mo...
Is there an open source tool based on perl or python to generate the summary of mindmap of documents
I am really looking for a toolkit or readymade tool which will parse a given document and then generate a brief summary of better still a mindmap of the document. I know Python has ntlk and perl has quite a few modules which will help in natural language parsing etc. It is even feasible to write a tool to do so, with...
[ "Someone (here on SO) has already written it for you (discussion). Another option would be TexLexAn (Text Analyzer Classifier Summarizer).\n", "Google people may already be working on such a thing. ;-)\nIf I get you right, you want a tool that will read a book for you and then briefly summarize for you what it wa...
[ 1, 0 ]
[]
[]
[ "nlp", "perl", "python" ]
stackoverflow_0004733866_nlp_perl_python.txt
Q: Beginning python for the web I'm looking for a nice tutorial or framework for developing Python written web applications. I've done lots in PHP, but very little in Python or Ruby and figured I'd start with the first one alphabetically. A: Try Django. It's one of the more popular Python web frameworks out there ...
Beginning python for the web
I'm looking for a nice tutorial or framework for developing Python written web applications. I've done lots in PHP, but very little in Python or Ruby and figured I'd start with the first one alphabetically.
[ "Try Django. It's one of the more popular Python web frameworks out there and arguably the easiest to use for simple projects.\n", "Depending on what level you want to work at, there are various ways to get started. At the most basic level, there is the WSGI specification, which is kind of like Python's version o...
[ 5, 2, 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0002770426_php_python.txt
Q: test for the file related function in python I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows. def copy_file (self): if not os.path.isdir(dest_path): os.makedirs(dest_path) try: s...
test for the file related function in python
I am rather new to software testing. I wonder how to write a unit test for file related functions in python. e.g., if I have a file copy function as follows. def copy_file (self): if not os.path.isdir(dest_path): os.makedirs(dest_path) try: shutil.copy2(src_path, dest_path) except IOErro...
[ "You can rely on shutil.copy2 copying the contents correctly. You only need to test your code. In this case that it creates the directories if they don't exist, and that it swallows IOErrors.\nAnd don't forget to clean up. ;)\n", "I think, you can get some clue from test_shutil itself and see how it is testing th...
[ 1, 1, 0 ]
[]
[]
[ "file", "python", "testing" ]
stackoverflow_0004734043_file_python_testing.txt
Q: sqrt: ValueError: math domain error I'm facing a problem with "distance ValueError: math domain error" when using sqrt function in python. Here is my code: from math import sqrt def distance(x1,y1,x2,y2): x3 = x2-x1 xFinal = x3^2 y3 = y2-y1 yFinal = y3^2 final = xFinal + yFinal d = sqrt(fi...
sqrt: ValueError: math domain error
I'm facing a problem with "distance ValueError: math domain error" when using sqrt function in python. Here is my code: from math import sqrt def distance(x1,y1,x2,y2): x3 = x2-x1 xFinal = x3^2 y3 = y2-y1 yFinal = y3^2 final = xFinal + yFinal d = sqrt(final) return d
[ "Your issue is that exponentiation in Python is done using a ** b and not a ^ b (^ is bitwise XOR) which causes final to be a negative value, which causes a domain error.\nYour fixed code:\ndef distance(x1, y1, x2, y2):\n return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** .5 # to the .5th power equals sqrt\n\n", "Th...
[ 11, 6 ]
[]
[]
[ "math", "python" ]
stackoverflow_0004735448_math_python.txt
Q: Bug in python tokenize? Why would this if 1 \ and 0: pass simplest of code choke on tokenize/untokenize cycle import tokenize import cStringIO def tok_untok(src): f = cStringIO.StringIO(src) return tokenize.untokenize(tokenize.generate_tokens(f.readline)) src='''if 1 \\ and 0: pass ''' print to...
Bug in python tokenize?
Why would this if 1 \ and 0: pass simplest of code choke on tokenize/untokenize cycle import tokenize import cStringIO def tok_untok(src): f = cStringIO.StringIO(src) return tokenize.untokenize(tokenize.generate_tokens(f.readline)) src='''if 1 \\ and 0: pass ''' print tok_untok(src) It throws: Asse...
[ "Yes, it's a known bug and there is interest in a cleaner patch than the one attached to that issue. Perfect time to contribute to a better Python ;)\n" ]
[ 3 ]
[]
[]
[ "python", "tokenize" ]
stackoverflow_0004735458_python_tokenize.txt
Q: Python object to C++ pointer problem this is my first post :). I could convert a python extended object into a C++ pointer, but I have a problem. First I will show you my code and then I will explain the problem. This is my class: #include <boost/python.hpp> using namespace boost::python; class Base { public: ...
Python object to C++ pointer problem
this is my first post :). I could convert a python extended object into a C++ pointer, but I have a problem. First I will show you my code and then I will explain the problem. This is my class: #include <boost/python.hpp> using namespace boost::python; class Base { public: virtual const char* HelloWorld() = 0...
[ "Finally, another programmer explained me the solution.\nI don't know why it worked originally, but the problem is that the object is getting destroyed before I try calling the member function. I need to break the extract call into two parts like so:\nobject derived = module.attr(\"NewDerived\")();\nBase* base = ex...
[ 2 ]
[]
[]
[ "boost", "boost_python", "c++", "embedded_language", "python" ]
stackoverflow_0004693462_boost_boost_python_c++_embedded_language_python.txt
Q: converting object to str and back to objects i had a list of obj [<DiffMatchPatch.patch_obj instance at 0x152a0b00>, <DiffMatchPatch.patch_obj instance at 0x152a0ab8>] i later converted them to a strs - then i got ["@@ -797,44 +797,8 @@\n : %0A\n- print 'WithDrwaing %25d' %25 shs%0A\n \n", "@@ -854,1...
converting object to str and back to objects
i had a list of obj [<DiffMatchPatch.patch_obj instance at 0x152a0b00>, <DiffMatchPatch.patch_obj instance at 0x152a0ab8>] i later converted them to a strs - then i got ["@@ -797,44 +797,8 @@\n : %0A\n- print 'WithDrwaing %25d' %25 shs%0A\n \n", "@@ -854,158 +854,4 @@\n e %0A%0A\n-'''%0Aif __name__ == '__...
[ "You must use Pickle for this purpose... \nfrom cPickle import dumps, loads\n\nlst = [1,2,3]\npckld = dumps(lst)\n\nprint (pckld)\n>> '(lp1\\nI1\\naI2\\naI3\\na.'\n\nloads(pckld)\n>> [1,2,3]\n\n", "Although it is not exactly what you ask for, maybe the \"serialization\" can solve your problems:\nhttp://en.wikiped...
[ 1, 0 ]
[]
[]
[ "object", "python", "string" ]
stackoverflow_0004735732_object_python_string.txt
Q: Behind the scenes activity on python prompt load-up What happens behind the scenes when we invoke the python prompt? I am more interested in understanding how do the methods/functions like print, import and the likes load up in the interpreter? EDIT: Some clarification on my question: When we type python on our un...
Behind the scenes activity on python prompt load-up
What happens behind the scenes when we invoke the python prompt? I am more interested in understanding how do the methods/functions like print, import and the likes load up in the interpreter? EDIT: Some clarification on my question: When we type python on our unix prompt/windows console and Hit enter, what are the lib...
[ "Like you , I am very interested by the underlying mechanisms of Python.\nI think you'll love this series:\nhttp://tech.blog.aknin.name/category/my-projects/pythons-innards/\n", "There are too many levels to that question. Here's a very rough sketch.\nThere's the whole C-level interpreter initialization, a bunch ...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004735502_python.txt
Q: Ordering a list of lists by lists len I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong Relevant part of the code: orderedpaths=[] if(len(paths)==1): orderedpaths=paths else: c=0 while(len(paths)!=0): if(c==0...
Ordering a list of lists by lists len
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong Relevant part of the code: orderedpaths=[] if(len(paths)==1): orderedpaths=paths else: c=0 while(len(paths)!=0): if(c==0): smallest=(len(paths[c]) c+=1 ...
[ "Your problem was the number of brackets in:\nsmallest=(len(paths[c])\n\nand in:\nif(len[paths[c])<smallest):\n\nand also in:\nif(len[paths[c])<smallest):\n\nTo sort paths according to their length, you can try this:\norderedpaths = sorted(paths, key=len)\n\nHere's the documentation for sorted.\n", "As stated in ...
[ 22, 2 ]
[ "You can also use this pretty piece of code :) :\n>>> a = [[1,2,3], [1,2,3,4], [1,2]]\n>>> b = sorted(a, lambda x,y: 1 if len(x)>len(y) else -1 if len(x)<len(y) else 0)\n>>> print b\n[[1, 2], [1, 2, 3], [1, 2, 3, 4]]\n\nand swap 1 with -1 if you want another sorting order.\nAs commenters notice this code works only...
[ -1 ]
[ "python", "sorting" ]
stackoverflow_0004735704_python_sorting.txt
Q: How to calculate running time from status and time using python I have a circulation pump that I check wither it's on or off on and this is not by any fixed interval what so ever. For a single day that could give me a dataset looking like this where 'value' represents the pump being on or off. data=( {'value': 0,...
How to calculate running time from status and time using python
I have a circulation pump that I check wither it's on or off on and this is not by any fixed interval what so ever. For a single day that could give me a dataset looking like this where 'value' represents the pump being on or off. data=( {'value': 0, 'time': datetime.datetime(2011, 1, 18, 7, 58, 25)}, {'value': 1, 't...
[ "It really depends on how you're going to treat this data points, are they representative of what? Generally, to know when switch occur you could use itertools.groupby like this:\n>>> from itertools import groupby\n>>> for i, grp in groupby(data, key=lambda x: x['value']):\n lst = [x['time'] for x in grp]\n ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004736079_python.txt
Q: How to properly sanitize a filename (protect against shell injection)? What is the common practice to sanitize a filename from an outside source (e.g.: xml file) before using it within a subprocess (shell=False)? Update: Before sending some parsed strings around I would like to make some basic security checks. The...
How to properly sanitize a filename (protect against shell injection)?
What is the common practice to sanitize a filename from an outside source (e.g.: xml file) before using it within a subprocess (shell=False)? Update: Before sending some parsed strings around I would like to make some basic security checks. The given example uses mpg123 (a command line audioplayer) in remote mode to pl...
[ "There's a couple of things I can think of.\nA lightweight verification can be done if the systems are tolerant. It may also be appropriate if there is little chance of data destruction, or compromise of sensitive data. You can test to see if the string your given is an actual file by using os.path.isfile.\nA mor...
[ 3, 1 ]
[]
[]
[ "python", "sanitization", "subprocess" ]
stackoverflow_0004734837_python_sanitization_subprocess.txt
Q: Sending other data along with a file using Kombu (carrot) How can I send a file along with other data using Kombu? I'm using rabbitmq as the broker. e.g. file.pdf along a dictionary {'author': 'user'} I'd like to do this in a single message if possible. But if you reckon using standard serializers of Kombu, how wo...
Sending other data along with a file using Kombu (carrot)
How can I send a file along with other data using Kombu? I'm using rabbitmq as the broker. e.g. file.pdf along a dictionary {'author': 'user'} I'd like to do this in a single message if possible. But if you reckon using standard serializers of Kombu, how would you bind the separate messages?
[ "There are several ways, but how about:\nproducer.send({\"author\": \"user\", \"file\": file})\n\nor:\nproducer.send(file, serializer=None, headers={\"author\": \"user\"})\n\nHeaders can only be of types supported by AMQP though.\n" ]
[ 0 ]
[]
[]
[ "carrot", "python", "rabbitmq" ]
stackoverflow_0004728838_carrot_python_rabbitmq.txt
Q: Algorithm in Python to store and search daily occurrence for thousands of numbered events? I'm investigating solutions of storing and querying a historical record of event occurrences for a large number of items. This is the simplified scenario: I'm getting a daily log of 200 000 streetlamps (labeled sl1 to sl2000...
Algorithm in Python to store and search daily occurrence for thousands of numbered events?
I'm investigating solutions of storing and querying a historical record of event occurrences for a large number of items. This is the simplified scenario: I'm getting a daily log of 200 000 streetlamps (labeled sl1 to sl200000) which shows if the lamp was operational on the day or not. It does not matter for how long t...
[ "Create a 2D-array in Numpy:\nimport numpy as np\n\nnbLamps = 200000\nnbDays = 365\n\narr = np.array([nbLamps, nbDays], dtype=np.bool)\n\nIt will be very memory-efficient and you can aggregate easily the days and lamps.\nIn order to manipulate the days even better, have a look at scikits.timeseries. They will allow...
[ 5, 0 ]
[]
[]
[ "data_structures", "date", "python", "zodb" ]
stackoverflow_0004734591_data_structures_date_python_zodb.txt
Q: Making decimal.Decimal the default numerical type in Python Is there some way I could make decimal.Decimal the default type for all numerical values in Python? I would like to be able to use Python in a manner similar to the bc and dc programs without having to call decimal.Decimal(...) for every number. EDIT: For...
Making decimal.Decimal the default numerical type in Python
Is there some way I could make decimal.Decimal the default type for all numerical values in Python? I would like to be able to use Python in a manner similar to the bc and dc programs without having to call decimal.Decimal(...) for every number. EDIT: For the uninitiated: bc. EDIT 2: Thank you tokenize module..
[ "At the bottom of the tokenize module's documentation, there is a function that does exactly what I need: \n\nPython 3: \"Example of a script rewriter that transforms float literals into Decimal objects\"\nPython 2: \"Example of a script re-writer that transforms float literals into Decimal objects\"\n\n", "You c...
[ 8, 6 ]
[]
[]
[ "bc", "dc", "decimal", "interpreter", "python" ]
stackoverflow_0004727008_bc_dc_decimal_interpreter_python.txt
Q: Accessing Local Variables Inside a Python Generator How would you access a local variable defined inside a Python generator from outside the generator? I have a case where my generator manipulates a local state, and for unittests I want to inspect this state to ensure it contains the correct values. I can't store...
Accessing Local Variables Inside a Python Generator
How would you access a local variable defined inside a Python generator from outside the generator? I have a case where my generator manipulates a local state, and for unittests I want to inspect this state to ensure it contains the correct values. I can't store the state to an instance variable (e.g. self.state = bla...
[ "Sorry to answer my own question, but after digging into the generator interface, I found the exact path I need to access the generator's local variables:\nfrom random import random\n\nclass MyIter(object):\n def __iter__(self):\n context = {}\n for i in xrange(10):\n context[random()] =...
[ 3, 1, 0 ]
[]
[]
[ "generator", "iterator", "python", "scripting" ]
stackoverflow_0004736470_generator_iterator_python_scripting.txt