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: Finding the workspace size (screen size less the taskbar) using GTK How do you create a main window that fills the entire desktop without covering (or being covered by) the task bar and without being maximized? I can find the entire screen size with and set the main window accordingly with this: window = gtk.Windo...
Finding the workspace size (screen size less the taskbar) using GTK
How do you create a main window that fills the entire desktop without covering (or being covered by) the task bar and without being maximized? I can find the entire screen size with and set the main window accordingly with this: window = gtk.Window() screen = window.get_screen() window.resize(screen.get_width(), screen...
[ "You are totally at the mercy of your window manager for this, and the key issue here is:\n\nwithout being maximized\n\nSo we are left with a number of hacks, because basically maximization and resizing are two separate things, in order that you might be able to remember where it was when it is unmaximized.\nSo bef...
[ 9, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0000502282_gtk_pygtk_python.txt
Q: need help with this Kombu error Pardon the copy and paste from the python interpreter but I'm trying to play with Kombu but I can't seem to create a consumer. Please help, I'm utterly in the dark here. >>> from kombu.messaging import Consumer, Producer >>> from kombu.entity import Exchange, Queue >>> x = Exchange(...
need help with this Kombu error
Pardon the copy and paste from the python interpreter but I'm trying to play with Kombu but I can't seem to create a consumer. Please help, I'm utterly in the dark here. >>> from kombu.messaging import Consumer, Producer >>> from kombu.entity import Exchange, Queue >>> x = Exchange("stmt",type="topic") >>> helloQ = Que...
[ "Look at the error\namqplib.client_0_8.exceptions.AMQPConnectionException: (530, u\"NOT_ALLOWED - parameters for queue 'hello' in vhost 'clippy' not equivalent\", (50, 10), 'Channel.queue_declare')\n\nThis means the queue has already been declared, but with other parameters than what you\nare declaring it with now....
[ 1, 1 ]
[]
[]
[ "kombu", "python" ]
stackoverflow_0005796280_kombu_python.txt
Q: python-mplayer closes immediately Consider the following example: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from mplayer import * class mplayerStarter(QMainWindow): def __init__(self, parent=None): super(mplayerStarter, self).__init__(parent) the_button = QPushButton('Sta...
python-mplayer closes immediately
Consider the following example: import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from mplayer import * class mplayerStarter(QMainWindow): def __init__(self, parent=None): super(mplayerStarter, self).__init__(parent) the_button = QPushButton('Start Mplayer') the_button.clicke...
[ "I think it might be being garbage collected. Try this:\nclass mplayerStarter(QMainWindow):\n def __init__(self, parent=None):\n super(mplayerStarter, self).__init__(parent)\n the_button = QPushButton('Start Mplayer')\n the_button.clicked.connect(self.start)\n self.setCentralWidget(th...
[ 2 ]
[]
[]
[ "mplayer", "pyqt4", "python" ]
stackoverflow_0006521517_mplayer_pyqt4_python.txt
Q: How to add Members folder in plone.app.testing? How can I add Members folder for my functional tests in plone.app.testing so that it is findable as in real site? Have have set member area creation flag in my product installation step which I'm testing. membership.memberareaCreationFlag = 1 I need to get this tes...
How to add Members folder in plone.app.testing?
How can I add Members folder for my functional tests in plone.app.testing so that it is findable as in real site? Have have set member area creation flag in my product installation step which I'm testing. membership.memberareaCreationFlag = 1 I need to get this test working: class TestMemberFolder(unittest.TestCase):...
[ "I finally figured it out. \nAt first membership.memberareaCreationFlag = 1 is not enough for enabling member folders.\nIt must be enabled with SecurityControlPanelAdapter in plone.app.controlpanel.security\nfrom plone.app.controlpanel.security import ISecuritySchema\n# Fetch the adapter\nsecurity_adapter = ISecur...
[ 4, 0, 0 ]
[]
[]
[ "plone", "python", "testing" ]
stackoverflow_0006520207_plone_python_testing.txt
Q: Validating a list of values in Django In my model I have a field which should contain only the values 'A', 'B' and 'C'. Would this be best use for using a choice parameter when declaring the field? If I didn't decide to use the choice parameter and wanted to write custom validation logic for it, where would I writ...
Validating a list of values in Django
In my model I have a field which should contain only the values 'A', 'B' and 'C'. Would this be best use for using a choice parameter when declaring the field? If I didn't decide to use the choice parameter and wanted to write custom validation logic for it, where would I write this — would this be in the clean method ...
[ "If you only want it to be 'A', 'B', and 'C', you should definitely use Django's built in validation instead of rolling your own. See https://docs.djangoproject.com/en/1.3/ref/models/fields/ in the section titled choices.\nIn brief:\nclass Action(models.Model):\n \"\"\"\n Contains the logic for the visit\n ...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006521409_django_django_models_python.txt
Q: How to save and load an array of complex numbers using numpy.savetxt? I want to use numpy.savetxt() to save an array of complex numbers to a text file. Problems: If you save the complex array with the default format string, the imaginary part is discarded. If you use fmt='%s', then numpy.loadtxt() can't load it u...
How to save and load an array of complex numbers using numpy.savetxt?
I want to use numpy.savetxt() to save an array of complex numbers to a text file. Problems: If you save the complex array with the default format string, the imaginary part is discarded. If you use fmt='%s', then numpy.loadtxt() can't load it unless you specify dtype=complex, converters={0: lambda s: complex(s)}. Even...
[ "It's easier and saves a few temporary arrays to just reinterpret the array as a real array.\nSaving:\nnumpy.savetxt('outfile.txt', array.view(float))\n\nLoading:\narray = numpy.loadtxt('outfile.txt').view(complex)\n\nIf you prefer to have real and imaginary part on the same line in the file, you can use\nnumpy.sav...
[ 17, 6 ]
[]
[]
[ "complex_numbers", "numpy", "python" ]
stackoverflow_0006494102_complex_numbers_numpy_python.txt
Q: Python alternative to _winreg I am accessing a python script using jython and apparently the _winreg module is not supported. Are there any alternatives to this module? I am using jython 2.5. A: You'll need to access the Windows registry via Java instead.
Python alternative to _winreg
I am accessing a python script using jython and apparently the _winreg module is not supported. Are there any alternatives to this module? I am using jython 2.5.
[ "You'll need to access the Windows registry via Java instead.\n" ]
[ 1 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0006522650_java_jython_python.txt
Q: GUI interface for sqlite data entry in Python I am making a simple sqlite database for storing some non-sensitive client information. I am very familiar with python+sqlite and would prefer to stick with this combo on this project. I would like to create an simple GUI interface for data entry and searching of the...
GUI interface for sqlite data entry in Python
I am making a simple sqlite database for storing some non-sensitive client information. I am very familiar with python+sqlite and would prefer to stick with this combo on this project. I would like to create an simple GUI interface for data entry and searching of the database... something very similar to what MS Acce...
[ "Since you're interested in future integration with a web application, you might consider using a Python web framework and running the app locally on your machine, using your web browser as the interface. In that case, one easy option would be web2py. Just download, unzip, and run, and you can use the web-based IDE...
[ 11, 2 ]
[]
[]
[ "ms_access", "python", "sqlite", "user_interface" ]
stackoverflow_0006514680_ms_access_python_sqlite_user_interface.txt
Q: QLineEdit can't get anything i using pyqt develop a dialog, and a LineEidt some like below, but i can't get anything from lineEdit1: lineEdit1 = QtGui.QLineEdit() lineEdit1.setEchoMode(2) passWord = lineEdit1.text() A: lineEdit1 = QtGui.QLineEdit() lineEdit1.setEchoMode(2) passWord = lineEdit1.text() of cours...
QLineEdit can't get anything
i using pyqt develop a dialog, and a LineEidt some like below, but i can't get anything from lineEdit1: lineEdit1 = QtGui.QLineEdit() lineEdit1.setEchoMode(2) passWord = lineEdit1.text()
[ "lineEdit1 = QtGui.QLineEdit()\nlineEdit1.setEchoMode(2)\npassWord = lineEdit1.text() \n\nof course you can't get anything, because when lineEdit1.text() is executed, I believe there is no characters input into lineEdit1.\nYou should call passWord = lineEdit1.text() by some action when the input is over, for exam...
[ 3, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006522212_pyqt_python.txt
Q: Python-LDAP wont compile So I got the latest python-ldap from source. I am also running the source compiled version of python 2.7.2 and I am running this on RHEL. So when I try to compile the package I get this long error message as seen below. So I installed the openldap-devel package and now it is a much smaller...
Python-LDAP wont compile
So I got the latest python-ldap from source. I am also running the source compiled version of python 2.7.2 and I am running this on RHEL. So when I try to compile the package I get this long error message as seen below. So I installed the openldap-devel package and now it is a much smaller error. But still not compilin...
[ "The first and second error message state that you're missing lber.h and ldap.h. This is a strong pointer to a missing or invalid openldap-devel package. Do you you have that package (or a similar one matching *ldap-dev*) installed?\n", "Possibly a mismatch in the OpenLDAP and python-ldap versions. Try to compile...
[ 2, 0 ]
[]
[]
[ "ldap", "python" ]
stackoverflow_0006521141_ldap_python.txt
Q: Do you use the "global" statement in Python? I was reading a question about the Python global statement ( "Python scope" ) and I was remembering about how often I used this statement when I was a Python beginner (I used global a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a...
Do you use the "global" statement in Python?
I was reading a question about the Python global statement ( "Python scope" ) and I was remembering about how often I used this statement when I was a Python beginner (I used global a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic". Do you use this statement in P...
[ "I use 'global' in a context such as this:\n_cached_result = None\ndef myComputationallyExpensiveFunction():\n global _cached_result\n if _cached_result:\n return _cached_result\n\n # ... figure out result\n\n _cached_result = result\n return result\n\nI use 'global' because it makes sense and ...
[ 58, 16, 10, 9, 3, 3, 2, 2, 2, 2, 1, 0 ]
[]
[]
[ "global", "python" ]
stackoverflow_0000146557_global_python.txt
Q: User-defined command line arguments in python Encountered a couple of problems with my python program. Basically, I want to be able to send the path files of multiple images to the command prompt (the user defines how many images, so just putting the direct file paths as args, as below, doesn't do what I want). My...
User-defined command line arguments in python
Encountered a couple of problems with my python program. Basically, I want to be able to send the path files of multiple images to the command prompt (the user defines how many images, so just putting the direct file paths as args, as below, doesn't do what I want). My code currently looks like this: os.system("java -j...
[ "I believe you are looking for something like this\nfileNames=\"\"\nfor i in range(1, NumberOfImages):\n fileNames += \"image_0000000%d.jpg \"%i\n\nos.system( \"java -jar C:\\\\Inetpub\\\\ftproot\\\\JPivSource\\\\jpivc.jar %s\"%fileNames )\n\nRename your file from script.py to script.pyw to avoid the opening of ...
[ 1 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0006523228_command_line_python.txt
Q: Python Multi-threading Help I'm looking to call a python function from within another python script in a new thread. I have experience using subprocess.Popen, but I used that for calling .exe's in the command line. Anyone recommend how to do this or a module to use? def main(argv): call otherdef(1,2,3) in a ne...
Python Multi-threading Help
I'm looking to call a python function from within another python script in a new thread. I have experience using subprocess.Popen, but I used that for calling .exe's in the command line. Anyone recommend how to do this or a module to use? def main(argv): call otherdef(1,2,3) in a new thread sleep for 10 minutes...
[ "Here is a solution, but its not exactly like you asked, because its complicated to kill a thread. Its better to let the thread terminate itself, all threads default to daemonic=False (unless its parent thread is daemonic), so when the main thread dies, your thread would live. Set it to true, and it will die with y...
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006523526_multithreading_python.txt
Q: Can't import the ctypes python library in Google App Engine I can't import ctypes on the production GAE server, which is causing our code to break. Seemingly, urllib and urllib2 also rely on this library, but somehow it's possible to import them on production through the console (e.g. navigate to www.myapp.com/con...
Can't import the ctypes python library in Google App Engine
I can't import ctypes on the production GAE server, which is causing our code to break. Seemingly, urllib and urllib2 also rely on this library, but somehow it's possible to import them on production through the console (e.g. navigate to www.myapp.com/console). Is this a feature or a bug? Thanks! Python 2.5.2 (r252:609...
[ "ctypes is not available in the Python 2.5 runtime or in the current Python 2.7 runtime. See the knowledge base for more details and this list enumerating white-listed module.\n" ]
[ 0 ]
[]
[]
[ "ctypes", "google_app_engine", "python" ]
stackoverflow_0006515151_ctypes_google_app_engine_python.txt
Q: How to mask out bits for a pseudorandom number generator I am constructing a pseudorandom number generator for hashing purposes. We are required to use a certain algorithm. The algorithm is as follows: Initialize an integer R to be equal to 1 every time the tabling routine is called On each successive call for a...
How to mask out bits for a pseudorandom number generator
I am constructing a pseudorandom number generator for hashing purposes. We are required to use a certain algorithm. The algorithm is as follows: Initialize an integer R to be equal to 1 every time the tabling routine is called On each successive call for a random number, set R = R*5 Mask all but the lower order n+2 b...
[ "It means you take the number modulo 2^(2+n). This is so that 0 <= R < 2^(2+n), which means that 0 <= P < 2^n. One way to do this:\nR %= 2 ** (2+n)\n\nUsing bit-shift operations, which could be more efficient (note that mask is a constant, so you only need to compute it once):\nmask = (1 << 2+n) - 1\nR &= mask\n\nT...
[ 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0006523688_python_random.txt
Q: tkinter: check modified I'm a newbie python/tkinter programmer! I am displaying a text widget for the user to use as a barebones editor. Is it possible to check if the user modified it in any way, so that I know if it necessary a savefile step? thanks! alessandro A: The easiest thing to do would be to use the Te...
tkinter: check modified
I'm a newbie python/tkinter programmer! I am displaying a text widget for the user to use as a barebones editor. Is it possible to check if the user modified it in any way, so that I know if it necessary a savefile step? thanks! alessandro
[ "The easiest thing to do would be to use the Text.edit_modified() method. A simple usage example:\n>>> import Tkinter\n>>> root = Tkinter.Tk()\n>>> frame = Tkinter.Frame(root)\n>>> text = Tkinter.Text(frame)\n>>> text.pack()\n>>> frame.pack()\n>>> text.edit_modified()\n0\n>>> text.insert('1.0', 'some text')\n>>> te...
[ 8 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006523188_python_tkinter.txt
Q: python regex to replace all windows newlines with spaces I did this: from urllib import urlopen import nltk url = http://myurl.com html = urlopen(url).read() cleanhtml = nltk.clean_html(html) I now have a long string in python which is full of text interrupted periodically by windows newlines /r/n, and I simply w...
python regex to replace all windows newlines with spaces
I did this: from urllib import urlopen import nltk url = http://myurl.com html = urlopen(url).read() cleanhtml = nltk.clean_html(html) I now have a long string in python which is full of text interrupted periodically by windows newlines /r/n, and I simply want to remove all of the occurrences of /r/n from the string u...
[ "There's no need to use regular expressions, just\nhtmlspaced = html.replace('\\r\\n', ' ')\n\nIf you need to also match UNIX and oldMac newlines, use regular expressions:\nimport re\nhtmlspaces = re.sub(r'\\r\\n|\\r|\\n', ' ', html)\n\n", "Just a small syntax error:\nhtmlspaced = re.sub(r\"\\r\\n\", \" \", html)...
[ 35, 16 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006523893_python_regex.txt
Q: Error in python script I wrote a python script to make an animation but when I run it I get the error AttributeError: 'module' object has no attribute 'ion' Here is the script: import numpy as np import pylab as pl data = np.loadtxt( "random.dat" ) pl.ion() M = len( data[0] )-1 N = len( data[:,0] ) line , ...
Error in python script
I wrote a python script to make an animation but when I run it I get the error AttributeError: 'module' object has no attribute 'ion' Here is the script: import numpy as np import pylab as pl data = np.loadtxt( "random.dat" ) pl.ion() M = len( data[0] )-1 N = len( data[:,0] ) line , = pl.plot( data[0,1:] , pl.o...
[ "Try\npl.pyplot.ion()\nhttp://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ion\n" ]
[ 1 ]
[]
[]
[ "animation", "python" ]
stackoverflow_0006523834_animation_python.txt
Q: Cherrypy 3.2 virtual host dispatcher i am trying to get virtual host working in cherrypy 3.2.0 runing on python 3: #!/usr/bin/env python import cherrypy from cherrypy import expose class Root(object): @expose def index(self): return "I am the root vhost" class Foo(object): @expose de...
Cherrypy 3.2 virtual host dispatcher
i am trying to get virtual host working in cherrypy 3.2.0 runing on python 3: #!/usr/bin/env python import cherrypy from cherrypy import expose class Root(object): @expose def index(self): return "I am the root vhost" class Foo(object): @expose def index(self): return "I am testin...
[ "The ports that they show in the cherrypy docs are values other than '80'. curl at least, does not add port numbers to the Host request header if the port is 80; I suspect that cherrypy.dispatch.VirtualHost is not clever enough to match a host header of example.com on port 80 to example.com:80 or visa versa. I w...
[ 2 ]
[]
[]
[ "cherrypy", "python", "python_3.x", "virtualhost" ]
stackoverflow_0006521126_cherrypy_python_python_3.x_virtualhost.txt
Q: encoding errors running python from within bbedit Here's a question that's puzzled me for a long time. I use bbedit to edit python code. Running the code from within the editor, as I understand it, spawns its own python process, runs the code, and writes the output to a log file. So bbedit doesn't know about envir...
encoding errors running python from within bbedit
Here's a question that's puzzled me for a long time. I use bbedit to edit python code. Running the code from within the editor, as I understand it, spawns its own python process, runs the code, and writes the output to a log file. So bbedit doesn't know about environment variables and such. If I try this at the command...
[ "If BBEdit relies on external files and/or redirection to do this then no, there's no way to fix it. Fixing it would require poking some internal Python structures in order to tell it to use UTF-8 when encoding output.\n", "In the unlikely event that others have run into this, here's an odd corner of python lore ...
[ 2, 1 ]
[]
[]
[ "bbedit", "encoding", "python" ]
stackoverflow_0005981570_bbedit_encoding_python.txt
Q: Where is meta.local_fields set in django.db.models.base.py? I'm getting the error: Exception Value: (1110, "Column 'about' specified twice") As I was reviewing the Django error page, I noticed that the customizations the model User, seem to be appended to the List twice. This seems to be happening here in django/d...
Where is meta.local_fields set in django.db.models.base.py?
I'm getting the error: Exception Value: (1110, "Column 'about' specified twice") As I was reviewing the Django error page, I noticed that the customizations the model User, seem to be appended to the List twice. This seems to be happening here in django/db/model/base.py in base_save(): values = [(f, f.get_db_prep_...
[ "I had the same problem. In my case, the code was executed twice. I had the following situation:\nIn one app:\nfrom apps.accounts.models import User\n\nAnd in another app:\nfrom accounts.models import User\n\nSince the customization code was in the accounts/models.py module, it was executed twice.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002188457_django_django_models_python.txt
Q: Using self in Django Model classes While adding model class to models.py in Django, why don't we use self with the field variables which we define? Shouldn't not using self field variables make them class variables instead,which "may" cause a problem. A: Django uses metaclasses to create the actual class based ...
Using self in Django Model classes
While adding model class to models.py in Django, why don't we use self with the field variables which we define? Shouldn't not using self field variables make them class variables instead,which "may" cause a problem.
[ "Django uses metaclasses to create the actual class based on the class definition your provide. In brief, upon instantiation of your model class, the metaclass will run through your model field definitions and return a corresponding class with the appropriate attributes.\nTo answer your question directly, using cla...
[ 12 ]
[]
[]
[ "django", "django_models", "python", "self" ]
stackoverflow_0006524251_django_django_models_python_self.txt
Q: Debugging a simple pygame game When I run this, it executes to an error in one of the imports. I posted the error at tend end of the code. The program essentially doesn't run, I can't tell what errors are occurring from the tracebacks. Any insight would be appreciated. from livewires import games, color import ran...
Debugging a simple pygame game
When I run this, it executes to an error in one of the imports. I posted the error at tend end of the code. The program essentially doesn't run, I can't tell what errors are occurring from the tracebacks. Any insight would be appreciated. from livewires import games, color import random games.init (screen_width = 640,...
[ "Don't know anything about livewires, but the following looks suspicious:\nle_chef = Chef = ()\ngames.screen.add(le_chef)\nle_pan = Pan = ()\ngames.screen.add (le_pan)\n\nYou have classes called Chef, and Pan, but you're not doing anything with these - just assigning these things an empty tuple, and then adding the...
[ 7 ]
[]
[]
[ "debugging", "pygame", "python" ]
stackoverflow_0006524630_debugging_pygame_python.txt
Q: How far up the chain of function calls does an exception travel? For example, say func1 calls func2, which calls func3, which calls func4, which raises an exception. If I put a try/except when calling func1, will it catch the exception raised by func4? func1 --> func2 --> func3 --> func4 Raises exception A: Exce...
How far up the chain of function calls does an exception travel?
For example, say func1 calls func2, which calls func3, which calls func4, which raises an exception. If I put a try/except when calling func1, will it catch the exception raised by func4? func1 --> func2 --> func3 --> func4 Raises exception
[ "Exceptions propagate until they reach a handler, or until they reach the entry point for the program or thread. If the latter happens, your program will terminate. So, yes, the exception will be caught in func1, unless one of the other functions catches it first.\n", "The exception is propagated up the call stac...
[ 7, 3 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0006524973_exception_python.txt
Q: Python Regular Expressions to extract date I have strings that look like these: {server}_{date:YYYYMMDD}{int:######} {server}_{date:MON DAY YYYY}{int:######} ...plus more, in different date formats. Also, there can be any number of {} blocks, and they can appear in any order. I'm trying to get just the "date" pa...
Python Regular Expressions to extract date
I have strings that look like these: {server}_{date:YYYYMMDD}{int:######} {server}_{date:MON DAY YYYY}{int:######} ...plus more, in different date formats. Also, there can be any number of {} blocks, and they can appear in any order. I'm trying to get just the "date" part between the curly braces in Python 3.2. So f...
[ "'(\\{date:[\\w\\s]+\\})' gives what you want:\n>>> import re\n>>> re.findall('(\\{date:[\\w\\s]+\\})', '{server}_{date:YYYYMMDD}{date:MONDAYYYYY}{int:######}')\n['{date:YYYYMMDD}', '{date:MONDAYYYYY}']\n>>> re.findall('(\\{date:[\\w\\s]+\\})', '{server}_{date:MON DAY YYYY}{int:######}')\n['{date:MON DAY YYYY}']\n\...
[ 5, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006524850_python_regex.txt
Q: How to implement pointer of typedef'd variable into SWIG? argument 2 of type 'BYTE const *' error I am setting up a Python-C SWIG interface right now. I've already gotten it to produce the shared object file through the following commands: swig -python myFile.i gcc -c myFile.c myFile2.c myFile3.c myFile_wrap.c -IC...
How to implement pointer of typedef'd variable into SWIG? argument 2 of type 'BYTE const *' error
I am setting up a Python-C SWIG interface right now. I've already gotten it to produce the shared object file through the following commands: swig -python myFile.i gcc -c myFile.c myFile2.c myFile3.c myFile_wrap.c -IC:\myincludedirectory\include gcc -shared myFile.o myFile2.o myFile3.o myFile_wrap.o -Ic:\myincludedirec...
[ "After the %include \"defs.h line, try adding this line:\n%apply char* {BYTE*};\n\nThis will apply all of the char* typemaps (including type-checking) to BYTE*. For more on this, read the following section of the SWIG manual:\nhttp://www.swig.org/Doc2.0/Typemaps.html#Typemaps_nn6\n" ]
[ 3 ]
[]
[]
[ "c", "parameters", "pointers", "python", "swig" ]
stackoverflow_0006416377_c_parameters_pointers_python_swig.txt
Q: Trying to write Python script to remove duplicate fonts Mac OSX I am trying to write a utility to check through the fonts on OSX and remove duplicates - so far I've had success iterating through the folder structure and writing out an xml file containing fonts and paths. The drawback is that this doesn't find dupl...
Trying to write Python script to remove duplicate fonts Mac OSX
I am trying to write a utility to check through the fonts on OSX and remove duplicates - so far I've had success iterating through the folder structure and writing out an xml file containing fonts and paths. The drawback is that this doesn't find duplicates as the same font can be installed twice in different locations...
[ "Install the fonttools package and take a look at this blog post. There's a script there that gives the font name of its first argument and I'm sure you could adapt it to your use case.\n", "Thanks once again for the replies - I just wanted to update this in the hope it helps. I'm looking at fontTools now, but ad...
[ 1, 0 ]
[]
[]
[ "fonts", "macos", "pyobjc", "python" ]
stackoverflow_0006426299_fonts_macos_pyobjc_python.txt
Q: MySql bulk import without writing a file to disk I have a django site running with a mysql database backend. I accept fairly large uploads from one of the admin users to bulk import some data. The data comes in a format that is slightly different than the form it needs to be in the database so I need to do a lit...
MySql bulk import without writing a file to disk
I have a django site running with a mysql database backend. I accept fairly large uploads from one of the admin users to bulk import some data. The data comes in a format that is slightly different than the form it needs to be in the database so I need to do a little parsing. I'd like to be able to pivot this data in...
[ "There is an excellent tutorial called Generator Tricks for Systems Programmers that addresses processing large log files, which is similar, but not identical, to your situation. As long as you can perform the needed transform with access to only the current (and possibly previous) data in the stream, this may work...
[ 2, 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006525010_django_mysql_python.txt
Q: Python to Javascript >>> def clockwise(r): ... return list(r[0]) + clockwise(list(reversed(zip(*r[1:])))) if r else [] ... >>> a = [ ... [ 1, 2, 3], ... [ 5, 6, 7], ... [ 9, 10, 11]] >>> clockwise(a) [1, 2, 3, 7, 11, 10, 9, 5, 6] I'm trying to change the function clockwise into Javascript but ca...
Python to Javascript
>>> def clockwise(r): ... return list(r[0]) + clockwise(list(reversed(zip(*r[1:])))) if r else [] ... >>> a = [ ... [ 1, 2, 3], ... [ 5, 6, 7], ... [ 9, 10, 11]] >>> clockwise(a) [1, 2, 3, 7, 11, 10, 9, 5, 6] I'm trying to change the function clockwise into Javascript but can't seem to get it to work...
[ "I think the problem lies in the use of splice. Try something like this instead...\nfunction clockwise(r){\n if(r.length>0){\n var remaining = r.slice(1)\n var a = reversed(zip(remaining));\n return r[0].concat(clockwise(a));\n } else {\n return [];\n }\n}\n\n", "I think you...
[ 2, 1, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0006524691_javascript_python.txt
Q: How can one identify children of a child process? I have a long-running Python program that starts and stops a Postgres server as part of its operation. I stop the server by using subprocess to spawn pg_ctl -m fast. As a fall-back, I check the return code and, if it failed, I then run pg_ctl -m immediate. The pr...
How can one identify children of a child process?
I have a long-running Python program that starts and stops a Postgres server as part of its operation. I stop the server by using subprocess to spawn pg_ctl -m fast. As a fall-back, I check the return code and, if it failed, I then run pg_ctl -m immediate. The problem is that sometimes both fail. I haven't been able...
[ "Here is a simple shell script solution:\npgrep -P $(head -1 $PGDATA/postmaster.pid)\n\nThis prints out the PIDs of the child processes.\nI'm not aware of a standard Python module that can get that information. pgrep gets the information from /proc, so you could reimplement that in Python, but I doubt that it woul...
[ 1, 0 ]
[]
[]
[ "c++", "cross_platform", "postgresql", "process", "python" ]
stackoverflow_0006523883_c++_cross_platform_postgresql_process_python.txt
Q: Parse timestamps in plain text file and count them per 5 minute intervals My Input is a plain text file containing 6,000 timestamps, looks like this 2011-06-21 13:17:05,905 2011-06-21 13:17:11,371 2011-06-21 13:17:16,380 2011-06-21 13:17:20,074 2011-06-21 13:17:20,174 2011-06-21 13:17:24,749 2011-06-21 13:17:27,21...
Parse timestamps in plain text file and count them per 5 minute intervals
My Input is a plain text file containing 6,000 timestamps, looks like this 2011-06-21 13:17:05,905 2011-06-21 13:17:11,371 2011-06-21 13:17:16,380 2011-06-21 13:17:20,074 2011-06-21 13:17:20,174 2011-06-21 13:17:24,749 2011-06-21 13:17:27,210 2011-06-21 13:17:27,354 2011-06-21 13:17:29,231 2011-06-21 13:17:29,965 2011-...
[ "This is untested and you'll have to implement the time conversion functions yourself. You'll have to look in the time module for functions that does what you want. The convert_time_string_to_unix_time should convert a time string to the corresponding number of milliseconds since Jan 1st, 1970 (a standard Unix time...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0006525434_python.txt
Q: availableAudioEffects() error when trying to play audio at different speed in Phonon I'm trying to investigate how to play sound at different speeds with Phonon in Ubuntu. My first thought was to examine what options are available in the function call: Phonon.BackendCapabilities.availableAudioEffects() However, ...
availableAudioEffects() error when trying to play audio at different speed in Phonon
I'm trying to investigate how to play sound at different speeds with Phonon in Ubuntu. My first thought was to examine what options are available in the function call: Phonon.BackendCapabilities.availableAudioEffects() However, here is what happens when I import PyQt and Phonon and then make that function call: ely@...
[ "You are getting a list of EffectDescription objects. You can get the api from the class reference. For example,\n>>>for effect in Phonon.BackendCapabilities.availableAudioEffects():\n print effect.name()\n\nParamEq\nWavesReverb\nGargle\nCompressor\nDistortion\nEcho\nI3DL2Reverb\nFlanger\nChorus\n\nOn anoth...
[ 1 ]
[]
[]
[ "phonon", "pyqt", "python" ]
stackoverflow_0006525159_phonon_pyqt_python.txt
Q: Python URL Redirect Problem I've got a link that I know redirects to another end url, and I'm trying to get the address for that end url using python. But the original link is a little weird, and doesn't work like a normal redirect, and I can't figure out why. When I post the link (the link's below for you try, ...
Python URL Redirect Problem
I've got a link that I know redirects to another end url, and I'm trying to get the address for that end url using python. But the original link is a little weird, and doesn't work like a normal redirect, and I can't figure out why. When I post the link (the link's below for you try, if you'd like) into a browser, it...
[ "(original answer deleted)\nIf you look at the contents of f.read() you'll see what's going on here. Instead of returning a 301 or 302 that redirects to the new URL, Facebook actually returns a real HTML document - which contains a piece of Javascript that uses document.location.replace to change the URL in the br...
[ 0, 0 ]
[]
[]
[ "ajax", "python", "redirect" ]
stackoverflow_0006525244_ajax_python_redirect.txt
Q: Fortran to Python format floats I'm writing a front end gui in Python3.2, and part of the final output is based off of a fortran format. I've found a good few examples, and haven't had many problems translating from fortran to python (e.g. F10.3 == "{:10.3F}") However, I'm seeing some differences in some of the ex...
Fortran to Python format floats
I'm writing a front end gui in Python3.2, and part of the final output is based off of a fortran format. I've found a good few examples, and haven't had many problems translating from fortran to python (e.g. F10.3 == "{:10.3F}") However, I'm seeing some differences in some of the example output my python is trying to m...
[ "M. S. B. is correct about the input and ouptut. If you are unclear about FORTRAN format statements then the following examples using the fortranformat library (v 0.2.2, available on PyPI) may help. Note the library has been extensively tested against Intel FORTRAN compiler 9.1 on Linux (other platforms only differ...
[ 3, 2, 0 ]
[]
[]
[ "floating_point", "format", "fortran", "python" ]
stackoverflow_0006197908_floating_point_format_fortran_python.txt
Q: How to convert letters like ā, ä, å to simple ascii letters like a, a, a in Python? Possible Duplicate: Python and character normalization Anyone knows how to drop the umlauts and other funny thingies above letters such as ā, ä, å to make them simple ascii characters like a, a, a in Python?
How to convert letters like ā, ä, å to simple ascii letters like a, a, a in Python?
Possible Duplicate: Python and character normalization Anyone knows how to drop the umlauts and other funny thingies above letters such as ā, ä, å to make them simple ascii characters like a, a, a in Python?
[]
[]
[ "I don't think they can be trivially converted since the letters ā, ä, å are valid characters as per Unicode. What you would need to do is do your own mapping from say ā, ä, å to a, if that's what you are looking to do.\n" ]
[ -2 ]
[ "python", "special_characters" ]
stackoverflow_0006525993_python_special_characters.txt
Q: String block formatting challenge I'm working on a way to automatically download earthquake parameters from the National Earthquake Information Center (the USGS). Unfortunately their format is a pile of crap, and I don't think I'll have much luck convincing them to change their format. So, I have to format their...
String block formatting challenge
I'm working on a way to automatically download earthquake parameters from the National Earthquake Information Center (the USGS). Unfortunately their format is a pile of crap, and I don't think I'll have much luck convincing them to change their format. So, I have to format their <pre> block of html just to put it in ...
[ "Why not just use one of their XML formatted feeds such as this one. I'm sure it's easier to parse.\n", "Parsing html with regular expressions is normally seen as a very, very bad idea, so I'd second Abizern's suggestion of using the RSS feed. In fact, the USGS provide XML downloads also (see http://earthquake.us...
[ 3, 2, 1 ]
[]
[]
[ "awk", "formatting", "python", "shell", "string" ]
stackoverflow_0006523257_awk_formatting_python_shell_string.txt
Q: Understanding super() and questions about class constructors The following is a sample piece of code from a program that I'm referring to. I realized that I hadn't truly this concept, so I'm asking here. class Chef(games.Sprite): """ A chef which moves left and right, dropping pizzas. """ image = ...
Understanding super() and questions about class constructors
The following is a sample piece of code from a program that I'm referring to. I realized that I hadn't truly this concept, so I'm asking here. class Chef(games.Sprite): """ A chef which moves left and right, dropping pizzas. """ image = games.load_image("chef.bmp") def __init__(self, y = 0, speed ...
[ "Naw. The = 0, = 2, etc., don't initialize the object - they're just default arguments to a function. Eg:\ndef foo(x, y=20):\n print x, y\nfoo(10, 30)\nfoo(10)\n\nIn the code you wrote, that means you can just call Chef(), and in the constructor, the values for the variables y, speed, and odds_change will be the...
[ 3, 2 ]
[]
[]
[ "class", "python", "super" ]
stackoverflow_0006526123_class_python_super.txt
Q: Python Programming for the Absolute Beginner I'm a python noob and I'm getting to grips with python via 'Python Programming for the Absolute Beginner (2nd Edition - Python 2.3, but I'm using 2.7)'. The book presents challenges to complete and I'm having trouble getting my head round one of them; any help would b...
Python Programming for the Absolute Beginner
I'm a python noob and I'm getting to grips with python via 'Python Programming for the Absolute Beginner (2nd Edition - Python 2.3, but I'm using 2.7)'. The book presents challenges to complete and I'm having trouble getting my head round one of them; any help would be greatly appreciated as I want to get my head aro...
[ "You have a tries variable there. How about checking it inside while and if it reaches a certain value, you print a message to the user and exit ;)\n", "I think what this exercise wants to teach you is the break statement. Before you had only one exit condition (guessing the number) but now you have also the limi...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "python_2.x" ]
stackoverflow_0004542581_python_python_2.x.txt
Q: In python, how to divide two lists of lists by each other? I have two lists like so volB = [(Tarp, 3440, 7123), (Greg, 82, 1083)] and # 500B = [(Tarp, 85, 203), (Greg, 913, 234)] B500 = [(Tarp, 85, 203), (Greg, 913, 234)] I want to divide the second elements by each other. (In this case, I'd want to divide 3440 ...
In python, how to divide two lists of lists by each other?
I have two lists like so volB = [(Tarp, 3440, 7123), (Greg, 82, 1083)] and # 500B = [(Tarp, 85, 203), (Greg, 913, 234)] B500 = [(Tarp, 85, 203), (Greg, 913, 234)] I want to divide the second elements by each other. (In this case, I'd want to divide 3440 by 85, 82 by 913, and so on. Thanks for the help?
[ "from __future__ import division\nquotients = [x[1] / y[1] for x, y in zip(list1, list2)]\n\n" ]
[ 7 ]
[ "OR not so beatiful but:\nlA = [('A',123,11),('B', 1, 11)]\nlB = [('B',12,11),('A', 1, 11)]\n\nres = {}\n\nfor x,y,z in (lA+lB):\n if not x in res:\n res[x] = y\n continue\n res[x] = res[x] / (y * 1.0)\n\nEdited as per comment to be more pythonic (note that Sven's solution has been selected as b...
[ -1 ]
[ "list", "python" ]
stackoverflow_0006525746_list_python.txt
Q: Testing (unittest) if a variable is a nonempty string in python the right way? Maybe this question is trivial, but I am still trying to warm up with unittests in python, so please have patience with me. :-) While trying to write some tests of my own, the following question araised. Assuming a function that process...
Testing (unittest) if a variable is a nonempty string in python the right way?
Maybe this question is trivial, but I am still trying to warm up with unittests in python, so please have patience with me. :-) While trying to write some tests of my own, the following question araised. Assuming a function that processes nonempty strings: class BadInputError(Exception): pass class FooBar(object): ...
[ "If it looks like a duck it is a duck. Don't worry so much about type. Just try to use param. If you absolutely must check that it seems kosher, you can always do:\nif not hasattr(param, 'replace'):\n raise ValueError('I cant work with param')\n\n... or, if it is really important that param is something (rather ...
[ 3, 3 ]
[]
[]
[ "python", "string", "unit_testing" ]
stackoverflow_0006524839_python_string_unit_testing.txt
Q: How to handle XMPP subscribtions with SleekXMPP or python i general Here is my use-case: User clicks link on webpage saying: "Follow this person on XMPP" Script is initiated and gets (based on registered data) the requestors username and password and starts. The subscription request is sent. If a subscription is...
How to handle XMPP subscribtions with SleekXMPP or python i general
Here is my use-case: User clicks link on webpage saying: "Follow this person on XMPP" Script is initiated and gets (based on registered data) the requestors username and password and starts. The subscription request is sent. If a subscription is already sent, the script should not send another one. If the subscriptio...
[ "Alternately, try putting a like like xmpp:simena@*.com?subscribe on the web page, which should do the right thing in your existing desktop client.\n" ]
[ 0 ]
[]
[]
[ "python", "xmpp", "xmppframework" ]
stackoverflow_0006506806_python_xmpp_xmppframework.txt
Q: C++ Name Mangling Library for Python I'd like to mangle and demangle C++ function names in a Python program. Is there anything like that available? I searched for hours now, perhaps I'm lucky here... A: If you want to demangle names, eg. for display, then you can create a pipe that runs c++filt. def demangle(nam...
C++ Name Mangling Library for Python
I'd like to mangle and demangle C++ function names in a Python program. Is there anything like that available? I searched for hours now, perhaps I'm lucky here...
[ "If you want to demangle names, eg. for display, then you can create a pipe that runs c++filt.\ndef demangle(names):\n args = ['c++filt']\n args.extend(names)\n pipe = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n stdout, _ = pipe.communicate()\n demangled = stdout.split(\"\...
[ 22, 3 ]
[]
[]
[ "c++", "name_mangling", "python" ]
stackoverflow_0006526500_c++_name_mangling_python.txt
Q: Is it possible to specify Date XFStyle without an exact format with xlwt? I'm using Python-Excel xlwt to create a blank Excel spreadsheet for filling out in a spreadsheet. I would like to specify that a certain range of cells should be date formatted. I'm doing something like: datestyle = xlwt.XFStyle() datestyle....
Is it possible to specify Date XFStyle without an exact format with xlwt?
I'm using Python-Excel xlwt to create a blank Excel spreadsheet for filling out in a spreadsheet. I would like to specify that a certain range of cells should be date formatted. I'm doing something like: datestyle = xlwt.XFStyle() datestyle.num_format_str = "YYYY-MM-DD" ws.write(row, column, "", datestyle) but that's ...
[ "The format you're prescribing defines how the date will be displayed, but it won't affect how excel interprets entered dates. If your format is YYYY-MM-DD, the user can still enter 5/21/2008, and the string will be converted to it's date value (39589) and then displayed in your specified format: \"2008-01-21\"\n",...
[ 2, 2 ]
[]
[]
[ "excel", "python", "xlwt" ]
stackoverflow_0006524346_excel_python_xlwt.txt
Q: Python throwing strange NameError: name is not defined import networkx as nx #@UnresolvedImport from networkx.algorithms import bipartite #@UnresolvedImport from operator import itemgetter from random import choice corpus = open('/home/abehl/Desktop/Corpus/songs.wx', 'r') ALPHA = 1.5 EPSILON = 0.5 song_nodes =...
Python throwing strange NameError: name is not defined
import networkx as nx #@UnresolvedImport from networkx.algorithms import bipartite #@UnresolvedImport from operator import itemgetter from random import choice corpus = open('/home/abehl/Desktop/Corpus/songs.wx', 'r') ALPHA = 1.5 EPSILON = 0.5 song_nodes = [] word_nodes = [] edges = zip(song_nodes, word_nodes) ...
[ "A Python program is executed from top to bottom, so you need to define the function before you use it. A common alternative is putting all the code that is automatically executed in a main function, and adding at the bottom of the file:\nif __name__ == '__main__':\n main()\n\nThis has the additional advantage t...
[ 8, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006526856_python.txt
Q: How to extract playlists (list of file locations) from iTunes using python I want to point a python script to my iTunes directory and extract the playlist information. I believe playlist information is in a .ITL file? How can I do this using python? A: The iTunes library xml file is in the same directory as the ...
How to extract playlists (list of file locations) from iTunes using python
I want to point a python script to my iTunes directory and extract the playlist information. I believe playlist information is in a .ITL file? How can I do this using python?
[ "The iTunes library xml file is in the same directory as the .itl file. The file is in Apple plist format, and Python's standard library has a good parser for it.\n", "According to Apple there should also be an xml file in the same location with the express purpose of making your music and playlists available. Tr...
[ 3, 1 ]
[]
[]
[ "itunes", "playlist", "python" ]
stackoverflow_0006525963_itunes_playlist_python.txt
Q: Twitter Oauth problem - I need a website to register an app I need to use Oauth for a personal twitter script I am making. Its not commercial or anything like that. To register it here: https://dev.twitter.com/apps/new I need a website even though it is a client. It wont let me register my app without a website. ...
Twitter Oauth problem - I need a website to register an app
I need to use Oauth for a personal twitter script I am making. Its not commercial or anything like that. To register it here: https://dev.twitter.com/apps/new I need a website even though it is a client. It wont let me register my app without a website. Is there anything I can do? If I just created a blog that explain...
[ "Choose Client here:\n\nIn place of Application Website you can put any link. Its just the link-back url.\n", "If it is just for personal use, you could put pretty much any url in that field. As far as I know it isn't double checked or subjected to approval.\n", "As mentioned above, the callback URL can be anyt...
[ 1, 1, 0 ]
[]
[]
[ "oauth", "python", "registration", "twitter" ]
stackoverflow_0006513168_oauth_python_registration_twitter.txt
Q: What is the pros/cons of storing session data in file vs database? When building a website, one have to decide how to store the session info, when a user is logged in. What is a pros and cons of storing each session in its own file versus storing it in a database? A: I generally wouldnt ever store this informati...
What is the pros/cons of storing session data in file vs database?
When building a website, one have to decide how to store the session info, when a user is logged in. What is a pros and cons of storing each session in its own file versus storing it in a database?
[ "I generally wouldnt ever store this information in a file - you run the risk of potentially swapping this file in and out of memory (yes it could be cached at times) but I would rather use an in memory mechanism designed as such and you are then using something that is fairly nonstandard.\nIn ASP.Net \n\nyou can u...
[ 3, 1, 1 ]
[]
[]
[ "asp.net", "php", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0006510075_asp.net_php_python_ruby_ruby_on_rails.txt
Q: How to PyOpengl or pyglet to draw on top of desktop? I'm writing an application that is looking to draw basic polygons and ellipses on the Windows 7 desktop using OpenGL. According to this previous question, this is possibly by getting the window handle to the desktop, which I know how to do. Draw OpenGL on the wi...
How to PyOpengl or pyglet to draw on top of desktop?
I'm writing an application that is looking to draw basic polygons and ellipses on the Windows 7 desktop using OpenGL. According to this previous question, this is possibly by getting the window handle to the desktop, which I know how to do. Draw OpenGL on the windows desktop without a window However, I've got two quest...
[ "Trying to do OpenGL on another process' window is a really, really bad idea! For OpenGL to work it needs to set the window's pixel format. However the pixel format of a window can be set only once, so doing this on a foreign window is a recipe for disaster.\nThe proper way to do this, but it's slow like nothing el...
[ 2 ]
[]
[]
[ "opengl", "pyglet", "pyopengl", "python", "windows" ]
stackoverflow_0006526627_opengl_pyglet_pyopengl_python_windows.txt
Q: Two syntax errors in my python code I've written a small program in python 3.2 that takes numbers as an input and counts them by a user chosen amount. For some reason I've been getting some syntax errors. Here's the code. start = input(int("Starting number: ")) ending = input(int("Ending number: ")) ti...
Two syntax errors in my python code
I've written a small program in python 3.2 that takes numbers as an input and counts them by a user chosen amount. For some reason I've been getting some syntax errors. Here's the code. start = input(int("Starting number: ")) ending = input(int("Ending number: ")) tick = input(int(("Interval: ")) print(...
[ "You have an unmatched '(' in line 3.\nYour for loop shouldn't be in a print function call.\nThis isn't a syntax problem, I don't think, but you should have int(input(...)) instead of input(int(...)).\n", "start = input(int(\"Starting number: \"))\nending = input(int(\"Ending number: \"))\ntick = input(int((\"Int...
[ 2, 0, 0 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0006527335_python_syntax_error.txt
Q: How to Fetch all Entity Types in AppEngine How can I retrieve all of the entity types from the datastore in appengine? For examaple, in my ORM I have defined: class Person(db.Model): # fields here... class Employee(db.Model): # fields here... I want a way to get "Employee" and "Person" in a list, but not the...
How to Fetch all Entity Types in AppEngine
How can I retrieve all of the entity types from the datastore in appengine? For examaple, in my ORM I have defined: class Person(db.Model): # fields here... class Employee(db.Model): # fields here... I want a way to get "Employee" and "Person" in a list, but not the actual data. Thanks in advance!
[ "Look in http://code.google.com/appengine/docs/python/datastore/metadataqueries.html and look for\nq = Kind.all()\n\nThat's the snippet you need.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "metadata", "orm", "python" ]
stackoverflow_0006525563_google_app_engine_metadata_orm_python.txt
Q: One server vs. multiple clients with data communication I have a question on how to implement a server and multiple clients with data communication. They share the same dataset for each step. That is, a server gets the same step's data for each client. I have no idea how to sync all clients and communicate data f...
One server vs. multiple clients with data communication
I have a question on how to implement a server and multiple clients with data communication. They share the same dataset for each step. That is, a server gets the same step's data for each client. I have no idea how to sync all clients and communicate data file for each step. Can you give me some hints or a basic idea...
[ "Take a loot at these\nMulti-threaded multi-client server in python\nClient Server programming in python?\nhttp://ilab.cs.byu.edu/python/select/echoserver.html\n", "If you don't want to deal with details like socket and connection handling and you like high diving, you should look into Twisted\nHere's a SO answer...
[ 2, 0 ]
[]
[]
[ "client_server", "communication", "python", "sockets" ]
stackoverflow_0006527366_client_server_communication_python_sockets.txt
Q: Python multiprocessing pool inside daemon process I opened up a question for this problem and did not get a thorough enough answer to solve the issue (most likely due to a lack of rigor in explaining my issues which is what I am attempting to correct): Zombie process in python multiprocessing daemon I am trying to...
Python multiprocessing pool inside daemon process
I opened up a question for this problem and did not get a thorough enough answer to solve the issue (most likely due to a lack of rigor in explaining my issues which is what I am attempting to correct): Zombie process in python multiprocessing daemon I am trying to implement a python daemon that uses a pool of workers ...
[ "The solution is to put the self.pool = Pool(process=4) as the last line of the daemonize method. Otherwise the pool ends up getting lost somewhere (perhaps in the forks). Then the pool can be access inside the run method which is overloaded by the application you wish to daemonize. However, the pool cannot be acce...
[ 1 ]
[]
[]
[ "multiprocessing", "multithreading", "pool", "python", "threadpool" ]
stackoverflow_0006516508_multiprocessing_multithreading_pool_python_threadpool.txt
Q: How can I loop and change the elements of a list with the elements of another list that has a different range? This first lines work, and i get V(i) =V+QIN(i)-QOUT(i), but when i try to do T(i) = (T + C(i) + TIN(i)*QIN(i)) /((C(i)+QIN(i)), how can I loop trought each C [i], QOUT=[1.0, 3.0, 1.0, 2.0] QIN=[2.0,...
How can I loop and change the elements of a list with the elements of another list that has a different range?
This first lines work, and i get V(i) =V+QIN(i)-QOUT(i), but when i try to do T(i) = (T + C(i) + TIN(i)*QIN(i)) /((C(i)+QIN(i)), how can I loop trought each C [i], QOUT=[1.0, 3.0, 1.0, 2.0] QIN=[2.0, 3.0, 5.0, 2.0] TIN=[10.0,12.0,13.0, 12.0] V=[2.0, 4.0, 5.0] T=[10.0, 11.0, 12.0] #4 iterations #V(i) = V+QIN(i)...
[ "Sorry could not post images.\nindentation problems are on lines 19,21,23,25,29 - switch special characters on in any editor and you will see them.\nBut real cause of problem is in reusing numlines variable, thus it rises IndexError.\nPossible solution:\nQOUT=[1.0, 3.0, 1.0, 2.0]\nQIN=[2.0, 3.0, 5.0, 2.0]\nTIN=[10....
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006526238_python.txt
Q: Plugin design question My program is broken down into two parts: the engine, which deals with user interface and other "main program" stuff, and a set of plugins, which provide methods to deal with specific input. Each plugin is written in its own module, and provides a function that will allow me to send and retr...
Plugin design question
My program is broken down into two parts: the engine, which deals with user interface and other "main program" stuff, and a set of plugins, which provide methods to deal with specific input. Each plugin is written in its own module, and provides a function that will allow me to send and retrieve data to and from the pl...
[ "Here is the code I use to do this:\ndef _loadPackagePlugins(package):\n \"Load plugins from a specified package.\"\n ppath = package.__path__\n pname = package.__name__ + \".\"\n for importer, modname, ispkg in pkgutil.iter_modules(ppath, pname):\n module = __import__(modname, fromlist = \"dummy\")\n\nThe m...
[ 2, 1 ]
[]
[]
[ "plugin_architecture", "python" ]
stackoverflow_0006527747_plugin_architecture_python.txt
Q: How to remove a word from .txt i am reading a file .txt, now I wanna remove duplicate words. c = collections.Counter() with open('DatoSO.txt', 'rt') as f: for line in f: c.update(line.split()) for palabra,count in c.most_common(): if count > 1 : with open('DatoSO.txt', 'rt') as f: ...
How to remove a word from .txt
i am reading a file .txt, now I wanna remove duplicate words. c = collections.Counter() with open('DatoSO.txt', 'rt') as f: for line in f: c.update(line.split()) for palabra,count in c.most_common(): if count > 1 : with open('DatoSO.txt', 'rt') as f: Here REMOVE I dont know ...
[ "You can't remove content from a file and have the remaining content shifted down. You can only append, truncate or overwrite.\nYour best option is to read the file in to memory, process it in memory and then write it back to disk.\n", "Use regular expressions:\nimport re\n\n...\n\nf = re.sub(r'\\w+\\s?','',f)\n\...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006527849_python.txt
Q: Simple test tool for python projects I have a python project that takes in two Excel spreadsheets with various data as input, and depending on given parameters in a python 'run' type module, produces several spreadsheets which contain statistical information as outputs. I have several versions of this project rel...
Simple test tool for python projects
I have a python project that takes in two Excel spreadsheets with various data as input, and depending on given parameters in a python 'run' type module, produces several spreadsheets which contain statistical information as outputs. I have several versions of this project released already to a few clients, but testin...
[ "One of the unit testing frameworks you list is just what you need. Testing is hard and takes time. If you try to do it without putting in sufficient time and thought your testing won't be worth very much.\nIt sounds like you are wanting a list of inputs and outputs that your test loops through. That's easy. Just d...
[ 0 ]
[]
[]
[ "excel", "python", "testing", "unit_testing" ]
stackoverflow_0006528059_excel_python_testing_unit_testing.txt
Q: Index by word length My aim was to simply make a hangman game. However, I have been slightly over-ambitious. I want to ask the user to input how long they want the word. Then choose a random word of that length. To index an entire dictionary of that length would take far too long on each iteration. So. I have a di...
Index by word length
My aim was to simply make a hangman game. However, I have been slightly over-ambitious. I want to ask the user to input how long they want the word. Then choose a random word of that length. To index an entire dictionary of that length would take far too long on each iteration. So. I have a dictionary, formatted like s...
[ "It's really not that big of a deal to load an entire dictionary into memory. You can try something like this:\nimport random\nfrom collections import defaultdict\n\n# load words\nindex = defaultdict(list)\nwith open('words.txt') as file:\n for line in file:\n word = line.strip().lower()\n index[le...
[ 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "indexing", "new_operator", "python" ]
stackoverflow_0006528263_dictionary_indexing_new_operator_python.txt
Q: Why does Aptana (eclipse) create duplicate python packages/files? A picture says more then thousand words: I created one src foulder and one webscraper folder with one file named dblp.py in it. Why is Aptana/Eclipse showing the duplicates? A: A workaround is to click on the drop-down arrow in Project Explorer a...
Why does Aptana (eclipse) create duplicate python packages/files?
A picture says more then thousand words: I created one src foulder and one webscraper folder with one file named dblp.py in it. Why is Aptana/Eclipse showing the duplicates?
[ "A workaround is to click on the drop-down arrow in Project Explorer and select Customize View...; then in the new dialog, switch to Content tab and uncheck the Local Filesystem entry.\n" ]
[ 1 ]
[]
[]
[ "aptana", "duplication", "eclipse", "file", "python" ]
stackoverflow_0006480915_aptana_duplication_eclipse_file_python.txt
Q: Mysterious Apache Django WSGI Error I'm running a django application on apache with mod_wsgi. The apache error log is clean except for one mysterious error. Exception exceptions.TypeError: "'NoneType' object is not callable" in <bound method SharedSocket.__del__ of <httplib.SharedSocket instance at 0x82fb138c>> i...
Mysterious Apache Django WSGI Error
I'm running a django application on apache with mod_wsgi. The apache error log is clean except for one mysterious error. Exception exceptions.TypeError: "'NoneType' object is not callable" in <bound method SharedSocket.__del__ of <httplib.SharedSocket instance at 0x82fb138c>> ignored I understand that this means that...
[ "It is likely that this is coming about because while handling an exception a further exception is occurring within the destructor of an object being destroyed and that the latter exception is unable to be raised because of the state of the pending one. Within Python C API details of such can be written direct to e...
[ 1, 0 ]
[]
[]
[ "apache", "django", "python", "wsgi" ]
stackoverflow_0006525236_apache_django_python_wsgi.txt
Q: How to modify pythonpath for a WSGI application in alwaysdata.net I've created a small Python web application using Flask, and I wanted to host it in alwaysdata.net. I already installed mod_wsgi in my subdomain, but when I try to import the main module of my app it fails because it can't be found. All the files ar...
How to modify pythonpath for a WSGI application in alwaysdata.net
I've created a small Python web application using Flask, and I wanted to host it in alwaysdata.net. I already installed mod_wsgi in my subdomain, but when I try to import the main module of my app it fails because it can't be found. All the files are in the /www folder. Should I place my files somewhere else? I tried i...
[ "The current working directory under mod_wsgi will not be where the WSGI script is located, so you shouldn't be using os.getcwd(). See:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues#Application_Working_Directory\nTo do what you want, use:\nsys.path.append(os.path.dirname(__file__))\n\nThis is calculating...
[ 12 ]
[]
[]
[ "flask", "hosting", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0006525243_flask_hosting_mod_wsgi_python_wsgi.txt
Q: Python twisted game server monitoring I have few question about writing game server, I hope that someone have experience from practice, and will help me. I'm developing server for Flash game (MMO avatar game) using python and twisted. This is first time that I Use twisted and also first time that I write game ser...
Python twisted game server monitoring
I have few question about writing game server, I hope that someone have experience from practice, and will help me. I'm developing server for Flash game (MMO avatar game) using python and twisted. This is first time that I Use twisted and also first time that I write game server, and I have few question about server d...
[ "twisted.conch.manhole is one possibility for monitoring/administration. Ultimately you'll probably want a number of control interfaces for different purposes. Don't be afraid to setup a web server on another port, an IRC server on another, perhaps an SMTP client to email you statistics at the end of the day - this...
[ 3 ]
[]
[]
[ "monitoring", "python", "twisted" ]
stackoverflow_0006492128_monitoring_python_twisted.txt
Q: How does the {{ form }} tag work in Django-registration app I downloaded and installed django-registration app. I also downloaded a template that has this strange piece of code {{ form }} that magically creates 4 labels and 4 textboxes for the user to enter his registration information. How does it work? {% ext...
How does the {{ form }} tag work in Django-registration app
I downloaded and installed django-registration app. I also downloaded a template that has this strange piece of code {{ form }} that magically creates 4 labels and 4 textboxes for the user to enter his registration information. How does it work? {% extends "registration/registration_base.html" %} {% block title %}Re...
[ "It is part of django forms. See the documentation for more info.\nhttps://docs.djangoproject.com/en/1.3/topics/forms/\nIf you are really interested check out the source code.\nhttps://code.djangoproject.com/browser/django/trunk/django/forms\n", "A django form (but other objects, too) has a unicode method, which ...
[ 1, 0 ]
[]
[]
[ "django", "python", "registration" ]
stackoverflow_0006528581_django_python_registration.txt
Q: Django/Python apps and prerequisites for developer environment Currently my Django project has a huge readme doc, that any developer, whishing to work on the source, must follow to setup their development environment. It goes something like this: Prerequisites: Django Css. See Django CSS. CleverCSS. See Cle...
Django/Python apps and prerequisites for developer environment
Currently my Django project has a huge readme doc, that any developer, whishing to work on the source, must follow to setup their development environment. It goes something like this: Prerequisites: Django Css. See Django CSS. CleverCSS. See Clever CSS. Beautiful Soup. See Beautiful Soup. Dateutil. See python-da...
[ "Will pip not do the job?\nhttp://www.pip-installer.org/en/latest/index.html#\nYou can freeze all requirements on your server to a file (run this on the server):\npip freeze > REQUIREMENTS.txt\n\nand then on your dev environment:\npip install -r ./REQUIREMENTS.txt\n\nto install everything listed in the REQUIREMENTS...
[ 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006524803_django_python.txt
Q: WPF Binding Alternatives / Enhancements I love WPF bindings, but I often find myself wish I could do a little more. PyBindings seem like a good start, but the Python syntax seems very clunky and out of place in a XAML file. Are there any alternatives out there? Something with a simpler syntax, that allows for q...
WPF Binding Alternatives / Enhancements
I love WPF bindings, but I often find myself wish I could do a little more. PyBindings seem like a good start, but the Python syntax seems very clunky and out of place in a XAML file. Are there any alternatives out there? Something with a simpler syntax, that allows for quick comparisons & conversions so that I don'...
[ "http://www.thinkbottomup.com.au/site/blog/Embedding_DLR_Scripts_in_XAML_Part_1\nThis is page discusses various ways of bolting the DLR onto bindings and using them in interesting ways to do get all sorts of languages into your XAML.\n", "http://www.fikrimvar.net/lestirelim/?p=15\nIn this blog post, the author de...
[ 0, 0 ]
[]
[]
[ "binding", "pybinding", "python", "wpf" ]
stackoverflow_0003951896_binding_pybinding_python_wpf.txt
Q: Filtering textual data in Python I'm having a problem understanding what I'm doing wrong here. I have the code below (fairly straightforward). def compileWordList(textList, wordDict): '''Function to extract words from text lines exc. stops, and add associated line nums''' i = 0; for row in tex...
Filtering textual data in Python
I'm having a problem understanding what I'm doing wrong here. I have the code below (fairly straightforward). def compileWordList(textList, wordDict): '''Function to extract words from text lines exc. stops, and add associated line nums''' i = 0; for row in textList: i = i + 1 words...
[ "What about that?\nfrom collections import defaultdict\nimport re\n\nstop_words = set(['a', 'is', 'and', 'the', 'i'])\ntext = [ 'This is the first line in my text'\n , 'and this one is the second line in my text'\n , 'I like texts with three lines, so I added that one'\n ] \nword_line_dict = def...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0006528666_python.txt
Q: How to get UTC time given timezone? I am in the US and I want to get the UTC time (without the effect of Daylight Saving Time) for a piece of code: localtime = strftime("%m%d%y%H%M", gmtime()) Right now that code give me time in Greenwich, England. I know that I have a time offset of -8 (GMT -8). How can I get th...
How to get UTC time given timezone?
I am in the US and I want to get the UTC time (without the effect of Daylight Saving Time) for a piece of code: localtime = strftime("%m%d%y%H%M", gmtime()) Right now that code give me time in Greenwich, England. I know that I have a time offset of -8 (GMT -8). How can I get the UTC time to a specific timezone? (using...
[ "Try the datetime module:\ndatetime.datetime.utcnow() + datetime.timedelta(hours=-8)\n\nBTW, UTC doesn't have timezones, it's Universal Co-ordinated Time, it's the same everywhere.\n", "Just use the localtime() rather than gmtime() function: \nlocaltime = time.strftime(\"%m%d%y%H%M\", time.localtime())\n\nFrom...
[ 9, 3, 1 ]
[]
[]
[ "python", "time", "utc" ]
stackoverflow_0006528391_python_time_utc.txt
Q: Optimized searching in Python against a list Problem: Given a list of n objects (n's Order of magnitude is 10^5), search for a given item very fast with a minimum of spacetime tradeoff. Current, unoptimized & prototype-y solution takes too long and consumes too much RAM (the optimization is not premature, that is)...
Optimized searching in Python against a list
Problem: Given a list of n objects (n's Order of magnitude is 10^5), search for a given item very fast with a minimum of spacetime tradeoff. Current, unoptimized & prototype-y solution takes too long and consumes too much RAM (the optimization is not premature, that is). There is not a primary key to sort against in t...
[ "filter(test1, filter(test2, filter(test3, the_list)))\n\nFirstly, this is O(n) time, not O(n^3) time. The time adds not multiply. The only this could be worse then that is if test3/test2/test1 are doing something odd, in which we should look at those.\nIf we suggest that each test? function takes 10 ms, then we ha...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0006525314_optimization_python.txt
Q: What do I need to get my phone app to connect to a https database? I want to build an app that talks to a database. Analogy would be the youtube app for example. It connects to a secure host (requires login and password), and then returns to user results based on their query. What I need the app to do is: Get use...
What do I need to get my phone app to connect to a https database?
I want to build an app that talks to a database. Analogy would be the youtube app for example. It connects to a secure host (requires login and password), and then returns to user results based on their query. What I need the app to do is: Get user Login information (preferrably do it in a secure way and not store it ...
[ "You can use HttpPost and HttpGet requests to communicate with a server. HttpGet sends parameters in the url (ex: http://mysite.com/index.html?username=admin&password=cleartext). That is obviously not the preferred method for secure information. The HttpPost sends the data in a packet which is encrypted using https...
[ 1 ]
[]
[]
[ "android", "python", "sl4a" ]
stackoverflow_0006529164_android_python_sl4a.txt
Q: TypeError: can't multiply sequence by non-int of type 'float'? This error is referring to "sstax= grosspay*SS_TAX". I don't know what I'm doing wrong. ): After changing the global constants to integers I got another error that said 'TypeError: can only concatenate tuple (not "float") to tuple' referring to "netpay...
TypeError: can't multiply sequence by non-int of type 'float'?
This error is referring to "sstax= grosspay*SS_TAX". I don't know what I'm doing wrong. ): After changing the global constants to integers I got another error that said 'TypeError: can only concatenate tuple (not "float") to tuple' referring to "netpay=(grosspay)-(sstax+fedtax+statetax)". Here's my code: HOURS_IN_WEEK=...
[ "There error says that you can't multiply a sequence by anything that is not an integer.\nYou are returning a sequence in the getInfo() function:\nreturn grosspay,hrs,dependents\n\nThis is equivalent to:\nreturn [grosspay, hrs, dependents]\n\nIn Python, when you multiply a sequence by an integer, you duplicate the ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006529415_python.txt
Q: How to use tun/tap interface to split packets, tunnel and then reassemble. (similar to MLPPP) I am looking to create a client/server application that I can use to slit network packets in half, tunnel each half of the packet over a separate udp connection (because each udp connection will be going over a different ...
How to use tun/tap interface to split packets, tunnel and then reassemble. (similar to MLPPP)
I am looking to create a client/server application that I can use to slit network packets in half, tunnel each half of the packet over a separate udp connection (because each udp connection will be going over a different wifi link) and then reassemble the split packets on the other end. In addition to splitting the pac...
[ "We are doing something like this in production and it works quite well. We don't split individual packets though. We set fractional weights for each connection (unlimited) and send the packets out. We have some code in place to deal with different latencies on each line. On the other end we buffer them and reorder...
[ 4, 1 ]
[]
[]
[ "networking", "packet", "python", "tap" ]
stackoverflow_0006018185_networking_packet_python_tap.txt
Q: Arrays/dictionaries in python I was trying to create a method that does a loop and in the process it creates array with 2 levels. In PHP it would look like this for($a = 0; $a < 3; $a++) { $something[$a] = [1,2,3]; } But the problem is with python. I can't seem to add the key "u" to the variable and the array...
Arrays/dictionaries in python
I was trying to create a method that does a loop and in the process it creates array with 2 levels. In PHP it would look like this for($a = 0; $a < 3; $a++) { $something[$a] = [1,2,3]; } But the problem is with python. I can't seem to add the key "u" to the variable and the array under it in the same time. How wou...
[ "The best way to find information that you need is to use python tutorial. For example to answer your question yourself you can take a look at the following link: http://docs.python.org/tutorial/datastructures.html\nYou can use list comprehension:\nsomething = [[1,2,3] for u in xrange(3)]\n\nOR map:\nsomething = ma...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006530258_python.txt
Q: how to encode url in python I have created a function for decoding url. from urllib import unquote def unquote_u(source): result = source if '%u' in result: result = result.replace('%u','\\u').decode('unicode_escape') result = unquote(result) print result return result if __name__=='__main__': ...
how to encode url in python
I have created a function for decoding url. from urllib import unquote def unquote_u(source): result = source if '%u' in result: result = result.replace('%u','\\u').decode('unicode_escape') result = unquote(result) print result return result if __name__=='__main__': unquote_u('{%22%22%3A%22test_%E5%...
[ "urllib.unquote can do it:\n>>> urllib.unquote('{%22%22%3A%22test_%E5%93%A6%E4%BA%88%E4%BB%A5%E8%85%BF%E5%93%A6.doc.txt%22%2C%22mimeType%22%3A%22text%2Fplain%22%2C%22compressed%22%3AFalse%7D')\n'{\"\":\"test_\\xe5\\x93\\xa6\\xe4\\xba\\x88\\xe4\\xbb\\xa5\\xe8\\x85\\xbf\\xe5\\x93\\xa6.doc.txt\",\"mimeType\":\"text/pl...
[ 5, 1 ]
[]
[]
[ "python", "url" ]
stackoverflow_0006530380_python_url.txt
Q: Django debugging with Eclipse and PyDev I just managed to get debugging my django site 'kind of' working in Eclipse. All my breakpoints get caught just fine, but I have to restart the server every time I make a code change. I think this is because I'm using the --noreload argument when kicking off the server. Is t...
Django debugging with Eclipse and PyDev
I just managed to get debugging my django site 'kind of' working in Eclipse. All my breakpoints get caught just fine, but I have to restart the server every time I make a code change. I think this is because I'm using the --noreload argument when kicking off the server. Is there any way to setup Eclipse debugging so th...
[ "This is a bit late, but in case someone else comes looking for a solution to the same problem:\nThis video was very helpful when I was trying to setup Django Eclipse debugging with autoreload i.e. without using the --noreload switch. It pretty much walks you through the steps with a couple of helpful pointers. I'v...
[ 2, 0 ]
[]
[]
[ "django", "eclipse", "python" ]
stackoverflow_0003527934_django_eclipse_python.txt
Q: Python: How to print a word one letter at a time How do I use Python to print a word one letter at a time? Any help would be appreciated. A: If i understood you correctly than you can use the following code: for word in text.split(): print word else if you need to print word's letters: for let in word: ...
Python: How to print a word one letter at a time
How do I use Python to print a word one letter at a time? Any help would be appreciated.
[ "If i understood you correctly than you can use the following code:\nfor word in text.split():\n print word\n\nelse if you need to print word's letters:\nfor let in word:\n print let\n\nIn case you need to skip punctuation and so on you can also use regEx:\ntst = 'word1, word2 word3;'\n\nfrom re import findal...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006530552_python.txt
Q: Improving performance of raytracing hit function I have a simple raytracer in python. rendering an image 200x200 takes 4 minutes, which is definitely too much for my taste. I want to improve the situation. Some points: I shoot multiple rays per each pixel (to provide antialiasing) for a grand total of 16 rays per ...
Improving performance of raytracing hit function
I have a simple raytracer in python. rendering an image 200x200 takes 4 minutes, which is definitely too much for my taste. I want to improve the situation. Some points: I shoot multiple rays per each pixel (to provide antialiasing) for a grand total of 16 rays per pixel. 200x200x16 is a grand total of 640000 rays. Eac...
[ "Looking at your code, it looks like your main problem is that you have lines of code that are being called 2560000 times. That will tend to take a lot of time regardless what kind of work you are doing in that code. However, using numpy, you can aggregate alot of this work into a small number of numpy calls.\nTh...
[ 9, 7, 1, 1, 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0006528214_performance_python.txt
Q: Selecting the next formfield with Selenium RC and python I am running an automated test to test a webform for my company. They have just installed a zipcode service which automatically adds the Street and City/Region when you fill in the Address and housenumber. This autofill appears when you deselect the last for...
Selecting the next formfield with Selenium RC and python
I am running an automated test to test a webform for my company. They have just installed a zipcode service which automatically adds the Street and City/Region when you fill in the Address and housenumber. This autofill appears when you deselect the last form element (e.g. that of the housenumber). This is the order o...
[ "Hi i got a solution for this i think, \nproblem is with generating the user interactions to the addition field. \nuse these statements\nfocus(\"form:addition\");\nkeyPressNative(\"10\") //this is ENTER command \nit should work \n", "Yesterday I found out that the zipcode service uses an Ajax call to retrieve t...
[ 0, 0 ]
[]
[]
[ "autofill", "field", "forms", "python", "selenium_rc" ]
stackoverflow_0006504482_autofill_field_forms_python_selenium_rc.txt
Q: Python shared object module naming convention I have written a Python module in C++ and built it as a shared object library and it worked fine. But while figuring all that out, I noticed (via strace) that Python looks for a few different variations import is called. In particular, when I say import foo, Python s...
Python shared object module naming convention
I have written a Python module in C++ and built it as a shared object library and it worked fine. But while figuring all that out, I noticed (via strace) that Python looks for a few different variations import is called. In particular, when I say import foo, Python searches for, in order: foo (a directory) foo.so fo...
[ "This is actually platform-dependent, Python has different suffixes that it tries depending on the operating system. Here is the initialization of the suffix table in import.c:\n#ifdef HAVE_DYNAMIC_LOADING\n memcpy(filetab, _PyImport_DynLoadFiletab,\n countD * sizeof(struct filedescr));\n#endif\n me...
[ 20, 10 ]
[]
[]
[ "module", "naming_conventions", "python", "shared_libraries" ]
stackoverflow_0006319379_module_naming_conventions_python_shared_libraries.txt
Q: python reverse proxy spawning via cgi I need to write a cgi page which will act like a reverse proxy between the user and another page (mbean). The issue is that each mbean uses different port and I do not know ahead of time which port user will want to hit. Therefore want I need to do is following: A) Give user ...
python reverse proxy spawning via cgi
I need to write a cgi page which will act like a reverse proxy between the user and another page (mbean). The issue is that each mbean uses different port and I do not know ahead of time which port user will want to hit. Therefore want I need to do is following: A) Give user a page which will allow him to choose which...
[ "You don't need to spawn another process, that would complicate things a lot. Here's how I would do it based on something similar in my current project : \n\nCreate a WSGI application, which can live behind a web server.\nCreate a request handler (or \"view\") that is accessible from any URL mapping as long as the ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006488806_python.txt
Q: Brain going to explode. Need to search external file and return muliple results I'm not going to lie. I'm trying to do an assignment and I'm being beaten by it. I need to have python prompt the user to enter a room number, then lookup that room number in a supplied .txt file which has csv [comma-separated values],...
Brain going to explode. Need to search external file and return muliple results
I'm not going to lie. I'm trying to do an assignment and I'm being beaten by it. I need to have python prompt the user to enter a room number, then lookup that room number in a supplied .txt file which has csv [comma-separated values], and then show multiple results if there are any. I was able to get python to return ...
[ "Your code does \"return(s)\" the first time the \"id2find\" argument is exactly equal to the room. \nIf you want multiple matches, you could create an empty list before entering the loop, append every match to the list WITHOUT returning, return the list, and then use a for-loop to print out each match.\n", "Firs...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006531725_python.txt
Q: What is the recommended way to generate and copy some files to arbitrary places in a setup.py? I have a PyQT KDE application and I need to generate some files(with pyuic and pyrcc commands) and copy some files(.desktop) to some places(ie /usr/share/applications/kde4/). What are preferred ways to do this? Is using ...
What is the recommended way to generate and copy some files to arbitrary places in a setup.py?
I have a PyQT KDE application and I need to generate some files(with pyuic and pyrcc commands) and copy some files(.desktop) to some places(ie /usr/share/applications/kde4/). What are preferred ways to do this? Is using shutil.copy() and os.command() (or subprocess.Popen()) good way to copy operations and commands? Or ...
[ "Judging from this question shutil is the way to go for copying files/directories (copyfile/copytree/...)\nAs for installing extra files with distutils, see the data_files and package_data options.\n" ]
[ 1 ]
[]
[]
[ "distribute", "distutils", "python", "setup.py" ]
stackoverflow_0006484223_distribute_distutils_python_setup.py.txt
Q: wxPython ListCtrl Help I'm using a ListCtrl and it is populated with items on the fly, when an item is "Activated"(Double Click/Enter) it calls a function. def onClick(self, event): How do I find out which item was clicked in the List since they don't have pre-set IDs? Is the String passed to the function as ...
wxPython ListCtrl Help
I'm using a ListCtrl and it is populated with items on the fly, when an item is "Activated"(Double Click/Enter) it calls a function. def onClick(self, event): How do I find out which item was clicked in the List since they don't have pre-set IDs? Is the String passed to the function as part of self or event? Thank...
[ "Try event.GetText() or event.GetItem().<manipulate your item here>; here is wx.ListEvent documentation.\n", "Since you are probably binding the ListCtrl with the event, the ListCtrl item gets passed inside the event;\nlist = event.GetEventObject()\nselected_string = list.GetStringSelection()\n\nSo now you have a...
[ 4, 0 ]
[]
[]
[ "listctrl", "python", "wxpython" ]
stackoverflow_0006531207_listctrl_python_wxpython.txt
Q: Python BeautifulSoup with Optional Tags Let me set up an example: from BeautifulSoup import BeautifulStoneSoup root = ''' <all2> <images> <image> <name> Picture </name> <url> www.thing.com</url> ...
Python BeautifulSoup with Optional Tags
Let me set up an example: from BeautifulSoup import BeautifulStoneSoup root = ''' <all2> <images> <image> <name> Picture </name> <url> www.thing.com</url> </image> ...
[ "What do you want with 'nameTag'??? \nThe BeautifulSoup documentation clearly tells you to use\n iname = img.name.renderContents()\n iurl = img.url.renderContents()\n\nZero reason to invent new syntax or semantics here\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "xml" ]
stackoverflow_0006531812_beautifulsoup_python_xml.txt
Q: Uniq id function in python or not? I have several python scripts run parallel this simple code: test_id = id('test') Is test_id unique or not? A: http://docs.python.org/library/functions.html#id Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and consta...
Uniq id function in python or not?
I have several python scripts run parallel this simple code: test_id = id('test') Is test_id unique or not?
[ "http://docs.python.org/library/functions.html#id\n\nReturn the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.\nCPython implementation detail: Th...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006531662_python.txt
Q: Google App Engine post request query string I'm building my first GAE app. After watching a tutorial video on youtube, (this one) I noticed that when a post request is made, say from a form, yo don't see the querystring in the URL (my desired behavior). The surprise arises when I perform a post request from a form...
Google App Engine post request query string
I'm building my first GAE app. After watching a tutorial video on youtube, (this one) I noticed that when a post request is made, say from a form, yo don't see the querystring in the URL (my desired behavior). The surprise arises when I perform a post request from a form, conceptually the same one that's on the video, ...
[ "I think you talk about the HTTP methods like POST or GET,\ncheck the attribute \"method\" in your form definition, you need to put it to \"POST\" like\n<form action=\"\" method=\"POST\">\n...\n</form>\n\nYou can see more informations: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006531874_google_app_engine_python.txt
Q: How are lambda expressions bound to a class? If I set up a class like below in Python, as I expect the lambda expressions created should be bound to the class A. I don't understand why when I put a lambda inside a list like in g it isn't bound. class A(object): f = lambda x,y: (x + y) g = [lambda x,y: (x + y)]...
How are lambda expressions bound to a class?
If I set up a class like below in Python, as I expect the lambda expressions created should be bound to the class A. I don't understand why when I put a lambda inside a list like in g it isn't bound. class A(object): f = lambda x,y: (x + y) g = [lambda x,y: (x + y)] a = A() #a.f bound print a.f <bound method A.<...
[ "f is bound because it's a part of the class as per the definition. g is not a method. g is a list. The first element of this list incidentally happens to be a lambda expression. That's got nothing to do with whether g is defined inside a class definition or not. \n", "If you want g[0] to be a bound method too, d...
[ 15, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006530110_python.txt
Q: Separate number/letter tokens in Python I'm using re.split() to separate a string into tokens. Currently the pattern I'm using as the argument is [^\dA-Za-z], which retrieves alphanumeric tokens from the string. However, what I need is to also split tokens that have both numbers and letters into tokens with only ...
Separate number/letter tokens in Python
I'm using re.split() to separate a string into tokens. Currently the pattern I'm using as the argument is [^\dA-Za-z], which retrieves alphanumeric tokens from the string. However, what I need is to also split tokens that have both numbers and letters into tokens with only one or the other, eg. re.split(pattern, "my t...
[ "Try the findall method instead.\n>>> print re.findall ('[^\\d ]+', \"my t0kens\");\n['my', 't', 'kens']\n>>> print re.findall ('[\\d]+', \"my t0kens\");\n['0']\n>>>\n\nEdit: Better way from Bart's comment below.\n>>> print re.findall('[a-zA-Z]+|\\\\d+', \"my t0kens\")\n['my', 't', '0', 'kens']\n>>>\n\n", ">>> [x...
[ 7, 2, 1, 0 ]
[]
[]
[ "python", "regex", "split" ]
stackoverflow_0006532065_python_regex_split.txt
Q: Search keyword in document in python I am trying to write a python script so that it can search for a keyword in a document, and retrieve the entire sentence where the keyword is. From my research i saw that acora can be used but i still found it unsuccessful. A: >>> text = """Hello, this is the first sentence....
Search keyword in document in python
I am trying to write a python script so that it can search for a keyword in a document, and retrieve the entire sentence where the keyword is. From my research i saw that acora can be used but i still found it unsuccessful.
[ ">>> text = \"\"\"Hello, this is the first sentence. This is the second. \nAnd this may or may not be the third. Am I right? No? lol...\"\"\"\n\n>>> import re\n>>> s = re.split(r'[.?!:]+', text)\n>>> def search(word, sentences):\n return [i for i in sentences if re.search(r'\\b%s\\b' % word, i)]\n\n>>> search...
[ 3, 0, 0, 0 ]
[]
[]
[ "keyword", "python" ]
stackoverflow_0006530731_keyword_python.txt
Q: Can we run multiprocessing Pool in GAE? Is it possible to run multiprocessing Pool in gae? If yes, how come my code runs fine in my local machine but pops out the following err msg with django remote api: File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/multiprocessing/pool.py", line 14...
Can we run multiprocessing Pool in GAE?
Is it possible to run multiprocessing Pool in gae? If yes, how come my code runs fine in my local machine but pops out the following err msg with django remote api: File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, ite...
[ "You won't be able to run multiprocessing on the production servers, but if you are using the remote_api, then you can run your script locally (with multiprocessing) and have each Pool process use communicate with the production server via remote_api calls.\nIf you need multiprocess style actions actually in server...
[ 2 ]
[]
[]
[ "django", "google_app_engine", "multiprocessing", "python" ]
stackoverflow_0006531388_django_google_app_engine_multiprocessing_python.txt
Q: regex to catch any http address I'm trying hard to write a regex that should catch any http address. (background: I'd like to use it in a tkinter window, a simple editor, to transform an http address into a clickable link) Due to how complicated they can be, which is the better regex? alessandro A: Considering t...
regex to catch any http address
I'm trying hard to write a regex that should catch any http address. (background: I'd like to use it in a tkinter window, a simple editor, to transform an http address into a clickable link) Due to how complicated they can be, which is the better regex? alessandro
[ "Considering the possibilities that came with Punycode, I'd say this is almost impossible to do with a RegEx.\nOf course you could restrict your view to ASCII URLs.\nYou should take a look at the Regular Expression Library.\n", "Using A regex that validates a web address and matches an empty string? as a basis fo...
[ 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006532089_python_regex.txt
Q: Parallel programming with coroutines in Python Coroutines are a great paradigm to ease concurrent programming. And most of the time, concurrent tasks are easily parallelizable. In Go language, it is easy to use goroutines to perform parallel tasks. Is there a way to do the same thing in Python, e.g. to use corouti...
Parallel programming with coroutines in Python
Coroutines are a great paradigm to ease concurrent programming. And most of the time, concurrent tasks are easily parallelizable. In Go language, it is easy to use goroutines to perform parallel tasks. Is there a way to do the same thing in Python, e.g. to use coroutines to create processes and to synchronize them?
[ "Yes, Python has support for coroutines in libraries and via generators: see the Greenlet library, for example. Also, there is a derivative named Stackless Python that has built-in support for several concurrent programming features, such as microthreads and channels.\nNote that in default CPython, the Global Inter...
[ 3, 2 ]
[]
[]
[ "concurrency", "coroutine", "parallel_processing", "python" ]
stackoverflow_0006528789_concurrency_coroutine_parallel_processing_python.txt
Q: Trying to run gevent socketio example (Django) I have encountered the following error: (virtenv3)iMac:codysoyland-django-socketio-example-d35672f admin$ python run_example.py Traceback (most recent call last): File "run_example.py", line 12, in <module> from socketio import SocketIOServer File "build/bdis...
Trying to run gevent socketio example (Django)
I have encountered the following error: (virtenv3)iMac:codysoyland-django-socketio-example-d35672f admin$ python run_example.py Traceback (most recent call last): File "run_example.py", line 12, in <module> from socketio import SocketIOServer File "build/bdist.macosx-10.6-universal/egg/socketio/__init__.py", l...
[ "Did you compile libevent with llvm? I think the homebrew formula (before it switched to libevent2) had a \"don't compile with llvm\" directive because of this error. \n" ]
[ 0 ]
[]
[]
[ "django", "gevent", "python", "sockets" ]
stackoverflow_0006518542_django_gevent_python_sockets.txt
Q: python: serve a file as it is being downloaded with urllib, BaseHTTPSserver I am making a RPM file cache server. A PC on the network accesses the cache server. If the file is present on the server, it is served. If not, it is downloaded from the internet before being served. I wrote this with BaseHTTPServer with u...
python: serve a file as it is being downloaded with urllib, BaseHTTPSserver
I am making a RPM file cache server. A PC on the network accesses the cache server. If the file is present on the server, it is served. If not, it is downloaded from the internet before being served. I wrote this with BaseHTTPServer with urllib to fetch the files. Now with small files, there is little delay between dow...
[ "A read-write loop.\nx= download_buffer.read(1024)\nwhile x:\n self.wfile.write(x)\n x= download_buffer.read(1024)\n\n" ]
[ 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0006532950_python_urllib2.txt
Q: How to scale gevent-socketio server? I'm planning to build a realtime service with gevent-socketio (released by Jeffrey Gelens). For some purposes, I need to scale my service with many gevent-socketio servers. I think it can be used as a reverse proxy (like nginx) for distributing requests across multiple Comet se...
How to scale gevent-socketio server?
I'm planning to build a realtime service with gevent-socketio (released by Jeffrey Gelens). For some purposes, I need to scale my service with many gevent-socketio servers. I think it can be used as a reverse proxy (like nginx) for distributing requests across multiple Comet servers and use another server as a central ...
[ "I think haproxy is most appropriate for proxying in this manner. You're on the right track with your approach. \n" ]
[ 1 ]
[]
[]
[ "comet", "gevent", "python", "real_time", "socket.io" ]
stackoverflow_0006282053_comet_gevent_python_real_time_socket.io.txt
Q: How to specify the SDK version used when installing a Python package on Mac OS X? I'm trying to install python-ldap on Mac OS X 10.6, but I get this error because it's using 10.4u.sdk instead of 10.6.sdk. How can I specify the SDK version to be used? So far, I tried specifying the MACOSX_DEPLOYMENT_TARGET env vari...
How to specify the SDK version used when installing a Python package on Mac OS X?
I'm trying to install python-ldap on Mac OS X 10.6, but I get this error because it's using 10.4u.sdk instead of 10.6.sdk. How can I specify the SDK version to be used? So far, I tried specifying the MACOSX_DEPLOYMENT_TARGET env variable to 10.6 and SDKROOT to /Developer/SDKs/MacOSX10.6.sdk, but 10.4u.sdk was stil used...
[ "When installing Python packages with C extension modules on Mac OS X, Python will automatically use the SDK and deployment target with which the interpreter was built. Presumably you are using a 32-bit-only Python, perhaps from one of the python.org installers. These Pythons are built using the 10.4u SDK for com...
[ 2 ]
[]
[]
[ "ldap", "macos", "python" ]
stackoverflow_0006533502_ldap_macos_python.txt
Q: How to log in to twitter without Oauth for a script? To use OAUTH with python-twitter I need to register a web app, website etc. The program I have is for personal use though. Since basic auth is now defunct and Oauth is not an option due to the requirements is there a work around to log in to twitter using a scri...
How to log in to twitter without Oauth for a script?
To use OAUTH with python-twitter I need to register a web app, website etc. The program I have is for personal use though. Since basic auth is now defunct and Oauth is not an option due to the requirements is there a work around to log in to twitter using a script? I can't imagine that Twitter would alienate everyone w...
[ "If you register your Twitter app as a \"Client\" app instead of a \"Browser\" (aka web) app, you can create an application without the need for a live web app. (Note: you'll still have to store an OAuth key.)\nHere is a down-and-dirty resource for how it all works and how to accomplish this.\nEdit: maybe somethin...
[ 1, 0 ]
[]
[]
[ "authentication", "oauth", "python", "twitter" ]
stackoverflow_0006511633_authentication_oauth_python_twitter.txt
Q: Installing Arial on Ubuntu and using in Python Ok, I'm trying to install Arial on Ubuntu and then produce a graph using Python, in which I want the text to display in Arial. I'm not sure if the error is with how I have installed Arial, or how I am trying to access it through the Python script, which I've been doin...
Installing Arial on Ubuntu and using in Python
Ok, I'm trying to install Arial on Ubuntu and then produce a graph using Python, in which I want the text to display in Arial. I'm not sure if the error is with how I have installed Arial, or how I am trying to access it through the Python script, which I've been doing with pylab.rcParams['font.sans-serif'] = 'Arial' T...
[ "Here is a way of installing Arial on an ubuntu machine : http://embraceubuntu.com/2005/09/09/installing-microsoft-fonts/\nHope it helps,\n" ]
[ 1 ]
[]
[]
[ "fonts", "graph", "matplotlib", "python", "ubuntu" ]
stackoverflow_0006533919_fonts_graph_matplotlib_python_ubuntu.txt
Q: opencv and python in osx - but how? I tried to install opencv and python with port and brew. but when i try import cv it says "module not found". i have the same problem on my windows machine and just no solution works. is there a simple step by step solution for someone who does not know all the terminal codes? i...
opencv and python in osx - but how?
I tried to install opencv and python with port and brew. but when i try import cv it says "module not found". i have the same problem on my windows machine and just no solution works. is there a simple step by step solution for someone who does not know all the terminal codes? im not really a good programmer but it wou...
[ "When using brew, try brew info opencv, which explicitly tells you:\n\nThe OpenCV Python module will not work until you edit your PYTHONPATH like so:\n export PYTHONPATH=\"/usr/local/lib/python2.6/site-packages/:$PYTHONPATH\"\n\nThe export thing should go into your shell config. You could put this into ~/.bashrc, ...
[ 4, 0 ]
[]
[]
[ "computer_vision", "import", "macos", "opencv", "python" ]
stackoverflow_0006534081_computer_vision_import_macos_opencv_python.txt
Q: Python, sigaction(2) available? Is there an equivalent to the POSIX sigaction available through Python? I realize python has traditional support for signals, but I need sigaction. I'm trying to identify the pid of a process that is the source of a signal being issued. From what I can see from the documentation, th...
Python, sigaction(2) available?
Is there an equivalent to the POSIX sigaction available through Python? I realize python has traditional support for signals, but I need sigaction. I'm trying to identify the pid of a process that is the source of a signal being issued. From what I can see from the documentation, there isn't a way to do this. I'm only ...
[ "There is a standard module called, unsurprisingly, signal. This seems to carry out the functionality of sigaction(2). However I'm guessing that what you really need is the siginfo_t struct, which gives the PID of the source of the signal, which is not part of the module at the moment (possibly because it is not ...
[ 7 ]
[]
[]
[ "linux", "posix", "python", "signals" ]
stackoverflow_0006532213_linux_posix_python_signals.txt
Q: Semantics of args passed to python threading.Thread __init__ What are the semantics of data passed to threading.Thread.__init__()? Are they copied over and made local to the thread? Or, do they continue to be shared with the creating thread? The docs say that args is a tuple, so I assume it will be deep copied, bu...
Semantics of args passed to python threading.Thread __init__
What are the semantics of data passed to threading.Thread.__init__()? Are they copied over and made local to the thread? Or, do they continue to be shared with the creating thread? The docs say that args is a tuple, so I assume it will be deep copied, but would like to make sure. Basically, I'd like to dump a buffer pe...
[ "Data are generally shared in Python unless you explicitly copy. Dumping a buffer from one thread while modifying it in another is not a safe operation unless the buffer itself has a thread-safe design. You need to synchronise access to the buffer somehow.\n", "\nCan I continue to modifying the buffer in the call...
[ 3, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006534117_multithreading_python.txt
Q: A custom file class. Is this feasible? Currently I'm reading and writing binary files and am calling the struct pack/unpack functions frequently. Rather than constantly having to write something like struct.unpack("3f", myFile.read(12)) I decided to write a function to save myself some typing, so the equivalent of...
A custom file class. Is this feasible?
Currently I'm reading and writing binary files and am calling the struct pack/unpack functions frequently. Rather than constantly having to write something like struct.unpack("3f", myFile.read(12)) I decided to write a function to save myself some typing, so the equivalent of the above statement in my code is my_unpack...
[ "Don't subclass. Instead, compose:\nclass StructReader(object):\n def __init__(self, input_file):\n self.input_file = input_file\n\n def get_float(self, n):\n fmt = ...\n return struct.unpack(fmt, self.input_file.read(struct.calcsize(fmt)))\n\n ...\n\nWhen you subclass, you have to wo...
[ 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006535184_python.txt