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:
How can I embed an MP3 on my Google App Engine website?
I have a system that accepts MP3 uploads to the BlobStore, and now I would like to embed them in an HTML5 player. The trouble is: I can't seem to get a link directly to the MP3 file. I've used images.get_serving_url(blob_key) to great effect, but there does... | How can I embed an MP3 on my Google App Engine website? | I have a system that accepts MP3 uploads to the BlobStore, and now I would like to embed them in an HTML5 player. The trouble is: I can't seem to get a link directly to the MP3 file. I've used images.get_serving_url(blob_key) to great effect, but there doesn't seem to be an equivalent for audio files.
The documentati... | [
"\nMake sure that the mp3 are accessible to everyone.\nBecause of licensing issues mp3 is not available on Firefox audio tag, you will need to store your files as ogg in order for them to work on Firefox.\n\n"
] | [
0
] | [] | [] | [
"audio_streaming",
"google_app_engine",
"python"
] | stackoverflow_0007826604_audio_streaming_google_app_engine_python.txt |
Q:
PyQt show one widget by clicking button on another
I'm new in PyQt and using PyQt4. Have two independent widgets. First of them showFullScreen() and second show(). I want after hiding second by hide() show it by clicking button on first. Tried something and googled - nothing.
Full code:
from PyQt4 import QtCore, Q... | PyQt show one widget by clicking button on another | I'm new in PyQt and using PyQt4. Have two independent widgets. First of them showFullScreen() and second show(). I want after hiding second by hide() show it by clicking button on first. Tried something and googled - nothing.
Full code:
from PyQt4 import QtCore, QtGui
class FileExplorer(QtGui.QWidget):
def __init... | [
"It sounds like what you want is a modeless dialog.\nIn the code you posted, change the FileExplor class to a QDialog:\nclass FileExplor(QtGui.QDialog):\n\nThen add a signal handler to the main FileExplorer class:\ndef handleShowDialog(self):\n if not hasattr(self, 'dialog'):\n self.dialog = FileExplor(se... | [
2,
0
] | [] | [] | [
"pyqt",
"python",
"qwidget"
] | stackoverflow_0007839600_pyqt_python_qwidget.txt |
Q:
Mysql connection pooling question: is it worth it?
I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using a library that provides connection pooling (SQLAlchemy) won't actually help you that much if you enable the connection pool.
Does... | Mysql connection pooling question: is it worth it? | I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using a library that provides connection pooling (SQLAlchemy) won't actually help you that much if you enable the connection pool.
Does anyone have any experience with this?
I'm leery of enab... | [
"There's no need to worry about residual state on a connection when using SQLA's connection pool, unless your application is changing connectionwide options like transaction isolation levels (which generally is not the case). SQLA's connection pool issues a connection.rollback() on the connection when its checked ... | [
10,
6,
2,
0,
0
] | [] | [] | [
"connection_pooling",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0000405352_connection_pooling_mysql_python_sqlalchemy.txt |
Q:
Extracting Information from a Tuple (Python)
I'm currently using the httplib library in Python 2.7 to obtain some headers from a website to establish a) the filesize of a download and b) the last modified date of the file. I've used some online tools and these details do exist.
I'm currently scripting my Python co... | Extracting Information from a Tuple (Python) | I'm currently using the httplib library in Python 2.7 to obtain some headers from a website to establish a) the filesize of a download and b) the last modified date of the file. I've used some online tools and these details do exist.
I'm currently scripting my Python code and it appears to work correctly bringing back ... | [
"First, you can make it a little easier to work with by turning your list of tuples into a dictionary:\n>>> headers = [('content-length', '2501479'),\n... ('accept-ranges', 'bytes'),\n... ('vary', 'Accept-Encoding'),\n... ('server', 'off'),\n... ('last-modified', 'Thu, 20 Oct 2011 04:30:01 GMT'),\n... ('etag',... | [
7,
4,
2,
0,
0
] | [] | [] | [
"http_headers",
"list",
"parsing",
"python",
"tuples"
] | stackoverflow_0007839168_http_headers_list_parsing_python_tuples.txt |
Q:
wxPython Frame with wx.CAPTION style, an upper left Icon and a closebox?
Needed is a fixed size frame with a title bar having only an icon, the title, and a close box. No minimize nor maximize box.
Can it be done?
A:
See http://docs.wxwidgets.org/stable/wx_wxframe.html#wxframe for the various styles available (s... | wxPython Frame with wx.CAPTION style, an upper left Icon and a closebox? | Needed is a fixed size frame with a title bar having only an icon, the title, and a close box. No minimize nor maximize box.
Can it be done?
| [
"See http://docs.wxwidgets.org/stable/wx_wxframe.html#wxframe for the various styles available (sorry it's the wxwidgets ref...I couldn't find the wxPython version for some reason). You'd want to pass something like this to the frame's style parameter:\nstyle = wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.CLIP_CHILDREN\n\nI'... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007840238_python_wxpython.txt |
Q:
Python Inheritance : Return subclass
I have a function in a superclass that returns a new version of itself. I have a subclass of this super that inherits the particular function, but would rather it return a new version of the subclass. How do I code it so that when the function call is from the parent, it return... | Python Inheritance : Return subclass | I have a function in a superclass that returns a new version of itself. I have a subclass of this super that inherits the particular function, but would rather it return a new version of the subclass. How do I code it so that when the function call is from the parent, it returns a version of the parent, but when it is ... | [
"If new does not depend on self, use a classmethod:\nclass Parent(object):\n @classmethod\n def new(cls,*args,**kwargs):\n return cls(*args,**kwargs)\nclass Child(Parent): pass\n\np=Parent()\np2=p.new()\nassert isinstance(p2,Parent)\nc=Child()\nc2=c.new()\nassert isinstance(c2,Child)\n\nOr, if new does... | [
10
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0007840911_inheritance_python.txt |
Q:
Custom QDialog stealing fullscreen application focus and showing the taskbar
I was wondering how I can make a custom QDialog message box with my own buttons, similar to the code below.
So far I have this code, which works pretty well. The problem with this code is that it launches from a full screen application, a... | Custom QDialog stealing fullscreen application focus and showing the taskbar | I was wondering how I can make a custom QDialog message box with my own buttons, similar to the code below.
So far I have this code, which works pretty well. The problem with this code is that it launches from a full screen application, and it steals the focus of it (the main taskbar on the top appears along with the Q... | [
"I think the issue you're having is that you aren't giving your msgBox a parent. This makes Qt treat it as a top-level window. Try changing your instantiation of your message box to look like this:\nmsgBox = QMessageBox(self)\n\n"
] | [
1
] | [] | [] | [
"pyqt",
"python",
"qdialog",
"qt"
] | stackoverflow_0007840825_pyqt_python_qdialog_qt.txt |
Q:
Using Pylab to create a plot of a line and then getting the rasterized data from the line
I am trying to get the rasterized line data from a pylab plot function. My code is like so:
fitfunc = lambda p, x: p[0] + p[1] * sin(2 * pi * x / data[head[0]].size + p[2])
errfunc = lambda p, x, y: fitfunc(p, x) - y
data = ... | Using Pylab to create a plot of a line and then getting the rasterized data from the line | I am trying to get the rasterized line data from a pylab plot function. My code is like so:
fitfunc = lambda p, x: p[0] + p[1] * sin(2 * pi * x / data[head[0]].size + p[2])
errfunc = lambda p, x, y: fitfunc(p, x) - y
data = np.genfromtxt(dataFileName, dtype=None, delimiter='\t', names=True)
xAxisSeries =linspace(0., ... | [
"import numpy as np\nimport matplotlib.pyplot as plt\nN=4\nx=np.linspace(0, 10, N)\ny=np.cumsum(np.random.random(N) - 0.5)\nline=plt.plot(x,y)[0]\npath=line._path\n\nThese are the original (x,y) data points:\nprint(path.vertices)\n# [[ 0. 0.08426592]\n# [ 3.33333333 0.14204252]\n# [ 6.66666667 0.... | [
2
] | [] | [] | [
"matlab",
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0007841017_matlab_matplotlib_numpy_python_scipy.txt |
Q:
Google maps API help or List indices output
I have an excel sheet with a bunch of info regarding the stops a
delivery truck makes throughout the day. I can successfully extract
the information I need with xlrd. This is the code I am using:
book = xlrd.open_workbook(r'c:\xytest.xls')
sheet= book.sheet_by_inde... | Google maps API help or List indices output | I have an excel sheet with a bunch of info regarding the stops a
delivery truck makes throughout the day. I can successfully extract
the information I need with xlrd. This is the code I am using:
book = xlrd.open_workbook(r'c:\xytest.xls')
sheet= book.sheet_by_index(0)
odList = []
for i in range(1,6125):
cI... | [
"Try using an tuple (var1, var2) or (var,) instead of a list [var1, var2], or convert the lists to tuples before sending printing tuple([var]).\n",
"Instead of this:\nxyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long and lat \nxyCoord.reverse() #reversed, so that lat,long is in correct format \nod... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007840975_python.txt |
Q:
Monitor outgoing internet request in Python
What are some useful methods or libraries that can be used to track IP request from a personal computer. Ideally I would like the option to block or pause a specific outgoing request before/after some checks are carried out. I've seen Twisted, but I'm not sure if its exa... | Monitor outgoing internet request in Python | What are some useful methods or libraries that can be used to track IP request from a personal computer. Ideally I would like the option to block or pause a specific outgoing request before/after some checks are carried out. I've seen Twisted, but I'm not sure if its exactly what I'm looking for just yet, or if there e... | [
"Twisted will make it easy to get up and running right away while making it possible for you to intercept, delay, or block requests: http://twistedmatrix.com/documents/current/api/twisted.web.proxy.Proxy.html\n"
] | [
3
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0007841463_linux_python.txt |
Q:
What is Celery Application ( celery.app.App )?
Can somebody please explain me what is celery Application object, noted here and what purposes it should be used for?
A:
Read this document:
http://docs.celeryproject.org/en/latest/internals/app-overview.html
The App is an instance of the Celery library, you can sub... | What is Celery Application ( celery.app.App )? | Can somebody please explain me what is celery Application object, noted here and what purposes it should be used for?
| [
"Read this document:\nhttp://docs.celeryproject.org/en/latest/internals/app-overview.html\nThe App is an instance of the Celery library, you can subclass app to override almost any part and corner of how Celery behaves.\n"
] | [
4
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0007838356_celery_python.txt |
Q:
how to synchronize data between two connects
I'm using a python tool called "Ajaxterm"(http://wiki.kartbuilding.net/index.php/Ajaxterm). After setting it up. The problem , I face is,when type few chars - they appear as jumbled character.For example,When i type "abcde" it may come as "cdbea" - but no character mis... | how to synchronize data between two connects | I'm using a python tool called "Ajaxterm"(http://wiki.kartbuilding.net/index.php/Ajaxterm). After setting it up. The problem , I face is,when type few chars - they appear as jumbled character.For example,When i type "abcde" it may come as "cdbea" - but no character missing. From my understanding - I tried to debug t... | [
"Thanks Prusse,It works now - I have increased time limit from 1 to 200 on function queue(s) \n"
] | [
0
] | [] | [] | [
"ajax",
"javascript",
"python"
] | stackoverflow_0007838401_ajax_javascript_python.txt |
Q:
Daemonising python project, that uses Twisted
If we use PEP-3143 and it's reference implementation http://pypi.python.org/pypi/python-daemon
then it looks like impossible to have Twisted working, since during daemonising ALL possible file handlers are explicitly closed, which includes pipes.
When Twisted tries to ... | Daemonising python project, that uses Twisted | If we use PEP-3143 and it's reference implementation http://pypi.python.org/pypi/python-daemon
then it looks like impossible to have Twisted working, since during daemonising ALL possible file handlers are explicitly closed, which includes pipes.
When Twisted tries to call os.pipe() and then write to it - gets bad file... | [
"It doesn't close all the open file descriptors: just the ones not in the files_preserve attribute. You could probably coerce this to work by figuring out the FD of the waker and all open sockets in the reactor and then passing that to files_preserve... but why bother? Just use twistd and have twisted daemonize it... | [
2,
1,
1,
0
] | [] | [] | [
"daemon",
"python",
"twisted"
] | stackoverflow_0007833038_daemon_python_twisted.txt |
Q:
Django Admin filter on Foreign Key property
I want to add a filter in an admin changelist by a property of a foreign key, e.g.
class Address(model.Models):
street = models.CharField(max_length=25)
city = models.CharField(max_length=25)
country = models.CharField(max_length=25)
class Cu... | Django Admin filter on Foreign Key property | I want to add a filter in an admin changelist by a property of a foreign key, e.g.
class Address(model.Models):
street = models.CharField(max_length=25)
city = models.CharField(max_length=25)
country = models.CharField(max_length=25)
class Customer(models.Model):
name = models.CharField... | [
"See https://code.djangoproject.com/ticket/3400 . It works ok in django 1.3 :)\nclass Room(models.Model):\n house = models.ForeignKey(House)\n\n def __unicode__(self):\n return self.house.town.name\n\nclass Booking(models.Model):\n room = models.ForeignKey(Room)\n\n def __unicode__(self):\n ... | [
27,
1,
0
] | [] | [] | [
"admin",
"django",
"filter",
"python"
] | stackoverflow_0002379702_admin_django_filter_python.txt |
Q:
Workaround for Pythonbrew failing because test_socket can't resolve?
I'm using pythonbrew to install Python 2.6.6 on Snow Leopard. It failed with a readline error, then a socket error. I installed readline from source, which made the installer happy on the next attempt, but the socket error remains:
test_socket
t... | Workaround for Pythonbrew failing because test_socket can't resolve? | I'm using pythonbrew to install Python 2.6.6 on Snow Leopard. It failed with a readline error, then a socket error. I installed readline from source, which made the installer happy on the next attempt, but the socket error remains:
test_socket
test test_socket failed -- Traceback (most recent call last):
File "/User... | [
"I'm having the exact same issue on OSX 10.7 standard Perl and Macports Perl.\nIt seems that socket.gethostname() is working, but on my Mac at least, running the reply to that, which is identical to running hostname in the terminal, does not work.\nIf I do:\nlocal_ip = socket.gethostbyname(local_ip+\".local\")\n\nI... | [
2,
0
] | [] | [] | [
"installation",
"macos",
"osx_snow_leopard",
"python"
] | stackoverflow_0004090753_installation_macos_osx_snow_leopard_python.txt |
Q:
Are there functions/commands available that will help multiple scripts execute to a certain point and proceed?
I am looking for a mechanism to sync between scripts (bash or perl or Python) My requirement is as follows
Scripts a, b and c will start (not necessarily at the same time). Once a, b, or c hits a certain... | Are there functions/commands available that will help multiple scripts execute to a certain point and proceed? | I am looking for a mechanism to sync between scripts (bash or perl or Python) My requirement is as follows
Scripts a, b and c will start (not necessarily at the same time). Once a, b, or c hits a certain point in the script, it should stop for other scripts to hit the same point. For the sake of discussion lets call ... | [
"This isn't simple. But the good news is that it's very well understood.\nStart here: http://en.wikipedia.org/wiki/Job_scheduler\nThen read this: http://en.wikipedia.org/wiki/List_of_job_scheduler_software\nYou probably want something like http://en.wikipedia.org/wiki/Simple_Linux_Utility_for_Resource_Management\n... | [
1,
1
] | [] | [] | [
"bash",
"perl",
"python",
"sync"
] | stackoverflow_0007840858_bash_perl_python_sync.txt |
Q:
I suspect that re.match messing up control flow
Is there any way that regular expression match inside a if block would interfere with the code inside an else block?
In the following code, I have 100 test strings that are being inputed as job_name that should be appended to my del_job_ids array. Only 99 of them are... | I suspect that re.match messing up control flow | Is there any way that regular expression match inside a if block would interfere with the code inside an else block?
In the following code, I have 100 test strings that are being inputed as job_name that should be appended to my del_job_ids array. Only 99 of them are being appended.
for j in jobs:
name = jobs[j][... | [
"name=p.match(name).group(1)\n\nYou're changing what name is. That probably makes this false:\nif name==job_name and state!='C':\n\nWhich makes this statement not execute:\ndel_job_ids.append(j)\n\nI suggest taking a look at what name is after the name.p.match(name).group(1) statement.\n",
" for j in jobs:\n ... | [
2,
2,
2,
1
] | [] | [] | [
"match",
"python",
"regex"
] | stackoverflow_0007840784_match_python_regex.txt |
Q:
Python programming with FTP and lists
My main goal is to check an FTP server at anytime for a new file hits and then generate a .txt file with only the new files copied there. If there are no new files then it returns nothing. Here is what I have so far. I have started by copying the files from the server into old... | Python programming with FTP and lists | My main goal is to check an FTP server at anytime for a new file hits and then generate a .txt file with only the new files copied there. If there are no new files then it returns nothing. Here is what I have so far. I have started by copying the files from the server into oldlist.txt, then connecting to the FTP site a... | [
"It's a little easier/faster to convert the lists to a set and not worry about sorting.\nfor filename in set(newlist) - set(oldlist):\n print 'New file: ', filename\n\nAlso, instead of saving the list to a file as raw text, you could use the shelve module to make a persistent store that is conveniently accessibl... | [
3,
0
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0007841722_ftp_python.txt |
Q:
PyQt: Can I make a toolbar button with an icon and text?
I am learning PyQt by playing with examples. In this case, I'm playing with the webbrowser example that is located at \Python26\Lib\site-packages\PyQt4\examples\activeqt\webbrowser .
The demo does something really odd if you add one line to set the icon text... | PyQt: Can I make a toolbar button with an icon and text? | I am learning PyQt by playing with examples. In this case, I'm playing with the webbrowser example that is located at \Python26\Lib\site-packages\PyQt4\examples\activeqt\webbrowser .
The demo does something really odd if you add one line to set the icon text property of a QAction.
Here's a code sample of the change I t... | [
"Try setting the button style on the toolbar that the actions are being added to:\nself.tbNavigate.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)\n...\nself.actionBack.setIconText(\"Back\")\n\n"
] | [
11
] | [] | [] | [
"icons",
"pyqt",
"pyqt4",
"python",
"qtoolbar"
] | stackoverflow_0007842377_icons_pyqt_pyqt4_python_qtoolbar.txt |
Q:
Java raw audio output
Just wondering if there is a library in Java like the module PyAudiere in Python, that simply allows you to create tones and play them, like this sample Python code:
device = audiere.open_device()
tone = device.create_tone(500) #create a 500hz tone
tone.play()
tone.stop()
This simply assigns... | Java raw audio output | Just wondering if there is a library in Java like the module PyAudiere in Python, that simply allows you to create tones and play them, like this sample Python code:
device = audiere.open_device()
tone = device.create_tone(500) #create a 500hz tone
tone.play()
tone.stop()
This simply assigns a variable to your default... | [
"It is pretty simple to generate a sound in memory.\nE.G.\n\nThe important part of generating the tone (and storing it in a Clip) is encompassed in this code:\n/** Generates a tone, and assigns it to the Clip. */\npublic void generateTone()\n throws LineUnavailableException {\n if ( clip!=null ) {\n cl... | [
22,
1
] | [] | [] | [
"audio",
"java",
"javasound",
"python"
] | stackoverflow_0007782721_audio_java_javasound_python.txt |
Q:
How to check if a string from a list is inside another list?
Lets say i have 2 lists:
a=['LOL','GG','rofl']
b=['5 KEK muh bobo LOL', 'LOL KEK bobo bobo GG']
How do i check if first element in a can found in first element of b?
A:
Just that:
a[0] in b[0] # will return True or False
maybe you want to check all o... | How to check if a string from a list is inside another list? | Lets say i have 2 lists:
a=['LOL','GG','rofl']
b=['5 KEK muh bobo LOL', 'LOL KEK bobo bobo GG']
How do i check if first element in a can found in first element of b?
| [
"Just that:\na[0] in b[0] # will return True or False\n\nmaybe you want to check all of them:\nset(i for i in a for j in b if i in j)\n\nor \n{i for i in a for j in b if i in j} #Python 2.7+\n\n",
"Python is actually very robust. You can just do.\na[0] in b[0]\n\n",
"If you only need to know if it's in the stri... | [
4,
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007842753_list_python.txt |
Q:
Is there a way to make a user-defined Python function act like a built-in statement?
Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:
myfunc
rather than:
myfunc()
and have it get called anyway -- the way that, say, print would.
I can already ... | Is there a way to make a user-defined Python function act like a built-in statement? | Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:
myfunc
rather than:
myfunc()
and have it get called anyway -- the way that, say, print would.
I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid f... | [
"No, it is not possible.\nAs you can see from the Language Reference, there is no room left for extensions of the list of simple statements in the specification.\nMoreover, print as a statement no longer exists in Python 3.0 and is replaced by the print() builtin function.\n",
"If what you're looking for is to ad... | [
9,
3,
3,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000489524_python.txt |
Q:
How can I block a Python stdlib module from being imported?
In my Python script, I want to prevent certain stdlib modules, such as os and sys, from being imported. How would I accomplish this?
A:
Taking you very literally, and if you just mean "to stub them out so that they won't be loaded by a straight import",... | How can I block a Python stdlib module from being imported? | In my Python script, I want to prevent certain stdlib modules, such as os and sys, from being imported. How would I accomplish this?
| [
"Taking you very literally, and if you just mean \"to stub them out so that they won't be loaded by a straight import\", not \"make them unloadable by untrusted code\", then:\nimport sys\nsys.modules['os'] = None\nsys.modules['system'] = None\n\nOf course, there is no module system so you might have meant sys, in w... | [
6,
1
] | [] | [] | [
"import",
"python",
"sandbox",
"std"
] | stackoverflow_0007842852_import_python_sandbox_std.txt |
Q:
Request URI returns HTTP 401
I am using LinkedIn api along with Python, Django and Linux. The problem I face is when I apply filters to the request uri.
Supposingly /v1/posts/{post_id}:(id,type,category,creator,title,summary,creation-timestamp,likes,comments,attachment,site-group-post-url) returns a xml for the da... | Request URI returns HTTP 401 | I am using LinkedIn api along with Python, Django and Linux. The problem I face is when I apply filters to the request uri.
Supposingly /v1/posts/{post_id}:(id,type,category,creator,title,summary,creation-timestamp,likes,comments,attachment,site-group-post-url) returns a xml for the data of the following post. But if I... | [
"Could your OAuth library be incorrectly calculating the request signature?\nConfirm that it matches the one generated by this page:\nhttps://developer.linkedin.com/oauth-test-console\n"
] | [
0
] | [] | [] | [
"api",
"django",
"linkedin",
"python",
"rest"
] | stackoverflow_0007818091_api_django_linkedin_python_rest.txt |
Q:
Python Tkinter - Overwriting/Deleting "Default" Widget Bindings
I'm using a Tkinter Text box in my Python (using 2.7.2) script as an entry-type box -- when enter is pressed, it copies the contents into a different text box and then deletes it out of the entry one.
I've bound the necessary event to the Text box whe... | Python Tkinter - Overwriting/Deleting "Default" Widget Bindings | I'm using a Tkinter Text box in my Python (using 2.7.2) script as an entry-type box -- when enter is pressed, it copies the contents into a different text box and then deletes it out of the entry one.
I've bound the necessary event to the Text box when the Enter key is pressed.
The only problem I have is that whenever... | [
"Returning 'break' at the end of your event handler will interrupt event propagation.\n",
"Variations of this question have been asked before. The short answer is \"do a return \"break\" in the code executed by your binding.\nI gave a much longer answer here: python gui events out of order\n"
] | [
0,
0
] | [] | [] | [
"binding",
"python",
"tkinter"
] | stackoverflow_0007842538_binding_python_tkinter.txt |
Q:
How do I block all network access for a script?
Suppose I have a script written in Python or Ruby, or a program written in C. How do I ensure that the script has no access to network capabilities?
A:
You more or less gave a generic answer yourself by tagging it with "sandbox" because that's what you need, some k... | How do I block all network access for a script? | Suppose I have a script written in Python or Ruby, or a program written in C. How do I ensure that the script has no access to network capabilities?
| [
"You more or less gave a generic answer yourself by tagging it with \"sandbox\" because that's what you need, some kind of sandbox. Things that come to mind are: using JPython or JRuby that run on the JVM. Within the JVM you can create a sandbox using a policy file so no code in the JVM can do thing you don't allow... | [
5,
2,
0
] | [] | [] | [
"c",
"python",
"sandbox"
] | stackoverflow_0007843238_c_python_sandbox.txt |
Q:
Data exchange for Python?
Just getting started with Python, but the first goal is to create a web service. I plan on using werkzeug for this, however, all I will be doing is writing a client to interface with it. How would I go about exchanging objects between the 2 systems? Is there anything similar to JSON for P... | Data exchange for Python? | Just getting started with Python, but the first goal is to create a web service. I plan on using werkzeug for this, however, all I will be doing is writing a client to interface with it. How would I go about exchanging objects between the 2 systems? Is there anything similar to JSON for Python?
EDIT:
A couple mentions ... | [
"Python has had native JSON support since 2.6 via the json module. Previous versions have had to use external libraries, SimpleJson being the most common.\n",
"Sounds like you're looking to use pickle instead of json -- pickles are Python specific but can handle user classes as well as dicts:\n>>> class User():\n... | [
4,
1,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0007831652_json_python.txt |
Q:
How to intepret the shape of the array in Python?
I am using a package and it is returning me an array. When I print the shape it is (38845,). Just wondering why this ','.
I am wondering how to interpret this.
Thanks.
A:
Python has tuples, which are like lists but of fixed size. A two-element tuple is (a, b); a ... | How to intepret the shape of the array in Python? | I am using a package and it is returning me an array. When I print the shape it is (38845,). Just wondering why this ','.
I am wondering how to interpret this.
Thanks.
| [
"Python has tuples, which are like lists but of fixed size. A two-element tuple is (a, b); a three-element one is (a, b, c). However, (a) is just a in parentheses. To represent a one-element tuple, Python uses a slightly odd syntax of (a,). So there is only one dimension, and you have a bunch of elements in that on... | [
8,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007843786_python.txt |
Q:
Python number-like class that remembers arithmetic operations?
I'm wondering if there exists a python module that would allow me to do something like this:
x = MagicNumber()
x.value = 3
y = 2 * (x + 2) ** 2 - 8
print y # 42
x.value = 2
print y # 24
So MagicNumber would implement all the special operator metho... | Python number-like class that remembers arithmetic operations? | I'm wondering if there exists a python module that would allow me to do something like this:
x = MagicNumber()
x.value = 3
y = 2 * (x + 2) ** 2 - 8
print y # 42
x.value = 2
print y # 24
So MagicNumber would implement all the special operator methods, and they would all return instances of MagicNumber, while keepin... | [
"Something like this?\nimport operator\n\nMAKE_BINARY = lambda opfn : lambda self,other : BinaryOp(self, asMagicNumber(other), opfn)\nMAKE_RBINARY = lambda opfn : lambda self,other : BinaryOp(asMagicNumber(other), self, opfn)\n\nclass MagicNumber(object):\n __add__ = MAKE_BINARY(operator.add)\n __sub__ = M... | [
13,
7,
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007820771_python.txt |
Q:
How to turn newlines in a file to lines extending to end of line?
I am copying this answer like this
for line in fileinput.input(['my_file'], inplace=True):
sys.stdout.write('_____ {l}'.format(l=line))
to add four underlines to beginning of line. This turns my_file into a checklist. But the above code prints ... | How to turn newlines in a file to lines extending to end of line? | I am copying this answer like this
for line in fileinput.input(['my_file'], inplace=True):
sys.stdout.write('_____ {l}'.format(l=line))
to add four underlines to beginning of line. This turns my_file into a checklist. But the above code prints the underlines on the blank lines too. I want to change the blank lines... | [
"Strip the whitespace on the line and see if it's non-empty (and thus, truthy). If it's non-empty, do what it did before. Otherwise, it's empty; print the horizontal line. (although I must say 49 characters is somewhat odd)\nterm_width = 50\nwith contextlib.closing(fileinput.input(['my_file'], inplace=True)) as f:\... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007844477_python.txt |
Q:
python unittest failing assertion with overloaded __repr__
In my code, I've defined a class with its own repr method. The representation of the class should be a list.
def __repr__(self):
if self.front <= self.tail:
q = self._queue[self.front:self.tail+1]
elif self.front > self.tail:
q = s... | python unittest failing assertion with overloaded __repr__ | In my code, I've defined a class with its own repr method. The representation of the class should be a list.
def __repr__(self):
if self.front <= self.tail:
q = self._queue[self.front:self.tail+1]
elif self.front > self.tail:
q = self._queue[self.front:]
q.extend(self._queue[:self.tail ... | [
"q is a BoundedQueue. [1] is a list. They can't be equal unless you override __eq__. repr is not used for equality testing.\n",
"As recursive states, __repr__ isn't used to detect whether two values are equal.\nYou have several options:\n\nDefine __eq__ which is what python calls to check equality. I don't rec... | [
4,
1
] | [] | [] | [
"python",
"repr",
"unit_testing"
] | stackoverflow_0007844817_python_repr_unit_testing.txt |
Q:
Python Widget that can show both HTML & CSS
I have an idea to create a Parental Supervision Web Browser. The way it works is that I create a desktop application in python(preferably using wxPython or wxPythons webkit) thats just a widget that can display HTML & CSS.
HTTP requests for a website will go through a pr... | Python Widget that can show both HTML & CSS | I have an idea to create a Parental Supervision Web Browser. The way it works is that I create a desktop application in python(preferably using wxPython or wxPythons webkit) thats just a widget that can display HTML & CSS.
HTTP requests for a website will go through a proxy on my server. So if someone wants to access t... | [
"I suggest you try XULRunner instead of Python for this project.\nXULRunner is a toolkit created by Mozilla and is used in Firefox and Thunderbird to create the GUI and such.\nIt is based on XUL (an XML-like language) and JavaScript with extensive support for DOM-interactions (like loading pages and tweaking CSS/HT... | [
0,
0
] | [] | [] | [
"html",
"python",
"tkinter",
"wxpython"
] | stackoverflow_0007844861_html_python_tkinter_wxpython.txt |
Q:
Django Python Macports
I installed Django via Macports.
I wasted a lot of time on making it work.
It still does not work.
I would like to COMPLETELY uninstall Django (Macports) and install with the easy install (DJANGO).
I would like to keep Macports and not uninstall it, because I read it SHOULD be useful.
How ... | Django Python Macports | I installed Django via Macports.
I wasted a lot of time on making it work.
It still does not work.
I would like to COMPLETELY uninstall Django (Macports) and install with the easy install (DJANGO).
I would like to keep Macports and not uninstall it, because I read it SHOULD be useful.
How can I achieve this?
Thank yo... | [
"Did you try port -f uninstall <port>?\nIf you want to uninstall everything that you've installed with MacPorts you could run:\nport -f uninstall installed\n\nYou should be running these commands as the root user, so either use sudo or su root before the commands.\nsudo port -f uninstall <port>\n\nDepending on what... | [
4,
1
] | [] | [] | [
"django",
"macports",
"python",
"uninstallation"
] | stackoverflow_0002802782_django_macports_python_uninstallation.txt |
Q:
Constants for infinity
Are there constants for infinity in python?
The only way I found was to parse the values from a string.
INF = float("inf")
NINF = float("-inf")
A:
You can use
inf = 1e3000
ninf = -1e3000
A:
No. Even fpconst generates them by unpacking the IEEE 754 bit sequences.
| Constants for infinity | Are there constants for infinity in python?
The only way I found was to parse the values from a string.
INF = float("inf")
NINF = float("-inf")
| [
"You can use\ninf = 1e3000\nninf = -1e3000\n\n",
"No. Even fpconst generates them by unpacking the IEEE 754 bit sequences.\n"
] | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0007845466_python.txt |
Q:
Python Modules on commandline
I just found out about the following code I can enter into the command line:
python -m SimpleHTTPServer
Where can I find more documentation about the modules and what I can do with this?
A:
In the main Python documentation, there is a note at the bottom of the SimpleHTTPServer docu... | Python Modules on commandline | I just found out about the following code I can enter into the command line:
python -m SimpleHTTPServer
Where can I find more documentation about the modules and what I can do with this?
| [
"In the main Python documentation, there is a note at the bottom of the SimpleHTTPServer documentation. Other modules such as pdb and timeit have similar notes.\n",
"The overall -m command line feature is documented here and here. You can use it for you own modules. As noted, for individual standard lib modules ... | [
4,
1,
0,
0
] | [] | [] | [
"command_line_interface",
"python"
] | stackoverflow_0007845274_command_line_interface_python.txt |
Q:
How do I add Jinja2 to my cherrypy project?
I have this tool right here
http://tools.cherrypy.org/wiki/Jinja
but what do I do with this?
A:
This tool allows you to render your response using jinga templates. Read the usage...
@cherrypy.expose
@cherrypy.tools.jinja(filename='index.html')
def controller(**kwargs):... | How do I add Jinja2 to my cherrypy project? | I have this tool right here
http://tools.cherrypy.org/wiki/Jinja
but what do I do with this?
| [
"This tool allows you to render your response using jinga templates. Read the usage...\n@cherrypy.expose\n@cherrypy.tools.jinja(filename='index.html')\ndef controller(**kwargs):\n return {\n\n } # This dict is the template context \n\n"
] | [
2
] | [] | [] | [
"cherrypy",
"jinja2",
"python"
] | stackoverflow_0007761709_cherrypy_jinja2_python.txt |
Q:
Cython OpenMP compiler flag
as in http://docs.cython.org/src/userguide/parallelism.html,
I put the compiler flags "-fopenmp" in the 'setup.py' file.
It compiles ok, but returns this: "cl : Command line warning D9002 : ignoring unknown option '-fopenmp'" and there is no speed up on the parallel code.
Using Cython 0... | Cython OpenMP compiler flag | as in http://docs.cython.org/src/userguide/parallelism.html,
I put the compiler flags "-fopenmp" in the 'setup.py' file.
It compiles ok, but returns this: "cl : Command line warning D9002 : ignoring unknown option '-fopenmp'" and there is no speed up on the parallel code.
Using Cython 0.15.1, Python 2.7.2, Windows 7 , ... | [
"You are using MSVC compiler cl.exe. For MSVC compiler, you should give /openmp compiler option: http://msdn.microsoft.com/en-us/library/fw509c3b\n"
] | [
4
] | [] | [] | [
"cython",
"openmp",
"python"
] | stackoverflow_0007844830_cython_openmp_python.txt |
Q:
Python threading.Condition() functionality across multiple processes
I am writing a WSGI app using mod_wsgi. I want to have the ability of many concurrent connections. mod_wsgi spins up a new process for each request, making it impossible to use threading.Condition() for notifying a change from one thread to ano... | Python threading.Condition() functionality across multiple processes | I am writing a WSGI app using mod_wsgi. I want to have the ability of many concurrent connections. mod_wsgi spins up a new process for each request, making it impossible to use threading.Condition() for notifying a change from one thread to another thread.
I understand there is a few different ways to provide real ti... | [
"In the mod_wsgi configuration, set processes=1. See http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess for details.\n"
] | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0007845491_multithreading_python.txt |
Q:
How to prompt a user to open a file in Python
I'm using the following code to open a file based on the path set by the user, but am getting errors. Any suggestions?
f = raw_input("\n Hello, user. "
"\n \n Please type in the path to your file and press 'Enter': ")
file = open('f', 'r')
It says f is undefin... | How to prompt a user to open a file in Python | I'm using the following code to open a file based on the path set by the user, but am getting errors. Any suggestions?
f = raw_input("\n Hello, user. "
"\n \n Please type in the path to your file and press 'Enter': ")
file = open('f', 'r')
It says f is undefined or no such thing exists... even though I am defi... | [
"You shouldn't have the f in quotes:\nmyfile = open(f, 'r')\n\n'f' means the string consisting of the letter f so your code was looking for a file called f and not finding it. Instead use f which means the value of the variable f.\nAlso, don't call the variable to store your file file. This is easily done but try... | [
6,
2,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0007846154_file_python.txt |
Q:
How to get process network usage in Windows in python?
I'm using Python 2.7 and Windows 7 (but I need it to work on at least XP as well).
How can I get the percentage of the network bandwidth used by my program written in Python? So if the internet speed is 20 Mbit/s, and my program is connecting to the web at a "... | How to get process network usage in Windows in python? | I'm using Python 2.7 and Windows 7 (but I need it to work on at least XP as well).
How can I get the percentage of the network bandwidth used by my program written in Python? So if the internet speed is 20 Mbit/s, and my program is connecting to the web at a "full speed", it'd write 100%, etc.
Thanks in advance!
| [
"You would need to develop a windows network driver with such capability.\nCheck the related answer at:\nMonitor a process's network usage?\n"
] | [
1
] | [] | [] | [
"bandwidth",
"python",
"windows"
] | stackoverflow_0007845159_bandwidth_python_windows.txt |
Q:
python pycrypto installation error
Possible Duplicate:
PyCrypto and GMP library not found error [Mac OS 10.6.3]
I'm trying to install pycrypto on ubuntu, but it throws error
hom@PC71:~/Desktop/pycrypto-2.3$ sudo python setup.py build
running build
running build_py
running build_ext
warning: GMP library not found... | python pycrypto installation error |
Possible Duplicate:
PyCrypto and GMP library not found error [Mac OS 10.6.3]
I'm trying to install pycrypto on ubuntu, but it throws error
hom@PC71:~/Desktop/pycrypto-2.3$ sudo python setup.py build
running build
running build_py
running build_ext
warning: GMP library not found; Not building Crypto.PublicKey._fastma... | [
"You are missing the Python development libraries. (Try apt-get install python-dev.)\nHowever, unless you have a valid reason to compile pycrypto yourself, just install it via (I think) apt-get install python-crypto.\n"
] | [
42
] | [] | [] | [
"pycrypto",
"python"
] | stackoverflow_0007845963_pycrypto_python.txt |
Q:
Creating touples in randomly generated numpy arrays
The homework task sounds something like this
Generate a random vector of 4*n uniform integer numbers ranging from 1
to 6, reshape this vector into an array with four rows and n columns,
representing the outcome of n throws with four dice....
I've come up wi... | Creating touples in randomly generated numpy arrays | The homework task sounds something like this
Generate a random vector of 4*n uniform integer numbers ranging from 1
to 6, reshape this vector into an array with four rows and n columns,
representing the outcome of n throws with four dice....
I've come up with the following solution :
import numpy as np
num = 10
... | [
"Both ways are equivalent, although your homework task seems to require to create a 1D array first and reshape it to 2D afterwards.\nv = np.random.randint(1, 7, (num, 4))\n\nNumPy allocates a single memory block for num*4 integers, fills them with random values drawn uniformly from the interval [1, 7), then returns... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007844754_python.txt |
Q:
Why can't I just add Content-Type:text/html to a text file when Python can?
This will seem like a stupid question to most of you but why can't I do this:
Content-Type:text/html
<html>
<head><title>Hello</title></head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
in a file called test.txt and open it in my brows... | Why can't I just add Content-Type:text/html to a text file when Python can? | This will seem like a stupid question to most of you but why can't I do this:
Content-Type:text/html
<html>
<head><title>Hello</title></head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
in a file called test.txt and open it in my browser as html when a Python script can do this:
#!/usr/bin/python
print "Content-ty... | [
"An HTTP response consists of headers and body, separate by the first \\r\\n\\r\\n received. By the time a web server sends an ordinary file, it has already sent all the headers, and the separator.\nWhen a script is run, however, the headers are not sent automatically.\nSo in the first case, your webserver guessed ... | [
4,
3
] | [] | [] | [
"html",
"http_headers",
"python"
] | stackoverflow_0007846294_html_http_headers_python.txt |
Q:
Django - object level premission and class based generic views
This is the model:
class Car(models.Model):
user = models.ForeignKey(User, related_name='cars')
name = models.CharField(max_length=64)
Url pattern goes something like this:
url(r'^car/(?P<pk>\d+)/$', login_required(CarDetails.as_view()), name=... | Django - object level premission and class based generic views | This is the model:
class Car(models.Model):
user = models.ForeignKey(User, related_name='cars')
name = models.CharField(max_length=64)
Url pattern goes something like this:
url(r'^car/(?P<pk>\d+)/$', login_required(CarDetails.as_view()), name='car_details)
And view:
class CarDetail(DetailView):
context_ob... | [
"What about definig base class (or mixin) and using inheritance?\nclass CurUserOnlyDetailView(DetailView):\n def get_object(self, *args, **kwargs):\n obj = super(CurUserOnlyDetailView, self).get_object(*args, **kwargs)\n if obj.user != self.request.user:\n raise PermissionDenied()\n ... | [
6
] | [] | [] | [
"django",
"permissions",
"python"
] | stackoverflow_0007844962_django_permissions_python.txt |
Q:
Sending Email using smtplib
I have following code which successfully sent email using Gmail address. But when i tried to use email account other than Gmail which is one of domain email. It gaves me socket error. Do i need to change something?
def sendEmail(userName, password, subject, content, toEmail, fromEmail):... | Sending Email using smtplib | I have following code which successfully sent email using Gmail address. But when i tried to use email account other than Gmail which is one of domain email. It gaves me socket error. Do i need to change something?
def sendEmail(userName, password, subject, content, toEmail, fromEmail):
print 'Sending email to: %s'... | [
"When you use SMTPserver='smtp.gmail.com' try port number as 465, it may work.\n",
"May be You have to change conn = SMTP(SMTPserver, 587) port also with respective to your email server.\n"
] | [
4,
3
] | [] | [] | [
"python",
"smtplib"
] | stackoverflow_0007846480_python_smtplib.txt |
Q:
How to get MySQLdb to work on OSX with _www user?
I've just managed to get mySQLdb for Python installed on OSX - and from the command line it works fine. I can query the database no problem.
What I'm trying to do now is call up a python script from PHP using the system() function.
This snippet:
import MySQLdb
pr... | How to get MySQLdb to work on OSX with _www user? | I've just managed to get mySQLdb for Python installed on OSX - and from the command line it works fine. I can query the database no problem.
What I'm trying to do now is call up a python script from PHP using the system() function.
This snippet:
import MySQLdb
print "hello from py"
when run from PHP system() returns... | [
"Check your apache error log for errors.\nAlso, try su'ing to _www and execute the script manually.\n",
"Adding the symbolic link in /usr/lib to /usr/local/mysql-5.5.16-osx10.6-x86_64/lib/libmysqlclient.18.dylib as described above fixed this problem for me. Hopefully this will be useful to someone else.\n"
] | [
0,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0007839568_php_python.txt |
Q:
Append a new item to a list within a list
I'm trying to append a new float element to a list within another list, for example:
list = [[]]*2
list[1].append(2.5)
And I get the following:
print list
[[2.5], [2.5]]
When I'd like to get:
[[], [2.5]]
How can I do this?
Thanks in advance.
A:
lst = [[] for _ in xran... | Append a new item to a list within a list | I'm trying to append a new float element to a list within another list, for example:
list = [[]]*2
list[1].append(2.5)
And I get the following:
print list
[[2.5], [2.5]]
When I'd like to get:
[[], [2.5]]
How can I do this?
Thanks in advance.
| [
"lst = [[] for _ in xrange(2)] (or just [[], []]). Don't use multiplication with mutable objects — you get the same one X times, not X different ones.\n",
"list_list = [[] for Null in range(2)]\n\ndont call it list, that will prevent you from calling the built-in function list().\nThe reason that your problem hap... | [
19,
5,
3,
2,
2,
2,
1,
0
] | [] | [] | [
"append",
"list",
"python"
] | stackoverflow_0006814727_append_list_python.txt |
Q:
Very fast sampling from a set with fixed number of elements in python
I need to sample uniformly at random a number from a set with fixed size, do some calculation, and put the new number back into the set. (The number samples needed is very large)
I've tried to store the numbers in a list and use random.choice() ... | Very fast sampling from a set with fixed number of elements in python | I need to sample uniformly at random a number from a set with fixed size, do some calculation, and put the new number back into the set. (The number samples needed is very large)
I've tried to store the numbers in a list and use random.choice() to pick an element, remove it, and then append the new element. But that's ... | [
"Python lists are implemented internally as arrays (like Java ArrayLists, C++ std::vectors, etc.), so removing an element from the middle is relatively slow: all subsequent elements have to be reindexed. (See http://www.laurentluce.com/posts/python-list-implementation/ for more on this.) Since the order of elements... | [
7,
4,
2
] | [] | [] | [
"numpy",
"performance",
"python",
"random",
"random_access"
] | stackoverflow_0007815263_numpy_performance_python_random_random_access.txt |
Q:
python: container to memorize a large number of images
I have to store/retrieve a large number of images to use in my program.
Each image is small: an icon 50x50, and each one has associated a string which is the path the icon is related to.
Since they are so small I was thinking if there is some library which all... | python: container to memorize a large number of images | I have to store/retrieve a large number of images to use in my program.
Each image is small: an icon 50x50, and each one has associated a string which is the path the icon is related to.
Since they are so small I was thinking if there is some library which allows to store all of them in a single file.
I would need to ... | [
"The sqlite3 module in the standard library would do the job nicely.\nThe photos are small at 2500 bits per color plane and they a can easily be stored as blob entries in the database (which is stored as a single file).\n",
"Isnt this maybe easier? (stolen here http://bytes.com/topic/python/answers/44238-pickle-i... | [
4,
0,
0
] | [] | [] | [
"database",
"python"
] | stackoverflow_0007846413_database_python.txt |
Q:
Django ImageField/FileField save uploaded file using model's pk
I'm converting a legacy site (originally written in rails) and by default the images were saved using the format {{pk}}.{{extension}} and that file was always overwritten if a new file is uploaded.
I'd like to continue that format with this django ver... | Django ImageField/FileField save uploaded file using model's pk | I'm converting a legacy site (originally written in rails) and by default the images were saved using the format {{pk}}.{{extension}} and that file was always overwritten if a new file is uploaded.
I'd like to continue that format with this django version.
I originally thought extending FileSystemStorage would be te wa... | [
"You need to define upload_to function. It accepts instance as an argument. But don't forget that if you are creating the instance it won't have pk yet (but you can save it first, and then save the image).\n",
"You can use upload_to like:\ndef image_path(instance, filename):\n return instance.id + os.path.spli... | [
3,
3
] | [] | [] | [
"django",
"django_file_upload",
"pim",
"python"
] | stackoverflow_0007845057_django_django_file_upload_pim_python.txt |
Q:
How do I run lots of subprocesses efficiently in python?
Basic setup:
I am using a python script for automatic testing of a programming project that I am working on. In the test, I run my executable with lots of different options and compare the result with previous runs. The testing takes quite a lot of time sinc... | How do I run lots of subprocesses efficiently in python? | Basic setup:
I am using a python script for automatic testing of a programming project that I am working on. In the test, I run my executable with lots of different options and compare the result with previous runs. The testing takes quite a lot of time since I have roughly 600k different tests to run.
At the moment, I... | [
"You could have a look to mulitprocessing module, especially the Pool part. \nIt will allow you to launch as processes as you want (default as many as CPU cores).\n",
"First, try measuring the testing script/scheme with a null-executable. That way you can see how much overhead the process spawning has w.r.t. actu... | [
3,
1,
1
] | [] | [] | [
"multicore",
"multithreading",
"performance",
"python"
] | stackoverflow_0006046224_multicore_multithreading_performance_python.txt |
Q:
Django / Python : Change uploaded filename before saving file
I am creating a site where users can upload images. I need to make sure that each filename has a unique name to prevent the files from overwriting each other. I will generate the unique name. But how do I change the filename before saving the file? I s... | Django / Python : Change uploaded filename before saving file | I am creating a site where users can upload images. I need to make sure that each filename has a unique name to prevent the files from overwriting each other. I will generate the unique name. But how do I change the filename before saving the file? I see that there are ways to change the folder that it is saved to, bu... | [
"You need to define upload_to function.\n",
"Django can handle the unique filename correctly. The duplicate file name will be renamed automatically.\nIf you want to set the filename manually, just define upload_to function as DrTyrsa said. This question may help you.\n"
] | [
7,
1
] | [] | [] | [
"django",
"file_upload",
"python"
] | stackoverflow_0007847440_django_file_upload_python.txt |
Q:
run tests automatically after sources changed
I use Cxxtest for unit-testing my C++ code. I would like that each time I change and save my code, tests are run (simply, by make tests). I know that for Python there is Nosy that enables that. Is there some generic program that would allow this for Cxxtest or any othe... | run tests automatically after sources changed | I use Cxxtest for unit-testing my C++ code. I would like that each time I change and save my code, tests are run (simply, by make tests). I know that for Python there is Nosy that enables that. Is there some generic program that would allow this for Cxxtest or any other testing unit?
Simply, I just need running a sing... | [
"On Linux you can use a filesystem monitoring daemon like incron to run a command (e.g. make tests) every time a file is changed in a directory (a so-called IN_CLOSE_WRITE event). \n",
"You could use TeamCity for this. It can monitor your code repository and run automated builds + unit tests when changes are dete... | [
2,
1,
0
] | [] | [] | [
"c++",
"python",
"unit_testing"
] | stackoverflow_0007833106_c++_python_unit_testing.txt |
Q:
Python Beginners - Searching a text file for an array of text
I'm brand new to python. I have a text file full of strings. I want to see which of these multiple strings contain a set of keywords. I've managed to write this:
f = open('C:\\blah\\list.txt')
for line in f:
if 'keyword' in line:
print line
... | Python Beginners - Searching a text file for an array of text | I'm brand new to python. I have a text file full of strings. I want to see which of these multiple strings contain a set of keywords. I've managed to write this:
f = open('C:\\blah\\list.txt')
for line in f:
if 'keyword' in line:
print line
Which works great! Its just, I have a lot of keywords to search, s... | [
"Are you searching for lines with all keywords included?\nkeywords = ['abc', 'def', 'ghi']\n\nfor line in f:\n if all(keyword in line for keyword in keywords):\n print line\n\nor with any of them? In the latter case replace the all with any.\n"
] | [
4
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0007848216_arrays_python.txt |
Q:
Why do browsers add extra options to my select element?
I'm using a date selection widget for a registration form in Django. For some reason if you submit the page with validation errors the first option element in the select is duplicated. This happens for every refresh, so if you've submitted the page 5 times, y... | Why do browsers add extra options to my select element? | I'm using a date selection widget for a registration form in Django. For some reason if you submit the page with validation errors the first option element in the select is duplicated. This happens for every refresh, so if you've submitted the page 5 times, you'll have the first element repeated 6 times. Even stranger ... | [
"\nThis is not about webkit, it's about the rendered markup, webkit just happens to be rendering the markup you give it, and the others don't (they see it as a duplicate option)\nThe problem is actually that you're changing the value of MONTHS with your choices.insert(0.. on every execution of your render method. s... | [
1,
0
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0007809286_django_html_python.txt |
Q:
Fixing array indices in Python
I'd like to have arrays that start from say an index of 4 and go to 9. I'm not interested in creating memory space for < 4, so how is best to proceed? My 2D code is as follows:
arr = [[ 0 for row in range(2)] for col in range(1, 129)]
>>> arr[0][0] = 1
>>> arr[128][0] = 1
Traceback (... | Fixing array indices in Python | I'd like to have arrays that start from say an index of 4 and go to 9. I'm not interested in creating memory space for < 4, so how is best to proceed? My 2D code is as follows:
arr = [[ 0 for row in range(2)] for col in range(1, 129)]
>>> arr[0][0] = 1
>>> arr[128][0] = 1
Traceback (most recent call last):
File "<std... | [
"For sparse arrays, use a dict:\nsparseArray = {}\nsparseArray[(0,0)] = 1\nsparseArray[(128,128)] = 1\n\nprint sparseArray # Show the content of the sparse array\nprint sparseArray.keys() # Get all used indices.\n\n",
"You can simply emulate a list:\nclass OffsetList(object):\n def __init__(self, offset=4):\n ... | [
2,
2,
0,
0
] | [] | [] | [
"arrays",
"indexing",
"indices",
"python"
] | stackoverflow_0007848631_arrays_indexing_indices_python.txt |
Q:
Extend all occurences in a string in Python
The goal is to prefix and suffix all occurrences of a substring (case-insensitive) in a source string. I basically need to figure out how to get from source_str to target_str.
source_str = 'You ARe probably familiaR with wildcard'
target_str = 'You [b]AR[/b]e probably fa... | Extend all occurences in a string in Python | The goal is to prefix and suffix all occurrences of a substring (case-insensitive) in a source string. I basically need to figure out how to get from source_str to target_str.
source_str = 'You ARe probably familiaR with wildcard'
target_str = 'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'
In this exam... | [
">>> import re\n>>> source_str = 'You ARe probably familiaR with wildcard'\n>>> re.sub(r\"(ar)\", r\"[b]\\1[/b]\", source_str, flags=re.IGNORECASE)\n'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'\n\n",
"Something like\nimport re\nar_re = re.compile(\"(ar)\", re.I)\nprint ar_re.sub(r\"[b]\\1[/b]\",... | [
4,
3
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0007848880_python_regex_string.txt |
Q:
Python: Urllib.urlopen nonnumeric port
for the following code
theurl = "https://%s:%s@members.dyndns.org/nic/update?hostname=%s&myip=%s&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG" % (username, password, hostname, theip)
conn = urlopen(theurl) # send the request to the url
print(conn.read()) # read the response
conn.cl... | Python: Urllib.urlopen nonnumeric port | for the following code
theurl = "https://%s:%s@members.dyndns.org/nic/update?hostname=%s&myip=%s&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG" % (username, password, hostname, theip)
conn = urlopen(theurl) # send the request to the url
print(conn.read()) # read the response
conn.close() # close the connection
i get the fo... | [
"You probably need to url-encode the password. You'll see an error like that if the password happens to contain a '/'.\nHere's a local example (actual values redacted):\n>>> opener\n<urllib.FancyURLopener instance at 0xb6f0e2ac>\n>>> opener.open('http://admin:somepass@example.com')\n<addinfourl at 3068618924L whose... | [
6,
1,
0,
0
] | [] | [] | [
"python",
"urllib",
"urlopen"
] | stackoverflow_0003351272_python_urllib_urlopen.txt |
Q:
What is the fastest way to sample slices of numpy arrays?
I have a 3D (time, X, Y) numpy array containing 6 hourly time series for a few years. (say 5). I would like to create a sampled time series containing 1 instance of each calendar day randomly taken from the available records (5 possibilities per day), as fo... | What is the fastest way to sample slices of numpy arrays? | I have a 3D (time, X, Y) numpy array containing 6 hourly time series for a few years. (say 5). I would like to create a sampled time series containing 1 instance of each calendar day randomly taken from the available records (5 possibilities per day), as follows.
Jan 01: 2006
Jan 02: 2011
Jan 03: 2009
...
this means ... | [
"The year 2008 was 366 days long, so don't reshape.\nHave a look at scikits.timeseries:\nimport scikits.timeseries as ts\n\nstart_date = ts.Date('H', '2006-01-01 00:00')\nend_date = ts.Date('H', '2010-12-31 18:00')\narr3d = ... # your 3D array [time, X, Y]\n\ndates = ts.date_array(start_date=start_date, end_date=en... | [
3,
0
] | [] | [] | [
"numpy",
"python",
"sampling"
] | stackoverflow_0007849077_numpy_python_sampling.txt |
Q:
How to properly process regex match
I have strings that come from outside to my application and may look like these with quotes:
Prefix content. "Some content goes here". More contents without quotes.
Prefix content. "Another "Additional" goes here". More contents without quotes.
Prefix content. "Just another "con... | How to properly process regex match | I have strings that come from outside to my application and may look like these with quotes:
Prefix content. "Some content goes here". More contents without quotes.
Prefix content. "Another "Additional" goes here". More contents without quotes.
Prefix content. "Just another "content". More contents without quotes.
The... | [
"Looks like you just want everything from the first quote to the last quote, even if there are other quotes between. This should suffice:\n\".*\"\n\nThe leading and trailing .* in your regex were never needed, and the leading one was distorting your results. It would initially consume the whole input, then back o... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007847873_python_regex.txt |
Q:
Sqlalchemy select condition
I have a mapper on a table and I want to define a column_property which should select True or False whether the entity has some propertie or not:
mapper( Person, persons_table, properties = {
'administrator': column_property(
select(
[True if roles_table.c.is_a... | Sqlalchemy select condition | I have a mapper on a table and I want to define a column_property which should select True or False whether the entity has some propertie or not:
mapper( Person, persons_table, properties = {
'administrator': column_property(
select(
[True if roles_table.c.is_admin or roles_table.c.id == 1 els... | [
"Your SELECT-expression is actually a Python expression:\nselect([True if roles_table.c.is_admin or roles_table.c.id == 1 else False],\n roles_table.c.id == persons_table.c.role_id)\n\nsqlalchemy.select() will see this as:\nselect([True], some_expression_object)\n\nsince the column object roles_table.c.is_adm... | [
4
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007848573_python_sqlalchemy.txt |
Q:
Combing for loop
Both programs are reading the same XML file. First program copies all data between <text></text> tags. And second program copies limited data from <text></text> tags.
I want to only limited data. So is it possible to use this statement in first program:
m = re.search(r'(?ms).*?{{(Infobox film.*?... | Combing for loop | Both programs are reading the same XML file. First program copies all data between <text></text> tags. And second program copies limited data from <text></text> tags.
I want to only limited data. So is it possible to use this statement in first program:
m = re.search(r'(?ms).*?{{(Infobox film.*?)}}', t.text)
First ... | [
"I don't see any reason why you wouldn't be able to do the following at the end of your first program:\nm = re.search(r'(?ms).*?{{(Infobox film.*?)}}', text)\nif m:\n print m.group(1)\n\nAs per what you describe, your text variable should contain all the text, and your regexp should then be able to filter out th... | [
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0007847014_elementtree_python_xml.txt |
Q:
Removing a file with only the python file object
Let's say that I open a file, that didn't previously exist, for writing:
f = open('/tmp/test.txt', 'w')
Once this line is executed the file '/tmp/test.txt' is created. What is the cleanest way to remove (delete) the file with only the file object (f) and not the p... | Removing a file with only the python file object | Let's say that I open a file, that didn't previously exist, for writing:
f = open('/tmp/test.txt', 'w')
Once this line is executed the file '/tmp/test.txt' is created. What is the cleanest way to remove (delete) the file with only the file object (f) and not the path?
| [
"You cannot remove a file handle, only a file path, since multiple paths can refer to the same file and some files (like sockets) don't even have paths. Therefore:\nimport os\nf = open('/tmp/test.txt', 'w')\nos.unlink(f.name)\n# You can still use f here, it's just only visible for people having a handle.\n# close i... | [
30,
9,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0007848919_python.txt |
Q:
Django populating a choice field
I am working with four tables:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
class Alarm(models.Model):
active = models.BooleanField(... | Django populating a choice field | I am working with four tables:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
class Alarm(models.Model):
active = models.BooleanField(default=True)
product = models.For... | [
"It turns out the best way round it was:\nclass FileAlarmForm(ModelForm):\n\n def __init__(self,file,*args,**kwargs):\n super(FileAlarmForm, self).__init__(*args, **kwargs)\n p = Product.objects.get(id=file.product_id)\n self.fields['alarm_type'].widget = Select(attrs={'onchange':'updateAlar... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0007849169_django_django_forms_python.txt |
Q:
Make new software for Windows 95 on 486 machines, what to use?
I have a VB6 application running on a number of old 486 Windows 95 machines and sometimes the application is upgraded. The only way to accomplish this today is to use Hyperterminal and send the file over a null modem cable. Replacing the machines is no... | Make new software for Windows 95 on 486 machines, what to use? | I have a VB6 application running on a number of old 486 Windows 95 machines and sometimes the application is upgraded. The only way to accomplish this today is to use Hyperterminal and send the file over a null modem cable. Replacing the machines is not an option at this point.
I want to write an application that can t... | [
"If you must use a null modem, how about the built in serial line networking support?\nThen you can just use normal network methods (psexec, file share, etc) methods to do the update.\n",
"Network Method\nI would first get network cards installed in everything. If you want something that you can just plugin and ... | [
3,
2,
0,
0
] | [] | [] | [
"native",
"python",
"vb6",
"windows_95"
] | stackoverflow_0007833831_native_python_vb6_windows_95.txt |
Q:
python2: merge a list of csv elements
I have a dict like this:
{1: ['1,2,3', '4,5,6', '7,8']}
the dict can be variable in the number of list items but always 1 dict item. How do I merge it to
{1: ['1,2,3,4,5,6,7,8']}
?
Thanks
A:
>>> d
{1: ['1,2,3', '4,5,6', '7,8'], 2: ['9,10', '11']}
>>> for k,v in d.iteritems(... | python2: merge a list of csv elements | I have a dict like this:
{1: ['1,2,3', '4,5,6', '7,8']}
the dict can be variable in the number of list items but always 1 dict item. How do I merge it to
{1: ['1,2,3,4,5,6,7,8']}
?
Thanks
| [
">>> d\n{1: ['1,2,3', '4,5,6', '7,8'], 2: ['9,10', '11']}\n>>> for k,v in d.iteritems():\n... d[k] = [\",\".join(v)]\n...\n>>> d\n{1: ['1,2,3,4,5,6,7,8'], 2: ['9,10,11']}\n\n",
"in your case, you just need concat a string.\nBut if you want to merge the collection, try this:\na = [1, 2, 3]\nb = [3, 4, 5]\na.ex... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007850357_python.txt |
Q:
Django conditional template tag library loader
I'm working on a Django app that provides templates with optional functionality if certain other apps are available.
It's not possible to load an unavailable template tag library using the standard {% load %} Django tag. Trying to do that results in a TemplateSyntaxEr... | Django conditional template tag library loader | I'm working on a Django app that provides templates with optional functionality if certain other apps are available.
It's not possible to load an unavailable template tag library using the standard {% load %} Django tag. Trying to do that results in a TemplateSyntaxError.
Has anyone come up with a solution to this prob... | [
"I've created a new Django app that does what I wanted. It's called django-friendly-tag-loader and is available from PyPi http://pypi.python.org/pypi/django-friendly-tag-loader/ and hackable @ https://github.com/ataylor32/django-friendly-tag-loader\nIt provides 3 template tags: {% friendly_load %}, {% if_has_tag %}... | [
5,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0007835155_django_django_templates_python.txt |
Q:
how to return index of a sorted list?
I need to sort a list and then return a list with the index of the sorted items in the list. For example, if the list I want to sort is [2,3,1,4,5], I need [2,0,1,3,4] to be returned.
This question was posted on bytes, but I thought I would repost it here.
http://bytes.com/t... | how to return index of a sorted list? | I need to sort a list and then return a list with the index of the sorted items in the list. For example, if the list I want to sort is [2,3,1,4,5], I need [2,0,1,3,4] to be returned.
This question was posted on bytes, but I thought I would repost it here.
http://bytes.com/topic/python/answers/44513-sorting-list-then... | [
"You can use the python sorting functions' key parameter to sort the index array instead.\n>>> s = [2, 3, 1, 4, 5, 3]\n>>> sorted(range(len(s)), key=lambda k: s[k])\n[2, 0, 1, 5, 3, 4]\n>>> \n\n",
"You can do this with numpy's argsort method if you have numpy available:\n>>> import numpy\n>>> vals = numpy.array([... | [
326,
91,
22,
9,
3,
0
] | [
"Straight out of the documentation for collections.OrderedDict:\n>>> # dictionary sorted by value\n>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))\nOrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])\n\nAdapted to the example in the original post:\n>>> l=[2,3,1,4,5]\n>>> OrderedDict(sorted... | [
-2
] | [
"python"
] | stackoverflow_0007851077_python.txt |
Q:
trying to call a perl script from python, resulting in weird behaviour
I am trying to call a perl script from my python program with the following line:
subprocess.call(r'/path/to/compute_lexrank.pl /path/to/11sent',shell=True)
when I run the same perl script from the shell (just typing /path/to/compute_lexrank.p... | trying to call a perl script from python, resulting in weird behaviour | I am trying to call a perl script from my python program with the following line:
subprocess.call(r'/path/to/compute_lexrank.pl /path/to/11sent',shell=True)
when I run the same perl script from the shell (just typing /path/to/compute_lexrank.pl /path/to/11sent) it works fine as expected, but when I run it from the pyt... | [
"In Perl, there's a good rule: if possible, use list forms of popen and system. Python seems to have those, too. I wonder what happens if you try this out: \nhelper = \"/path/to/compute_lexrank.pl\"\nhelper_input = \"/path/to/11sent\"\nsubprocess.call([helper, helper_input])\n\n",
"You may need to pass the workin... | [
0,
0
] | [] | [] | [
"perl",
"python",
"subprocess"
] | stackoverflow_0006449924_perl_python_subprocess.txt |
Q:
Import folder of modules in Python
Is it possible in python to get a list of modules from a folder/package and import them?
I would like to be able to do this from a function inside a class, so that the entire class has access to them (possibly done from the __init__ method).
Any help would be greatly appreciated.... | Import folder of modules in Python | Is it possible in python to get a list of modules from a folder/package and import them?
I would like to be able to do this from a function inside a class, so that the entire class has access to them (possibly done from the __init__ method).
Any help would be greatly appreciated.
| [
"See the modules document.\n\nThe only solution is for the package author to provide an explicit\n index of the package. The import statement uses the following\n convention: if a package’s __init__.py code defines a list named\n __all__, it is taken to be the list of module names that should be imported when fr... | [
4,
0,
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0007851321_import_module_python.txt |
Q:
solve the determinent using python
As a simple example, let's say you have this matrix:
M = [omega 1;
2 omega];
and you need to solve for the values of omega that satisfy the condition det M = 0. How do you do this in python?
A:
Use sympy library.
You can create the Matrix.
Then calculate the determinan... | solve the determinent using python | As a simple example, let's say you have this matrix:
M = [omega 1;
2 omega];
and you need to solve for the values of omega that satisfy the condition det M = 0. How do you do this in python?
| [
"Use sympy library.\nYou can create the Matrix.\nThen calculate the determinant. \nAnd then solve the equation against omega.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0007851571_python.txt |
Q:
Django error when using South migration: Unknown column in 'field list'
I'm running into a problem when using schemamigration to add a column to my database. The field in question, 'is_flagged', is a boolean belonging to the Video model in my app 'upload'. When running the migration, I get the following:
....:~/... | Django error when using South migration: Unknown column in 'field list' | I'm running into a problem when using schemamigration to add a column to my database. The field in question, 'is_flagged', is a boolean belonging to the Video model in my app 'upload'. When running the migration, I get the following:
....:~/..../webapp$ python manage.py schemamigration upload --auto
Traceback (most r... | [
"The problem is not that you have a ForeignKey pointed to the model you are migrating. That is a very common situation, and South definitely deals fine with that.\nThe real problem is that you are doing something very very bad in that FK declaration.\nvideo = models.ForeignKey(Video, default=Video.objects.all()[0])... | [
5,
5
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0006850333_django_django_south_python.txt |
Q:
How can i invoke a shell command from python which includes regexp?
How can I invoke a shell command from python which includes regexp (i.e., cat filename*).
I wrote:
pid = subprocess.Popen(["cat", filename + "*"])
but I am getting an error
cat filename* no such file or directory.
I'd like to force the shell to... | How can i invoke a shell command from python which includes regexp? | How can I invoke a shell command from python which includes regexp (i.e., cat filename*).
I wrote:
pid = subprocess.Popen(["cat", filename + "*"])
but I am getting an error
cat filename* no such file or directory.
I'd like to force the shell to treat "*" as a regexp and not as a string. Is there any way to implement... | [
"Use an underlying shell to expand your globs:\npid = subprocess.Popen([\"cat\",filename+\"*\"], shell=True)\n\nAlternatively, use glob.glob to expand your arguments before running the command:\nimport glob\npid = subprocess.Popen([\"cat\"] + glob.glob(filename + \"*\"))\n\n",
"FIRST it's not regular expression i... | [
6,
4
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0007851652_python_shell.txt |
Q:
Subsuming the Linux packet processing stack
We occasionally have to debug glitchy Cisco routers that don't handle the TCP Selective Acknowledgment (SACK) options correctly. This causes our TCP sessions to die when routed through an IPTABLES port redirection rule.
To help with the diagnosis, I've been constructing ... | Subsuming the Linux packet processing stack | We occasionally have to debug glitchy Cisco routers that don't handle the TCP Selective Acknowledgment (SACK) options correctly. This causes our TCP sessions to die when routed through an IPTABLES port redirection rule.
To help with the diagnosis, I've been constructing a python-based utility to construct a sequence of... | [
"Are you receiving and processing the packet and only need to suppress the ICMP port-unreachable? If so, maybe just add an entry to the iptables OUTPUT chain to drop it?\n"
] | [
1
] | [] | [] | [
"linux",
"networking",
"python"
] | stackoverflow_0007851817_linux_networking_python.txt |
Q:
Read files with greek filenames
I am not a unicode expert, I read similar posts without any conclusive solution. I need a snippet to read some files with Greek characters. My files have names like
20.10.2011 Ισοζύγιο Πληρωμών- Αύγουστος 2011.xls
I have a generator function that yields filenames:
# -*- coding:utf-... | Read files with greek filenames | I am not a unicode expert, I read similar posts without any conclusive solution. I need a snippet to read some files with Greek characters. My files have names like
20.10.2011 Ισοζύγιο Πληρωμών- Αύγουστος 2011.xls
I have a generator function that yields filenames:
# -*- coding:utf-8 -*-
import os
import glob
def file... | [
"You need to make sure that you call os.walk() with a Unicode string, or it will silently change non-ASCII letters to ASCII (or change them to ? as you've observed).\nSo do\nfor file in filesInDir(directory=u'.'):\n with open(file,'r') as f:\n print f\n\nand\ndef filesInDir(directory, mask=u'*.*'):\n f... | [
5
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0007851877_python_unicode.txt |
Q:
Is there a library for retrieving a file from a remote zip?
The goal is just to retrieve a specific file without downloading the entire contents, using the HTTP range method as described:
http://www.codeproject.com/KB/cs/remotezip.aspx
A:
You can solve this a bit more generally with less code. Essentially, crea... | Is there a library for retrieving a file from a remote zip? | The goal is just to retrieve a specific file without downloading the entire contents, using the HTTP range method as described:
http://www.codeproject.com/KB/cs/remotezip.aspx
| [
"You can solve this a bit more generally with less code. Essentially, create enough of a file-like object for ZipFile to use. So you wind up with z = ZipFile(HttpFile(url)) and it dynamically downloads just the portion needed. The advantage with this is you write less code, and it applies to more than just zip f... | [
18,
6
] | [] | [] | [
"http",
"python",
"zip"
] | stackoverflow_0007829311_http_python_zip.txt |
Q:
Python tkinter: Update GUI between subprocess calls
I programmed a GUI that calls a .cmd file several times (with different parameters)
class App:
def process(self):
for filename in os.listdir(path):
subprocess.call(['script.cmd', filename])
self.output('processed ' + filename)
... | Python tkinter: Update GUI between subprocess calls | I programmed a GUI that calls a .cmd file several times (with different parameters)
class App:
def process(self):
for filename in os.listdir(path):
subprocess.call(['script.cmd', filename])
self.output('processed ' + filename)
def output(self, line):
self.textarea.config... | [
"I found a dirty solution:\nI call root.update() before every subprocess.call().\nTo make sure that no buttons are pressed during processing (that seems to be a problem with root.update() according to a quick google search), I disable them all before the subprocesses are started\nlike this:\nfrom Tkinter import *\n... | [
4
] | [] | [] | [
"python",
"subprocess",
"tkinter"
] | stackoverflow_0007801163_python_subprocess_tkinter.txt |
Q:
Why am i getting error
The error:
Error Traceback (most recent call last):
File "/home/enrique/Dropbox/Public/pygametut3.py", line 41, in <module>
pix = MovingPixel(width/2, height/2)
TypeError: this constructor takes no arguments
The Code:
#Creat a moving pixel
pix = MovingPixel(width/2, height/2)
while... | Why am i getting error | The error:
Error Traceback (most recent call last):
File "/home/enrique/Dropbox/Public/pygametut3.py", line 41, in <module>
pix = MovingPixel(width/2, height/2)
TypeError: this constructor takes no arguments
The Code:
#Creat a moving pixel
pix = MovingPixel(width/2, height/2)
while running:
pix.move()
... | [
"Because MovingPixel needs to be instantiated with no arguments:\npix = MovingPixel()\n\n",
"You created the MovingPixel object passing two arguments to the constructor, it requires no arguments. Did you forget to import the right module?\nIf you are referring to something like this: http://lorenzod8n.wordpress.c... | [
1,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0007852249_pygame_python.txt |
Q:
Can't import specific modules in embedded Python
I'm running an embedded Python interpreter in Obj-C. I can run Python scripts just fine, but when I try to import certain standard modules, I get ImportError: No module named random, for instance.
However, I can import certain other modules. My investigations has gi... | Can't import specific modules in embedded Python | I'm running an embedded Python interpreter in Obj-C. I can run Python scripts just fine, but when I try to import certain standard modules, I get ImportError: No module named random, for instance.
However, I can import certain other modules. My investigations has given me this list so far:
Can:
import sys
import math
... | [
"Thomas K set me on the right track, even though the problem was the completely opposite.\nMy Python setup was lacking the standard Python library - the part written in Python (usually distributed through /Library, /Lib or /pylib in the distribution. Once those files were added to my application, all of it imported... | [
0
] | [] | [] | [
"import",
"objective_c",
"python"
] | stackoverflow_0007806031_import_objective_c_python.txt |
Q:
Ternary operator for NumPy ndarray?
Does NumPy have a ternary operator? For instance, in R there is a vectorized if-else function:
> ifelse(1:10 < 3,"a","b")
[1] "a" "a" "b" "b" "b" "b" "b" "b" "b" "b"
Is there anything equivalent in NumPy?
A:
You are looking for numpy.where():
>>> print numpy.where(numpy.aran... | Ternary operator for NumPy ndarray? | Does NumPy have a ternary operator? For instance, in R there is a vectorized if-else function:
> ifelse(1:10 < 3,"a","b")
[1] "a" "a" "b" "b" "b" "b" "b" "b" "b" "b"
Is there anything equivalent in NumPy?
| [
"You are looking for numpy.where():\n>>> print numpy.where(numpy.arange(10) < 3, 'a', 'b')\n['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b']\n\nNumPy even has a generalization (that maps 0, 1, 2, etc. to values, instead of mapping only True and False): numpy.choose().\n"
] | [
35
] | [] | [] | [
"arrays",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0007852519_arrays_multidimensional_array_numpy_python.txt |
Q:
full file path for zipped folder in python
I have the following code that is trying to get the full file path (including the folder):
import zipfile
import os
import sys
zipped_files_dir = 'Z:\Dev\some_files'
def get_folder_names():
path_list = []
for folder_name in os.listdir(zipped_files_dir):
... | full file path for zipped folder in python | I have the following code that is trying to get the full file path (including the folder):
import zipfile
import os
import sys
zipped_files_dir = 'Z:\Dev\some_files'
def get_folder_names():
path_list = []
for folder_name in os.listdir(zipped_files_dir):
path_list.append(folder_name)
return path_li... | [
"You could use os.path.join(zipped_files_dir, folder) in the get_folder_directories function:\nimport zipfile\nimport os\nimport sys\n\nzipped_files_dir = 'Z:\\Dev\\some_files'\n\ndef get_folder_names():\n path_list = []\n for folder_name in os.listdir(zipped_files_dir):\n path_list.append(folder_name)... | [
2,
1
] | [] | [] | [
"file",
"path",
"python",
"zip"
] | stackoverflow_0007852539_file_path_python_zip.txt |
Q:
Mongoengine document consistency under concurrency
I am trying to create a dummy wrapper class ( a mongoengine Document ) that implements the interface of Redis hashes. For example:
class HashModel(mongoengine.Document):
'''
Represents a dictionary with a name.
Interface similar to Redis Hashes
'''... | Mongoengine document consistency under concurrency | I am trying to create a dummy wrapper class ( a mongoengine Document ) that implements the interface of Redis hashes. For example:
class HashModel(mongoengine.Document):
'''
Represents a dictionary with a name.
Interface similar to Redis Hashes
'''
name = mongoengine.StringField()
adict = mongoe... | [
"This is a pure race condition issue. My celery workers may simultaneously obtain an instance and perform different operations on it, then save it, no consistency anymore..\n"
] | [
1
] | [] | [] | [
"celery",
"mongoengine",
"python",
"redis"
] | stackoverflow_0007746266_celery_mongoengine_python_redis.txt |
Q:
Finding multiple common starting strings
I have a list of strings in which one or more subsets of the strings have a common starting string. I would like a function that takes as input the original list of strings and returns a list of all the common starting strings. In my particular case I also know that each co... | Finding multiple common starting strings | I have a list of strings in which one or more subsets of the strings have a common starting string. I would like a function that takes as input the original list of strings and returns a list of all the common starting strings. In my particular case I also know that each common prefix must end in a given delimiter. Bel... | [
"Isn't this just looping over the strings, splitting them on the delimiter, then grouping the second halves by the first halves? Like so:\ndef groupByPrefix(strings):\n stringsByPrefix = {}\n for string in strings:\n prefix, suffix = map(str.strip, string.split(\"/\", 1))\n group = strin... | [
8,
5,
3,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0007852384_algorithm_python.txt |
Q:
finding index in a nested list
Possible Duplicate:
efficient word indexing in python
Apologies for the basic question, how can I find the indexes ((1,2),(2,1),(2,2)) corresponding to "yellow" in ref and store them so that I can access them afterwords without rerunning the search?
ref1 = "this is a test"
ref2 = ... | finding index in a nested list |
Possible Duplicate:
efficient word indexing in python
Apologies for the basic question, how can I find the indexes ((1,2),(2,1),(2,2)) corresponding to "yellow" in ref and store them so that I can access them afterwords without rerunning the search?
ref1 = "this is a test"
ref2 = "this is a yellow test"
ref3 = "thi... | [
"Just for the sake of it:\n[(k,i) for k,m in enumerate(ref, 1) for i,j in enumerate(m, 1) if 'yellow' in j]\n\nbut you probably want the real index (starting at zero)... Remove the second argument of enumerate if so.\n",
"I'm not sure what you mean, but if you want to generate a list of pairs from a list (or tupl... | [
0,
0
] | [] | [] | [
"indexing",
"list",
"nested",
"python"
] | stackoverflow_0007853126_indexing_list_nested_python.txt |
Q:
Anynchronous Logging strategy for Python & PHP
Here's the situation: We have a bunch of python scripts continuously doing stuff and ultimately writing data in mysql, and we need a log to analyse the error rate and script performance.
We also have php front-end that interacts with the mysql data and we also need t... | Anynchronous Logging strategy for Python & PHP | Here's the situation: We have a bunch of python scripts continuously doing stuff and ultimately writing data in mysql, and we need a log to analyse the error rate and script performance.
We also have php front-end that interacts with the mysql data and we also need to log the user actions so that we can analyse their ... | [
"There are (AFAIK) only two ways to do anything a-synchronously in PHP:\n\nFork the process (requires pcntl_fork)\nexec() a process and release it by (assuming *nix) appending > /dev/null & to the end of the command string.\n\nBoth of these approaches result in a new process being created, albeit temporarily, so wh... | [
2,
2
] | [] | [] | [
"asynchronous",
"logging",
"php",
"python",
"queue"
] | stackoverflow_0007852073_asynchronous_logging_php_python_queue.txt |
Q:
Get value from 2nd list based on ID from 1st list in Python
I'm a beginner in Python and have a file i've read in that has an Market_ID field. While looping over this file (list), I need to access the Market_name in a 2nd file (Market_ID,Market_Name).
What's the best place for me to start? I can give more detail ... | Get value from 2nd list based on ID from 1st list in Python | I'm a beginner in Python and have a file i've read in that has an Market_ID field. While looping over this file (list), I need to access the Market_name in a 2nd file (Market_ID,Market_Name).
What's the best place for me to start? I can give more detail on what the program is doing if necessary.
The files(lists) are l... | [
"If the files are not too big (a few megabytes) you could store each item in a dict() using the Market_ID as key. \nThis looks like data drom a database - if you are familiar with relational databases and their use you could insert each file into a separate table and then perform queries. Python has an interface to... | [
1,
1,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0007853045_loops_python.txt |
Q:
Distribution of "tasks" to multiple hosts in python
I am wondering whether there's a lightweight way to distribute python "tasks" among different hosts. Here's what I mean:
Master script running in e.g. London
Client 1 running in London
Client 2 running in New York
Client 3 running in Hong Kong
The clients would h... | Distribution of "tasks" to multiple hosts in python | I am wondering whether there's a lightweight way to distribute python "tasks" among different hosts. Here's what I mean:
Master script running in e.g. London
Client 1 running in London
Client 2 running in New York
Client 3 running in Hong Kong
The clients would have a way (e.g. SOAP) to communicate with the master. The... | [
"0MQ\nI would look at zeromq. However, before I built a system that allowed arbitrary code to be executed, I would make sure I had a thorough understanding of cryptographic authentication!\n",
"You should check out Pyro. It handles some of the requirements you have.\n"
] | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0007853247_python.txt |
Q:
fetch text from a web site and displaying it back
Currently, there's a game that has different groups, and you can play for a prize 'gold' every hour. Sometimes there is gold, sometimes there isn't. It is posted on facebook every hour ''gold in group2" or "gold in group6'', and other times there isn't a post due t... | fetch text from a web site and displaying it back | Currently, there's a game that has different groups, and you can play for a prize 'gold' every hour. Sometimes there is gold, sometimes there isn't. It is posted on facebook every hour ''gold in group2" or "gold in group6'', and other times there isn't a post due to no gold being a prize for that hour. I want to write ... | [
"Check out urllib2 for getting html from a url and BeautifulSoup/HTMLParser/etc to parse the html. Then, you could use something like this as a starting point for the script:\nimport time\nimport urllib2\nimport BeautifulSoup\nimport HTMLParser\n\ndef getSource(url, postdata):\n source = \"\"\n req = urllib2... | [
1,
1
] | [] | [] | [
"python",
"screen_scraping"
] | stackoverflow_0007829768_python_screen_scraping.txt |
Q:
searching for strings in all lines of a text file: Python
having a problem here so hopefully could use some help.
I have a text file with an ID number and a set of "descriptors" on each line. The descriptors may or may not be unique to each line (they can be used multiple times throughout the document).
I basica... | searching for strings in all lines of a text file: Python | having a problem here so hopefully could use some help.
I have a text file with an ID number and a set of "descriptors" on each line. The descriptors may or may not be unique to each line (they can be used multiple times throughout the document).
I basically want to identify all the ID numbers that contain a certain ... | [
"I'd suggest using a dict for this, with the descriptors as the keys and the corresponding IDs as the values. You go through the file and at each line, add the ID to the list filed in the dictionary under each descriptor. For example:\nby_descriptors = collections.defaultdict(list)\nfor line in file:\n id, _, de... | [
0
] | [] | [] | [
"loops",
"python",
"search"
] | stackoverflow_0007853559_loops_python_search.txt |
Q:
Twisted Python: Max Packet Size? Flush socket?
I'm implementing a client-server solution based on Twisted for the server side and e.g. and Android phone for the client side.
Because the Andoird emulator takes no TCP Packets larger then 1500b (or less?), I need to be able to chunk packets on the server side. Withou... | Twisted Python: Max Packet Size? Flush socket? | I'm implementing a client-server solution based on Twisted for the server side and e.g. and Android phone for the client side.
Because the Andoird emulator takes no TCP Packets larger then 1500b (or less?), I need to be able to chunk packets on the server side. Without flushing the socket after each "transport.write", ... | [
"TCP packets are automatically chunked by the OS, all the application can do is give hints when to flush. Apart from that, an application can just read and write to a stream.\nThe OSs of two communicating peers will automatically configure the maximum packet sizes based on the MTU on the links with Path MTU discove... | [
2,
2
] | [] | [] | [
"chunking",
"packet",
"python",
"tcp",
"twisted"
] | stackoverflow_0007844302_chunking_packet_python_tcp_twisted.txt |
Q:
web.py deployment for iOS app backend
I am currently developing an iOS application that needs a backend to pull data from. I have implemented the backend using Python, web.py and pymongo.
I deployed everything on an EC2 instance, assigned an elastic IP to the instance that the iOS devices call to access the backen... | web.py deployment for iOS app backend | I am currently developing an iOS application that needs a backend to pull data from. I have implemented the backend using Python, web.py and pymongo.
I deployed everything on an EC2 instance, assigned an elastic IP to the instance that the iOS devices call to access the backend, and launch the application through SSH b... | [
"FWIW, we use CherryPy (the web server \"built into\" web.py) behind nginx to serve most of the HTML at Oyster.com -- nginx splits the traffic across 2 or 3 web servers each running 4 Python processes, and we can easily handle 100s of requests per second.\nHowever, we use a content delivery network (CDN) for our st... | [
2,
1
] | [] | [] | [
"backend",
"python",
"web.py"
] | stackoverflow_0007788149_backend_python_web.py.txt |
Q:
Automatically preventing wiki-rot in Trac?
Hi guys : Is there a way to improve trac wiki quality using a plugin that deals with artifacts like for obsolete pages, or pages that refer to code which doesn't exist anymore, pages that are unlinked, or pages which have a low update-rate ? I think there might be sever... | Automatically preventing wiki-rot in Trac? | Hi guys : Is there a way to improve trac wiki quality using a plugin that deals with artifacts like for obsolete pages, or pages that refer to code which doesn't exist anymore, pages that are unlinked, or pages which have a low update-rate ? I think there might be several heuristics which could be used to prevent wik... | [
"I don't know of an existing plugin that does this, but everything you mentioned certainly sounds do-able in one way or another.\nYou can use the trac-admin CLI command to get a list of wiki pages and to dump the contents of a particular wiki page (as plain text) to a file or stdout. Using this, you can write a sc... | [
1,
1
] | [] | [] | [
"code_documentation",
"python",
"trac",
"wiki"
] | stackoverflow_0007841577_code_documentation_python_trac_wiki.txt |
Q:
Python: setting configuration parameters
What's your preferred way of processing configuration parameters?
For example:
test(this=7)
could be processed by:
def test(**kw):
this = kw.pop('this', 1)
that = kw.pop('that', 2)
or
def test(**kw):
if 'this' in kw:
this = kw['this']
else:
this = 1
... | Python: setting configuration parameters | What's your preferred way of processing configuration parameters?
For example:
test(this=7)
could be processed by:
def test(**kw):
this = kw.pop('this', 1)
that = kw.pop('that', 2)
or
def test(**kw):
if 'this' in kw:
this = kw['this']
else:
this = 1
if 'that' in kw:
that = kw['that']
el... | [
"If the possible parameters and defaults are fixed, the Pythonic way is to write:\ndef test(this=1, that=2):\n ...\n\nIf the parameter list is dynamic, your approach with kwds.pop() has a nice advantage of letting you verify that all the arguments were used (detecting misspelled parameter names for example). It... | [
3,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0007853706_function_python.txt |
Q:
Strange behaviour of Python strip function
Possible Duplicate:
python str.strip strange behavior
I have following piece of code:
st = '55000.0'
st = st.strip('.0')
print st
When i execute, it print only 55 but i expect it to print 55000. I thought that the dot in strip causing this as we usually escape it in Re... | Strange behaviour of Python strip function |
Possible Duplicate:
python str.strip strange behavior
I have following piece of code:
st = '55000.0'
st = st.strip('.0')
print st
When i execute, it print only 55 but i expect it to print 55000. I thought that the dot in strip causing this as we usually escape it in Regular Expression so i also tried st = st.strip(... | [
"You've misunderstood strip() - it removes any of the specified characters from both ends; there is no regex support here.\nYou're asking it to strip both . and 0 off both ends, so it does - and gets left with 55.\nSee the official String class docs for details.\n",
"See the documentation on str.strip, the import... | [
9,
5,
5,
2,
2,
1,
1
] | [] | [] | [
"python",
"string",
"strip"
] | stackoverflow_0007853914_python_string_strip.txt |
Q:
Storing QListWidget column widths
I'm trying to store the widths of a QListWidget QTableWidget's columns. The user might adjust them as he wishes, but closing the app makes everything go back to 'normal' widths.
I've been trying to look for a 'columnResize' or 'resize' signal. But haven't seen something similar t... | Storing QListWidget column widths | I'm trying to store the widths of a QListWidget QTableWidget's columns. The user might adjust them as he wishes, but closing the app makes everything go back to 'normal' widths.
I've been trying to look for a 'columnResize' or 'resize' signal. But haven't seen something similar to it.
| [
"I assume you mean QTreeWidget rather than QListWidget, as the latter does not have columns. The widths of the columns can be retrieved like this:\ncolumns = [tree.columnWidth(index) for index in range(tree.columnCount())]\n\nYou can then save this list when your application closes.\nEDIT\nNB: The same code will wo... | [
0
] | [] | [] | [
"pyqt4",
"python",
"qt4"
] | stackoverflow_0007853894_pyqt4_python_qt4.txt |
Q:
Monitoring filesystem events using Python without other lowlevel libs
Ex, I need to catch remove and add files events on some directory on linux os. I found libs like inotify and python wrappers for them, but if I want to use clear python code should I watch for os.listdir(path) output every sec or are there some ... | Monitoring filesystem events using Python without other lowlevel libs | Ex, I need to catch remove and add files events on some directory on linux os. I found libs like inotify and python wrappers for them, but if I want to use clear python code should I watch for os.listdir(path) output every sec or are there some ways to accomplish such task?
| [
"Source: http://code.activestate.com/recipes/215418-watching-a-directory-tree-on-unix/\nThe watch_directories() function takes a list of paths and a callable object, and then repeatedly traverses the directory trees rooted at those paths, watching for files that get deleted or have their modification time changed. ... | [
1
] | [] | [] | [
"filesystemwatcher",
"linux",
"python"
] | stackoverflow_0007849117_filesystemwatcher_linux_python.txt |
Q:
Python2.6 email.parser.parsestr not working?
The function below is giving me trouble for no reason. But I cant find the bug. The problem is that in the function parsestr(), when I put as an argument a literal string like "Hello world!", sends a email with that string. But, and here is the surprise, if I put the va... | Python2.6 email.parser.parsestr not working? | The function below is giving me trouble for no reason. But I cant find the bug. The problem is that in the function parsestr(), when I put as an argument a literal string like "Hello world!", sends a email with that string. But, and here is the surprise, if I put the variable body, which is also a string, the email has... | [
"parsestr is expecting the headers as well as the body. \nTry this instead:\nfrom email.mime.text import MIMEText\n\nmsg = MIMEText('<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; CHARSET=UTF-8\"></head><body><tt><pre>'\n + body\n + '</pre></tt></body></html>', \"html... | [
2
] | [] | [] | [
"email",
"parsing",
"python"
] | stackoverflow_0007853877_email_parsing_python.txt |
Q:
Django cache.set() causing duplicate key error
My Django site recently started throwing errors from my caching code and I can't figure out why...
I call:
from django.core.cache import cache
cache.set('blogentry', some_value)
And the error thrown by Django is:
TransactionManagementError: This code isn't under tran... | Django cache.set() causing duplicate key error | My Django site recently started throwing errors from my caching code and I can't figure out why...
I call:
from django.core.cache import cache
cache.set('blogentry', some_value)
And the error thrown by Django is:
TransactionManagementError: This code isn't under transaction management
But looking at the PostgreSQL da... | [
"That's a typical race. It checks if the key you inserted exists; if it doesn't, it does an insert, but someone else can insert the key between the count and the insert. Transactions don't prevent this.\nThe code appears to expect this and to try to deal with it, but when I looked at the code to handle this case ... | [
4,
0,
0
] | [] | [] | [
"caching",
"django",
"postgresql",
"python"
] | stackoverflow_0001189541_caching_django_postgresql_python.txt |
Q:
:Python incidence matrix - How to remove Vertex?
Here is my code:
class incidenceMatrix:
def __init__(self, vertexNumber):
self.matrix = []
for k in range(0, vertexNumber):
self.matrix += [[]]
#print self.matrix
def showGraph(self):
i = 1
for row in ... | :Python incidence matrix - How to remove Vertex? | Here is my code:
class incidenceMatrix:
def __init__(self, vertexNumber):
self.matrix = []
for k in range(0, vertexNumber):
self.matrix += [[]]
#print self.matrix
def showGraph(self):
i = 1
for row in self.matrix:
print i, row
i +=... | [
"An answer to your question 2 and 3 is to use enumerate instead of incrementing a counter. For example your showGraph method:\ndef showGraph(self):\n i = 1\n for row in self.matrix:\n print i, row\n i += 1\n\ncan be simplified to:\ndef showGraph(self):\n for i, row in enumerate(self.matrix, 1... | [
1,
1
] | [] | [] | [
"coding_style",
"graph",
"matrix",
"python"
] | stackoverflow_0007852942_coding_style_graph_matrix_python.txt |
Q:
How does the GPL affect macros stored in user data?
I'm considering writing a program in C++ which will embed a Python interpreter for executing macros created by users. Suppose that I'm intending to release my program under the GPLv3. What is not clear to me is what impact this has on the macros and data created ... | How does the GPL affect macros stored in user data? | I'm considering writing a program in C++ which will embed a Python interpreter for executing macros created by users. Suppose that I'm intending to release my program under the GPLv3. What is not clear to me is what impact this has on the macros and data created by the users of my program.
Do any of the requirements of... | [
"No the macros don't become GPL derived works anymore than a 'C' program written on a GPL linux system or with a GPL gcc compiler become GPL.\nIncluding library functions is a little more complicated. If you wrote those library functions then you can let the user do what they want with them. If they are part of the... | [
3,
0
] | [] | [] | [
"c++",
"gpl",
"licensing",
"macros",
"python"
] | stackoverflow_0007827628_c++_gpl_licensing_macros_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.