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: what technology is involved in mapping sound waves? see soundcloud.com for an example, but basically I am wondering what technology allows for sound waves to be mapped like this, and also what programming modules are available for creating visual output from audio input, if that makes sense (preferably a python mo...
what technology is involved in mapping sound waves?
see soundcloud.com for an example, but basically I am wondering what technology allows for sound waves to be mapped like this, and also what programming modules are available for creating visual output from audio input, if that makes sense (preferably a python module :)
[ "PyAudio (http://people.csail.mit.edu/hubert/pyaudio/) should allow you to analyse audio input and then you can use something like PyGame or PIL to create visual output.\nI found an example of something like you might want here:\nhttp://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/\nYou are also likely to nee...
[ 2 ]
[]
[]
[ "audio", "programming_languages", "python" ]
stackoverflow_0006405256_audio_programming_languages_python.txt
Q: How to pass two python dictionaries to C++ function received by map I want to call a C++ function in Python that takes two Python dictionaries whose key values are lists, as parameters, like: a = {'str1': [1, 2, 3], 'str2': [4, 5, 6]} b = {'str3': [7, 8, 9], 'str4': [10, 11, 12]} cppFunction(a, b) And in C++, the...
How to pass two python dictionaries to C++ function received by map
I want to call a C++ function in Python that takes two Python dictionaries whose key values are lists, as parameters, like: a = {'str1': [1, 2, 3], 'str2': [4, 5, 6]} b = {'str3': [7, 8, 9], 'str4': [10, 11, 12]} cppFunction(a, b) And in C++, the function called take the two dictionaries and store them in two variable...
[ "As I understand there are two parts to your question: 1. How to call a C++ function from python?, 2. What data structures should be used in C++ for holding the inputs for the computation?\nAn answer to 1. is a long story. See, for example, this question and this question. For 2., for the given example, I would eit...
[ 3, 1 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0006404676_c++_python.txt
Q: string insertion in big file I have big file (few GBs) with text. For example, it have next text: Hello, World! I need to insert word " funny" at 5 position, and offset the rest of text: Hello, funny World! How I can don't read all file for offsetting rest? Or how I can optimise this operation? Thanks. A: You ...
string insertion in big file
I have big file (few GBs) with text. For example, it have next text: Hello, World! I need to insert word " funny" at 5 position, and offset the rest of text: Hello, funny World! How I can don't read all file for offsetting rest? Or how I can optimise this operation? Thanks.
[ "You can't. Plain text files cannot be shrunk or expanded in the beginning or middle of the file, but only at the end.\n", "Well you cant, please see this for more info\nHow do I modify a text file in Python?\n", "If your file is a few gigabytes, then probably my solution will apply only to 64-bit operating sys...
[ 8, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0006404962_file_python.txt
Q: Why is foo(*arg, x) not allowed in Python? Look at the following example point = (1, 2) size = (2, 3) color = 'red' class Rect(object): def __init__(self, x, y, width, height, color): pass It would be very tempting to call: Rect(*point, *size, color) Possible workarounds would be: Rect(point[0], poi...
Why is foo(*arg, x) not allowed in Python?
Look at the following example point = (1, 2) size = (2, 3) color = 'red' class Rect(object): def __init__(self, x, y, width, height, color): pass It would be very tempting to call: Rect(*point, *size, color) Possible workarounds would be: Rect(point[0], point[1], size[0], size[1], color) Rect(*(point + ...
[ "I'm not going to speak to why multiple tuple unpacking isn't part of Python, but I will point out that you're not matching your class to your data in your example.\nYou have the following code:\npoint = (1, 2)\nsize = (2, 3)\ncolor = 'red'\n\nclass Rect(object):\n def __init__(self, x, y, width, height, color):...
[ 11, 9, 0, 0, 0 ]
[]
[]
[ "function", "python", "variadic_functions" ]
stackoverflow_0006387631_function_python_variadic_functions.txt
Q: Automatically resizing NumPy recarray I'd like to create a subclass of numpy.recarray that automatically resizes when data is added to a row outside of its current length. The code below does most of what I want. class autorecarray(numpy.recarray): def __init__(self,*args,**kwargs): self._increment = 1 ...
Automatically resizing NumPy recarray
I'd like to create a subclass of numpy.recarray that automatically resizes when data is added to a row outside of its current length. The code below does most of what I want. class autorecarray(numpy.recarray): def __init__(self,*args,**kwargs): self._increment = 1 numpy.recarray.__init__(self,args,kwar...
[ "First of all you're missing the asterisks in the numpy.recarray.__init__ call:\ndef __init__(self, *args, **kwargs):\n self._increment = 1\n numpy.recarray.__init__(self, *args, **kwargs)\n\nAnd second, you're missing return statements in the __getitem__:\ndef __getitem__(self,ind):\n try:\n return...
[ 3, 2 ]
[]
[]
[ "numpy", "python", "subclassing" ]
stackoverflow_0006405342_numpy_python_subclassing.txt
Q: Python - multiple simultaneous threadpools I'm writing a web scraper in python, using httplib2 and lxml (yes - I know I could be using scrapy. Let's move past that...) The scraper has about 15000 pages to parse into approximately 400,000 items. I've got the code to parse the items to run instantaneously (almost) b...
Python - multiple simultaneous threadpools
I'm writing a web scraper in python, using httplib2 and lxml (yes - I know I could be using scrapy. Let's move past that...) The scraper has about 15000 pages to parse into approximately 400,000 items. I've got the code to parse the items to run instantaneously (almost) but the portion that downloads the page from the ...
[ "First of all, your design seems to be correct at a high level. The use of a threadpool for collecting the pages is justified by the synchronous nature of the httlib2 module. (With an asynchronous library one thread would be enough; note that even with httplib2 and the pool at most one collector thread is running a...
[ 7 ]
[]
[]
[ "multithreading", "python", "threadpool" ]
stackoverflow_0006039150_multithreading_python_threadpool.txt
Q: I am unsure how to make my dictionary print the info i want it to. Python 3.1 Please be gentle, I'm very new to programming and only own one book which is giving me some terrible directions (Head First Programming). Here is the code I have in the Python IDLE: scores = {} scores[8.45] = 'Zach' scores[9.12] = 'Juan...
I am unsure how to make my dictionary print the info i want it to. Python 3.1
Please be gentle, I'm very new to programming and only own one book which is giving me some terrible directions (Head First Programming). Here is the code I have in the Python IDLE: scores = {} scores[8.45] = 'Zach' scores[9.12] = 'Juan' scores[8.31] = 'Aaron' scores[8.05] = 'Aideen' scores[8.65] = 'Johnny' scores[7.8...
[ "You can use the {...}.items() iterator as follows:\nfor score,name in scores.items():\n print('{name} had a score of {score}'.format(**locals()))\n\nHowever, your dictionary is in the wrong order. For example, what if Zach and Juan had the same score of 9.10? Then, writing scores[9.10]='Zach' scores[9.10]='Juan...
[ 4, 2 ]
[]
[]
[ "dictionary", "hash", "python" ]
stackoverflow_0006405992_dictionary_hash_python.txt
Q: In Python is it considered bad practice to import something solely to expose it in a more convenient manner? This probably won't make sense without an example. I'm using python-disqus in my Django app, and I'm wrapping it to better decouple it from the rest of my application. I have a file, disqus.py, which import...
In Python is it considered bad practice to import something solely to expose it in a more convenient manner?
This probably won't make sense without an example. I'm using python-disqus in my Django app, and I'm wrapping it to better decouple it from the rest of my application. I have a file, disqus.py, which imports disqusapi and defines a number of helper functions. Elsewhere in the application code I can simply add from mang...
[ "\nIn Python is it considered bad\n practice to import something solely to\n expose it in a more convenient manner?\n\nShort answer: No.\nLong answer, if you are writing a wrapper to make your own code simpler and easier for you to understand you can do whatever you like. If you want to wrap other code, or impor...
[ 3, 3, 0 ]
[]
[]
[ "disqus", "import", "python" ]
stackoverflow_0006406087_disqus_import_python.txt
Q: virtualenv gcc error IF I use --no-site-packages option while creating a virtualenv and try to install MySQL-python afterwards I get : error: command 'gcc' failed with exit status 1 Here are the steps I followed: easy_install-2.7 --install-dir ~/src/lib/ virtualenv==dev ~/src/lib/virtualenv --no-site-packages EN...
virtualenv gcc error
IF I use --no-site-packages option while creating a virtualenv and try to install MySQL-python afterwards I get : error: command 'gcc' failed with exit status 1 Here are the steps I followed: easy_install-2.7 --install-dir ~/src/lib/ virtualenv==dev ~/src/lib/virtualenv --no-site-packages ENV .../ENV/bin/pip-2.7 inst...
[ "you need the mysql-devel package. to install, you need to specify the actual package name -\nsudo apt-get install libmysql++-dev\n\n", "Have you tried using the sudo command. I am guessing you are having permission issues than issue with anything else here. Usually an install throws up this error as it is tryin...
[ 1, 0 ]
[]
[]
[ "mysql_python", "python", "virtualenv" ]
stackoverflow_0005744906_mysql_python_python_virtualenv.txt
Q: using python finditer, how can I replace each matched string? I am using Python (pl/python, actually) to find, successively, a series of regex matches in a very large text object. This is working fine! Each match is a different result, and each replace will be a different result, eventually based on a query inside...
using python finditer, how can I replace each matched string?
I am using Python (pl/python, actually) to find, successively, a series of regex matches in a very large text object. This is working fine! Each match is a different result, and each replace will be a different result, eventually based on a query inside the loop. For the moment, I'd be happy to replace every match in ...
[ "You want re.sub() instead.\nimport re\n\ndef repl(var):\n return var.group().encode('rot13')\n\nprint re.sub('[aeiou]', repl, 'yesterday')\n\n\nyrstrrdny\n\n" ]
[ 9 ]
[]
[]
[ "iterator", "plpython", "python" ]
stackoverflow_0006406211_iterator_plpython_python.txt
Q: setting up Python interpreter I'm following a video tutorial (not available online) for installing Python and setting it up to use with Eclipse (text editor). To configure Eclipse to use Python, he adds the Python interpreter. In his movie, the python interpreter is a file python.exe. However, when I'm browsing...
setting up Python interpreter
I'm following a video tutorial (not available online) for installing Python and setting it up to use with Eclipse (text editor). To configure Eclipse to use Python, he adds the Python interpreter. In his movie, the python interpreter is a file python.exe. However, when I'm browsing through my folder in Python, I don...
[ "The path for the Python .exe can be found in: /usr/local/bin/pythonw\nHope this helps!\n", "I was using a windows tutorial when I should have been using a tutorial for Mac, so that explains why I didn't have an .exe file. Launching the wizard didn't set up the interpreter. I had to navigate to another folder on ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005552579_python.txt
Q: Iterating class object It's not a real world program but I would like to know why it can't be done. I was thinking about numpy.r_ object and tried to do something similar but just making a class and not instantiating it. a simple code (has some flaws) for integers could be: class r_: @classmethod def __get...
Iterating class object
It's not a real world program but I would like to know why it can't be done. I was thinking about numpy.r_ object and tried to do something similar but just making a class and not instantiating it. a simple code (has some flaws) for integers could be: class r_: @classmethod def __getitem__(clc, sl): try...
[ "The protocol for resolving obj[index] is to look for a __getitem__ method in the type of obj, not to directly look up a method on obj (which would normally fall back to looking up a method on the type if obj didn't have an instance attribute with the name __getitem__).\nThis can be easily verified.\n>>> class Foo(...
[ 4, 2, 1, 1 ]
[]
[]
[ "python", "range" ]
stackoverflow_0006406519_python_range.txt
Q: What happens when I omit the brackets when trying to catch multiple exceptions? I just tried writing this: try: # do something except ValueError, IndexError: # do something else And then got very confused when my program still threw an IndexError because I thought I was catching it. If it doesn't catch th...
What happens when I omit the brackets when trying to catch multiple exceptions?
I just tried writing this: try: # do something except ValueError, IndexError: # do something else And then got very confused when my program still threw an IndexError because I thought I was catching it. If it doesn't catch the IndexError, what exactly does this code do? It doesn't seem to be a syntax error.
[ "Because this mistake/problem is so common, the syntax changes for Python3. You code would be equivalent to\ntry:\n # do something\nexcept (ValueError, ) as IndexError:\n # do something else\n\nYou would have seen that this is obviously wrong.\nThe new syntax works back as far as Python2.6\nThis works ok\ntry...
[ 7, 4 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0006407079_exception_python.txt
Q: Prevent a file descriptor's closure on POSIX systems There is a library (libvte, a terminal emulation library) that uses a pair of file descriptors for a pty master/slave pair. I need to be able to "steal" the master fd from the library for my own use (in order to implement support for ZMODEM for the very rare oc...
Prevent a file descriptor's closure on POSIX systems
There is a library (libvte, a terminal emulation library) that uses a pair of file descriptors for a pty master/slave pair. I need to be able to "steal" the master fd from the library for my own use (in order to implement support for ZMODEM for the very rare occasion when the only link I have to the 'net is via a term...
[ "One possible solution would be to write a helper process which opens its own pty master/slave pair, and interposes between libvte and the actual target program that runs on the slave pty:\n+---------------+\n| libvte |\n| |\n| pty master=|-----\\\n+---------------+ |\n ...
[ 3, 1 ]
[]
[]
[ "c", "posix", "python", "system_calls", "unix" ]
stackoverflow_0006406081_c_posix_python_system_calls_unix.txt
Q: Controlling location of Pmw.MessageDialog (and other similar widgets) Python newbie here, newer still to Pmw: I have the following method defined for showing a Pmw MessageDialog box, and it works as expected and the result value is returned and posted in edit1, which is a Tkinter.Text widget; 'self' here is a Tkin...
Controlling location of Pmw.MessageDialog (and other similar widgets)
Python newbie here, newer still to Pmw: I have the following method defined for showing a Pmw MessageDialog box, and it works as expected and the result value is returned and posted in edit1, which is a Tkinter.Text widget; 'self' here is a Tkinter.Frame. (running Win7-32 and Python v2.7.2): def _showMessageBar(self): ...
[ "The answer is that the geometry options need to be in quotes, I wasn't seeing the proper results because an exception was being thrown by the improper geometry specifier. This code:\nresult = dialog.activate(geometry = \"first+50+20\")\n\nworks fine.\n" ]
[ 0 ]
[]
[]
[ "python", "pythonw" ]
stackoverflow_0006394556_python_pythonw.txt
Q: How to launch and compare some information from windows/console programs with python? It's been a long time since my last "play" with python, and recently I need to do something with it but I don't remember to much about it, even with libs are needed to import... Could you guys give me a hand? I will give you an e...
How to launch and compare some information from windows/console programs with python?
It's been a long time since my last "play" with python, and recently I need to do something with it but I don't remember to much about it, even with libs are needed to import... Could you guys give me a hand? I will give you an example, its not the exactly comparison that I need, but it will work just like it... For ex...
[ "Use subprocess.check_output and parse its output http://docs.python.org/library/subprocess.html#subprocess.check_output . Per the docs : \n\nRun command with arguments and return its output as a byte string.\n\nE.g. \nimport subprocess, re\nc = subprocess.check_output([\"ping\",\"www.google.com\"])\nt = re.findall...
[ 0 ]
[]
[]
[ "cmd", "python", "windows" ]
stackoverflow_0006407035_cmd_python_windows.txt
Q: Python pointers or queue share Before I used C, now I want to learn Python. I have a question, I have two class, how can I pass a variable address when I call the constructor, because I want to share a Queue between this two class( each class has a thread). Or does it have any other options to share a queue betwee...
Python pointers or queue share
Before I used C, now I want to learn Python. I have a question, I have two class, how can I pass a variable address when I call the constructor, because I want to share a Queue between this two class( each class has a thread). Or does it have any other options to share a queue between two class.
[ "Python already uses reference (as opposed to value) semantics:\na = [1, 2, 3]\nb = a\na.append(4)\nprint b # => [1, 2, 3, 4]\n\nYou don't have to do any extra work to get what you want.\n", "However if you're talking about threading, that's another story. If you are talking specifically about the multiprocessing...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006407620_python.txt
Q: How to extract data from JSON Object in Python? I am trying to extract data from JSON Object which is returned from the api call for api.trends() [Tweepy] but I am not able to extract the data. Can anyone give me an example of how to extract data from JSON object. I want to extract the data in tabular form. Thanks...
How to extract data from JSON Object in Python?
I am trying to extract data from JSON Object which is returned from the api call for api.trends() [Tweepy] but I am not able to extract the data. Can anyone give me an example of how to extract data from JSON object. I want to extract the data in tabular form. Thanks in advance.
[ "Once you run it though json.loads() it becomes normal Python objects. Simply index it as you would any dict or list.\n>>> json.loads('{\"foo\": 42, \"bar\": \"baz\"}')['bar']\n'baz'\n\n" ]
[ 11 ]
[]
[]
[ "json", "python", "simplejson", "tweepy" ]
stackoverflow_0006407780_json_python_simplejson_tweepy.txt
Q: Django.db import error File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module> if not settings.DATABASES: File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__ self._setup() File "/usr/l...
Django.db import error
File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module> if not settings.DATABASES: File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__ self._setup() File "/usr/local/lib/python2.6/dist-pack...
[ "\"Standalone Django scripts\"\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006407900_django_python.txt
Q: python: Why does SQLObject fail in conn.autocommit(1)? In my server code, there is a call to _SO_fetchAlternateID (nested in some value call), which ultimately calls makeConnection in pgconnection.py. This call fails on conn.autocommit(1), with the error TypeError: 'bool' object is not callable Here is SQLObje...
python: Why does SQLObject fail in conn.autocommit(1)?
In my server code, there is a call to _SO_fetchAlternateID (nested in some value call), which ultimately calls makeConnection in pgconnection.py. This call fails on conn.autocommit(1), with the error TypeError: 'bool' object is not callable Here is SQLObject's (0.8.7) code: def makeConnection(self): try: if sel...
[ "You have just spotted a bug. Take a look at this code:\ndef _setAutoCommit(self, conn, auto):\n # psycopg2 does not have an autocommit method.\n if hasattr(conn, 'autocommit'):\n conn.autocommit(auto)\n\nIt assumes that conn (type: psycopg2.connection) may not have an autocommit property, but when it ...
[ 5, 1 ]
[]
[]
[ "psycopg2", "python", "sqlobject" ]
stackoverflow_0006374121_psycopg2_python_sqlobject.txt
Q: Index a SciPy sparse matrix with an array of booleans NumPy arrays can be indexed with an array of booleans to select the rows corresponding to True entries: >>> X = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> rows = np.array([True,False,True]) >>> X[rows] array([[1, 2, 3], [7, 8, 9]]) >>> X[np.logical_not(ro...
Index a SciPy sparse matrix with an array of booleans
NumPy arrays can be indexed with an array of booleans to select the rows corresponding to True entries: >>> X = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> rows = np.array([True,False,True]) >>> X[rows] array([[1, 2, 3], [7, 8, 9]]) >>> X[np.logical_not(rows)] array([[4, 5, 6]]) But this seems not possible with S...
[ "You can use np.nonzero (or ndarray.nonzero) on your boolean array to get corresponding numerical indices, then use these to access the sparse matrix. Since \"fancy indexing\" on sparse matrices is quite limited compared to dense ndarrays, you need to unpack the rows tuple returned by nonzero and specify that you ...
[ 12 ]
[]
[]
[ "indexing", "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0006408385_indexing_numpy_python_scipy_sparse_matrix.txt
Q: thread lock necessary for processing queues + Python I have a queue in which i have to use it in several threads, so is it necessary to acquire the thread lock to avoid conflicts while processing this single queue, because i know it is necessary to acquire thread lock for variables or other resources, but little c...
thread lock necessary for processing queues + Python
I have a queue in which i have to use it in several threads, so is it necessary to acquire the thread lock to avoid conflicts while processing this single queue, because i know it is necessary to acquire thread lock for variables or other resources, but little confused for queues. thanks
[ "If you use the Queue in the module Queue, it will take care of the locking for you. See this page for more information: http://docs.python.org/library/queue.html (\"The Queue class in this module implements all the required locking semantics.\")\n", "The easiest solution is to use a mutex(lock) which will protec...
[ 11, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006408665_multithreading_python.txt
Q: How do I fit an image to a fixed size box using pythonMagick in python try: original = PythonMagick.Blob(data) image = PythonMagick.Image(original) except Exception as e: raise errors.UnknownFileFormat() medium = PythonMagick.Blob() small = PythonMagick.Blob() large = PythonMagick.Blob() largesize = "...
How do I fit an image to a fixed size box using pythonMagick in python
try: original = PythonMagick.Blob(data) image = PythonMagick.Image(original) except Exception as e: raise errors.UnknownFileFormat() medium = PythonMagick.Blob() small = PythonMagick.Blob() large = PythonMagick.Blob() largesize = "128X128" mediumsize = "64X64" smallsize = "48X48" image.scale(largesize) im...
[ "You can probably achieve what you are trying to do in CSS by background-size:cover or background-size:contain and background-position:...;. May be more complicated if trying to do other things.\n" ]
[ 1 ]
[]
[]
[ "imagemagick", "python" ]
stackoverflow_0006344704_imagemagick_python.txt
Q: Installing modules into a custom site-packages directory I have inherited a half-finished django project which uses a custom site-packages directory that is checked into subversion along with the code. Being a newbie to python, I'm wondering if I can just copy the contents of some eggs - that I want to add into th...
Installing modules into a custom site-packages directory
I have inherited a half-finished django project which uses a custom site-packages directory that is checked into subversion along with the code. Being a newbie to python, I'm wondering if I can just copy the contents of some eggs - that I want to add into the django project - directly into this site-packages directory ...
[ "You need to use virtualenv\n\nvirtualenv is a tool to create\n isolated Python environments.\n\n" ]
[ 1 ]
[]
[]
[ "django", "easy_install", "python" ]
stackoverflow_0006408863_django_easy_install_python.txt
Q: Why do all module run together? I just made a fresh copy of eclipse and installed pydev. In my first trial to use pydev with eclipse, I created 2 module under the src package(the default one) FirstModule.py: ''' Created on 18.06.2009 @author: Lars Vogel ''' def add(a,b): return a+b def addFixedValue(a): ...
Why do all module run together?
I just made a fresh copy of eclipse and installed pydev. In my first trial to use pydev with eclipse, I created 2 module under the src package(the default one) FirstModule.py: ''' Created on 18.06.2009 @author: Lars Vogel ''' def add(a,b): return a+b def addFixedValue(a): y = 5 return y +a print "123" r...
[ "When you import a module, everything in it is \"run\". This means that classes and function objects are created, global variables are set, and print statements are executed. *)\nIt is common practice to enclose statements only meant to be executed when the module is run directly in an if-block such as this:\nif __...
[ 10 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0006409012_eclipse_pydev_python.txt
Q: Importing global namespace in python let's say i have the following files: a.py glo_var = 0 def func(): global glo_var glo_var = 5 print "A %d" % (glo_var) b.py from a import * func() print "B %d" % (glo_var) If I ran b.py the output is: A 5 B 0 My question is, how to import the global namespace so ...
Importing global namespace in python
let's say i have the following files: a.py glo_var = 0 def func(): global glo_var glo_var = 5 print "A %d" % (glo_var) b.py from a import * func() print "B %d" % (glo_var) If I ran b.py the output is: A 5 B 0 My question is, how to import the global namespace so the output will be A 5 B 5 I need to cal...
[ "Using from ... import ... copies the references from the other module. Rebinding the value in the original causes it to have a new reference, breaking the link between a.glo_var and b.glo_var permanently. Either use a mutable object and mutate it, or reimport a.glo_var whenever you need the updated value.\n" ]
[ 4 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0006409458_namespaces_python.txt
Q: Verification of a Point in a Volume/ 3D space I've been working on development of a mesh library.I want to add a feature such that it will detect if a point is located inside of a 3D mesh or not. I've tried something like ray casting algo. But the problem is., In my algo., to test the possibility,I project the poi...
Verification of a Point in a Volume/ 3D space
I've been working on development of a mesh library.I want to add a feature such that it will detect if a point is located inside of a 3D mesh or not. I've tried something like ray casting algo. But the problem is., In my algo., to test the possibility,I project the point onto plane along Z axis.If projected point is wi...
[ "The usual approach for this kind of situations is to apply a small tranformation to the whole system (either a rotation or a shear transform). In some cases (at least in 2d) you don't even need to know the exact amount of your transformation but you can do this symbolically and adjust the algorithm accordingly.\nI...
[ 0 ]
[]
[]
[ "3d", "c", "graphics", "mesh", "python" ]
stackoverflow_0006409134_3d_c_graphics_mesh_python.txt
Q: Opensource Online IDE There're several online IDEs for PHP and some even for Python, but is there any open-source online IDE like IDEone that supports atleast the major languages (PHP, Python, Ruby etc..)? A: I created ShiftEdit Web Based IDE It uses Bespin and has basic PHP support. Includes Syntax highlighting...
Opensource Online IDE
There're several online IDEs for PHP and some even for Python, but is there any open-source online IDE like IDEone that supports atleast the major languages (PHP, Python, Ruby etc..)?
[ "I created ShiftEdit Web Based IDE\nIt uses Bespin and has basic PHP support.\nIncludes Syntax highlighting, Integrated (S)FTP, Tabs, Find/Replace, Revision history + it's free.\n", "Bespin is a sort interesting online js based editor in development primarly by Mozilla Labs. It's open source, saves files on the c...
[ 13, 6, 6, 4, 1, 0, 0 ]
[]
[]
[ "ide", "open_source", "php", "python", "ruby" ]
stackoverflow_0002040108_ide_open_source_php_python_ruby.txt
Q: Django forms want to auto-save user, client and datetime I need some help. In my models.py I have a table for Note. What I want to to do with this table is to create a form where a user could enter some notes in a text field for a particular client. models.py class Note(models.Model): client = models.ForeignK...
Django forms want to auto-save user, client and datetime
I need some help. In my models.py I have a table for Note. What I want to to do with this table is to create a form where a user could enter some notes in a text field for a particular client. models.py class Note(models.Model): client = models.ForeignKey(Client) datetime = models.DateTimeField(default=datetim...
[ " if form.is_valid():\n note = form.save(commit=False)\n note.user = request.user\n note.client = client\n note.save()\n\n", "class NoteForm(forms.ModelForm):\n class Meta:\n model = models.Note\n exclude = ('client','user','datetime')\n\n def __init__(self, clie...
[ 10, 7, 1 ]
[]
[]
[ "autosave", "django", "forms", "python" ]
stackoverflow_0006409541_autosave_django_forms_python.txt
Q: How to get a list from a set? How do I get the contents of a set() in list[] form in Python? I need to do this because I need to save the collection in Google App Engine and Entity property types can be lists, but not sets. I know I can just iterate over the whole thing, but it seems like there should be a short-...
How to get a list from a set?
How do I get the contents of a set() in list[] form in Python? I need to do this because I need to save the collection in Google App Engine and Entity property types can be lists, but not sets. I know I can just iterate over the whole thing, but it seems like there should be a short-cut, or "best practice" way to do t...
[ "See Sven's answer, but I would use the sorted() function instead: that way you get the elements in a nice predictable order (so you can compare the lists afterwards, for example).\n>>> s = set([1, 2, 3, 4, 5])\n>>> sorted(s)\n[1, 2, 3, 4, 5]\n\nOf course, the set elements have to be sortable for this to work. You ...
[ 78, 77, 2 ]
[]
[]
[ "list", "python", "set" ]
stackoverflow_0006405512_list_python_set.txt
Q: Python Json Parsing I'm having a bit of an issue with parsing json with python using the json library. Here is the format of the json I'm trying to parse: {'entry':[ { JSON Data 1 }, JSON Data 2 } ]} And here is my Python: for entry in response['entry'][0]: video['video_url'] =...
Python Json Parsing
I'm having a bit of an issue with parsing json with python using the json library. Here is the format of the json I'm trying to parse: {'entry':[ { JSON Data 1 }, JSON Data 2 } ]} And here is my Python: for entry in response['entry'][0]: video['video_url'] = entry['id']['$t'] vi...
[ "That list contains 2 separate dicts. Iterate over the list directly.\n", "If:\nresponse = {'entry':[\n {\n\n JSON Data 1\n }, \n {\n\n JSON Data 2\n }\n]}\n\nAnd:\nresponse['entry'][0] == { JSON Data 1 }\n\nThen:\nfor entry in response['entry']:\n\n video['video_url'] = entry['id'][...
[ 1, 1 ]
[]
[]
[ "json", "parsing", "python" ]
stackoverflow_0006409822_json_parsing_python.txt
Q: where is the sys module in python source code? I have found most python modules in python source directory, under Python/Lib or Python/Modules ,but where is the sys (import sys) module ? I didn't find it . A: The Answer I find it here: ./Python/sysmodule.c If you're on Linux or Mac OS X, and in doubt, just try f...
where is the sys module in python source code?
I have found most python modules in python source directory, under Python/Lib or Python/Modules ,but where is the sys (import sys) module ? I didn't find it .
[ "The Answer\nI find it here: ./Python/sysmodule.c\nIf you're on Linux or Mac OS X, and in doubt, just try find . -name 'sysmodule.c' in the Python directory.\nOther Stuff\nThe way I found it was by searching for the string \"platform\" throughout the Python directory (using TextMate), as I've used e.g. sys.platform...
[ 12, 6, 2 ]
[]
[]
[ "module", "python" ]
stackoverflow_0006409935_module_python.txt
Q: searching through a nested-list in python I have a nested list of tuples of 97510 values like this: a = [ (1,2,3), (3,4,5), (5,4,2)] every first value (index=0) is unique and I need to find other index=0 items that have the same index=1 items In the example , I need to find the second and third tuples where the...
searching through a nested-list in python
I have a nested list of tuples of 97510 values like this: a = [ (1,2,3), (3,4,5), (5,4,2)] every first value (index=0) is unique and I need to find other index=0 items that have the same index=1 items In the example , I need to find the second and third tuples where the the second item '4' is common . How do I do i...
[ "If you want to find all matches:\n>>> from collections import defaultdict\n>>> d = defaultdict(list)\n>>> for inner in a:\n... d[inner[1]].append(inner)\n... \n>>> d\ndefaultdict(<type 'list'>, {2: [(1, 2, 3)], 4: [(3, 4, 5), (5, 4, 2)]})\n>>> d[4]\n[(3, 4, 5), (5, 4, 2)]\n\nIf you want to pick out all matches...
[ 4, 3, 1, 1 ]
[]
[]
[ "list", "nested_lists", "python", "search" ]
stackoverflow_0006410062_list_nested_lists_python_search.txt
Q: sqlalchemy objects as dict keys? The use case is that I have a remote (read slow) database from which I grab some data through ORM mapped classes. I'd like to store non-db temporary data along side the ORM data and I don't want to pollute the mapped class namespace (which other people use) with a bunch of temporar...
sqlalchemy objects as dict keys?
The use case is that I have a remote (read slow) database from which I grab some data through ORM mapped classes. I'd like to store non-db temporary data along side the ORM data and I don't want to pollute the mapped class namespace (which other people use) with a bunch of temporary attributes just so I can store some ...
[ "Consider storing your local, \"non-db\" data in the appropriate mapped instances as a non-mapped attribute. e.g.\nlocal_data = {'batsman': 'Sangakkara', 'bowler': 'swann'}\nmapped_instance_from_query._local_data = local_data\n\nSQLAlchemy will simply ignore unmapped attributes.\n" ]
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006410496_python_sqlalchemy.txt
Q: How to dynamically change child widgets with Python and Qt? I would like to create a widget that has a child widget that I can dynamically change. Here is what I tried: import sys from PySide.QtCore import * from PySide.QtGui import * class Widget(QWidget): def __init__(self, parent=None): QWidget.__i...
How to dynamically change child widgets with Python and Qt?
I would like to create a widget that has a child widget that I can dynamically change. Here is what I tried: import sys from PySide.QtCore import * from PySide.QtGui import * class Widget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setLayout(QVBoxLayout()) ...
[ "removeWidget() only removes the item from the layout, it doesn't delete it. You can delete the child widget by calling setParent(None).\ndef update(self):\n self.layout().removeWidget(self.child)\n self.child.setParent(None)\n self.child = QLabel(\"bar\", self)\n self.layout().addWidget(self.child)\n\...
[ 22 ]
[]
[]
[ "pyqt", "pyqt4", "pyside", "python", "qt" ]
stackoverflow_0006410593_pyqt_pyqt4_pyside_python_qt.txt
Q: Error in number of bindings supplied and values supplied I am trying to convert an excel sheet into an sqlite3 db using win32com module in python. My excel sheet has 6 columns and so my a part of my python code is: for row in exceldata: c.execute('INSERT INTO exceltable1 VALUES(?,?,?,?,?,?)',row) conn.commit...
Error in number of bindings supplied and values supplied
I am trying to convert an excel sheet into an sqlite3 db using win32com module in python. My excel sheet has 6 columns and so my a part of my python code is: for row in exceldata: c.execute('INSERT INTO exceltable1 VALUES(?,?,?,?,?,?)',row) conn.commit() But python gives me the following error: c.execute('INSE...
[ "First of all, make sure what the value of row is, and how many items it has:\n print row, len(row)\n\nThen try and use the complete insert sql statement:\n insert into table (col1, col2, col3, ...) values (?, ?,? ...)\n\nand see what happens. This should solve your problem, or at least let you understand what is h...
[ 1, 0 ]
[]
[]
[ "python", "sqlite", "win32com" ]
stackoverflow_0006410763_python_sqlite_win32com.txt
Q: How to iterate through an enumerate object and print all the index-item pairs using next() function? I have the following program enum1 = enumerate("This is the test string".split()) I need to iterate through enum1 and print all the index-item pairs by using next() function. I try to get the index-item pairs by d...
How to iterate through an enumerate object and print all the index-item pairs using next() function?
I have the following program enum1 = enumerate("This is the test string".split()) I need to iterate through enum1 and print all the index-item pairs by using next() function. I try to get the index-item pairs by doing the following for i in range(len(enum1)): print enum1.next() It throws me an error showing len()...
[ "simply use:\nfor i,item in enum1:\n # i is the index\n # item is your item in enum1\n\nor\nfor i,item in enumerate(\"This is the test string\".split()):\n # i is the index\n # item is your item in enum1\n\nthis will use the next method underneath...\n", "Given the weird requirement that you need to use t...
[ 6, 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006411127_python.txt
Q: Python cmd interpreter adding if statements For one of my projects I have a python program built around the python cmd class. This allowed me to craft a mini language around sql statements that I was sending to a database. Besides making it far easier to connect with python, I could do things that sql can't do. Th...
Python cmd interpreter adding if statements
For one of my projects I have a python program built around the python cmd class. This allowed me to craft a mini language around sql statements that I was sending to a database. Besides making it far easier to connect with python, I could do things that sql can't do. This was very important for several projects. Howev...
[ "The limitations of making a \"mini language\" have become apparent.\nProper languages have a tree-like structure and more complex syntax than cmd can handle easily.\nSometimes it's actually easier to use Python directly than it is to invent your own DSL.\nCurrently, your DSL probably reads a script-like file of co...
[ 1, -1 ]
[]
[]
[ "control_flow", "python", "sql" ]
stackoverflow_0006143087_control_flow_python_sql.txt
Q: Raising exceptions without 'raise' in the traceback? Possible Duplicate: Don't show Python raise-line in the exception stack Built in exceptions like NameError etc. give me a traceback to the point in my code where the exception occurred. I'm working on a utility module and it bugs me that if code using my modul...
Raising exceptions without 'raise' in the traceback?
Possible Duplicate: Don't show Python raise-line in the exception stack Built in exceptions like NameError etc. give me a traceback to the point in my code where the exception occurred. I'm working on a utility module and it bugs me that if code using my module raises and exception the last thing in the traceback be...
[ "Pure Python doesn't provide a way to mutate existing traceback objects or create arbitrary traceback objects.\n>>> exc_info[2].tb_next = None\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: readonly attribute\n\n>>> types.TracebackType()\nTraceback (most recent call last):\...
[ 3 ]
[]
[]
[ "exception", "python", "raise" ]
stackoverflow_0006410764_exception_python_raise.txt
Q: First time getting Django/WSGI running, having some issues I've got Python installed ok, I can run scripts at the command line just fine. But I want to build web pages with it, and use the Django framework. I've read through lots of documentation on how to setup and get django running. Most of the work was done wi...
First time getting Django/WSGI running, having some issues
I've got Python installed ok, I can run scripts at the command line just fine. But I want to build web pages with it, and use the Django framework. I've read through lots of documentation on how to setup and get django running. Most of the work was done with apt-get install, which did install everything needed, but the...
[ "From the documentation:\n\nThe value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite.settings\n designating-the-settings \n modpython basic-configuration \n\nSo if your project (site) name is application:\nSetEnv DJANGO_SETTINGS_MODULE application.settings\n\n" ]
[ 0 ]
[]
[]
[ "apache2", "configuration", "django", "python", "wsgi" ]
stackoverflow_0006406231_apache2_configuration_django_python_wsgi.txt
Q: PyTables vs. SQLite3 insertion speed I bought Kibot's stock data and it is enormous. I have about 125,000,000 rows to load (1000 stocks * 125k rows/stock [1-minute bar data since 2010-01-01], each stock in a CSV file whose fields are Date,Time,Open,High,Low,Close,Volume). I'm totally new to python (I chose it be...
PyTables vs. SQLite3 insertion speed
I bought Kibot's stock data and it is enormous. I have about 125,000,000 rows to load (1000 stocks * 125k rows/stock [1-minute bar data since 2010-01-01], each stock in a CSV file whose fields are Date,Time,Open,High,Low,Close,Volume). I'm totally new to python (I chose it because it's free and well-supported by a co...
[ "\nBack in 2003, a scientific paper on the comparison of PyTables and Sqlite was written by F. Altec, the author of PyTables. This shows that PyTables is usually faster, but not always.\nOn your point that PyTables feels 'bare bones', I would say the H5py is the bare bones way of accessing HDF5 in python, PyTable...
[ 10, 4 ]
[]
[]
[ "pytables", "python", "sqlite" ]
stackoverflow_0006083713_pytables_python_sqlite.txt
Q: How to split large wikipedia dump .xml.bz2 files in Python? I am trying to build a offline wiktionary using the wikimedia dump files (.xml.bz2) using Python. I started with this article as the guide. It involves a number of languages, I wanted to combine all the steps as a single python project. I have found almos...
How to split large wikipedia dump .xml.bz2 files in Python?
I am trying to build a offline wiktionary using the wikimedia dump files (.xml.bz2) using Python. I started with this article as the guide. It involves a number of languages, I wanted to combine all the steps as a single python project. I have found almost all the libraries required for the process. The only hump now i...
[ "At last I have written a Python Script myself:\nimport os\nimport bz2\n\ndef split_xml(filename):\n ''' The function gets the filename of wiktionary.xml.bz2 file as input and creates\n smallers chunks of it in a the diretory chunks\n '''\n # Check and create chunk diretory\n if not os.path.exists(\...
[ 19, 1, 0 ]
[]
[]
[ "mediawiki", "python", "xml" ]
stackoverflow_0006184912_mediawiki_python_xml.txt
Q: Why do I get a parentheses when writing text to a file? for node in tree.getiterator('TARGET'): tgt_name = node.attrib.get('NAME') print map_name, ",", "TARGET" , ", " , tgt_name tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name writer.writelines (str(tgt_name_str)) writer.writelines('\n...
Why do I get a parentheses when writing text to a file?
for node in tree.getiterator('TARGET'): tgt_name = node.attrib.get('NAME') print map_name, ",", "TARGET" , ", " , tgt_name tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name writer.writelines (str(tgt_name_str)) writer.writelines('\n') Here is the output file content: ('m_myname', ',', 'TARGE...
[ "This line:\ntgt_name_str = map_name, \",\", \"TARGET\" , \", \" , tgt_name\n\ncreates a tuple, and the string representation of a tuple is enclosed in parenthesis. To do what you want, use this:\nwriter.write(\"{0}, TARGET, {1}\\n\".format(map_name, tgt_name))\n\n", "This is because when you execute next line:\n...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "file", "file_io", "python" ]
stackoverflow_0006411833_file_file_io_python.txt
Q: Extraction from python over multiple lines I'm working with python and am trying to extract numbers from a .txt file and then group them into multiple categories. The .txt file looks like this: IF 92007<=ZIPCODE<=92011 OR ZIPCODE=92014 OR ZIPCODE=92024 OR 92054<=ZIPCODE<=92058 OR ZIPCODE=92067 OR ZIPCODE=92075 O...
Extraction from python over multiple lines
I'm working with python and am trying to extract numbers from a .txt file and then group them into multiple categories. The .txt file looks like this: IF 92007<=ZIPCODE<=92011 OR ZIPCODE=92014 OR ZIPCODE=92024 OR 92054<=ZIPCODE<=92058 OR ZIPCODE=92067 OR ZIPCODE=92075 OR ZIPCODE=92083 OR ZIPCODE=92084 OR ZIPCODE=9209...
[ "Just do:\nmatches = re.findall(\"([0-9]{5})\",f.read())\n\nYou can extract them all at once - no need to loop over lines.\n", "Don't you just need to change 'expr' to 'L'?\nmatches = re.findall(\"([0-9]{5})\",L)\n\n", "Maybe I'm being naive, but shouldn't you search for numbers in L, instead of in expr?\nmatch...
[ 9, 4, 1 ]
[]
[]
[ "findall", "python" ]
stackoverflow_0006411911_findall_python.txt
Q: How to read and parse XML without schema in Python? Is there a way to read an XML document in Python without the schema? In my use case there is a file similar to the following. <people> <human> <weight>75</weight> <height>174</height> </human> <human> <weight>89</weight> <heigh...
How to read and parse XML without schema in Python?
Is there a way to read an XML document in Python without the schema? In my use case there is a file similar to the following. <people> <human> <weight>75</weight> <height>174</height> </human> <human> <weight>89</weight> <height>187</height> </human> </people> I need to extract ...
[ "You could use ElementTree (included in the python standard library) and do the following:\nimport xml.etree.ElementTree\ntree = xml.etree.ElementTree.parse(\"foo.xml\")\nmyArray = [int(x.text) for x in tree.getroot().findall(\"human/weight\")]\n\n" ]
[ 7 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0006411797_python_xml_xml_parsing.txt
Q: Enumerate items in a list so a user can select the numeric value I'm trying to find the most straightforward way to enumerate items in a list so that a user will not be burdened to type a long file name on a command line. The function below shows a user all .tgz and .tar files in a folder ... the user is then allo...
Enumerate items in a list so a user can select the numeric value
I'm trying to find the most straightforward way to enumerate items in a list so that a user will not be burdened to type a long file name on a command line. The function below shows a user all .tgz and .tar files in a folder ... the user is then allowed to enter the name of the file he wants to extract. This is tedious...
[ "Start with a list of files:\nfiles = [fname for fname in os.listdir(path) \n if fname.endswith(('.tgz','.tar'))]\n\nNow you can literally enumerate them:\nfor item in enumerate(files):\n print \"[%d] %s\" % item\n\ntry:\n idx = int(raw_input(\"Enter the file's number\"))\nexcept ValueError:\n ...
[ 8, 3, 3, 3 ]
[]
[]
[ "enumerate", "python" ]
stackoverflow_0006410982_enumerate_python.txt
Q: How to pass List as an argument to a function in threading.Timer How to pass a list as an argument to function in threading.Timer(...) ? Please see the following code. I would like to pass nb[] as an argument nb=['192.168.1.2', '192.168.1.3', '192.168.1.4'] ping_thread = threading.Timer(12.0, pingstarter, nb,) pin...
How to pass List as an argument to a function in threading.Timer
How to pass a list as an argument to function in threading.Timer(...) ? Please see the following code. I would like to pass nb[] as an argument nb=['192.168.1.2', '192.168.1.3', '192.168.1.4'] ping_thread = threading.Timer(12.0, pingstarter, nb,) ping_thread.start() pingstarter is a funciton and taking argument as a l...
[ "The problem is simple: you need to pass the list argument nb to threading.Timer() as the single element of a sequence (I usually use a tuple, note the trailing comma inside the parentheses):\nthreading.Timer(12.0, pingstarter, (nb,))\n\n...or, a list\nthreading.Timer(12.0, pingstarter, [nb])\n\nWhy? Well, threadin...
[ 10, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006406748_python.txt
Q: Django Templates replacement for Google App Engine (Python) I am looking for Django Templates replacement for Google App Engine (Python). I need easy to use templates with inheritance + fast execution. I see on Dinja2. What is your choice? A: I like Jinja2 a lot: http://jinja.pocoo.org/docs/ If you want to use s...
Django Templates replacement for Google App Engine (Python)
I am looking for Django Templates replacement for Google App Engine (Python). I need easy to use templates with inheritance + fast execution. I see on Dinja2. What is your choice?
[ "I like Jinja2 a lot: http://jinja.pocoo.org/docs/\nIf you want to use something which is very close to webapp I would recommend webapp2: http://code.google.com/p/webapp-improved/\nWith webapp2_extras you can use Jinja2 templating.\nMy personal choice is Tipfy: http://www.tipfy.org/\nIt is a very nice framework, co...
[ 1, 0 ]
[]
[]
[ "django", "django_templates", "google_app_engine", "python" ]
stackoverflow_0006407838_django_django_templates_google_app_engine_python.txt
Q: Randomly selecting a file from a tree of directories in a completely fair manner I'm looking for a way to randomly select a file from a tree of directories in a manner such that any individual file has exactly the same probability of being chosen as all other files. For example in the following tree of files, each...
Randomly selecting a file from a tree of directories in a completely fair manner
I'm looking for a way to randomly select a file from a tree of directories in a manner such that any individual file has exactly the same probability of being chosen as all other files. For example in the following tree of files, each file should have a 25% chance of being chosen: /some/parent/dir/ Foo.jpg sub_dir/ ...
[ "You can only select all files with the same probability if you know the total number of files in advance, so you need to create a full list first:\nfiles = [os.path.join(path, filename)\n for path, dirs, files in os.walk(dir)\n for filename in files\n if not filename.endswith(\".bak\")]\nre...
[ 14, 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006411811_python.txt
Q: python - assign letter of the alphabet to each value in a list I have a list of values in a for loop. e.g. myList = [1,5,7,3] which I am using to create a bar chart (using google charts) I want to label each value with a letter of the alphabet (A-Z) e.g. A = 1, B = 5, C = 7, D = 3 What is the best way to do this r...
python - assign letter of the alphabet to each value in a list
I have a list of values in a for loop. e.g. myList = [1,5,7,3] which I am using to create a bar chart (using google charts) I want to label each value with a letter of the alphabet (A-Z) e.g. A = 1, B = 5, C = 7, D = 3 What is the best way to do this running through a for loop e.g. for x in myList: x.label = LETTER...
[ "If you want to go on like ..., Y, Z, AA, AB ,... you can use itertools.product:\nimport string\nimport itertools\n\ndef product_gen(n):\n for r in itertools.count(1):\n for i in itertools.product(n, repeat=r):\n yield \"\".join(i)\n\nmylist=list(range(35))\n\nfor value, label in zip(mylist, pr...
[ 5, 2, 1, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006412473_python.txt
Q: Parsing XML Entity with python xml.sax Parsing XML with python using xml.sax, but my code fails to catch Entities. Why doesn't skippedEntity() or resolveEntity() report in the following: import os import cStringIO import xml.sax from xml.sax.handler import ContentHandler,EntityResolver,DTDHandler #Class to parse...
Parsing XML Entity with python xml.sax
Parsing XML with python using xml.sax, but my code fails to catch Entities. Why doesn't skippedEntity() or resolveEntity() report in the following: import os import cStringIO import xml.sax from xml.sax.handler import ContentHandler,EntityResolver,DTDHandler #Class to parse and run test XML files class TestHandler(Co...
[ "I think resolveEntity and skippedEntity are only called for external DTDs. I got this to work by modifying the XML.\nXML = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<!DOCTYPE test SYSTEM \"external.dtd\" >\n<test summary='step: &foo; &bar;'>Entity: &not;</test>\n\"\"\"\n\nThe external.dtd contains two sim...
[ 2, 1 ]
[]
[]
[ "parsing", "python", "sax", "xml" ]
stackoverflow_0006349513_parsing_python_sax_xml.txt
Q: Finding the closest point(s) by ranking them I Have a N x D dimensional features, which I need to rank according to their distance to a 1 x D dimensional vector. Any fast way to implement that in python without recursively apply argmin? Thanks! A: Something really simple is Squared Euclidean Distance, and it's i...
Finding the closest point(s) by ranking them
I Have a N x D dimensional features, which I need to rank according to their distance to a 1 x D dimensional vector. Any fast way to implement that in python without recursively apply argmin? Thanks!
[ "Something really simple is Squared Euclidean Distance, and it's implementation would be like:\nIn []: F= randn(5, 3)\nIn []: t= randn(1, 3)\nIn []: ((F- t)** 2).sum(1)\nOut[]: array([ 8.80512, 4.61693, 2.6002, 3.3293, 12.41800])\n\nWhere F are the features and t the target vector. Thus the ranking would be...
[ 3 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0006413193_numpy_python_scipy.txt
Q: Generating sharing message and shortened URL to Twitter I am using a Twitter ghetto sharing on a very simple Python based mobile site return "http://mobile.twitter.com/home?status=" + urllib.quote(link) I'd like to change the sharing so that Twitter messages gets the page title (I have it) and shortened URL. D...
Generating sharing message and shortened URL to Twitter
I am using a Twitter ghetto sharing on a very simple Python based mobile site return "http://mobile.twitter.com/home?status=" + urllib.quote(link) I'd like to change the sharing so that Twitter messages gets the page title (I have it) and shortened URL. Does there exist any general libraries/micro-frameworks for th...
[ "I'd recommend implementing a URL-shortener API (ie: bit.ly). Even further, there are API wrappers available for most of these popular services (ie: Python API wrapper for bit.ly - http://code.google.com/p/python-bitly/).\n" ]
[ 3 ]
[]
[]
[ "mobile", "python", "twitter", "url_shortener" ]
stackoverflow_0006412277_mobile_python_twitter_url_shortener.txt
Q: how to embed an image in a text widget I know it is possible to embed an image in a Tkinter text widget, but I've been unable to find some simple example code. Specifically, I need to embed a jpg, so according to the docs I think I need to use the photoimage class I tried to use this: img=PhotoImage ( file=imgfn...
how to embed an image in a text widget
I know it is possible to embed an image in a Tkinter text widget, but I've been unable to find some simple example code. Specifically, I need to embed a jpg, so according to the docs I think I need to use the photoimage class I tried to use this: img=PhotoImage ( file=imgfn ) text.image_create(image=img) where img...
[ "PhotoImage only handles GIF and PGM/PPM files. In order to use JPEG with Tkinter, you can use the Python Imaging Library (PIL) to create a PhotoImage.\nfrom PIL import Image, ImageTk\n\nimg = Image.open(\"yourimg.jpg\")\nphotoImg = ImageTk.PhotoImage(img)\n\nAlternatively you could just one of the other supported...
[ 5 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006413266_python_tkinter.txt
Q: This Iron Python Package Do Not Contain Ironpython.module.dll? I am using IronPython 1.0. This version does not contain Ironpython.module.dll and results in an error OS module importing error. How do I fix it? A: Your best bet is to use IronPython 2.7. If you need Visual Studio support, you can use Python Tools ...
This Iron Python Package Do Not Contain Ironpython.module.dll?
I am using IronPython 1.0. This version does not contain Ironpython.module.dll and results in an error OS module importing error. How do I fix it?
[ "Your best bet is to use IronPython 2.7. If you need Visual Studio support, you can use Python Tools for Visual Studio.\n" ]
[ 1 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0006410712_ironpython_python.txt
Q: Recursion counter solution in python The basic idea of the program is that it searches a large list for a given string, notes its index, and assigns other words based upon that index. The major issue is that, as there are some requirements built into the system that reject certain words, a very large recursion dep...
Recursion counter solution in python
The basic idea of the program is that it searches a large list for a given string, notes its index, and assigns other words based upon that index. The major issue is that, as there are some requirements built into the system that reject certain words, a very large recursion depth is likely to occur. There may be soluti...
[ "You seem to be mixing local and global variables.\nIn curgb, count2 variable isn't defined, and in curgd, count variable isn't defined. Either use global keywork to access them, or pass both variable as arguments to both functions (the later is what you should do)\n" ]
[ 1 ]
[]
[]
[ "counter", "python", "recursion" ]
stackoverflow_0006414119_counter_python_recursion.txt
Q: Python: How to read stdout non blocking from another process? During the runtime of a process I would like to read its stdout and write it to a file. Any attempt of mine however failed because no matter what I tried as soon as I tried reading from the stdout it blocked until the process finished. Here is a snippet...
Python: How to read stdout non blocking from another process?
During the runtime of a process I would like to read its stdout and write it to a file. Any attempt of mine however failed because no matter what I tried as soon as I tried reading from the stdout it blocked until the process finished. Here is a snippet of what I am trying to do. (The first part is simply a python scri...
[ "What is happening is buffering on the writer side. Since you are writing such small chunks from the little code snippet the underlying FILE object is buffering the output until the end. The following works as you expect.\n#!/usr/bin/python\n\nimport sys\nimport subprocess\n\np = subprocess.Popen(\"\"\"python -c '\...
[ 12, 5 ]
[ "You can use subprocess.communicate() to get the output from stdout. Something like:\nwhile(p.poll() == None):\n #read the stdout continuously\n print(p.communicate()[0])\n pass\n\nMore info available at: http://docs.python.org/library/subprocess.html\n" ]
[ -3 ]
[ "popen", "python", "stdout" ]
stackoverflow_0006413803_popen_python_stdout.txt
Q: Confused with arrays in python Is this the correct way to declare and iterate through an array in Python, where each element is multiplied by a constant value? timeArray = array([0]*1000) for x in timeArray: timeArray[x] = x * deltaTime print(timeArray) A: timeArray = [i*deltaTime for i in range(1000)] ...
Confused with arrays in python
Is this the correct way to declare and iterate through an array in Python, where each element is multiplied by a constant value? timeArray = array([0]*1000) for x in timeArray: timeArray[x] = x * deltaTime print(timeArray)
[ "timeArray = [i*deltaTime for i in range(1000)]\n\nwill construct a list with the contents that you want. Indexing into a list takes O(1) time, the same as for an array. Python lists are very fast, they're actually implemented as arrays.\nAre you sure you want to print the contents of the array/list while it's bein...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006414304_python.txt
Q: Having problems profiling memory in Python program using Valgrind I've looked at some questions about profiling memory usage in Python programs, but so far haven't been able to get anything to work. My program must run as root (it opens a TUN/TAP device). First, I tried heapy; unfortunately this didn't work for me...
Having problems profiling memory in Python program using Valgrind
I've looked at some questions about profiling memory usage in Python programs, but so far haven't been able to get anything to work. My program must run as root (it opens a TUN/TAP device). First, I tried heapy; unfortunately this didn't work for me. Every time my code tried to execute hpy().heap() the program froze. N...
[ "Instead of having the script launch the interpreter, directly calling it as a parameter to Valgrind solves the problem.\nvalgrind --tool=massif python my_script.py\n\n" ]
[ 10 ]
[]
[]
[ "profiling", "python", "valgrind" ]
stackoverflow_0006413895_profiling_python_valgrind.txt
Q: : cannot import name service_handlers I built a web app a month ago and then tested it. It had been working fine during last month without any code modifications but suddenly today I saw there an error occurring permanently. <type 'exceptions.ImportError'>: cannot import name service_handlers Traceback (most recen...
: cannot import name service_handlers
I built a web app a month ago and then tested it. It had been working fine during last month without any code modifications but suddenly today I saw there an error occurring permanently. <type 'exceptions.ImportError'>: cannot import name service_handlers Traceback (most recent call last): File "/base/data/home/apps/...
[ "This is a bit of a guess; but I think protorpc is going to be included in AppEngine 1.5.1, maybe they have added it in the background somewhere and it's conflicting.\nTry adding the protorpc path to the beginging of sys.path:\nsys.path = ['protorpc'] + sys.path\n\nAlso, try updating protorpc to the latest version ...
[ 3, 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006368542_google_app_engine_python.txt
Q: Python:winreg module :Windows 7:None is not valid HKEY error I ran into issues while reading registry value for windows 7 winth winreg module .Any pointers to resolve the same? Code : try: ParentKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall") i = ...
Python:winreg module :Windows 7:None is not valid HKEY error
I ran into issues while reading registry value for windows 7 winth winreg module .Any pointers to resolve the same? Code : try: ParentKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall") i = 0 while 1: name, value, type = _winreg.EnumValue(Paren...
[ "This line:\nParentKey = _winreg.DisableReflectionKey(ParentKey)\n\nwill return None. The function DisableReflectionKey is not documented as returning anything (success or failure is indicated by whether or not an exception is raised). Such a function that does not return anything returns None implicitly. Since you...
[ 1 ]
[]
[]
[ "python", "winreg" ]
stackoverflow_0006414567_python_winreg.txt
Q: Python exception ordering Just curious, why does the following code import sys class F(Exception): sys.stderr.write('Inside exception\n') sys.stderr.flush() pass sys.stderr.write('Before Exception\n') sys.stderr.flush() try: raise F except F: pass output: Inside exception Before Exception a...
Python exception ordering
Just curious, why does the following code import sys class F(Exception): sys.stderr.write('Inside exception\n') sys.stderr.flush() pass sys.stderr.write('Before Exception\n') sys.stderr.flush() try: raise F except F: pass output: Inside exception Before Exception and not: Before exception Inside...
[ "You're printing in the class, not its initialization block . Try running this \nimport sys\nclass F(Exception):\n sys.stderr.write('Inside exception\\n')\n sys.stderr.flush()\n pass\n\nalone. i.e., it's not running when you call raise F. Try this instead\nimport sys\nclass F(Exception):\n def __init_...
[ 8, 1, 0 ]
[]
[]
[ "python", "python_2.x" ]
stackoverflow_0006414390_python_python_2.x.txt
Q: Pythonic way to extract values from this text file I have an output file from a legacy piece of software which is shown below. I want to extract values from it, so that, for example, I can set a variable called direct_solar_irradiance to 648.957, and target ground pressure to 1013.00. So far, I have been extractin...
Pythonic way to extract values from this text file
I have an output file from a legacy piece of software which is shown below. I want to extract values from it, so that, for example, I can set a variable called direct_solar_irradiance to 648.957, and target ground pressure to 1013.00. So far, I have been extracting individual lines and processing them like below (repea...
[ "A more complete, perhaps more robust solution will require the use of either a parser using a custom grammer (pyparsing) or some sort of FSM-based processor (TextFSM).\nBoth options like they'll be non-trivial to use with this output. A (possibly) lighter-weight solution would be to identify each line based on kno...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "idioms", "python", "text" ]
stackoverflow_0006413439_idioms_python_text.txt
Q: Wrapping generator functions in Python I am writing some code that traverses a structure that may have cyclic references. Rather than explicitly doing checks at the beginning of the recursive functions I thought that I would create a decorator that didn't allow a function to be called more than once with the same ...
Wrapping generator functions in Python
I am writing some code that traverses a structure that may have cyclic references. Rather than explicitly doing checks at the beginning of the recursive functions I thought that I would create a decorator that didn't allow a function to be called more than once with the same arguments. Below is what I came up with. As...
[ "Okay, check this out:\n>>> from inspect import isgeneratorfunction\n>>> def foo(x):\n... for y in x:\n... yield y\n...\n>>> isgeneratorfunction(foo)\nTrue\n\nThis requires Python 2.6 or higher, though.\n", "Unfortunately there is not really a good way to know whether a function might return some type o...
[ 5, 4 ]
[]
[]
[ "decorator", "generator", "python" ]
stackoverflow_0006414682_decorator_generator_python.txt
Q: eval giving syntax error even when correct code given I have the following code, which uses the eval function: lines = self.fulltext.splitlines() CURRENT = 0 extractors = { "solar zenith angle" : (CURRENT, 1, "self.solar_z"), "ground pressure" : (CURRENT, 2, "self.ground_pressure") ...
eval giving syntax error even when correct code given
I have the following code, which uses the eval function: lines = self.fulltext.splitlines() CURRENT = 0 extractors = { "solar zenith angle" : (CURRENT, 1, "self.solar_z"), "ground pressure" : (CURRENT, 2, "self.ground_pressure") } print locals() for line in ...
[ "Use exec instead, it does evaluate statements, to.\nexec \"self.solar_z = values[1]\" in locals(), locals()\n", "eval() evaluates expressions. Assignment in Python is a statement. This will not work.\n" ]
[ 10, 7 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0006414991_eval_python.txt
Q: ManyToManyField IntegrityError in Django - why? I have News and Page models, and News has two fields referencing to Page: chapter = models.ForeignKey('pages.Page', verbose_name='Main chapter', limit_choices_to={'type__in':['news','speech']}, related_name='news' ) add_chapters = models.ManyToMa...
ManyToManyField IntegrityError in Django - why?
I have News and Page models, and News has two fields referencing to Page: chapter = models.ForeignKey('pages.Page', verbose_name='Main chapter', limit_choices_to={'type__in':['news','speech']}, related_name='news' ) add_chapters = models.ManyToManyField('pages.Page', blank=True, null=True, ...
[ "This works OK for me with Django 1.2 and sqlite and mysql. I think your db scheme is wrong. Try it on a fresh db and check if it is working.\n(Check your code - keep in mind that type is a python built_in. Did you use type instead of self.type somewhere?).\nThe code I used:\n# models.py\nclass Page(models.Model...
[ 0 ]
[]
[]
[ "django", "foreign_keys", "many_to_many", "mysql", "python" ]
stackoverflow_0006402882_django_foreign_keys_many_to_many_mysql_python.txt
Q: Python -- how to grab images off the internet How can I grab a picture off of a known url and save it to my computer using Python (v2.6)? Thanks A: You can use urllib.urlretrieve. Copy a network object denoted by a URL to a local file, if necessary. Example: >>> import urllib >>> urllib.urlretrieve('http://i....
Python -- how to grab images off the internet
How can I grab a picture off of a known url and save it to my computer using Python (v2.6)? Thanks
[ "You can use urllib.urlretrieve.\n\nCopy a network object denoted by a URL to a local file, if necessary. \n\nExample:\n>>> import urllib\n>>> urllib.urlretrieve('http://i.imgur.com/Ph4Xw.jpg', 'duck.jpg')\n('duck.jpg', <httplib.HTTPMessage instance at 0x10118e830>)\n# by now the file should be downloaded to 'duck....
[ 8, 2, 1, 0, 0, 0 ]
[]
[]
[ "download", "image", "python" ]
stackoverflow_0006415015_download_image_python.txt
Q: Manually Clone/Copy an instance in Python I know we have both copy and deepcopy inside the module copy, but I'd like to do it manually... I started by playing a little with __dict__ object just to see how can I create instances setting the same attributes that the object to be copied have, and here's the result of...
Manually Clone/Copy an instance in Python
I know we have both copy and deepcopy inside the module copy, but I'd like to do it manually... I started by playing a little with __dict__ object just to see how can I create instances setting the same attributes that the object to be copied have, and here's the result of my first test: class A(object): def F(self...
[ "To manually create a shallow copy of an instance of the user-defined class A, you can do\na = A()\nb = object.__new__(A)\nb.__dict__ = a.__dict__.copy() # or dict(a.__dict__)\n\nThe call to object.__new__() creates a new instance without calling __init__().\nYour code constructs a new type object rather than a n...
[ 9, 0 ]
[]
[]
[ "clone", "copy", "python" ]
stackoverflow_0006414881_clone_copy_python.txt
Q: Include python script/program in PHP I am new to Python and currently have to write a python program/script to be integrated inside PHP. Basically I have one stand-alone python program that will be executed through CRONTAB that grabs data from a remote device and exports the data to an XML file. I also have to wri...
Include python script/program in PHP
I am new to Python and currently have to write a python program/script to be integrated inside PHP. Basically I have one stand-alone python program that will be executed through CRONTAB that grabs data from a remote device and exports the data to an XML file. I also have to write another python program/script to be inc...
[ "The only way you can run a python script inside of a PHP script is to use the exec call. With that you will be able to capture the output from the python script and be able to use it in PHP.\n" ]
[ 4 ]
[]
[]
[ "php", "python" ]
stackoverflow_0006415165_php_python.txt
Q: Creating custom JSONEncoder I'm running Python 2.7 and I'm trying to create a custom FloatEncoder subclass of JSONEncoder. I've followed many examples such as this but none seem to work. Here is my FloatEncoder class: class FloatEncoder(JSONEncoder): def _iterencode(self, obj, markers=None): if isinst...
Creating custom JSONEncoder
I'm running Python 2.7 and I'm trying to create a custom FloatEncoder subclass of JSONEncoder. I've followed many examples such as this but none seem to work. Here is my FloatEncoder class: class FloatEncoder(JSONEncoder): def _iterencode(self, obj, markers=None): if isinstance(obj, float): ret...
[ "You seem to be trying to round float values down to 4 decimal points while generating JSON (based on test examples).\nJSONEncoder shipping with Python 2.7 does not have have _iterencode method, so that's why it's not getting called. Also a quick glance at json/encoder.py suggests that this class is written in such...
[ 2, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0006413891_json_python.txt
Q: How to create a 3D matrix with 3 columns and each column having 1000 rows This is the code that I have: positionMatrix = ([0]*1000, [0]*1000, [0]*1000) A: It is still not really clear what you want. If you want multidimensional array you can use lists: >>> matrix = [[None]*10 for x in range(3)]#replace 10 with ...
How to create a 3D matrix with 3 columns and each column having 1000 rows
This is the code that I have: positionMatrix = ([0]*1000, [0]*1000, [0]*1000)
[ "It is still not really clear what you want.\nIf you want multidimensional array you can use lists:\n>>> matrix = [[None]*10 for x in range(3)]#replace 10 with 1000 or what ever\n>>> matrix\n[[None, None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None, None], ...
[ 2, 0 ]
[ "positionMatrix = [[[0 for x in range(1000)] for x in range(1000)] for x in range(1000)]\nThis is the same as int positionMatrix[1000][1000][1000] in C/C++.\n" ]
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0006415109_python_python_3.x.txt
Q: How to work with this form in Django? Normally when I want to display individual form fields I use: {{ form.NAMEOFFIELD }} and if I want to display the entire form I just do: {{ form }} But now I'm working on a file where that doesn't work. The backend developers might not have made the form view specific so the...
How to work with this form in Django?
Normally when I want to display individual form fields I use: {{ form.NAMEOFFIELD }} and if I want to display the entire form I just do: {{ form }} But now I'm working on a file where that doesn't work. The backend developers might not have made the form view specific so the only way I can display it is by doing: {% ...
[ "Presumably you're talking about the comments app. As well as render_comment_form, that app provides a get_comment_form tag:\n{% get_comment_form for object.video as comment_form %}\n\nNow the form is available in the comment_form variable, and can be iterated in the normal way.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006415306_django_python.txt
Q: Transfer data from PC application to remotely hosted database Basically I want to be able to transfer data from PC application to remotely hosted database. I have developed a wxPython which application which is used for parsing and analysing test data. I want to update the application so that it can transfer the...
Transfer data from PC application to remotely hosted database
Basically I want to be able to transfer data from PC application to remotely hosted database. I have developed a wxPython which application which is used for parsing and analysing test data. I want to update the application so that it can transfer the analysed data to an online MySQL database. As it is for just for in...
[ "Do you have access server side? If so, you could enable secured remote mysql, or add a php page that allows access. For example, Python could use urllib to open \"mypage/search.php?name=name&otherdata=otherdata\", and read the result. This would also work in a web browser.\nIt seems uploading the file and then cal...
[ 2 ]
[]
[]
[ "data_transfer", "mysql", "php", "python", "wxpython" ]
stackoverflow_0006415367_data_transfer_mysql_php_python_wxpython.txt
Q: Python command line 'file input stream' I'm fairly new to python coming from C/C++, I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as: python main.py < text.txt (the file is in plain text) A: Read from sys.stdin: import sys sys.stdin.read() Being a file-like ob...
Python command line 'file input stream'
I'm fairly new to python coming from C/C++, I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as: python main.py < text.txt (the file is in plain text)
[ "Read from sys.stdin:\nimport sys\nsys.stdin.read()\n\nBeing a file-like object, you can use its reading functions or simply iterate over the input lines:\nfor line in sys.stdin:\n print line\n\n", "Using the fileinput module would be most appropriate here, and more flexible.\nhttp://docs.python.org/library/fi...
[ 9, 6, 1 ]
[]
[]
[ "file", "file_io", "filestream", "python" ]
stackoverflow_0006415382_file_file_io_filestream_python.txt
Q: Porting a JavaScript library to Python I am interested in porting the protovis javascript visualization library to python for use in scientific computing. I have a general question and a specific one. General: I have never ported a whole library before. What are some good strategies? Should I first just impleme...
Porting a JavaScript library to Python
I am interested in porting the protovis javascript visualization library to python for use in scientific computing. I have a general question and a specific one. General: I have never ported a whole library before. What are some good strategies? Should I first just implement the user-facing API and then fill it in i...
[ "You might be better off looking at Prefuse (http://www.prefuse.org), or Flare (http://flare.prefuse.org). The former is Java based, the latter Flash.\nProtovis is a little different in that it's plain old Javascript running the browser, using SVG as the canvas. You're not going to be able to readily leverage that ...
[ 1, 1, 1 ]
[]
[]
[ "inheritance", "javascript", "porting", "prototype", "python" ]
stackoverflow_0004481451_inheritance_javascript_porting_prototype_python.txt
Q: MySQLdb error when running python server on MacOSX10.6 Running my server (python manage.py runserver) yielded this error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I attempted the winning solution on this page with no avail: Django + MySQL on Mac OS 10.6.2...
MySQLdb error when running python server on MacOSX10.6
Running my server (python manage.py runserver) yielded this error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I attempted the winning solution on this page with no avail: Django + MySQL on Mac OS 10.6.2 Snow Leopard And then moved on to try Thierry Lam (5 votes)...
[ "It looks like you have everything installed right, but it can't find libmysqlclient. Have you tried the following?\n> sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib\n> sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql\n\n", "Sounds like your just missing the my...
[ 15, 1 ]
[]
[]
[ "django", "macos", "mysql", "python" ]
stackoverflow_0006414407_django_macos_mysql_python.txt
Q: Python equivalence of default in C# Is there a way in python to get a types default value? //C# default(typeof(int)) I am looking for a more pythonic way to get type defaults? #python if(isinstance(myObj, int): return 0 elif(isinstance(myObj, dict): return {} else: return None Obviously I dumbed ...
Python equivalence of default in C#
Is there a way in python to get a types default value? //C# default(typeof(int)) I am looking for a more pythonic way to get type defaults? #python if(isinstance(myObj, int): return 0 elif(isinstance(myObj, dict): return {} else: return None Obviously I dumbed it down. I am dealing with some abstract ...
[ "Just instantiate it:\nint() # 0\ndict() # {}\nlist() # []\n\nMore detail: there's no explicit concept of a 'default value' in Python. There's just an instance of the class instantiated with the default parameters. Some classes may expect arguments when you instantiate them, in which case there isn't really a defa...
[ 12, 4 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0006415663_python_python_2.7.txt
Q: Python Twitter Statistics I need to get the number of people who have followed a certain account by month, also the number of people who have unfollowed the same account by month, the total number of tweets by month, and the total number of times something the account tweeted has been retweeted by month. I am usin...
Python Twitter Statistics
I need to get the number of people who have followed a certain account by month, also the number of people who have unfollowed the same account by month, the total number of tweets by month, and the total number of times something the account tweeted has been retweeted by month. I am using python to do this, and have i...
[ "These types of statistical breakdowns are not generally available via the Twitter API. Depending on your sample date range, you may have luck using Twittercounter.com's API (you can sign up for an API key here).\nThe API is rate limited to 100 calls per hour, unless you get whitelisted. You can get results for th...
[ 1, 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0006362710_python_twitter.txt
Q: Creating a progress bar in a CLI application When using tools like bzr, doxygen and scp or wget, I see that all of them have a nice progress bar that looks like this: |=============>---------| 55% ETA 3:30 I tried writing something like that in C++ using the \b character as many times as I had written something o...
Creating a progress bar in a CLI application
When using tools like bzr, doxygen and scp or wget, I see that all of them have a nice progress bar that looks like this: |=============>---------| 55% ETA 3:30 I tried writing something like that in C++ using the \b character as many times as I had written something out before. The output was flickering pretty badly ...
[ "Use \"\\r\" to send the cursor to the beginning of the line. Reprint no more than 2-3 times per second to avoid flickering.\n", "this might be useful example:\nhttp://code.google.com/p/corey-projects/source/browse/trunk/python2/progress_bar.py\nimport sys\nimport time\n\n\nclass ProgressBar:\n def __init__(s...
[ 5, 4 ]
[]
[]
[ "command_line_interface", "progress_bar", "python" ]
stackoverflow_0006415402_command_line_interface_progress_bar_python.txt
Q: Debugging RadioButtons program in Python I wrote a simple program importing Tkinter just to play with Radio Buttons. I find that I'm getting errors in very, very weird places. from Tkinter import * class Application (Frame): def __init__(self, master): Frame.__init__(self, master) self.grid(...
Debugging RadioButtons program in Python
I wrote a simple program importing Tkinter just to play with Radio Buttons. I find that I'm getting errors in very, very weird places. from Tkinter import * class Application (Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def creat...
[ "There are a lot of things going on here. I'll just point out the few that I've found quickly looking at this.\nFor your Label you shouldn't have = before your parameters...\nLabel = (self, text = \"Select the last book you read.\").grid (row = 0, column = 0, sticky = W)\n\nto:\nLabel(self, text = \"Select the las...
[ 2 ]
[]
[]
[ "debugging", "python", "radio_button", "tkinter" ]
stackoverflow_0006415746_debugging_python_radio_button_tkinter.txt
Q: filter text file using script I have a tab-delimited text file that is very large. Some lines have the same value in the file, some lines just have unique value, For example: a foo a bar a foo2 b bar2 c bar2 c foo3 d bar3 ... I also have another ID list file, which is just part of the whole list. Fo...
filter text file using script
I have a tab-delimited text file that is very large. Some lines have the same value in the file, some lines just have unique value, For example: a foo a bar a foo2 b bar2 c bar2 c foo3 d bar3 ... I also have another ID list file, which is just part of the whole list. For example: a b d ... I want to get...
[ "Quickie untested Python:\nids = set()\nwith open('id-list.txt') as f:\n for line in f:\n ids.add(line.strip())\nwith open('data.txt') as f:\n for line in f:\n parts = line.strip().split('\\t', 1)\n if parts[0] in ids:\n print line,\n\n", "You can also use the following code(...
[ 1, 1, 1, 1, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0006413311_perl_python.txt
Q: Python Wrapper to a C Callback Trying to create a python callback which needs to be invoked while calling the C callback from a dll in Windows environment. Please review the code below to understand the issue. from ctypes import * #---------qsort Callback-------------# IntArray5 = c_int * 5 ia = IntArray5(5,1,7,...
Python Wrapper to a C Callback
Trying to create a python callback which needs to be invoked while calling the C callback from a dll in Windows environment. Please review the code below to understand the issue. from ctypes import * #---------qsort Callback-------------# IntArray5 = c_int * 5 ia = IntArray5(5,1,7,33,99) libc = cdll.msvcrt qsort = li...
[ "You can't. C/C++ functions can't access Python functions directly - that function prototype is probably expecting a pointer to C. Python will be passing it a pointer to its internal data structure for that particular function.\nThis is the time to build a C extension to python to wrap that DLL and expose it to Pyt...
[ 6 ]
[]
[]
[ "c", "ctypes", "python", "windows" ]
stackoverflow_0006412828_c_ctypes_python_windows.txt
Q: Change the value of the progress bar from a class other than my GUI class PyQt4 I have a GUI class created by Qt designer in which i have a progress bar, and another class in which all the number crunching is done during which i want my progress bar to update regularly. The way i thought i would do this it to do s...
Change the value of the progress bar from a class other than my GUI class PyQt4
I have a GUI class created by Qt designer in which i have a progress bar, and another class in which all the number crunching is done during which i want my progress bar to update regularly. The way i thought i would do this it to do something like this in the other class: gui.progressbar.setValue(some%) but i cant se...
[ "gui.Ui_mainLayout is not an instantiated class but a 'type' object (an object that can be instantiated - see here for a good overview). gui.Ui_mainLayout.progressBar is not going to exist as its created when setupUi is run.\nTry passing progressBar to RunProgram explicitly:\nfrom PyQt4 import QtCore, QtGui\nfrom R...
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qprogressbar" ]
stackoverflow_0006415737_pyqt_pyqt4_python_qprogressbar.txt
Q: Python pickle crash when trying to return default value in __getattr__ I have a dictionary like class that I use to store some values as attributes. I recently added some logic(__getattr__) to return None if an attribute doesn't exist. As soon as I did this pickle crashed, and I wanted some insight into why? Tes...
Python pickle crash when trying to return default value in __getattr__
I have a dictionary like class that I use to store some values as attributes. I recently added some logic(__getattr__) to return None if an attribute doesn't exist. As soon as I did this pickle crashed, and I wanted some insight into why? Test Code: import cPickle class DictionaryLike(object): def __init__(self, ...
[ "Implementing __getattr__ is a bit tricky, since it is called for every non-existing attribute. In your case, the pickle module tests your class for the __getnewargs__ special method and receives None, which is obviously not callable.\nYou might want to alter __getattr__ to call the base implementation for magic n...
[ 13, 5 ]
[]
[]
[ "pickle", "python", "python_2.7" ]
stackoverflow_0006415951_pickle_python_python_2.7.txt
Q: Python webhelpers.html.tags with WSGI SCRIPT_NAME prefix I have a pylons web-app that generates links to controller actions using routes.url_for, and links to static files (CSS, javascript, images etc) using the functions defined in webhelpers.html.tags. This works fine while my web-app is hosted at the root of th...
Python webhelpers.html.tags with WSGI SCRIPT_NAME prefix
I have a pylons web-app that generates links to controller actions using routes.url_for, and links to static files (CSS, javascript, images etc) using the functions defined in webhelpers.html.tags. This works fine while my web-app is hosted at the root of the server (i.e., the web-app is run from '/'). However, if I mo...
[ "If I'm reading this correctly, it sounds like the url_for is correctly returning the string with the URL you want. But as far as I can see, you pass in a url string to the various webhelpers.\nAre you doing something like this?\nlink_to('something', url(controller='path', action='to'))\n\n" ]
[ 1 ]
[]
[]
[ "html", "pylons", "python", "wsgi" ]
stackoverflow_0006408475_html_pylons_python_wsgi.txt
Q: Passing a relative path in a function Can someone tell me if the following function declaration is the correct way to pass a relative path to a function? The call is only taking one variable. When I include a second variable (absolute path), my function does not work. def extract(tar_url, extract_path='.'): The ...
Passing a relative path in a function
Can someone tell me if the following function declaration is the correct way to pass a relative path to a function? The call is only taking one variable. When I include a second variable (absolute path), my function does not work. def extract(tar_url, extract_path='.'): The call that does not work: extract(chosen, p...
[ "It looks like you missed an escape character in \"PLACE .tgz FILES in c:\\Extracted AT THIS TIME!!! PRESS ENTER WHEN FINISHED!\"\nI don't think raw_input sees the prompt string as a raw string, just the user input.\nBut this shouldn't affect the functionality of your program.\nAre you on Unix or windows? I was und...
[ 1 ]
[]
[]
[ "path", "python" ]
stackoverflow_0006415187_path_python.txt
Q: Need for while True: I don't understand why "while True:" is needed in below example import os import sys import subprocess import time from threading import Thread from Queue import Queue def worker(): while True: item = q.get() do_work(item) q.task_done() def ...
Need for while True:
I don't understand why "while True:" is needed in below example import os import sys import subprocess import time from threading import Thread from Queue import Queue def worker(): while True: item = q.get() do_work(item) q.task_done() def do_work(item): time....
[ "Because otherwise the worker thread would quit as soon as the first job was processed from the queue. The infinite loop ensures that the worker thread retrieves a new job from the queue when finished.\nUpdate: to summarize the comments to my (admittedly hasty) answer: the worker thread is daemonic (ensured by t.da...
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0006416127_python.txt
Q: Python equivalent of PHP's __DIR__ magic constant? In PHP, the __DIR__ magic constant evaluates to the path to the directory containing the file in which that constant appears. Is there an equivalent feature in Python? A: os.path.dirname(__file__) In Python 3.4 and newer, that's it – you get an absolute path. I...
Python equivalent of PHP's __DIR__ magic constant?
In PHP, the __DIR__ magic constant evaluates to the path to the directory containing the file in which that constant appears. Is there an equivalent feature in Python?
[ "os.path.dirname(__file__)\n\nIn Python 3.4 and newer, that's it – you get an absolute path.\nIn earlier versions of Python, __file__ refers to the file location relative to the cwd at module import time. If you call chdir, the information will be lost. If this becomes an issue, you can add the following to the roo...
[ 31 ]
[]
[]
[ "magic_constants", "php", "python" ]
stackoverflow_0006416321_magic_constants_php_python.txt
Q: Help verifying RSA signed text with Python Using Java I have created RSA keypairs. Using Java I can use these keys to sign and verify some text. I can also "export" these keys in PEM format and load them into a Python test script. Once in the Python script, I can use these keys to sign and verify some text using M...
Help verifying RSA signed text with Python
Using Java I have created RSA keypairs. Using Java I can use these keys to sign and verify some text. I can also "export" these keys in PEM format and load them into a Python test script. Once in the Python script, I can use these keys to sign and verify some text using M2Crypto. I have not yet been able to verify in P...
[ "M2Crypto.EVP defaults to 'sha1' (SHA1) and you're using MD5WithRSA. I think you should switch SHA1WithRSA (MD5 is a very weak algorithm).\n" ]
[ 2 ]
[]
[]
[ "java", "m2crypto", "public_key", "python", "rsa" ]
stackoverflow_0006370470_java_m2crypto_public_key_python_rsa.txt
Q: Why does my python not add current working directory to the path? I keep seeing sites mentioning that the directory that you execute 'python ' get added to the python path. For example on http://www.stereoplex.com/blog/understanding-imports-and-pythonpath, the author cd's to the /tmp folder then does 'print(sys.pa...
Why does my python not add current working directory to the path?
I keep seeing sites mentioning that the directory that you execute 'python ' get added to the python path. For example on http://www.stereoplex.com/blog/understanding-imports-and-pythonpath, the author cd's to the /tmp folder then does 'print(sys.path)' and lo and behold, the /tmp folder appears in the path list. Here ...
[ "It is the script's directory that is added, not the current directory. If you turn inner_folder/ into a package then you can use python -m inner_folder.myscript in order to run the script while having app/ added to sys.path.\n", "Whether or not the current directory is in sys.path, import statements usually look...
[ 78, 4 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0006416424_python_python_import.txt
Q: Add a new item to a dictionary in Python How do I add an item to an existing dictionary in Python? For example, given: default_data = { 'item1': 1, 'item2': 2, } I want to add a new item such that: default_data = default_data + {'item3': 3} A: default_data['item3'] = 3 Easy as py. Another possible solu...
Add a new item to a dictionary in Python
How do I add an item to an existing dictionary in Python? For example, given: default_data = { 'item1': 1, 'item2': 2, } I want to add a new item such that: default_data = default_data + {'item3': 3}
[ "default_data['item3'] = 3\n\nEasy as py.\nAnother possible solution:\ndefault_data.update({'item3': 3})\n\nwhich is nice if you want to insert multiple items at once.\n", "It can be as simple as:\ndefault_data['item3'] = 3\n\nAs Chris' answer says, you can use update to add more than one item. An example:\ndefa...
[ 1355, 93, 25 ]
[]
[]
[ "dictionary", "items", "python" ]
stackoverflow_0006416131_dictionary_items_python.txt
Q: Logical Error in Python Simulation This python program is supposed to simulate an object being thrown off a 50 meter building, with some initial velocity and constant gravitational acceleration. I am using arrays to store the different components, but when it's time to do my computations, my resulting matrix is n...
Logical Error in Python Simulation
This python program is supposed to simulate an object being thrown off a 50 meter building, with some initial velocity and constant gravitational acceleration. I am using arrays to store the different components, but when it's time to do my computations, my resulting matrix is not turning out like it should. In fact, ...
[ "I am not sure you have a valid question? How are you judging failure? Is it because you are printing out positionMatrix each time? \nIt just looks like nothing is there because you are printing out 3k None's each iteration. Change your line of code from: \nprint(positionMatrix)\n\nto \nprint(positionMatrix[i][...
[ 1, 1, 0 ]
[]
[]
[ "python", "simulation" ]
stackoverflow_0006416329_python_simulation.txt
Q: Simplifying an Expression in Python I feel there must be a simpler/cleaner/faster (choose one or more) way to write this expression... take a BigString = "This is a long sentence about a red cat named dude." and LittleStringList = [ "red dog", "red cat", "red mouse" ] I effectively want a function/expression that ...
Simplifying an Expression in Python
I feel there must be a simpler/cleaner/faster (choose one or more) way to write this expression... take a BigString = "This is a long sentence about a red cat named dude." and LittleStringList = [ "red dog", "red cat", "red mouse" ] I effectively want a function/expression that returns true when one of LittleStringList...
[ "any([s in BigString for s in LittleStringList])\nor even better using a generator expression - as pointed out by @GWW:\nany(s in BigString for s in LittleStringList)\n", "use any():\n>>> BigString = \"This is a long sentence about a red cat named dude.\"\n>>> LittleStringList = [ \"red dog\", \"red cat\", \"red ...
[ 11, 3, 1, 1, 0, 0 ]
[]
[]
[ "expression", "iteration", "python", "string" ]
stackoverflow_0006416432_expression_iteration_python_string.txt
Q: Django Gunicorn: Error when calling the metaclass bases I have a Django application which includes a custom model field (and accompanying form field). When I run the project with the built-in development server, it works fine. Loading the server with gunicorn, however, results in the following error: TemplateSynta...
Django Gunicorn: Error when calling the metaclass bases
I have a Django application which includes a custom model field (and accompanying form field). When I run the project with the built-in development server, it works fine. Loading the server with gunicorn, however, results in the following error: TemplateSyntaxError at /admin/ Caught TypeError while rendering: Error whe...
[ "This is due to a bug in Gunicorn when we were trying to reload Django. Its since been reverted and should be fixed on master. We're currently working on an alternative method to get reloading running for the run_gunicorn command. You can follow the progress of this here:\nhttps://github.com/benoitc/gunicorn/issues...
[ 1 ]
[]
[]
[ "django", "gunicorn", "metaclass", "python" ]
stackoverflow_0006416692_django_gunicorn_metaclass_python.txt
Q: Converters behavior in NumPy loadtxt not understood I am trying to read in data from a text file using numpy.loadtxt with the converters argument. I have a mixture of columns of ints and strings. The code is: a, b, c, d, e = np.loadtxt(infile, delimiter = ',', usecols=(0, 2, 5, 8, 9), skiprows = 1, ...
Converters behavior in NumPy loadtxt not understood
I am trying to read in data from a text file using numpy.loadtxt with the converters argument. I have a mixture of columns of ints and strings. The code is: a, b, c, d, e = np.loadtxt(infile, delimiter = ',', usecols=(0, 2, 5, 8, 9), skiprows = 1, unpack = True, converters = dict(zip((0, 2, 5...
[ "The loadtxt documentation indicates that\nconverters should contain functions that specifically return floats:\n\nconverters : dict, optional\n\nA dictionary mapping column number to a function that will convert that column to a float. E.g., if column 0 is a date string: converters = {0: datestr2num}. Converters c...
[ 4, 4 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006416688_numpy_python.txt
Q: Export data elements to text file in Python How could I alter the following code to get a table of data elements in a text file to be plotted in excel? x = z = vz = vy = ax = ay = time = 0.0 y = 50 #Initial Height: 50 meters vx = 25 #Initial velocity in the x direction: 25 m/s az = -9.8 #Constant acceleration ...
Export data elements to text file in Python
How could I alter the following code to get a table of data elements in a text file to be plotted in excel? x = z = vz = vy = ax = ay = time = 0.0 y = 50 #Initial Height: 50 meters vx = 25 #Initial velocity in the x direction: 25 m/s az = -9.8 #Constant acceleration in the z direction: -9.8 m/s^2 deltaTime = 1 #...
[ "Probably the best way to save a file for opening in Excel is to use the builtin CSV module. It will allow you to save a file that can be imported in Excel and other spreadsheet apps.\nCreate a CSV writer and use the writerows method, passing your positionMatrix list.\nPlease take a look at python docs: 13.1. csv —...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006416897_python.txt
Q: how to pass a list between views in django I have a list in one view that I would like to pass to another view to be parsed. This is what I currently have. The views: def view1(request): if request.method=='POST': list = request.POST.values() HttpResponseRedirect('/urls/'+ str(list)) def vie...
how to pass a list between views in django
I have a list in one view that I would like to pass to another view to be parsed. This is what I currently have. The views: def view1(request): if request.method=='POST': list = request.POST.values() HttpResponseRedirect('/urls/'+ str(list)) def view2(request, *list): #do something with list ...
[ "As Brandon suggested, posting to the second view was a usable solution.\nSomething along the lines of:\ndef view2(request):\n if request.method == 'POST':\n page_list=request.POST.values()\n else:\n HttpResponseRedirect('/urls/')\n\nand then no need for regex in the urls\n", "\nI would like t...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006416084_django_python.txt
Q: Duplicate packets in Python multicast receiver There is a script that opens a socket and read from it the multicast (from Multicast in Python) import socket import struct MCAST_GRP = '224.1.1.1' MCAST_PORT = 1234 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.S...
Duplicate packets in Python multicast receiver
There is a script that opens a socket and read from it the multicast (from Multicast in Python) import socket import struct MCAST_GRP = '224.1.1.1' MCAST_PORT = 1234 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', MC...
[ "An application listening to all incoming connections on a port will get all messages to that port, no matter which application initiated multicast group membership. To mitigate this, have every application listen to the multicast address it's expecting data from, by specifying it as the first argument in the addre...
[ 3 ]
[]
[]
[ "multicast", "python", "python_2.6" ]
stackoverflow_0006387535_multicast_python_python_2.6.txt
Q: Parsing unicode string read from a cell in an xlrd.Book object I am trying to parse some unicode text from an excel2007 cell read by using xlrd (actually xlsxrd). For some reason xlrd attaches "text: " to the beginning of the unicode string and is making it difficult for me to type cast. I eventually want to reve...
Parsing unicode string read from a cell in an xlrd.Book object
I am trying to parse some unicode text from an excel2007 cell read by using xlrd (actually xlsxrd). For some reason xlrd attaches "text: " to the beginning of the unicode string and is making it difficult for me to type cast. I eventually want to reverse the order of the string since it is a name and will be put in al...
[ "I think you may need\nname = sh.cell(0,0).value\n\nto get the unicode object. Then, to split into two variables, you can obtain a list with the first and last name, using an empty space as separator:\nsplit_name = name.split(' ')\nprint split_name\n\nThis gives [u'First', u'Last']. You can easily reverse the list:...
[ 4, 0 ]
[]
[]
[ "parsing", "python", "unicode", "xlrd" ]
stackoverflow_0006413772_parsing_python_unicode_xlrd.txt
Q: How do I display add model in tabular format in the Django admin? I'm just starting out with Django writing my first app - a chore chart manager for my family. In the tutorial it shows you how to add related objects in a tabular form. I don't care about the related objects, I just want to add the regular object in...
How do I display add model in tabular format in the Django admin?
I'm just starting out with Django writing my first app - a chore chart manager for my family. In the tutorial it shows you how to add related objects in a tabular form. I don't care about the related objects, I just want to add the regular object in a tabular form. This is what I have in my admin.py from chores.models ...
[ "OP is probably all set, but for new users reading this, refer to: https://docs.djangoproject.com/en/dev/ref/contrib/admin/\nBasically following part in above link:\n\nThe field_options dictionary can have the following keys:\nfields: A tuple of field names to display in this fieldset. This key is required.\nExampl...
[ 6, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004575030_django_python.txt