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:
KindError on setting a ReferenceProperty value
This seemingly perfect Google App Engine code fails with a KindError.
# in a django project 'stars'
from google.appengine.ext import db
class User(db.Model):
pass
class Picture(db.Model):
user = db.ReferenceProperty(User)
user = User()
user.put()
picture =... | KindError on setting a ReferenceProperty value | This seemingly perfect Google App Engine code fails with a KindError.
# in a django project 'stars'
from google.appengine.ext import db
class User(db.Model):
pass
class Picture(db.Model):
user = db.ReferenceProperty(User)
user = User()
user.put()
picture = Picture()
picture.user = user
# ===> KindError: Pro... | [
"Turns out that I was importing the model in admin.py as\nfrom frontend.stars.models import Star\n\nThis line had contaminated the module namespace of Star and the isinstance query was failing.\n>>> user.__class__\n<class 'frontend.stars.models.User'>\n>>> Picture.user.reference_class\n<class 'stars.models.User'>\n... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001460105_google_app_engine_python.txt |
Q:
Modify address in Django middleware
I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?
ie.
user clicks: .../some_link
and middleware rewrites it to: .../some_link?par1=1&par2=2
Other way is to modify... | Modify address in Django middleware | I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?
ie.
user clicks: .../some_link
and middleware rewrites it to: .../some_link?par1=1&par2=2
Other way is to modify reponse and replace every HTML link but ... | [
"class YourRedirectMiddleware:\n\n def process_request(self, request):\n redirect_url = request.path+'?par1=1&par2=2'\n return HttpResponsePermanentRedirect(redirect_url)\n\nwhat are you trying to accomplish and why this way?\n",
"I think this really depends on your problem and what exactly you a... | [
4,
1,
0
] | [] | [] | [
"django",
"django_middleware",
"django_urls",
"python"
] | stackoverflow_0001458829_django_django_middleware_django_urls_python.txt |
Q:
Why does Python keep a reference count on False and True?
I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest:
Py_INCREF(Py_False);
return Py_False;
...
Py_INCREF(Py_True);
return Py_True;
Aren't Py_False and Py_True global values? Just out of... | Why does Python keep a reference count on False and True? | I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest:
Py_INCREF(Py_False);
return Py_False;
...
Py_INCREF(Py_True);
return Py_True;
Aren't Py_False and Py_True global values? Just out of sheer curiosity, why is Python keeping a reference count for t... | [
"It's to make all object handling uniform. If I'm writing C code that handles a return value from a function, I have to increment and decrement the reference count on that object. If the function returns me True, I don't want to have to check to see if it's one of those special objects to know whether to manipula... | [
23
] | [] | [] | [
"python",
"python_c_api",
"reference_counting"
] | stackoverflow_0001460454_python_python_c_api_reference_counting.txt |
Q:
How can I get the element of a list that has a minimum/maximum property in Python?
I have the following array in Python:
points_list = [point0, point1, point2]
where each of points_list is of the type:
class point:
__init__(self, coord, value):
self.coord = numpy.array(coord)
self.value = valu... | How can I get the element of a list that has a minimum/maximum property in Python? | I have the following array in Python:
points_list = [point0, point1, point2]
where each of points_list is of the type:
class point:
__init__(self, coord, value):
self.coord = numpy.array(coord)
self.value = value
# etc...
And a function:
def distance(x,y):
return numpy.linalg.norm(x.coord - y.... | [
"Have you tried this?\nmin(points_list, key=lambda x: distance(x, point_a))\n\nTo answer a question in comment: lambda is indeed necessary here since function specified as a key argument needs to accept only a single argument.\nHowever, since your point_a is essentially global you could \"hard-code\" it into the di... | [
13
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001460512_list_python.txt |
Q:
Verbose list comprehension in Python
I have a list of integers and I want to create a new list with all elements smaller than a given limit.
a=range(15) #example list
limit=9 #example limit
My approach to solve this problem was
[i for i in a if i < limit]
To me the beginning 'i for i in' looks pretty verbose. Is... | Verbose list comprehension in Python | I have a list of integers and I want to create a new list with all elements smaller than a given limit.
a=range(15) #example list
limit=9 #example limit
My approach to solve this problem was
[i for i in a if i < limit]
To me the beginning 'i for i in' looks pretty verbose. Is there a better implementation in Python?
| [
"You could use filter\n>>> filter(lambda i: i < limit, a)\n[0, 1, 2, 3, 4, 5, 6, 7, 8]\n\nBut list comprehensions are the preferred way to do it\nHere is what python docs has to say about this:\n\nList comprehensions provide a concise\n way to create lists without resorting\n to use of map(), filter() and/or\n l... | [
4,
2,
1,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0001460484_list_comprehension_python.txt |
Q:
Install MySQLdb (for python) as non-compressed egg
The install instructions are:
$ python setup.py build
$ sudo python setup.py install # or su first
This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?
Thanks!
A:
OK, I hate to answer my own question, but:
f... | Install MySQLdb (for python) as non-compressed egg | The install instructions are:
$ python setup.py build
$ sudo python setup.py install # or su first
This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?
Thanks!
| [
"OK, I hate to answer my own question, but:\nfind your python site-packages (mine is /usr/local/lib/python2.5/site-packages )\nthen:\n$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg\n\nThis worked fine for me\n",
"I'm a little late to this party, but here's a way to do it that seems to work great:\nsudo python se... | [
7,
4,
3,
1
] | [] | [] | [
"egg",
"installation",
"mysql",
"python"
] | stackoverflow_0000268025_egg_installation_mysql_python.txt |
Q:
Related to executing Java programs through Python
I am using os.system to execute a java program through a python script.
I need to pass a file name to the java program as an argument.
I am not able to figure out how to pass the relative file location. What should be my reference for determining the relative locat... | Related to executing Java programs through Python | I am using os.system to execute a java program through a python script.
I need to pass a file name to the java program as an argument.
I am not able to figure out how to pass the relative file location. What should be my reference for determining the relative location. I tried to use the location of the python script a... | [
"See the subprocess module for all your external process invoking needs.\np = subprocess.Popen(['myjavaapp', 'afilename.txt'])\n\nIf you need to get the relative location and you aren't sure how the other command is going to take it, make it absolute.\np = subprocess.Popen(['myjavaapp', os.path.abspath('afilename.t... | [
2
] | [] | [] | [
"java",
"python"
] | stackoverflow_0001460590_java_python.txt |
Q:
How to decompile a regex?
Is there any way to decompile a regular expression once compiled?
A:
Compiled regular expression objects have a "pattern" attribute which gives the original text pattern.
>>> import re
>>> regex = re.compile('foo (?:bar)*')
>>> regex.pattern
'foo (?:bar)*'
A:
r = re.compile('some[patt... | How to decompile a regex? | Is there any way to decompile a regular expression once compiled?
| [
"Compiled regular expression objects have a \"pattern\" attribute which gives the original text pattern.\n>>> import re\n>>> regex = re.compile('foo (?:bar)*')\n>>> regex.pattern\n'foo (?:bar)*'\n\n",
"r = re.compile('some[pattern]');\nprint r.pattern\n\n"
] | [
40,
8
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001460686_python_regex.txt |
Q:
Jinja2 If Statement
The code below is a sample form I'm using to learn jinja2. As written, it returns an error saying that it doesn't recognize the {% endif %} tag. Why does this happen?
<html>
Name: {{ name }}
Print {{ num }} times
Color: {{ color }}
{% if convert_to_upper %}Case: Upper
{% elif not convert_to_... | Jinja2 If Statement | The code below is a sample form I'm using to learn jinja2. As written, it returns an error saying that it doesn't recognize the {% endif %} tag. Why does this happen?
<html>
Name: {{ name }}
Print {{ num }} times
Color: {{ color }}
{% if convert_to_upper %}Case: Upper
{% elif not convert_to_upper %}Case: Lower{% end... | [
"I think you have your lines mixed up. Your endif comese before endfilter whereas if is before filter. That's just a syntax error.\n"
] | [
12
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0001461484_jinja2_python.txt |
Q:
epylint script is not working on Windows
I have installed http://ftp.logilab.org/pub/pylint/pylint-0.18.1.tar.gz on Windows and now I am trying to configure my Emacs's flymake mode using epylint script.
Here is the output of I got when I tried epylint on windows command prompt.
C:\>epylint test.py
'test.py':1: [F... | epylint script is not working on Windows | I have installed http://ftp.logilab.org/pub/pylint/pylint-0.18.1.tar.gz on Windows and now I am trying to configure my Emacs's flymake mode using epylint script.
Here is the output of I got when I tried epylint on windows command prompt.
C:\>epylint test.py
'test.py':1: [F] No module named 'test.py'
Any suggestions o... | [
"Reading the documentation of the epylint.lint function:\n\nWhen run from emacs we will be in the directory of a file, and passed its filename.\nIf this file is part of a package and is trying to import other modules from within\nits own package or another package rooted in a directory below it, pylint will classif... | [
0
] | [] | [] | [
"emacs",
"pylint",
"python",
"windows"
] | stackoverflow_0001460275_emacs_pylint_python_windows.txt |
Q:
do you know of any python component(s) for syntax highlighting?
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
A:
Other than pygments? http://pyg... | do you know of any python component(s) for syntax highlighting? | Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
| [
"Other than pygments? http://pygments.org/\n",
"If you're using gtk+, there's a binding of gtksourceview for Python in gnome-python-extras. It seems to work well in my experience. The downside: the documentation is less than perfect.\nThere's also a binding of QScintilla for Python if PyQt is your thing.\n",
... | [
9,
1,
1,
0
] | [] | [] | [
"components",
"python",
"syntax_highlighting"
] | stackoverflow_0000620954_components_python_syntax_highlighting.txt |
Q:
How much data could be stored into a Google App Engine, application?
Answering this question and searching for references I have this doubt my self:
*How much data could be stored into a Google App Engine, application?
If I'm reading well this table:
Resources | Free daily | Free Max Rate | Daily Billing en... | How much data could be stored into a Google App Engine, application? | Answering this question and searching for references I have this doubt my self:
*How much data could be stored into a Google App Engine, application?
If I'm reading well this table:
Resources | Free daily | Free Max Rate | Daily Billing enable | Max Rate Billing
----------------------------------------... | [
"I read that to mean 1 GB stored during the course of a day, not added in a day, so in other words you can have up to 1 GB of storage for free. If you store more, calculated daily, you have to pay for that additional storage. There is no maximum on how much you can store, you just get billed for it.\n"
] | [
6
] | [] | [] | [
"cloud",
"google_app_engine",
"java",
"python"
] | stackoverflow_0001462160_cloud_google_app_engine_java_python.txt |
Q:
Django forms: how to display media (javascript) for a DateTimeInput widget?
Hello (please excuse me for my bad english ;) ),
Imagine the classes bellow:
models.py
from django import models
class MyModel(models.Model):
content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
object_id ... | Django forms: how to display media (javascript) for a DateTimeInput widget? | Hello (please excuse me for my bad english ;) ),
Imagine the classes bellow:
models.py
from django import models
class MyModel(models.Model):
content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
object_id = models.PositiveIntegerField(_('object id'))
content_object = generic.Generi... | [
"The standard DateTimeWidget doesn't include any javascript. The widget used in the admin is a different one - django.contrib.admin.widgets.AdminSplitDateTime - and this includes the javascript.\n"
] | [
5
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"django_models",
"python"
] | stackoverflow_0001462003_django_django_admin_django_forms_django_models_python.txt |
Q:
Command line options with optional arguments in Python
I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:
> script.py --foo
> script.py --foo=bar
From the Python getopt docs it seems I have to choo... | Command line options with optional arguments in Python | I was wondering if there's a simple way to parse command line options having optional arguments in Python. For example, I'd like to be able to call a script two ways:
> script.py --foo
> script.py --foo=bar
From the Python getopt docs it seems I have to choose one or the other.
| [
"Also, note that the standard library also has optparse, a more powerful options parser.\n",
"check out argparse:\nhttp://code.google.com/p/argparse/\nespecially the 'nargs' option\n",
"optparse module from stdlib doesn't support it out of the box (and it shouldn't due to it is a bad practice to use command-lin... | [
3,
3,
3,
2,
1
] | [] | [] | [
"getopt",
"python"
] | stackoverflow_0001461942_getopt_python.txt |
Q:
How do I switch this Proxy to use Proxy-Authentication?
I'm trying to modify my simple Twisted web proxy to use "Proxy-Authentication" (username/password) instead of the current IP based authentication. Problem is, I'm new to Twisted and don't even know where to start.
Here is my Factory Class.
class ProxyFacto... | How do I switch this Proxy to use Proxy-Authentication? | I'm trying to modify my simple Twisted web proxy to use "Proxy-Authentication" (username/password) instead of the current IP based authentication. Problem is, I'm new to Twisted and don't even know where to start.
Here is my Factory Class.
class ProxyFactory(http.HTTPFactory):
def __init__(self, ip, internal_ips... | [
"A similar question came up on the Twisted mailing list a while ago:\nhttp://www.mail-archive.com/twisted-python@twistedmatrix.com/msg01080.html\nAs I mentioned there, you probably need to subclass some of the twisted.proxy classes so that they understand the Proxy-Authenticate and Proxy-Authorization headers.\n"
] | [
1
] | [] | [] | [
"authentication",
"proxy",
"python",
"twisted"
] | stackoverflow_0001336882_authentication_proxy_python_twisted.txt |
Q:
Automatic String to Number conversion in Python
I am trying to compare two lists of string in python. Some of the strings are numbers however I don't want to use it as number, only for string comparison.
I read the string from a file and put them on a list like this:
def main():
inputFileName = 'BateCarteira.c... | Automatic String to Number conversion in Python | I am trying to compare two lists of string in python. Some of the strings are numbers however I don't want to use it as number, only for string comparison.
I read the string from a file and put them on a list like this:
def main():
inputFileName = 'BateCarteira.csv'
inputFile = open(inputFileName, "r")
ban... | [
"Python never transforms a string to a number, unless you try something like:\ns = \"1.2\"\na = float(s)\n\nSo I guess that your .csv file has the string \"1,20091E+11\" inside it. Also notice that the decimal point is a coma. So, if you tried to convert it to a float, the transformation would fail.\n",
"You need... | [
3,
2
] | [] | [] | [
"casting",
"python"
] | stackoverflow_0001462427_casting_python.txt |
Q:
Django generates 'WHERE ... BETWEEN ...' sentences?
Actually, somewhere in the view:
dif = datetime.timedelta(days=1)
today = datetime.date.today()
yesterday = today - dif
ex = Fact.objects.filter(fecha_fact__lte=today ,fecha_fact__gte=yesterday )
It results to this SQL Query:
SELECT `facts_fact`.`id` ...
FROM `f... | Django generates 'WHERE ... BETWEEN ...' sentences? | Actually, somewhere in the view:
dif = datetime.timedelta(days=1)
today = datetime.date.today()
yesterday = today - dif
ex = Fact.objects.filter(fecha_fact__lte=today ,fecha_fact__gte=yesterday )
It results to this SQL Query:
SELECT `facts_fact`.`id` ...
FROM `facts_fact`
WHERE (`facts_fact`.`fecha_fact` >= 2009-09-2... | [
"Have you tried range?\nFact.objects.filter(fecha_fact__range=(yesterday, today))\n\n",
"i dont know, but maybe (gte / lte ):\nq1 = Entry.objects.filter(headline__startswith=\"What\")\nq2 = q1.exclude(pub_date__gte=datetime.now())\nq3 = q1.filter(pub_date__gte=datetime.now())\n\n\nq = Entry.objects.filter(headlin... | [
4,
0
] | [] | [] | [
"django",
"django_models",
"python",
"sql"
] | stackoverflow_0001462968_django_django_models_python_sql.txt |
Q:
How to improve performance of python cgi that reads a big file and returns it as a download?
I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download.
It works,but performance s... | How to improve performance of python cgi that reads a big file and returns it as a download? | I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download.
It works,but performance sucks. The bottleneck seems to be reading this huge file over and over:
def download_demo():
""... | [
"Use mod_wsgi and use something akin to:\ndef application(environ, start_response):\n status = '200 OK'\n output = 'Hello World!'\n\n response_headers = [('Content-type', 'text/plain')]\n start_response(status, response_headers)\n\n file = open('/usr/share/dict/words', 'rb')\n return environ['wsgi... | [
9,
2,
1,
1
] | [] | [] | [
"cgi",
"mod_wsgi",
"performance",
"python"
] | stackoverflow_0001462330_cgi_mod_wsgi_performance_python.txt |
Q:
django - using a common header with some dynamic elements
I'm planning to create a website using django that will have a common header throughout the entire website. I've read django's documentation on templating inheritance, but I can't seem to find an elegant solution for the "dynamic" elements in my header.
Fo... | django - using a common header with some dynamic elements | I'm planning to create a website using django that will have a common header throughout the entire website. I've read django's documentation on templating inheritance, but I can't seem to find an elegant solution for the "dynamic" elements in my header.
For example, the header in the website will include tabs, say sim... | [
"I'm assuming each tab is a list item in your template base.html.\n<ul>\n <li>Tab 1</li>\n <li>Tab 2</li>\n ...\n</ul>\n\nAdd an extra block to each li.\n<ul>\n <li class=\"{% block class_tab1 %}inactive{% endblock %}\">Tab 1</li>\n <li class=\"{% block class_tab2 %}inactive{% endblock %}\">Tab 2</li... | [
9,
1,
1
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0001463153_django_javascript_python.txt |
Q:
python system calls
with this command, I get only the file called OUTPUT (in reality I have many more --include flags) - so works as expected:
os.system("rsync --rsh=ssh -arvuP --include='OUTPUT' --exclude='*' user@host:there/ ./here")
In this case, the --include and --exclude flags are ignored:
subprocess.call("... | python system calls | with this command, I get only the file called OUTPUT (in reality I have many more --include flags) - so works as expected:
os.system("rsync --rsh=ssh -arvuP --include='OUTPUT' --exclude='*' user@host:there/ ./here")
In this case, the --include and --exclude flags are ignored:
subprocess.call("rsync --rsh=ssh -arvuP --... | [
"Try using subprocess.call with shell=True, it will simulate os.system more closely:\nsubprocess.call(\"...\", shell=True)\n\n",
"Python does have an rsync module if I am not wrong, why not use that instead of a call. It will make your app more manageable.\n"
] | [
3,
1
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0001462878_python_shell.txt |
Q:
How to create user defined fields in Django
Ok, I am working on a Django application with several different models, namely Accounts, Contacts, etc, each with a different set of fields. I need to be able to allow each of my users to define their own fields in addition to the existing fields. I have seen several d... | How to create user defined fields in Django | Ok, I am working on a Django application with several different models, namely Accounts, Contacts, etc, each with a different set of fields. I need to be able to allow each of my users to define their own fields in addition to the existing fields. I have seen several different ways to implement this, from having a la... | [
"What if you were to use a ForeignKey?\nThis code (untested and for demo) is assuming there is a system-wide set of custom fields. To make it user-specific, you'd add a \"user = models.ForiegnKey(User)\" onto the class CustomField.\nclass Account(models.Model):\n name = models.CharField(max_length=75)\n\n # ... | [
4
] | [] | [] | [
"configuration",
"django",
"modeling",
"python"
] | stackoverflow_0001463242_configuration_django_modeling_python.txt |
Q:
How can this python function code work?
this is from the source code of csv2rec in matplotlib
how can this function work, if its only parameters are 'func, default'?
def with_default_value(func, default):
def newfunc(name, val):
if ismissing(name, val):
return default
else:
... | How can this python function code work? | this is from the source code of csv2rec in matplotlib
how can this function work, if its only parameters are 'func, default'?
def with_default_value(func, default):
def newfunc(name, val):
if ismissing(name, val):
return default
else:
return func(val)
return newfunc
ismi... | [
"This with_default_value function is what's often referred to (imprecisely) as \"a closure\" (technically, the closure is rather the inner function that gets returned, here newfunc -- see e.g. here). More generically, with_default_value is a higher-order function (\"HOF\"): it takes a function (func) as an argument... | [
8,
6,
1,
0
] | [] | [] | [
"function",
"matplotlib",
"python"
] | stackoverflow_0001463588_function_matplotlib_python.txt |
Q:
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
(Title and contents updated after reading Alex's answer)
In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameter... | Is it Pythonic for a function to return an iterable or non-iterable depending on its input? | (Title and contents updated after reading Alex's answer)
In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters.
For example struct.unpack always returns a tuple even if it contains only one item.
I'm trying... | [
"If you are going to be returning iterators sometimes, and single objects on others, I'd say return always an iterator, so you don't have to think about it. \nGeneraly, you would use that function in a context that expects an iterator, so if you'd have to check if it where a list to iterate or an object to do just ... | [
12,
3,
2,
1,
1,
1
] | [
"In python lists are objects :) So no type mismatch\n"
] | [
-1
] | [
"python",
"return_value"
] | stackoverflow_0001461392_python_return_value.txt |
Q:
Google app engine and python and objects that pass by value
This is really a python language question, but its wrapped around a Google appengine specific problem.
We have
class User( db.Model ) :
email = db.StringProperty()
name = db.StringProperty()
password = db.StringProperty()
# more fields..
Because... | Google app engine and python and objects that pass by value | This is really a python language question, but its wrapped around a Google appengine specific problem.
We have
class User( db.Model ) :
email = db.StringProperty()
name = db.StringProperty()
password = db.StringProperty()
# more fields..
Because the user account is accessed so often, we keep a copy in sessio... | [
"I'm guessing: \nPutting objects in the Session means that the objects is serialized ( pickled usually ) and stored somewhere (disk, memory, db). When it is retrieved from the Session, a new object is created from serialized the old state.\n\nIn the first example each self.session[ 'current_user' ] gives you a new ... | [
3,
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001449257_google_app_engine_python.txt |
Q:
How do I get this program to start over in python?
I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?
from random import randint
print 'Go... | How do I get this program to start over in python? | I believe the word is "recurse" instead of 'start over.' I've created this program to hone my multiplication skills in the morning. I can get it to give me a multiplication problem, but how do I get it to ask me another one?
from random import randint
print 'Good Morning Pete!'
X = randint(0, 10)
Y = randint(0, 10... | [
"Pete, you wouldn't need recursion in this case, but merely a loop.\nI suggest you put the bulk of the logic of this program (the part that asks the multiplcation problem and check your answer), into a function. Say One Problem(). This function could return 0 if you answered wrong, 1 if you answered correctly a... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0001463710_python_recursion.txt |
Q:
What is the accepted python alternative to C++ overloaded input stream operators?
In C++, you can do this to easily read data into a class:
istream& operator >> (istream& instream, SomeClass& someclass) {
...
}
In python, the only way I can find to read from the console is the "raw_input" function, which isn'... | What is the accepted python alternative to C++ overloaded input stream operators? | In C++, you can do this to easily read data into a class:
istream& operator >> (istream& instream, SomeClass& someclass) {
...
}
In python, the only way I can find to read from the console is the "raw_input" function, which isn't very adaptable to this sort of thing. Is there a pythonic way to go about this?
| [
"You are essentially looking for deserialization. Python has a myriad of options for this depending on the library used. The default is python pickling. There are lots of other options you can have a look here.\n",
"No, there's no widespread Pythonic convention for \"read the next instance of class X from this op... | [
6,
3,
2
] | [] | [] | [
"input",
"operator_overloading",
"python"
] | stackoverflow_0001463499_input_operator_overloading_python.txt |
Q:
Calculate brute force size dynamically?
How you could calculate size of brute force method dynamically? For example how many iterations and space would take if you printed all IPv6 addresses from 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff to file? The tricky parts are those when length of line varie... | Calculate brute force size dynamically? | How you could calculate size of brute force method dynamically? For example how many iterations and space would take if you printed all IPv6 addresses from 0:0:0:0:0:0:0:0 - ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff to file? The tricky parts are those when length of line varies. IP address is only example.
Idea is that ... | [
"Using combinatorics and discrete math:\nThe IPv4 address space is 256*256*256*256 = 2^32 = 4,294,967,296 addresses.\nIPv6 has 2^128 addresses (8 groups of 16*16*16*16).\nAn IPv4 address use 32 bits, so 32 bits * 4,294,967,296 addresses = 16 gigabytes if stored e.g. on disk.\nAn IPv6 address uses 128 bits, so 128 b... | [
4,
0,
0
] | [] | [] | [
"brute_force",
"math",
"python"
] | stackoverflow_0001463832_brute_force_math_python.txt |
Q:
Json encoder python recursive reference
I don't know whether I am doing the right thing here, basically I want both of my class to be json-serializable.
import json
class gpagelet(json.JSONEncoder):
"""
Holds 1) the pagelet xpath, which is a string
2) the list of pagelet shingles, list
"... | Json encoder python recursive reference | I don't know whether I am doing the right thing here, basically I want both of my class to be json-serializable.
import json
class gpagelet(json.JSONEncoder):
"""
Holds 1) the pagelet xpath, which is a string
2) the list of pagelet shingles, list
"""
def __init__(self, parent):
if... | [] | [] | [
"FYI \nI am seeing a lot of trouble with this:\nu['gpagelets'] = [ gpageletEncoder.default( each) for each in gw.gpagelets ]\n"
] | [
-1
] | [
"json",
"python"
] | stackoverflow_0001458671_json_python.txt |
Q:
What is the pythonic way of checking if an object is a list?
I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]
Edit:
I seem to have started a war of word... | What is the pythonic way of checking if an object is a list? | I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0]
Edit:
I seem to have started a war of words down below by not giving enough info. For completeness let me pr... | [
"In such situations, you normally need to check for ANY iterable, not just lists -- if you're accepting lists OR numbers, rejecting (e.g) a tuple would be weird. The one kind of iterable you might want to treat as a \"scalar\" is a string -- in Python 2.*, this means str or unicode. So, either:\ndef isNonStringIter... | [
21,
13,
11,
2,
1,
0
] | [
"Just use the type method? Or am I misinterpreting the question\nif type(objectname) is list:\n do something\nelse:\n do something else :P\n\n"
] | [
-3
] | [
"list",
"python"
] | stackoverflow_0001464028_list_python.txt |
Q:
wxpython drag&drop focus problem
I'd like to implement drag&drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:
when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus a... | wxpython drag&drop focus problem | I'd like to implement drag&drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:
when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus and is on top.
When I implement drag&dr... | [
"Wouldn't this work?\nclass DropFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n text = wx.TextCtrl(self, wx.ID_ANY)\n self.SetFocus() # Set's the focus to this window, allowing it to receive keyboard input.\n text.SetDropTarget(TextDropTarget(text))\n\nwx.Fram... | [
1,
1
] | [] | [] | [
"drag_and_drop",
"focus",
"python",
"wxpython"
] | stackoverflow_0001460722_drag_and_drop_focus_python_wxpython.txt |
Q:
Django: how to including inline model fields in the list_display?
I'm attempting to extend django's contrib.auth User model, using an inline 'Profile' model to include extra fields.
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
class P... | Django: how to including inline model fields in the list_display? | I'm attempting to extend django's contrib.auth User model, using an inline 'Profile' model to include extra fields.
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
class Profile(models.Model):
user = models.ForeignKey(User, unique=True, re... | [
"You've mentioned the only solution - creating a callable. There's currently no other way to do it, and yes this does mean you can't sort by that column. \n"
] | [
7
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0001463398_django_django_admin_django_models_python.txt |
Q:
vim syntax highlighting for jinja2?
How do you do jinja2 aware syntax highlighting for vim?
A:
There appears to be a syntax highlighting file here.
| vim syntax highlighting for jinja2? | How do you do jinja2 aware syntax highlighting for vim?
| [
"There appears to be a syntax highlighting file here.\n"
] | [
16
] | [] | [] | [
"jinja2",
"python",
"vim",
"vim_syntax_highlighting"
] | stackoverflow_0001465240_jinja2_python_vim_vim_syntax_highlighting.txt |
Q:
Trouble with positive look behind assertion in python regex
Trying to use a reasonably long regex and it comes down to this small section that doesn't match how I'd expect it to.
>>> re.search(r'(foo)((?<==)bar)?', 'foo').groups()
('foo', None)
>>> re.search(r'(foo)((?<==)bar)?', 'foo=bar').groups()
('foo', None)... | Trouble with positive look behind assertion in python regex | Trying to use a reasonably long regex and it comes down to this small section that doesn't match how I'd expect it to.
>>> re.search(r'(foo)((?<==)bar)?', 'foo').groups()
('foo', None)
>>> re.search(r'(foo)((?<==)bar)?', 'foo=bar').groups()
('foo', None)
The first one is what I'm after, the second should be returning... | [
"The look behind target is never included in the match - it's supposed to serve as an anchor, but not actually be consumed by the regex.\nThe look behind pattern is only supposed to match if the current position is preceded by the target. In your case, after matching the \"foo\" in the string, the current position ... | [
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001465246_python_regex.txt |
Q:
mod_python interpreter's cache not getting reset on script change?
I use mod_python.publisher to run Python code and discovered a problem: When I update a script the update doesn't always work right away and I get the same error I fixed with the update until I restart Apache.
Sometimes it works right away, but som... | mod_python interpreter's cache not getting reset on script change? | I use mod_python.publisher to run Python code and discovered a problem: When I update a script the update doesn't always work right away and I get the same error I fixed with the update until I restart Apache.
Sometimes it works right away, but sometimes not...but restarting Apache definitely always catches it up. It's... | [
"This is the expected behavior of mod_python. Your code is loaded into memory and won't be refreshed until the server is restarted.\nYou have two options:\n\nSet MaxRequestsPerChild 1 in your httpd.conf file to force Apache to reload everything for each request.\nSet PythonAutoReload to be On\nhttp://www.modpython.... | [
3
] | [] | [] | [
"mod_python",
"python"
] | stackoverflow_0001465364_mod_python_python.txt |
Q:
What is involved in adding to the standard Python API?
What steps would be necessary, and what kind of maintenance would be expected if I wanted to contribute a module to the Python standard API? For example I have a module that encapsulates automated update functionality similar to Java's JNLP.
A:
Please look ... | What is involved in adding to the standard Python API? | What steps would be necessary, and what kind of maintenance would be expected if I wanted to contribute a module to the Python standard API? For example I have a module that encapsulates automated update functionality similar to Java's JNLP.
| [
"Please look at Python PEP 2 for details. You'll surely find more necessary information at the PEP Index, such as PEP 1: PEP Purpose and Guidelines.\nHave a look through the PEP index for previous PEPs which may have been rejected in the past.\nOf course you should also consult the python-dev mailing list.\n",
"F... | [
9,
2
] | [] | [] | [
"api",
"python"
] | stackoverflow_0001465302_api_python.txt |
Q:
Limiting results returned fromquery in django, python
I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:
newUsers = User.objects.filter(is_active=True).order_by("-date_joined")
This as I understand it gives me A... | Limiting results returned fromquery in django, python | I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:
newUsers = User.objects.filter(is_active=True).order_by("-date_joined")
This as I understand it gives me ALL the users, sorted by date joined. How would I best limit... | [
"User.objects.filter(is_active=True).order_by(\"-date_joined\")[:10]\n\nwill give you the last 10 users who joined. See the Django docs for details.\n",
"Use list slice operation on constructed queries e.g.\nFor example, this returns the first 5 objects (LIMIT 5):\nEntry.objects.all()[:5]\n\nThis returns the sixt... | [
8,
4,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001465734_django_python.txt |
Q:
Custom QStyledItemDelegate: adding bold items
So here's the story:
I have a QListview that uses a QSqlQueryModel to fill it up. Because some items should display in bold based on the value of a hidden column of the model, I decided to make my own custom delegate. I'm using PyQT 4.5.4 and thus inheriting from QStyl... | Custom QStyledItemDelegate: adding bold items | So here's the story:
I have a QListview that uses a QSqlQueryModel to fill it up. Because some items should display in bold based on the value of a hidden column of the model, I decided to make my own custom delegate. I'm using PyQT 4.5.4 and thus inheriting from QStyledItemDelegate is the way to go according to the do... | [
"I've not tested this, but I think you can do:\nclass TypeSoortDelegate(QStyledItemDelegate):\n\ndef paint(self, painter, option, index):\n get value...\n if value:\n option.font.setWeight(QFont.Bold)\n\n QStyledItemDelegate.paint(self, painter, option, index)\n\n"
] | [
3
] | [] | [] | [
"pyqt",
"python",
"user_interface"
] | stackoverflow_0001412156_pyqt_python_user_interface.txt |
Q:
Problem when getting the content of a listbox with python and ctypes on win32
I would like to get the content of a list box thanks to python and ctypes.
item_count = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETCOUNT, 0, 0)
items = []
for i in xrange(item_count):
text_len = ctypes.windll.user32.Send... | Problem when getting the content of a listbox with python and ctypes on win32 | I would like to get the content of a list box thanks to python and ctypes.
item_count = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETCOUNT, 0, 0)
items = []
for i in xrange(item_count):
text_len = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXTLEN, i, 0)
buffer = ctypes.create_string_buff... | [
"If the list box in question is owner-drawn, this passage from the LB_GETTEXT documentation may be relevant:\n\nIf you create the list box with an owner-drawn style but without the LBS_HASSTRINGS style, the buffer pointed to by the lParam parameter will receive the value associated with the item (the item data).\n\... | [
1,
0
] | [] | [] | [
"ctypes",
"python",
"winapi"
] | stackoverflow_0001466453_ctypes_python_winapi.txt |
Q:
Testing for cookie existence in Django
Simple stuff here...
if I try to reference a cookie in Django via
request.COOKIE["key"]
if the cookie doesn't exist that will throw a key error.
For Django's GET and POST, since they are QueryDict objects, I can just do
if "foo" in request.GET
which is wonderfully sophistic... | Testing for cookie existence in Django | Simple stuff here...
if I try to reference a cookie in Django via
request.COOKIE["key"]
if the cookie doesn't exist that will throw a key error.
For Django's GET and POST, since they are QueryDict objects, I can just do
if "foo" in request.GET
which is wonderfully sophisticated...
what's the closest thing to this for... | [
"request.COOKIES is a standard Python dictionary, so the same syntax works.\nAnother way of doing it is:\nrequest.COOKIES.get('key', 'default')\n\nwhich returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.\n",
"First, it's \nrequest.COOKIES\n\nnot request... | [
22,
6
] | [] | [] | [
"cookies",
"django",
"http",
"python"
] | stackoverflow_0001466732_cookies_django_http_python.txt |
Q:
Retrieving the latitude/longitude from Google Map Mobile 3.0's MyLocation feature
I want to fetch my current latitude/longitude from Google Maps Mobile 3.0 with the help of some script, which I guess could be a Python one. Is this possible? And, more importantly: is the Google Maps Mobile API designed for such int... | Retrieving the latitude/longitude from Google Map Mobile 3.0's MyLocation feature | I want to fetch my current latitude/longitude from Google Maps Mobile 3.0 with the help of some script, which I guess could be a Python one. Is this possible? And, more importantly: is the Google Maps Mobile API designed for such interaction? Any legal issues?
Basically i have a S60 phone that doesnt have GPS,and I hav... | [
"No, you can't access it from a Python script or another S60 application because of platform security features of S60 3rd ed. Even if Google Maps application would write information to disk, your app is not able to access application specific files of other apps. \nGoogle Maps use cell-based locationing in addition... | [
1,
1,
0
] | [] | [] | [
"google_maps",
"pys60",
"python",
"s60"
] | stackoverflow_0000623504_google_maps_pys60_python_s60.txt |
Q:
how to rewrite this loop in a more efficient way in python
I have a loop of the following type:
a = range(10)
b = [something]
for i in range(len(a)-1):
b.append(someFunction(b[-1], a[i], a[i+1]))
However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 element... | how to rewrite this loop in a more efficient way in python | I have a loop of the following type:
a = range(10)
b = [something]
for i in range(len(a)-1):
b.append(someFunction(b[-1], a[i], a[i+1]))
However the for-loop is killing a lot of performance. I have try to write a windows generator to give me 2 elements everything time but it still require explicit for-loop in the ... | [
"Consider this\ndef make_b( a, seed ):\n yield seed\n for a,b in zip( a[:-1], a[1:] ):\n seed= someFunction( seed, a, b )\n yield seed\n\nWhich lets you do this\na = xrange(10)\nb= list(make_b(a,something))\n\nNote that you can often use this: \nb = make_b(a)\n\nInstead of actually creating b a... | [
8,
4,
2,
0
] | [] | [] | [
"list",
"list_comprehension",
"python"
] | stackoverflow_0001466282_list_list_comprehension_python.txt |
Q:
Are python modules first class citizens?
I mean, can I create them dynamically?
A:
Yes:
>>> import types
>>> m = types.ModuleType("mymod")
>>> m
<module 'mymod' (built-in)>
A:
You can create them dynamically, with the imp.new_module method.
| Are python modules first class citizens? | I mean, can I create them dynamically?
| [
"Yes:\n>>> import types\n>>> m = types.ModuleType(\"mymod\")\n>>> m\n<module 'mymod' (built-in)>\n\n",
"You can create them dynamically, with the imp.new_module method.\n"
] | [
9,
5
] | [] | [] | [
"module",
"python"
] | stackoverflow_0001467612_module_python.txt |
Q:
django registration module
i started to learn django using the official documentation tutorial and in turn created this registration form.
i have the whole app setup but am stuck at how to process the data. i mean the documentation is a little tough to understand. if i can get some help, it would be great.
this i... | django registration module | i started to learn django using the official documentation tutorial and in turn created this registration form.
i have the whole app setup but am stuck at how to process the data. i mean the documentation is a little tough to understand. if i can get some help, it would be great.
this is how the models are setup:
clas... | [
"You don't seem to have read the documentation on forms. It explains in detail how to create a form from your model, how to output it in a template (so you don't need to write the HTML input elements manually), and how to process it in a view.\n",
"It took me a bit of time to figure out the form processing bit wh... | [
1,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0001467735_django_mysql_python.txt |
Q:
python: how to get all members of an array except for ones that match a condition
I'm trying to create an array of all .asm files I need to build except for one that is causing me trouble right now. Here's what I have, based on the Scons "Handling Common Cases" page:
projfiles['buildasm'] =
['#build/'+os.path.s... | python: how to get all members of an array except for ones that match a condition | I'm trying to create an array of all .asm files I need to build except for one that is causing me trouble right now. Here's what I have, based on the Scons "Handling Common Cases" page:
projfiles['buildasm'] =
['#build/'+os.path.splitext(x)[0]+'.asm' for x in projfiles['a']];
(this maps paths of the form 'foo.a' to... | [
"projfiles['buildasm'] = ['#build/'+os.path.splitext(x)[0]+'.asm' for x in projfiles['a'] if x != 'baz.a']\n\nor more generally:\nignored_files = ['baz.a',\n 'foo.a',\n 'xyzzy.a',\n ]\nprojfiles['buildasm'] = ['#build/'+os.path.splitext(x)[0]+'.asm' for x in projfiles... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0001467930_python.txt |
Q:
refer to map via. maps() action in python/ pylonshq
I just started to learn python, and i'm totally new and n00b. Normally i work with php.
I choose to use this framework: http://pylonshq.com/
I have created an map called ajax in my controller map.
now i just need my "htaccees" file to find the ajax map.
I want... | refer to map via. maps() action in python/ pylonshq | I just started to learn python, and i'm totally new and n00b. Normally i work with php.
I choose to use this framework: http://pylonshq.com/
I have created an map called ajax in my controller map.
now i just need my "htaccees" file to find the ajax map.
I want the file to go into the map /ajax/ where the file ajax_l... | [
"solution :\nhttp://pylonshq.com/docs/en/0.9.7/configuration/\nthis is how it works->\n$ paster controller ajax/ajax_load\n"
] | [
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0001455446_pylons_python.txt |
Q:
How does this work?
So I'm trying to comprehend the source file for csv2rec in matplotlib.mlab. It is used to take a csv file and parse the data into certain formats. So it may take a string '234' and convert it to int. or take a date string and make it into python datetimes.
def get_converters(reader):
... | How does this work? | So I'm trying to comprehend the source file for csv2rec in matplotlib.mlab. It is used to take a csv file and parse the data into certain formats. So it may take a string '234' and convert it to int. or take a date string and make it into python datetimes.
def get_converters(reader):
converters = None
for... | [
"Converters gets set again at the beginning of the loop with\nif i==0:\n converters = [mybool]*len(row)\n\nSo after that it's not None anymore.\n",
"Unless I'm missing something, on the first iteration \"i\" is 0, so the following is executed:\nconverters = [mybool]*len(row)\n\nand that initializes \"converters\... | [
2,
1,
1
] | [] | [] | [
"function",
"matplotlib",
"python"
] | stackoverflow_0001467902_function_matplotlib_python.txt |
Q:
How can I print only every third index in Perl or Python?
How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
A:
Perl:
As with draegtun's answer, but using a count var:
my $i;
my @new = grep {not ++$i % 3} @... | How can I print only every third index in Perl or Python? | How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
| [
"Perl:\nAs with draegtun's answer, but using a count var:\nmy $i;\nmy @new = grep {not ++$i % 3} @list;\n\n",
"Python\nprint list[::3] # print it\nnewlist = list[::3] # copy it\n\nPerl\nfor ($i = 0; $i < @list; $i += 3) {\n print $list[$i]; # print it\n push @y, $list[$i]; # copy it\n}\n\n",
"Perl 5.10 ne... | [
16,
12,
9,
9,
8,
5,
3,
1
] | [] | [] | [
"arrays",
"perl",
"python"
] | stackoverflow_0001464923_arrays_perl_python.txt |
Q:
How to contribute improvements to packages hosted on Cheeseshop ( pypi )?
I've been using zc.buildout more and more and I'm encountering problems with some recipes that I have solutions to.
These packages generally fall into several categories:
Package with no obvious links to a project site
Package with links t... | How to contribute improvements to packages hosted on Cheeseshop ( pypi )? | I've been using zc.buildout more and more and I'm encountering problems with some recipes that I have solutions to.
These packages generally fall into several categories:
Package with no obvious links to a project site
Package with links to free hosted service like github or google code
Setup #2 is better then #1, b... | [
"Your \"upload my personalized fork\" solution sounds like a terrible idea. You should try http://pypi.python.org/pypi/collective.recipe.patch which lets you automatically patch eggs. Try setting up a local PyPi-compatible index. I think you can also point find-links = at a directory (not just a http:// url) contai... | [
3
] | [] | [] | [
"buildout",
"collaboration",
"pypi",
"python"
] | stackoverflow_0001468476_buildout_collaboration_pypi_python.txt |
Q:
Twisted(asynch server) vs Django(or any other framework)
I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until some... | Twisted(asynch server) vs Django(or any other framework) | I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it ... | [
"First off Django is a framework for writing web apps so it provides ORM, html templating, it requires running an http server etc. Twisted helps to write much lower level code than that. You could use twisted to write the http server Django runs on. If you use Django you are limited to http model, with twisted i... | [
19,
16,
5,
3,
0,
0
] | [] | [] | [
"asynchronous",
"django",
"python",
"real_time",
"twisted"
] | stackoverflow_0001412169_asynchronous_django_python_real_time_twisted.txt |
Q:
Python CreateFile Cannot Find PhysicalMemory
I am trying to access the Physical Memory of a Windows 2000 system (trying to do this without a memory dumping tool). My understanding is that I need to do this using the CreateFile function to create a handle. I have used an older version of win32dd to help me throug... | Python CreateFile Cannot Find PhysicalMemory | I am trying to access the Physical Memory of a Windows 2000 system (trying to do this without a memory dumping tool). My understanding is that I need to do this using the CreateFile function to create a handle. I have used an older version of win32dd to help me through this. Other documentation on the web points me ... | [
"I don't believe it's possible to access the physical memory object from user mode land in Windows. As your win32dd link suggests, you will need to do it from kernel mode.\n"
] | [
0
] | [] | [] | [
"createfile",
"ctypes",
"memory",
"python"
] | stackoverflow_0001468130_createfile_ctypes_memory_python.txt |
Q:
Why can't I import the 'math' library when embedding python in c?
I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The example C-code does not allow me to execute the following 1 line script:
import math
Using line:
./tmp.exe tmp foo bar
it complains
Traceback (most r... | Why can't I import the 'math' library when embedding python in c? | I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The example C-code does not allow me to execute the following 1 line script:
import math
Using line:
./tmp.exe tmp foo bar
it complains
Traceback (most recent call last):
File "/home/rbroger1/scripts/tmp.py", line 1, in <m... | [
"I'm using Python 2.6, and I successfully compiled and ran that same example code that you listed, without changing anything in the source. \n\n$ gcc python.c -I/usr/include/python2.6/ /usr/lib/libpython2.6.so\n$ ./a.out random randint 1 100\nResult of call: 39\n$ ./a.out random randint 1 100\nResult of call: 57\n... | [
2
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0001469370_c_c++_python.txt |
Q:
Networkx node traversal
Using Python's Networkx library, I created an undirected graph to represent a relationship network between various people. A snippet of my code is below:
import networkx as nx
def creategraph(filepath):
G=nx.Graph()
#All the various nodes and edges are added in this stretch of code.... | Networkx node traversal | Using Python's Networkx library, I created an undirected graph to represent a relationship network between various people. A snippet of my code is below:
import networkx as nx
def creategraph(filepath):
G=nx.Graph()
#All the various nodes and edges are added in this stretch of code.
return G
From what I un... | [
"The choice function in the random module could help with the selection process. You don't really need to worry about the distinction between unicode and string unless you're trying to write them out somewhere as sometimes unicode characters aren't translatable into the ASCII charset that Python defaults to.\nThe ... | [
4
] | [] | [] | [
"graph",
"networkx",
"nodes",
"python"
] | stackoverflow_0001469653_graph_networkx_nodes_python.txt |
Q:
Django: ImportError: cannot import name Count
I just pulled from my github and tried to setup my application on my Ubuntu (I originally ran my app on a Mac at home).
I re-created the database and reconfigured the settings.py -- also update the template locations, etc.
However, when I run the server "python manage.... | Django: ImportError: cannot import name Count | I just pulled from my github and tried to setup my application on my Ubuntu (I originally ran my app on a Mac at home).
I re-created the database and reconfigured the settings.py -- also update the template locations, etc.
However, when I run the server "python manage.py runserver" get an error that says:
ImportError: ... | [
"I've updated my Django and it turns out that your import statement is correct as module structure was changed a bit. Are you sure your Django is of latest version?\n",
"This sounds like you're not using Django 1.1. Double check by opening up the Django shell and running\nimport django\nprint django.VERSION\n\nYo... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001469614_django_python.txt |
Q:
Making a facade in Python 2.5
I want to have a Python class that acts as a wrapper for another Python class.
Something like this
class xxx:
name = property( fset=lambda self, v: setattr(self.inner, 'name', v), fget=lambda self: getattr(self.inner, 'name' ))
def setWrapper( self, obj )
self.inner = ... | Making a facade in Python 2.5 | I want to have a Python class that acts as a wrapper for another Python class.
Something like this
class xxx:
name = property( fset=lambda self, v: setattr(self.inner, 'name', v), fget=lambda self: getattr(self.inner, 'name' ))
def setWrapper( self, obj )
self.inner = obj
So when someone says xxx().x =... | [
"This is where you use the __setattr__ and __getattr__ methods as documented here.\nIn short, if you do this:\nclass Wrapper(object):\n def __init__(self, wrapped):\n object.__setattr__(self, 'inner', wrapped)\n\n def __getattr__(self, attr):\n return getattr(self.inner, attr)\n\n def __setatt... | [
6,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0001469591_python.txt |
Q:
PGP/GnuPG to encrypt
Need to use PGP/GnuPG to encrypt.can suggest what the Python packages to use that.
for PGP encryption i.e. on the other side is PGP used to decrypt.
A:
You could try python-gnupg. Encryption is covered in the docs here.
| PGP/GnuPG to encrypt | Need to use PGP/GnuPG to encrypt.can suggest what the Python packages to use that.
for PGP encryption i.e. on the other side is PGP used to decrypt.
| [
"You could try python-gnupg. Encryption is covered in the docs here.\n"
] | [
0
] | [] | [] | [
"gnupg",
"python"
] | stackoverflow_0001469798_gnupg_python.txt |
Q:
What networking libraries/frameworks exist for Python?
I was wondering what good networking libraries/frameworks there are for Python.
Please provide a link to the standard API documentation for the library, and perhaps a link to a decent tutorial to get started with it.
A comment or two about its advantages/disad... | What networking libraries/frameworks exist for Python? | I was wondering what good networking libraries/frameworks there are for Python.
Please provide a link to the standard API documentation for the library, and perhaps a link to a decent tutorial to get started with it.
A comment or two about its advantages/disadvantages would be nice as well.
| [
"The standard library has asyncore which is good for very simple stuff as well as the SocketServer stuff if you'd prefer something that does threads. There's also Twisted but the barrier of entry to that is a bit high if you're not used to event-driven IO. If you're after web frameworks, CherryPy is a good start ... | [
6,
4,
3,
2
] | [] | [] | [
"frameworks",
"networking",
"python"
] | stackoverflow_0001468780_frameworks_networking_python.txt |
Q:
python win32 extensions documentation
I'm new to both python and the python win32 extensions available at http://python.net/crew/skippy/win32/ but I can't find any documentation online or in the installation directories concerning what exactly the win32 extensions provide. Where is this information?
A:
You'll fi... | python win32 extensions documentation | I'm new to both python and the python win32 extensions available at http://python.net/crew/skippy/win32/ but I can't find any documentation online or in the installation directories concerning what exactly the win32 extensions provide. Where is this information?
| [
"You'll find documentation here:\nhttp://docs.activestate.com/activepython/2.4/pywin32/PyWin32.HTML\n(Note: most of the API docs are under 'modules' and 'objects'. Note that the documentation is very sparse here but rembember: since it's only a wrapper on top of the win32 API --> the 'full' documentation is also on... | [
13,
2,
2,
2
] | [] | [] | [
"documentation",
"python",
"pywin32"
] | stackoverflow_0001468099_documentation_python_pywin32.txt |
Q:
What is going on with this code from the Google App Engine tutorial
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Greeting(db.Model):
author = db.UserProperty()
cont... | What is going on with this code from the Google App Engine tutorial | import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto... | [
"The first piece of code is a model definition:\nclass Greeting(db.Model):\n content = db.StringProperty(multiline=True)\n\nIt says that there is a model Greeting that has a StringProperty with the name content.\nIn the second piece of code, you create an instance of the Greeting model and assign a value to its ... | [
2,
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001470405_google_app_engine_python.txt |
Q:
Create a wrapper class to call a pre and post function around existing functions?
I want to create a class that wraps another class so that when a function is run through the wrapper class a pre and post function is run as well. I want the wrapper class to work with any class without modification.
For example if i... | Create a wrapper class to call a pre and post function around existing functions? | I want to create a class that wraps another class so that when a function is run through the wrapper class a pre and post function is run as well. I want the wrapper class to work with any class without modification.
For example if i have this class.
class Simple(object):
def one(self):
print "one"
def... | [
"You're almost there, you just need to do some introspection inside __getattr__, returning a new wrapped function when the original attribute is callable:\nclass Wrapper(object):\n def __init__(self,wrapped_class):\n self.wrapped_class = wrapped_class()\n\n def __getattr__(self,attr):\n orig_att... | [
31,
3
] | [] | [] | [
"python"
] | stackoverflow_0001466676_python.txt |
Q:
Probability exercise returning different result that expected
As an exercise I'm writing a program to calculate the odds of rolling 5 die with the same number. The idea is to get the result via simulation as opposed to simple math though. My program is this:
# rollFive.py
from random import *
def main():
n... | Probability exercise returning different result that expected | As an exercise I'm writing a program to calculate the odds of rolling 5 die with the same number. The idea is to get the result via simulation as opposed to simple math though. My program is this:
# rollFive.py
from random import *
def main():
n = input("Please enter the number of sims to run: ")
hits = sim... | [
"The probability of getting a particular number five times is (1/6)^5, but the probability of getting any five numbers the same is (1/6)^4.\nThere are two ways to see this.\nFirst, the probability of getting all 1's, for example, is (1/6)^5 since there is only one way out of six to get a 1. Multiply that by five d... | [
6,
1,
1,
0
] | [] | [] | [
"probability",
"python"
] | stackoverflow_0001469421_probability_python.txt |
Q:
How do I determine the proper `paramstyle` when all I have is a `Connection` object?
I have an instance of a Connection (required to DB API 2.0-compliant), but I don't have the module from which it was imported. The problem is that I am trying to use named parameters, but I don't know which paramstyle to use.
Sinc... | How do I determine the proper `paramstyle` when all I have is a `Connection` object? | I have an instance of a Connection (required to DB API 2.0-compliant), but I don't have the module from which it was imported. The problem is that I am trying to use named parameters, but I don't know which paramstyle to use.
Since paramstyle is a module-level constant, I can't just ask the Connection. I tried using in... | [
"Where did you get the instance from? I can't imagine a situation where you won't know the beforehand the source of the connection. If the user of your library is passing you a connection, ask him for the paramstyle as well.\nAnyway, look at the following console session:\n>>> import sqlite3\n>>> c = sqlite3.connec... | [
2,
2,
2
] | [] | [] | [
"python",
"python_db_api"
] | stackoverflow_0001471304_python_python_db_api.txt |
Q:
Django models - pass additional information to manager
I'm trying to implement row-based security checks for Django models. The idea is that when I access model manager I specify some additional info which is used in database queries so that only allowed instances are fetched from database.
For example, we can hav... | Django models - pass additional information to manager | I'm trying to implement row-based security checks for Django models. The idea is that when I access model manager I specify some additional info which is used in database queries so that only allowed instances are fetched from database.
For example, we can have two models: Users and, say, Items. Each Item belongs to so... | [
"From my reading of the documentation I think there are two problems:\n\nThe SecurityManager will not be used for the related objects (and instance of django.db.models.Manager will be used instead)\nYou can fix the above, but the documentation goes to great lengths to specify that get_query_set() should not filter ... | [
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001467245_django_django_models_python.txt |
Q:
Copying modules into Django, "No module named [moduleName]"
I run into this problem pretty consistently... keep in mind I am quite new to Django and a total Python amateur.
It seems that, for example, whenever I check out my Django project on a new computer after a clean install of Python and Django, it can never ... | Copying modules into Django, "No module named [moduleName]" | I run into this problem pretty consistently... keep in mind I am quite new to Django and a total Python amateur.
It seems that, for example, whenever I check out my Django project on a new computer after a clean install of Python and Django, it can never find the project/apps I create or copy in.
So right now I have an... | [
"They way Django works is pretty much how Python works. At default the folder you create when you run django-admin.py startproject name is added to your python path. That means that anything you put into there you can get to. But you have to mind that when you write the app into the installed app list. If you have ... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001471707_django_python.txt |
Q:
Twisted network client with multiprocessing workers?
So, I've got an application that uses Twisted + Stomper as a STOMP client which farms out work to a multiprocessing.Pool of workers.
This appears to work ok when I just use a python script to fire this up, which (simplified) looks something like this:
# stompcli... | Twisted network client with multiprocessing workers? | So, I've got an application that uses Twisted + Stomper as a STOMP client which farms out work to a multiprocessing.Pool of workers.
This appears to work ok when I just use a python script to fire this up, which (simplified) looks something like this:
# stompclient.py
logging.config.fileConfig(config_path)
logger = lo... | [
"Since the difference between your working invocation and your non-working invocation is only the \"-n\" option, it seems most likely that the problem is caused by the daemonization process (which \"-n\" prevents from happening).\nOn POSIX, one of the steps involved in daemonization is forking and having the parent... | [
12,
0
] | [] | [] | [
"multiprocessing",
"python",
"twisted"
] | stackoverflow_0001470850_multiprocessing_python_twisted.txt |
Q:
Small Tables in Python?
Let's say I don't have more than one or two dozen objects with different properties, such as the following:
UID, Name, Value, Color, Type, Location
I want to be able to call up all objects with Location = "Boston", or Type = "Primary". Classic database query type stuff.
Most table solution... | Small Tables in Python? | Let's say I don't have more than one or two dozen objects with different properties, such as the following:
UID, Name, Value, Color, Type, Location
I want to be able to call up all objects with Location = "Boston", or Type = "Primary". Classic database query type stuff.
Most table solutions (pytables, *sql) are really... | [
"For small relational problems I love using Python's builtin sets.\nFor the example of location = 'Boston' OR type = 'Primary', if you had this data:\nusers = {\n 1: dict(Name=\"Mr. Foo\", Location=\"Boston\", Type=\"Secondary\"),\n 2: dict(Name=\"Mr. Bar\", Location=\"New York\", Type=\"Primary\"),\n 3: dict... | [
14,
6,
2
] | [] | [] | [
"lookup_tables",
"python"
] | stackoverflow_0001471924_lookup_tables_python.txt |
Q:
What is the Python equivalent of application & session scope variables?
Recently started on python, wondered what the equivalent object was for storing session & application scope data?
I'm using Google App Engine too so if it has any extra features (can't seem to find any immediate references myself) that would b... | What is the Python equivalent of application & session scope variables? | Recently started on python, wondered what the equivalent object was for storing session & application scope data?
I'm using Google App Engine too so if it has any extra features (can't seem to find any immediate references myself) that would be useful
| [
"I assume you're talking about a web session, used to retain state between http requests. Python is a general programming language and by itself doesn't contain the concept of a session. \nHowever most different python web frameworks have session implementations. Which one are you using? I've linked to the session ... | [
0
] | [] | [] | [
"python",
"scope",
"session",
"web_applications"
] | stackoverflow_0001472279_python_scope_session_web_applications.txt |
Q:
Using Heapy's Memory Profile Browser with Twisted.web
I am trying to profile twisted python code with Heapy. For example (pseudo code):
from twisted.web import resource, server
from twisted.internet import reactor
from guppy import hpy
class RootResource(resource.Resource):
render_GET(self, path, request):
... | Using Heapy's Memory Profile Browser with Twisted.web | I am trying to profile twisted python code with Heapy. For example (pseudo code):
from twisted.web import resource, server
from twisted.internet import reactor
from guppy import hpy
class RootResource(resource.Resource):
render_GET(self, path, request):
return "Hello World"
if __name__ == '__main__':
... | [
"After looking over the guppy website and not finding any information about how to launch the profile browser there, I started looking around the guppy source and eventually found guppy/heapy/Prof.py, at the end of which I saw a docstring containing this line:\n[0] heapy_Use.html#heapykinds.Use.pb\n\nThen, remember... | [
6
] | [] | [] | [
"heap_memory",
"heapy",
"profiling",
"python",
"twisted"
] | stackoverflow_0001331561_heap_memory_heapy_profiling_python_twisted.txt |
Q:
Understanding Python profile output
I'm trying to use the Python profiler to speed up my code. I've been able to identify the specific function where nearly all of the time is spent, but I can't figure out where in that function the time is being spent.
Below I have the profile output, which shows that "appendBal... | Understanding Python profile output | I'm trying to use the Python profiler to speed up my code. I've been able to identify the specific function where nearly all of the time is spent, but I can't figure out where in that function the time is being spent.
Below I have the profile output, which shows that "appendBallot" is the primary culprit and consumes ... | [
"Yeah I came across that same problem as well.\nThe only way I know to work around this is to wrap your large function into several smaller function calls. This will allow the profiler to take into account each of the smaller function calls.\nInteresting enough, the process of doing this (for me, anyway) made it ob... | [
7,
5,
5,
5,
4,
2
] | [] | [] | [
"profile",
"profiling",
"python"
] | stackoverflow_0001469679_profile_profiling_python.txt |
Q:
How can I link against libpython.a such that the runtime linker can find all the symbols in libpython.a?
In a sequel question to this question, my corporate environment lacks the libpython2.6.so shared object but has the libpython2.6.a file. Is there a way that I can compile in libpython2.6.a while retaining the ... | How can I link against libpython.a such that the runtime linker can find all the symbols in libpython.a? | In a sequel question to this question, my corporate environment lacks the libpython2.6.so shared object but has the libpython2.6.a file. Is there a way that I can compile in libpython2.6.a while retaining the symbols in libpython2.6.a such that dynamic libraries can find these symbols at runtime?
My current compile wi... | [
"You need to pass --export-dynamic to the linker. So from g++ it's...\ng++ -Wl,--export-dynamic ...\n\n"
] | [
3
] | [] | [] | [
"g++",
"gcc",
"python"
] | stackoverflow_0001472828_g++_gcc_python.txt |
Q:
Why is the WindowsError while deleting the temporary file?
I have created a temporary file.
Added some data to the file created.
Saved it and then trying to delete it.
But I am getting WindowsError. I have closed the file after editing it. How do I check which other process is accessing the file.
C:\Documents... | Why is the WindowsError while deleting the temporary file? |
I have created a temporary file.
Added some data to the file created.
Saved it and then trying to delete it.
But I am getting WindowsError. I have closed the file after editing it. How do I check which other process is accessing the file.
C:\Documents and Settings\Administrator>python
Python 2.6.1 (r261:67517, De... | [
"From the documentation:\n\nmkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. New in version 2.3. \n\nSo, mkstemp returns both the OS file handle to and the filename of the temporary file. When you re-op... | [
11,
7,
0
] | [] | [] | [
"python",
"temporary_files"
] | stackoverflow_0001470350_python_temporary_files.txt |
Q:
select_related does not join columns marked with nulll=True
I have a Django model -
class NoticedUser(models.Model):
user = models.ForeignKey(User, null=False)
text = models.CharField(max_length=255, null=True)
photo = models.ForeignKey(Photo, null=True, blank=True)
article = models.ForeignKey(Arti... | select_related does not join columns marked with nulll=True | I have a Django model -
class NoticedUser(models.Model):
user = models.ForeignKey(User, null=False)
text = models.CharField(max_length=255, null=True)
photo = models.ForeignKey(Photo, null=True, blank=True)
article = models.ForeignKey(Article, null=True, blank=True)
date = models.DateTimeField(defau... | [
"It doesn't follow these relations by default when using select_related() with no parameters. You have to explicitly specify the names:\nNoticedUser.objects.all().select_related('article', 'photo')\n\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001472974_django_python.txt |
Q:
What's a good resource for starting to write a programming language, that's not context free?
I'm looking to write a programming language for fun, however most of the resource I have seen are for writing a context free language, however I wish to write a language that, like python, uses indentation, which to my un... | What's a good resource for starting to write a programming language, that's not context free? | I'm looking to write a programming language for fun, however most of the resource I have seen are for writing a context free language, however I wish to write a language that, like python, uses indentation, which to my understanding means it can't be context free.
| [
"A context-free grammar is, simply, one that doesn't require a symbol table in order to correctly parse the code. A context-sensitive grammar does.\nThe D programming language is an example of a context free grammar. C++ is a context sensitive one. (For example, is T*x declaring x to be pointer to T, or is it multi... | [
19,
6,
5,
3,
2,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"compiler_construction",
"interpreter",
"programming_languages",
"python"
] | stackoverflow_0000068243_compiler_construction_interpreter_programming_languages_python.txt |
Q:
open source data mining/text analysis tools in python
I have a database full of reviews of various products. My task is to perform various calculation and "create" another "database/xml-export" with aggregated data. I am thinking of writing command line programs in python to do that. But I know someone have done t... | open source data mining/text analysis tools in python | I have a database full of reviews of various products. My task is to perform various calculation and "create" another "database/xml-export" with aggregated data. I am thinking of writing command line programs in python to do that. But I know someone have done this before and I know that there is some open source python... | [
"What kind of analysis are you trying to do?\nIf you're analyzing text take a look at the Natural Language Toolkit (NLTK).\nIf you want to index and search the data, take a look at the whoosh search engine.\nPlease provide some more detail on what kind of analysis you're looking to do.\n",
"Looks like you are loo... | [
1,
1
] | [] | [] | [
"analyzer",
"data_mining",
"database",
"python"
] | stackoverflow_0001473087_analyzer_data_mining_database_python.txt |
Q:
How to create a hardlink on attached Volumes on Mac?
os.link is not working for the attached Volumes on Mac.
~ $ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> ... | How to create a hardlink on attached Volumes on Mac? | os.link is not working for the attached Volumes on Mac.
~ $ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.link("/Volumes/ARCHANA/JULY 09/PRAMANPATRA.doc", "/Volu... | [
"You're working on a mac, yet the volume ARCHANA might not have a link-able file system. (The uppercase label makes it suspicious.)\nAlso, you are trying to refer a hard link to a directory and \"Hard links may not normally refer to directories and may not span file systems.\" (from the man page.)\nOne last thing ... | [
2,
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0001473368_macos_python.txt |
Q:
Do I need multiple cursor objects to loop over a recordset and update at the same time?
So I've got a large database that I can't hold in memory at once. I've got to loop over every item in a table, process it, and put the processed data into another column in the table.
While I'm looping over my cursor, if I try... | Do I need multiple cursor objects to loop over a recordset and update at the same time? | So I've got a large database that I can't hold in memory at once. I've got to loop over every item in a table, process it, and put the processed data into another column in the table.
While I'm looping over my cursor, if I try to run an update statement it truncates the recordset (I believe because it's re-purposing t... | [
"I think you have roughly the right architecture -- presenting it in terms of \"cursors\" WILL confuse the \"old SQL hands\", because they'll be thinking of the many issues connected with DECLARE foo CURSOR, FETCH FROM CURSOR, WHERE CURRENT OF CURSOR, and other such beauts having to do with SQL cursors. Python DB ... | [
3,
2,
1
] | [] | [] | [
"database",
"database_cursor",
"python",
"sqlite"
] | stackoverflow_0001462511_database_database_cursor_python_sqlite.txt |
Q:
django view function code runs after return
I have a django view that looks like...
def add_user(request):
if User.objects.get(username__exact = request.POST['username']):
context = { 'message': "Username already taken"}
return render_to_response("mytemplate.html", context, Req... | django view function code runs after return | I have a django view that looks like...
def add_user(request):
if User.objects.get(username__exact = request.POST['username']):
context = { 'message': "Username already taken"}
return render_to_response("mytemplate.html", context, RequestContext(request))
newUser = User(use... | [
"The return statement will indeed terminate the function. So if you see other code being executed, you either\n\ndon't execute the return statement, and thus produce the output somehow differently, or\nhave other code (before the function is called, or in a middleware) that makes the database changes.\n\n",
"You ... | [
1,
0
] | [] | [] | [
"django",
"python",
"views"
] | stackoverflow_0001473543_django_python_views.txt |
Q:
How should I handle software packages?
I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. My platform: CentOS release 5.3 (Final). I have Python-2.6.2.
I also found out that I need .rpm files. As far a... | How should I handle software packages? | I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. My platform: CentOS release 5.3 (Final). I have Python-2.6.2.
I also found out that I need .rpm files. As far as I have them I execute:
rpm -i sqlite3-deve... | [
"Python 2.6 (and some earlier) include sqlite Python org library ref so you should not need to do this. Just import it and run\n",
"You can use buildout to create localized version of your project. This will install all necessary packages without having sudo access to the server.\nTo give it try, do the following... | [
3,
2,
1
] | [] | [] | [
"pysqlite",
"python",
"rpm",
"sqlite"
] | stackoverflow_0001471567_pysqlite_python_rpm_sqlite.txt |
Q:
Django ORM - assigning a raw value to DecimalField
EDIT!!! - The casting of the value to a string seems to work fine when I create a new object, but when I try to edit an existing object, it does not allow it.
So I have a decimal field in one of my models of Decimal(3,2)
When I query up all these objects and try t... | Django ORM - assigning a raw value to DecimalField | EDIT!!! - The casting of the value to a string seems to work fine when I create a new object, but when I try to edit an existing object, it does not allow it.
So I have a decimal field in one of my models of Decimal(3,2)
When I query up all these objects and try to set this field:
fieldName = 0.85
OR
fieldName = .85
... | [
"from decimal import Decimal\nobject.fieldName = Decimal(\"0.85\")\n\nor\nf = 0.85\nobject.fieldName = Decimal(str(f))\n\n",
"The Django DecimalField is \"...represented in by a python Decimal instance.\" You might try:\n>>> obj.fieldName = Decimal(\"0.85\")\n\nBehavior may also vary depending on the database ba... | [
11,
3
] | [] | [] | [
"casting",
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0001473332_casting_django_django_models_django_orm_python.txt |
Q:
Can Python's MiniMock create mock of functions defined in the same file?
I'm using the Python MiniMock library for unit testing. I'd like to mock out a function defined in the same Python file as my doctest. Can MiniMock handle that? The naive approach fails:
def foo():
raise ValueError, "Don't call me during... | Can Python's MiniMock create mock of functions defined in the same file? | I'm using the Python MiniMock library for unit testing. I'd like to mock out a function defined in the same Python file as my doctest. Can MiniMock handle that? The naive approach fails:
def foo():
raise ValueError, "Don't call me during testing!"
def bar():
"""
Returns twice the value of foo()
>>> f... | [
"I just replied on the mailing list with a MiniMock patch that fixes this.\nUntil that's applied, instead of the following two lines in itsadok's snippet:\n>>> mock('foo',returns=5)\n>>> bar.func_globals['foo'] = foo\n\nyou could also use\n>>> mock('foo', nsdicts=(bar.func_globals,), returns=5)\n\n",
"This works:... | [
5,
1
] | [] | [] | [
"mocking",
"python"
] | stackoverflow_0001462381_mocking_python.txt |
Q:
global counter in Django Application?
I was wondering if there is "global counter" in Django application, like the way I store "global counter" in Servlet Context scope in Tomcat.
something like
getServletContext().getAttribute("counter");
counter++;
A:
When you write a django application (or any wsgi applicat... | global counter in Django Application? | I was wondering if there is "global counter" in Django application, like the way I store "global counter" in Servlet Context scope in Tomcat.
something like
getServletContext().getAttribute("counter");
counter++;
| [
"When you write a django application (or any wsgi application, for that matter), you don't know beforehand if your application will end up running standalone on a single server, or multithreaded, or multiprocessed, or even in multiple separate machines as part of a load balancing strategy.\nIf you're going to make ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001475264_django_python.txt |
Q:
Google App Engine get PolyModel as child class
When I run Google App Engine likeso:
from google.appengine.ext import db
from google.appengine.ext.db import polymodel
class Father(polymodel.PolyModel):
def hello(self):
print "Father says hi"
class Son(Father):
def hello(self):
... | Google App Engine get PolyModel as child class | When I run Google App Engine likeso:
from google.appengine.ext import db
from google.appengine.ext.db import polymodel
class Father(polymodel.PolyModel):
def hello(self):
print "Father says hi"
class Son(Father):
def hello(self):
print "Spawn says hi"
When I run, e.g.
s = Son()
... | [
"I can't reproduce your problem -- indeed, your code just dies with an import error (PolyModel is not in module db) on my GAE (version 1.2.5). Once I've fixed things enough to let the code run...:\nimport wsgiref.handlers\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.db import polymodel\n\ncl... | [
1
] | [
"You did a \"Father.get...\" so you created an object from the Father class. \nSo why wouldn't it say \"Father says hi\". \nIf you Father class had lastname and firstname, and your Son class had middle name, you won't get the middle name unless you specifically retrieve the 'Son' record. \nIf you want to do a polym... | [
-1
] | [
"google_app_engine",
"polymodel",
"python"
] | stackoverflow_0001474868_google_app_engine_polymodel_python.txt |
Q:
What are the best benefits of using Pinax?
I recently discovered Pinax that appear to be an django stack with added most-used apps so easy and speed up development.
I never used or heard of Pinax before and like to know if you have feedback about it. I love Django and would like to understand what are to parts of ... | What are the best benefits of using Pinax? | I recently discovered Pinax that appear to be an django stack with added most-used apps so easy and speed up development.
I never used or heard of Pinax before and like to know if you have feedback about it. I love Django and would like to understand what are to parts of web dev Pinax helps with and using what tools.
| [
"Pinax is a collection of Django-Apps that have already been glued together for you with some code and sample templates.\nIt's not plug&play, because Django is not a CMS and Apps are not plugins, but you can get your site going really fast. You just have to remove the stuff you don't need, add other Django Apps tha... | [
14,
8,
5
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0001448292_django_pinax_python.txt |
Q:
BitString error on Windows XP?
Scott,
I'd like to thank you for your BitString program. I am working on interpreting data from a neutron detector, and I've found that this module is just the tool I need. Unfortunately, I have yet to get the module to successfully pass test-bitstring.py. I'm running Windows XP a... | BitString error on Windows XP? | Scott,
I'd like to thank you for your BitString program. I am working on interpreting data from a neutron detector, and I've found that this module is just the tool I need. Unfortunately, I have yet to get the module to successfully pass test-bitstring.py. I'm running Windows XP and Python 3.1. I've downloaded your... | [
"I just tested that bitstring-0.4.1 's test-bitstring.py works flawlessly on both Python 3.0 and Python 3.1, on a Windows XP host.\nThe 3.1 version, specifically, this is what happens.\n'3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)]'\n\nc:\\python31\\python test_bitstring.py\n.................. | [
2,
1
] | [] | [] | [
"bitstring",
"python",
"python_3.x",
"windows_xp"
] | stackoverflow_0001475033_bitstring_python_python_3.x_windows_xp.txt |
Q:
Why is host aborting connection?
I'm teaching myself Python networking, and I recalled that back when I was teaching myself threading, I came across this page, so I copied the scripts, updated them for Python 3.1.1 and ran them. They worked perfectly.
Then I made a few modifications. My goal is to do something s... | Why is host aborting connection? | I'm teaching myself Python networking, and I recalled that back when I was teaching myself threading, I came across this page, so I copied the scripts, updated them for Python 3.1.1 and ran them. They worked perfectly.
Then I made a few modifications. My goal is to do something simple:
The client pickles an integer ... | [
"Your client is now correct - you want to open the socket send the data, receive the reply and then close the socket.\nThe error original error was caused by the server closing the socket after it sent the first response which caused the client to receive a connection closed message when it tried to send the second... | [
11
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0001472876_networking_python.txt |
Q:
Install CherryPy on Linux hosting provider without command line access
I have a linux based web hosting provider (fatcow.com) that doesn't give any command line access and won't run the setup script for CherryPy (python web server) for me.
Is there any way to run get around this limitation so that I have a working... | Install CherryPy on Linux hosting provider without command line access | I have a linux based web hosting provider (fatcow.com) that doesn't give any command line access and won't run the setup script for CherryPy (python web server) for me.
Is there any way to run get around this limitation so that I have a working install of CherryPy?
This might be more or a serverfault.com question, but ... | [
"If CherryPy is pure Python, then you may be able to simply put the cherrypy folder in the same place your project resides. This will enable you to import the necessary things from CherryPy without needing to copy it to the official install directory. I've personally never used CherryPy, so I don't know precisely w... | [
2,
0
] | [] | [] | [
"cherrypy",
"linux",
"python"
] | stackoverflow_0000938185_cherrypy_linux_python.txt |
Q:
what happens to a python object when you throw an exception from it
My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to ... | what happens to a python object when you throw an exception from it | My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.
Problem is that the server only handles one conn... | [
"This is an artifact of garbage collection. Even though the object is out of scope, it is not necessarily collected and therefore destroyed until a garbage collection run occurs -- this is not like C++ where a destructor is called as soon as an object loses scope.\nYou can probably work around this particular issu... | [
5,
1,
0,
0
] | [] | [] | [
"exception",
"garbage_collection",
"python",
"sockets"
] | stackoverflow_0001475193_exception_garbage_collection_python_sockets.txt |
Q:
Python: Referencing another project
I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders.
One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hac... | Python: Referencing another project | I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders.
One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want i... | [
"If you import sys, it contains a list of the directories in PYTHONPATH as sys.path\nAdding directories to this list (sys.path.append(\"my/path\")) allows you to import from those locations in the current module as normal without changing the global settings on your system.\n",
"Take a look at tools like\n\nvirtu... | [
10,
5,
1,
0,
0
] | [] | [] | [
"command_line",
"python"
] | stackoverflow_0001476111_command_line_python.txt |
Q:
python multiprocessing manager & composite pattern sharing
I'm trying to share a composite structure through a multiprocessing manager but I felt in trouble with a "RuntimeError: maximum recursion depth exceeded" when trying to use just one of the Composite class methods.
The class is token from code.activestate a... | python multiprocessing manager & composite pattern sharing | I'm trying to share a composite structure through a multiprocessing manager but I felt in trouble with a "RuntimeError: maximum recursion depth exceeded" when trying to use just one of the Composite class methods.
The class is token from code.activestate and tested by me before inclusion into the manager.
When retrievi... | [
"Python has a default maximum recursion depth of 1000 (or 999, I forget...). But you can change the default behavior thusly:\nimport sys\nsys.setrecursionlimit(n)\n\nWhere n is the number of recursions you wish to allow. \nEdit:\nThe above answer does nothing to solve the root cause of this problem (as pointed out... | [
0,
0,
0
] | [] | [] | [
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0001473625_multiprocessing_python_python_multiprocessing.txt |
Q:
python arbitrarily incrementing an iterator inside a loop
I am probably going about this in the wrong manner, but I was wondering how to handle this in python.
First some c code:
int i;
for(i=0;i<100;i++){
if(i == 50)
i = i + 10;
printf("%i\n", i);
}
Ok so we never see the 50's...
My question is, how c... | python arbitrarily incrementing an iterator inside a loop | I am probably going about this in the wrong manner, but I was wondering how to handle this in python.
First some c code:
int i;
for(i=0;i<100;i++){
if(i == 50)
i = i + 10;
printf("%i\n", i);
}
Ok so we never see the 50's...
My question is, how can I do something similar in python? For instance:
for line in ... | [
"There is a fantastic package in Python called itertools.\nBut before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the __iter__() class method that provides an iterator type. \"Understanding Pytho... | [
46,
17,
2,
1,
1,
1,
1
] | [
"I can't parse the question vary well because there's this block of confusing and irrelevant C code. Please delete it.\nFocusing on just the Python code and the question about how to skip 5 lines...\nlineIter= iter( cdata.splitlines() )\nfor line in lineIter:\n if exp.match(line):\n for count in range(5):\n ... | [
-6
] | [
"iterator",
"python"
] | stackoverflow_0001474646_iterator_python.txt |
Q:
How to find and run my old (global) version of Python?
I have locally installed a newer version of Python. For that I did the following:
$ cd
$ mkdir opt
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz
$ tar xvzf Python-2.6.2.tgz
$ cd Python-2.6.2
$ ./configure --pre... | How to find and run my old (global) version of Python? | I have locally installed a newer version of Python. For that I did the following:
$ cd
$ mkdir opt
$ mkdir downloads
$ cd downloads
$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz
$ tar xvzf Python-2.6.2.tgz
$ cd Python-2.6.2
$ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4
$ make
$ make install
... | [
"You can directly call the program with something like \"/usr/local/bin/python myscript.py\". You just need to know where your standard installation of python is. If you don't know, you can undo your changes and then type \"which python\" to find out what actually gets executed when you type \"python\" on the comm... | [
2,
0
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0001477300_installation_python.txt |
Q:
Form Validation in Admin with Inline formset and Model form
I have a model, OrderedList, which is intended to be a listing of content objects ordered by the user. The OrderedList has several attributes, including a site which it belongs to.
The content objects are attached to it via an OrderedListRow class, which ... | Form Validation in Admin with Inline formset and Model form | I have a model, OrderedList, which is intended to be a listing of content objects ordered by the user. The OrderedList has several attributes, including a site which it belongs to.
The content objects are attached to it via an OrderedListRow class, which is brought into OrderedList's admin via an inline formset in the ... | [
"In the inline formset, self.instance should refer to the parent object, ie the OrderedList.\n",
"I am dealing with the same issue. And unfortunately I don't think the answer above covers things entirely.\nIf there are changes in both the inline formset and the admin form, accessing self.instance will not give ac... | [
6,
1
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0000967045_django_django_admin_django_forms_python.txt |
Q:
How do you bind a language (python, for example) to another (say, C++)?
I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.
A:
Interprete... | How do you bind a language (python, for example) to another (say, C++)? | I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.
| [
"Interpreters Written in C89 with Reflection, Who Knew?\n\nI have a feeling you are looking for an explanation of the mechanism and not a link to the API or instructions on how to code it. So, as I understand it . . .\nThe main interpreter is typically written in C and is dynamically linked. In a dynamically linked... | [
12,
7,
4,
3,
2,
2
] | [] | [] | [
"binding",
"java",
"python"
] | stackoverflow_0001475637_binding_java_python.txt |
Q:
Python chat : delete variables to clean memory in functions?
I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's... | Python chat : delete variables to clean memory in functions? | I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's a strip down version of my code to illustrate my point:
class Cha... | [
"C Python (the reference implementation) uses reference counting and garbage collection. When count of references to object decrease to 0, it is automatically reclaimed. The garbage collection normally reclaims only those objects that refer to each other (or other objects from them) and thus cannot be reclaimed by ... | [
16,
7,
4
] | [] | [] | [
"class",
"function",
"python",
"twisted"
] | stackoverflow_0001477980_class_function_python_twisted.txt |
Q:
How was the syntax chosen for static methods in Python?
I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.
A regular method would be declared:
def mymethod(self, params)
...
return
A static method is declared:
def mystaticethod(params)
...
r... | How was the syntax chosen for static methods in Python? | I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar.
A regular method would be declared:
def mymethod(self, params)
...
return
A static method is declared:
def mystaticethod(params)
...
return
mystaticmethod = staticmethod(mystaticmethod)
If you d... | [
"Static methods were added to Python long after classes were (classes were added very early on, possibly even before 1.0; static methods didn't show up until sometime about 2.0). They were implemented as a modification of normal methods — you create a static method object from a function to get a static method, wh... | [
12,
11,
4,
3,
2,
2,
1,
0
] | [] | [] | [
"language_history",
"python",
"static",
"syntax"
] | stackoverflow_0001477545_language_history_python_static_syntax.txt |
Q:
To do RegEx, what are the advantages/disadvantages to use UTF-8 string instead of unicode?
Usually, the best practice in python, when using international languages, is to use unicode and to convert early any input to unicode and to convert late to a string encoding (UTF-8 most of the times).
But when I need to do ... | To do RegEx, what are the advantages/disadvantages to use UTF-8 string instead of unicode? | Usually, the best practice in python, when using international languages, is to use unicode and to convert early any input to unicode and to convert late to a string encoding (UTF-8 most of the times).
But when I need to do RegEx on unicode I don't find the process really friendly. For example, if I need to find the 'é... | [
"If you're using utf-8 in your python source, you can just write:\nu'Élisa'\n\nand that would be a unicode string, equivalent to writing:\nu'\\xc9lisa'\n\nSo the 'u' prefix makes the decode thing unneeded. If you leave out the 'u' and write:\n'Élisa'\n\nThen you'd have a (utf-8 encoded) bytestring, equivalent to:\n... | [
3,
3
] | [] | [] | [
"python",
"regex",
"unicode",
"utf_8"
] | stackoverflow_0001478178_python_regex_unicode_utf_8.txt |
Q:
How to import bookmarks from users web browsers using python?
I am working on an RSS Reader type program and I would like it to be able to
automatically import RSS feeds from the users browser bookmarks. I assume different
browsers use different methods to store bookmarks. Is there any library out there just for ... | How to import bookmarks from users web browsers using python? | I am working on an RSS Reader type program and I would like it to be able to
automatically import RSS feeds from the users browser bookmarks. I assume different
browsers use different methods to store bookmarks. Is there any library out there just for this purpose?
I only need it to work on Linux so I don't care abou... | [
"Take a look at: XBEL\n"
] | [
1
] | [] | [] | [
"browser",
"linux",
"python",
"xbel"
] | stackoverflow_0001478375_browser_linux_python_xbel.txt |
Q:
Why my python does not see pysqlite?
I would like to have an interface between Python and sqlite. Both are installed on the machine. I had an old version of Python (2.4.3). So, pysqlite was not included by default. First, I tried to solve this problem by installing pysqlite but I did not succeed in this direction.... | Why my python does not see pysqlite? | I would like to have an interface between Python and sqlite. Both are installed on the machine. I had an old version of Python (2.4.3). So, pysqlite was not included by default. First, I tried to solve this problem by installing pysqlite but I did not succeed in this direction. My second attempt to solve the problem wa... | [
"On Windows, _sqlite3.pyd resides in C:\\Python26\\DLLs. On *nix, it should be under a path similar to /usr/lib/python2.6/lib-dynload/_sqlite3.so. Chances are that either you are missing that shared library or your PYTHONPATH is set up incorrectly. \nSince you said you did not install as a superuser, it's probabl... | [
1,
1
] | [] | [] | [
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0001478479_pysqlite_python_sqlite.txt |
Q:
for line in open(filename)
I frequently see python code similar to
for line in open(filename):
do_something(line)
When does filename get closed with this code?
Would it be better to write
with open(filename) as f:
for line in f.readlines():
do_something(line)
A:
filename would be closed when it... | for line in open(filename) | I frequently see python code similar to
for line in open(filename):
do_something(line)
When does filename get closed with this code?
Would it be better to write
with open(filename) as f:
for line in f.readlines():
do_something(line)
| [
"filename would be closed when it falls out of scope. That normally would be the end of the method.\nYes, it's better to use with.\n\nOnce you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the close method on the o... | [
40,
9,
8,
3
] | [] | [] | [
"file",
"garbage_collection",
"python"
] | stackoverflow_0001478697_file_garbage_collection_python.txt |
Q:
Python: "1-2-3-4" to [1, 2, 3, 4]
What is the best way to convert a string on the format "1-2-3-4" to a list [1, 2, 3, 4]? The string may also be empty, in which case the conversion should return an empty list [].
This is what I have:
map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('... | Python: "1-2-3-4" to [1, 2, 3, 4] | What is the best way to convert a string on the format "1-2-3-4" to a list [1, 2, 3, 4]? The string may also be empty, in which case the conversion should return an empty list [].
This is what I have:
map(lambda x: int(x),
filter(lambda x: x != '',
"1-2-3-4".split('-')))
EDIT: Sorry all of those who ans... | [
"You can use a list comprehension to make it shorter. Use the if to account for the empty string.\nthe_string = '1-2-3-4'\n\n[int(x) for x in the_string.split('-') if x != '']\n\n",
">>> for s in [\"\", \"0\", \"-0-0\", \"1-2-3-4\"]:\n... print(map(int, filter(None, s.split('-'))))\n... \n[]\n[0]\n[0, 0]\n[1,... | [
12,
8,
4,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001478908_python.txt |
Q:
Build failure during install py25-gtk on Mac OS X 10.6 using MacPorts 1.8
When I do this command :
sudo port clean py25-gtk
sudo port install py25-gtk
I get this error :
---> Computing dependencies for py25-gtk
---> Building getopt
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/ma... | Build failure during install py25-gtk on Mac OS X 10.6 using MacPorts 1.8 | When I do this command :
sudo port clean py25-gtk
sudo port install py25-gtk
I get this error :
---> Computing dependencies for py25-gtk
---> Building getopt
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_s... | [
"The solution is to reinstall all ports because I upgraded to a new OS version (10.5 -> 10.6).\nTo reinstall your ports, save the list of your installed ports:\nport installed > myports.txt\n\nClean any partially completed builds, and uninstall all installed ports:\nsudo port clean installed\nsudo port -f uninstall... | [
1
] | [] | [] | [
"getopt",
"gtk",
"macos",
"macports",
"python"
] | stackoverflow_0001478263_getopt_gtk_macos_macports_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.