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:
convert PyInt to C Int
i need to convert PyInt to C int. In my code
count=PyInt_FromSsize_t(PyList_Size(pValue))
pValue is a PyObject, PyList. the problem i was having is the PyList_Size is not returning me the correct list size (count is supposed to be 5, but it gave me 6 million), or there is a problem with dat... | convert PyInt to C Int | i need to convert PyInt to C int. In my code
count=PyInt_FromSsize_t(PyList_Size(pValue))
pValue is a PyObject, PyList. the problem i was having is the PyList_Size is not returning me the correct list size (count is supposed to be 5, but it gave me 6 million), or there is a problem with data types since im in C code i... | [
"The PyInt_FromSsize_t() returns a full-fledged Python int object sitting in memory and returns its memory address — that is where the 6-million number is coming from. You just want to get the scalar returned by PyList_Size() and cast it to a C integer, I think:\ncount = (int) PyList_Size(pValue)\n\nIf the list cou... | [
3
] | [] | [] | [
"int",
"python",
"python_c_api",
"python_c_extension"
] | stackoverflow_0008262185_int_python_python_c_api_python_c_extension.txt |
Q:
python and hours formula calculation
I have some working code that I altered but I can't seem to get the math right for the hours variable. I think I had to much food for the holidays because I'm coming up with a blank.
## {{{ http://code.activestate.com/recipes/124894/ (r2)
from Tkinter import *
import time
impor... | python and hours formula calculation | I have some working code that I altered but I can't seem to get the math right for the hours variable. I think I had to much food for the holidays because I'm coming up with a blank.
## {{{ http://code.activestate.com/recipes/124894/ (r2)
from Tkinter import *
import time
import pygtk
import gtk
import time
class Stop... | [
"It is much easier to work from the other end. You don't need big numbers like 86400 which make code reviewers reach for their calculator app.\nc = int(elap * 100) # centiseconds\ns, c = divmod(c, 100)\nm, s = divmod(s, 60)\nh, m = divmod(m, 60)\nd, h = divmod(h, 24)\nprint(d, h, m, s, c)\n\nor, avoiding the functi... | [
5,
2,
0,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0008261269_math_python.txt |
Q:
Exposing a file-like object from Cython
I need to expose a file-like object from a C library that i'm wrapping with a Cython module. I want to reuse python's generic io code for stuff like buffering, readline(), etc.
The new IO module seems to be just what i need, but actually using it from Cython seems to be non-... | Exposing a file-like object from Cython | I need to expose a file-like object from a C library that i'm wrapping with a Cython module. I want to reuse python's generic io code for stuff like buffering, readline(), etc.
The new IO module seems to be just what i need, but actually using it from Cython seems to be non-trivial, I've tried several aproaches:
My co... | [
"Would it be too inefficient to call os.fdopen() on the file descriptor number returned by the underlying library, and then to dispatch normal Python method calls to the resulting file object in order to do your input and output? With most I/O, I would be surprised if you could see a difference with whether you cal... | [
1
] | [] | [] | [
"cython",
"file_io",
"python"
] | stackoverflow_0004278444_cython_file_io_python.txt |
Q:
Doing a Simple Yahoo Search in Python
I need to write a Python script which, at one point, does a Yahoo web search to find and download a bunch of C source files. I'm very new to this and I can't figure out how to just get started with doing a simple web search... I've seen a lot of stuff about BOSS but, from my u... | Doing a Simple Yahoo Search in Python | I need to write a Python script which, at one point, does a Yahoo web search to find and download a bunch of C source files. I'm very new to this and I can't figure out how to just get started with doing a simple web search... I've seen a lot of stuff about BOSS but, from my understanding, this is something you need to... | [
"You might want to try it using mechanize, which simulates a browser. If you need to clean out some of the crud in the resulting files, use Beautiful Soup.\n",
"\nI can't figure out how to just do a normal web search (since the search.web table is apparently gone). A basic working example would be much appreciate... | [
2,
1
] | [] | [] | [
"python",
"yahoo",
"yql"
] | stackoverflow_0008248007_python_yahoo_yql.txt |
Q:
Google App Engine Back End URL Access from AJAX Call
Hi. I was trying to access backend URL from an AJAX call and here's my code, but there's something wrong in the code it preventing me from access the backend URL can anyone help?
$.ajax({
type : "GET",
url : "http://backend.appid.appspot.com/updateuser/",
... | Google App Engine Back End URL Access from AJAX Call | Hi. I was trying to access backend URL from an AJAX call and here's my code, but there's something wrong in the code it preventing me from access the backend URL can anyone help?
$.ajax({
type : "GET",
url : "http://backend.appid.appspot.com/updateuser/",
cache: false,
data : $("#userform").serialize(),
succe... | [
"Change the url to '/updateuser/' and try it out again. Note that you can make Ajax queries only to the same host where document was loaded (same origin policy).\nAdd also error handler in your call to get some debug info.\n"
] | [
1
] | [] | [] | [
"ajax",
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0008261672_ajax_google_app_engine_jquery_python.txt |
Q:
app engine: get rid of extra lines (Status: 200 content-type: application/json; etc) when running locally
I have a couple of app engine urls that return pure JSON and this works fine in production. However, when I run the app locally (dev_appserver.py), it spits out a few additional lines in the response before th... | app engine: get rid of extra lines (Status: 200 content-type: application/json; etc) when running locally | I have a couple of app engine urls that return pure JSON and this works fine in production. However, when I run the app locally (dev_appserver.py), it spits out a few additional lines in the response before the actual json string, like so:
Status: 200
content-type: application/json; charset=utf-8
Cache-Control: no-cach... | [
"ok, figure it out:\nsomewhere in the handler, I had a print statement, which seems to cause these extra lines to show up. Leaving this is here reference.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008258476_google_app_engine_python.txt |
Q:
Run ssh-add with Fabric in a machine
I'm running some deployment tasks with Fabric that needs to checkout/update a Mercurial repository to the machine and then execute the appropriate copying/configuration.
Every time that I instatiate a new machine (we're currently using EC2 for our infrastructure) or when I run ... | Run ssh-add with Fabric in a machine | I'm running some deployment tasks with Fabric that needs to checkout/update a Mercurial repository to the machine and then execute the appropriate copying/configuration.
Every time that I instatiate a new machine (we're currently using EC2 for our infrastructure) or when I run hg pull in the machine it'll ask for my ss... | [
"A comment on fabric's issue tracker solved this for me. It's a modified version of the lincolnloop solution. Using this \"run\" instead of fabric's will pipe your commands through ssh locally, allowing your local ssh-agent to provide the keys.\nfrom fabric.api import env, roles, local, output\nfrom fabric.operatio... | [
3
] | [] | [] | [
"fabric",
"python",
"ssh"
] | stackoverflow_0007772373_fabric_python_ssh.txt |
Q:
Vector in python
I'm working on this project which deals with vectors in python. But I'm new to python and don't really know how to crack it. Here's the instruction:
"Add a constructor to the Vector class. The constructor should take a single argument. If this argument is either an int or a long or an instance of ... | Vector in python | I'm working on this project which deals with vectors in python. But I'm new to python and don't really know how to crack it. Here's the instruction:
"Add a constructor to the Vector class. The constructor should take a single argument. If this argument is either an int or a long or an instance of a class derived from o... | [
"Your instructor seems not to \"speak Python as a native language\". ;) The entire concept for the class is pretty silly; real Python programmers just use the built-in sequence types directly. But then, this sort of thing is normal for academic exercises, sadly...\n\nAdd a constructor to the Vector class.\n\nIn Pyt... | [
2,
0,
0,
0,
0
] | [] | [] | [
"class",
"initialization",
"python",
"vector"
] | stackoverflow_0008262017_class_initialization_python_vector.txt |
Q:
Errors When Installing MySQL-python module for Python 2.7
I'm currently trying to build and install the mySQLdb module for Python, but the command
python setup.py build
gives me the following error
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-intel-2.7/MySQLdb
error: could n... | Errors When Installing MySQL-python module for Python 2.7 | I'm currently trying to build and install the mySQLdb module for Python, but the command
python setup.py build
gives me the following error
running build
running build_py
copying MySQLdb/release.py -> build/lib.macosx-10.3-intel-2.7/MySQLdb
error: could not delete 'build/lib.macosx-10.3-intel-2.7/MySQLdb/release.py':... | [
"Make sure that gcc-4.0 is in your PATH. Also, you can create an alias from gcc to gcc-4.0.\nTake care about 32b and 64b versions. Mac OS X is a 64b operating system and you should right flags to make sure you're compiling for 64b architecture.\n",
"If you're on Windows, you can use a pre-compiled installer. Chec... | [
1,
0
] | [] | [] | [
"django",
"mysql",
"mysql_python",
"python"
] | stackoverflow_0008236963_django_mysql_mysql_python_python.txt |
Q:
Python : 2 sockets, sending from A to B and from B to A
I've been working on this for 2 days and still I do not manage to get it to work properly.
I wanted to write an application that uses 2 sockets with a medium in the middle
This medium is this script that should read from socketA and write to SocketB and read... | Python : 2 sockets, sending from A to B and from B to A | I've been working on this for 2 days and still I do not manage to get it to work properly.
I wanted to write an application that uses 2 sockets with a medium in the middle
This medium is this script that should read from socketA and write to SocketB and read from SocketB and write to SocketA.
However it seems I can n... | [
"Used your exact code and it worked for me. I think what you might be doing wrong is telnet'ing to the wrong IP. Dont use 'localhost' or 127.0.0.1, you need to use the actual (internal) IP of your box.\nIf on linux, you can see if with ifconfig -a, or ipconfig /all on windows.\nRunning your code exactly, no modif... | [
2
] | [] | [] | [
"multithreading",
"python",
"sockets"
] | stackoverflow_0008263170_multithreading_python_sockets.txt |
Q:
Can you invoke a python routine inside an Android App?
There are some cool python scripts out there and I was wondering what is involved in running one within an Android device? Is this possible? I don't want to call out to a server. Thanks
A:
It is possible, although with limitations.
The Scripting Layer for ... | Can you invoke a python routine inside an Android App? | There are some cool python scripts out there and I was wondering what is involved in running one within an Android device? Is this possible? I don't want to call out to a server. Thanks
| [
"It is possible, although with limitations. \nThe Scripting Layer for Android provides and interface for script languages to expose a great deal of Android's internals.\nYou will need a specific built of python though, that you can get here.\nSome libraries are also being simplified and shrunk to be available on An... | [
3,
2
] | [] | [] | [
"android",
"python"
] | stackoverflow_0008263275_android_python.txt |
Q:
Virtualenv __future__ module works on command line, but not while running dev_appserver.py
I'm running into a strange error when running App Engine from within my virtualenv. Here is the error:
File "/home/matthew/dev/sdks/google_appengine_1.5.2/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRe... | Virtualenv __future__ module works on command line, but not while running dev_appserver.py | I'm running into a strange error when running App Engine from within my virtualenv. Here is the error:
File "/home/matthew/dev/sdks/google_appengine_1.5.2/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description)
File "/home/matthew/dev/projects/webapp2/project/src/webapp2.py", line 11,... | [
"This is bug 4339. Make sure you use the SDK version 1.6.0, then do:\n$ cd /usr/local/google_appengine/google/appengine/tools\n$ wget \"http://googleappengine.googlecode.com/issues/attachment?aid=43390029000&name=dev_appserver_import_hook.patch&token=974d9f138a5604dc7eb0526156b26cc7\" -O dev_appserver.patch\n$ patc... | [
1
] | [] | [] | [
"google_app_engine",
"importerror",
"python",
"virtualenv"
] | stackoverflow_0006853710_google_app_engine_importerror_python_virtualenv.txt |
Q:
python csv.read fails on second iteration
my code looks something like this:
for filename in files:
with open(filename, 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter=';')
values=list(csvreader)
dosomething()
i have about 10 files i want to process and it works without a problem for the f... | python csv.read fails on second iteration | my code looks something like this:
for filename in files:
with open(filename, 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter=';')
values=list(csvreader)
dosomething()
i have about 10 files i want to process and it works without a problem for the first file. but when python tries to start proce... | [
"Somewhere you have used a (global, if the problem is showing up here) variable named list to hold an instance of a list. That is a bad idea. The name list is looked up every time it's used, and that variable is found in preference to the actual list type, which is what you want (i.e. in order to construct a list f... | [
5,
1,
1
] | [] | [] | [
"csv",
"parsing",
"python"
] | stackoverflow_0008263489_csv_parsing_python.txt |
Q:
django smart decimal field
I am creating an app that basically stores shoe sizes, along with other information. I have been using the Django Decimal field to store the sizes, however the decimal field stores sizes like 10 as 10.0, so my question is, is there a way to make or if already exists a field that when pro... | django smart decimal field | I am creating an app that basically stores shoe sizes, along with other information. I have been using the Django Decimal field to store the sizes, however the decimal field stores sizes like 10 as 10.0, so my question is, is there a way to make or if already exists a field that when provided an int ( 10 ) it stores th... | [
"TBH for a shoe size field I'd probably use a CharField with choices attribute - there are a relatively small number of valid shoe sizes and that way you can format them how you want to.\nIf it's part of a Product model that may contain things other than shoes, a CharField for 'size' is useful because you can also ... | [
3,
2,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007890810_django_django_models_python.txt |
Q:
Mathematica to Python
How can this Mathematica code be ported to Python? I do not know the Mathematica syntax and am having a hard time understanding how this is described in a more traditional language.
Source (pg 5): http://subjoin.net/misc/m496pres1.nb.pdf
A:
This cannot be ported to Python directly as the d... | Mathematica to Python | How can this Mathematica code be ported to Python? I do not know the Mathematica syntax and am having a hard time understanding how this is described in a more traditional language.
Source (pg 5): http://subjoin.net/misc/m496pres1.nb.pdf
| [
"This cannot be ported to Python directly as the definition a[j] uses the Symbolic Arithmetic feature of Mathematica.\na[j] is basically the coefficient of xj in the series expansion of that rational function inside Apart.\nAssume you have a[j], then f[n] is easy. A Block in Mathematica basically introduces a scope... | [
7,
5,
3
] | [] | [] | [
"python",
"wolfram_mathematica"
] | stackoverflow_0003957087_python_wolfram_mathematica.txt |
Q:
Invalid ELF header when loading library from Python using ctypes.cdll.LoadLibrary
I am just getting started with gcc on Linux. I am following the tutorial here, except that I am using the g++ compiler.
hello_fn.cpp
#include <stdio.h>
#include "hello.h"
void
hello (const char * name)
{
printf ("Hello, %s!\n", ... | Invalid ELF header when loading library from Python using ctypes.cdll.LoadLibrary | I am just getting started with gcc on Linux. I am following the tutorial here, except that I am using the g++ compiler.
hello_fn.cpp
#include <stdio.h>
#include "hello.h"
void
hello (const char * name)
{
printf ("Hello, %s!\n", name);
}
bye_fn.cpp
#include <stdio.h>
#include "hello.h"
void
bye (void)
{
printf... | [
"ctypes is for loading shared libraries. ar creates archives of object files, also known as static libraries. You can't load that file with ctypes, it will only be understood by the linker.\nAnother issue is that using C++ shared libraries via ctypes is painful if not downright impossible. Just don't. Use Cython in... | [
6
] | [] | [] | [
"c++",
"ctypes",
"g++",
"python"
] | stackoverflow_0008263914_c++_ctypes_g++_python.txt |
Q:
Read into a bytearray at an offset?
How can I use the readinto() method call to an offset inside a bytearray, in the same way that struct.unpack_from works?
A:
You can use a memoryview to do the job. For example:
dest = bytearray(10) # all zero bytes
v = memoryview(dest)
ioObject.readinto(v[3:])
print(repr(dest)... | Read into a bytearray at an offset? | How can I use the readinto() method call to an offset inside a bytearray, in the same way that struct.unpack_from works?
| [
"You can use a memoryview to do the job. For example:\ndest = bytearray(10) # all zero bytes\nv = memoryview(dest)\nioObject.readinto(v[3:])\nprint(repr(dest))\n\nAssuming that iObject.readinto(...) reads the bytes 1, 2, 3, 4, and 5 then this code prints:\nbytearray(b'\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\x05\\x00\\... | [
18
] | [] | [] | [
"buffer",
"io",
"python",
"python_3.x"
] | stackoverflow_0008263899_buffer_io_python_python_3.x.txt |
Q:
sl4a python notify question
I have two questions regarding the sl4a scripting language. I'd like to develop a python script that will be periodically contacted by a server and post some information to the notification bar.
I've successfully add message to the notification bar, but
The notification icon is always... | sl4a python notify question | I have two questions regarding the sl4a scripting language. I'd like to develop a python script that will be periodically contacted by a server and post some information to the notification bar.
I've successfully add message to the notification bar, but
The notification icon is always sl4a logo. Is there a way to cha... | [
"\nOfficially, there is no API exposed to SL4A for customization of notifications which exist does exist in Android. \nReference:\nhttp://developer.android.com/guide/topics/ui/notifiers/notifications.html#CustomExpandedView\nhttp://code.google.com/p/android-scripting/wiki/ApiReference\nOfficially, there is no API e... | [
3
] | [] | [] | [
"android",
"python",
"scripting",
"sl4a"
] | stackoverflow_0007225432_android_python_scripting_sl4a.txt |
Q:
re.sub emptying list
def process_dialect_translation_rules():
# Read in lines from the text file specified in sys.argv[1], stripping away
# excess whitespace and discarding comments (lines that start with '##').
f_lines = [line.strip() for line in open(sys.argv[1], 'r').readlines()]
f_lines = filt... | re.sub emptying list | def process_dialect_translation_rules():
# Read in lines from the text file specified in sys.argv[1], stripping away
# excess whitespace and discarding comments (lines that start with '##').
f_lines = [line.strip() for line in open(sys.argv[1], 'r').readlines()]
f_lines = filter(lambda line: not re.mat... | [
"In Python, multiple for loops in a list comprehension are handled from left to right, not from right to left, so your last expression should read:\n[re.sub(r'\"', '', elem) for line in f_lines for elem in line]\n\nIt doesn't lead to an error as it is, since list comprehensions leak the loop variable, so line is st... | [
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008263598_python_regex.txt |
Q:
error when using random graph generator in NetworkX
I am trying to create a graph F with a degree sequence of another
graph G.
The code is this
import networkx as nx
import matplotlib.pyplot as plt
# some code
deg_sequence = nx.degree(G).values()
print nx.is_valid_degree_sequence(deg_sequence)
... | error when using random graph generator in NetworkX | I am trying to create a graph F with a degree sequence of another
graph G.
The code is this
import networkx as nx
import matplotlib.pyplot as plt
# some code
deg_sequence = nx.degree(G).values()
print nx.is_valid_degree_sequence(deg_sequence)
F = nx.random_degree_sequence_graph(deg_sequence, seed=N... | [
"I searched the documentation for nx.random_degree_sequence_graph, and it is a new function in version1.6 .\ntry:\neasy_install networkx==1.6\n\n:)\n"
] | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0008264262_networkx_python.txt |
Q:
Python Divide a string
I have a string like this:
<td casd2" aasdeft" class="satyle3">
<b><a asddidasd?ct=Peasds&fasdaao=Monsdar
&pID=19635"...
I need the 19635.
Someone can help me ?
A:
I would use regular expressions to make a more neat solution:
>>> import re
>>> s = '<td casd2" aasdeft" cl... | Python Divide a string | I have a string like this:
<td casd2" aasdeft" class="satyle3">
<b><a asddidasd?ct=Peasds&fasdaao=Monsdar
&pID=19635"...
I need the 19635.
Someone can help me ?
| [
"I would use regular expressions to make a more neat solution:\n>>> import re\n>>> s = '<td casd2\" aasdeft\" class=\"satyle3\"><b><a asddidasd?ct=Peasds&fasdaao=Monsdar&pID=19635\"...'\n>>> match = re.search(\".*pID=(\\d+).*\",s)\n>>> if match:\n... match.group(1)\n... \n'19635'\n\nNice and simple isn't ... | [
3,
3,
1
] | [] | [] | [
"divide",
"python",
"split",
"string"
] | stackoverflow_0008197099_divide_python_split_string.txt |
Q:
partial ancestor fetches before deletion from the AppEngine datastore
I'd like to delete a bunch of objects from the AppEngine datastore within a transaction:
def F():
items_to_delete = []
for item in db.Query().ancestor(...):
if item.aaa ... item.bbb:
items_to_delete.append(item)
db.delete(items_t... | partial ancestor fetches before deletion from the AppEngine datastore | I'd like to delete a bunch of objects from the AppEngine datastore within a transaction:
def F():
items_to_delete = []
for item in db.Query().ancestor(...):
if item.aaa ... item.bbb:
items_to_delete.append(item)
db.delete(items_to_delete)
db.run_in_transaction(F)
Is it possible to fetch only a few fiel... | [
"It's not possible to fetch only a few fields; i.e. you'll always be fetching the entire entity with all its fields (or just the entity keys). From the App Engine GQL reference docs:\nThe GQL syntax can be summarized as follows: \n SELECT [* | __key__]\n [FROM <kind>]]\n [WHERE <condition> [AND <... | [
3,
0
] | [] | [] | [
"datastore",
"google_app_engine",
"model",
"python"
] | stackoverflow_0008257470_datastore_google_app_engine_model_python.txt |
Q:
pywinauto with Remote Desktop
I have just started to use the pywinauto module to automate GUI tasks. One of them is to launch the remote desktop exe (mstsc.exe)->Login->Invoke another tool there.
However, I manged to connect to the remote server but the control gets lost after that. I did not manage to login. So, ... | pywinauto with Remote Desktop | I have just started to use the pywinauto module to automate GUI tasks. One of them is to launch the remote desktop exe (mstsc.exe)->Login->Invoke another tool there.
However, I manged to connect to the remote server but the control gets lost after that. I did not manage to login. So, the question is how to use the pywi... | [
"After trying out various things I figured that the window which opens after pressing the \"Connect\" button on mstsc can be found by searching for the window with the title 'XYZ - Remote Desktop' where XYZ is the name of the remote server. I have tested this on the WinXP. \n"
] | [
1
] | [] | [] | [
"python",
"pywinauto",
"rdp",
"remote_desktop"
] | stackoverflow_0008207755_python_pywinauto_rdp_remote_desktop.txt |
Q:
How to deal with a Class generated exception from within Main
I'm having some trouble getting my head around how best to solve this situation (mostly due to lack of experience I think).
I have written a couple of definitions in a single class that are called from a Main to perform certain tasks. It is assumed the... | How to deal with a Class generated exception from within Main | I'm having some trouble getting my head around how best to solve this situation (mostly due to lack of experience I think).
I have written a couple of definitions in a single class that are called from a Main to perform certain tasks. It is assumed the Main could be written by anyone for a number of purposes, so killi... | [
"\nOne basic rule of these subclasses is, if subclass1 does its tasks\n successfully, subclass2 can be called. But if subclass1 fails,\n subclass2 must not be called as it will fail also.\n\nWrite a third class, or a module function? Or the two classes shouldn't have been decomposed as independent if they truly ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008264627_python.txt |
Q:
Django to_python function being called on every database query
I am working on a web application that allows users to submit a form. Once the form has been submitted the get_db_prep_value() encrypts all the fields. The bit I'm struggling with is the functionality that decrypts the fields in the django admin app. ... | Django to_python function being called on every database query | I am working on a web application that allows users to submit a form. Once the form has been submitted the get_db_prep_value() encrypts all the fields. The bit I'm struggling with is the functionality that decrypts the fields in the django admin app. The decryption process works fine, the problem is that the decryptio... | [
"\"The to_python() method on a Field is the first step in every validation.\"\nhttps://docs.djangoproject.com/en/1.3/ref/forms/validation/\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0008235249_django_django_admin_python.txt |
Q:
Database not created because of defining "app_label" META in Django
I am designing a simple model in Django(1.3) which has 3 fields and some META options.
class DataSource(models.Model):
title = models.CharField(max_length=255)
priority = models.IntegerField(unique=True)
read_only ... | Database not created because of defining "app_label" META in Django | I am designing a simple model in Django(1.3) which has 3 fields and some META options.
class DataSource(models.Model):
title = models.CharField(max_length=255)
priority = models.IntegerField(unique=True)
read_only = models.BooleanField(default = False)
class Meta:
verbose... | [
"Read the documentation:\n\napp_label\nIf a model exists outside of the standard models.py (for instance, if the app’s models are in submodules of myapp.models), the model must define which app it is part of:\napp_label = 'myapp'\n\n\nThe app_label must be an app name. You don't have an app called \"My Admin\".\n"
... | [
2
] | [] | [] | [
"database",
"django",
"meta",
"python"
] | stackoverflow_0008265008_database_django_meta_python.txt |
Q:
Can we somehow create Server Side Filters using Python?
I get around 100k mails everyday and client side filters are not working due to crash of Outlook and Thunderbird. I wrote following code in Python to delete all messages:
import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("... | Can we somehow create Server Side Filters using Python? | I get around 100k mails everyday and client side filters are not working due to crash of Outlook and Thunderbird. I wrote following code in Python to delete all messages:
import imaplib
box = imaplib.IMAP4_SSL('imap.mail.microsoftonline.com', 993)
box.login("userid@nextag.microsoftonline.com","password")
box.select('In... | [
"It might have something to do with you closing the connection before logging out.\n"
] | [
0
] | [] | [] | [
"imap",
"python"
] | stackoverflow_0008265511_imap_python.txt |
Q:
Using the lowercase function with CSV rows
I'm trying to print all data from a csv in lowercase, but I'm not having any luck.
Here's what I have so far:
import csv
books = csv.reader(open("books.csv","rb"))
for row in books:
print row
This prints all the content of the csv, but when I add the .lower() functi... | Using the lowercase function with CSV rows | I'm trying to print all data from a csv in lowercase, but I'm not having any luck.
Here's what I have so far:
import csv
books = csv.reader(open("books.csv","rb"))
for row in books:
print row
This prints all the content of the csv, but when I add the .lower() function, I get errors.
What am I doing wrong?
| [
"Try\nprint [r.lower() for r in row]\n\n"
] | [
7
] | [] | [] | [
"csv",
"lowercase",
"python"
] | stackoverflow_0008265648_csv_lowercase_python.txt |
Q:
Why is double considered a global name?
I've created the code below, when I import the module and attempt to run it I received the following error:
>>> import aiyoo
>>> aiyoo.bixidist(1,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "aiyoo.py", line 50, in bixidist
currentDi... | Why is double considered a global name? | I've created the code below, when I import the module and attempt to run it I received the following error:
>>> import aiyoo
>>> aiyoo.bixidist(1,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "aiyoo.py", line 50, in bixidist
currentDist = dist(X,Y,c)
File "aiyoo.py", line 39, ... | [
"As answered by others, double is not a built-in type in python. You have to use, float instead. Floating point is implemented using double in C [ ref ].\nAnd as to the main part of your question i.e. \"why the double considered a global name?\", when you use a variable-name say double, which is not found in local ... | [
3,
2,
0,
0
] | [] | [] | [
"module",
"nameerror",
"python"
] | stackoverflow_0008265410_module_nameerror_python.txt |
Q:
Simple python mvc framework
Is there any lightweight mvc webframework which is not necessary to install to the server?
I need something simple, that i could just copy to the shared hosting. And it must handle urls other that localhost/test.py, something like this localhost/Blog/test
A:
You should probably check ... | Simple python mvc framework | Is there any lightweight mvc webframework which is not necessary to install to the server?
I need something simple, that i could just copy to the shared hosting. And it must handle urls other that localhost/test.py, something like this localhost/Blog/test
| [
"You should probably check out Flask or Bottle, two nice Python microframeworks. With an appropriate \"main\" Python script (to initialize your app and dispatch requests to it) and mod_rewrite rules in place, you can probably get pretty close to your goal of \"just copy[ing] to the shared hosting\" with nice URLs.... | [
4,
3,
2,
1
] | [] | [] | [
"frameworks",
"python"
] | stackoverflow_0002852056_frameworks_python.txt |
Q:
Have program report bazaar revision number when run
I have a python program under bazaar version control. How can I get the program to display the current branch revision number and date/build-date when run? The program is exported, not executed from a working copy tree.
There is a svn version of this question at... | Have program report bazaar revision number when run | I have a python program under bazaar version control. How can I get the program to display the current branch revision number and date/build-date when run? The program is exported, not executed from a working copy tree.
There is a svn version of this question at Getting SVN revision number into a program automatically... | [
"If you don't have the branch (that's what I understand from the question), I don't know if there's any standard solution for that. What I usually do is use a template that is populated with values at build time (in my case debian package generation) so that a file like version.py.tmpl becomes version.py. That modu... | [
3,
1,
1
] | [] | [] | [
"bazaar",
"python"
] | stackoverflow_0008247085_bazaar_python.txt |
Q:
Python regex negating metacharacters
Python metacharacter negation.
After scouring the net and writing a few different syntaxes I'm out of ideas.
Trying to rename some files. They have a year in the title e.g. [2002].
Some don't have the brackets, which I want to rectify.
So I'm trying to find a regex (that I can ... | Python regex negating metacharacters | Python metacharacter negation.
After scouring the net and writing a few different syntaxes I'm out of ideas.
Trying to rename some files. They have a year in the title e.g. [2002].
Some don't have the brackets, which I want to rectify.
So I'm trying to find a regex (that I can compile preferably) that in my mind looks ... | [
"If you want to check for things around a pattern you can use lookahead and lookbehind assertions. These don't form part of the match but say what you expect to find (or not find) around it.\nAs we don't want brackets we'll need use a negative lookbehind and lookahead.\nA negative lookahead looks like this (?!...)... | [
9
] | [] | [] | [
"python",
"regex",
"regex_negation"
] | stackoverflow_0008266052_python_regex_regex_negation.txt |
Q:
Basic Django Feeds
I am a beginner. I want to add a RSS function to my blog. It shows an RSS page but it shows no entries. I don't know why. My urls.py is:
feeds = {'latest': PostAtomFeed, }
...
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
And feeds.py:
from djang... | Basic Django Feeds | I am a beginner. I want to add a RSS function to my blog. It shows an RSS page but it shows no entries. I don't know why. My urls.py is:
feeds = {'latest': PostAtomFeed, }
...
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
And feeds.py:
from django.contrib.syndication.fe... | [
"I have fix it!\nI defined a wrong get_absolte_url() in my models.\nNow, it works well.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008256795_django_python.txt |
Q:
How to open a template in Django platform
I want to open a html file i.e map.html which is saved in same directories where i saved this views.py and urls.py. (django based platform)
I wrote this sample code for views.py (to load map.html) but it is not working:
from django.template import Template, Context,Reques... | How to open a template in Django platform | I want to open a html file i.e map.html which is saved in same directories where i saved this views.py and urls.py. (django based platform)
I wrote this sample code for views.py (to load map.html) but it is not working:
from django.template import Template, Context,RequestContext
from django.http import HttpResponse... | [
"The problem is, I think, that you are using the path './map.html'. This is means that Python will try and find the current directory of the program, not the same directory as the view file is in.\nLets say the Django project is in the directory /home/foo/myproject. If you cd to that directory and run python manage... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008266088_django_python.txt |
Q:
calculation of no. of rows (data from csv) satisfying condition and also slower code
1 2 3 4 5
1 0.000 0.733 0.762 0.745 0.692
2 0.733 0.000 0.842 0.766 0.701
3 0.762 0.842 0.000 0.851 0.803
4 0.745 0.766 0.851 0.000 0.402
5 0.692 0.701 0.80... | calculation of no. of rows (data from csv) satisfying condition and also slower code | 1 2 3 4 5
1 0.000 0.733 0.762 0.745 0.692
2 0.733 0.000 0.842 0.766 0.701
3 0.762 0.842 0.000 0.851 0.803
4 0.745 0.766 0.851 0.000 0.402
5 0.692 0.701 0.803 0.402 0.000
I am wrting a python code as follows:
import csv
import time
import num... | [
"50000 * 50000 numbers won't probably fit into your RAM, as @DavidAlber said.\nBut the following code should be fast enough and it keeps just the current row in the memory.\nimport csv\nimport time\nimport numpy as np\n\ncount = 0\n\nwith open('test.csv','r') as infile:\n reader=csv.reader(infile, delimiter='\\t... | [
6,
4
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008265955_csv_python.txt |
Q:
Convert a space delimited string to list
i have a string like this :
states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
and I want to split it into a list like this
states = {Alaska, Alabama, Arkansas, American, Samoa, ....}
I am new in python.
Help me, please. :-))
edit: I need to mak... | Convert a space delimited string to list | i have a string like this :
states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
and I want to split it into a list like this
states = {Alaska, Alabama, Arkansas, American, Samoa, ....}
I am new in python.
Help me, please. :-))
edit: I need to make a random choice from states and make it like... | [
"states.split() will return\n['Alaska',\n 'Alabama',\n 'Arkansas',\n 'American',\n 'Samoa',\n 'Arizona',\n 'California',\n 'Colorado']\n\nIf you need one random from them, then you have to use the random module:\nimport random\n\nstates = \"... ...\"\n\nrandom_state = random.choice(states.split())\n\n",
"try \nst... | [
99,
62,
31,
10,
8
] | [] | [] | [
"python",
"string"
] | stackoverflow_0008266529_python_string.txt |
Q:
Why is python's dict implemented as hash table whereas std::map is tree-based?
Why one languages uses tree and another uses hash table for seemingly similar data structure?
c++'s map vs python's dict
A related question is about performance of hash table.
Please comment on my understanding of hash table below.
A ... | Why is python's dict implemented as hash table whereas std::map is tree-based? | Why one languages uses tree and another uses hash table for seemingly similar data structure?
c++'s map vs python's dict
A related question is about performance of hash table.
Please comment on my understanding of hash table below.
A tree is guaranteed to have O(log n).
Whereas hash table has no guarantee unless inpu... | [
"The new C++ standard has the std::unordered_map type which is a hash table. IIRC they wanted it to get into the previous standard as well, but there was not enough time during the discussions so it was left out. However, most popular compilers provided it in one way or another for years.\nIn other words, don't wor... | [
22,
13,
5,
4
] | [] | [] | [
"c++",
"hashtable",
"map",
"python"
] | stackoverflow_0008265608_c++_hashtable_map_python.txt |
Q:
Python Demo Web Projects on a Tornado Server?
Are there any Python demo projects available I can learn from. I am basically looking into learning the basics like linking and creating a navigation bar.
I am currently trying to get the blog demo in the demo folder of Tornado to run, I am experiencing problems with t... | Python Demo Web Projects on a Tornado Server? | Are there any Python demo projects available I can learn from. I am basically looking into learning the basics like linking and creating a navigation bar.
I am currently trying to get the blog demo in the demo folder of Tornado to run, I am experiencing problems with the SQL file and do not know yet how to open it.
Be... | [
"Besides Tornado's standard examples, I recommend to digg into tornadogists and other gist snippets.\n"
] | [
0
] | [] | [] | [
"python",
"python_2.7",
"tornado",
"web_applications"
] | stackoverflow_0008266893_python_python_2.7_tornado_web_applications.txt |
Q:
Python/C++/Java: Is there a library that will recognize characters and tell me where they are in an image?
I've looked into PyTesser/Tesseract and as far I as I can tell, it only gives me a string once I input an image.
However, I'd like to receive, instead, the coordinates/bounding rectangle of each character it ... | Python/C++/Java: Is there a library that will recognize characters and tell me where they are in an image? | I've looked into PyTesser/Tesseract and as far I as I can tell, it only gives me a string once I input an image.
However, I'd like to receive, instead, the coordinates/bounding rectangle of each character it recognized. The string itself might be useful for me later on, but right now that's now what I need.
Assuming Py... | [
"According to this mailing list thread, you can do this with Tesseract. However, I don't know of Python wrapper that will grant you access to that data.\n",
"Have a look at a similar question recently posted to tesseract google group: http://groups.google.com/group/tesseract-ocr/browse_thread/thread/70ad57cb37eda... | [
3,
1,
0
] | [] | [] | [
"c++",
"image_processing",
"java",
"ocr",
"python"
] | stackoverflow_0008263954_c++_image_processing_java_ocr_python.txt |
Q:
Removing duplicate records in a file
Possible Duplicate:
How might I remove duplicate lines from a file?
I have a file with duplicated records that I want to remove. This is what I have tried
import sys
for line in sys.stdin:
line = line.rstrip()
line = line.split()
idlist = []
if idli... | Removing duplicate records in a file |
Possible Duplicate:
How might I remove duplicate lines from a file?
I have a file with duplicated records that I want to remove. This is what I have tried
import sys
for line in sys.stdin:
line = line.rstrip()
line = line.split()
idlist = []
if idlist == []:
idlist = line[1]
... | [
"elem1_seen = set() # first initialize an empty set of seen elem[1]\nlines_out = [] # list of \"unique\" output lines\nfor line in sys.stdin: # iterate over input\n elems = line.rstrip().split() # split line into two elements\n if elems[1] not in elem1_seen: # ... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008266901_python.txt |
Q:
Python Memory Error (Unix vs Windows)
I am developing an application which loads big JPEG2000 images and converts them to TIF. Later on, it extracts the pixel data and there is some processing. It perfectly works except in one case:
When I load the biggest image and extract the data (10956x10956 array) the program... | Python Memory Error (Unix vs Windows) | I am developing an application which loads big JPEG2000 images and converts them to TIF. Later on, it extracts the pixel data and there is some processing. It perfectly works except in one case:
When I load the biggest image and extract the data (10956x10956 array) the program crashes but it only crashes on Windows -- ... | [
"You should examine the memory use of the application under windows. Considering that the size of the raw image is going to be ~360MB (assuming a 24bit image) if you are allocating memory for each pixel, this is going to multiply, and could easily exceed the memory requirements of a 32bit address space (You are lim... | [
4
] | [] | [] | [
"linux",
"memory",
"python"
] | stackoverflow_0008267142_linux_memory_python.txt |
Q:
wxTreeCtrl which contains wxCheckBox element. Is it possible?
I've got to do wxTreeCtrl which contains wxCheckBox elements. Similar like that you can see in different installers. You can select several elements, all elements and etc.
Is it possible?
When I can see some examples?
Thanks
A:
The CustomTreeCtrl can ... | wxTreeCtrl which contains wxCheckBox element. Is it possible? | I've got to do wxTreeCtrl which contains wxCheckBox elements. Similar like that you can see in different installers. You can select several elements, all elements and etc.
Is it possible?
When I can see some examples?
Thanks
| [
"The CustomTreeCtrl can do it. An example is in the wxPython demo.\n"
] | [
3
] | [] | [] | [
"python",
"user_interface",
"wxpython",
"wxwidgets"
] | stackoverflow_0008267212_python_user_interface_wxpython_wxwidgets.txt |
Q:
Error: No such file or directory
I am trying to extract data from a XML file with python. I tried the following code.
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("data_v2.xml")
Error message:
IOError: [Errno 2] No such file or directory: 'data_v2.xml'.
A:
This is not XML erro... | Error: No such file or directory | I am trying to extract data from a XML file with python. I tried the following code.
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("data_v2.xml")
Error message:
IOError: [Errno 2] No such file or directory: 'data_v2.xml'.
| [
"This is not XML error. This means that data_v2.xml does not exist -- system (operation system) cannot find it. Maybe this name is wrong, maybe you need to provide full path.\nimport traceback\n# ...\ntry:\n input_fname = \"data_v2.xml\"\n tree.parse(input_fname)\n # ...\nexcept IOError:\n ex_info = tra... | [
9
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0008268150_file_io_python.txt |
Q:
After writing to a file, why does os.path.getsize still return the previous size?
I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.
What would be a good way... | After writing to a file, why does os.path.getsize still return the previous size? | I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected.
What would be a good way to get the filesize of a file that is changing in size.
Ive done something like this..... | [
"File size is different from file position. For example,\nos.path.getsize('sample.txt') \n\nIt exactly returns file size in bytes. \nBut \nf = open('sample.txt')\nprint f.readline()\nf.tell() \n\nHere f.tell() returns the current position of the file handler - i.e. where the next write will put its data. Since it ... | [
11,
10,
5,
4,
1
] | [] | [] | [
"filesize",
"python"
] | stackoverflow_0001013778_filesize_python.txt |
Q:
python IP validation REGex validation for full and partial IPs
Im trying to validate the input to see if it a valid IP address(could be a partial one).
Acceptable input : 172, 172.112, 172.112.113, 172.112.113.114
Unacceptable input: 1724,172.11113 etc etc
Heres a function that I created to check it (however it v... | python IP validation REGex validation for full and partial IPs | Im trying to validate the input to see if it a valid IP address(could be a partial one).
Acceptable input : 172, 172.112, 172.112.113, 172.112.113.114
Unacceptable input: 1724,172.11113 etc etc
Heres a function that I created to check it (however it validates unacceptable input like 1724 which I cant seem to fix..plea... | [
"Maybe you could avoid to use regex and let python socket.inet_aton do the job : \nimport socket\n\ntry:\n socket.inet_aton(addr)\n # correct IP\nexcept socket.error:\n # bad IP\n\nFor inet_aton, a valid IP address is something of the form : \n a.b.c.d\n a.b.c\n a.b\n a\n\n\nIn all ... | [
7,
3
] | [] | [] | [
"ip",
"python",
"regex"
] | stackoverflow_0008269376_ip_python_regex.txt |
Q:
Cron automated tests with python
How can I run my "Hello word" script in python every 10 seconds?
I know thats stupid question, because there are a lot of answers returned by google.
Thank you for your help.
A:
To schedule every 10 seconds, a simple system cron job won't be enough because the precision is on the... | Cron automated tests with python | How can I run my "Hello word" script in python every 10 seconds?
I know thats stupid question, because there are a lot of answers returned by google.
Thank you for your help.
| [
"To schedule every 10 seconds, a simple system cron job won't be enough because the precision is on the minute. \nYet, you can use the Advanced Python Scheduler cron-like scheduler to do it.\nfrom apscheduler.scheduler import Scheduler\n\n# Start the scheduler\nsched = Scheduler()\nsched.start()\n\ndef job_function... | [
2,
1
] | [] | [] | [
"automation",
"cron",
"python"
] | stackoverflow_0008269434_automation_cron_python.txt |
Q:
Edit pdf file with PDFMiner
I was wondering if it's possible to édit an existing pdf file with Pdfminer. It seens to be a powerful tool, but the documentation is poor/inexisting.
I found some exemples, but they don't match with my goal. I want to make a search engine which changes the color of my keywords in the p... | Edit pdf file with PDFMiner | I was wondering if it's possible to édit an existing pdf file with Pdfminer. It seens to be a powerful tool, but the documentation is poor/inexisting.
I found some exemples, but they don't match with my goal. I want to make a search engine which changes the color of my keywords in the pdf file.
| [
"PDFMiner is not for altering existing PDF files, but for extracting text and metadata from them. The closest solution to what you're looking for using PDFMiner would probably be to use the included pdf2txt.py tool to extract the text and then mark that up to highlight your keywords.\nThere's also the simple optio... | [
0,
0
] | [] | [] | [
"pdf",
"python"
] | stackoverflow_0008248622_pdf_python.txt |
Q:
How to get priorly-unknown array as the output of a function in Fortran
In Python:
def select(x):
y = []
for e in x:
if e!=0:
y.append(e)
return y
that works as:
x = [1,0,2,0,0,3]
select(x)
[1,2,3]
to be translated into Fortran:
function select(x,n) result(y)
implicit none
... | How to get priorly-unknown array as the output of a function in Fortran | In Python:
def select(x):
y = []
for e in x:
if e!=0:
y.append(e)
return y
that works as:
x = [1,0,2,0,0,3]
select(x)
[1,2,3]
to be translated into Fortran:
function select(x,n) result(y)
implicit none
integer:: x(n),n,i,j,y(?)
j = 0
do i=1,n
if (x(i)/=0) the... | [
"I hope a real Fortran programmer comes along, but in the absence of better advice, I would only specify the shape and not the size of x(:), use a temporary array temp(size(x)), and make the output y allocatable. Then after the first pass, allocate(y(j)) and copy the values from the temporary array. But I can't str... | [
13,
13,
5
] | [] | [] | [
"arrays",
"dynamic_arrays",
"fortran",
"python"
] | stackoverflow_0008264336_arrays_dynamic_arrays_fortran_python.txt |
Q:
WebDriverException:can't load profile error in selenium python script
I am using selenium webdriver in python to drive Firefox automaticly, the python script is exported from the selenium IDE add-on in Firefox. But when I run the script it raise error:
======================================================... | WebDriverException:can't load profile error in selenium python script | I am using selenium webdriver in python to drive Firefox automaticly, the python script is exported from the selenium IDE add-on in Firefox. But when I run the script it raise error:
======================================================================
ERROR: test_selenium (__main__.SeleniumTest)
-----... | [
"I had this issue after upgrading to Firefox 8, when running selenium v 2.9.0.\nIt was fixed by upgrading to the latest version of selenium (2.13).\n sudo pip install selenium --upgrade\n\n(if you're using the Python flavour)\n"
] | [
11
] | [] | [] | [
"python",
"selenium",
"unit_testing",
"web_testing",
"webdriver"
] | stackoverflow_0007328658_python_selenium_unit_testing_web_testing_webdriver.txt |
Q:
How to put multiple input boxes in a modal? wxpython
Hi i am trying to put multiple text boxes into a modal, here is the code for one text box.
dlg = wx.TextEntryDialog(
self, 'What is your favorite programming language?',
'Eh??', 'Python')
Is there a way to put multiple text boxes in ... | How to put multiple input boxes in a modal? wxpython | Hi i am trying to put multiple text boxes into a modal, here is the code for one text box.
dlg = wx.TextEntryDialog(
self, 'What is your favorite programming language?',
'Eh??', 'Python')
Is there a way to put multiple text boxes in a modal?
Something like this would be nice.
Thanks
| [
"You can't do that using the TextEntryDialog - you would have to create your own subclass of wx.Dialog and manually create your desired GUI elements in there.\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008258225_python_wxpython.txt |
Q:
decode javascript sequence into python
I'm a beginner to Python trying to decode this javascript sequence. I'm not only a beginner in Python, I understand javascript even less :) I know i could put it into an online decoder such as this: http://coderstoolbox.net/string/ but I want to deal with it myself - more for... | decode javascript sequence into python | I'm a beginner to Python trying to decode this javascript sequence. I'm not only a beginner in Python, I understand javascript even less :) I know i could put it into an online decoder such as this: http://coderstoolbox.net/string/ but I want to deal with it myself - more for practice than anything else... Im using Bea... | [
"I don't know Python, but I can explain what is happening here so that you can rewrite in Python.\n1) function encode is declared and not assigned, so in JavaScript it will get hoisted to the top of its parent function, if there is one.\n2) Inside function encode there are 4 variables that will get hoisted to the t... | [
0,
0
] | [] | [] | [
"decode",
"javascript",
"python"
] | stackoverflow_0008269578_decode_javascript_python.txt |
Q:
Interpolate a discontinuous function with Scipy
I am having problems interpolating some data points using Scipy. I guess that it might depend on the fact that the function I'm trying to interpolate is discontinuous at x roughly 4.
Here is the code I'm using to interpolate:
from scipy import *
y_interpolated = ... | Interpolate a discontinuous function with Scipy | I am having problems interpolating some data points using Scipy. I guess that it might depend on the fact that the function I'm trying to interpolate is discontinuous at x roughly 4.
Here is the code I'm using to interpolate:
from scipy import *
y_interpolated = interp1d(x,y,buonds_error=False,fill_value=0.,kind='c... | [
"What version of scipy are you using?\nThe script you posted has some syntax errors (I assume due to wrong copy and paste).\nThis script works, with scipy.__version__ == 0.9.0. .\nimport sys\nfrom scipy import *\nfrom scipy.interpolate import *\nfrom pylab import plot\n\nx = []\ny = []\nfor line in sys.stdin:\n a... | [
5
] | [] | [] | [
"interpolation",
"python"
] | stackoverflow_0008268551_interpolation_python.txt |
Q:
How to Inherit objects in django?
is there a link or tutorial on how to inherit an objects in django? let us say that i have a vehicle as a parent and a car and a truck for it's child.
if it is possible, is it done in the models.py?
and how is it work?
thanks...
A:
Exactly the same as python inheritence
class Ve... | How to Inherit objects in django? | is there a link or tutorial on how to inherit an objects in django? let us say that i have a vehicle as a parent and a car and a truck for it's child.
if it is possible, is it done in the models.py?
and how is it work?
thanks...
| [
"Exactly the same as python inheritence\nclass Vehicle(Model):\n name = models.TextField()\n\nclass Car(Vehicle):\n passengers = PositiveIntegerField()\n\nclass Truck(Vehicle):\n tonnage = FloatField()\n\n>>> Car.objects.create(name='Beetle', passengers = 5)\n<Car: name=\"Beetle\",passengers=5>\n>>> Truck.... | [
4,
1,
0
] | [] | [] | [
"django",
"inheritance",
"python"
] | stackoverflow_0008267428_django_inheritance_python.txt |
Q:
Understanding Error Codes in Python and Using Meanful Error Names
I understand the basic try: except: finally: syntax for pythons error handling. What I don't understand is how to find the proper error names to make readable code.
For example:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.... | Understanding Error Codes in Python and Using Meanful Error Names | I understand the basic try: except: finally: syntax for pythons error handling. What I don't understand is how to find the proper error names to make readable code.
For example:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.settimeout(60)
char = ... | [
"To achieve what you want, you'll have to grab the raised exception, extract the error code stored into, and make some if comparisons against errno codes: \ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((HOST, PORT))\n s.settimeout(60) \n char = s.recv(1)\nex... | [
5,
2,
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0008270510_error_handling_python.txt |
Q:
Creating a Connection Between MySQL and Tornado
I am trying to get a Python and Tornado environment up and running.
As of now I am able to execute Python scripts and now I am trying to be able to make use of databases as well.
By my understanding Tornado has a MySQL wrapper, and I as of now I have XAMPP installe... | Creating a Connection Between MySQL and Tornado | I am trying to get a Python and Tornado environment up and running.
As of now I am able to execute Python scripts and now I am trying to be able to make use of databases as well.
By my understanding Tornado has a MySQL wrapper, and I as of now I have XAMPP installed and I would like to continue using PhpMyAdmin as th... | [
"From Tornado's documentation: \ndb = database.Connection(\"localhost\", \"mydatabase\")\n\nOnce you instantiate a connection ( named db in this example ), you can reuse it during your server's lifetime..\nIf you need to change it dynamically while your tornado server is running, then have tornado \"listen\" to a s... | [
3
] | [] | [] | [
"mysql",
"python",
"python_2.7",
"tornado"
] | stackoverflow_0008270506_mysql_python_python_2.7_tornado.txt |
Q:
Decode Python encoding in Jquery ui autocomplete JSON
My python function.json returns this:
[{"id": "187", "label": "H\xc3\xa1bitos"}]
The label is an encoding of "Hábitos",
How can I get the proper label in Javascript?
A:
This is a proper UTF8 string and not some kind of "python encoding". You just need tn use... | Decode Python encoding in Jquery ui autocomplete JSON | My python function.json returns this:
[{"id": "187", "label": "H\xc3\xa1bitos"}]
The label is an encoding of "Hábitos",
How can I get the proper label in Javascript?
| [
"This is a proper UTF8 string and not some kind of \"python encoding\". You just need tn use UTF8 on your page and it will work.\n"
] | [
0
] | [] | [] | [
"encoding",
"jquery_ui_autocomplete",
"json",
"python"
] | stackoverflow_0008261415_encoding_jquery_ui_autocomplete_json_python.txt |
Q:
Optional named groups Python re
In the Django urls I need an optional named group. This conf without arguments raised an 404 exception:
r'^list_cv/(?P<category>[\d]+)?/$'
How to make optional named group?
A:
Works this way to me:
r'^list_cv/(?:(?P<category>[\w+])/)?$'
EDIT:
Comparing to the original answer ... | Optional named groups Python re | In the Django urls I need an optional named group. This conf without arguments raised an 404 exception:
r'^list_cv/(?P<category>[\d]+)?/$'
How to make optional named group?
| [
"Works this way to me:\nr'^list_cv/(?:(?P<category>[\\w+])/)?$'\n\nEDIT:\nComparing to the original answer the difference is in the repetition match.\n(?:(?P<category>[\\w+])/)?$ vs original (?:(?P<category>[\\w+])?/)$.\n",
"The last slash should be part of the optional RE, and the RE should be like\nr'^list_cv/(... | [
7,
4,
4
] | [] | [] | [
"django",
"python",
"regex"
] | stackoverflow_0008270439_django_python_regex.txt |
Q:
Merging SQLite databases is driving me mad. Help?
I've got 32 SQLite (3.7.9) databases with 3 tables each that I'm trying to merge together using the idiom that I've found elsewhere (each db has the same schema):
attach db1.sqlite3 as toMerge;
insert into tbl1 select * from toMerge.tbl1;
insert into tbl2 select * ... | Merging SQLite databases is driving me mad. Help? | I've got 32 SQLite (3.7.9) databases with 3 tables each that I'm trying to merge together using the idiom that I've found elsewhere (each db has the same schema):
attach db1.sqlite3 as toMerge;
insert into tbl1 select * from toMerge.tbl1;
insert into tbl2 select * from toMerge.tbl2;
insert into tbl3 select * from toMer... | [
"You didn't mention the OS you were using or the db file sizes. Windows can have issues with files that are bigger than 2Gb depending on what version.\nIn any case, since this is a glorified batch script why not get rid of the for loop, get the filename from sys.argv, and then just run it once for each merge db. Th... | [
1,
1
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0008264569_database_python_sqlite.txt |
Q:
Matplotlib demo code not working
I am trying to run demo code from Matplotlib: the legend_picking example.
This code is supposed to hide and show plot lines when the legend is clicked.
It seems that event 'pick_event' is not fired when I click on the line on the legend.
I have no problem with the simple picking ex... | Matplotlib demo code not working | I am trying to run demo code from Matplotlib: the legend_picking example.
This code is supposed to hide and show plot lines when the legend is clicked.
It seems that event 'pick_event' is not fired when I click on the line on the legend.
I have no problem with the simple picking example
"""
# Enable picking on the lege... | [
"Which version of matplotlib are you running? Works just fine for me (version 1.1.0). There are multiple examples on the sourceforge site which do not work for versions below 1.0. To find out the version number, use\nimport matplotlib\nprint matplotlib.__version__\n\n",
"It does work. Just click on the lines in t... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008270587_matplotlib_python.txt |
Q:
Python: compile into an Unix commandline app
I am not sure if I searched for the wrong terms, but I could not find much on this subject. I am on osx and I'd like to compile a commandline python script into a small commandline app, that I can put into usr/local/bin so I can call it from anywhere. Is there a straigh... | Python: compile into an Unix commandline app | I am not sure if I searched for the wrong terms, but I could not find much on this subject. I am on osx and I'd like to compile a commandline python script into a small commandline app, that I can put into usr/local/bin so I can call it from anywhere. Is there a straighforward way to do that?
Thanks
| [
"The simplest way to do this is to rename your file from filename.py to filename and add this line to the top of the file.\n#!/usr/bin/env python\nYou may also need to set the executable bit on the file, which may be set using chmod +x on the command line.\n",
"On Unix it works usually in the following way:\n\nPu... | [
6,
4,
2,
0,
0
] | [] | [] | [
"command_line",
"python",
"unix"
] | stackoverflow_0008271629_command_line_python_unix.txt |
Q:
Testing multiple browsers with a single test definition in Selenium
Is there an easy way to do this in Python? I have a pytest funcarg defined like so;
def pytest_funcarg__selenium(request):
sel = selenium('10.3.10.154', 5555, '*firefox', 'http://10.3.10.180:8000')
sel.start()
return sel
Which obviou... | Testing multiple browsers with a single test definition in Selenium | Is there an easy way to do this in Python? I have a pytest funcarg defined like so;
def pytest_funcarg__selenium(request):
sel = selenium('10.3.10.154', 5555, '*firefox', 'http://10.3.10.180:8000')
sel.start()
return sel
Which obviously won't work, as I have no means of changing the specified browser in m... | [
"One technique I've seen used is to organize the tests in a class and use subclassing to switch class variables indicating which browser to test:\nclass TestFirefox:\n browser = '*firefox'\n\n def pytest_funcarg__selenium(self, request):\n sel = selenium('10.3.10.154', 5555, self.browser, 'http://10.3.... | [
0,
0,
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0008264791_python_selenium.txt |
Q:
how do i go over lines in an open text file on Python (2.72)
I have text files with a few thousands words in them (one word in a line).
I've written a function which take two words (strings), and checks if one
word is an Anagram of the other (that means if the two words contains the same
letters, even if in differ... | how do i go over lines in an open text file on Python (2.72) | I have text files with a few thousands words in them (one word in a line).
I've written a function which take two words (strings), and checks if one
word is an Anagram of the other (that means if the two words contains the same
letters, even if in different order).
Now I want to go over my huge text file and search for... | [
"file = 'file.txt'\nwith open(file, 'r') as f:\n for line in f:\n pass\n\n",
"The Python Tutorial has you covered:\n\nAn alternative approach to reading lines is to loop over the file\n object. This is memory efficient, fast, and leads to simpler code:\nfor line in f:\n print line,\n\n\nYou can use ... | [
2,
0,
0,
0,
0,
0
] | [] | [] | [
"list",
"python",
"text_files"
] | stackoverflow_0008269722_list_python_text_files.txt |
Q:
Why does text retrieved from pages sometimes look like gibberish?
I'm using urllib and urllib2 in Python to open and read webpages but sometimes, the text I get is unreadable. For example, if I run this:
import urllib
text = urllib.urlopen('http://tagger.steve.museum/steve/object/141913').read()
print text
I get... | Why does text retrieved from pages sometimes look like gibberish? | I'm using urllib and urllib2 in Python to open and read webpages but sometimes, the text I get is unreadable. For example, if I run this:
import urllib
text = urllib.urlopen('http://tagger.steve.museum/steve/object/141913').read()
print text
I get some unreadable text. I've read these posts:
Gibberish from urlopen
D... | [
"This gibberish is a real server response for the request to 'http://tagger.steve.museum/steve/object/141913'. Actually, it looks like obfuscated JavaScript, which, if executed by a browser, loads page content.\nTo get this content, you need to execute this JavaScript, and this can be a really difficult task withi... | [
2,
1
] | [] | [] | [
"python",
"urllib",
"urllib2",
"urlopen"
] | stackoverflow_0008271484_python_urllib_urllib2_urlopen.txt |
Q:
Not getting what I want using the format function
Ok. I have a CSV, and I'm trying to use the format function to rearrange the order in which the data of the columns prints.
In other words, how can I use the format function to print columns in the order e,d,c instead of the default c,d,e?
Here's what I have so fa... | Not getting what I want using the format function | Ok. I have a CSV, and I'm trying to use the format function to rearrange the order in which the data of the columns prints.
In other words, how can I use the format function to print columns in the order e,d,c instead of the default c,d,e?
Here's what I have so far:
for row in books:
print [item.upper() for item... | [
"If you want to change the order of the columns, you can do:\nfor row in books:\n print list(reversed(row)) # Prints the reversed row, as a list\n print ', '.join(reversed(row)) # Prints a single string of comma-separated values\n print [row[index] for index in (2, 0, 1)] # General order change\n pri... | [
2,
2,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0008272027_csv_python.txt |
Q:
An issue with the soaplib hello world program
I am trying to get this server to run however I keep getting an error:
server:
import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.claz... | An issue with the soaplib hello world program | I am trying to get this server to run however I keep getting an error:
server:
import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array
class HelloWorldService(DefinitionB... | [
"Add the following line to your imports\n from soaplib.core.service import soap\n\nAnd it should work fine ;-)\nsecuredome\n",
"Shouldn't it be :\n@soapmethod(String,Integer,_returns=Array(String)) ?\n"
] | [
2,
0
] | [] | [] | [
"python",
"soap",
"soaplib"
] | stackoverflow_0008089070_python_soap_soaplib.txt |
Q:
return pdf response from stdout with Django
I am using wkhtmltopdf to create PDF files, how ever I don't know how to return them properly, so I had to write them to my media folder and then redirect to the just created file.
Edit:
Ian's advice is to write to STDOUT, so I have changed my wkhtmltopdf command to do ... | return pdf response from stdout with Django | I am using wkhtmltopdf to create PDF files, how ever I don't know how to return them properly, so I had to write them to my media folder and then redirect to the just created file.
Edit:
Ian's advice is to write to STDOUT, so I have changed my wkhtmltopdf command to do that, but now I don't know how to return that con... | [
"You should open your sub command like so:\npopen = Popen(command_args, stdout=PIPE, stderr=PIPE)\nbody_contents = popen.stdout().read()\npopen.terminate()\npopen.wait()\nr = HttpResponse(body_contents, mimetype='application/pdf')\n\nSome things to be careful of:\n\nIf your popen'd command writes to STDERR it may d... | [
5,
1,
0,
0
] | [] | [] | [
"django",
"pdf",
"python",
"wkhtmltopdf"
] | stackoverflow_0005008466_django_pdf_python_wkhtmltopdf.txt |
Q:
cherrypy relative paths in config file?
I am using Cherrypy v3.2. I fail to find good docs about how to write nice config files. At the moment here is an excerpt of what I have (the original file is fairly large) :
[global]
server.thread_pool = 8
server.socket_host = '10.109.26.56'
server.socket_port = 8000
tools.... | cherrypy relative paths in config file? | I am using Cherrypy v3.2. I fail to find good docs about how to write nice config files. At the moment here is an excerpt of what I have (the original file is fairly large) :
[global]
server.thread_pool = 8
server.socket_host = '10.109.26.56'
server.socket_port = 8000
tools.sessions.on = True
[/]
tools.staticdir.root ... | [
"staticdir and staticfile are two different tools; they don't share config. If you're going to use staticfile, then set its root:\n[/]\ntools.staticfile.root = \"C:\\Documents and Settings\\ginssj\\Desktop\\cherry\"\n\nand then you can use relative file paths for the .file entries:\n[/style/iegl/Samples.css]\ntools... | [
2
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0008266491_cherrypy_python.txt |
Q:
Python Sendmail with Attachment?
I am programming with python. I already have a function that sends mails with attachments, but the problem is that it takes the message and puts it as an attachment. I need that it respects the message as message and the attachment as attachment. I have investigated and I found tha... | Python Sendmail with Attachment? | I am programming with python. I already have a function that sends mails with attachments, but the problem is that it takes the message and puts it as an attachment. I need that it respects the message as message and the attachment as attachment. I have investigated and I found that has to do with MIME Multipart "MIXED... | [
"You forgot to attach the text as msg.attach( MIMEText(text) )\ndef enviarCorreo(fromaddr, toaddr, text, file):\n msg = MIMEMultipart('mixed')\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = 'asunto'\n\n #This is the part you had missed.\n msg.attach( MIMEText(text) )\n\n #adju... | [
3,
0
] | [] | [] | [
"mime_types",
"python",
"sendmail"
] | stackoverflow_0008271931_mime_types_python_sendmail.txt |
Q:
How to print a file to paper in Python 3 on windows XP/7?
For a project i'm working on, I need to be able to write to a text file and then send that file to the printer. I'm fairly new to programming (1.5 yrs) and in my time have never needed to do this.
So, my question is how would I send the file to the printer?... | How to print a file to paper in Python 3 on windows XP/7? | For a project i'm working on, I need to be able to write to a text file and then send that file to the printer. I'm fairly new to programming (1.5 yrs) and in my time have never needed to do this.
So, my question is how would I send the file to the printer? (Obviously I know how to write to the file in the first place)... | [
"A simple approach is to have Notepad print the text file:\nimport subprocess\nsubprocess.call(['notepad', '/p', filename])\n\n",
"I did this a long time ago, so I don't remember the specifics, but it involved going through a win32 extension for python to call the Windows API related to printing.\nYou may also co... | [
7,
4
] | [] | [] | [
"printing",
"python"
] | stackoverflow_0008272161_printing_python.txt |
Q:
Setting the display range suplot of errorbars in matplotlib
I'm trying to plot my data using matplot lib. I have 3 separetes sets of data I want to plot in 3 subplots (I'm using this is my guidence):
plt.figure()
fig, axs = plt.subplots(nrows=3, ncols = 1, sharex=False)
ax1 = axs[0]
ax1.errorbar(X,Y,Err,fmt='o')
... | Setting the display range suplot of errorbars in matplotlib | I'm trying to plot my data using matplot lib. I have 3 separetes sets of data I want to plot in 3 subplots (I'm using this is my guidence):
plt.figure()
fig, axs = plt.subplots(nrows=3, ncols = 1, sharex=False)
ax1 = axs[0]
ax1.errorbar(X,Y,Err,fmt='o')
ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.set_title('epsilo... | [
"You might want to use Axes.axis(*v, **kwargs):\nax1.axis(xmin=0.5,xmax=13.5)\n\nFrom the documentation:\n\nSet/Get the axis properties\nIf len(*v)==0, you can pass in xmin, xmax,\nymin, ymax as kwargs selectively to alter just those limits without\nchanging the others.\n\n",
"The corresponding method of axis obj... | [
26,
12
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008224894_matplotlib_python.txt |
Q:
How to write data by dynamic parameter name
I need to be able to write data to datastore of google-app-engine for some known entity. But I don't want write assignment code for each parameter of the entity. I meen, I don't want do like this
val_1 = self.request.get('prop_1')
val_2 = self.request.get('prop_2')
...
v... | How to write data by dynamic parameter name | I need to be able to write data to datastore of google-app-engine for some known entity. But I don't want write assignment code for each parameter of the entity. I meen, I don't want do like this
val_1 = self.request.get('prop_1')
val_2 = self.request.get('prop_2')
...
val_N = self.request.get('prop_N')
item.prop_1 = v... | [
"You need to use the Expando class.\n\nThe Expando class is a superclass for data model definitions whose\n properties are determined dynamically. An Expando model can have a\n combination of fixed properties similar to Model and dynamic\n properties assigned to an entity at run-time\n\n",
"You can do this usi... | [
0,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008272487_google_app_engine_python.txt |
Q:
Why is early return slower than else?
This is a follow-up question to an answer I gave a few days back. Edit: it seems that the OP of that question already used the code I posted to him to ask the same question, but I was unaware of it. Apologies. The answers provided are different though!
Substantially I observed... | Why is early return slower than else? | This is a follow-up question to an answer I gave a few days back. Edit: it seems that the OP of that question already used the code I posted to him to ask the same question, but I was unaware of it. Apologies. The answers provided are different though!
Substantially I observed that:
>>> def without_else(param=False):
.... | [
"This is a pure guess, and I haven't figured out an easy way to check whether it is right, but I have a theory for you.\nI tried your code and get the same of results, without_else() is repeatedly slightly slower than with_else():\n>>> T(lambda : without_else()).repeat()\n[0.42015745017874906, 0.3188967452567226, 0... | [
416
] | [] | [] | [
"optimization",
"python",
"python_2.7"
] | stackoverflow_0008271139_optimization_python_python_2.7.txt |
Q:
Unicode string Python
I need to write to a file a string that contains the degree sign (°).
This string is stored in variable and, as expected, when I try: f.write(myVariable.encode('utf-8')) I get UnicodeDecodeError.
If I try to write this string to a file like:
x = u'aaa°°bbb'
f.write(encode(x))
works fine, but... | Unicode string Python | I need to write to a file a string that contains the degree sign (°).
This string is stored in variable and, as expected, when I try: f.write(myVariable.encode('utf-8')) I get UnicodeDecodeError.
If I try to write this string to a file like:
x = u'aaa°°bbb'
f.write(encode(x))
works fine, but I can't write x = u'aaa°°b... | [
"Decode it after retrieving it, using whatever encoding your database uses.\ns.decode('latin1')\n\nOf course, if it's misencoded in the database in the first place then you'll need to compensate somehow.\ns.encode('latin1').decode('utf8')\n\n",
"Depending on if your myVariable is in unicode or bytes format (diffe... | [
2,
1,
1,
0
] | [
"make sure you have # -*- coding: utf-8 -*- at the top of your python file. It should encode seamlessly\n"
] | [
-1
] | [
"python",
"unicode"
] | stackoverflow_0008271854_python_unicode.txt |
Q:
A slider for curses based UI
As a learning project, I'd like to set-out to make an ncurses-based UI for a program I had in mind, written in python.
After looking at urwid documentation, I cannot see anyway to create a simple slider (I need it to make a volume slider) that can be adjusted with the mouse.
Am I missi... | A slider for curses based UI | As a learning project, I'd like to set-out to make an ncurses-based UI for a program I had in mind, written in python.
After looking at urwid documentation, I cannot see anyway to create a simple slider (I need it to make a volume slider) that can be adjusted with the mouse.
Am I missing something in urwid, or is there... | [
"Curses is has very low level API - going back to the 1980's C'programing.\nThe Python wrappers have some higher level support for keyboard input and some other niceties, but they are few and apart and not nicely documented.\nThe Python niceties do not include Mouse support (ok, you get your mouse state back in a t... | [
2
] | [] | [] | [
"ncurses",
"python",
"slider",
"volume"
] | stackoverflow_0008251110_ncurses_python_slider_volume.txt |
Q:
Problems installing SimpleCV
I'm having trouble finding out how to install SimpleCV. I followed a YouTube video and I installed it (on OSX Lion with Python 2.6) and everything went fine. Now when I run SimpleCV.command from the application folder I get the following:
$ /Applications/SimpleCV/SimpleCV.command
Trac... | Problems installing SimpleCV | I'm having trouble finding out how to install SimpleCV. I followed a YouTube video and I installed it (on OSX Lion with Python 2.6) and everything went fine. Now when I run SimpleCV.command from the application folder I get the following:
$ /Applications/SimpleCV/SimpleCV.command
Traceback (most recent call last):
Fil... | [
"That import error means that the SimpleCV module didn't make it into your Python path. If you installed with the superpack, this means something probably went wrong with the post-install script hook.\nIf re-installing the superpack does not work, take a look at http://simplecv.org/doc/installation.html#mac-os-x-1... | [
2
] | [] | [] | [
"macos",
"opencv",
"osx_lion",
"python"
] | stackoverflow_0008248572_macos_opencv_osx_lion_python.txt |
Q:
Why do some arguments need to be defined, and others not? (Learn Python the Hard Way, ex. 25)
Working my way through Learn Python the Hard Way ex.25, and I just can't wrap my head around something. Here's the script:
def break_words(stuff):
"""this function will break waords up for us."""
words = stuff.sp... | Why do some arguments need to be defined, and others not? (Learn Python the Hard Way, ex. 25) | Working my way through Learn Python the Hard Way ex.25, and I just can't wrap my head around something. Here's the script:
def break_words(stuff):
"""this function will break waords up for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(word... | [
"It's about the type of value that each function accepts as its parameter. \nbreak_words returns a list. sort_words uses the built-in function sorted(), which expects to be passed a list. This means that the parameter you pass to sort_words should be a list.\nMaybe the following example illustrates this:\n>>> sort_... | [
5
] | [] | [] | [
"arguments",
"declaration",
"python"
] | stackoverflow_0008272718_arguments_declaration_python.txt |
Q:
Pass a function to a COM Object Function as a parameter
I'm using the UPnP Object Method IUPnPDeviceFinder::[CreateAsyncFind][1] and the third parameter is a callback function.
I've tried to create my own COM Object but the method don't call back my function. Here's my code:
class Callback():
_public_methods_ ... | Pass a function to a COM Object Function as a parameter | I'm using the UPnP Object Method IUPnPDeviceFinder::[CreateAsyncFind][1] and the third parameter is a callback function.
I've tried to create my own COM Object but the method don't call back my function. Here's my code:
class Callback():
_public_methods_ = ['DeviceAdded','DeviceRemoved', 'SearchComplete']
_reg_... | [
"One problem (maybe not the only one) is DeviceAdded is a method of a class, so it needs a self parameter:\ndef DeviceAdded(self, device, UDN, calltype):\n\nI think you are on the right track with your first example, at least when compared to the VBScript (and C++ link) in the link you provided.\nAlso, You shouldn'... | [
1
] | [] | [] | [
"com",
"python",
"upnp"
] | stackoverflow_0008271577_com_python_upnp.txt |
Q:
Python SSLError: Client-side-error(EOF occurred in violation of protocol), Server-side-error(SSL3_GET_RECORD:wrong version number)
I'm having some difficulty attempting to create an SSL socket in Python to use a proxy that requires authentication. I am very sorry for the length, but I felt it was best to include ... | Python SSLError: Client-side-error(EOF occurred in violation of protocol), Server-side-error(SSL3_GET_RECORD:wrong version number) | I'm having some difficulty attempting to create an SSL socket in Python to use a proxy that requires authentication. I am very sorry for the length, but I felt it was best to include as much detail as possible.
First, the server code looks like this:
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TC... | [
"I've figured out the issue to my problem. I am sending the self.user_agent to the remote host when I connect via the proxy for the first time, which interferes with the SSL Handshake.\nTo solve this, I put an initial self.request.recv() in the def setup(self) function before I call ssl.wrap_socket on the socket.\... | [
1
] | [] | [] | [
"python",
"sockets",
"ssl"
] | stackoverflow_0008247416_python_sockets_ssl.txt |
Q:
Python. How to edit data in text database?
I have a little database text file db.txt:
(peter)
name = peter
surname = asd
year = 23
(tom)
name = tom
surname = zaq
year = 22
hobby = sport
(paul)
name = paul
surname = zxc
hobby = music
job = teacher
How to get all data sec... | Python. How to edit data in text database? | I have a little database text file db.txt:
(peter)
name = peter
surname = asd
year = 23
(tom)
name = tom
surname = zaq
year = 22
hobby = sport
(paul)
name = paul
surname = zxc
hobby = music
job = teacher
How to get all data section from for example tom? I want to get in vari... | [
"Using PyYAML as suggested by @aitchnyu and making a little modifications on the original format makes this an easy task:\nimport yaml\n\ntext = \"\"\"\npeter:\n name: peter\n surname: asd\n year: 23\ntom:\n name: tom\n surname: zaq\n year: 22\n hobby: sport\npaul:\n name: paul\n surname:... | [
2,
0
] | [] | [] | [
"database",
"file",
"python",
"rewrite",
"text"
] | stackoverflow_0008271084_database_file_python_rewrite_text.txt |
Q:
Keeping a socket opened in a thread, and sending commands from Main
I need to open a socket connection in a new thread. That connection needs to stay open. Then I need to be able to send data to the socket from the main scope.
I have a feeling what's happening with my code is that the thread is completing & clos... | Keeping a socket opened in a thread, and sending commands from Main | I need to open a socket connection in a new thread. That connection needs to stay open. Then I need to be able to send data to the socket from the main scope.
I have a feeling what's happening with my code is that the thread is completing & closing the socket right away and then there's no properties to send data to.... | [
"You may find the example in this post useful - it demonstrates a thread that perform socket communication receiving commands from another thread via Queue objects. It's a rather generic sample, well documented (both in comments and the linked blog post) and you can easily adapt it for any specific purpose.\n",
"... | [
1,
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0008273297_python_sockets.txt |
Q:
Python's MySQLdb slow! using 'SSCurso'r vs PHP's 'mysql_fetch_assoc'
I need to go over an entire table in Python.
I am using MySQLdb via 'SSCursor' and it is much slower than PHP's stuff.
PHP 5.3.5
$result = mysql_query("SELECT * FROM anytable");
while($row = mysql_fetch_assoc($result)){
#do stuff
}
Python2.7
cu... | Python's MySQLdb slow! using 'SSCurso'r vs PHP's 'mysql_fetch_assoc' | I need to go over an entire table in Python.
I am using MySQLdb via 'SSCursor' and it is much slower than PHP's stuff.
PHP 5.3.5
$result = mysql_query("SELECT * FROM anytable");
while($row = mysql_fetch_assoc($result)){
#do stuff
}
Python2.7
cursor.execute("SELECT * FROM anytable")
for row in cursor:
pass
RESULT... | [
"Are you printing python results to stdout? \nBecause I'd expect around this kind of difference in performance if you ARE printing all the data to stdout (the console). PHP code normally is run without stdout output to the console. The problem is that outputing to the console involves the computer having to draw an... | [
0
] | [
"You can use SQLAlchemy module. You can optimize your quires, for better memory and cpu usage.\nReference: http://www.sqlalchemy.org/features.html\n"
] | [
-2
] | [
"mysql_python",
"php",
"python"
] | stackoverflow_0007111656_mysql_python_php_python.txt |
Q:
Find the largest divisor of N that is less than sqrt(N)
Actually, given N a (possibly very large) even integer, I want to find N = F * R where gcd(F,R) = 1, F>R, and F is as small as possible (since I'll be completely factoring F). The heart of the problem is finding the largest divisor R where R < sqrt(N).
For ex... | Find the largest divisor of N that is less than sqrt(N) | Actually, given N a (possibly very large) even integer, I want to find N = F * R where gcd(F,R) = 1, F>R, and F is as small as possible (since I'll be completely factoring F). The heart of the problem is finding the largest divisor R where R < sqrt(N).
For example, N=36 should give F=9 and R=4. Notice that R is not nec... | [
"Wikipedia has a nice list of factoring algorithms: http://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms\nYour second approach effectively uses a sieve and has the nice property of quickly reducing the problem when N is a multiple of some small prime. The code can be improved by looping over p... | [
5,
0,
0
] | [] | [] | [
"c",
"factorization",
"generator",
"math",
"python"
] | stackoverflow_0008272905_c_factorization_generator_math_python.txt |
Q:
google-api-python-client sample code gives 'module object has no attribute socket'
When trying to activate sample code from the Latitude example in google-api-python-client I get the following error: "_webapp25.py:464] 'module' object has no attribute 'socket'".
The code is:
from apiclient.ext.file import Storage
... | google-api-python-client sample code gives 'module object has no attribute socket' | When trying to activate sample code from the Latitude example in google-api-python-client I get the following error: "_webapp25.py:464] 'module' object has no attribute 'socket'".
The code is:
from apiclient.ext.file import Storage
from apiclient.discovery import build
from apiclient.ext.authtools import run
from oauth... | [
"It would have been useful to post the traceback - that's always helpful information.\nI would guess that your problem is that the example you post is for a command-line application, yet you're trying to use it for a web server authentication flow. Try importing run from oauth2client.tools instead.\n"
] | [
0
] | [] | [] | [
"google_api",
"google_api_client",
"google_api_python_client",
"python"
] | stackoverflow_0008273287_google_api_google_api_client_google_api_python_client_python.txt |
Q:
Using OAuth in Yahoo! API Requests (Python)
I'm trying to integrate an application with a Yahoo! api that requires oauth authentication to access protected data.
I'm using python-oauth2 and following along with the steps listed in Yahoo's Oauth Authorization Flow document. I've been able to complete all of the st... | Using OAuth in Yahoo! API Requests (Python) | I'm trying to integrate an application with a Yahoo! api that requires oauth authentication to access protected data.
I'm using python-oauth2 and following along with the steps listed in Yahoo's Oauth Authorization Flow document. I've been able to complete all of the steps to negotiate an access token with Yahoo, but ... | [
"Well I feel a bit sheepish. So it turns out that Yahoo also throws this exact error when you access an invalid API call. So in my case I was accessing a root API when I had to specify a sub API. Moral of the story: beware that oauth errors might be representative of other issues in your app/code.\n"
] | [
0
] | [] | [] | [
"oauth",
"python",
"yahoo_api"
] | stackoverflow_0008205534_oauth_python_yahoo_api.txt |
Q:
Tutorial or Guide for Scripting Xcode Build Phases
I would like to add some files to the Compile Sources build phase using a script in Xcode, which pulls from some folder references. I haven't been able to find much documentation so far.
Where is the general documentation (or a good tutorial) for scripting Xcode ... | Tutorial or Guide for Scripting Xcode Build Phases | I would like to add some files to the Compile Sources build phase using a script in Xcode, which pulls from some folder references. I haven't been able to find much documentation so far.
Where is the general documentation (or a good tutorial) for scripting Xcode build phases?
How can I add files to the Compile Sources... | [
"To add files to the Compile Sources build phase using a script, you will need to manipulate your project's project.pbxproj file programmatically. \nGenerally speaking, you would accomplish this by parsing the project.pbxproj file into an in-memory data structure, manipulating that data structure through a program... | [
22
] | [] | [] | [
"build_automation",
"python",
"ruby",
"xcode"
] | stackoverflow_0007557273_build_automation_python_ruby_xcode.txt |
Q:
Deleting widgets (involving tkinter module)
new guy here and I'm slowly getting the hang of python, but I have a question.
I have two files here
one is named first_file.py
from other_file import GameFrame
from Tkinter import Tk
def main():
tk = Tk()
tk.title("Game of Life Simulator")
tk.geometry("380x... | Deleting widgets (involving tkinter module) | new guy here and I'm slowly getting the hang of python, but I have a question.
I have two files here
one is named first_file.py
from other_file import GameFrame
from Tkinter import Tk
def main():
tk = Tk()
tk.title("Game of Life Simulator")
tk.geometry("380x580")
GameFrame(tk)
tk.mainloop()
main()
... | [
"A common method is to save your objects in a list (or dictionary) in order to access them when needed. A simple example:\nself.mybuttons = defaultdict(list)\nfor rows in range(1,21):\n for columns in range(1,21):\n self.mybuttons[rows].append(Button(self, text=''))\n\nThen you can get buttons, this way:\... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008269824_python_tkinter.txt |
Q:
How to check whether a variable is a SwigObject type
I want to check whether a variable is a SwigObject type. I am trying to use isinstance built-in but doesn't know what need to be passed (i.e. isinstance(obj, ???)).
Thanks!
A:
Are you simply asking for this?
>>> a = list()
>>> isinstance(a, int)
False
>>> isin... | How to check whether a variable is a SwigObject type | I want to check whether a variable is a SwigObject type. I am trying to use isinstance built-in but doesn't know what need to be passed (i.e. isinstance(obj, ???)).
Thanks!
| [
"Are you simply asking for this?\n>>> a = list()\n>>> isinstance(a, int)\nFalse\n>>> isinstance(a, list)\nTrue\n\nAs you can see the first argument of isinstance is your object instantiation, the second - in your case - would probably look like swig.SwigObject (you need to provide the correct \"path\" to the class,... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008274353_python.txt |
Q:
Can't recover list of items from HTTP POST request
I'm working on a Django app.
In the frontend, I've got a HTML form with some checkboxes that go something like:
<input type="checkbox" name="list" value="item1" />Item one<br/>
<input type="checkbox" name="list" value="item2" />Item two<br/>
Upon submitting, the... | Can't recover list of items from HTTP POST request | I'm working on a Django app.
In the frontend, I've got a HTML form with some checkboxes that go something like:
<input type="checkbox" name="list" value="item1" />Item one<br/>
<input type="checkbox" name="list" value="item2" />Item two<br/>
Upon submitting, the HTTP POST request as seen from the Django backend looks... | [
"Try:\nlist = request.POST.getlist('list')\n\nalso consider changing the name of variable list to something else, it's a built in type.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008274724_django_python.txt |
Q:
saving an 'lxml.etree._ElementTree' object
I've spent the last couple of days getting to grips with the basics of lxml; in particular using lxml.html to parse websites and create an ElementTree of the content. Ideally, I want to save the returned ElementTree so that I can load it up and experiment with it, without... | saving an 'lxml.etree._ElementTree' object | I've spent the last couple of days getting to grips with the basics of lxml; in particular using lxml.html to parse websites and create an ElementTree of the content. Ideally, I want to save the returned ElementTree so that I can load it up and experiment with it, without having to parse the website every time I modify... | [
"You are already dealing with XML, and lxml is great at parsing XML. So I think\nthe simplest thing to do would be to serialize to XML:\nTo write to file:\nimport lxml.etree as ET\n\nfilename = '/tmp/test.xml'\nmyobject.write(filename)\n\nTo call the write method, note that myobject must be an lxml.etree._ElementTr... | [
19,
16,
4
] | [] | [] | [
"lxml",
"pickle",
"python"
] | stackoverflow_0008274438_lxml_pickle_python.txt |
Q:
How to do a memset with Python buffer object?
How can I do a fast reset for a continue set of values inside a Python buffer object?
Mainly I am looking for a memset :)
PS. The solution should work with Python 2.5 and modify the buffer itself (no copy).
A:
The ctypes package has a memset function built right in. ... | How to do a memset with Python buffer object? | How can I do a fast reset for a continue set of values inside a Python buffer object?
Mainly I am looking for a memset :)
PS. The solution should work with Python 2.5 and modify the buffer itself (no copy).
| [
"The ctypes package has a memset function built right in. Ctypes does work with Python 2.5, but is not included by default. You will need a separate install.\ndef memsetObject(bufferObject):\n \"Note, dangerous\"\n import ctypes\n data = ctypes.POINTER(ctypes.c_char)()\n size = ctypes.c_int() # Note, i... | [
3,
1,
1
] | [] | [] | [
"buffer",
"python",
"python_2.5",
"wxpython"
] | stackoverflow_0008270919_buffer_python_python_2.5_wxpython.txt |
Q:
Writing all data from each row in CheckListCtrl
There is example code for the creation of CheckListCtrl. I took it from here.
import wx
import sys
from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
packages = [('abiword', '5.8M', 'base'), ('adie', '145k', 'base'),
('airsnort', '71k'... | Writing all data from each row in CheckListCtrl | There is example code for the creation of CheckListCtrl. I took it from here.
import wx
import sys
from wx.lib.mixins.listctrl import CheckListCtrlMixin, ListCtrlAutoWidthMixin
packages = [('abiword', '5.8M', 'base'), ('adie', '145k', 'base'),
('airsnort', '71k', 'base'), ('ara', '717k', 'base'), ('arc', '139k', '... | [
"Get the item for the corresponding row/column and print its text:\nitem = self.list.GetItem(row, column)\nprint item.GetText()\n\n"
] | [
1
] | [] | [] | [
"python",
"user_interface",
"wxpython",
"wxwidgets"
] | stackoverflow_0008271128_python_user_interface_wxpython_wxwidgets.txt |
Q:
Comparing between two words (Anagrams) in Python 2.72
Possible Duplicate:
Checking if two strings are permutations of each other in Python
I need to write a function which receives two words (strings), and checks
if the two words have exactly the same letters, with exactly the same number of appearances for each... | Comparing between two words (Anagrams) in Python 2.72 |
Possible Duplicate:
Checking if two strings are permutations of each other in Python
I need to write a function which receives two words (strings), and checks
if the two words have exactly the same letters, with exactly the same number of appearances for each letter (if so, they are Anagrams).
The function will ret... | [
"from collections import Counter\ndef isAnagram( w1, w2):\n return Counter(w1) == Counter(w2)\n\n",
"Think about what you just learned, and this should make your homework a lot easier.\nLet me guess, you just learned about sorting?\n"
] | [
0,
0
] | [] | [] | [
"anagram",
"compare",
"python",
"string"
] | stackoverflow_0008275092_anagram_compare_python_string.txt |
Q:
Custom Items in QListView
I'm (very) new to PyQT and QT in general and have to quickly design a user interface that's broadly similar to modern 2-pane mail apps: left a list of mails, right an editor. I'd like to give a little more information than just a String to display in the QListView -- basically the items n... | Custom Items in QListView | I'm (very) new to PyQT and QT in general and have to quickly design a user interface that's broadly similar to modern 2-pane mail apps: left a list of mails, right an editor. I'd like to give a little more information than just a String to display in the QListView -- basically the items name in bold text, below two lin... | [
"If you dont want to think about your model, or really share is between views, then a QListWidget is meant for that purpose. You just deal with the List directly and the data is stored in its own underlying model.\nFor a QListWidget, you can use: QListWidget.setItemWidget(QListWidgetItem item, QWidget widget)\nThat... | [
4,
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008247151_pyqt_pyqt4_python.txt |
Q:
Python urllib2 ensuring url is well-formed
In ValueError: unknown url type in urllib2, though the url is fine if opened in a browser, it was pointed out that before calling opener.open() you must ensure that the url passed to it is well-formed (ie - has a "http://" prefix for HTTP urls, "ftp://" for FTP, etc).
Th... | Python urllib2 ensuring url is well-formed | In ValueError: unknown url type in urllib2, though the url is fine if opened in a browser, it was pointed out that before calling opener.open() you must ensure that the url passed to it is well-formed (ie - has a "http://" prefix for HTTP urls, "ftp://" for FTP, etc).
The question was refined to ask "Is it possible to... | [
"In Python it's quite common to accept and exception instead of checkin the value in advance. So something like this would be perfectly of for me and probably for most python programmers:\ntry:\n opener.open(url)\nexcept ValueError,e:\n # fix url and try again\n # ...\n\nBut I don't see how you would like ... | [
3,
0
] | [] | [] | [
"httprequest",
"python",
"urllib2"
] | stackoverflow_0008274829_httprequest_python_urllib2.txt |
Q:
How to make a python wsgi script return to php?
I have a php script that passes a value to an http://something..../wsgi.py page which computes and returns a value.
I do not want to display this .py page. Instead, I want to call another php page along with the value computed by the python page.
Any pointers on how ... | How to make a python wsgi script return to php? | I have a php script that passes a value to an http://something..../wsgi.py page which computes and returns a value.
I do not want to display this .py page. Instead, I want to call another php page along with the value computed by the python page.
Any pointers on how to proceed?
| [
"An elegant solution to this problem would be to return an HTTP redirect response from the Python script. With such a solution, your browser doesn't need to load and display the HTML from the Python script, making the redirection more transparent to the user.\nA code snippet creating HTTP redirect with WSGI follows... | [
2,
1
] | [] | [] | [
"php",
"python",
"wsgi"
] | stackoverflow_0008274248_php_python_wsgi.txt |
Q:
How to check if item has been dropped? wxpython?
Using the DragAndDrop of wxpython, is there a way to get when text has been dropped then preform a function? ( i am looking for something like a bind ). There doesnt seem to be any examples online how to do this.
It says on http://wiki.wxpython.org/DragAndDrop to
B... | How to check if item has been dropped? wxpython? | Using the DragAndDrop of wxpython, is there a way to get when text has been dropped then preform a function? ( i am looking for something like a bind ). There doesnt seem to be any examples online how to do this.
It says on http://wiki.wxpython.org/DragAndDrop to
Bind a wxDataObject to the drop target by calling SetDa... | [
"The self.Bind() methods you are looking for are not visible in the posted code. They are defined in the wx.TextDropTarget and wx.FileDropTarget classes from where your classes inherit.\nThe 'Binded' methods triggered by the drop event are OnDropText and OnDropFiles, respectively.\nSo you can code or call your func... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008263945_python_wxpython.txt |
Q:
Audio using PyGame Subset for Android
I am trying to play a simple wav file using PyGame Subset for Android. I can't seem to get it working. Does anyone have any example code working? There isn't any examples in the documentation.
A:
According to Pygame Subset for Android documentation, you should be able to pla... | Audio using PyGame Subset for Android | I am trying to play a simple wav file using PyGame Subset for Android. I can't seem to get it working. Does anyone have any example code working? There isn't any examples in the documentation.
| [
"According to Pygame Subset for Android documentation, you should be able to play sounds using android_mixer. Start by importing it [1]:\nimport android_mixer as mixer\n\nNow use the mixer just as a common pygame mixer to play sounds:\nmixer.music.load(sys.argv[1])\nmixer.music.play()\n\nPlease note that \"the init... | [
0
] | [] | [] | [
"android",
"audio",
"pygame",
"python",
"subset"
] | stackoverflow_0008275224_android_audio_pygame_python_subset.txt |
Q:
StandardContextMenu internationalization in PyQt
What is the best way to translate (localize) context menu in QPlaintTextEdit in PyQt ?
For example :
popup_menu = self.createStandardContextMenu()
popup_menu.insertMenu(popup_menu.actions()[0], QMenu(self.tr("My menu")))
Here, i can translate "My menu" (pylupdate4, ... | StandardContextMenu internationalization in PyQt | What is the best way to translate (localize) context menu in QPlaintTextEdit in PyQt ?
For example :
popup_menu = self.createStandardContextMenu()
popup_menu.insertMenu(popup_menu.actions()[0], QMenu(self.tr("My menu")))
Here, i can translate "My menu" (pylupdate4, then lrelease) but not all others standards items like... | [
"The context menu for QPlaintTextEdit is provided by an internal QTextControl class (which is also used by other widgets like QTextEdit), and the text of each menu item is already wrapped in a tr call. So any applications that want these strings translated just needs to ensure that they load the appropriate transla... | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008274465_pyqt_pyqt4_python.txt |
Q:
Python - How to define attributes not affected by __getattr__?
I'm fairly new to Python. In programming a lot of PHP recently I got used to some creative use of __get and __set "magic" methods. These were only called when a public variable of the class wasn't present.
I'm trying to replicate the same behavior in... | Python - How to define attributes not affected by __getattr__? | I'm fairly new to Python. In programming a lot of PHP recently I got used to some creative use of __get and __set "magic" methods. These were only called when a public variable of the class wasn't present.
I'm trying to replicate the same behavior in Python, but seem to be failing miserably. Given there doesn't seem... | [
"__getattr__ is only invoked when Python cannot find the attribute in the instance itself or in any of its base classes. The simple solution is to add Document and Filename to the class so it is found.\nclass ApplicationSettings(object):\n Document = None\n Filename = None\n RootXml = '<?xml version=\"1.0... | [
1,
0,
0,
0
] | [] | [] | [
"getattr",
"ironpython",
"python",
"xml"
] | stackoverflow_0007115531_getattr_ironpython_python_xml.txt |
Q:
Deadlock in Python Threads
I am trying to implement a simpley portscanner with Python. It works by creating a number of worker threads which scan ports that are provided in a queue. They save the results in another queue. When all ports are scanned the threads and the application should terminate. And here lies th... | Deadlock in Python Threads | I am trying to implement a simpley portscanner with Python. It works by creating a number of worker threads which scan ports that are provided in a queue. They save the results in another queue. When all ports are scanned the threads and the application should terminate. And here lies the problem: For small numbers of ... | [
"I don't see anything obviously wrong with your code, but as it stands the break will never be hit - self.to_scan.get() will wait forever rather than raising Queue.Empty. Given that you're loading up the queue with ports to scan before starting the threads, you can change that to self.to_scan.get(False) to have the... | [
3,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0008275573_multithreading_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.