content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python: exceptions in assignments
If I try the following code (in Python 3.2.2),
def f():
raise Exception
x = f()
then it appears that x is untouched - it either remains undefined or keeps whatever value it had previously. Is this behaviour guaranteed whenever the right hand side of an assignment throws an ... | Python: exceptions in assignments | If I try the following code (in Python 3.2.2),
def f():
raise Exception
x = f()
then it appears that x is untouched - it either remains undefined or keeps whatever value it had previously. Is this behaviour guaranteed whenever the right hand side of an assignment throws an exception? I realise this is a very ba... | [
"The Python language reference specifies this:\nhttp://docs.python.org/reference/expressions.html#evaluation-order\n\nPython evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.\n\nThe right side is evaluated, then the left... | [
14,
0
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0008493071_exception_exception_handling_python.txt |
Q:
convert cstring to python string object
I have a function wrapper for c and python. This wrapper will receive 2 string arguments and convert these two into a tuple and pass it to python script. fileName and className are the c string arguments. pFunc is the python function name.
PyObject *pArgs, *pValue,*pFunc;
pV... | convert cstring to python string object | I have a function wrapper for c and python. This wrapper will receive 2 string arguments and convert these two into a tuple and pass it to python script. fileName and className are the c string arguments. pFunc is the python function name.
PyObject *pArgs, *pValue,*pFunc;
pValue = PyString_FromString(fileName);
PyTuple... | [
"\nthe error was cannot convert QString to const char*\n\nSo your strings fileName and className are QString objects, not C strings (const char*)? You have to convert the data first, for example using QString::toAscii():\npValue = PyString_FromString(fileName.toAscii().data());\n\n"
] | [
2
] | [] | [] | [
"char",
"python",
"python_c_api",
"string"
] | stackoverflow_0008494488_char_python_python_c_api_string.txt |
Q:
Using cssutils to access or read the properties of page rule
I have read/write the properties of Font_face rule and style rule in css file.
Using the cssutils version 0.9.6 and programming language in python.
I try to read ,access the property of page rule.
But it gives problem for reading the property in page_rul... | Using cssutils to access or read the properties of page rule | I have read/write the properties of Font_face rule and style rule in css file.
Using the cssutils version 0.9.6 and programming language in python.
I try to read ,access the property of page rule.
But it gives problem for reading the property in page_rule style sheet.the property in the page rule gives the type as unkn... | [
"The syntax for css page rule selectors is:\n@page [identifier][:(first|left|right)]\n\nSo the example given in the question is invalid, because \"blank\" is not a pseudo-page.\nYou possibly meant:\n@page blank {\n @top-left { \n content: normal;\n }\n @top-center { \n content: normal;\n ... | [
0
] | [] | [] | [
"css",
"python"
] | stackoverflow_0008486877_css_python.txt |
Q:
converting string to tuple
I need to write a function that takes a string '(1,2,3,4,5),(5,4,3,2,1)' and returns a list of tuples of the 1st and last element of each tuple, [(1,5),(5,1)].
I was thinking:
def f(givenstring):
a=givenstring.split(',')
for i in a[0:-1]:
tuple(int(i[0,-1]))
but here I'm... | converting string to tuple | I need to write a function that takes a string '(1,2,3,4,5),(5,4,3,2,1)' and returns a list of tuples of the 1st and last element of each tuple, [(1,5),(5,1)].
I was thinking:
def f(givenstring):
a=givenstring.split(',')
for i in a[0:-1]:
tuple(int(i[0,-1]))
but here I'm stucked..
| [
"You can use ast.literal_eval():\n\nSafely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.\nThis can be used for safely evaluating strings cont... | [
79,
31,
6
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0008494514_python_string_tuples.txt |
Q:
asynchronous url opener in python
I want to open a big file from the web, and would like to start processing it before it downloads entirely.
What I would want is something like urllib2 but one that has another thread that downloads the file in the background.
It will have a same interface as a file :
if I do read... | asynchronous url opener in python | I want to open a big file from the web, and would like to start processing it before it downloads entirely.
What I would want is something like urllib2 but one that has another thread that downloads the file in the background.
It will have a same interface as a file :
if I do read for more bytes that are downloaded the... | [
"I looked into this:\nhttp://mail.python.org/pipermail/python-bugs-list/2007-April/038250.html\nand this:\nhttps://stackoverflow.com/a/1517728/498782\nand came up with a buffered reader for you:\nurl_resource = urllib2.urlopen(url)\nCHUNK = 8 * 1024\nwhile True:\n chunk_data = url_resource.read(CHUNK)\n if no... | [
0
] | [] | [] | [
"python",
"url"
] | stackoverflow_0008494319_python_url.txt |
Q:
Django 1.3 Matching query does not exist
I have a question about this error and hope someone has ran into it like I have. I am getting this error on a model when trying to use the Models.ForeignKey field. I can verify that the table the foreign key is used in exists, as well as the table that the fk references e... | Django 1.3 Matching query does not exist | I have a question about this error and hope someone has ran into it like I have. I am getting this error on a model when trying to use the Models.ForeignKey field. I can verify that the table the foreign key is used in exists, as well as the table that the fk references exists. I can get the model to work if I use a... | [
"I can definitely see one problem with your models here. When you define a ForegnKey field with the name \"claim_status\", Django will be automatically creating an attribute on your model instances called \"claim_status_id\" which will be used to store the raw value of the \"claim_status\" database column. However,... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008483981_django_django_models_python.txt |
Q:
format from string to integer?
I have some problems with format from string to int in Python:
obj=self.browse(cr,uid,ids,context=context)[0]
hour_den=obj.time_in[12:13]
hour_di=obj.time_out[12:13]
min_den=obj.time_in[15:16]
min_di=obj.time_out[15:16]
gl=hour_di-hour_den
pl=min_di-min_den
and error is:
unsupporte... | format from string to integer? | I have some problems with format from string to int in Python:
obj=self.browse(cr,uid,ids,context=context)[0]
hour_den=obj.time_in[12:13]
hour_di=obj.time_out[12:13]
min_den=obj.time_in[15:16]
min_di=obj.time_out[15:16]
gl=hour_di-hour_den
pl=min_di-min_den
and error is:
unsupported operand type(s) for -: 'unicode' a... | [
"It is not clear what type obj is. However you could do.\nobj=self.browse(cr,uid,ids,context=context)[0]\nhour_den = hour_di = min_den = min_di = 0\ntry:\n hour_den=int(obj.time_in[12:13])\n hour_di=int(obj.time_out[12:13])\n min_den=int(obj.time_in[15:16])\n min_di=int(obj.time_out[15:16])\nexcept ValueError:\... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008494822_python.txt |
Q:
Creating in c#,c++ and java a strong typed version of a python weak typed structure
In python I have the following:
graph = {}
graph[1] = {}
graph[2] = {}
graph[3] = {}
graph[1][3] = graph[3]
graph[2][1] = graph[1]
graph[2][3] = graph[3]
graph[3][2] = graph[2]
this is a structure to represent a graph and that... | Creating in c#,c++ and java a strong typed version of a python weak typed structure | In python I have the following:
graph = {}
graph[1] = {}
graph[2] = {}
graph[3] = {}
graph[1][3] = graph[3]
graph[2][1] = graph[1]
graph[2][3] = graph[3]
graph[3][2] = graph[2]
this is a structure to represent a graph and that I find nice because its structure is the same as the one of one of it's nodes so I can u... | [
"In Java, I would go with a Node class which represents any node of a graph.\npublic class Node<T> {\n private List<Node<T>> children = new ArrayList<Node<T>>();\n private T value;\n\n public Node(T value) {\n this.value = value;\n }\n\n public void addChild(Node<T> child) {\n this.chil... | [
3,
1,
1
] | [] | [] | [
"c#",
"c++",
"java",
"python",
"strong_typing"
] | stackoverflow_0008495001_c#_c++_java_python_strong_typing.txt |
Q:
Defining __repr__ when subclassing set in Python
I'm trying to subclass the set object in Python, using code similar to the below, but I can't work out a sensible definition of __repr__ to use.
class Alpha(set):
def __init__(self, name, s=()):
super(Alpha, self).__init__(s)
self.name = name
I'... | Defining __repr__ when subclassing set in Python | I'm trying to subclass the set object in Python, using code similar to the below, but I can't work out a sensible definition of __repr__ to use.
class Alpha(set):
def __init__(self, name, s=()):
super(Alpha, self).__init__(s)
self.name = name
I'd like to define __repr__ in such a way that I can get... | [
"I think I have something that gets you what you want, in addition to showing some benchmarks. They are almost all equivalent though I am sure there is a difference in memory usage.\n#!/usr/bin/env python\n\nimport time\n\nclass Alpha(set):\n def __init__(self, name, s=()):\n super(Alpha, self).__init... | [
11,
2
] | [] | [] | [
"python",
"set",
"subclassing"
] | stackoverflow_0008494358_python_set_subclassing.txt |
Q:
Where am I missing an argument?
I'm about to go blind starring at this problem, so I have to ask:
I have 1 clue: rearranging the code, makes the error message different:
I get the error: min_analyzer = SpaceSeparatedTokenizer() | LowercaseFilter() | mitt_filter()
TypeError: _call_() takes exactly 2 arguments (1 g... | Where am I missing an argument? | I'm about to go blind starring at this problem, so I have to ask:
I have 1 clue: rearranging the code, makes the error message different:
I get the error: min_analyzer = SpaceSeparatedTokenizer() | LowercaseFilter() | mitt_filter()
TypeError: _call_() takes exactly 2 arguments (1 given)
From this code:
import sqlite3... | [
"Your analyzer argument to Schema constructor is incorrect. analyzer must be a function or a class with the __call__ method, hence your error about call.\nhttp://packages.python.org/Whoosh/analysis.html\n",
"You probably just want mitt_filter, otherwise you are executing __call__ on the instantiated object, whic... | [
1,
1
] | [] | [] | [
"python",
"whoosh"
] | stackoverflow_0008495222_python_whoosh.txt |
Q:
python identity dictionary
Possible Duplicate:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?
I need something like a defaultdict. However, for any key that isn't in the dictionary, it should return the key itself.
What is the best way to do tha... | python identity dictionary |
Possible Duplicate:
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?
I need something like a defaultdict. However, for any key that isn't in the dictionary, it should return the key itself.
What is the best way to do that?
| [
"Use the magic __missing__ method:\n>>> class KeyDict(dict):\n... def __missing__(self, key):\n... return key\n... \n>>> x = KeyDict()\n>>> x[2]\n2\n>>> x[2]=0\n>>> x[2]\n0\n>>> \n\n",
"you mean something like the following?\nvalue = dictionary.get(key, key)\n\n",
"class Dict(dict):\n def __g... | [
15,
10,
2
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0008495503_dictionary_python_python_3.x.txt |
Q:
Extract text from Webpages with Python 3.x
I am working with Python 3.x
I want to extract text from several webpages. What is a good library to allow me do just that?
Thanks,
Barry.
A:
http://www.crummy.com/software/BeautifulSoup/
and the documentation to get you started
http://www.crummy.com/software/BeautifulS... | Extract text from Webpages with Python 3.x | I am working with Python 3.x
I want to extract text from several webpages. What is a good library to allow me do just that?
Thanks,
Barry.
| [
"http://www.crummy.com/software/BeautifulSoup/\nand the documentation to get you started\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html\n",
"mechanize is good library but unfortunately not ready for python 3, but you can take a look at lxml.html\n",
"I would suggest using Beautiful Soup and th... | [
3,
1,
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x"
] | stackoverflow_0008495302_beautifulsoup_python_python_3.x.txt |
Q:
Using Celery with SQLAlchemy and Pyramid
I'm creating the web app using Pyramid-1.2.1 with SQLAlchemy as database backend.
Now I need to do some periodic tasks along with this app and I want to use Celery as a task processor and SQLAlchemy as the message queue and the result backend.
1) I've installed Celery-2.1... | Using Celery with SQLAlchemy and Pyramid | I'm creating the web app using Pyramid-1.2.1 with SQLAlchemy as database backend.
Now I need to do some periodic tasks along with this app and I want to use Celery as a task processor and SQLAlchemy as the message queue and the result backend.
1) I've installed Celery-2.1.4 but I can not figure out how to make it wor... | [
"This looks like an issue with version compatibility between celery packages and its dependencies. With the latest version of celery, 2.4.5 your example just works. With 2.1.4 I get the same error.\nIf for any reason you need 2.1.4 version of celery only, you have to find out which dependencies you need to downgrad... | [
4
] | [] | [] | [
"celery",
"pyramid",
"python",
"sqlalchemy"
] | stackoverflow_0008094760_celery_pyramid_python_sqlalchemy.txt |
Q:
Use a context manager to redirect script output to a file?
I'm programming a script where I have an option, to be passed on the command line, whether the script should print its results to stdout or to a predefined results file. A code outline for this is shown below. I now have read a little bit about context man... | Use a context manager to redirect script output to a file? | I'm programming a script where I have an option, to be passed on the command line, whether the script should print its results to stdout or to a predefined results file. A code outline for this is shown below. I now have read a little bit about context managers in Python, but am not really sure whether and how to use a... | [
"A context manager is something you can use with a with statement. It is explicitly designed to:\n\nperform some setup,\ngive you an object, and\nperform some teardown again (even if you raise an exception).\n\nFor example, open can be used as a context manager. In the following code\nwith open(...) as f:\n # do... | [
4
] | [] | [] | [
"contextmanager",
"file_io",
"python"
] | stackoverflow_0008495422_contextmanager_file_io_python.txt |
Q:
How come when I press the Up or Down Arrow keys in the Python interpreter I get ^[[A or ^[[B instead of history?
Possible Duplicate:
Python shell: Arrow keys do not work on remote machine
I have no idea why history won't work in the Python 2.7.2 interpreter. I get strange character groups for each of the arrow ke... | How come when I press the Up or Down Arrow keys in the Python interpreter I get ^[[A or ^[[B instead of history? |
Possible Duplicate:
Python shell: Arrow keys do not work on remote machine
I have no idea why history won't work in the Python 2.7.2 interpreter. I get strange character groups for each of the arrow keys. This doesn't happen in Terminal. BTW I am on Ubuntu 10.04. Here is a screen shot of this hell:
How do I get back... | [
"It looks as if you're using a build from source. It looks like you'll need to rebuild Python after installing the libreadline-dev or equivalent package on your distribution.\nUpdate: There should be no special build steps needed, just running make should do. There are some messages printed at the end about optiona... | [
25
] | [] | [] | [
"interpreter",
"python"
] | stackoverflow_0008495655_interpreter_python.txt |
Q:
Programatically import ICS files to iCalendar
I've written an ICS file using the iCalendar module and python.
My trouble is, how can I tell iCalendar to read the ICS file? I thought I could put it in ~/Library/iCalendar/<--->/Events but it seems that just stores the ICS files once they've been imported.
Does any... | Programatically import ICS files to iCalendar | I've written an ICS file using the iCalendar module and python.
My trouble is, how can I tell iCalendar to read the ICS file? I thought I could put it in ~/Library/iCalendar/<--->/Events but it seems that just stores the ICS files once they've been imported.
Does anyone know a way I could do this?
Thanks,
| [
"You would use Applescript or Python scripting bridge framework. In either case, tell iCal to add the events. \nAn example (in Applescript):\ntell application \"iCal\"\n tell calendar \"Work\"\n set theDate to current date\n make new event at end with properties {description:\"The Event Description\", \... | [
1,
0
] | [] | [] | [
"icalendar",
"python"
] | stackoverflow_0008495145_icalendar_python.txt |
Q:
Python - returning multiple values from function to different arrays
I have a function where I am returning two values. I would like to put the two values directly into two different arrays. I know how to return the output as two different values to be later added to the array, but I don't want to have the tempor... | Python - returning multiple values from function to different arrays | I have a function where I am returning two values. I would like to put the two values directly into two different arrays. I know how to return the output as two different values to be later added to the array, but I don't want to have the temporary place holders. An example is shown below.
def two_outputs():
outpu... | [
"How about using a helper function?\ndef zippend(lists, values):\n assert len(lists) == len(values)\n for l,v in zip(lists, values):\n l.append(v)\n\nzippend((one_array, two_array), two_outputs())\n\nThe function zippend takes two parameters. The first is an iterable of Lists (what you are referring to as \"a... | [
5,
1,
1,
0
] | [] | [] | [
"arrays",
"function",
"python"
] | stackoverflow_0008494974_arrays_function_python.txt |
Q:
How do I convert integers into high-resolution times in Python? Or how do I keep Python from dropping zeros?
Currently, I'm using this to calculate the time between two messages and listing the times if they are above 20 seconds.
def time_deltas(infile):
entries = (line.split() for line in open(INFILE, "r"))... | How do I convert integers into high-resolution times in Python? Or how do I keep Python from dropping zeros? | Currently, I'm using this to calculate the time between two messages and listing the times if they are above 20 seconds.
def time_deltas(infile):
entries = (line.split() for line in open(INFILE, "r"))
ts = {}
for e in entries:
if " ".join(e[2:5]) == "OuchMsg out: [O]":
ts[e[8]] = e[0... | [
"You are yielding floats, so the csv writer turns those floats into strings as it pleases.\nIf you want your output values to be a certain format, yield a string in that format.\nPerhaps something like this?\nprint \"%04.0f\" % (900) # prints 0900\n\n"
] | [
1
] | [] | [] | [
"integer",
"python",
"time"
] | stackoverflow_0008495786_integer_python_time.txt |
Q:
python popen.stdout.readline() hangs
I am having a problem... does anyone knows why this code hangs in the while loop. The loop doesn't seem to catch the last line of the stdout.
working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
l... | python popen.stdout.readline() hangs | I am having a problem... does anyone knows why this code hangs in the while loop. The loop doesn't seem to catch the last line of the stdout.
working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
line = working_file.stdout.readline()
worki... | [
"Does doing a nonblocking read help you out?\nimport fcntl\nimport os\n\ndef nonBlockReadline(output):\n fd = output.fileno()\n fl = fcntl.fcntl(fd, fcntl.F_GETFL)\n fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)\n try:\n return output.readline()\n except:\n return ''\n\nworking_fil... | [
7
] | [] | [] | [
"popen",
"python",
"stdout"
] | stackoverflow_0008495794_popen_python_stdout.txt |
Q:
An XML file inside HDF5, h5py
I am using h5py to save data (float numbers), in groups. In addition to the data itself, I need to include an additional file (an .xml file, containing necessary information) within the hdf5. How do i do this? Is my approach wrong?
f = h5py.File('filename.h5')
f.create_dataset('/data/... | An XML file inside HDF5, h5py | I am using h5py to save data (float numbers), in groups. In addition to the data itself, I need to include an additional file (an .xml file, containing necessary information) within the hdf5. How do i do this? Is my approach wrong?
f = h5py.File('filename.h5')
f.create_dataset('/data/1',numpy_array_1)
f.create_dataset(... | [
"One option is to add it as a variable-length string dataset.\nhttp://code.google.com/p/h5py/wiki/HowTo#Variable-length_strings\nE.g.:\nimport h5py\nxmldata = \"\"\"<xml>\n<something>\n <else>Text</else>\n</something>\n</xml>\n\"\"\"\n\n# Write the xml file...\nf = h5py.File('test.hdf5', 'w')\nstr_type = h5py.ne... | [
5,
3
] | [] | [] | [
"h5py",
"hdf5",
"python"
] | stackoverflow_0008493343_h5py_hdf5_python.txt |
Q:
Reuse of an inner function in Python
I'm trying to figure out how to use a Python 3 function (using nonlocal variables) within more than one other function without defining it all over again. Here's a very simplified example of what I mean:
def inner(airplane):
nonlocal var
if airplane == "Alpha":
... | Reuse of an inner function in Python | I'm trying to figure out how to use a Python 3 function (using nonlocal variables) within more than one other function without defining it all over again. Here's a very simplified example of what I mean:
def inner(airplane):
nonlocal var
if airplane == "Alpha":
var = a
elif airplane == "Beta":
... | [
"Are you just learning to programme?\nForget about nonlocal anything. The correct way to do this is to return var with return var, and then assign the result of that in the calling context:\nvar = inner(airplane)\n\nEdit:\nWhere you are simply calling:\nplaneandoffset(airplane)\n\nYou are not doing anything with th... | [
3
] | [] | [] | [
"function",
"python",
"python_3.x",
"python_nonlocal"
] | stackoverflow_0008496011_function_python_python_3.x_python_nonlocal.txt |
Q:
Django url match not matching for rule in urls.py
urls.py
urlpatterns = patterns('',
(r'^page/\w+/$', get_page),
(r'', main),
)
calling : http://localhost:8081/page/cricket
calls the main, function and not get_page
How can I make this work?
A:
The regular expression is wrong. It would match http://loc... | Django url match not matching for rule in urls.py | urls.py
urlpatterns = patterns('',
(r'^page/\w+/$', get_page),
(r'', main),
)
calling : http://localhost:8081/page/cricket
calls the main, function and not get_page
How can I make this work?
| [
"The regular expression is wrong. It would match http://localhost:8081/page/cricket/ or http://localhost:8081/page/dog/. It does not match http://localhost:8081/page/cricket because the regular expression requires a / at the end. \nBased on your comments and question you may want something like:\n (r'^page/(?P... | [
3,
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0008495897_django_django_urls_python.txt |
Q:
python zipfile.ZipFile() method generates 20G zip file from 6M original
I am running a python program (v2.7) which zips output so that it can be emailed.
Usually this works as expected, but occasionally the zipped file is so huge that the machine runs out of disk space. Yet when I zip the file manually using the ... | python zipfile.ZipFile() method generates 20G zip file from 6M original | I am running a python program (v2.7) which zips output so that it can be emailed.
Usually this works as expected, but occasionally the zipped file is so huge that the machine runs out of disk space. Yet when I zip the file manually using the finder, it works fine.
In this case, the 6MB file gets zipped down to a 1.6MB... | [
"Do you maybe create that zip file in the same directory and the program is then trying to add the zipfile itself to the zip file?\n",
"Its Linux?, i think you are including hidden files and folders?\n"
] | [
1,
0
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0008495912_python_zip.txt |
Q:
Python xml creation from list with element levels
This is the first time i am working with xml processing.
The following python list contains all the elements/nodes that will used to create the final xml.
Every item of the list is also a list composed of element/node and level pair.
For example:
['root', 1]
'root... | Python xml creation from list with element levels | This is the first time i am working with xml processing.
The following python list contains all the elements/nodes that will used to create the final xml.
Every item of the list is also a list composed of element/node and level pair.
For example:
['root', 1]
'root' is the name of the element, and 1 is level or positio... | [
"keep a \"lastforlevel\" array which stores the last item appended at a given level. If you try create an element for level n, you need to append it to lastforlevel[n-1].\n",
"I had the same problem last week. Here is my solution \nhttp://www.yilmazhuseyin.com/blog/dev/convert-python-dict-xml/\nBasic difference ... | [
1,
0,
0
] | [] | [] | [
"list",
"python",
"xml"
] | stackoverflow_0008496052_list_python_xml.txt |
Q:
get real time output from Popen
# cmd = "python subscript.py"
cmd = "ping localhost -n 10"
ofile =open("C:\file.log","w")
sp = subprocess.Popen(cmd,bufsize = 1, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
while True:
sp.poll()
line = sp.stdout.readline()
#eline = sp.stderr.readline()
if li... | get real time output from Popen | # cmd = "python subscript.py"
cmd = "ping localhost -n 10"
ofile =open("C:\file.log","w")
sp = subprocess.Popen(cmd,bufsize = 1, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
while True:
sp.poll()
line = sp.stdout.readline()
#eline = sp.stderr.readline()
if line:
print line
ofile.... | [
"Have you tried calling sys.stdout.flush() in your subprocess after the print statement? You could be running into output buffering.\n"
] | [
2
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0008495701_popen_python_subprocess.txt |
Q:
google-app-engine: How to apply filter in query when filter parameter is db.ReferenceProperty?
This is next step to this question, where I need to run queries and apply filters.
Here is my Model
from google.appengine.ext import db
Class Car(db.Model):
name=db.StringProperty()
model=db.StringProperty()
... | google-app-engine: How to apply filter in query when filter parameter is db.ReferenceProperty? | This is next step to this question, where I need to run queries and apply filters.
Here is my Model
from google.appengine.ext import db
Class Car(db.Model):
name=db.StringProperty()
model=db.StringProperty()
mileage=db.IntegerProperty()
person = db.ReferenceProperty(Person, collection_name='person')
C... | [
"You can only use filter on indexed attributes. person.name is from other entity! In sql you would need to use join (which is impossible when data grows big), in google bigtable like in many other non-relational databases tables join is not possible. Luckily your case is very simple, you can select all cars if you ... | [
2
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0008496362_google_app_engine_gql_python.txt |
Q:
django how to access an already uploaded video
i have uploaded a video to django and it's all working fine ..
but i need to render that video in the view..
django cant access it
any idea how to make django template see my uploaded files
modles.py :
class VideoData(models.Model):
title = models.CharField(ma... | django how to access an already uploaded video | i have uploaded a video to django and it's all working fine ..
but i need to render that video in the view..
django cant access it
any idea how to make django template see my uploaded files
modles.py :
class VideoData(models.Model):
title = models.CharField(max_length=200)
file = models.FileField(upload_to=... | [
"Your video is uploaded media_root/vid directory(just check it on file system to make sure).\nso when you call it from template you should write your media template in front of your video image. (So your url could be /media/vids/name.mov)\nI also noticed that you are writing hardcoded video name here use something ... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008496331_django_python.txt |
Q:
How can I use pysandbox in a Django request handler?
I want to use pysandbox to allow users to run code on my server. I'm using Django's internal server (manage.py runserver) with this request handler:
def try_sandbox(request):
from sandbox import Sandbox
def func(a, b):
return a + b
sandbox = ... | How can I use pysandbox in a Django request handler? | I want to use pysandbox to allow users to run code on my server. I'm using Django's internal server (manage.py runserver) with this request handler:
def try_sandbox(request):
from sandbox import Sandbox
def func(a, b):
return a + b
sandbox = Sandbox()
result = sandbox.call(func, 1, 2)
return... | [
"I've not encountered this error myself so I may be absolutely wrong - but it seems like if pysandbox doesn't like running on non-main threads then you should ensure that it is running on the main thread. If you look at the django runserver documentation, it seems that a --nothreading option has been introduced i... | [
2
] | [] | [] | [
"django",
"pysandbox",
"python"
] | stackoverflow_0008398464_django_pysandbox_python.txt |
Q:
Construct a tree from list os file paths (Python) - Performance dependent
Hey I am working on a very high performance file-managing/analyzing toolkit written in python.
I want to create a function that gives me a list or something like that in a tree format.
Something like in this question (java-related)
From:
di... | Construct a tree from list os file paths (Python) - Performance dependent | Hey I am working on a very high performance file-managing/analyzing toolkit written in python.
I want to create a function that gives me a list or something like that in a tree format.
Something like in this question (java-related)
From:
dir/file
dir/dir2/file2
dir/file3
dir3/file4
dir3/file5
Note: the list of paths ... | [
"Now that you clarified the question a bit more, I guess the following is what you want:\nfrom collections import defaultdict\n\ninput_ = '''dir/file\ndir/dir2/file2\ndir/file3\ndir2/alpha/beta/gamma/delta\ndir2/alpha/beta/gamma/delta/\ndir3/file4\ndir3/file5'''\n\nFILE_MARKER = '<files>'\n\ndef attach(branch, trun... | [
23,
1,
0
] | [] | [] | [
"path",
"python",
"recursion",
"tree"
] | stackoverflow_0008484943_path_python_recursion_tree.txt |
Q:
What is StringIO() used for in this script?
I just started using Django and Python and I'm trying to build a photo app. This script is generating thumbnails and I'd like to do that myself. Unfortunately I don't understand what StringIO() is doing. The Python Docs aren't very helpful to me in that case.
Can someone... | What is StringIO() used for in this script? | I just started using Django and Python and I'm trying to build a photo app. This script is generating thumbnails and I'd like to do that myself. Unfortunately I don't understand what StringIO() is doing. The Python Docs aren't very helpful to me in that case.
Can someone please explain to me what StringIO() does in thi... | [
"StringIO is a class which can be used as a file-like object. You can use it exactly as you would a regular file, except instead of the data being written to disk, it will be written to a buffer ( a string buffer ) in memory.\nIn this script it looks like the image is first saved to a StringIO memory buffer, and af... | [
2,
0
] | [] | [] | [
"django",
"frameworks",
"python",
"stringio"
] | stackoverflow_0008496711_django_frameworks_python_stringio.txt |
Q:
Determine whether the current Linux console supports 256 colours?
Is there any way to check whether the 'current' console supports 256 colours in Python under Linux?
I specifically dont want to use curses.
A:
As discussed in the comments, the correct solution is to use curses.
>>> import curses
>>> curses.setupt... | Determine whether the current Linux console supports 256 colours? | Is there any way to check whether the 'current' console supports 256 colours in Python under Linux?
I specifically dont want to use curses.
| [
"As discussed in the comments, the correct solution is to use curses.\n>>> import curses\n>>> curses.setupterm()\n>>> curses.tigetnum(\"colors\")\n... 8\n\n",
"There is no portable way to detect whether a console or terminal supports 256 colors because there is no common supported interface through which to ask t... | [
12,
3
] | [] | [] | [
"colors",
"console",
"linux",
"python"
] | stackoverflow_0008495605_colors_console_linux_python.txt |
Q:
Django - Static pictures not found
Helo all,
I am running a Django application in development mode. I have collected static files into a /static/images/ directory in my project.
In my template I try to link an example image:
<img src="{{ STATIC_URL }}items/no_image.jpeg"/>
{{ STATIC_URL }}items/no_image.jpeg
... | Django - Static pictures not found | Helo all,
I am running a Django application in development mode. I have collected static files into a /static/images/ directory in my project.
In my template I try to link an example image:
<img src="{{ STATIC_URL }}items/no_image.jpeg"/>
{{ STATIC_URL }}items/no_image.jpeg
(The bottom line is printing for debug p... | [
"Found out the problem. The problem was I was using the wrong directory. STATIC_URL was named /site_media/ when it should be /static/. Changed it and everything now works clear as water...\n",
"I think it's slash issue. Try\nSTATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static')\n\n",
"Maybe you've mis... | [
3,
2,
0,
0
] | [] | [] | [
"django",
"django_staticfiles",
"python",
"static_files"
] | stackoverflow_0008474921_django_django_staticfiles_python_static_files.txt |
Q:
running subprocess.Popen under apache+mod_wsgi is always returning an error with a returncode of -6
I'm hoping someone's seen this -
I'm running django-compressor, taking advantage of the lessc setup to render/compress the less into CSS on the file. It works perfectly when invoked from the development server, but... | running subprocess.Popen under apache+mod_wsgi is always returning an error with a returncode of -6 | I'm hoping someone's seen this -
I'm running django-compressor, taking advantage of the lessc setup to render/compress the less into CSS on the file. It works perfectly when invoked from the development server, but when run underneath apache+mod_wsgi it is consistently returning an error.
To debug this, I have run the... | [
"Are you using Python 2.7.2 by chance?\nThat version of Python introduced a bug which cause fork() in sub interpreters to fail:\nhttp://bugs.python.org/issue13156\nYou will have to force WSGI application to run in main Python interpreter of the process by setting:\nWSGIApplicationGroup %{GLOBAL}\n\nIf running multi... | [
8
] | [] | [] | [
"apache",
"django",
"django_compressor",
"mod_wsgi",
"python"
] | stackoverflow_0008494335_apache_django_django_compressor_mod_wsgi_python.txt |
Q:
Python: For loop skip in If
Why do the line "old_langpacks.append(act_item)" get skipped?
When I use just the for loop, without the if, then it works.
if act_file == "Languages.csv":
temp_list = open(act_file,"r")
for act_item in temp_list:
old_langpacks.append(act_item)
else:
... | Python: For loop skip in If | Why do the line "old_langpacks.append(act_item)" get skipped?
When I use just the for loop, without the if, then it works.
if act_file == "Languages.csv":
temp_list = open(act_file,"r")
for act_item in temp_list:
old_langpacks.append(act_item)
else:
pass
| [
"The reason it is not working is because your if condition is evaluating to false.\nIn addition to what Mark Byers suggested one thought came to mind:\nIs it possible that act_file is a file object, opposed to a string which represents the name of the file?\nHow is act_file created? \nIf you obtain it via something... | [
2,
0
] | [] | [] | [
"for_loop",
"if_statement",
"loops",
"python",
"skip"
] | stackoverflow_0008497433_for_loop_if_statement_loops_python_skip.txt |
Q:
gesture recognition with kinect with python: hmm learning
I want to do gesture recognition in python with kinect.
After reading up on some theory, I think one of the best method is unsupervised learning with Hidden Markov Model (HMM) (baum welch or some EM method) with some known gesture data, to achieve a set of... | gesture recognition with kinect with python: hmm learning | I want to do gesture recognition in python with kinect.
After reading up on some theory, I think one of the best method is unsupervised learning with Hidden Markov Model (HMM) (baum welch or some EM method) with some known gesture data, to achieve a set of trained HMM (one for each gesture that I want to recognize).
I... | [
"First of all: This is a very special question, you'll need a machine learning expert here. Unfortunately there's no ML equivalent here among the stack exchange sites yet ... maybe there'll be one some day. :)\nI guess your approach is valid, just some remarks:\n\nThe HMM class which you just instantiate with HMM()... | [
2,
1
] | [] | [] | [
"hidden_markov_models",
"machine_learning",
"python"
] | stackoverflow_0008490462_hidden_markov_models_machine_learning_python.txt |
Q:
Python modules for version 2.6 / 2.7
I need to use two python versions on my Ubuntu system: 2.6.5 and 2.7.2 (for compatibility with some third-party projects).
For both of them, I need the PyGTK package.
I installed the latest version of this package, but strangely, only the 2.6 version identifies it; the 2.7 vers... | Python modules for version 2.6 / 2.7 | I need to use two python versions on my Ubuntu system: 2.6.5 and 2.7.2 (for compatibility with some third-party projects).
For both of them, I need the PyGTK package.
I installed the latest version of this package, but strangely, only the 2.6 version identifies it; the 2.7 version cannot find it:
erelsgl@ubuntu:/usr/li... | [
"You may need to download and install pyGTK separately for both versions. Don't use the OS package installer.\nDownload separate egg packages of pyGTK for both versions. Then run setup.py of each egg using the respective python interpreter. E.g.\n`...../python26/python /download/pyGTK-2.6/setup.py install\n...../py... | [
0,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0008110132_pygtk_python.txt |
Q:
Python write to file based on offset
I want to create a python program which splits up a files into segments of specified width, and then a consumer program takes the segments and creates a duplicate of the original file. The segments might be out of order so I intent to use the offset value to write to the file.
... | Python write to file based on offset | I want to create a python program which splits up a files into segments of specified width, and then a consumer program takes the segments and creates a duplicate of the original file. The segments might be out of order so I intent to use the offset value to write to the file.
Is there a way I can achieve this with wit... | [
"I still could nt figure out what is your intent - but this version of combine_bytes will get rid of your \"mother of your inefficiency\" part (which actually is exactly that)\ndef combine_bytes(in_buff, in_offset, in_data, in_width):\n #something like memcpy would be nice\n #in_buff[in_offset:in_offset + in_... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008478524_python.txt |
Q:
python saving .pyw to desktop after running a program
from Tkinter import *
import tkMessageBox
from test2_new import *
When I run this, python is saving a .pyw file of test2_new to the deskop. Why is this happening and how do i fix this? Thank you!
A:
A pyw file is a windows specific format that is generated f... | python saving .pyw to desktop after running a program | from Tkinter import *
import tkMessageBox
from test2_new import *
When I run this, python is saving a .pyw file of test2_new to the deskop. Why is this happening and how do i fix this? Thank you!
| [
"A pyw file is a windows specific format that is generated for GUi scripts. It causes windows to open the script directly in a window instead of launching a console. Most likely you are calling your script from the user desktop location. Try changing directories to your script location. Also if you are double click... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008497697_python_tkinter.txt |
Q:
How to obtain the Jacobian from the returned data of the leastsq()?
I am using frequently scipy.optimize.leastsq() for my Ph.D thesis however I have no idea how can I get the estimate of a jacobian from the data that leastsq() returns. I need to know the estimate of a jacobian that is used in minimization to compa... | How to obtain the Jacobian from the returned data of the leastsq()? | I am using frequently scipy.optimize.leastsq() for my Ph.D thesis however I have no idea how can I get the estimate of a jacobian from the data that leastsq() returns. I need to know the estimate of a jacobian that is used in minimization to compare with the finite difference approximation at minimum.
Does anyone has a... | [
"I think the answer is that nobody ever managed to recover the Jacobian from optimize.leastsq.\nlatest threat on this http://mail.scipy.org/pipermail/scipy-user/2011-August/030320.html\nFrom some examples of the covariance matrix returned by leastsq, I think there are many cases where the precision with default set... | [
3
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0008487745_numpy_python_scipy.txt |
Q:
urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection
I need to make an API call (of sorts) in Django as a part of the custom authentication system we require. A username and password is sent to a specific URL over SSL (using GET for those parameters) and the response should be an HTTP 200... | urllib2/pycurl in Django: Fetch XML, check HTTP status, check HTTPS connection | I need to make an API call (of sorts) in Django as a part of the custom authentication system we require. A username and password is sent to a specific URL over SSL (using GET for those parameters) and the response should be an HTTP 200 "OK" response with the body containing XML with the user's info.
On an unsuccessful... | [
"Using M2Crypto:\nfrom M2Crypto import SSL\nctx = SSL.Context('sslv3')\nctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9)\nif ctx.load_verify_locations('ca.pem') != 1:\n raise Exception('No CA certs')\n\nc = SSL.Connection(ctx)\nc.connect(('www.google.com', 443)) # automatically checks ce... | [
3,
0
] | [] | [] | [
"django",
"pycurl",
"python",
"ssl_certificate",
"urllib2"
] | stackoverflow_0008497079_django_pycurl_python_ssl_certificate_urllib2.txt |
Q:
ArcMap Data Driven Pages Dynamic Feature Labels
I am trying to work out a way to change between two sets of labels on a map. I have a map with zip codes that are labeled and I want to be able to output two maps: one with the zip code label (ZIP) and one with a value from a field I have joined to the data (called c... | ArcMap Data Driven Pages Dynamic Feature Labels | I am trying to work out a way to change between two sets of labels on a map. I have a map with zip codes that are labeled and I want to be able to output two maps: one with the zip code label (ZIP) and one with a value from a field I have joined to the data (called chrlabel). The goal is to have one map showing data fo... | [
"8 months too late, but for posterity...\nYou're making things hard on yourself - it would be much easier to set up a duplicate layer and use different layers, then adjust layer visibility. I'm not familiar with VBScript for this sort of thing, but in Python (using ESRI's library) it would look something like so [p... | [
1
] | [] | [] | [
"arcgis",
"arcmap",
"python",
"vbscript"
] | stackoverflow_0005425659_arcgis_arcmap_python_vbscript.txt |
Q:
How create a message protocol
So I have to create a message protocol that works like this:
codFunc arg1 arg2...
ex:
0 'hello world'
10 'user' 'password'
Right now I concatenate to send, and use string.split to read, but for several reasons, that is not the best way.
So my question is, what's the best way to crea... | How create a message protocol | So I have to create a message protocol that works like this:
codFunc arg1 arg2...
ex:
0 'hello world'
10 'user' 'password'
Right now I concatenate to send, and use string.split to read, but for several reasons, that is not the best way.
So my question is, what's the best way to create the protocol? What existing prot... | [
"What is wrong with split is that if your username contains white-space, it will be splited into separate arguments.\nSplit it one time to get responsible function number:\nnum, args = s.split(None, 1)\n\nParse string into arguments, maybe with shlex:\nimport shlex\nargv = shlex.split(args)\n\nRemove surrounding qu... | [
2,
2
] | [] | [] | [
"protocols",
"python",
"web_services"
] | stackoverflow_0008496841_protocols_python_web_services.txt |
Q:
Graceful Primary Key Error handling in Python/psycopg2
Using Python 2.7 and
In [150]: psycopg2.version
Out[150]: '2.4.2 (dt dec pq3 ext)'
I have a simple python scripts that processing transactions and writes data to a database. Occasionally there is an insert that violates my primary key. This is fine, i just wa... | Graceful Primary Key Error handling in Python/psycopg2 | Using Python 2.7 and
In [150]: psycopg2.version
Out[150]: '2.4.2 (dt dec pq3 ext)'
I have a simple python scripts that processing transactions and writes data to a database. Occasionally there is an insert that violates my primary key. This is fine, i just want it to ignore that record and continue on it merry way. Th... | [
"You should rollback transaction on error.\nI've added one more try..except..else construction in the code bellow to show the exact place where exception will occur.\ntry:\n cur = conn.cursor()\n\n try:\n cur.execute(\"\"\"insert into encounter_id_table (\n encounter_id,current_date )\n ... | [
26,
2
] | [] | [] | [
"postgresql",
"psycopg2",
"python",
"sql"
] | stackoverflow_0008497886_postgresql_psycopg2_python_sql.txt |
Q:
Using subprocess.call - if exist an error save the error into a file
I'm trying to save all errors in a file, and I can't find a solutions. I'm too newbie in python, please patience :D
In a "for" I have this line, and works fine, but can't log the errors.
knull = open(os.devnull, 'w')
kerror = open('/tmp/error.log... | Using subprocess.call - if exist an error save the error into a file | I'm trying to save all errors in a file, and I can't find a solutions. I'm too newbie in python, please patience :D
In a "for" I have this line, and works fine, but can't log the errors.
knull = open(os.devnull, 'w')
kerror = open('/tmp/error.log','wb')
proc = subprocess.call(['7z','a', file-Zip, files],stdout = knull... | [
"Firstly, you should use \"a+\" mode to append new messages to an existing file, using \"w\" will overwrite it.\nSecondly, error messages are text messages so you should not use \"b\" mode(which means binary).\nFYI, you may want to use the handy logging module which is the best to handle logging-related tasks :)\n"... | [
0
] | [] | [] | [
"python",
"stderr",
"subprocess"
] | stackoverflow_0008498221_python_stderr_subprocess.txt |
Q:
Can i calculate exp(1+2j) in python?
Can i calculate exp(1+2j) in python?
exp(1+2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
A:
You need a complex version of this function:
cmath.exp(1+2j)
See http://docs.python.org/library/cmath.html
A:... | Can i calculate exp(1+2j) in python? | Can i calculate exp(1+2j) in python?
exp(1+2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
| [
"You need a complex version of this function:\ncmath.exp(1+2j)\n\nSee http://docs.python.org/library/cmath.html\n",
"You may want to import e from the math module to do this.\nFor example:\n>>> from math import e\n>>> print e ** (1+2j)\n(-1.1312043837568135+2.4717266720048188j)\n\n"
] | [
30,
15
] | [] | [] | [
"math",
"python"
] | stackoverflow_0008498310_math_python.txt |
Q:
Express floating point numbers in non standard notation in python?
I am trying to print 1.2e-08 as 12e-09 for display purposes but cannot seem to get the format specifiers.
Is there a way to express floating point numbers in a non standard form without resorting to string operations or using regexes?
Edit: If the... | Express floating point numbers in non standard notation in python? | I am trying to print 1.2e-08 as 12e-09 for display purposes but cannot seem to get the format specifiers.
Is there a way to express floating point numbers in a non standard form without resorting to string operations or using regexes?
Edit: If the question is not clear, I am looking for something that lets me express ... | [
"Check out the decimal module. It should be able to put it out in the format you want.\nhttp://docs.python.org/library/decimal.html\nFor what you are describing (engineering notation), there is a to_eng_string() method.\nEDIT\nIn light of your clarification, you can build the number in parts:\nmyNumber = 1.2e-8\nmy... | [
6
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0008498317_floating_point_python.txt |
Q:
Controlling C++ Output from Python Script
I have a bit of an issue here. I have a Python script which calls binaries compiled from C++. The Python script has its own set of outputs (to standard out and error), which are easily disable-able. The C++ binaries have their own set of outputs (to standard out and err... | Controlling C++ Output from Python Script | I have a bit of an issue here. I have a Python script which calls binaries compiled from C++. The Python script has its own set of outputs (to standard out and error), which are easily disable-able. The C++ binaries have their own set of outputs (to standard out and error, among others) as well; the source can be al... | [
"One way to do this is:\n\nDuplicate in python the file descriptors for stdout and stderr using os.dup.\nRedirect the original stdout and stderr using reopen (from C's stdio) to write to a file of your choice.\n\nNote: reopen isn't available directly from python, but you should be able to call it as in the example ... | [
8,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0008496733_c++_python.txt |
Q:
Using the split function in Python
I am working with the CSV module, and I am writing a simple program which takes the names of several authors listed in the file, and formats them in this manner: john.doe
So far, I've achieved the results that I want, but I am having trouble with getting the code to exclude title... | Using the split function in Python | I am working with the CSV module, and I am writing a simple program which takes the names of several authors listed in the file, and formats them in this manner: john.doe
So far, I've achieved the results that I want, but I am having trouble with getting the code to exclude titles such as "Mr."Mrs", etc. I've been thin... | [
"It depends on how much messy the strings are, in worst cases this regexp-based solution should do the job:\nimport re\nx=re.compile(r\"^\\s*(mr|mrs|ms|miss)[\\.\\s]+\", flags=re.IGNORECASE)\nx.sub(\"\", text)\n\n(I'm using re.compile() here since for some reasons Python 2.6 re.sub doesn't accept the flags= kwarg..... | [
3,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008498514_csv_python.txt |
Q:
python facebook sdk call to facebook is slow when compared to command line curl
I am using facebook python Graph API. When i am calling put_object to write to news feed it is taking about 12-14 sec to complete the call. When i run from command line using curl with same parameters i get the response back in 1.2 sec... | python facebook sdk call to facebook is slow when compared to command line curl | I am using facebook python Graph API. When i am calling put_object to write to news feed it is taking about 12-14 sec to complete the call. When i run from command line using curl with same parameters i get the response back in 1.2 seconds.
I ran the profiler on the python code and from i see that it is spending 99.5%... | [
"Direct command-line CURL is bound to be faster than urllib or urllib2. If you want speed, you could replace the call using pycurl (which is also a C-extension) whereas urllib is a python module written on top of httplib. \nWhat more you could do is, if you're flexible enough to use a Tornado server, use the async ... | [
0,
0
] | [] | [] | [
"facebook",
"performance",
"python",
"sdk"
] | stackoverflow_0005131262_facebook_performance_python_sdk.txt |
Q:
set(filter) repetition
I maintain a set that needs to be progressively shrunk, according to various conditions.
For example:
acceptable = read_input()
acceptable.rank_by_x()
acceptable = set(filter(is_rank_x_top_100, acceptable))
acceptable.rank_by_y()
acceptable = set(filter(is_rank_y_top_10, acceptable))
It wor... | set(filter) repetition | I maintain a set that needs to be progressively shrunk, according to various conditions.
For example:
acceptable = read_input()
acceptable.rank_by_x()
acceptable = set(filter(is_rank_x_top_100, acceptable))
acceptable.rank_by_y()
acceptable = set(filter(is_rank_y_top_10, acceptable))
It works, but the set(filter()) co... | [
"If you're using Python 3 or Python 2.7, you can use set comprehensions:\nacceptable = {i for i in acceptable if is_rank_x_top_100(i)}\n\n",
"You may collapse this to:\nacceptable = set()\n#...\nacceptable = set(filter(is_rank_y_top_10,\n filter(is_rank_x_top_100, acceptable)))\n\nOr use co... | [
3,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008498381_python_python_3.x.txt |
Q:
Getting "code" instead of "access_token" in desktop application
In spite of setting Auth Token Parameter of my application to URI Fragment (#access_token=...), I keep being redirected to the address with code in the text. I'm using Python 2.7 and cookielib for login. Is there anything else I need to do to get acce... | Getting "code" instead of "access_token" in desktop application | In spite of setting Auth Token Parameter of my application to URI Fragment (#access_token=...), I keep being redirected to the address with code in the text. I'm using Python 2.7 and cookielib for login. Is there anything else I need to do to get access_token instead of code?
| [
"The flow is to get the access token, you need that code....But sorry I don't know how to implement this using Python 2.7...\n"
] | [
0
] | [] | [] | [
"access_token",
"facebook",
"python"
] | stackoverflow_0008498332_access_token_facebook_python.txt |
Q:
Python - Adding a Tkinter Graph to a PyQt Widget
We currently have a fully functional Gui written created using PyQt. My partner wrote a function that graphs a dataSet in Tkinter. My question is, how do we combine the two so they work together?
Here is the graphing function:
def createGraph(self):
import ... | Python - Adding a Tkinter Graph to a PyQt Widget | We currently have a fully functional Gui written created using PyQt. My partner wrote a function that graphs a dataSet in Tkinter. My question is, how do we combine the two so they work together?
Here is the graphing function:
def createGraph(self):
import tkinter as tk
# Send in data as param, OR
... | [
"Here's a PyQt port:\nfrom PyQt4 import QtCore, QtGui\n\nclass Graph(QtGui.QWidget):\n def __init__(self, data, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self._data = data\n self.resize(400, 700)\n self.setWindowTitle('FSPwners')\n self.setAutoFillBackground(True)\... | [
5,
4
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"tkinter"
] | stackoverflow_0008497142_pyqt_pyqt4_python_tkinter.txt |
Q:
How do I abort a socket.recv() from another thread in Python
I have a main thread that waits for connection. It spawns client threads that will echo the response from the client (telnet in this case). But say that I want to close down all sockets and all threads after some time, like after 1 connection.
How would... | How do I abort a socket.recv() from another thread in Python | I have a main thread that waits for connection. It spawns client threads that will echo the response from the client (telnet in this case). But say that I want to close down all sockets and all threads after some time, like after 1 connection.
How would I do it? If I do clientSocket.close() from the main thread, it wo... | [
"I know this is an old thread and that Samuel probably fixed his issue a long time ago. However, I had the same problem and came across this post while google'ing. Found a solution and think it is worthwhile to add.\nYou can use the shutdown method on the socket class. It can prevent further sends, receives or both... | [
28,
9,
3,
2
] | [] | [] | [
"multithreading",
"python",
"recv",
"sockets"
] | stackoverflow_0002915160_multithreading_python_recv_sockets.txt |
Q:
Python ValueError abs of an array
I am new to python and have been unable to figure out how to fix this. I am trying to do an iteration for each value in the array, and return the array of final values. e is a user-input single value, while M is an array of varying length. I am trying to loop the iteration for e... | Python ValueError abs of an array | I am new to python and have been unable to figure out how to fix this. I am trying to do an iteration for each value in the array, and return the array of final values. e is a user-input single value, while M is an array of varying length. I am trying to loop the iteration for each value of E until it closely solves ... | [
"Not sure what you're actually trying to do, but the problem is this:\nwhile abs(E-e*sin(E)-M[i]) > 10**(-4):\n\nAll of those operations in the abs() work elementwise in numpy arrays, so you're doing some things that end with an array, taking the absolute value of every element in that array, then comparing to 10**... | [
1,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0008484091_numpy_python.txt |
Q:
PyQt: How can I get a large list of filenames from the user?
The FileDialog in pyqt is an excellent way to get one path for a file from the user, but is there a good way to get a large number of file selections from the user?
A:
Use QFileDialog.getOpenFileNames to allow the user to select multiple files:
from Py... | PyQt: How can I get a large list of filenames from the user? | The FileDialog in pyqt is an excellent way to get one path for a file from the user, but is there a good way to get a large number of file selections from the user?
| [
"Use QFileDialog.getOpenFileNames to allow the user to select multiple files:\nfrom PyQt4 import QtGui, QtCore\n\nclass Window(QtGui.QWidget):\n def __init__(self):\n QtGui.QWidget.__init__(self)\n layout = QtGui.QVBoxLayout(self)\n self.button = QtGui.QPushButton('Select Files', self)\n ... | [
6,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qfiledialog"
] | stackoverflow_0008498475_pyqt_pyqt4_python_qfiledialog.txt |
Q:
urllib.read() result return null value
I'm trying to read & print the result from google's URL in GAE. When i run the first program, output was blank. then i have added a print statement before printing the url result and run it. Now i got the result.
Why the Program 1 doesn't give any output ?
Program 1
import ... | urllib.read() result return null value | I'm trying to read & print the result from google's URL in GAE. When i run the first program, output was blank. then i have added a print statement before printing the url result and run it. Now i got the result.
Why the Program 1 doesn't give any output ?
Program 1
import urllib
class MainHandler(webapp.RequestHand... | [
"You're using print from inside a WSGI application. Never, ever use print from inside a WSGI application.\nWhat's happening is that your text is being output in the place where the webserver expects to see headers, so your output is not displayed as you expect.\nInstead, you should use self.response.out.write() to ... | [
4,
0
] | [] | [] | [
"google_app_engine",
"python",
"urllib",
"web_applications"
] | stackoverflow_0008484883_google_app_engine_python_urllib_web_applications.txt |
Q:
For loop repeating/stuck? Python 3.2
I am trying to write a python script for Sieve of Eratosthenes. I have everything done, but when I tell the program to test each number if it is a multiple of at least one of the prime numbers below the √input. It goes well but when I try to remove a multiple it works until it ... | For loop repeating/stuck? Python 3.2 | I am trying to write a python script for Sieve of Eratosthenes. I have everything done, but when I tell the program to test each number if it is a multiple of at least one of the prime numbers below the √input. It goes well but when I try to remove a multiple it works until it tries to delete 6 twice... I've been looki... | [
"Your code can be much simplified by the following realisations:\n\nThe numbers up to a number n can easily be generated as needed, they don't have to be calculated berforehand and stored in a list.\n2 is the only even prime, so you only need to test odd numbers.\nAll numbers can be fully factorised into prime fact... | [
2,
1,
1
] | [] | [] | [
"for_loop",
"numbers",
"python",
"sieve_of_eratosthenes"
] | stackoverflow_0008498621_for_loop_numbers_python_sieve_of_eratosthenes.txt |
Q:
libxml2 in python edit of a specific node
I use python with libxml2 for a webapplication.
I need to add an xml node child of one of the articles to an xml with this structure:
<?xml version="1.0" encoding="UTF-8"?>
<archive>
<article>text<span>tag</span></article>
<article>text2<span>tag2</span></article>
... | libxml2 in python edit of a specific node | I use python with libxml2 for a webapplication.
I need to add an xml node child of one of the articles to an xml with this structure:
<?xml version="1.0" encoding="UTF-8"?>
<archive>
<article>text<span>tag</span></article>
<article>text2<span>tag2</span></article>
<article>text3<span>tag3</span></article>
</ar... | [
"If you can narrow down the XPath results to a single node then this code will work:\n#!/usr/bin/env python\n\nimport libxml2\n\ndoc = libxml2.parseFile(\"foo.xml\")\n\nnodes=doc.xpathEval('/archive/article[2]')\nnewElement = nodes[0].newChild(None, 'counter', None)\nnewElement.newProp('count', '1')\nprint nodes[0]... | [
3
] | [] | [] | [
"libxml2",
"python",
"xml"
] | stackoverflow_0008214005_libxml2_python_xml.txt |
Q:
Python 2.6.2: writing lines to file hard wrap at 192 characters
I implemented a function to make a wrapper to write to files. This is the code:
def writeStringToFile(thestring, thefile, mode='w'):
"""Write a string to filename `thefile' to the directory specified in `dir_out'."""
with open(os.path.join(di... | Python 2.6.2: writing lines to file hard wrap at 192 characters | I implemented a function to make a wrapper to write to files. This is the code:
def writeStringToFile(thestring, thefile, mode='w'):
"""Write a string to filename `thefile' to the directory specified in `dir_out'."""
with open(os.path.join(dir_out, thefile), mode) as fh:
fh.write("{0}\n".format(thestri... | [
"My own stupidity -- I was writing strings that had the character sequence \\n in them, and python was rightly interpreting them as newlines. I need to escape them in my string. I'd take this post down if it hadn't already been responded to.\n",
"fh.write() won't wrap long lines. There are two possibilities:\n\... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008482007_python.txt |
Q:
python: find out if running in shell or not (e.g. sun grid engine queue)
is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?
the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.
thanks!
p.... | python: find out if running in shell or not (e.g. sun grid engine queue) | is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?
the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.
thanks!
p.
| [
"The standard way is isatty().\nimport sys\nif sys.stdout.isatty():\n print(\"Interactive\")\nelse:\n print(\"Non-interactive\")\n\n",
"You can use os.getppid() to find out the process id for the parent-process of this one, and then use that process id to determine which program that process is running. Mor... | [
12,
6,
3,
2
] | [] | [] | [
"python",
"shell",
"stdout",
"terminal"
] | stackoverflow_0000967369_python_shell_stdout_terminal.txt |
Q:
Why mocking is still effective after existing a code in nosetests multiple tests?
I have the following code test_A.py which mocks MyClass.mymethod:
from unittest import main
from mocker import Mocker, MockerTestCase
Class test_A(MockerTestCase):
def setUp(self):
self.m=Mock()
MyClass.mymethod = self.m.mo... | Why mocking is still effective after existing a code in nosetests multiple tests? | I have the following code test_A.py which mocks MyClass.mymethod:
from unittest import main
from mocker import Mocker, MockerTestCase
Class test_A(MockerTestCase):
def setUp(self):
self.m=Mock()
MyClass.mymethod = self.m.mock()
self.m.result(None)
self.m.count(0,None)
self.m.replay()
def test_m... | [
"The line:\nMyClass.mymethod = self.m.mock()\n\nreally does replace MyClass.mymethod() with a new object. All subsequent references to MyClass.mymethod will be to the mock object, even if those references are in a different class.\nWhat you want is a way to replace MyClass.mymethod() that only works in class test_A... | [
3
] | [] | [] | [
"nosetests",
"python"
] | stackoverflow_0008499718_nosetests_python.txt |
Q:
Python loop to write across columns in CSV
I'm trying to write a csv as follows: data[0][0] should be in row 1 column A, data[0][1] should be in row 1 column B, data[1][0] should be in row 2 column A, data[1][1] should be in row 2 column B and so on.
If I use something inefficient like the following code, I can w... | Python loop to write across columns in CSV | I'm trying to write a csv as follows: data[0][0] should be in row 1 column A, data[0][1] should be in row 1 column B, data[1][0] should be in row 2 column A, data[1][1] should be in row 2 column B and so on.
If I use something inefficient like the following code, I can write to the csv as intended.
for... | [
"I think the idiomatic way to do this would be as such (not fully understanding your lg variable):\nnum_cols = lg + 6\nfor row in data:\n writer.writerow(row[:num_cols])\n\nIf you weren't doing any processing on the rows in the loop, you could do it even more concisely:\nwriter.writerows(data)\n\nEdit 1\nUpdated... | [
3,
2,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008499833_csv_python.txt |
Q:
sqlite remove non utf-8 characters
I have an sqlite db that has some crazy ascii characters in it and I would like to remove them, but I have no idea how to go about doing it. I googled some stuff and found some people saying to use REGEXP with mysql, but that threw an error saying REGEXP wasn't recognized.
Here ... | sqlite remove non utf-8 characters | I have an sqlite db that has some crazy ascii characters in it and I would like to remove them, but I have no idea how to go about doing it. I googled some stuff and found some people saying to use REGEXP with mysql, but that threw an error saying REGEXP wasn't recognized.
Here is the error I get:
sqlalchemy.exc.Opera... | [
"Well, if you really want to shoehorn a rich unicode string into a plain ascii string \n(and don't mind some goofs), you could use this:\nimport unicodedata as ud\ndef shoehorn_unicode_into_ascii(s):\n # This removes accents, but also other things, like ß‘’“”\n return ud.normalize('NFKD', s).encode('ascii','i... | [
1,
0
] | [] | [] | [
"ascii",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0003586903_ascii_python_sqlalchemy_sqlite.txt |
Q:
Linux Mint 9 Virtualenv ImportError for zlib and PYTHONPATH is empty?
I'm running Mint 9 and I can't get Virtualenv to run. Every time I run it I get an ImportError for zlib, while the Software Manager claims both zlib1g-dev and zlib1g are installed.
One interesting thing is that there's no PYTHONPATH environment... | Linux Mint 9 Virtualenv ImportError for zlib and PYTHONPATH is empty? | I'm running Mint 9 and I can't get Virtualenv to run. Every time I run it I get an ImportError for zlib, while the Software Manager claims both zlib1g-dev and zlib1g are installed.
One interesting thing is that there's no PYTHONPATH environment variable set. Is this typical and could it be the problem why zlib can't b... | [
"virtualenv doesn't export a PYTHONPATH, instead VIRTUAL_ENV is exported, then the sys.path thing is handled by site module.\nThe zlib is in the standard library, and it's configured to be enabled by default, so I guess you didn't have zlib-dev installed.\ntry:\nsudo apt-get install zlib1g-dev\nand recompile yr pyt... | [
0
] | [] | [] | [
"linux_mint",
"python",
"ubuntu",
"virtualenv",
"zlib"
] | stackoverflow_0006636821_linux_mint_python_ubuntu_virtualenv_zlib.txt |
Q:
Using google app engine in development environment to query objects?
The default app_engine development interactive console at http://localhost/_ah/admin is
from google.appengine.api import users
# Say hello to the current user
user = users.get_current_user()
if user:
nickname = user.nickname()
else:
nicknam... | Using google app engine in development environment to query objects? | The default app_engine development interactive console at http://localhost/_ah/admin is
from google.appengine.api import users
# Say hello to the current user
user = users.get_current_user()
if user:
nickname = user.nickname()
else:
nickname = "guest"
print "Hello, " + nickname
I have model which is like
clas... | [
"My code was not in top-level directory\nfrom top.models import Page\n\nthis worked for me\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008494697_google_app_engine_python.txt |
Q:
How to inherit stdin and stdout in python by using os.execv()
First, I wrote a c++ code as follows:
#include <cstdio>
int main()
{
int a,b;
while(scanf("%d %d",&a,&b) == 2)
printf("%d\n",a+b);
return 0;
}
I use g++ -o a a.cpp to complie it.
Afterwards, I wrote python code as follows:
import os... | How to inherit stdin and stdout in python by using os.execv() | First, I wrote a c++ code as follows:
#include <cstdio>
int main()
{
int a,b;
while(scanf("%d %d",&a,&b) == 2)
printf("%d\n",a+b);
return 0;
}
I use g++ -o a a.cpp to complie it.
Afterwards, I wrote python code as follows:
import os,sys
sys.stdin = open("./data.in","r")
sys.stdout = open("./data.ou... | [
"In your python code, you've opened new IO streams and set the sys.stdin and sys.stdout Python names to point to these. They will have their own file descriptors (most likely 3, and 4). However the standard file descriptors, 0, and 1 will remain unchanged, and continue to point at their original locations. These ar... | [
6
] | [] | [] | [
"execv",
"fork",
"python",
"stdin",
"stdout"
] | stackoverflow_0008500047_execv_fork_python_stdin_stdout.txt |
Q:
Creating a .ini generator can't pass IP Address at all
What I'm looking to do is create a .ini generator I've got everything to work but this statement. There will be 5 agents but once I get one working the others are cake.
We have SUT 0 - 15, so do I need a range and why won't this print to the text document? ... | Creating a .ini generator can't pass IP Address at all | What I'm looking to do is create a .ini generator I've got everything to work but this statement. There will be 5 agents but once I get one working the others are cake.
We have SUT 0 - 15, so do I need a range and why won't this print to the text document?
def ipDSS():
ipDss = input('Please enter your SUT numbe... | [
"You are comparing a string to an integer. Try this instead:\nif int(ipDSS) <= 16:\n\nMore info on comparisons in manual.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008500281_python.txt |
Q:
How much slower python classes are compared to their equivalent functions?
When I started learning Python, I created a few applications just using functions and procedural code. However, now I know classes and realized that the code can be much readable (and subjectively easier to understand) if I rewrite it with ... | How much slower python classes are compared to their equivalent functions? | When I started learning Python, I created a few applications just using functions and procedural code. However, now I know classes and realized that the code can be much readable (and subjectively easier to understand) if I rewrite it with classes.
How much slower the equivalent classes may get compared to the function... | [
"To answer the question: yes, it is likely to be a little slower, all else being equal. Some things that used to be variables (including functions) are now going to be object attributes, and self.foo is always going to be slightly slower than foo regardless of whether foo was a global or local originally. (Local va... | [
45,
32,
10,
7
] | [] | [] | [
"class",
"performance",
"python"
] | stackoverflow_0008492624_class_performance_python.txt |
Q:
using python: how create firewall to block/drop network packets
Like the question stated... How to use python to block/drop packets from blacklisted host (MAC address) ... or more specific, ARP packets
I know that *inux has utilities like "iptables" that can perform this ...
is there any modules or solution in p... | using python: how create firewall to block/drop network packets | Like the question stated... How to use python to block/drop packets from blacklisted host (MAC address) ... or more specific, ARP packets
I know that *inux has utilities like "iptables" that can perform this ...
is there any modules or solution in python that can apply on windows or both *inux and windows?
thanks ...... | [
"Short answer: no.\nIptables is command line tool for controling netfilter, a linux kernel module for filtering network packet. This is only for Linux. Windows have his own kernel approach, and same for BSD* system.\nYou might found some tools done in Python for controling one of them, but not all :) Feel free to s... | [
0
] | [] | [] | [
"firewall",
"iptables",
"python"
] | stackoverflow_0008499462_firewall_iptables_python.txt |
Q:
python: Overhead to using classes instead of dictionaries?
First, I'd like to point out that I know OOP concepts and understand the differences between dictionaries and classes. My question is about what makes sense design wise in this case:
I am designing a webapp in python and I have to represent something like ... | python: Overhead to using classes instead of dictionaries? | First, I'd like to point out that I know OOP concepts and understand the differences between dictionaries and classes. My question is about what makes sense design wise in this case:
I am designing a webapp in python and I have to represent something like a book object.
Books have chapters and chapters have titles and ... | [
"This is highly unlikely to be the bottleneck in your application, so worrying about the performance is probably a waste of time. However, if this is the bottleneck or you just have some time on your hands, look into using a namedtuple. It combines the immutability and low memory footprint of a tuple with the nice ... | [
10,
8,
5,
4,
1,
1
] | [] | [] | [
"class",
"dictionary",
"python"
] | stackoverflow_0001290030_class_dictionary_python.txt |
Q:
Counter in a Recursive function
I am new to python and programming in general. I have written a function which will search adjoining elements in an array and look for ones with values within 0.05 of each other much like a floodfill algorithm does. The only difference is I am doing something stupid when it comes to... | Counter in a Recursive function | I am new to python and programming in general. I have written a function which will search adjoining elements in an array and look for ones with values within 0.05 of each other much like a floodfill algorithm does. The only difference is I am doing something stupid when it comes to counting how many time the function ... | [
"So the floodcount() is returning the new count value. But you never store it / use it :)\nReplace lines like:\nfloodcount(x+1, y-1, array, value, count)\n\nWith:\ncount = floodcount(x+1, y-1, array, value, count)\n\n",
"The result you obtain is expected\nUPDATE: My explication (here under) is not exactly right. ... | [
3,
2,
2,
1,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0008500627_python_recursion.txt |
Q:
Django: order_by and filter on integer fields
I have this:
#models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=30)
result = models.IntegerField()
#views.py
def MyView(request):
foo = MyModel.objects.order_by('result')
return render_to_response(... | Django: order_by and filter on integer fields | I have this:
#models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=30)
result = models.IntegerField()
#views.py
def MyView(request):
foo = MyModel.objects.order_by('result')
return render_to_response('foo.html', {'foo': foo})
And instead of integer v... | [
"I have had this issue before it occurs when the database field is set to Char / Varchar instead of Int.\nYou will need to go into the database and alter the field type to ensure you can sort and filter correctly.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006480887_django_python.txt |
Q:
Python matplotlib: memory not being released when specifying figure size
I'm using matplotlib to generate many plots of the results of a numerical simulation. The plots are used as frames in a video, and so I'm generating many of them by repeatedly calling a function similar to this one:
from pylab import *
def p... | Python matplotlib: memory not being released when specifying figure size | I'm using matplotlib to generate many plots of the results of a numerical simulation. The plots are used as frames in a video, and so I'm generating many of them by repeatedly calling a function similar to this one:
from pylab import *
def plot_density(filename,i,t,psi_Na):
figure(figsize=(8,6))
imshow(abs(p... | [
"From the docstring for pylab.figure:\nIn [313]: pylab.figure?\n\n\nIf you are creating many figures, make\n sure you explicitly call \"close\" on\n the figures you are not using, because\n this will enable pylab to properly\n clean up the memory.\n\nSo perhaps try:\npylab.close() # closes the current figur... | [
36,
10
] | [] | [] | [
"matplotlib",
"memory_management",
"python"
] | stackoverflow_0003623600_matplotlib_memory_management_python.txt |
Q:
number of zeroes to prefix file number
The point of this is to find number of zeroes to put in new file names.
Say, if there is 86 files in dir, we need to start file names from 00 (or 01), if there's 600, 001, etc.
dir_ls = os.listdir(os.getcwd())
# number of zeroes to prefix file number
ln = len(str(len(dir_ls)... | number of zeroes to prefix file number | The point of this is to find number of zeroes to put in new file names.
Say, if there is 86 files in dir, we need to start file names from 00 (or 01), if there's 600, 001, etc.
dir_ls = os.listdir(os.getcwd())
# number of zeroes to prefix file number
ln = len(str(len(dir_ls))) - 1
Is it all right, or this can be done... | [
">>> import math\n>>> int(math.ceil(math.log10(86)))\n2\n>>> int(math.ceil(math.log10(600)))\n3\n\n",
"I don't think that you are doing right thing at all.\nIf you are going to place files numbered with a string like '%03.d' % num you will not get that you want in described way.\nSay if you already have 99 files ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008501136_python.txt |
Q:
A small piece of code which attract top_tracks from Last.fm API by pylast software
I modified the code published on smbrown.wordpress.com which can extract the top tracks using the Last.fm API as below:
#!/usr/bin/python
import time
import pylast
import re
from md5 import md5
user_name = '*******'
user_p... | A small piece of code which attract top_tracks from Last.fm API by pylast software | I modified the code published on smbrown.wordpress.com which can extract the top tracks using the Last.fm API as below:
#!/usr/bin/python
import time
import pylast
import re
from md5 import md5
user_name = '*******'
user_password = '*******'
password_hash = pylast.md5("*******")
api_key = '****************... | [
"Apparently some track names do not match your regex, so match() returns None. Catch the exception and examine track.\n"
] | [
1
] | [] | [] | [
"last.fm",
"python"
] | stackoverflow_0008501636_last.fm_python.txt |
Q:
Python Image Library Additive Blending
How can I additively blend two images?
I am trying to create random polygons and I'd like to layer them up.
I have tried Image.Blend and Image.paste however they just 'replace' the pixel values.
I would like to intensify images if that makes sense. So two images that are half... | Python Image Library Additive Blending | How can I additively blend two images?
I am trying to create random polygons and I'd like to layer them up.
I have tried Image.Blend and Image.paste however they just 'replace' the pixel values.
I would like to intensify images if that makes sense. So two images that are half transparent, will layer down to a fully opa... | [
"This could be achieved with the ImageChops module: If you want the \"average\" of two images (channel-wise), simply use\nImageChops.add(image1, image2, 2)\n\n(The last parameter causes the \"sum\" of the images to be divided by 2.) Depending on what exactly you want, ImageChops.multiply might also be useful.\n"
] | [
1
] | [] | [] | [
"blending",
"image",
"python"
] | stackoverflow_0008027931_blending_image_python.txt |
Q:
Representing filesystem table
I’m working on simple class something like “in memory linux-like filesystem” for educational purposes. Files will be as StringIO objects. I can’t make decision how to implement files-folders hierarchy type in Python. I’m thinking about using list of objects with fields: type, name, p... | Representing filesystem table | I’m working on simple class something like “in memory linux-like filesystem” for educational purposes. Files will be as StringIO objects. I can’t make decision how to implement files-folders hierarchy type in Python. I’m thinking about using list of objects with fields: type, name, parent what else? Maybe I should loo... | [
"May be you can try using networkx. You just have to intutive to adapt it to use with files and folder. \nA simple example\nimport os,networkx as nx\nG=nx.Graph()\nfor (path, dirs, files) in os.walk(os.getcwd()):\n bname = os.path.split(path)\n for f in files:\n G.add_edge(bname,f)\n# Now do what ever ... | [
1,
1,
0,
0
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0008501756_filesystems_python.txt |
Q:
Vim python indenting changes code semantics
I'm trying to learn vim :-) Having some real trouble with auto-indent changing the meaning of my python code. Is there any way to get the goodness of autoindent without running into behaviors like the one below?
I start with a python file:
me@host:/tmp$ cat pytest.py ... | Vim python indenting changes code semantics | I'm trying to learn vim :-) Having some real trouble with auto-indent changing the meaning of my python code. Is there any way to get the goodness of autoindent without running into behaviors like the one below?
I start with a python file:
me@host:/tmp$ cat pytest.py
if False:
print('Never',
'print th... | [
"Yeah, don't do that.\nThe whole point of autoindent in VIM is to have the editor guess at where the whitespace ought to go according to language formatting rules. However:\n\nPython whitespace is important, as you know. As the doctor would say: Don't Do That Then.\n",
"Making auto indent work in vim is just a qu... | [
4,
2
] | [] | [] | [
"auto_indent",
"indentation",
"python",
"vim"
] | stackoverflow_0008498712_auto_indent_indentation_python_vim.txt |
Q:
how to import only the class methods in python
I have a GP.py file that I am then running a MyBot.py file from.
In the MyBot.py file, I have the line
from GP import *
I have a suspicion it is importing the whole file instead of just the class methods and class descriptions I want. In the GP.py file, There is code... | how to import only the class methods in python | I have a GP.py file that I am then running a MyBot.py file from.
In the MyBot.py file, I have the line
from GP import *
I have a suspicion it is importing the whole file instead of just the class methods and class descriptions I want. In the GP.py file, There is code in addition to the defintions
| [
"You cannot import class methods separately, you have to import the classes. You can do this by enumerating the classes you want to import:\nfrom GP import class1, class2, class3\n\nNote that this will still load the entire module. This always happens if you import anything from the module. If you have code in that... | [
20,
5,
4,
1
] | [
"If you want to import just some methods from class\nfrom GP.MyClass import MyFunction\n\n"
] | [
-4
] | [
"python"
] | stackoverflow_0008502287_python.txt |
Q:
Executing multiple commands using Popen.stdin
I'd like to execute multiple commands in a standalone application launched from a python script, using pipes. The only way I could reliably pass the commands to the stdin of the program was using Popen.communicate but it closes the program after the command gets execut... | Executing multiple commands using Popen.stdin | I'd like to execute multiple commands in a standalone application launched from a python script, using pipes. The only way I could reliably pass the commands to the stdin of the program was using Popen.communicate but it closes the program after the command gets executed. If I use Popen.stdin.write than the command exe... | [
"If I understand your problem correctly, you want to interact (i.e. send commands and read the responses) with a console application.\nIf so, you may want to check an Expect-like library, like pexpect for Python: http://pexpect.sourceforge.net\nIt will make your life easier, because it will take care of synchroniza... | [
1,
0,
0
] | [
"It sounds like your application is treating input from a pipe in a strange way. This means it won't get all of the commands you send until you close the pipe.\nSo the approach I would suggest is just to do this:\nprocess.stdin.write(\"command1\\n\")\nprocess.stdin.write(\"command2\\n\")\nprocess.stdin.write(\"com... | [
-1
] | [
"popen",
"python"
] | stackoverflow_0002161575_popen_python.txt |
Q:
Match unicode in ply's regexes
I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:
t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
In my markup language parser I match unicode characters by allowing all the c... | Match unicode in ply's regexes | I'm matching identifiers, but now I have a problem: my identifiers are allowed to contain unicode characters. Therefore the old way to do things is not enough:
t_IDENTIFIER = r"[A-Za-z](\\.|[A-Za-z_0-9])*"
In my markup language parser I match unicode characters by allowing all the characters except those I explicitly ... | [
"the re module supports the \\w syntax which:\n\nIf UNICODE is set, this will match the\n characters [0-9_] plus whatever is\n classified as alphanumeric in the\n Unicode character properties database.\n\ntherefore the following examples shows how to match unicode identifiers:\n>>> import re\n>>> m = re.compile(... | [
5,
4,
1,
1,
0
] | [] | [] | [
"character_properties",
"ply",
"python",
"regex",
"unicode"
] | stackoverflow_0000238223_character_properties_ply_python_regex_unicode.txt |
Q:
Using mimetypes.guess_type with email.mime.base.MIMEBase
I'm building SMTP ASCII emails to include attachments and wish to automate the extraction of the "content type" from the proposed attachment using mimetypes.guess_type, then using the result to add it to the mail body by using email.mime.base.MIMEBase.
The p... | Using mimetypes.guess_type with email.mime.base.MIMEBase | I'm building SMTP ASCII emails to include attachments and wish to automate the extraction of the "content type" from the proposed attachment using mimetypes.guess_type, then using the result to add it to the mail body by using email.mime.base.MIMEBase.
The problem I'm encountering is that mimetypes.guess_type produces ... | [
"Well, such kind of \"parsing\" is very easy with python. You may try the code below:\nformat, enc = mimetypes.guess_type(filename)\nmain, sub = format.split('/')\nmb = MIMEBase(main, sub)\n\nor even more compact:\nformat, enc = mimetypes.guess_type(filename)\nmb = MIMEBase(*format.split('/'))\n\n"
] | [
2
] | [] | [] | [
"mime_types",
"python",
"smtp"
] | stackoverflow_0008496779_mime_types_python_smtp.txt |
Q:
Django Persistent DB connections - A different approach
I have gone similar threads like Django persistent database connection and other stuff on same topic.
However Django doesn't officially support persistent connections to MySQL and Mongo(to my limited knowledge).So i tried avoiding a lot of stuff and tried to ... | Django Persistent DB connections - A different approach | I have gone similar threads like Django persistent database connection and other stuff on same topic.
However Django doesn't officially support persistent connections to MySQL and Mongo(to my limited knowledge).So i tried avoiding a lot of stuff and tried to make it simple.So what i did was in my views.py made global c... | [
"If you want to get into such a technical topic, have a look at the django.db package and review how Django's database backends and QuerySet instances interact with each other before you make any fallacious assumptions, suh as that Django opens a new database connection every time it interacts with a database. You'... | [
2
] | [] | [] | [
"django",
"mongodb",
"mysql",
"mysql_python",
"python"
] | stackoverflow_0008502814_django_mongodb_mysql_mysql_python_python.txt |
Q:
Python threads and Lock : Deadlock
I am trying to use locks to write and read data in threads but have a deadlock I can't solve :s.
Here is the thing. For a reason that is not useful in my problem, I have to start a thread that will itself start other threads.
So I have :
main
-> send_gps_data
... | Python threads and Lock : Deadlock | I am trying to use locks to write and read data in threads but have a deadlock I can't solve :s.
Here is the thing. For a reason that is not useful in my problem, I have to start a thread that will itself start other threads.
So I have :
main
-> send_gps_data
-> stream_session
I write in gpsDat... | [
"try with calling the lock.release method :\ndef stream_session(gpsData, session, lock):\n for report in session:\n if report.get(\"class\") == \"TPV\":\n print \":\"\n lock.acquire()\n fill_gpsdata(gpsData, session, report)\n lock.release() # better to call t... | [
7
] | [] | [] | [
"deadlock",
"multithreading",
"python"
] | stackoverflow_0008503301_deadlock_multithreading_python.txt |
Q:
Python: Bulk insert data into SQL Server
I want to quickly put data into a sql server database. Is there a possibility to access the bulk copy functionality of SqlBulkCopy from CPython? I know it would be possible from IronPython and I also know that I could create text files which I could load via T-SQL. But I wo... | Python: Bulk insert data into SQL Server | I want to quickly put data into a sql server database. Is there a possibility to access the bulk copy functionality of SqlBulkCopy from CPython? I know it would be possible from IronPython and I also know that I could create text files which I could load via T-SQL. But I would prefer a solution where I can pass in data... | [
"The flat file solution would be the simplest solution, but if you really need an alternative then you might be able to use ctypes to drive the SQL Server ODBC bulk copy extension.\n"
] | [
0
] | [] | [] | [
"bulkinsert",
"python",
"sql_server"
] | stackoverflow_0008186434_bulkinsert_python_sql_server.txt |
Q:
Defacto template application in Python
Is there a defacto template application for Python?
I am trying to auto generate C code for use in unit tests from python
My original approach using print statements is very clunky and error prone
It struck me that a template application such as those used in web app developm... | Defacto template application in Python | Is there a defacto template application for Python?
I am trying to auto generate C code for use in unit tests from python
My original approach using print statements is very clunky and error prone
It struck me that a template application such as those used in web app development might be a more elegant solution
My init... | [
"While there are many standalone and powerful template engines in Python there is one in Python standard library.\nThere is Template class in string module that implements PEP 292 \"Simpler String Substitutions\" that is very easy to learn and use. Personally I prefer to use this in my unit tests.\n",
"I don't th... | [
5,
4
] | [] | [] | [
"c",
"python",
"templates",
"unit_testing"
] | stackoverflow_0008503720_c_python_templates_unit_testing.txt |
Q:
How do I write a string literal that includes quotation marks?
I want to create a string with this exact text: nuke.execute("Write1", 1, 10, 1)
Simply surrounding it with double quotes, like "nuke.execute("Write1", 1, 10, 1)", doesn't work:
>>> "nuke.execute("Write1", 1, 10, 1)"
File "<stdin>", line 1
"nuke.... | How do I write a string literal that includes quotation marks? | I want to create a string with this exact text: nuke.execute("Write1", 1, 10, 1)
Simply surrounding it with double quotes, like "nuke.execute("Write1", 1, 10, 1)", doesn't work:
>>> "nuke.execute("Write1", 1, 10, 1)"
File "<stdin>", line 1
"nuke.execute("Write1", 1, 10, 1)"
^
SyntaxError: inval... | [
"Simply enclose it in single quotes:\n'nuke.execute(\"Write1\", 1, 10, 1)'\n\nThere are several alternatives, such as escaping the embedded quotes with backslashes:\n\"nuke.execute(\\\"Write1\\\", 1, 10, 1)\"\n\nor using triple-quoted strings:\n\"\"\"nuke.execute(\"Write1\", 1, 10, 1)\"\"\"\n\nor\n'''nuke.execute(\... | [
4,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008504095_python_string.txt |
Q:
How to pass object between python instances
I have a genetic expression tree program to control a bot. I have a GP.py and a MyBot.py. I need to be able to have the MyBot.py access an object created in GP.py
The GP.py is starting the MyBot.py via the os.system() command
I have hundreds of tree objects in the GP.py ... | How to pass object between python instances | I have a genetic expression tree program to control a bot. I have a GP.py and a MyBot.py. I need to be able to have the MyBot.py access an object created in GP.py
The GP.py is starting the MyBot.py via the os.system() command
I have hundreds of tree objects in the GP.py file and the MyBot.py needs to evaluate them.
I c... | [
"You could serialize the object with the pickle module (or maybe json?)\nIf you really want to stick with os.system, then you could have MyBot.py write the pickled object to a file, which GP.py could read once MyBot.py returns.\nIf you use the subprocess module instead, then you could have MyBot.py write the pickle... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008500225_python.txt |
Q:
Using ManyToMany extra fields from template in Django
I'll use a slightly simplified version of the example from Djano's docs.
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person,... | Using ManyToMany extra fields from template in Django | I'll use a slightly simplified version of the example from Djano's docs.
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class MembershipInfo(models.Model):... | [
"You can try the following:\n{% for person in person_list.all %}\n {% for membership_info in person.members_set.all }}\n {{ membership_info.invite_reason }}\n {% endfor %}\n{% endfor %}\n\nIt is not very efficient, but it's the only option I can think of that uses solely templates.\nEdit. Another optio... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008504157_django_python.txt |
Q:
Python subprocess.check_output with ± characters
I'm using a subprocess.check_output call to a MS DOS command line application to return the stdout string from the application.
The return from the check_ouput is information about the command just run, a new line containing the result I'm after and another new line... | Python subprocess.check_output with ± characters | I'm using a subprocess.check_output call to a MS DOS command line application to return the stdout string from the application.
The return from the check_ouput is information about the command just run, a new line containing the result I'm after and another new line. Specifically the return string looks like this:
b'0m... | [
"MS DOS aplications use a different character encoding than Windows Latin (cp1252) or the civilized world (web + unix: utf-8) -- for backwards compatibility purposes, they use CP850 code page.\nAll you have to do to have a proper Python unicode from this string is to decode it with the CP850 encoding, like in:\n>>>... | [
2,
1
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0008504136_python_unicode.txt |
Q:
Parsing emails with bad mime types in python
I am trying to use python's imaplib and email.feedparser to grab an attachment out of a gmail inbox. The email is generated by an external party and sent to us, so I have no control over it.
The trouble is that the message I am trying to parse has msg.get_content_mainty... | Parsing emails with bad mime types in python | I am trying to use python's imaplib and email.feedparser to grab an attachment out of a gmail inbox. The email is generated by an external party and sent to us, so I have no control over it.
The trouble is that the message I am trying to parse has msg.get_content_maintype() return 'text' instead of 'multitype'. As a re... | [
"As email.parser.FeedParser documentation says you can use _factory parameter to provide your own Message class. You could put your own class derived from email.message.Message that will replace message contenttype with the correct one if this message was composed in \"Produced By Microsoft MimeOLE ...blablabla\".\... | [
0
] | [] | [] | [
"attachment",
"email",
"mime_types",
"python"
] | stackoverflow_0008496557_attachment_email_mime_types_python.txt |
Q:
Django XMPP Connection pooling
How can i pool a connection to XMPP server in django so that it is available across multiple requests. I don't want to connect and authenticate on every request which makes it a bit slow. Is this possible?
EDIT:
I am using xmpppy python xmpp library
A:
As xmpppy has its own main l... | Django XMPP Connection pooling | How can i pool a connection to XMPP server in django so that it is available across multiple requests. I don't want to connect and authenticate on every request which makes it a bit slow. Is this possible?
EDIT:
I am using xmpppy python xmpp library
| [
"As xmpppy has its own main loop I suggest to use it in a separate thread or even start separately. Actually you do have two separate applications: website and xmpp-client and it is normal to run them separately.\nIn this case you may use different ways to communicate between your applications: pipes between thread... | [
2
] | [] | [] | [
"connection_pooling",
"django",
"python",
"xmpp"
] | stackoverflow_0008500455_connection_pooling_django_python_xmpp.txt |
Q:
merge columns of a csv file in python with variable entries in every row in?
I have 2 csv files
One has traceroutes to different IP addresses(The last entry here is the target IP) also (their are variable number of entries in every row as different routes need different no. of hops)
other has a list of targets and... | merge columns of a csv file in python with variable entries in every row in? | I have 2 csv files
One has traceroutes to different IP addresses(The last entry here is the target IP) also (their are variable number of entries in every row as different routes need different no. of hops)
other has a list of targets and their real world positional coordinates
some targets in first file dont have an e... | [
"import csv\n\nip_file = open(\"ipfile.csv\")\nposition_file = open(\"positionfile.csv\")\noutput = open(\"output.csv\", \"wt\")\n\nips = {} \n\n# create a CSV reader for the proper csv file with locations:\nreader = csv.reader(position_file)\nfor line in reader:\n ips[line[0]] = line[1]\n\n\n#now you have th... | [
0
] | [] | [] | [
"csv",
"merge",
"python"
] | stackoverflow_0008504089_csv_merge_python.txt |
Q:
Xpath query to get the parent Element text and its child element attribute values?
I have the following XML :
<sample>
<Message number="2">
<Title>Program pointer has been reset</Title>
<Description>
The program pointer of task
<arg format="%s" ordinal="3" />
has been reset.
</Description>
</Me... | Xpath query to get the parent Element text and its child element attribute values? | I have the following XML :
<sample>
<Message number="2">
<Title>Program pointer has been reset</Title>
<Description>
The program pointer of task
<arg format="%s" ordinal="3" />
has been reset.
</Description>
</Message>
</sample>
I'm trying to get the decription text with arg attribute values. Somet... | [
"With XPath 2.0 or XQuery 1.0 you could use string-join(/sample//Message[@number = 2]/Description/(text() | */@*), ''). I am not sure whether Python gives you access to an XPath 2.0 or XQuery 1.0 library.\n"
] | [
0
] | [] | [] | [
"python",
"xpath"
] | stackoverflow_0008504349_python_xpath.txt |
Q:
Serialize collection to parse in python
I have a collection of simple elements in C#. Element is like:
public class Element
{
public string AName { get; private set; }
public string PName { get; private set; }
public string Value { get; set; }
}
I need to pass this collection as a string to a Python... | Serialize collection to parse in python | I have a collection of simple elements in C#. Element is like:
public class Element
{
public string AName { get; private set; }
public string PName { get; private set; }
public string Value { get; set; }
}
I need to pass this collection as a string to a Python script. And in python for each element I nee... | [
"If there is some character which you can guarantee is not in the strings for AName,PName and Value then you could use that character as a separator.\nIn C#, you could \"serialize\" the information by simply joining the three strings with the separator, e.g. \"foo,bar,baz\".\nThen in Python, the information could b... | [
1,
0
] | [] | [] | [
"c#",
"deserialization",
"python",
"serialization"
] | stackoverflow_0008504789_c#_deserialization_python_serialization.txt |
Q:
Upload a file in Google App Engine and making it downloadable
I am new with google app engine and I want to use it as a server to enable people download a file. I have gone through the tutorials in python. I didnt find anything to actually guide me how to upload files to the server for this purpose.
A:
The Blob... | Upload a file in Google App Engine and making it downloadable | I am new with google app engine and I want to use it as a server to enable people download a file. I have gone through the tutorials in python. I didnt find anything to actually guide me how to upload files to the server for this purpose.
| [
"The Blobstore tutorial gives an example for just this use case. That link provides this code: an application that lets users upload files and then immediately download them:\n#!/usr/bin/env python\n#\n\nimport os\nimport urllib\n\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import webapp\... | [
4,
0
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0008498771_blobstore_google_app_engine_python.txt |
Q:
Do python decorators strictly implement the decorator pattern ?
I've attended a session about decorator pattern where most of the examples provided were in java.For instance in the example below the Pizza object is being decorated with Two toppings .
Pizza vegPizza = new ToppingsType1(new ToppingType2(new Pizza())... | Do python decorators strictly implement the decorator pattern ? | I've attended a session about decorator pattern where most of the examples provided were in java.For instance in the example below the Pizza object is being decorated with Two toppings .
Pizza vegPizza = new ToppingsType1(new ToppingType2(new Pizza()))
In python i've seen decorators being used in the scenarios like th... | [
"You should read this which explains what are python's decorators. \n\nThe \"decorators\" we talk about with concern to Python are not exactly the same thing as the DecoratorPattern [...]. A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (a... | [
2,
1,
1
] | [] | [] | [
"decorator",
"design_patterns",
"python"
] | stackoverflow_0008504969_decorator_design_patterns_python.txt |
Q:
Vectorizing for loop in Numpy
is there a way to vectorize this?
waveheight=zeros(10000)
for t in range(10000):
for j in range(N_frequencysteps):
waveheight[t] = waveheight[t] + (Abs_S_newwave[j] * cos (K[j] * x - (omega[j] * ((t*0.01) - TimeShift)) + TSi_omega[j] + arg_S_newwave[j]))
A:
waveheight = ... | Vectorizing for loop in Numpy | is there a way to vectorize this?
waveheight=zeros(10000)
for t in range(10000):
for j in range(N_frequencysteps):
waveheight[t] = waveheight[t] + (Abs_S_newwave[j] * cos (K[j] * x - (omega[j] * ((t*0.01) - TimeShift)) + TSi_omega[j] + arg_S_newwave[j]))
| [
"waveheight = (Abs_S_newwave[:,None] * cos(K[:,None] * x - (omega[:,None] * ((arange(10000)[None,:]*0.01) - TimeShift)) + TSi_omega[:,None] + arg_S_newwave[:,None])).sum(axis=0)\n\nThis works if all arrays of length N_frequencysteps are 1-D numpy arrays.\n",
"At least one step of vectorization would be not to ite... | [
5,
0
] | [] | [] | [
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0008505045_multidimensional_array_numpy_python.txt |
Q:
Is it possible to prefill a input() in Python 3's Command Line Interface?
I'm using Python 3.2 on Ubuntu 11.10 (Linux). A piece of my new code looks like this:
text = input("TEXT=")
Is it possible to get some predefined string after the prompt, so I can adjust it if needed? It should be like this:
python3 file
TEX... | Is it possible to prefill a input() in Python 3's Command Line Interface? | I'm using Python 3.2 on Ubuntu 11.10 (Linux). A piece of my new code looks like this:
text = input("TEXT=")
Is it possible to get some predefined string after the prompt, so I can adjust it if needed? It should be like this:
python3 file
TEXT=thepredefinedtextishere
Now I press Backspace 3 times
TEXT=thepredefinedtext... | [
"If your Python interpreter is linked against GNU readline, input() will use it. In this case, the following should work:\nimport readline\n\ndef input_with_prefill(prompt, text):\n def hook():\n readline.insert_text(text)\n readline.redisplay()\n readline.set_pre_input_hook(hook)\n result =... | [
33
] | [] | [] | [
"command_line_interface",
"input",
"python",
"python_3.x"
] | stackoverflow_0008505163_command_line_interface_input_python_python_3.x.txt |
Q:
Twisted Deferred.addCallBack() vs. yield and @inlineDeferred
Is there any reason to use one over the other?
Do they have the same performance?
A:
I tend to use inlineCallbacks for multistep initialization (such as auth) to some service where each subsequent step depends on a result from the previous step, for ex... | Twisted Deferred.addCallBack() vs. yield and @inlineDeferred | Is there any reason to use one over the other?
Do they have the same performance?
| [
"I tend to use inlineCallbacks for multistep initialization (such as auth) to some service where each subsequent step depends on a result from the previous step, for example. Other than these situations, I tend to find that inlineCallbacks could lead to lazy programming that could slow down your app.\nHere's an exa... | [
18,
2,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003894278_python_twisted.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.