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:
Store python variables into an xml file
i need to store python variables (int, bool, string, list of bool) into an xml file.
In addition, i need to store a python script inside this xml file.
I explain better:
i want to read a python .py script, store it in the xml file. After that, i want to read it from the xml,... | Store python variables into an xml file | i need to store python variables (int, bool, string, list of bool) into an xml file.
In addition, i need to store a python script inside this xml file.
I explain better:
i want to read a python .py script, store it in the xml file. After that, i want to read it from the xml, and write it to a file(maintaining all the s... | [
"To store a text in an XML node preserving its formatting you can use:\n\na CDATA section, like <![CDATA[text with fancy formatting]]>.\na base-64 encoded string — this is good for binary data, too.\n\n"
] | [
2
] | [] | [] | [
"parsing",
"python",
"store",
"variables",
"xml"
] | stackoverflow_0005763891_parsing_python_store_variables_xml.txt |
Q:
Running Google App Engine from Eclipse on Ubuntu - Permission Denied in /opt
I have Google App Engine installed under my /opt directory on Ubuntu.
After creating a sample Pydev Google App Engine project, I right click the src folder and try to run it.
I get the following error:
/opt/python2.5/bin/python2.5: can't ... | Running Google App Engine from Eclipse on Ubuntu - Permission Denied in /opt | I have Google App Engine installed under my /opt directory on Ubuntu.
After creating a sample Pydev Google App Engine project, I right click the src folder and try to run it.
I get the following error:
/opt/python2.5/bin/python2.5: can't open file '/opt/google_appengine/dev_appserver.py': [Errno 13] Permission denied
... | [
"Looks like you did a chmod +x on the main google_appengine directory but not recursively. Try chmod -R +rx on the directory.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"pydev",
"python",
"ubuntu"
] | stackoverflow_0005759721_google_app_engine_pydev_python_ubuntu.txt |
Q:
Does Django automatically add tests to my application?
I'm using Django within PyDev. I started creating tests for my application. I wrote a single test (in tests.py) and issued python manage.py test my_application. The output was:
ran 188 tests in 5.59s
Why did it run 188 tests while I have only one test?
EDIT:... | Does Django automatically add tests to my application? | I'm using Django within PyDev. I started creating tests for my application. I wrote a single test (in tests.py) and issued python manage.py test my_application. The output was:
ran 188 tests in 5.59s
Why did it run 188 tests while I have only one test?
EDIT: All the tests passed.
| [
"I think it runs tests of all the INSTALLED_APPS. This may include apps from django.contrib or other third party apps that you added. 187 is probably the number of tests that were found for all those apps. Hence 187 + 1 gives the ran 188 tests.\n"
] | [
4
] | [] | [] | [
"django",
"pydev",
"python",
"unit_testing"
] | stackoverflow_0005764182_django_pydev_python_unit_testing.txt |
Q:
How to remove thousands separator dot from the formatted numbers
How can I remove the dot separator from formatted numbers? I'm getting a list from a website by using regular expression:
a = [10.000, 20.000, 25.000]
How can I change them to a = [10000, 20000, 25000]? (They're integers now).
A:
I am assuming wha... | How to remove thousands separator dot from the formatted numbers | How can I remove the dot separator from formatted numbers? I'm getting a list from a website by using regular expression:
a = [10.000, 20.000, 25.000]
How can I change them to a = [10000, 20000, 25000]? (They're integers now).
| [
"I am assuming what you have are strings, since you got them from a website, they should be text at first\n>>> a=[\"10.000\",\"20.000\",\"25.000\"]\n>>> [ i.replace(\".\",\"\") for i in a ]\n['10000', '20000', '25000']\n\n",
"Use replace as this:\nmystring.replace('.', '')\n\n",
"If you have a locale defined on... | [
9,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005763964_python.txt |
Q:
Converting a dict of dicts into a spreadsheet
My data is a dict of dicts like this (but with a lot more fields and names):
{'Jack': {'age': 15, 'location': 'UK'},
'Jill': {'age': 23, 'location': 'US'}}
I want to export it to a spreadsheet like this:
Name Age Location
Jack 15 UK
Jill 23 US
But apparentl... | Converting a dict of dicts into a spreadsheet | My data is a dict of dicts like this (but with a lot more fields and names):
{'Jack': {'age': 15, 'location': 'UK'},
'Jill': {'age': 23, 'location': 'US'}}
I want to export it to a spreadsheet like this:
Name Age Location
Jack 15 UK
Jill 23 US
But apparently csv.DictWriter wants to see a list of dicts like ... | [
"mydict = {'Jack': {'age': 15, 'location': 'UK'}, \n 'Jill': {'age': 23, 'location': 'US'}}\n\ndatalist = []\n\nfor name in mydict:\n data = mydict[name]\n data['name'] = name\n datalist.append(data)\n\nAnd datalist will hold the desired result. Notes:\n\nThis also modifies mydict (adding the 'name' key... | [
4,
1
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0005764831_csv_dictionary_python.txt |
Q:
Iterate through pairs of items in a Python list
Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
And it should produce
[5, 7]
[7, 11]
[11, 4]
[4, 5]
A:
You can zip the list with itself sans the first element:
a ... | Iterate through pairs of items in a Python list | Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
And it should produce
[5, 7]
[7, 11]
[11, 4]
[4, 5]
| [
"You can zip the list with itself sans the first element:\na = [5, 7, 11, 4, 5]\n\nfor previous, current in zip(a, a[1:]):\n print(previous, current)\n\nThis works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doe... | [
199,
122,
62,
18,
8
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0005764782_list_loops_python.txt |
Q:
Python dynamic decorators - why so many wraps?
So I'm still kind of new to Python decorators - I've used them before, but I've never made my own. I'm reading this tutorial (that particular paragraph) and I don't seem to understand why do we need three levels of functions? Why can't we do something like this:
def d... | Python dynamic decorators - why so many wraps? | So I'm still kind of new to Python decorators - I've used them before, but I've never made my own. I'm reading this tutorial (that particular paragraph) and I don't seem to understand why do we need three levels of functions? Why can't we do something like this:
def decorator(func, *args, **kwargs):
return func(*ar... | [
"Well, what would happen if you called that decorator on a function?\n@decorator\ndef foo(): pass\n\nThis code would immediately call foo, which we don't want. Decorators are called and their return value replaces the function. It's the same as saying \ndef foo(): pass\nfoo = decorator(foo)\n\nSo if we have a decor... | [
34,
4
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0005764922_decorator_python.txt |
Q:
How can I set delimiters between two numbers without setting the delimiter between two words on the same line in Python?
I have the following code:
text = 'hello world 2,000 3,000'
text = text.replace(' ', '|')
print text
The output is:
hello|world|2,000|3,000
I want to delimit using '|' but I want the output to... | How can I set delimiters between two numbers without setting the delimiter between two words on the same line in Python? | I have the following code:
text = 'hello world 2,000 3,000'
text = text.replace(' ', '|')
print text
The output is:
hello|world|2,000|3,000
I want to delimit using '|' but I want the output to be in three columns. I don't want the words to be delimited from eachother, just the words from the numbers:
hello world|2,0... | [
"Use regular expression replacement:\nimport re\n\ntext = 'hello world 2,000 3,000'\nprint re.sub(r'\\s(\\d)', '|\\\\1', text)\n\nThis only inserts a pipe mark for things preceded by a space and a digit.\n",
"You have three fields separated by spaces and the first field may also contain spaces. You can use rsplit... | [
3,
2,
1
] | [] | [] | [
"delimiter",
"python"
] | stackoverflow_0005764664_delimiter_python.txt |
Q:
locate element using lxml.html vs BeautifulSoup
I'm scraping an html document using lxml.html; there's one thing I can do in BeautifulSoup, but don't manage to do with lxml.htm. Here it is:
from BeautifulSoup import BeautifulSoup
import re
doc = ['<html>',
'<h2> some text </h2>',
'<p> some more text </p>',
'<tab... | locate element using lxml.html vs BeautifulSoup | I'm scraping an html document using lxml.html; there's one thing I can do in BeautifulSoup, but don't manage to do with lxml.htm. Here it is:
from BeautifulSoup import BeautifulSoup
import re
doc = ['<html>',
'<h2> some text </h2>',
'<p> some more text </p>',
'<table> <tr> <td> A table</td> </tr> </table>',
'<h2> som... | [
"You can use a regular expression in an lxml Xpath, by using EXSLT syntax. For example, given your document, this will select the parent node whose text matches the regexp spe.*al:\nimport re\nimport lxml.html\n\nNS = 'http://exslt.org/regular-expressions'\ntree = lxml.html.fromstring(DOC)\n\n# select sibling tabl... | [
2
] | [] | [] | [
"beautifulsoup",
"lxml",
"python"
] | stackoverflow_0005764721_beautifulsoup_lxml_python.txt |
Q:
Regular expression help
I am trying to create a regex in Python 3 that matches 7 characters (eg. >AB0012) separated by an unknown number of characters then matching another 6 characters(eg. aaabbb or bbbaaa). My input string might look like this:
>AB0012xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxaaaaaaaaaaaa... | Regular expression help | I am trying to create a regex in Python 3 that matches 7 characters (eg. >AB0012) separated by an unknown number of characters then matching another 6 characters(eg. aaabbb or bbbaaa). My input string might look like this:
>AB0012xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>CD0... | [
"Here's a non regular expression approach. Split on \">\" (your data will start from 2nd element onwards), then since you don't care what those 7 characters are, so start checking from 8th character onwards till 14th character. \n>>> string=\"\"\" AB0012xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxaaaaaaaaaaaaa... | [
5,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"regex"
] | stackoverflow_0005764642_python_python_3.x_regex.txt |
Q:
Loading a DER-encoded RSA key using M2Crypto
The method M2Crypto.RSA.RSA().save_key_der() can be used to save a key in the DER format. However, I do not see a corresponding method M2Crypto.RSA.load_key_der() as I would expect.
Is there a way to load a DER-encoded RSA key using M2Crypto?
A:
The PEM format is base... | Loading a DER-encoded RSA key using M2Crypto | The method M2Crypto.RSA.RSA().save_key_der() can be used to save a key in the DER format. However, I do not see a corresponding method M2Crypto.RSA.load_key_der() as I would expect.
Is there a way to load a DER-encoded RSA key using M2Crypto?
| [
"The PEM format is base64-encoded DER data with some additional header and footer lines. You can just read DER as binary, transform it to PEM and pass that to RSA.load_key_string:\nimport base64\nfrom M2Crypto import RSA\n\nTEMPLATE = \"\"\"\n-----BEGIN RSA PRIVATE KEY-----\n%s\n-----END RSA PRIVATE KEY-----\n\"\"\... | [
10
] | [] | [] | [
"m2crypto",
"python"
] | stackoverflow_0005764960_m2crypto_python.txt |
Q:
QtWebkit: loadFinished and loadProgress slots are never executed
Here is a basic PyQt code for Webkit I was trying out.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
class XPrinter(QObject):
def __init__(self):
QObject.__ini... | QtWebkit: loadFinished and loadProgress slots are never executed | Here is a basic PyQt code for Webkit I was trying out.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
class XPrinter(QObject):
def __init__(self):
QObject.__init__(self)
def print_page_info(self, ok):
print ok
de... | [
"Try using the new style signals\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\nfrom PyQt4.QtNetwork import *\n\nclass XPrinter(QObject):\n\n def __init__(self):\n QObject.__init__(self)\n\n def print_page_info(self, ok):\n print ok\n\n def p... | [
4
] | [] | [] | [
"pyqt",
"python",
"qt",
"qtwebkit"
] | stackoverflow_0005765077_pyqt_python_qt_qtwebkit.txt |
Q:
Center fixed-size GtkDrawingArea widget inside of parent widget
I've got a glade layout going, and in it I have a fixed-size GtkDrawingArea. The current relevant part of the hierarchy is:
GtkWindow > GtkVBox > GtkHPaned > GtkViewport > GtkAlignment > GtkFixed > GtkDrawingArea
Currently, the GtkFixed widget draws ... | Center fixed-size GtkDrawingArea widget inside of parent widget | I've got a glade layout going, and in it I have a fixed-size GtkDrawingArea. The current relevant part of the hierarchy is:
GtkWindow > GtkVBox > GtkHPaned > GtkViewport > GtkAlignment > GtkFixed > GtkDrawingArea
Currently, the GtkFixed widget draws at the top-left corner of the GtkViewport.
However, I'd really like i... | [
"In GTK 2.x add a GtkAlignment as the parent of whatever you want to center and align 0.5 (disable fill). \nIn 3.x, there are xalign and yalign properties on all widgets, set to CENTER.\nUpdate: from the sample glade file, the issue is that fill isn't disabled; I was too lazy to look up what the properties were cal... | [
7,
0
] | [] | [] | [
"glade",
"gtk",
"gtkbuilder",
"pygtk",
"python"
] | stackoverflow_0005750761_glade_gtk_gtkbuilder_pygtk_python.txt |
Q:
How to create a transparent frame with visible borders?
I would like to create a transparent frame with visible borders. The code I've written based on hasenj's work of 'shaped-frame' (http://hasenj.wordpress.com/2009/04/14/making-a-fancy-window-in-wxpython/) is as follows. But I still have problem making one. I m... | How to create a transparent frame with visible borders? | I would like to create a transparent frame with visible borders. The code I've written based on hasenj's work of 'shaped-frame' (http://hasenj.wordpress.com/2009/04/14/making-a-fancy-window-in-wxpython/) is as follows. But I still have problem making one. I must have missed something. Could anybody point out what's wro... | [
"It is not very good idea to draw stuff outside MainLoop. You should setup your wx application so it is Event driven. The events EVT_PAINT and EVT_SIZE should be handled. The wx.Timer can be used for basic movement.\nimport wx\n\n#============================================================================= \nclass... | [
2,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005734110_python_wxpython.txt |
Q:
libsvm prediction problem using a generated model
I have a question regarding libsvm predicting accuracy. I generated svm model file using easy.py. Now, when I am trying to predict the test vectors programatically in python, it shows wrongly predicted labels (all 1's) whereas, using easy.py I get an accuracy of 91... | libsvm prediction problem using a generated model | I have a question regarding libsvm predicting accuracy. I generated svm model file using easy.py. Now, when I am trying to predict the test vectors programatically in python, it shows wrongly predicted labels (all 1's) whereas, using easy.py I get an accuracy of 91%.
Each line of my test and train data is in the follow... | [
"One needs to load the scaled input values in order to get the predicted values. The problem got solved. \nBut there seems to be some dis-similarity between easy.py generated predicted labels and the ones when I load a model and predict the labels. \nThere is no proper documentation on libsvm on the web.\n"
] | [
0
] | [] | [] | [
"libsvm",
"python"
] | stackoverflow_0005756427_libsvm_python.txt |
Q:
PyQt4: timers cannot be started from another thread
When I run the following code ...
import sys, time
from PyQt4 import QtCore, QtGui
class WorkThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
for i in range(100):
time.sleep(1) # artificial time delay
print(i)... | PyQt4: timers cannot be started from another thread | When I run the following code ...
import sys, time
from PyQt4 import QtCore, QtGui
class WorkThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
for i in range(100):
time.sleep(1) # artificial time delay
print(i)
test.pbar.setValue(i)
return
class MyApp(QtGui.QW... | [
"As I mentioned in my comment, the error you're seeing provides you exactly with the information it was meant to provide. You are not allowed to invoke QObject::setTimer from a thread different from the one in which the timer was created. Specifically, one version of the code of QObject I found has this code:\nint ... | [
1
] | [] | [] | [
"multithreading",
"progress_bar",
"pyqt4",
"python"
] | stackoverflow_0005765370_multithreading_progress_bar_pyqt4_python.txt |
Q:
Dynamic Time Warping in Python
Does anyone know of a python library that has DTW implementation? mlpy seems to have what I'm looking for, but I can't seem to install it correctly -- currently awaiting replies from the mailing list so I thought I would scope out other libraries.
A:
Had to chime in on this one. To... | Dynamic Time Warping in Python | Does anyone know of a python library that has DTW implementation? mlpy seems to have what I'm looking for, but I can't seem to install it correctly -- currently awaiting replies from the mailing list so I thought I would scope out other libraries.
| [
"Had to chime in on this one. To follow up with C's response, here's an implementation that is geared more towards interfacing with data generated in NumPy. I find this to be considerably more useful since typically I'm generating data in Python and want to interface with R resources.\nimport numpy as np\n\nimport ... | [
24,
10
] | [] | [] | [
"python"
] | stackoverflow_0005695388_python.txt |
Q:
How to serialize a RawQuerySet in Django?
I am facing the problem that I need to serialize a RawQuerySet. It doesn't have the values function. I also added a decimal an annotation to every object, which is a count of a field.
Example code:
cow_query = """SELECT cow.* (count(leg.id) / 4) as 'percentage' FROM cow JO... | How to serialize a RawQuerySet in Django? | I am facing the problem that I need to serialize a RawQuerySet. It doesn't have the values function. I also added a decimal an annotation to every object, which is a count of a field.
Example code:
cow_query = """SELECT cow.* (count(leg.id) / 4) as 'percentage' FROM cow JOIN leg ON leg.cow_id = cow.id;"""
cows = Cow.... | [
"How about simplejson.dumps([dict(cow.__dict__) for cow in cows])? If your Cow model only has simple string or integer values this should work, otherwise you'll need to handle your more complex types manually (e.g., DateTimeField need to be unicode-ed for simplejson).\n"
] | [
5
] | [] | [] | [
"django",
"json",
"python",
"serialization"
] | stackoverflow_0005764348_django_json_python_serialization.txt |
Q:
UnboundLocalError with operators and functional programming in python (methods work fine)
prog1.py:
def runf(f):
f()
def main():
l = [0]
def f():
l.append(1)
runf(f)
print(l)
main()
Gives me (as expected):
[0, 1]
prog2.py:
def runf(f):
f()
def main():
l = [0]
def f():
... | UnboundLocalError with operators and functional programming in python (methods work fine) | prog1.py:
def runf(f):
f()
def main():
l = [0]
def f():
l.append(1)
runf(f)
print(l)
main()
Gives me (as expected):
[0, 1]
prog2.py:
def runf(f):
f()
def main():
l = [0]
def f():
l += [1] # <-- Only difference
runf(f)
print(l)
main()
Gives me:
Traceback (mo... | [
"The execution model reference of Python (section 4.1) states:\n\nIf a name is bound in a block, it is a\n local variable of that block.\n\nWhat happens is that l += [1], for the sake of binding is equivalent to l = l + [1] which means l is bound inside f. Here's another interesting document reference:\n\nAssignm... | [
4
] | [] | [] | [
"functional_programming",
"operators",
"python"
] | stackoverflow_0005766314_functional_programming_operators_python.txt |
Q:
PyQt4 problem with xml database browser (treeview, singals and insertplaintext)
I'm writing a database browser application with PyQt4 and because I'm new to Qt, I have some problems. I have most functionalities already written in python but know I'm trying to implement them with PyQt4 GUI.
First of all my applicat... | PyQt4 problem with xml database browser (treeview, singals and insertplaintext) | I'm writing a database browser application with PyQt4 and because I'm new to Qt, I have some problems. I have most functionalities already written in python but know I'm trying to implement them with PyQt4 GUI.
First of all my application now looks like this:
Browser
In these catalogues I have xml files which I would l... | [
"Consider using the new-style connection mechanism provided by PyQt:\nself.ui.treeView.clicked.connect(self.ui.plainTextEdit.paste)\n\nNow, paste is a method accepting a single argument, and this argument is of the type the clicked signal of self.ui.treeView sends. Dissect if from there, as you wish.\n\nHow can I c... | [
0
] | [] | [] | [
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0005766456_pyqt4_python_qt_qt4.txt |
Q:
problem with import qt in python
I want to use qt with python.
"import qt" return me :"ImportError: No module named qt". I already instaled pyqt.
what I hve to install in order to activate "import qt"
Thank You
A:
The current PyQt comes in the PyQt4 package, which has several modules. You almost always need to... | problem with import qt in python | I want to use qt with python.
"import qt" return me :"ImportError: No module named qt". I already instaled pyqt.
what I hve to install in order to activate "import qt"
Thank You
| [
"The current PyQt comes in the PyQt4 package, which has several modules. You almost always need to start with:\nfrom PyQt4 import QtCore\nfrom PyQt4 import QtGui\n\nAdd other imports as necessary if you need additional sub-modules of PyQt (like QtNetwork, QtSql etc).\n\nTip for the future: find the lib/site-package... | [
12,
3
] | [] | [] | [
"python"
] | stackoverflow_0005766539_python.txt |
Q:
python QtWebkit: nextSibing doesn't return null or None
Below is the code snippet which I use to get a list of all children of the given node. But the the nextSibling() never returns null so the while loop executes forever. Please help.
children = [ ]
children.append(documentElement.firstChild())
curr_node = ch... | python QtWebkit: nextSibing doesn't return null or None | Below is the code snippet which I use to get a list of all children of the given node. But the the nextSibling() never returns null so the while loop executes forever. Please help.
children = [ ]
children.append(documentElement.firstChild())
curr_node = children[0]
while curr_node.nextSibling():
print curr_nod... | [
"As i understand nextSibling will always return a QWebElement, however you can check if that is a null element using isNull()\nwhile not curr_node.nextSibling().isNull():\n print curr_node, len(children)\n children.append(curr_node.nextSibling())\n curr_node = curr_node.nextSibling()\n\nYou can check th... | [
2
] | [] | [] | [
"pyqt",
"python",
"qt",
"qtwebkit"
] | stackoverflow_0005766469_pyqt_python_qt_qtwebkit.txt |
Q:
List sorting/modify problem
Initially, I wasn't sure whether this was the appropriate place for this question, but after reading through the FAQ I feel fairly confident the topic is acceptable.... Furthermore I wasn't sure if this would be classified as a particular type of problem (eg. a knapsack problem), thus, ... | List sorting/modify problem | Initially, I wasn't sure whether this was the appropriate place for this question, but after reading through the FAQ I feel fairly confident the topic is acceptable.... Furthermore I wasn't sure if this would be classified as a particular type of problem (eg. a knapsack problem), thus, the title is rather vague. I'm so... | [
"The following code uses a brute force approach (it is not optimized), but is quite robust:\n#!usr/bin/env python\n\nimport random\nimport collections\n\n# Candidates:\ncandidates = ['John', 'Max', 'Philip', 'Eric', 'Jane']\n\ndef simul_ballots(num_voters):\n \"\"\"\n Returns the (random) ballots of num_voters ... | [
2,
1,
1,
1
] | [] | [] | [
"algorithm",
"list",
"python"
] | stackoverflow_0005762671_algorithm_list_python.txt |
Q:
How to implement threaded socket.recv() in python?
I have a number of devices from which i need to get status updates. A socket object is all I have, and socket.recv() is all I need to get the status. Put into a single threaded application, no problems occur:
class Device:
def receive(self):
log.debug(... | How to implement threaded socket.recv() in python? | I have a number of devices from which i need to get status updates. A socket object is all I have, and socket.recv() is all I need to get the status. Put into a single threaded application, no problems occur:
class Device:
def receive(self):
log.debug("receive waiting: %r", self.device_id)
try:
... | [
"How many different sockets do you have to read from?\n\nIf the answer is \"just one\", then use just one thread. Adding another helps you in no way and only complicates your life, as you found out.\nIf the answer is \"several\", than one way to organize this is indeed to have a thread per socket. recv is a blockin... | [
0,
0
] | [] | [] | [
"locking",
"multithreading",
"python",
"sockets"
] | stackoverflow_0005764534_locking_multithreading_python_sockets.txt |
Q:
How to copy dictionaries with matching values for a given key from list to new list?
Possible Duplicate:
Copy dictionaries with matching values for a given key
With an interface like a = copyf(dictlist, key, valuelist).
>>> dictlist = [{'first': 'James',
'last': 'Joule'},
{'first... | How to copy dictionaries with matching values for a given key from list to new list? |
Possible Duplicate:
Copy dictionaries with matching values for a given key
With an interface like a = copyf(dictlist, key, valuelist).
>>> dictlist = [{'first': 'James',
'last': 'Joule'},
{'first': 'James',
'last': 'Watt'},
{'first': 'Christian',
... | [
"x = [d for d in dictlist if d['first'] in valuelist]\n\n",
"This alternative returns a copy of the dictionaries:\ndef copyf(dictlist, key, valuelist)\n return [copy.deepcopy(dictio) for dictio in dictlist if dictio[key] in valueList]\n\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0005766820_python.txt |
Q:
processing opencv image pixels quickly using python interface
Using python-interface for OpenCV, one can easily access the pixel of image using [] operator,like this:
img = cv.LoadImage('test.jpg')
pixel = img[10,10]
variable pixel here is a python tuple object like (10,20,30) (3 channels for example), it's not v... | processing opencv image pixels quickly using python interface | Using python-interface for OpenCV, one can easily access the pixel of image using [] operator,like this:
img = cv.LoadImage('test.jpg')
pixel = img[10,10]
variable pixel here is a python tuple object like (10,20,30) (3 channels for example), it's not very convenient to process computation since tuple type does not sup... | [
"You could use cv2array()/array2cv() functions from adaptors.py in the opencv source distribution and perform all your computation using numpy arrays. 255 - imgarr works in this case. Example (stripped-down version of cv2array() for read-only arrays):\nassert isinstance(img, cv.iplimage) and img.depth == cv.IPL_DEP... | [
3
] | [] | [] | [
"numpy",
"opencv",
"python"
] | stackoverflow_0005762906_numpy_opencv_python.txt |
Q:
Python Reference Subclass in a Static Method
This is going to be difficult to explain, but what I'm trying to do is create a Base object to base other objects on. The Base class handles shared tasks so that subclasses don't need to keep implementing them. However, I also need a static/class method which creates in... | Python Reference Subclass in a Static Method | This is going to be difficult to explain, but what I'm trying to do is create a Base object to base other objects on. The Base class handles shared tasks so that subclasses don't need to keep implementing them. However, I also need a static/class method which creates instances of the classes. So for example, this is my... | [
"You want a class method instead, that will get the class object as its first parameter so that you can build an instance of that specific class:\n@classmethod\ndef get_objects(cls, service, references, as_dict=False):\n \"\"\"\n More efficient way to get multiple objects at once. Requires the service\n in... | [
13
] | [] | [] | [
"inheritance",
"introspection",
"python"
] | stackoverflow_0005767308_inheritance_introspection_python.txt |
Q:
Applying a method with no return value to each element of a list
Is there a way to use methods with no return value such as random.shuffle in a list comprehension?
>>> import pprint
>>> import random
>>>
>>> L = [ random.shuffle(range(5)) for x in range(5)]
>>>
>>> print L
[None, None, None, None, None]
This is... | Applying a method with no return value to each element of a list | Is there a way to use methods with no return value such as random.shuffle in a list comprehension?
>>> import pprint
>>> import random
>>>
>>> L = [ random.shuffle(range(5)) for x in range(5)]
>>>
>>> print L
[None, None, None, None, None]
This is the for loop that applies the random.shuffle method to each item of m... | [
"No - list comprehensions are meant to be use with functions having return values. It's how their semantics are defined:\n\nList comprehensions provide a concise\n way to create lists without resorting\n to use of map(), filter() and/or\n lambda. The resulting list definition\n tends often to be clearer than li... | [
13,
8
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0005766816_list_comprehension_python.txt |
Q:
Embedded for loop with regex
def find_string(header,file_1,counter):
ab = re.compile(str(header))
for line in file_1:
if re.search(ab,line) !=None:
print line
counter+=1
return counter
file_1 = open("text_file_with_headers.txt",'r')
header_array = []
header_array.append("header1")
header_array.... | Embedded for loop with regex | def find_string(header,file_1,counter):
ab = re.compile(str(header))
for line in file_1:
if re.search(ab,line) !=None:
print line
counter+=1
return counter
file_1 = open("text_file_with_headers.txt",'r')
header_array = []
header_array.append("header1")
header_array.append("header2")
# ...
counter =... | [
"Because when the loop for line in file_1: has ended for the first header, the file's pointer is at the end of the file. You must move this pointer to the file's beginning again, that is done with function seek() . You must add seek(0,0) like that\ncounter = 0 \nfor header in header_array:\n counter = find_strin... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005767535_python.txt |
Q:
How do I redirect Django commands using PyDev?
I would like to run the following Django command (to dump the contents of my database into a text file):
python manage.py dumpdata my_app > data.json
I'm using the Django framework within PyDev as an Eclipse plugin. Therefore, in order to run the above command in PyD... | How do I redirect Django commands using PyDev? | I would like to run the following Django command (to dump the contents of my database into a text file):
python manage.py dumpdata my_app > data.json
I'm using the Django framework within PyDev as an Eclipse plugin. Therefore, in order to run the above command in PyDev I go to "Custom command" and insert dumpdata my_a... | [
"\nOpen Eclipse and go to menu Run > Run configurations\nClick on Pydev Django and then the \"New\" icon to create a new launch configuration\nTab main: select the project and main module (manage.py)\nTab interpreter: select which interpreter will run manage.py\nTab arguments: write dumpdata my_app in Program argum... | [
3
] | [] | [] | [
"django",
"eclipse",
"pydev",
"python",
"redirect"
] | stackoverflow_0005766643_django_eclipse_pydev_python_redirect.txt |
Q:
Appengine GET parameters
I am not really familiar with Python and am trying to transform one of my php webapps to python. Currently I am running the app on localhost using the appengine launcher and this is what I am trying to do.
I am trying to get a list of all the parameters posted to the url and then submit th... | Appengine GET parameters | I am not really familiar with Python and am trying to transform one of my php webapps to python. Currently I am running the app on localhost using the appengine launcher and this is what I am trying to do.
I am trying to get a list of all the parameters posted to the url and then submit them to a page and get its conte... | [
"x = MyHandler()\nprint x.get() \n\nThis is not a typical part of an AppEngine app. You don't use print to return output to the browser.\nWhen you create a new app in AppEngineLauncher it gives you a skeleton project that looks like this:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp i... | [
6,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005767678_google_app_engine_python.txt |
Q:
BeautifulStoneSoup AttributeError: 'NavigableString' object has no attribute 'subtag'
I'm trying to use BeautifulSoup to parse some XML that looks like
<a>
<b>
<c>
<d attr="x">
<e>
</e>
<name>
</name>
</d>
</c>
<c>
...
<c>
</b>
</a>
but I can't... | BeautifulStoneSoup AttributeError: 'NavigableString' object has no attribute 'subtag' | I'm trying to use BeautifulSoup to parse some XML that looks like
<a>
<b>
<c>
<d attr="x">
<e>
</e>
<name>
</name>
</d>
</c>
<c>
...
<c>
</b>
</a>
but I can't figure out how to access e or name in a loop. This works:
print soup.a.b.c.d.e
but this d... | [
"You get an AttributeError because BSS returns NavigableStrings when you loop over Tag instances. Maybe you want to try: \nsoup.a.b.c.findChildren()\n#[<d attr=\"x\">\n#<e>\n#</e>\n#<name>\n#</name>\n#</d>, <e>\n#</e>, <name>\n#</name>]\n\nRegarding the issue w/ name: it is specified as an attribute, but you can in... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"xml"
] | stackoverflow_0005767552_beautifulsoup_python_xml.txt |
Q:
python.select, sending lists as arguments
r=select([f,s],[],[])[0][0]. Does this mean wait until the file pointed to by f AND s is ready for readiing or f OR s is ready for reading?
A:
The latter, although both may be returned if they're both ready for reading.
| python.select, sending lists as arguments | r=select([f,s],[],[])[0][0]. Does this mean wait until the file pointed to by f AND s is ready for readiing or f OR s is ready for reading?
| [
"The latter, although both may be returned if they're both ready for reading.\n"
] | [
2
] | [] | [] | [
"low_level_io",
"python"
] | stackoverflow_0005767905_low_level_io_python.txt |
Q:
bug in python interactive mode?
i got the syntax error reaction while try coding like bellow in python interactive mode.
>>> while True:
... reply = raw_input('enter text:')
... if reply == 'stop':
... break
... print reply
... print 'bye'
File "<stdin>", line 6
print reply
^
SyntaxError: i... | bug in python interactive mode? | i got the syntax error reaction while try coding like bellow in python interactive mode.
>>> while True:
... reply = raw_input('enter text:')
... if reply == 'stop':
... break
... print reply
... print 'bye'
File "<stdin>", line 6
print reply
^
SyntaxError: invalid syntax
>>>
but it executed no... | [
"I think when you return to the first column of indentation this must be left empty its to indicate that the block you opened is now ready to be interpreted.\nIf you put this in a function an invoke it after it works properly.\n In [66]: def fun():\n ....: while True:\n ....: reply = raw_input(\"... | [
2
] | [] | [] | [
"interactive",
"python"
] | stackoverflow_0005767910_interactive_python.txt |
Q:
How do I remove a \ from a string in python
I'm having trouble getting a replace() to work
I've tried my_string.replace('\\', '') and re.sub('\\', '', my_string), but neither one works.
I thought \ was the escape code for backslash, am I wrong?
The string in question looks like
'<2011315123.04C6DACE618A7C2763810@... | How do I remove a \ from a string in python | I'm having trouble getting a replace() to work
I've tried my_string.replace('\\', '') and re.sub('\\', '', my_string), but neither one works.
I thought \ was the escape code for backslash, am I wrong?
The string in question looks like
'<2011315123.04C6DACE618A7C2763810@\x82\xb1\x82\xea\x82\xa9\x82\xe7\x8c\xa9\x82\xa6\... | [
"You don't have any backslashes in your string. What you don't have, you can't remove.\nConsider what you are showing as '\\x82' ... this is a one-byte string.\n>>> s = '\\x82'\n>>> len(s)\n1\n>>> ord(s)\n130\n>>> hex(ord(s))\n'0x82'\n>>> print s\né # my sys.stdout.encoding is 'cp850'\n>>> print repr(s)\n'\\x82'\n>... | [
8,
2
] | [] | [] | [
"backslash",
"python",
"replace",
"string"
] | stackoverflow_0005767954_backslash_python_replace_string.txt |
Q:
In python how do you deal with other encodings in domain names
I'm trying to parse domain names from the Message-ID field of an email that's been loaded from a file and compare it to the domain of the from field to see how well it matches up. Then I compare the distance using nltk.edit_distance().
I'm using
re.se... | In python how do you deal with other encodings in domain names | I'm trying to parse domain names from the Message-ID field of an email that's been loaded from a file and compare it to the domain of the from field to see how well it matches up. Then I compare the distance using nltk.edit_distance().
I'm using
re.search('@[\[\]\w+\.]+',mail['Message-ID']).group()[1:]
but one spam me... | [
"You can try the chardet project, which uses an algorithm to guess the character encoding:\nimport chardet\n\ntext = '<2011315123.04C6DACE618A7C2763810@\\x82\\xb1\\x82\\xea\\x82\\xa9\\x82\\xe7' + \\\n '\\x8c\\xa9\\x82\\xa6\\x82\\xe9\\x82\\xbe\\x82\\xeb\\x82\\xa4>'\ncset = chardet.detect(text)\nprint cset\nencodi... | [
1
] | [] | [] | [
"email_spam",
"python",
"string",
"string_literals"
] | stackoverflow_0005767734_email_spam_python_string_string_literals.txt |
Q:
Sort a list of objects by an attribute given a string of the name of the attribute
So far:
def sort_by(column):
for order in sorted(orders, key=lambda order: order.column):
...
list('ratio')
Clearly both ratio and 'ratio' are illegal arguments here. I think Django and most other python web frameworks... | Sort a list of objects by an attribute given a string of the name of the attribute | So far:
def sort_by(column):
for order in sorted(orders, key=lambda order: order.column):
...
list('ratio')
Clearly both ratio and 'ratio' are illegal arguments here. I think Django and most other python web frameworks do something like this internally. Is there a pattern for this?
| [
"sorted(..., key=operator.attrgetter(column))\n\n",
"def arrange_list(column):\n for order in sorted(orders, key=lambda order: order.__dict__[column]):\n ...\n\nshould do the trick.\n"
] | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005768069_python.txt |
Q:
Does a syntax for this exist? In any language?
It seems pretty common to me to have an argument, in a dynamically typed language that is either an Object or a key to lookup that object. For instance when I'm working with a database I might have a method getMyRelatedStuff(person)
All I really need to lookup the rel... | Does a syntax for this exist? In any language? | It seems pretty common to me to have an argument, in a dynamically typed language that is either an Object or a key to lookup that object. For instance when I'm working with a database I might have a method getMyRelatedStuff(person)
All I really need to lookup the related stuff is the id of the person so my method coul... | [
"I study programming languages for a living. I've never seen a language with a built-in syntax for that operation. I'm not even sure what you want such a syntax to look like, especially since you can define a function for any of these patterns.\nPeople who like extensible syntax tend to define Lisp macros :-)\n",... | [
9,
3,
2,
1,
1,
0
] | [] | [] | [
"default",
"programming_languages",
"python",
"syntax"
] | stackoverflow_0002926565_default_programming_languages_python_syntax.txt |
Q:
Python - display different output if the input is a letter or a number
I want to print the result of the equation in my if statement if the input is a digit and print "any thing" if it is a letter.
I tried this code, but it's not working well. What is wrong here?
while 1:
print '\tConvert ciliuse to fehrenhit\... | Python - display different output if the input is a letter or a number | I want to print the result of the equation in my if statement if the input is a digit and print "any thing" if it is a letter.
I tried this code, but it's not working well. What is wrong here?
while 1:
print '\tConvert ciliuse to fehrenhit\n'
temp = input('\nEnter the temp in C \n\t')
f = ((9/5)*temp +32)
... | [
"You need to go through your code line by line and think about what type you expect each value to be. Python does not automatically convert between, for example, strings and integers, like some languages do, so it's important to keep types in mind.\nLet's start with this line:\ntemp = input('\\nEnter the temp in C ... | [
4,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005768018_python.txt |
Q:
Translation from Python to CIL(C Intermediate Language)
I have worked on the static analysis on Python source code recently.
There is already a static analyzer written in Ocaml for CIL(C Intermediate Language) in our group. We want to reuse this analyzer, so our ideal approach is to translate Python to CIL.
Curren... | Translation from Python to CIL(C Intermediate Language) | I have worked on the static analysis on Python source code recently.
There is already a static analyzer written in Ocaml for CIL(C Intermediate Language) in our group. We want to reuse this analyzer, so our ideal approach is to translate Python to CIL.
Currently, I use Python built-in ast module to parse Python to Pyth... | [
"I don't think this is going to work very well. CIL is essentially just the C langauge. For your trick to work, you have translate Python completely to C... but the langauges have very dissimilar concepts. How will you model Python objects? Continuations? Dynamic load? Runtime typing? Infinite precision arithmet... | [
3
] | [] | [] | [
"abstract_syntax_tree",
"cil",
"ocamllex",
"ocamlyacc",
"python"
] | stackoverflow_0005768406_abstract_syntax_tree_cil_ocamllex_ocamlyacc_python.txt |
Q:
Python: Problem with raw_input, turning the value I get into an array
I'm having issues with raw_input again, this time trying to turn the value I get into a list. Here is my code:
original = raw_input("Type is your input? ")
original_as_array = list('original')
print original_as_array
for i in range(0,len(origina... | Python: Problem with raw_input, turning the value I get into an array | I'm having issues with raw_input again, this time trying to turn the value I get into a list. Here is my code:
original = raw_input("Type is your input? ")
original_as_array = list('original')
print original_as_array
for i in range(0,len(original)):
print i
my print original_as_array literally prints ['o', 'r', 'i... | [
"Quotes form a string literal.\noriginal_as_array = list(original)\n\n",
"original = raw_input(\"Type is your input? \")\noriginal_as_array = list(original) # no quotes. If you put quotes, you are turning it into a string.\nprint original_as_array\nfor i in original_as_array: # this is shorter way to iterate and ... | [
3,
1,
1
] | [] | [] | [
"list",
"python",
"raw_input"
] | stackoverflow_0005768594_list_python_raw_input.txt |
Q:
How to disallow spaces in between literals in pyparsing?
grammar = Literal("from") + Literal(":") + Word(alphas)
The grammar needs to reject from : mary and only accept from:mary i.e. without any interleaving spaces. How can I enforce this in pyparsing ? Thanks
A:
Can you use Combine?
grammar = Combine(Literal(... | How to disallow spaces in between literals in pyparsing? | grammar = Literal("from") + Literal(":") + Word(alphas)
The grammar needs to reject from : mary and only accept from:mary i.e. without any interleaving spaces. How can I enforce this in pyparsing ? Thanks
| [
"Can you use Combine?\ngrammar = Combine(Literal(\"from\") + Literal(\":\") + Word(alphas))\n\nSo then:\nEDIT in response to your comment.\nReally?\n>>> grammar = pyparsing.Combine(Literal(\"from\") + Literal(\":\") + Word(pyparsing.alphas))\n>>> grammar.parseString('from : mary')\nTraceback (most recent call last)... | [
7
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0005768576_pyparsing_python.txt |
Q:
Understanding printing bytes in the Python interactive interpreter
I've stumbled upon what I can only describe as a bug in the interactive interpreter for Python. While the bug is rather inconsequential I felt that it was an interesting problem, and a good chance to learn something about python, low level computin... | Understanding printing bytes in the Python interactive interpreter | I've stumbled upon what I can only describe as a bug in the interactive interpreter for Python. While the bug is rather inconsequential I felt that it was an interesting problem, and a good chance to learn something about python, low level computing, and debugging.
The problem occurs here:
pic = open("blurry.jpg", "rb"... | [
"This is not a bug with Python, this is your terminal switching to an alternate charset. Run reset at the shell prompt to fix this.\n"
] | [
7
] | [] | [] | [
"ansi_escape",
"byte",
"python",
"terminal"
] | stackoverflow_0005768656_ansi_escape_byte_python_terminal.txt |
Q:
Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll
I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:
error MSVCP90.dll: No suc... | Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll | I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:
error MSVCP90.dll: No such file or directory.
I have already downloaded and installed the VC++ redistributab... | [
"Yes you should have it. You have to exclude it from py2exe.\noptions = {\n 'py2exe': {\n 'dll_excludes': [\n 'MSVCP90.dll'\n ]\n }\n}\n\nsetup(windows=[\"main.py\"], options=options)\n\n",
"what you need is to go to microsoft's download site and get visual C++ 2008 redistributed ... | [
8,
1
] | [] | [] | [
"dll",
"gui2exe",
"py2exe",
"python",
"wxwidgets"
] | stackoverflow_0001605006_dll_gui2exe_py2exe_python_wxwidgets.txt |
Q:
Trying to call an element in a 2-d array in a while loop (python/numpy)
I am trying to create a program that reduces any given matrix to reduced row echelon form.
What I'm trying to is to divide each entry in the row by the leading number. For example, say I have:
[ [3, 4, 5], [ 1, 2, 3] ] # a 2-d array. which g... | Trying to call an element in a 2-d array in a while loop (python/numpy) | I am trying to create a program that reduces any given matrix to reduced row echelon form.
What I'm trying to is to divide each entry in the row by the leading number. For example, say I have:
[ [3, 4, 5], [ 1, 2, 3] ] # a 2-d array. which gives:
[ 3, 4, 5]
[ 1, 2, 3]
I'm trying to turn that into [ 1 , 4/3, 5/3]. H... | [
"Since the question mentions numpy, here is a solution without using loops: \nimport numpy\na = numpy.array([[3.,4.,5.],[1.,2.,3.]])\na = a/a[:,0:1]\nprint a\n\ngives the required result \narray([[ 1. , 1.33333333, 1.66666667],\n [ 1. , 2. , 3. ]])\n\nThere are a few subtleti... | [
3,
0,
0
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0005768597_matrix_numpy_python.txt |
Q:
python opencv: no image
I am trying to capture from a Sony Handicam DCR-HC38, running the code below, and passing [-1 .. 3] to the CaptureFromCAM function. The code runs, but I get no image. Do I need to "wrap" the camera somehow? Skype recognizes the camera, but python/opencv won't. I'm running Windows Vista ... | python opencv: no image | I am trying to capture from a Sony Handicam DCR-HC38, running the code below, and passing [-1 .. 3] to the CaptureFromCAM function. The code runs, but I get no image. Do I need to "wrap" the camera somehow? Skype recognizes the camera, but python/opencv won't. I'm running Windows Vista if that helps any.
import cv
... | [
"try increasing the delay on the cv.WaitKey\n",
"not sure if you fixed it or not. But the solution I figured out is by checking which driver OpenCv is trying to access... I have both v4l1 and v4l2, however I can only access device /dev/video0 by using gstreamer codec and the v4l2 driver on my lenovo x200 (interna... | [
3,
2
] | [] | [] | [
"camera",
"capture",
"opencv",
"python"
] | stackoverflow_0003244409_camera_capture_opencv_python.txt |
Q:
How to assign an operation like sum or substitute, etc., to a variable
I want to do something like
class A:
def __init__( self, left, right, op ):
self.left = left
self.right = right
self.op = op
def calculate( self ):
self.number = op( self.left, self.right )
return... | How to assign an operation like sum or substitute, etc., to a variable | I want to do something like
class A:
def __init__( self, left, right, op ):
self.left = left
self.right = right
self.op = op
def calculate( self ):
self.number = op( self.left, self.right )
return self.number
and use it, for example, like this:
a = A( 1, 2, + )
a2 = A( 2... | [
"See the operator module.\na = A( 1, 2, operator.add )\n\n",
"Another way to do this would be to supply a lambda function as the third parameter:\na = A( 1, 2, lambda x,y: x + y)\nb = A( 1, 2, lambda x,y: x * y)\n\nThis would allow you to support more complex operations, not present in the operator module.\n"
] | [
9,
5
] | [] | [] | [
"python"
] | stackoverflow_0005769696_python.txt |
Q:
Python assert on property set
Is it possible to make a property assert when it is changed (for the purpose of debugging)?
class MyClass(object):
def set_my_property(self, value):
self.my_property = value
# TODO: mark my_property so that if it gets set again, an assert
# is triggered
c ... | Python assert on property set | Is it possible to make a property assert when it is changed (for the purpose of debugging)?
class MyClass(object):
def set_my_property(self, value):
self.my_property = value
# TODO: mark my_property so that if it gets set again, an assert
# is triggered
c = MyClass()
c.set_my_property(4)
#... | [
"EDIT:\nIs this what you're looking for? \nclass MyClass(object):\n def __init__(self):\n self.trigger = False\n self._my_property = 0\n\n def set_my_property(self, value):\n if self.trigger:\n raise Exception(\"WHOOPS!\")\n self._my_property = value\n # TODO: ma... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005769660_python.txt |
Q:
What is a post_form_id? (using python urllib2)
I'm interested in writing a python script to log into Facebook and then request some data (mainly checking the inbox). There are few nice examples out there on how to do this. One interesting script i found over here and there is some nice example on stackoverflow its... | What is a post_form_id? (using python urllib2) | I'm interested in writing a python script to log into Facebook and then request some data (mainly checking the inbox). There are few nice examples out there on how to do this. One interesting script i found over here and there is some nice example on stackoverflow itself.
Now i could just copy-paste some of the code i ... | [
"I don't understand why you are trying to \"hack\" this ... \nThere is an official api from facebook to read the mailbox of a user, and you need to ask the \"read_mailbox\" permission for this.\nSo I advice you to check my post here on how to use facebook and python/django together, and how to login to facebook fro... | [
1
] | [] | [] | [
"authentication",
"facebook",
"python",
"urllib2"
] | stackoverflow_0005767546_authentication_facebook_python_urllib2.txt |
Q:
Soap Client using Suds
Soap call in Python
Hi above is my previous question regarding soap. In there i am passing a 1D array. Now my problem is i need to pass the 2D array to the following Soap schema.
Request Schema
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSch... | Soap Client using Suds |
Soap call in Python
Hi above is my previous question regarding soap. In there i am passing a 1D array. Now my problem is i need to pass the 2D array to the following Soap schema.
Request Schema
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="ht... | [
"You pass invalid arguments to CalculateWeb2DObjectArray() function.\nTo find out what type of arguments CalculateWeb2DObjectArray() accepts, you could add to your script:\nprint client\n\nThe output contains:\nCalculateWeb2DObjectArray(xs:string HCID,\n ArrayOfArrayOfAnyType jaggedobjDataM... | [
10
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0005769128_python_soap_suds.txt |
Q:
python django Localization
I'm using django Internationalization current now.
When i use in template such as
{% trans "i love you" %}
it works fine.
But when i define it in python file
_("i love you")
it still outputs the English word.
If I replace _("i love you") with "我爱你", it says:
SyntaxError: Non-ASCII c... | python django Localization | I'm using django Internationalization current now.
When i use in template such as
{% trans "i love you" %}
it works fine.
But when i define it in python file
_("i love you")
it still outputs the English word.
If I replace _("i love you") with "我爱你", it says:
SyntaxError: Non-ASCII character '\xe4'
| [
"you shouldn't replace _(\"i love you\") in your views.py but in the .po file generated by django-admin.py compilemessages (see here).\nhope it helps\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005769567_django_python.txt |
Q:
Django: accessing model attributes
Apologies for the noobish question, I am completely new to both Python and Django and trying to make my first app.
I have a simple class
class About(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
date = models.DateTimeField(... | Django: accessing model attributes | Apologies for the noobish question, I am completely new to both Python and Django and trying to make my first app.
I have a simple class
class About(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
date = models.DateTimeField('date added')
to which I've added a sin... | [
"In your case, about is a QuerySet object, not an instance of your model. Try\nprint about[0].title\n\nAlternatively, use get() to retrieve a single instance of the model:\nabout = About.objects.get(id=1)\nprint about.title\n\n",
"Filter returns a QuerySet and not the single object you are looking for. Use get in... | [
16,
2,
1,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005769678_django_django_models_python.txt |
Q:
Python: Using dictwriter, but setting value types?
I'm just beginning at Python and stackoverflow, forgive me for any mistakes...
I'm trying to use dictreader and dictwriter for a project of mine. Basically I have a dictionary of songs, which contains many keys (names, artists, play count, song tags for example).... | Python: Using dictwriter, but setting value types? | I'm just beginning at Python and stackoverflow, forgive me for any mistakes...
I'm trying to use dictreader and dictwriter for a project of mine. Basically I have a dictionary of songs, which contains many keys (names, artists, play count, song tags for example).
The problem is that when I feed dictwriter into a file,... | [
"If your CSV consists of the representation of basic Python types then you can use ast.literal_eval() to convert it to Python types.\n"
] | [
2
] | [] | [] | [
"csv",
"python",
"types"
] | stackoverflow_0005769961_csv_python_types.txt |
Q:
python path problem: ImportError when calling zodbconvert (FreeBSD 8.1)
I guess this is a python path problem (on FreeBSD 8.1).
Im trying to convert a Data.fs to Postgresql using zodbconvert. Ive downloaded RelStorage-1.5.0b2 and is running:
/usr/local/Plone/Python-2.6/bin/python zodbconvert.py fstodb.conf
, to u... | python path problem: ImportError when calling zodbconvert (FreeBSD 8.1) | I guess this is a python path problem (on FreeBSD 8.1).
Im trying to convert a Data.fs to Postgresql using zodbconvert. Ive downloaded RelStorage-1.5.0b2 and is running:
/usr/local/Plone/Python-2.6/bin/python zodbconvert.py fstodb.conf
, to use the version that Plone is running with.
The error I get:
Traceback (most r... | [
"If you are using buildout (I do hope you are) the easiest way to get all the zodbconvert dependencies properly included in the python path is to have buildout create the script for you:\n[buildout]\n...\nparts =\n ...\n zodbconvert\n\n[zodbconvert]\nrecipe = zc.recipe.egg\neggs = ${buildout:eggs}\nscripts ... | [
5,
0,
0
] | [] | [] | [
"plone",
"python",
"relstorage"
] | stackoverflow_0005769777_plone_python_relstorage.txt |
Q:
Pyramid config loading error
I've got an issue with creating an app in Pyramid. When I try to serve through paster, I get:
File "/home/viraptor/blah/blah/__init__.py", line 23, in main
return config.make_wsgi_app()
File "/home/viraptor/pyramid/lib/python2.6/site-packages/pyramid/config.py", line 916, in ma... | Pyramid config loading error | I've got an issue with creating an app in Pyramid. When I try to serve through paster, I get:
File "/home/viraptor/blah/blah/__init__.py", line 23, in main
return config.make_wsgi_app()
File "/home/viraptor/pyramid/lib/python2.6/site-packages/pyramid/config.py", line 916, in make_wsgi_app
self.commit()
Fi... | [
"I suspect you hit a bug fixed in newer revisions of Pyramid; your traceback indicates that either args or defaults is None, but that code branch cannot be reached unless args is not None, leaving the possibility that defaults is None instead. I found the following commit to Pyramids that adds a specific test for d... | [
3,
0
] | [] | [] | [
"configuration",
"pyramid",
"python"
] | stackoverflow_0005770044_configuration_pyramid_python.txt |
Q:
Qt's absoluteFilePath() method returns wrong path
I'm trying to print file's path pointed in treeView with following functions:
1) Setting root index for treeView:self.treeView.setRootIndex(self.model.setRootPath("/some/unix/catalog"))
2) Setting connection between clicked file and function which prints name:
QtCo... | Qt's absoluteFilePath() method returns wrong path | I'm trying to print file's path pointed in treeView with following functions:
1) Setting root index for treeView:self.treeView.setRootIndex(self.model.setRootPath("/some/unix/catalog"))
2) Setting connection between clicked file and function which prints name:
QtCore.QObject.connect(self.ui.treeView, QtCore.SIGNAL("cli... | [
"In\nQtCore.QFileInfo(index.data(0).toString())\n\nyou are creating a new FileInfo instance with just the local path. The fileinfo has no possibility of knowing which folder this filename is in, so it uses the default folder. Think of it as\nQtCore.QFileInfo(\"readme.txt\")\n\nHow could the fileInfo know that you m... | [
2
] | [] | [] | [
"linux",
"pyqt",
"python",
"qt"
] | stackoverflow_0005770204_linux_pyqt_python_qt.txt |
Q:
using emacs CEDET completion for python
In default installation of cedet-1.0 completion can only track global scope symbols in current file. This is not much differs from built-in completion functions (dabbrev-expand or hippie-expand).
It can complete symbols from neither imported modules, nor class properties.
No... | using emacs CEDET completion for python | In default installation of cedet-1.0 completion can only track global scope symbols in current file. This is not much differs from built-in completion functions (dabbrev-expand or hippie-expand).
It can complete symbols from neither imported modules, nor class properties.
Not saying it cannot handle 'self'.
Is it possi... | [
"CEDET support for each language is slightly different. In the case of python, the 1.0 release for CEDET hadn't been configured to convert a python import into a file-name. In addition, 'self' is similar to 'this' in c++, which needs to be added by completion logic since it isn't declared. These two features we... | [
8
] | [] | [] | [
"cedet",
"code_completion",
"emacs",
"python"
] | stackoverflow_0005766832_cedet_code_completion_emacs_python.txt |
Q:
Checking QValidator's state
First, sorry for my bad English.
I'm trying to get an IP from user. I'm using QRegExpValidator for checking user input. The validator blocks unwanted characters succesfully. But I want to learn it's a proper IP when user clicked the button. Of course I can check the text manually, but t... | Checking QValidator's state | First, sorry for my bad English.
I'm trying to get an IP from user. I'm using QRegExpValidator for checking user input. The validator blocks unwanted characters succesfully. But I want to learn it's a proper IP when user clicked the button. Of course I can check the text manually, but there seems a better way, using QV... | [
"You're not doing the right thing here. The comparison:\nvalidator.State==QtGui.QValidator.Intermediate\n\nCompares an enumeration type to one of its values - this will always be False!\nUse the validate method instead:\ndef addClientButtonClicked(self, edit, validator):\n print(\"ip=\", edit.text())\n print(... | [
5
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0005770441_pyqt_python.txt |
Q:
Fetch a remote zip file and list the files within
I'm working on a small Google App Engine project in which I need to fetch a remote zip file from a URL and then list the files contained in the zip archive.
I'm using the zipfile module.
Here's what I've come up with so far:
# fetch the zip file from its remote URL... | Fetch a remote zip file and list the files within | I'm working on a small Google App Engine project in which I need to fetch a remote zip file from a URL and then list the files contained in the zip archive.
I'm using the zipfile module.
Here's what I've come up with so far:
# fetch the zip file from its remote URL
result = urlfetch.fetch(zip_url)
# store the contents... | [
"You are opening the file with w permissions, which truncates it. Change it to r permissions for reading:\nzip_file = zipfile.ZipFile(file_stream, 'r')\n\nReference: http://docs.python.org/library/zipfile.html#zipfile-objects\n",
"You're opening the ZipFile for writing. Try reading instead.\n"
] | [
7,
1
] | [] | [] | [
"google_app_engine",
"python",
"zip"
] | stackoverflow_0005770480_google_app_engine_python_zip.txt |
Q:
Twisted: How to pass parameter implicitly?
I would like to add security checks to my existing twisted server, but in order to do checks I need information about Request.
It is possible to pass request-object in every function call, but I am looking for solution to pass it as implicit parameter. If twisted was thre... | Twisted: How to pass parameter implicitly? | I would like to add security checks to my existing twisted server, but in order to do checks I need information about Request.
It is possible to pass request-object in every function call, but I am looking for solution to pass it as implicit parameter. If twisted was threaded framework I could use thread-local-storage ... | [
"Spooky action at a distance is great in physics (woo hoo quantum teleportation). However, in software, it's terrible. It's extremely detrimental to the readability of a program.\nTwisted Web (you must be talking about a web server, I guess) offers an authentication and authorization systems via twisted.web.guard... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0005770230_python_twisted.txt |
Q:
Why is python choking on numpy.core.ma?
I'm trying to set up pylab on my mac 10.6.7 32 bit machine; using virutalenv to isolate what I'm doing from everything else (coming from a ruby/rvm background this just makes me feel better--but I'm open to correction if it's not the "python way").
I have the following modul... | Why is python choking on numpy.core.ma? | I'm trying to set up pylab on my mac 10.6.7 32 bit machine; using virutalenv to isolate what I'm doing from everything else (coming from a ruby/rvm background this just makes me feel better--but I'm open to correction if it's not the "python way").
I have the following modules/libs installed:
DateUtils-0.5.1-py2.7.egg-... | [
"For someone else coming googling around, the one liner you search is currently:\npip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.0.1/matplotlib-1.0.1.tar.gz/download'\n\n",
"You appear to have a extremely old version of Matplotlib installed. I'm not sure where you got it,... | [
8,
3
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0005560129_matplotlib_numpy_python.txt |
Q:
Web Dev. Framework for RAD Web App Dev. in Shortest Time ( Yii vs. Django )
I googled it and found nothing of much interest , right now me & my Team know/partially know ( Codeigniter, Yii) and also Django (Python Framework) , now after working with codeigniter for past 1 year we have noticed that we are not that... | Web Dev. Framework for RAD Web App Dev. in Shortest Time ( Yii vs. Django ) | I googled it and found nothing of much interest , right now me & my Team know/partially know ( Codeigniter, Yii) and also Django (Python Framework) , now after working with codeigniter for past 1 year we have noticed that we are not that efficient and we still have to code most of the stuff( comment system, image upl... | [
"Vivek, this is one of those questions to which it's hard to give an answer better than \"it depends\". Personally, I think that the language and its ecosystem is a very important factor in the choice, perhaps more so than the specific framework.\nWhy so? As you mentioned, you found out that you had to write a lot ... | [
1,
0
] | [] | [] | [
"django",
"frameworks",
"python",
"rad",
"yii"
] | stackoverflow_0005770080_django_frameworks_python_rad_yii.txt |
Q:
Basic Python 2D graphics?
I'm looking for a Python 2D graphics library that can basically do the following and not necessarily anything more:
Create a window of specified width and height
Set the RGB of pixel X, Y on the back buffer.
Swap buffers
...and that's it basically. I can't find anything that doesn't com... | Basic Python 2D graphics? | I'm looking for a Python 2D graphics library that can basically do the following and not necessarily anything more:
Create a window of specified width and height
Set the RGB of pixel X, Y on the back buffer.
Swap buffers
...and that's it basically. I can't find anything that doesn't come with a massive amount of comp... | [
"I recommend PyQt for this - it's a GUI library/framework but it has very good drawing capabilities. If you look at the examples coming with PyQt, focusing on the graphics & drawing samples, it's quite amazing what you can do with very few lines of code.\nOh, and it does the double-buffering you mention automatical... | [
4
] | [] | [] | [
"2d",
"graphics",
"python"
] | stackoverflow_0005770944_2d_graphics_python.txt |
Q:
Python: How can I change the "to" field in smtp/MIME script rather than adding a new one?
Here's an excerpt from the code I'm using. I'm looping through the part that adds the email; my problem is rather than changing the "to" field on each loop, it is appending the "to" data. Obviously this causes some issues, ... | Python: How can I change the "to" field in smtp/MIME script rather than adding a new one? | Here's an excerpt from the code I'm using. I'm looping through the part that adds the email; my problem is rather than changing the "to" field on each loop, it is appending the "to" data. Obviously this causes some issues, since the to field ends up getting longer and longer. I tried msgRoot.del_param('To') to no av... | [
"You can use the replace_header method.\n\nreplace_header(_name, _value)\nReplace a header. Replace the first header found in the message that matches _name, retaining header order and field name case. If no matching header was found, a KeyError is raised.\nNew in version 2.2.2.\n\nFor example,\nif msgRoot.has_key(... | [
6,
1
] | [] | [] | [
"mime",
"python",
"smtp"
] | stackoverflow_0005770951_mime_python_smtp.txt |
Q:
python re.compile strings with vars and numbers
Hi I want to get a match for the following:
test = re.compile(r' [0-12](am|pm) [1-1000] days from (yesterday|today|tomorrow)')
with this match:
print test.match(" 3pm 2 days from today")
It returns none, what am i doing wrong? I am just getting into regex and reading... | python re.compile strings with vars and numbers | Hi I want to get a match for the following:
test = re.compile(r' [0-12](am|pm) [1-1000] days from (yesterday|today|tomorrow)')
with this match:
print test.match(" 3pm 2 days from today")
It returns none, what am i doing wrong? I am just getting into regex and reading the docs I thought this should work! ANY HELP APPREC... | [
"Here is my hat in the ring. Careful study of this regex will teach a few lessons:\nimport re\nreobj = re.compile(\n r\"\"\"# Loosely match a date/time reference\n ^ # Anchor to start of string.\n \\s* # Optional leading whitespace.\n (?P<time> # $time: mil... | [
5,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"nlp",
"python",
"regex"
] | stackoverflow_0005767987_nlp_python_regex.txt |
Q:
Python: Manipulating a 16-bit .tiff image in PIL &/or pygame: convert to 8-bit somehow?
Hello all,
I am working on a program which determines the average colony size of yeast from a photograph, and it is working fine with the .bmp images I tested it on. The program uses pygame, and might use PIL later.
However, t... | Python: Manipulating a 16-bit .tiff image in PIL &/or pygame: convert to 8-bit somehow? | Hello all,
I am working on a program which determines the average colony size of yeast from a photograph, and it is working fine with the .bmp images I tested it on. The program uses pygame, and might use PIL later.
However, the camera/software combo we use in my lab will only save 16-bit grayscale tiff's, and pygame ... | [
"I would look at pylibtiff, which has a pure python tiff reader.\nFor bundling, your best bet is probably py2exe and py2app.\n",
"py2exe is the way to go for packaging up your application if you are on a windows system.\nRegarding the 16bit tiff issue:\nThis example http://ubuntuforums.org/showthread.php?t=148326... | [
2,
2,
1
] | [] | [] | [
"16_bit",
"pygame",
"python",
"python_imaging_library",
"tiff"
] | stackoverflow_0005768714_16_bit_pygame_python_python_imaging_library_tiff.txt |
Q:
Python: output for recursively printing out files and folders
I have written a python function that recursively prints out files and folders, but now I am not sure how to display it in an aesthetic manner (in plain text). How do you display your folder structures?
A:
If you write a function to return the directo... | Python: output for recursively printing out files and folders | I have written a python function that recursively prints out files and folders, but now I am not sure how to display it in an aesthetic manner (in plain text). How do you display your folder structures?
| [
"If you write a function to return the directory structure as a nested list like this:\n['DIR1/',['fileA','fileB','DIR3/',['fileE','fileF']],'DIR2/',['fileC','fileD']]\n\nthen you could use pprint.pformat to create a passable string representation:\nimport pprint\nimport textwrap\nimport re\n\ndata=['DIR1/',['fileA... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0005771039_python.txt |
Q:
Ordered Dictionary in Python: add to MongoDB
I have a list of two element tuples, where the first element is a string (name of some parameter) and the second element is a float (the value of that parameter). For example,
thelist = [('costperunit', 200), ('profit', 10000), ('fixedcost', 5000),
('numpeop... | Ordered Dictionary in Python: add to MongoDB | I have a list of two element tuples, where the first element is a string (name of some parameter) and the second element is a float (the value of that parameter). For example,
thelist = [('costperunit', 200), ('profit', 10000), ('fixedcost', 5000),
('numpeople':300)]
There are many more such tuples and the... | [
"Pymongo offers a subclass of dict, bson.son.SON: http://api.mongodb.org/python/current/api/bson/son.html which is ordered for cases where you need that such as sending commands. \n"
] | [
7
] | [
"Dicts in Python and arrays in Javascript/BSON (MongoDB) are not ordered. Either you store some explicit sort-index number as part of the dict/array and perform app-level sorting on this level or you insert your data into a list which is of course sorted.\n"
] | [
-4
] | [
"mongodb",
"python"
] | stackoverflow_0005770959_mongodb_python.txt |
Q:
How to add file to RSSItem of PyRSS2Gen?
I use PyRSS2Gen in my GAE application.
How can I add attached file to the RSSItem?
A:
Ok, here is the way to add it:
PyRSS2Gen.RSSItem(
enclosure = PyRSS2Gen.Enclosure(
"http://www.example.com/url",
... | How to add file to RSSItem of PyRSS2Gen? | I use PyRSS2Gen in my GAE application.
How can I add attached file to the RSSItem?
| [
"Ok, here is the way to add it:\n PyRSS2Gen.RSSItem(\n enclosure = PyRSS2Gen.Enclosure(\n \"http://www.example.com/url\",\n 17176948, # file size\n \"mime-type\"))\n\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"rss"
] | stackoverflow_0005766718_google_app_engine_python_rss.txt |
Q:
How to import multiple locations to PYTHONPATH (bash)
I know you can add multiple locations to python path by separating them by colons ie:
export PYTHONPATH=~/one/location:~/second/location
etc.
I have several locations to add and it looks messy using the above method. Is there a way of adding them in multiple ... | How to import multiple locations to PYTHONPATH (bash) | I know you can add multiple locations to python path by separating them by colons ie:
export PYTHONPATH=~/one/location:~/second/location
etc.
I have several locations to add and it looks messy using the above method. Is there a way of adding them in multiple lines? This is what I tried and the last line erases the fi... | [
"PYTHONPATH=~/one/location:$PYTHONPATH\nPYTHONPATH=~/second/location:$PYTHONPATH\nexport PYTHONPATH\n\nNote the order here: I've made them so that each has higher precedence than the one before; you could switch what goes on each side of the colon if you want later entries to have lower precedence.\n",
"Assuming ... | [
31,
6,
2
] | [] | [] | [
"bash",
"python",
"pythonpath"
] | stackoverflow_0005771376_bash_python_pythonpath.txt |
Q:
How to prohibit a Python module from calling other modules?
In my Python application, I'll call 3rd party's Python modules. But these modules must have some restrictions for security problems. For example, they can't call some low level IO functions. Can I have a way to prohibit these 3rd party's modules from call... | How to prohibit a Python module from calling other modules? | In my Python application, I'll call 3rd party's Python modules. But these modules must have some restrictions for security problems. For example, they can't call some low level IO functions. Can I have a way to prohibit these 3rd party's modules from calling specific functions(modules)?
In my understanding, I can use t... | [
"http://pypi.python.org/pypi/RestrictedPython\n"
] | [
1
] | [] | [] | [
"python",
"security"
] | stackoverflow_0005771448_python_security.txt |
Q:
What is the exact pattern of legal values for filling URLFields in Django?
I need a precise definition of the set of strings which are considered legal urls for models.URLField.
As far as I'm concerned, a precise definition can be either a regular expression or a piece of code which verifies the validity of a url ... | What is the exact pattern of legal values for filling URLFields in Django? | I need a precise definition of the set of strings which are considered legal urls for models.URLField.
As far as I'm concerned, a precise definition can be either a regular expression or a piece of code which verifies the validity of a url or any other form of a formal accurate explanation.
| [
"Looking through the source, it seems URLField is a CharField which adds a validators.URLValidator to the field's validator list, and that's imported from django.core.\nFrom site-packages/django/core/validators.py:\nclass URLValidator(RegexValidator):\n regex = re.compile(\n r'^https?://' # http:// or htt... | [
2
] | [] | [] | [
"django",
"python",
"url",
"validation"
] | stackoverflow_0005771472_django_python_url_validation.txt |
Q:
Mocking an Http connection in python
I am trying to mock an http connection to test some of my python code. I was wondering how this is achieved. I need the mock class to return data store in a json object when requested. I am trying to figure out how to place the data and create a mock http request in order to ob... | Mocking an Http connection in python | I am trying to mock an http connection to test some of my python code. I was wondering how this is achieved. I need the mock class to return data store in a json object when requested. I am trying to figure out how to place the data and create a mock http request in order to obtain it and modify it through posts need b... | [
"Use the BaseHTTPServer module (http.server is its name if you're on Python 3) to create a simple HTTP mock server and bend it to your will. It allows you to easily customize its request handlers to achieve anything you need with relatively small amounts of code. The module's documentation is pretty good - start th... | [
4,
0
] | [] | [] | [
"http",
"json",
"mocking",
"python"
] | stackoverflow_0005771498_http_json_mocking_python.txt |
Q:
about python scopes
I've read about python scopes and browsed questions here on stackoverflow but theres something i'd like to clarify.
I'm extracting a piece of code to a function, from what i used to it should take all the variables it's using as parameters. But, in python the variable address is determined at r... | about python scopes | I've read about python scopes and browsed questions here on stackoverflow but theres something i'd like to clarify.
I'm extracting a piece of code to a function, from what i used to it should take all the variables it's using as parameters. But, in python the variable address is determined at runtime so theres actually... | [
"It's preferred not to use global variables, if not absolutely necessary. That said, in the second example you'd need global x declared before you refer to x.\nSo, first way:\n\nf takes an argument x\nIncrements x\nreturns x + 1\nthe global x is not affected\n\nThe second way:\ndef f():\n global x\n x += 1\n\nx =... | [
3,
3
] | [] | [] | [
"conventions",
"python",
"scope"
] | stackoverflow_0005770397_conventions_python_scope.txt |
Q:
Is it simple to implement a simple python function in C?
I am working on the problem posed by this post: Fast way to remove a few items from a list/queue
Basically all I want to do is implement a for loop in C. The for loop needs to access a generator and be able to delete elements of an array (and increment an i... | Is it simple to implement a simple python function in C? | I am working on the problem posed by this post: Fast way to remove a few items from a list/queue
Basically all I want to do is implement a for loop in C. The for loop needs to access a generator and be able to delete elements of an array (and increment an integer). Something in me tells me this would be painfully dif... | [
"If all you need is to remove for-loop overhead then it is sufficient to define type of a for loop variable in Cython (pip install cython). Here's a modified remove_inplace_senderle2() in Cython delitems.pyx:\n#cython: boundscheck=False, wraparound=False\nimport cython\n\n@cython.locals(end=cython.Py_ssize_t, i=cyt... | [
3,
2,
2
] | [] | [] | [
"c",
"ctypes",
"for_loop",
"python"
] | stackoverflow_0005762229_c_ctypes_for_loop_python.txt |
Q:
Searching for a FAST and THREADSAFE Database for large amount of data
Hey, searching for a database like the titel.
I need it in many threads and if possible scaleable so it could run an several server...
It should be possible to acess the db from c/c++ and python maybe from php...
A:
Most people start with:
ht... | Searching for a FAST and THREADSAFE Database for large amount of data | Hey, searching for a database like the titel.
I need it in many threads and if possible scaleable so it could run an several server...
It should be possible to acess the db from c/c++ and python maybe from php...
| [
"Most people start with:\nhttp://www.mysql.com/\n"
] | [
2
] | [] | [] | [
"c",
"c++",
"php",
"python"
] | stackoverflow_0005772202_c_c++_php_python.txt |
Q:
Extensive object composition
I have a Django model that has a lot of methods (and will continue to have more in the future) because it is central to the app. It is a custom User model that interfaces with a legacy database. There are methods that check the user's access permissions to different areas, different ki... | Extensive object composition | I have a Django model that has a lot of methods (and will continue to have more in the future) because it is central to the app. It is a custom User model that interfaces with a legacy database. There are methods that check the user's access permissions to different areas, different kinds of costs, etc.
Since there are... | [
"If you want to split out methods on the same underlying db model into different sets of related methods, perhaps you should use proxy models.\nSame underlying db will be used, but will be different distinct classes.\nI am not sure that this is the best solution when you are talking about User class though. You hav... | [
0,
0
] | [] | [] | [
"composition",
"django",
"python"
] | stackoverflow_0005771597_composition_django_python.txt |
Q:
Username available in all templates
I'm trying to make the currently logged in username available in all templates. I can receive it from pyramid.security.authenticated_userid, but to do that I need the request object. I tried to go via the BeforeRender subscription, but as far as I can tell, the request in not pa... | Username available in all templates | I'm trying to make the currently logged in username available in all templates. I can receive it from pyramid.security.authenticated_userid, but to do that I need the request object. I tried to go via the BeforeRender subscription, but as far as I can tell, the request in not passed to that callback.
How else can I mak... | [
"A common method is to attach the user object to the request via this cookbook recipe.\nAnother possibility is to attach it as you suggested using a BeforeRender subscriber. The request is available from the event:\ndef add_renderer_globals(event):\n request, context = event['request'], event['context']\n eve... | [
5
] | [] | [] | [
"authentication",
"pyramid",
"python"
] | stackoverflow_0005771281_authentication_pyramid_python.txt |
Q:
exec() raises 'unexpected EOF' error when encountering the : character
In the program I am writing (a text-based rpg) I am going to include 'scripts', little pieces of code that add interactive functionality to the game (such as an NPC greeting you when you enter a room). Writing my own scripting language/parser s... | exec() raises 'unexpected EOF' error when encountering the : character | In the program I am writing (a text-based rpg) I am going to include 'scripts', little pieces of code that add interactive functionality to the game (such as an NPC greeting you when you enter a room). Writing my own scripting language/parser seemed like a pretty big task so I thought I'd use Python code itself instead... | [
"You use exec to evaluate a single line. In this code:\nif a == b:\n do_c()\n\nThe first line, evaluated by itself, is a syntax error. The above can be also folded to a single line as:\nif a == b: do_c()\n\nIn the more general case, allowing multiple lines, what you could do is collect the whole input into a strin... | [
4,
2
] | [] | [] | [
"eof",
"exec",
"parsing",
"python"
] | stackoverflow_0005771392_eof_exec_parsing_python.txt |
Q:
How should I Arrange my data?
I'd like to log the CPU percentage of each process in different times. I need a data struct that will allow me to save the data like this:
Explorer.EXE
19:03 | 47%
19:05 | 14%
19:08 | 24%
Firefox.EXE
19:03 | 21%
19:05 | 14%
19:08 | 2%
Messenger.EXE
19:03 | 11%
19:05 | 12%
19:08 ... | How should I Arrange my data? | I'd like to log the CPU percentage of each process in different times. I need a data struct that will allow me to save the data like this:
Explorer.EXE
19:03 | 47%
19:05 | 14%
19:08 | 24%
Firefox.EXE
19:03 | 21%
19:05 | 14%
19:08 | 2%
Messenger.EXE
19:03 | 11%
19:05 | 12%
19:08 | 11%
What's the right way to do ... | [
"What about a dictionary that uses the process name as key: http://docs.python.org/library/stdtypes.html#dict\nThe dictionary value could be a list of tuples.\n",
"struct = {\n \"Explorer.EXE\": [\n (datetime.time(19, 03), .47),\n (datetime.time(19, 05), .14),\n ...\n ],\n \"Firefox.... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0005772529_python.txt |
Q:
how do I get rid of "^M" in data I have scraped from a website?
I have data that looks like this:
"1964 iwanttoholdyourhand beatles
^M
oh yeah, i'll tell you something
i think you'll understand
when i'll say that something
i wanna hold your hand
i wanna hold your hand
i wanna hold your hand
oh please, say to ... | how do I get rid of "^M" in data I have scraped from a website? | I have data that looks like this:
"1964 iwanttoholdyourhand beatles
^M
oh yeah, i'll tell you something
i think you'll understand
when i'll say that something
i wanna hold your hand
i wanna hold your hand
i wanna hold your hand
oh please, say to me
you'll let me be your man
and please, say to me
you'll let me ho... | [
"^M is used to represent the carriage return character in many editors. You would typically type Ctrl + M to generate that character in those editors.\nPython represents this as '\\r', as do most programming languages.\n",
"It's probably a windows vs. unix line endings issue. Unix uses \\n (newline), windows use... | [
5,
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0005772773_html_python.txt |
Q:
python library to create a video file from images
I was looking for a light weight python library which would allow me to create a simple video (a slideshow) from a bunch of images. I looked into PyFFMpeg and Pymedia, but they seem really old, and was wondering if anyone knows of any other libraries I could use, (... | python library to create a video file from images | I was looking for a light weight python library which would allow me to create a simple video (a slideshow) from a bunch of images. I looked into PyFFMpeg and Pymedia, but they seem really old, and was wondering if anyone knows of any other libraries I could use, (or has had success using PyFFMpeg/Pymedia recently).
Th... | [
"Go for opencv\nAnd a bit of help from Here\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0005772831_python.txt |
Q:
Caching pre-rendered templates with GAE Memcache API
I have been using this logic to render templates in my GAE application:
path = os.path.join(os.path.dirname(__file__), 'page.html')
self.response.out.write(template.render(path, template_values))
I'm wondering if it's possible (and more efficient) to load the u... | Caching pre-rendered templates with GAE Memcache API | I have been using this logic to render templates in my GAE application:
path = os.path.join(os.path.dirname(__file__), 'page.html')
self.response.out.write(template.render(path, template_values))
I'm wondering if it's possible (and more efficient) to load the unrendered template text and store it in Memcache. The tem... | [
"Google App Engine caches templates out of the box in order to keep your application responsive.\nHere is the interesting part of the template.py module available in the source code:\ndef render(template_path, template_dict, debug=False):\n \"\"\"Renders the template at the given path with the given dict of values... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005771469_google_app_engine_python.txt |
Q:
In python Sorting a list of tuples?
How do you sort a list by elemant thats a tuple?
Let say below is the list LL.
I want to sort ID2 -- LL[1] which is a tuple as asc.
How would I do it.
Id, Id2 CCC
A123 A120 '2011-03'
LL= A133 A123 '2011-03'
D123 D120 '2011-04'
... | In python Sorting a list of tuples? | How do you sort a list by elemant thats a tuple?
Let say below is the list LL.
I want to sort ID2 -- LL[1] which is a tuple as asc.
How would I do it.
Id, Id2 CCC
A123 A120 '2011-03'
LL= A133 A123 '2011-03'
D123 D120 '2011-04'
D140 D123 '2011-04'
| [
"Have a look at http://wiki.python.org/moin/HowTo/Sorting/\nsorted(LL, key=itemgetter(1)) might do what you want.\nPlease note that you have to from operator import itemgetter to get the itemgetter function.\nIn [1]: LL = (('A123', 'A120', '2011-03'), ('A133', 'A123', '2011-03'), ('D123', 'D120', '2011-04'), ('D140... | [
4,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0005773172_python_sorting.txt |
Q:
Merging dictionaries using a counter
I have the following dictionaries (example):
>>> x = {'a': 'foo', 'b': 'foobar'}
>>> y = {'c': 'barfoo', 'd': 'bar'}
I want to take the keys of each and make them the value of another dict, say z, such that the keys of z is an incremented counter, equal to the length of both t... | Merging dictionaries using a counter | I have the following dictionaries (example):
>>> x = {'a': 'foo', 'b': 'foobar'}
>>> y = {'c': 'barfoo', 'd': 'bar'}
I want to take the keys of each and make them the value of another dict, say z, such that the keys of z is an incremented counter, equal to the length of both the dicts.
>>> z = {1: 'a', 2: 'b', 3: 'c',... | [
"In [1]: import itertools\nIn [2]: x = {'a': 'foo', 'b': 'foobar'}\nIn [3]: y = {'c': 'barfoo', 'd': 'bar'}\n\nIn [4]: z = [key for key in itertools.chain(x, y)]\n\nIn [5]: z\nOut[5]: ['a', 'b', 'c', 'd']\n\nIn [6]: dict(enumerate(z))\nOut[6]: {0: 'a', 1: 'b', 2: 'c', 3: 'd'}\n\nIn [7]: dict(enumerate(z, 1))\nOut[7... | [
5,
3
] | [] | [] | [
"dictionary",
"merge",
"python"
] | stackoverflow_0005773224_dictionary_merge_python.txt |
Q:
Converting a deque object into list
Currently I fetch "list" data from my storage, "deque" it to work with that data.
After processing the fetched data I have to put them back into the storage.
This won't be a problem as long as I am not forced (at least I think so) to use Python's standard "list" object to save t... | Converting a deque object into list | Currently I fetch "list" data from my storage, "deque" it to work with that data.
After processing the fetched data I have to put them back into the storage.
This won't be a problem as long as I am not forced (at least I think so) to use Python's standard "list" object to save this data.
Storage Service: Google Appengi... | [
">>> list(collections.deque((1, 2, 3)))\n[1, 2, 3]\n\n"
] | [
109
] | [] | [] | [
"deque",
"list",
"python",
"queue"
] | stackoverflow_0005773397_deque_list_python_queue.txt |
Q:
How to recursively check an answer in a boggle type game
As an exercise, I have been trying to build a non-GUI boggle type game in python. So far, the user is able to enter a board size (4x4,5x5,etc). The 'array' of letters appears and then the user may type in a word that they think is a valid option.
I wanted... | How to recursively check an answer in a boggle type game | As an exercise, I have been trying to build a non-GUI boggle type game in python. So far, the user is able to enter a board size (4x4,5x5,etc). The 'array' of letters appears and then the user may type in a word that they think is a valid option.
I wanted to check if the entered word was valid by using a recursive f... | [
"Interesting exercise, I had a crack at it. I post the code below so consider this a spoiler alert. For general tips:\n\nBreak the code down into smaller chunks - one function to rule them all doesn't take you far.\nWhen doing recursion, start by finding the base cases, ie. when will the function not recurse.\nLet ... | [
0
] | [] | [] | [
"boggle",
"python",
"recursion"
] | stackoverflow_0005773028_boggle_python_recursion.txt |
Q:
How to use the pipe operator as part of a regular expression?
I want to match the url within strings like
u1 = "Check this out http://www.cnn.com/stuff lol"
u2 = "see http://www.cnn.com/stuff2"
u3 = "http://www.espn.com/stuff3 is interesting"
Something like the following works, but it's cumbersome because I have ... | How to use the pipe operator as part of a regular expression? | I want to match the url within strings like
u1 = "Check this out http://www.cnn.com/stuff lol"
u2 = "see http://www.cnn.com/stuff2"
u3 = "http://www.espn.com/stuff3 is interesting"
Something like the following works, but it's cumbersome because I have to repeat the whole pattern
re.findall("[^ ]*.cnn.[^ ]*|[^ ]*.espn.... | [
"Non-capturing groups allow you to group characters without having that group also be returned as a match.\ncnn|espn becomes (?:cnn|espn):\nre.findall(\"[^ ]*\\.(?:cnn|espn)\\.[^ ]*\", u1)\n\nAlso note that . is a regex special character (it will match any character except newline). To match the . character itself,... | [
8
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005773463_python_regex.txt |
Q:
What does Python 3.2 "with/as" do
I'm learning Python, and I'm trying out the with **** as ****: statement. I figure it works much like C#'s using(****) {, but I'm afraid I'm following outdated examples.
This is my code:
# -*- coding: iso-8859-1 -*-
import pprint
pow = 1, 2, 3
with pprint.pprint as pprint:
... | What does Python 3.2 "with/as" do | I'm learning Python, and I'm trying out the with **** as ****: statement. I figure it works much like C#'s using(****) {, but I'm afraid I'm following outdated examples.
This is my code:
# -*- coding: iso-8859-1 -*-
import pprint
pow = 1, 2, 3
with pprint.pprint as pprint:
pprint(pow)
I assume what's happening ... | [
"with doesn't work like that.\nIt's designed to automatically clean up an object at the end of a block, e.g. instead of\nfile = open('foo.txt')\n# do stuff\nclose(file)\n\nYou can do\nwith open('foo.txt') as file:\n # do stuff\n\nand the close happens automatically.\nSee PEP 343 -- The \"with\" Statement for det... | [
15,
9,
4,
2
] | [] | [] | [
"python",
"python_3.x",
"with_statement"
] | stackoverflow_0005773545_python_python_3.x_with_statement.txt |
Q:
Multiple forms and persistence in Google App Engine
I'm gathering input data via a Django like validated form and then upon validating loading new form from and then validating and then I wish to send to the data store. I'd like to perform temporary storage on the first form, in case the user does not enter the f... | Multiple forms and persistence in Google App Engine | I'm gathering input data via a Django like validated form and then upon validating loading new form from and then validating and then I wish to send to the data store. I'd like to perform temporary storage on the first form, in case the user does not enter the full details on form two I don't see much point of adding ... | [
"The natural place to persist data between forms is in the user's session; every fields in your multi-form wizard would be stored in session until the last form where, after the confirmation, the data should be finally persisted in the DataStore.\nSince Google App Engine does not provide session in the python envir... | [
1
] | [
"I could describe the options, but this blogpost by Nick Johnson describes it perfectly:\nStorage options on App Engine\n"
] | [
-1
] | [
"google_app_engine",
"python",
"webforms"
] | stackoverflow_0005772313_google_app_engine_python_webforms.txt |
Q:
Mapping URLs in my handler script in App Engine
I have
class Auth(webapp.RequestHandler):
def get(self,username,password):
self.response.out.write("auth" + self.request.get("username"))
The structure of my URL will be:
/api/auth/?username=xxxx&password=xxxx
How do I map this URL in my handler script... | Mapping URLs in my handler script in App Engine | I have
class Auth(webapp.RequestHandler):
def get(self,username,password):
self.response.out.write("auth" + self.request.get("username"))
The structure of my URL will be:
/api/auth/?username=xxxx&password=xxxx
How do I map this URL in my handler script?
| [
"Handler: \nclass Auth(webapp.RequestHandler):\n def get(self):\n self.response.out.write(\"username\" + self.request.get(\"username\"))\n self.response.out.write(\"password\" + self.request.get(\"password\"))\n\nUrl:\n/api/auth?username=xxxx&password=xxxx\n\nApplication:\napplication = webapp.WSGI... | [
4
] | [] | [] | [
"google_app_engine",
"mapping",
"python",
"url"
] | stackoverflow_0005773560_google_app_engine_mapping_python_url.txt |
Q:
Using a python module's C API in my own C module
This seems to be sort of what I want, except I want to make an instance of a C PyObject in another C module.
Create instance of a python class , declared in python, with C API
But I am not able to find the documentation for using a Python module from C. I can't seem... | Using a python module's C API in my own C module | This seems to be sort of what I want, except I want to make an instance of a C PyObject in another C module.
Create instance of a python class , declared in python, with C API
But I am not able to find the documentation for using a Python module from C. I can't seem to find the relevent docs online as everyone just tal... | [
"The trick is to write the normal Python routine, but in C. Use PyImport_ImportModule(), PyObject_GetAttr(), and PyObject_Call() as appropriate.\n",
"You can use the pygame C-API, even though it is probably not meant to be used in that way (which then again begs the question why the pygame headers are installed w... | [
1,
0
] | [
"I googled it in a single \"I'm feeling lucky.\"\n"
] | [
-1
] | [
"linker",
"module",
"pygame",
"python"
] | stackoverflow_0002170625_linker_module_pygame_python.txt |
Q:
Python: indexing floats?
I have two sets of data that I am reading via nested for loops in Python. I need to match lines of the two different text files using a common number (time). In the two files, time is written differently (ex. 21:53:28.339 vs. 121082008.3399). I only need the last four digits of the time... | Python: indexing floats? | I have two sets of data that I am reading via nested for loops in Python. I need to match lines of the two different text files using a common number (time). In the two files, time is written differently (ex. 21:53:28.339 vs. 121082008.3399). I only need the last four digits of the times to match them up, for exampl... | [
"edit - using Decimal exclusively - with full example\nimport decimal\n\ndef simplify(text):\n # might be a : separated value\n text = text.split(':')[-1]\n # turn into decimal\n number = decimal.Decimal(text)\n # remove everything but the ones place and forwards\n number = number - (number/10).qu... | [
3,
1,
0
] | [] | [] | [
"floating_point",
"indexing",
"python",
"string"
] | stackoverflow_0005773286_floating_point_indexing_python_string.txt |
Q:
pythonic way of checking endpoints of a list against two sets of valid entries
endpoint1 = [1,2,3]
endpoint2 = [4,5,6]
path = list(random.randrange(0,9) for x in range(10))
What's the most pythonic way to make sure the 2 endpoints of the "path" list in the above code contains an element in both "endpoint1" and "e... | pythonic way of checking endpoints of a list against two sets of valid entries |
endpoint1 = [1,2,3]
endpoint2 = [4,5,6]
path = list(random.randrange(0,9) for x in range(10))
What's the most pythonic way to make sure the 2 endpoints of the "path" list in the above code contains an element in both "endpoint1" and "endpoint2"
Something like this, but prettier:
if path[0] in endpoint1:
if pa... | [
"Well you can do the whole thing in one expression.\nif path[0] in endpoint1 and path[-1] in endpoint2 or \\\n path[0] in endpoint2 and path[-1] in endpoint1:\n\nI don't think it'll get much better than that.\n",
"If the valid endpoints are only a few and you want to test many paths then generating all possible... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005767363_python.txt |
Q:
python recursively convert decimal to hex
How would you recursively or iteratively change a decimal to hexadecimal?
I wrote a sample program that does not really work:
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
ChangeHex(n / 16)
if (n == 15):
... | python recursively convert decimal to hex | How would you recursively or iteratively change a decimal to hexadecimal?
I wrote a sample program that does not really work:
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
ChangeHex(n / 16)
if (n == 15):
print("F")
if (n == 14):
... | [
"# Converts a decimal number to hexadecimal.\n# Executes a zero-fill for up to six digits.\n# This is used for correct conversion back\n# to the instruction format. See zero_fill().\n# @param dec Decimal representation of instruction\n# @return Zero-filled hexadecimal instruction.\ndef convert(dec):\n# BEGIN con... | [
0,
0
] | [] | [] | [
"decimal",
"hex",
"python",
"recursion"
] | stackoverflow_0005773971_decimal_hex_python_recursion.txt |
Q:
Saving KDTree object in Python?
I am using Scipy's KDTree implementation to read a large file of 300 MB. Now, is there a way I can just save the datastructure to disk and load it again or am I stuck with reading raw points from file and constructing the data structure each time I start my program? I am constructin... | Saving KDTree object in Python? | I am using Scipy's KDTree implementation to read a large file of 300 MB. Now, is there a way I can just save the datastructure to disk and load it again or am I stuck with reading raw points from file and constructing the data structure each time I start my program? I am constructing the KDTree as follows:
def buildKDT... | [
"KDtree uses nested classes to define its node types (innernode, leafnode). Pickle only works on module-level class definitions, so a nested class trips it up:\nimport cPickle\n\nclass Foo(object):\n class Bar(object):\n pass\n\nobj = Foo.Bar()\nprint obj.__class__\ncPickle.dumps(obj)\n\n<class '__main__... | [
12
] | [] | [] | [
"numpy",
"pickle",
"python",
"scipy",
"serialization"
] | stackoverflow_0005773216_numpy_pickle_python_scipy_serialization.txt |
Q:
python spaces error
I'm just fed up from python codes and spaces can any one help me in this code spaces!!
enter code here
import sys
from threading import Thread
import socket
import MySQLdb
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
... | python spaces error | I'm just fed up from python codes and spaces can any one help me in this code spaces!!
enter code here
import sys
from threading import Thread
import socket
import MySQLdb
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = cli... | [
"Use spaces. Don't EVER use tabs. Use a consistent number of spaces for indentation (the preferred number is 4). Use tabnanny as well:\npython -m tabnanny myscript.py\n\nThe problem with your script is inconsistent indentation. Some places you indent 8 spaces, some 1, some 2, and some 4. Use 4 spaces for indentatio... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0005774155_python.txt |
Q:
Python Socket programming (TCP vs. UDP)
I'm planning to design a server that receives data from multiple clients, the server don't need to send anything back to the client, though STATUS_OK is still cool but not necessary.
I know the basics of Python socket module, twisted framework but my question is, should i u... | Python Socket programming (TCP vs. UDP) | I'm planning to design a server that receives data from multiple clients, the server don't need to send anything back to the client, though STATUS_OK is still cool but not necessary.
I know the basics of Python socket module, twisted framework but my question is, should i use UDP or TCP? The client that need to stay c... | [
"You should always use TCP until you have a performance problem that you know can be mitigated with UDP. TCP is easier to understand when it fails.\n",
"Can you afford to lose messages? If yes, use UDP. Otherwise use TCP. It's what they're designed for.\n",
"I would use TCP in your situation, but it's hard to ... | [
4,
1,
0
] | [
"For how long will one client be connected to the server? How many concurrent connections are you planning to handle? If there will be very short bursts of data for a lot of clients, then you should go with UDP. But chances are, TCP will do just fine initially.\n"
] | [
-2
] | [
"python",
"sockets",
"tcp",
"twisted",
"udp"
] | stackoverflow_0005769096_python_sockets_tcp_twisted_udp.txt |
Q:
Reading and Storing csv data line by line in a postgres
I want to copy csv data from different files and then store in a table. But the problem is, the number of column differes in each csv files, So some csv file have 3 columns while some have 4. So if there are 4 columns in a file, I want to simply ignore the f... | Reading and Storing csv data line by line in a postgres | I want to copy csv data from different files and then store in a table. But the problem is, the number of column differes in each csv files, So some csv file have 3 columns while some have 4. So if there are 4 columns in a file, I want to simply ignore the fourth column and save only first three.
Using following code... | [
"Since you want to read and store it one line at a time, the Python csv module should make it easy to read the first 3 columns from your CSV file regardless of any extra columns.\nYou can construct an INSERT statement and execute it with your preferred Python-PostGreSQL module. I have used pyPgSQL in the past; don... | [
3,
0,
0
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0005662806_postgresql_python.txt |
Q:
wxPython Sliders that influence each other
I am writing a program based on this matplotlib slider example. Now I want to create a third slider that acts as a parent slider and changes both sliders at the same time. Does anybody know a good tutorial on that topic? Or a way how to implement it in this example?
A:
... | wxPython Sliders that influence each other | I am writing a program based on this matplotlib slider example. Now I want to create a third slider that acts as a parent slider and changes both sliders at the same time. Does anybody know a good tutorial on that topic? Or a way how to implement it in this example?
| [
"This should be fairly easy to do. Catch the EVT_SCROLL events issued from the \"parent\" slider, and when these occur, have the handler call SetValue(position) for each of the two \"child\" sliders. This way, you can set them based on whatever algorithm you choose.\n"
] | [
2
] | [] | [] | [
"python",
"sliders",
"wxpython"
] | stackoverflow_0005771712_python_sliders_wxpython.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.