content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python - Number of Significant Digits in results of division
Newbie here. I have the following code:
myADC = 128
maxVoltage = 5.0
maxADC = 255.0
VoltsPerADC = maxVoltage/maxADC
myVolts = myADC * VoltsPerADC
print "myADC = {0: >3}".format(myADC)
print "VoltsPerADC = {0: >7}".format(VoltsPerADC)
print VoltsPerADC
... | Python - Number of Significant Digits in results of division | Newbie here. I have the following code:
myADC = 128
maxVoltage = 5.0
maxADC = 255.0
VoltsPerADC = maxVoltage/maxADC
myVolts = myADC * VoltsPerADC
print "myADC = {0: >3}".format(myADC)
print "VoltsPerADC = {0: >7}".format(VoltsPerADC)
print VoltsPerADC
print "myVolts = {0: >7}".format(myVolts)
print myVolts
This outp... | [
"The precision is determined by the hardware. Python uses hardware floats (actually doubles) for its floats. The implications are discussed in the tutorial: http://docs.python.org/tutorial/floatingpoint.html\nIf you want more control over precision and rounding, you should consider using the decimal module.\n",
"... | [
6,
0
] | [] | [] | [
"digits",
"division",
"floating_point",
"format",
"python"
] | stackoverflow_0002559835_digits_division_floating_point_format_python.txt |
Q:
wxPython: Sending a signal to several widgets
I am not even sure how to ask this question. I want something that is like the wxPython event system, but a bit different. I'll try to explain.
When there is a certain change in my program (a "tree change", never mind what that is,) I want to send a signal to all the w... | wxPython: Sending a signal to several widgets | I am not even sure how to ask this question. I want something that is like the wxPython event system, but a bit different. I'll try to explain.
When there is a certain change in my program (a "tree change", never mind what that is,) I want to send a signal to all the widgets in my program, notifying them that a "tree c... | [
"You can write your own publish-subscribe mechanism which can be as simple as this:\ndef register(self, callback):\n self.callbacks.append(callback)\n\ndef emit(self, eventName):\n for callback in self.callbacks:\n callback(eventName)\n\nAnybody interested in listening to event registers a function wi... | [
6,
0
] | [] | [] | [
"event_handling",
"events",
"python",
"signals",
"wxpython"
] | stackoverflow_0002546814_event_handling_events_python_signals_wxpython.txt |
Q:
Python check if object is in list of objects
I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.
I thought I could simply do
for item1 in list1:
for item2 in list2:
if item1 == item2:
... | Python check if object is in list of objects | I have a list of objects in Python. I then have another list of objects. I want to go through the first list and see if any items appear in the second list.
I thought I could simply do
for item1 in list1:
for item2 in list2:
if item1 == item2:
print "item %s in both lists"
However this does n... | [
"Assuming that your object has only a title attribute which is relevant for equality, you have to implement the __eq__ method as follows:\nclass YourObject:\n [...]\n def __eq__(self, other):\n return self.title == other.title\n\nOf course if you have more attributes that are relevant for equality, you... | [
39,
10,
5,
4,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002559083_python.txt |
Q:
Python: re-initialize a function's default value for subsequent calls to the function
I have a function that calls itself to increment and decrement a stack.
I need to call it a number of times, and I'd like it to work the same way in subsequent calls
but, as expected, it doesn't re-use the default value.
I've rea... | Python: re-initialize a function's default value for subsequent calls to the function | I have a function that calls itself to increment and decrement a stack.
I need to call it a number of times, and I'd like it to work the same way in subsequent calls
but, as expected, it doesn't re-use the default value.
I've read that this is a newbie trap and I've seen suggested solutions, but I haven't been able
to ... | [
"Just pass stack explicitly when doing recursive call:\ndef a(x, stack=None):\n if stack is None:\n stack = [None]\n ...\n a(x + 1, stack)\n\n",
"def a(x, stack = None):\n if stack is None:\n stack = [None]\n ...\n\n",
"This problem happens because you modify the default argument, w... | [
4,
3,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0002560697_function_python.txt |
Q:
cache.fetch in Django?
Does Django caching have a method similar to Rails' cache.fetch? (http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023)
The rails cache fetch works like:
cache.fetch("my_key") {
// return what I want to put in my_key if it is empty
"some_value"
}
It's useful becaus... | cache.fetch in Django? | Does Django caching have a method similar to Rails' cache.fetch? (http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#M001023)
The rails cache fetch works like:
cache.fetch("my_key") {
// return what I want to put in my_key if it is empty
"some_value"
}
It's useful because it checks the cache, and r... | [
"I think the code you would have to write would be like this: (EDIT)\ndef get_value(param1,param2):\n return \"value %s - %s \" % (str(param1),str(param2))\n\ndef fetch(key,val_function,**kwargs)\n val = cache.get(key)\n if not val:\n val = val_function(**kwargs)\n cache.set(key,val)\n ret... | [
4,
2,
0
] | [] | [] | [
"caching",
"django",
"fetch",
"python",
"ruby_on_rails"
] | stackoverflow_0002214330_caching_django_fetch_python_ruby_on_rails.txt |
Q:
Beginner having a problem with classes
I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem.
Fron page 88-89:
>>> class Worker:
def __innit__(self, name, pay):
self.name=name
self.pay=pay
d... | Beginner having a problem with classes | I'm working through O'Reilly's "Learning Python" and having a problem with classes. I think I understand the concept, but in practice have stumbled upon this problem.
Fron page 88-89:
>>> class Worker:
def __innit__(self, name, pay):
self.name=name
self.pay=pay
def lastName(self):
return self.name.... | [
"David, you've mis-typed __init__\nThe correct spelling is this:\ndef __init__(self, name, pay):\n self.name=name\n self.pay=pay\ndef lastName(self):\n return self.name.split()[-1]\ndef giveRaise(self, percent):\n self.pay*=(1.0+percent)\n\n",
"One misspelling: it's __init__, not __innit__ -- just one... | [
8,
5,
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002560997_class_python.txt |
Q:
How should I use try...except while defining a function?
I find I've been confused by the problem that when I needn't to use try..except.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:
class mongodb(object):
def getRecords(self,tname,condition... | How should I use try...except while defining a function? | I find I've been confused by the problem that when I needn't to use try..except.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:
class mongodb(object):
def getRecords(self,tname,conditions=''):
try:
col = eval("self.db.%s" %tname... | [
"This (catching all possible exceptions very broadly) is indeed considered bad practice. You'll mask the real reason for the exception.\nCatch only 'explicitely named' types of exceptions (which you expect to happen and you can/will handle gracefully). Let the rest (unexpected ones) bubble as they should.\nYou can... | [
5,
5,
4,
1
] | [] | [] | [
"exception",
"function",
"python"
] | stackoverflow_0002560137_exception_function_python.txt |
Q:
Google Books API - How do I separate Book from Book Edition?
I'm using Google Book Search API to add missings bits and pieces to my database.
Problem is that The API gives me back a list of book editions, and not reference to the original book itself.
The data I'm trying to get is this:
Original title: The Hobbit... | Google Books API - How do I separate Book from Book Edition? | I'm using Google Book Search API to add missings bits and pieces to my database.
Problem is that The API gives me back a list of book editions, and not reference to the original book itself.
The data I'm trying to get is this:
Original title: The Hobbit
Original year of publication: 1937
Can anyone help?
Just in cas... | [
"Try with this snippet:\nentry = self.service.get_by_google_id(\"XV0NAQAAIAAJ\")\nprint entry.dc_title[0].text\nprint entry.date.text\n\nResult is:\nThe hobbit\n1937\n"
] | [
1
] | [] | [] | [
"google_api",
"python"
] | stackoverflow_0002299589_google_api_python.txt |
Q:
A Question about using jython when run a receving socket in python
I have not a lot of knowledge of python and network programming. Currently I am trying to implement a simple application which can receive a text message sent by the user, fetch some information from the google search api, and return the results vi... | A Question about using jython when run a receving socket in python | I have not a lot of knowledge of python and network programming. Currently I am trying to implement a simple application which can receive a text message sent by the user, fetch some information from the google search api, and return the results via text message to the user. This application will continue to listening ... | [
"As stated on the jython select documentaion page, only sockets in non-blocking mode can be multiplexed on jython, in contrast to cpython, where sockets can be either blocking or non-blocking.\nhttp://wiki.python.org/jython/SelectModule#Onlysocketsinnon-blockingmodecanbemultiplexed\nThis is a limitation of Java tha... | [
2,
1
] | [] | [] | [
"jython",
"nonblocking",
"python",
"sockets"
] | stackoverflow_0002532943_jython_nonblocking_python_sockets.txt |
Q:
Problem with python class
Hi I am new to Python and as a part of my assignment I have written the following class
import nltk.stem.api
class BanglaStemmer(nltk.stem.api.StemmerI):
suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', ... | Problem with python class | Hi I am new to Python and as a part of my assignment I have written the following class
import nltk.stem.api
class BanglaStemmer(nltk.stem.api.StemmerI):
suffixList = ['\xef\xbb\xbf\xe0\xa6\xbf\xe0\xa7\x9f\xe0\xa7\x87\xe0\xa6\x9b\xe0\xa6\xbf\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\xae\n', '\xe0\xa6\xbf\xe0\xa7\x9f\xe0\x... | [
"for suffix in suffixList:\n\nshould be\nfor suffix in self.suffixList:\n\nUnlike a lot of OOP languages, Python requires you to qualify class members inside the class methods.\n",
"You can use BanglaStemmer.suffixList or self.suffixList to access the variable. Plain suffixList would only work on a local (defined... | [
6,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002561469_python.txt |
Q:
Once I know the basic elements and syntax of Python, what should I do?
Well, I have read several user guides and watched dozens and dozens of video tutorials on how to program with Python, and feel pretty confident about writing simple applications for it. My main point in my question is, where would I be able to ... | Once I know the basic elements and syntax of Python, what should I do? | Well, I have read several user guides and watched dozens and dozens of video tutorials on how to program with Python, and feel pretty confident about writing simple applications for it. My main point in my question is, where would I be able to learn more advanced programming knowledge about Python?
| [
"How simple of applications are you making? Have you gone through the exercises in Google's Python Class? I highly recommend going through those. If you really know what you are doing, you should breeze through them. If not, then you'll be learning some valuable skills and becoming a little more experienced in Pyth... | [
3,
2,
2,
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002513260_python_wxpython.txt |
Q:
How do I define a SWIG typemap for a reference to pointer?
I have a Publisher class written in C++ with the following two methods:
PublishField(char* name, double* address);
GetFieldReference(char* name, double*& address);
Python bindings for this class are being generated using SWIG. In my swig .i file I have t... | How do I define a SWIG typemap for a reference to pointer? | I have a Publisher class written in C++ with the following two methods:
PublishField(char* name, double* address);
GetFieldReference(char* name, double*& address);
Python bindings for this class are being generated using SWIG. In my swig .i file I have the following:
%pointer_class(double*, ptrDouble);
This lets me... | [
"Here is a working solution that I came up with.\nAdd a wrapper function to the swig.i file:\n%inline %{\n double * GetReference(char* name, Publisher* publisher)\n {\n double* ptr = new double;\n publisher->GetFieldReference(name, ptr);\n return ptr;\n }\n%}\n\nNow from Python I ca... | [
1,
0
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0001499569_c++_python_swig.txt |
Q:
Querying many to many fields in django
In the models there is a many to many fields as,
from emp.models import Name
def info(request):
name = models.ManyToManyField(Name)
And in emp.models the schema is as
class Name(models.Model):
name = models.CharField(max_length=512)
def __unicode__(self... | Querying many to many fields in django | In the models there is a many to many fields as,
from emp.models import Name
def info(request):
name = models.ManyToManyField(Name)
And in emp.models the schema is as
class Name(models.Model):
name = models.CharField(max_length=512)
def __unicode__(self):
return self.name
Now when i w... | [
"info.name is ManyToManyField so if you want all Name objects associated with it you have to use .all() method on it. Only then you'll get list (queryset) of Name objects:\ninfo_list = info.objects.filter(id=a)\nfor info_object in info_list:\n for name_object in info_object.name.all():\n print name_object... | [
3,
1
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0002559909_django_django_models_django_views_python.txt |
Q:
Python - Execute Process -> Block till it exits & Suppress Output
I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration.
subprocess.Popen(["scanx", "--udp", host], stdin... | Python - Execute Process -> Block till it exits & Suppress Output | I'm using the following to execute a process and hide its output from Python. It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration.
subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
| [
"Use subprocess.call(). From the docs:\n\nsubprocess.call(*popenargs, **kwargs)\n Run command with arguments. Wait for command to complete, then\n return the returncode attribute.\n The arguments are the same as for the\n Popen constructor.\n\nEdit:\nsubprocess.call() uses wait(), and wait() is vulnerable to de... | [
7,
7
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0002561902_python_subprocess.txt |
Q:
How to sort a list alphabetically and have additional lists sorted in the same order
I have 3 lists, each with equal elements: email addresses, salaries and IDs
I'd like to sort the email addresses alphabetically and in some way sort the other 2 lists (salaries and IDs).
E.g.,
Emails:
z@company.com
a@company.com
... | How to sort a list alphabetically and have additional lists sorted in the same order | I have 3 lists, each with equal elements: email addresses, salaries and IDs
I'd like to sort the email addresses alphabetically and in some way sort the other 2 lists (salaries and IDs).
E.g.,
Emails:
z@company.com
a@company.com
Salaries:
50000
60000
IDs:
2
1
The puzzle:
I'd like to sort Emails such that a@c.com is ... | [
"Try:\nemails = [\"z@c.com\", \"a@c.com\"]\nsalaries = [50, 60]\nids = [2, 1]\n\nintermediate = zip(emails, salaries, ids)\nintermediate.sort()\n\nresult = zip(*intermediate)\n\n",
"This is essentially ebo's solution, made to a one-liner with the user of sorted() rather than list.sort, and multiple lvalues in the... | [
5,
3,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0002562714_list_python_sorting.txt |
Q:
cannot append Model.objects.all()
I cannot run ['abc'].append( MyModel.objects.all() ) since it generates exception 'NoneType' object is not iterable if MyModel has no entry.
any workaround or something like ? : in c++
edit:
my statement is actually
','.join([ str(e) for e in ['abc','def'].append( MyModel.objec... | cannot append Model.objects.all() | I cannot run ['abc'].append( MyModel.objects.all() ) since it generates exception 'NoneType' object is not iterable if MyModel has no entry.
any workaround or something like ? : in c++
edit:
my statement is actually
','.join([ str(e) for e in ['abc','def'].append( MyModel.objects.all() ) ])
it seems that the proble... | [
"how about: \n['abc'].append( MyModel.objects.all() or [])\n\n",
"It might be best to be explicit rather than implicit (and avoid using the short circuit propoerties of or which can lead to errors:\nmy_objects = MyModel.objects.all()\nif my_objects:\n [a,b,c].extend(my_objects)\n\n",
"Model.objects.all() ... | [
2,
2,
1,
1,
0
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0002560178_django_django_models_django_queryset_python.txt |
Q:
How to implement simple sessions for Google App Engine?
Here is a very basic class for handling sessions on App Engine:
"""Lightweight implementation of cookie-based sessions for Google App Engine.
Classes:
Session
"""
import os
import random
import Cookie
from google.appengine.api import memcache
_COOKIE_NAME... | How to implement simple sessions for Google App Engine? | Here is a very basic class for handling sessions on App Engine:
"""Lightweight implementation of cookie-based sessions for Google App Engine.
Classes:
Session
"""
import os
import random
import Cookie
from google.appengine.api import memcache
_COOKIE_NAME = 'app-sid'
_COOKIE_PATH = '/'
_SESSION_EXPIRE_TIME = 180 * ... | [
"Here is a suggestion for simplifying your implementation.\nYou are creating a randomized temporary key that you use as the session's key in the memcache. You note that you will be storing the session in the datastore as well (where it will have another key).\nWhy not randomize the session's datastore key, and the... | [
5,
0
] | [] | [] | [
"cookies",
"google_app_engine",
"python",
"security",
"session"
] | stackoverflow_0002560022_cookies_google_app_engine_python_security_session.txt |
Q:
Python creating a dictionary and swapping these into another file
I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like:
'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n',
'EB3128': ' "\t"yagE "\t\t"b0268 "\n',
'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n',
'EB3944': ' "\t"eutS "\... | Python creating a dictionary and swapping these into another file | I have two tab delimited .csv file. From one.csv I have created a dictionary which looks like:
'EB2430': ' "\t"idnD "\t"yjgV "\t"b4267 "\n',
'EB3128': ' "\t"yagE "\t\t"b0268 "\n',
'EB3945': ' "\t"maeB "\t"ypfF "\t"b2463 "\n',
'EB3944': ' "\t"eutS "\t"ypfE "\t"b2462 "\n',
I would like to insert the value of the diction... | [
"It looks like you could more usefully use the Python standard library csv module here. rather than perform the text processing parts youself \"manually\". E.g.:\nimport csv\nwith open(\"one.csv\", \"r\") as f:\n rows_one = list(csv.reader(f, delimiter='\\t'))\nwith open(\"second.csv\", \"r\") as g:\n rows_two =... | [
2,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002563088_dictionary_python.txt |
Q:
Python script to get the data from the flex application
I am making a simple Python CGI script that collects data(in xml format) from a flex application and I want to insert it into the mysql database .
In perl The script is looks like the following...
my @samplexml=$cgi->param("Items");
my $data=$xml->XMLin("@s... | Python script to get the data from the flex application | I am making a simple Python CGI script that collects data(in xml format) from a flex application and I want to insert it into the mysql database .
In perl The script is looks like the following...
my @samplexml=$cgi->param("Items");
my $data=$xml->XMLin("@samplexml");
foreach my $e(@{$data->{Group}})
{
my $sample... | [
"It should be fairly easy to convert this to a Python script. Setting the stage:\n\nPython has the cgi module.\nGet the Python-MySQL library (or an equivalent for whatever db you're using).\nUse Python's xml.etree to parse the incoming XML.\n\nYou'd write a Python script that'd read the XML from the CGI variables, ... | [
0,
0
] | [] | [] | [
"apache_flex",
"cgi",
"python"
] | stackoverflow_0002550637_apache_flex_cgi_python.txt |
Q:
Google App Engine (python): TemplateSyntaxError: 'for' statements with five words should end in 'reversed'
This is using the web app framework, not Django.
The following template code is giving me an TemplateSyntaxError: 'for' statements with five words should end in 'reversed' error when I try to render a dictio... | Google App Engine (python): TemplateSyntaxError: 'for' statements with five words should end in 'reversed' | This is using the web app framework, not Django.
The following template code is giving me an TemplateSyntaxError: 'for' statements with five words should end in 'reversed' error when I try to render a dictionary. I don't understand what's causing this error. Could somebody shed some light on it for me?
{% for code, na... | [
"\nThis is using the web app framework,\n not Django.\n\nBut framework apart, you must be using Django's templating -- and apparently in an old version, which does not support the \"automatic unpacking\" style of for -- probably the 0.96 version that's the default for App Engine. To use any part of more modern Dj... | [
13
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0002563365_django_django_templates_google_app_engine_python.txt |
Q:
Open Source Alternative to ASP.NET membership
I'm currently supporting a Python web app with increasingly complicated user/role/permission management requirements. Currently, we are rolling our own user, groups, permissions, etc. code and supporting database.
I'd like to find something like ASP.NET membership tha... | Open Source Alternative to ASP.NET membership | I'm currently supporting a Python web app with increasingly complicated user/role/permission management requirements. Currently, we are rolling our own user, groups, permissions, etc. code and supporting database.
I'd like to find something like ASP.NET membership that can help manage user authentication and authoriza... | [
"If you are looking for off site user authentication you might want to consider openid. People have added openid support to cherrypy. \nIf you are looking for more user management type code. I guess it depends on exactally what you are doing but others have done user management before, why not leverage off them. ... | [
1
] | [] | [] | [
"asp.net_membership",
"cherrypy",
"ldap",
"open_source",
"python"
] | stackoverflow_0002563403_asp.net_membership_cherrypy_ldap_open_source_python.txt |
Q:
Pylons check for cookie on every page load
I want to check whether or not a cookie is set with every page load in Pylons. Where's the best place to put this logic? Thanks!
A:
You can modify __call__ function in BaseController.
| Pylons check for cookie on every page load | I want to check whether or not a cookie is set with every page load in Pylons. Where's the best place to put this logic? Thanks!
| [
"You can modify __call__ function in BaseController.\n"
] | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002563528_pylons_python.txt |
Q:
Python urlparse, correct or incorrect?
Python's urlparse function parses an url into six components (scheme, netloc, path and others stuff)
Now I've found that parsing "example.com/path/file.ext" return no netloc but a path "example.com/path/file.ext".
Should't it be netloc = "example.com" and path = "/path/file.e... | Python urlparse, correct or incorrect? | Python's urlparse function parses an url into six components (scheme, netloc, path and others stuff)
Now I've found that parsing "example.com/path/file.ext" return no netloc but a path "example.com/path/file.ext".
Should't it be netloc = "example.com" and path = "/path/file.ext"?
Do we really need a "://" to determine ... | [
"Without the scheme://, there's no guarantee that example.com is a domain. You could have a directory called example.com. Similarly, you could have a url 'omfgroflmao/path/file.ext', how would you know if 'omfgroflmao' is a machine on the local network (i.e. a netloc) or whether it's meant to be a path component?\n... | [
6,
1
] | [] | [] | [
"python",
"urlparse"
] | stackoverflow_0002563961_python_urlparse.txt |
Q:
Python: Taking an array and break it into subarrays based on some criteria
I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31,... | Python: Taking an array and break it into subarrays based on some criteria | I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31, I'd like to have an array with 31 subarrays (assuming there is at least > 1 fil... | [
"If you need to split a list into list of lists by some criteria, have a look at itertools.groupby().\n",
"To get the files with the latest timestamps for each day, use a dict with days as keys and tuples of (filename, timestamp) as the values. Loop through all the files, and update the dict value for that day if... | [
5,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002563990_python.txt |
Q:
Integer to byte conversion
Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?
A:
Use bitwise mathematical operators,... | Integer to byte conversion | Say I've got an integer, 13941412, that I wish to separate into bytes (the number is actually a color in the form 0x00bbggrr). How would you do that? In c, you'd cast the number to a BYTE and then shift the bits. How do you cast to byte in Python?
| [
"Use bitwise mathematical operators, the \"bytes\" are already there:\ndef int_to_rgb(n):\n b = (n & 0xff0000) >> 16\n g = (n & 0x00ff00) >> 8\n r = (n & 0x0000ff)\n return (r, g, b)\n\n",
"You can bitwise & with 0xff to get the first byte, then shift 8 bits and repeat to get the other 3 bytes.\nEdit:... | [
13,
2,
0
] | [] | [] | [
"byte",
"casting",
"python"
] | stackoverflow_0002562308_byte_casting_python.txt |
Q:
Dynamic variable name in python
I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired.
field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)
where if funct() returns name would equal to
loc... | Dynamic variable name in python | I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired.
field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)
where if funct() returns name would equal to
locations = Locations.objects.filter(nam... | [
"You can create a dictionary, set the parameters and pass this to the function by unpacking the dictionary as keyword arguments:\nfield_name = funct()\nparams = {field_name + '__lte': arg1, # field_name should still contain string\n 'some_other_field_name': arg2}\n\nlocations = Locations.objects.filt... | [
11
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002564140_django_python.txt |
Q:
Server authorization with MD5 and SQL
I currently have a SQL database of passwords stored in MD5. The server needs to generate a unique key, then sends to the client. In the client, it will use the key as a salt then hash together with the password and send back to the server.
The only problem is that the the SQL ... | Server authorization with MD5 and SQL | I currently have a SQL database of passwords stored in MD5. The server needs to generate a unique key, then sends to the client. In the client, it will use the key as a salt then hash together with the password and send back to the server.
The only problem is that the the SQL DB has the passwords in MD5 already. Theref... | [
"You should use SSL to encrypt the connection, then send the password over plain text from the client. The server will then md5 and compare with the md5 hash in the database to see if they are the same. If so auth = success.\nMD5'ing the password on the client buys you nothing because a hacker with the md5 password... | [
1,
0
] | [] | [] | [
"authorization",
"database",
"md5",
"python",
"sql"
] | stackoverflow_0002564312_authorization_database_md5_python_sql.txt |
Q:
mysql-python stopped working
This is a rather dumb question but i'am looking at a bizarre situation.
I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source).
Anyway yesterday i wrote my enti... | mysql-python stopped working | This is a rather dumb question but i'am looking at a bizarre situation.
I am running fedora and have python 2.6.5 installed. The other day i installed MySQL-python using yum (because i do not have the setuptools module so i cannot build it from source).
Anyway yesterday i wrote my entire data access layer in python and... | [
"If all else fails, go to http://sourceforge.net/projects/mysql-python/ and install the package manually. This should work reliably.\n",
"Well it seems to be working if i run or debug something from within eclipse. As it has the 2.5 version set as the python interpreter.\nDoes anyone know how i can set which pyth... | [
1,
0
] | [] | [] | [
"configuration",
"installation",
"mysql",
"python"
] | stackoverflow_0002562673_configuration_installation_mysql_python.txt |
Q:
Python mysql check for duplicate before insert
here is the table
CREATE TABLE IF NOT EXISTS kompas_url
(
id BIGINT(20) NOT NULL AUTO_INCREMENT,
url VARCHAR(1000),
created_date datetime,
modified_date datetime,
PRIMARY KEY(id)
)
I am trying to do INSERT to kompas_url table only if url is not e... | Python mysql check for duplicate before insert | here is the table
CREATE TABLE IF NOT EXISTS kompas_url
(
id BIGINT(20) NOT NULL AUTO_INCREMENT,
url VARCHAR(1000),
created_date datetime,
modified_date datetime,
PRIMARY KEY(id)
)
I am trying to do INSERT to kompas_url table only if url is not exist yet
any idea?
thanks
| [
"You can either find out whether it's in there first, by SELECTing by url, or you can make the url field unique:\nCREATE TABLE IF NOT EXISTS kompas_url\n ...\n url VARCHAR(1000) UNIQUE,\n ...\n)\n\nThis will stop MySQL from inserting a duplicate row, but it will also report an error when you try and insert... | [
9
] | [] | [] | [
"insert",
"mysql",
"no_duplicates",
"python"
] | stackoverflow_0002564568_insert_mysql_no_duplicates_python.txt |
Q:
Web-based game in Python + Django and client browser polling
I am creating a text-based game that implements a basic model in which multiple (10+) players interact with data and one moderator watches them and sets certain environmental statistics that affect gameplay.
Recently I have begun to familiarize myself wi... | Web-based game in Python + Django and client browser polling | I am creating a text-based game that implements a basic model in which multiple (10+) players interact with data and one moderator watches them and sets certain environmental statistics that affect gameplay.
Recently I have begun to familiarize myself with Django. It seems to me that it would be an excellent tool for ... | [
"You could use long polling.\nAlso, if you're creating a multiplayer game, it might be much easier and more efficient to use a server that's designed for long polling and multi-user interaction instead of using a standard HTTP server and framework.\n",
"In addition to long polling mentioned by Matti, the HTTP ser... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002563742_django_python.txt |
Q:
Better use a tuple or numpy array for storing coordinates
I'm porting an C++ scientific application to python, and as I'm new to python, some problems come to my mind:
1) I'm defining a class that will contain the coordinates (x,y). These values will be accessed several times, but they only will be read after the ... | Better use a tuple or numpy array for storing coordinates | I'm porting an C++ scientific application to python, and as I'm new to python, some problems come to my mind:
1) I'm defining a class that will contain the coordinates (x,y). These values will be accessed several times, but they only will be read after the class instantiation. Is it better to use an tuple or an numpy a... | [
"In terms of memory consumption, numpy arrays are more compact than Python tuples.\nA numpy array uses a single contiguous block of memory. All elements of the numpy array must be of a declared type (e.g. 32-bit or 64-bit float.) A Python tuple does not necessarily use a contiguous block of memory, and the elements... | [
7,
3
] | [] | [] | [
"arrays",
"complex_numbers",
"numpy",
"python",
"tuples"
] | stackoverflow_0002563773_arrays_complex_numbers_numpy_python_tuples.txt |
Q:
Best way to find similar items in python
I have 1M numbers:N[], and 1 single number n, now I want to find in those 1M numbers that are similar to that single number, say an area of [n-10, n+10].
what's the best way in python to do this? Do I have to sort the 1M number and do an iteration?
A:
[x for x in N if n ... | Best way to find similar items in python | I have 1M numbers:N[], and 1 single number n, now I want to find in those 1M numbers that are similar to that single number, say an area of [n-10, n+10].
what's the best way in python to do this? Do I have to sort the 1M number and do an iteration?
| [
"[x for x in N if n - 10 <= x <= n + 10]\n",
"results=[x for x in numbers if x >= n-10 and x <= n+10]\n\n",
"Another solution:\nis_close_to_n = lambda x: n-10 <= x <= n+10\nresult = filter(is_close_to_n, N)\n\nGeneralizing a bit:\ndef is_close_to(n):\n f = lambda x: n-10 <= x <= n+10\n return f\n\nresult1... | [
3,
1,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0002564896_python_sorting.txt |
Q:
I want all three shapes on the same line...please help...!
#Top half of triangle
for rows in range (5):
for row in range (12):
print("-", end='')
print()
for row in range (5):
stars=0
while stars<=row:
print("*", end='')
stars=stars+1
print()
for row in ... | I want all three shapes on the same line...please help...! | #Top half of triangle
for rows in range (5):
for row in range (12):
print("-", end='')
print()
for row in range (5):
stars=0
while stars<=row:
print("*", end='')
stars=stars+1
print()
for row in range(5):
star=4
while star>=row:
print("*... | [
"shape1 = [12*'-' for i in range(5)] # segments of rectangle\nshape2 = [i*'*' + (5-i)*' ' for i in range(1,5+1)] # segments of 1st triangle\nshape3 = [(5-i)*' ' + i*'*' for i in range(1,5+1)] # segments of 2nd triangle \n\nfor line in zip(shape1, shape2, shape3):\n print(\" \".join(line))\... | [
3,
0
] | [] | [] | [
"nested_loops",
"python",
"python_3.x"
] | stackoverflow_0002564972_nested_loops_python_python_3.x.txt |
Q:
Control VLC from Python in Windows
I'm running VLC (a media player) in Windows 7. Is there way to control (as in: play, pause, set volume) a running instance of VLC from Python?
A:
Yes, you can control it via telnet (with telnetlib). There are also libvlc bindings, but I'm not sure you can use that to control an... | Control VLC from Python in Windows | I'm running VLC (a media player) in Windows 7. Is there way to control (as in: play, pause, set volume) a running instance of VLC from Python?
| [
"Yes, you can control it via telnet (with telnetlib). There are also libvlc bindings, but I'm not sure you can use that to control an existing VLC instance.\n"
] | [
4
] | [
"As a general alternative to already mentioned solutions it's good to know about pywinauto\nUPDATE:\nCheck out swapy for a way to with pywinauto more easily.\n"
] | [
-1
] | [
"python",
"vlc",
"windows"
] | stackoverflow_0002564815_python_vlc_windows.txt |
Q:
Pylons redirect to 404 error page
What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you!
A:
abort(404) as mentioned in the quickwiki tutorial. See the docs for abort.
A:
404 isn't something you redirect to; there's no distinct "404 page" with its own distinct UR... | Pylons redirect to 404 error page | What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you!
| [
"abort(404) as mentioned in the quickwiki tutorial. See the docs for abort.\n",
"404 isn't something you redirect to; there's no distinct \"404 page\" with its own distinct URL. It's a status code that you send back in the HTTP response, instead of 200 (the code for a normal successful response).\nActual redirec... | [
3,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002565324_pylons_python.txt |
Q:
Adjust OSX System Audio Volume in Python
I would like to adjust the system audio volume in OSX from a python script. This question about implementing keyboard shortcuts tells me how to do it in applescript, but I'd really like to do it from my python script without using os.system, popen, etc. Ideally I'd like t... | Adjust OSX System Audio Volume in Python | I would like to adjust the system audio volume in OSX from a python script. This question about implementing keyboard shortcuts tells me how to do it in applescript, but I'd really like to do it from my python script without using os.system, popen, etc. Ideally I'd like to ramp up the volume slowly with some python c... | [
"Use appscript to control the StandardAdditions scripting addition set volume command:\n>>> from osax import *\n>>> import time\n>>> sa = OSAX()\n>>> for i in range(50):\n... sa.set_volume(i*2)\n... time.sleep(1)\n... \n>>> \n\n"
] | [
1
] | [] | [] | [
"audio",
"macos",
"python",
"volume"
] | stackoverflow_0002565204_audio_macos_python_volume.txt |
Q:
How use the google maps hand cursor in Python?
I want to use the google maps hand cursor in Python but I don't know how to do it.
I've downloaded the cursor but I only get to use the hand open, I also have a event that "closes" the hand when clicked but I don't know how can I change the style cursor on it.
I say t... | How use the google maps hand cursor in Python? | I want to use the google maps hand cursor in Python but I don't know how to do it.
I've downloaded the cursor but I only get to use the hand open, I also have a event that "closes" the hand when clicked but I don't know how can I change the style cursor on it.
I say this because the google maps hand cursor has two styl... | [
"Did you try just changing the cursor, i.e:\nmyFrame.SetCursor(closedCursor)\n\nIn the event handler for mouse-down? Then for mouse-up change it back again. myFrame is your container wx.Frame, and I suppose you already know how to load a cursor from a file.\n",
"Use two cursors and change them on events as they n... | [
0,
0
] | [] | [] | [
"cursor",
"python",
"wxpython"
] | stackoverflow_0002565776_cursor_python_wxpython.txt |
Q:
Apply function to one element of a list in Python
I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python.
For example, for the following input:
inp = ("hello", "my", "friend")
I would like to be able to get the following output:
out = (... | Apply function to one element of a list in Python | I'm looking for a concise and functional style way to apply a function to one element of a tuple and return the new tuple, in Python.
For example, for the following input:
inp = ("hello", "my", "friend")
I would like to be able to get the following output:
out = ("hello", "MY", "friend")
I came up with two solutions ... | [
"Here is a version that works on any iterable and returns a generator:\n>>> inp = (\"hello\", \"my\", \"friend\")\n>>> def apply_nth(fn, n, iterable):\n... return (fn(x) if i==n else x for (i,x) in enumerate(iterable))\n... \n>>> tuple(apply_nth(str.upper, 1, inp))\n('hello', 'MY', 'friend')\n\nYou can extend th... | [
7,
2,
2,
2,
0,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0002565249_list_comprehension_python.txt |
Q:
Q on Python serialization/deserialization
What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]):
enum { apple, orange } VariantTag;
struct {
uint16 number;
opaque string<0..10>; /* variable ... | Q on Python serialization/deserialization | What chances do I have to instantiate, keep and serialize/deserialize to/from binary data Python classes reflecting this pattern (adopted from RFC 2246 [TLS]):
enum { apple, orange } VariantTag;
struct {
uint16 number;
opaque string<0..10>; /* variable length */
} V1;
struct {
uint32 nu... | [
"Two suggestions:\n\nFor the variable length structure use a fixed format\nand just slice the result.\nUse struct.Struct\n\ne.g. If I've understood your formats correctly (is the length byte that appeared in your example but wasn't mentioned originally present in the other variant also?)\n>>> import binascii\n>>> i... | [
0
] | [] | [] | [
"binary",
"python",
"serialization"
] | stackoverflow_0002555705_binary_python_serialization.txt |
Q:
Matplotlib digit grouping (decimal separator)
Basically, when generating plots with matplotlib, The scale on the y-axis goes into the millions. How do I turn on digit grouping (i.e. so that 1000000 displays as 1,000,000) or turn on the decimal separator?
A:
I don't think there's a built-in function to do this. ... | Matplotlib digit grouping (decimal separator) | Basically, when generating plots with matplotlib, The scale on the y-axis goes into the millions. How do I turn on digit grouping (i.e. so that 1000000 displays as 1,000,000) or turn on the decimal separator?
| [
"I don't think there's a built-in function to do this. (That's what i thought after i read your Q; i just checked and couldn't find one in the Documentation). \nIn any event, it's easy to roll your own.\n(Below is a complete example--ie, it will generate an mpl plot with one axis having commified tick labels--altho... | [
3
] | [] | [] | [
"data_visualization",
"matplotlib",
"python"
] | stackoverflow_0002564362_data_visualization_matplotlib_python.txt |
Q:
In Python, how to make data members visible to subclasses if not known when initializing an object?
The title is a bit long, but it should be pretty straightforward for someone well-aware of python.
I'm a python newbie. So, maybe i'm doing things in the wrong way.
Suppose I have a class TreeNode
class TreeNode(Nod... | In Python, how to make data members visible to subclasses if not known when initializing an object? | The title is a bit long, but it should be pretty straightforward for someone well-aware of python.
I'm a python newbie. So, maybe i'm doing things in the wrong way.
Suppose I have a class TreeNode
class TreeNode(Node):
def __init__(self, name, id):
Node.__init__(self, name, id)
self.children = []
... | [
"You could just initialize it with a default value:\nself.father = None\n\nThat way the attribute will at least be recognized. And this is valid since at this point there really is no father.\n",
"In response to your statement on Justin's answer, try this:\nprint ' Name %s Father %s '%(str(self.name), str(self.fa... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002566840_python.txt |
Q:
No module named difflib
I want to execute python code from C# with following code.
static void Main(string[] args)
{
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py");
source.Execute();
}
I have the pr... | No module named difflib | I want to execute python code from C# with following code.
static void Main(string[] args)
{
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile(@"F:\Script\extracter.py");
source.Execute();
}
I have the problem at line source.Execute(... | [
"This looks like your engine does not have access to Python standard library - it does not see difflib.py. Either fix the sys.path or copy difflib.py from Python 2.6 to f:\\script folder.\nre and itertools modules are written in C# and are part of IronPython.modules.dll - that's why importing them work.\n"
] | [
3
] | [] | [] | [
"c#",
"ironpython",
"python",
"scriptengine"
] | stackoverflow_0002564870_c#_ironpython_python_scriptengine.txt |
Q:
MacPorts manual port location
I am installing one library for python from MacPorts. But macports version of the library is older than actual development svn version. Is it possible to specify a custom location for a port installation in MacPorts so I could install latest library from the developer's site?
A:
Hav... | MacPorts manual port location | I am installing one library for python from MacPorts. But macports version of the library is older than actual development svn version. Is it possible to specify a custom location for a port installation in MacPorts so I could install latest library from the developer's site?
| [
"Have a look here, you have to install a local portfile repositories.\n",
"If you simply want the latest version, couldn't you just not install the old version?\nIf you are planning to build and deploy the svn version yourself and want to test it while not removing the old version, you might find virtualenv usefu... | [
1,
0
] | [] | [] | [
"macports",
"python"
] | stackoverflow_0002566357_macports_python.txt |
Q:
"AttributeError: fileno" when attemping to import from pyevolve
I just installed Pyevolve using easy_install and I am getting errors trying to run my first program. I first tried copy and pasting the source code of the first example but this is what I receive when I attempt to run it:
Traceback (most recent ca... | "AttributeError: fileno" when attemping to import from pyevolve | I just installed Pyevolve using easy_install and I am getting errors trying to run my first program. I first tried copy and pasting the source code of the first example but this is what I receive when I attempt to run it:
Traceback (most recent call last):
File "/home/corey/CTest/first_intro.py", line 3, in
... | [
"Have you tried to check out the Development version ? It's near of the RC1, so it is stable right now:\nsvn co https://pyevolve.svn.sourceforge.net/svnroot/pyevolve/trunk pyevolve\nYour problem seems to be the paths, try uncompressing the \"egg\" file and put the \"pyevolve\" directory in the site-packages or insi... | [
1
] | [] | [] | [
"pyevolve",
"python"
] | stackoverflow_0002565061_pyevolve_python.txt |
Q:
Python In-memory table
What is the right way to forming in-memory table in python with direct lookups for rows and columns.I thought of using dict of dicts this way,
class Table(dict):
def __getitem__(self, key):
if key not in self:
self[key]={}
return dict.__getitem__(self, key)
t... | Python In-memory table | What is the right way to forming in-memory table in python with direct lookups for rows and columns.I thought of using dict of dicts this way,
class Table(dict):
def __getitem__(self, key):
if key not in self:
self[key]={}
return dict.__getitem__(self, key)
table = Table()
table['row1']... | [
"I'd use an in-memory database with SQLite for this. The sqlite module is even in the standard library since Python 2.5, which means this doesn't even add much to your requirements.\n",
"\nNow how do I do lookup if 'column1'\n has 'value11'\n\nany(arow['column1'] == 'value11' for arow in table.iteritems())\n\nI... | [
7,
7,
0,
0
] | [] | [] | [
"python",
"row"
] | stackoverflow_0002565415_python_row.txt |
Q:
Cassandra database, which python interface?
I'm going to write the web portal using Cassandra databases.
Can you advise me which python interface to use? thrift, lazygal or pycassa?
Are there any benefits to use more complicated thrift then cleaner pycassa?
What about performace - is the same (all of them are just... | Cassandra database, which python interface? | I'm going to write the web portal using Cassandra databases.
Can you advise me which python interface to use? thrift, lazygal or pycassa?
Are there any benefits to use more complicated thrift then cleaner pycassa?
What about performace - is the same (all of them are just the layer)?
Thanks for any advice.
| [
"Use pycassa if you don't know what to use.\nUse lazyboy if you want it to maintain indexes for you. It's significantly more complex.\n"
] | [
4
] | [] | [] | [
"cassandra",
"database",
"python",
"thrift"
] | stackoverflow_0002561804_cassandra_database_python_thrift.txt |
Q:
Python web development framework for python 3.1 user
I have been learning python for some time now. While starting this "learning python" endeavor I decided to learn the latest and greatest 3.1 version of python. I regret this decision now because I wanted to try my hands on some of the python web development fram... | Python web development framework for python 3.1 user | I have been learning python for some time now. While starting this "learning python" endeavor I decided to learn the latest and greatest 3.1 version of python. I regret this decision now because I wanted to try my hands on some of the python web development frameworks & it looks like many of them do not support 3.1 yet... | [
"How about trying Python2.7?, many of python 3.x features are backported to 2.7 recently, like OrderedDict, faster io modules, set comprehensions, dict comprehensions, etc...\nAnd Python 2.7 is running no problem at all with django 1.2 trunk version in my experience.\nIn my opinion, learning new framework will take... | [
5,
3,
2,
1,
1
] | [] | [] | [
"python",
"web_frameworks"
] | stackoverflow_0002564822_python_web_frameworks.txt |
Q:
Decorator for determining HTTP response from a view
I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far:
from django.shortcuts im... | Decorator for determining HTTP response from a view | I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far:
from django.shortcuts import render_to_response
from django.http import HttpRespo... | [
"You just need to call view from within your decorator and use the context returned from that.\nif request.method == \"GET\":\n context = view(*args, **kwargs)\n try:\n if request.GET['raw'] == \"1\":\n render = HttpResponse(\n render_to_string(template, context),\n ... | [
0,
0
] | [] | [] | [
"decorator",
"django",
"python"
] | stackoverflow_0002567570_decorator_django_python.txt |
Q:
Regex matching very slow
I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).
I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.
So, my current patt... | Regex matching very slow | I am trying to parse a PDF to extract the text from it (please don't suggest any libraries to do this, as this is part of learning the format).
I have already handled deflating it to put it in the alphanumeric format. I now need to extract the text from the text blocks.
So, my current pattern is BT.*?\((.*?)\).*?ET (wi... | [
"How many of these blocks might appear in a document?\nOften slow Regex execution is the result of catastrophic backtracking, as described here: http://www.regular-expressions.info/catastrophic.html\nI don't know what regex technology you're using, but you could try to use lookaround assertions, as described here:\... | [
4,
1,
0,
0,
0,
0
] | [] | [] | [
"pdf",
"python",
"regex"
] | stackoverflow_0002563329_pdf_python_regex.txt |
Q:
Python class structure ... prep() method?
We have a metaclass, a class, and a child class for an alert system:
class AlertMeta(type):
"""
Metaclass for all alerts
Reads attrs and organizes AlertMessageType data
"""
def __new__(cls, base, name, attrs):
new_class = super(AlertMeta, cls).__new__(cls, base, na... | Python class structure ... prep() method? | We have a metaclass, a class, and a child class for an alert system:
class AlertMeta(type):
"""
Metaclass for all alerts
Reads attrs and organizes AlertMessageType data
"""
def __new__(cls, base, name, attrs):
new_class = super(AlertMeta, cls).__new__(cls, base, name, attrs)
# do stuff to new_class
retu... | [
"For our particular issue, we're making dequeue() a classmethod.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002567238_python.txt |
Q:
Nested generator functions in python
Consider a tuple v = (a,b,c) and a generator function generate(x) which receives an item from the tuple and generates several options for each item.
What is the pythonic way of generating a set of all the possible combinations of the result of generate(x) on each item in the tu... | Nested generator functions in python | Consider a tuple v = (a,b,c) and a generator function generate(x) which receives an item from the tuple and generates several options for each item.
What is the pythonic way of generating a set of all the possible combinations of the result of generate(x) on each item in the tuple?
I could do this:
v = (a,b,c)
for d in... | [
"Python 2.6 has the function itertools.product() that does what you want:\nimport itertools\nv = (a, b, c)\nfor d, e, f in itertools.product(*(generate(x) for x in v)):\n print d, e, f\n\nFrom the docs:\n\nCartesian product of input iterables.\nEquivalent to nested for-loops in a\n generator expression. For examp... | [
8
] | [] | [] | [
"generator",
"list_comprehension",
"python"
] | stackoverflow_0002568396_generator_list_comprehension_python.txt |
Q:
Avoiding thumbnail name collisions with sorl-thumbnail
Understanding that I should probably just dig into the source to come up with a solution, I'm wondering if anyone has come up with a tactic for dealing with this.
In my project, I have a lot of images being generated outside of the application. I'm isolating ... | Avoiding thumbnail name collisions with sorl-thumbnail | Understanding that I should probably just dig into the source to come up with a solution, I'm wondering if anyone has come up with a tactic for dealing with this.
In my project, I have a lot of images being generated outside of the application. I'm isolating them on the filesystem based on a model's pk.
For example, a... | [
"Ah hah.\nWell it looks like the solution was staring me in the face the whole time.\nhttp://thumbnail.sorl.net/docs/#this-just-doesn-t-cover-my-cravings\nLooks like I'm going to subclass sorl.thumbnail.main.DjangoThumbnail and re-implement the _get_relative_thumbnail method to allow me to inject a template driven ... | [
1
] | [] | [] | [
"django",
"python",
"sorl_thumbnail"
] | stackoverflow_0002568134_django_python_sorl_thumbnail.txt |
Q:
Subprocess statement works in python console but not work in Serverdensity plugin?
in the python console the following statement works perfectly fine (i guess using eval that way is not really good, but its just for testing purpose in this case and will be replaced with proper parsing)
$ python
>>> import subproce... | Subprocess statement works in python console but not work in Serverdensity plugin? | in the python console the following statement works perfectly fine (i guess using eval that way is not really good, but its just for testing purpose in this case and will be replaced with proper parsing)
$ python
>>> import subprocess
>>> r = subprocess.Popen(['/pathto/plugin1.rb'], stdout=subprocess.PIPE, close_fds=Tr... | [
"Do you have subprocess imported in the module? Also what error are you getting could you post the error message ?\n",
"After switching my dev box (maybe because of the different python version?) i finally was able to get some proper error output.\nThen it was rather simple: I really just needed to import the mis... | [
0,
0
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0002560754_popen_python_subprocess.txt |
Q:
Python: why does `random.randint(a, b)` return a range inclusive of `b`?
It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like range(...).
Is there any reason for this apparent inconsistency?
A:
I tried to get to the bottom of this by e... | Python: why does `random.randint(a, b)` return a range inclusive of `b`? | It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like range(...).
Is there any reason for this apparent inconsistency?
| [
"I tried to get to the bottom of this by examining some old sources. I suspected that randint was implemented before Python's long integer: meaning that if you wanted a random number that included INT_MAX, you would have needed to call random.randrange(0, INT_MAX + 1) which would have overflowed and resulted in ar... | [
92,
16,
9,
3
] | [] | [] | [
"boundary",
"integer",
"python",
"random"
] | stackoverflow_0002568783_boundary_integer_python_random.txt |
Q:
urllib2 in Python 2.6.4: Any way to override windows hosts file?
I am using the urllib2 module in Python 2.6.4, running in Windows XP, to access a URL. I am making a post request, that does not involve cookies or https or anything too complicated. The domain is redirected in my C:\WINDOWS\system32\drivers\etc\host... | urllib2 in Python 2.6.4: Any way to override windows hosts file? | I am using the urllib2 module in Python 2.6.4, running in Windows XP, to access a URL. I am making a post request, that does not involve cookies or https or anything too complicated. The domain is redirected in my C:\WINDOWS\system32\drivers\etc\hosts file. However, I would like the request from urllib2 to go to the "r... | [
"Connect to the IP address and pass the Host header manually.\n"
] | [
5
] | [] | [] | [
"hosts",
"ip",
"python",
"urllib2",
"windows"
] | stackoverflow_0002569155_hosts_ip_python_urllib2_windows.txt |
Q:
Using pam_python in a script running with mod_python
I would like to develop a web interface to allow users of a Linux system to do certain tasks related to their account. I decided to write the backend of the site using Python and mod_python on Apache. To authenticate the users, I thought I could use python_pam t... | Using pam_python in a script running with mod_python | I would like to develop a web interface to allow users of a Linux system to do certain tasks related to their account. I decided to write the backend of the site using Python and mod_python on Apache. To authenticate the users, I thought I could use python_pam to query the PAM service. I adapted the example bundled wit... | [
"It seems like you have to enable Apache to use PAM authentication. Take a look at this site: http://www.debianhelp.co.uk/apachepam.htm\nYou might want to take a look at this site too : http://inming.net/?p=86\n"
] | [
0
] | [] | [] | [
"linux",
"mod_python",
"pam",
"python"
] | stackoverflow_0002567705_linux_mod_python_pam_python.txt |
Q:
wxPython: Load font from file
I'm making a wxPython app, and I want to use some non-standard font that I have on file. How do I do this?
A:
The Win32 API you need is called AddFontResource (you'll also want to use RemoveFontResource when you're done with a font). I haven't been able to find a python wrapper for... | wxPython: Load font from file | I'm making a wxPython app, and I want to use some non-standard font that I have on file. How do I do this?
| [
"The Win32 API you need is called AddFontResource (you'll also want to use RemoveFontResource when you're done with a font). I haven't been able to find a python wrapper for this function, so you'll need to use ctypes or equivalent to access the API directly. Once the font has been added, it should be accessible ... | [
0
] | [] | [] | [
"fonts",
"python",
"wxpython"
] | stackoverflow_0002569085_fonts_python_wxpython.txt |
Q:
Is it possible to use a back reference to specify the number of replications in a regular expression?
Is it possible to use a back reference to specify the number of replications in a regular expression?
foo= 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.G+3AGGa.'
The substrings that start with '+[0-9]' followed by '[A-z]{n}.' ne... | Is it possible to use a back reference to specify the number of replications in a regular expression? | Is it possible to use a back reference to specify the number of replications in a regular expression?
foo= 'ADCKAL+2AG.+2AG.+2AG.+2AGGG+.G+3AGGa.'
The substrings that start with '+[0-9]' followed by '[A-z]{n}.' need to be replaced with simply '+' where the variable n is the digit from earlier in the substring. Can tha... | [
"No, you cannot use back-references as quantifiers. A workaround is to construct a regular expression that can handle each of the cases in an alternation.\nimport re\n\nfoo = 'ADCKAL+2AG.+2AG.+2AG.+2AGGG^+.+G+3AGGa4.'\npattern = '|'.join('\\+%s[ACGTNacgtn]{%s}.' % (i, i) for i in range(1, 10))\nregex = re.compile(p... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002569418_python_regex.txt |
Q:
How to generate a mixed-case hash in Python?
I am having a hard time figuring out a reasonable way to generate a mixed-case hash in Python.
I want to generate something like: aZeEe9E
Right now I'm using MD5, which doesn't generate case-sensitive hashes.
Do any of you know how to generate a hash value consisting of... | How to generate a mixed-case hash in Python? | I am having a hard time figuring out a reasonable way to generate a mixed-case hash in Python.
I want to generate something like: aZeEe9E
Right now I'm using MD5, which doesn't generate case-sensitive hashes.
Do any of you know how to generate a hash value consisting of upper- and lower- case characters + numbers?
-
Ok... | [
"you can base64 encode the output of the hash. This has a couple of additional characters beyond those you mentioned.\n",
"Maybe you can use base64-encoded hashes?\n"
] | [
3,
3
] | [] | [] | [
"hash",
"mixed_case",
"python"
] | stackoverflow_0002569503_hash_mixed_case_python.txt |
Q:
Python and MySQL
Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python?
Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additi... | Python and MySQL | Is there an easy way (without downloading any plugins) to connect to a MySQL database in Python?
Also, what would be the difference from calling a PHP script to retrieve the data from the database and hand it over to Python and importing one of these third-parties plugins that requires some additional software in the s... | [
"You just need the MySQL for Python module that is Python DB API 2.0 compliant.\nI don't know why wouldn't you want to install it. If you are worried about it being too complex to install, there are eggs to make it easy to install.\nOnce installed, you just use it like\n>>> import MySQLdb\n>>> db=MySQLdb.connect(ho... | [
2
] | [
"If you don't want to download the python libraries to connect to MySQL, the effective answer is no, not trivially. \n",
"No, there is no way that I've ever heard of or can think of to connect to a MySQL database with vanilla python. Just install the MySqldb python package-\nYou can typically do:\n\nsudo easy_i... | [
-1,
-1
] | [
"mysql",
"php",
"python"
] | stackoverflow_0002569427_mysql_php_python.txt |
Q:
How do I most efficienty check the unique elements in a list?
let's say I have a list
li = [{'q':'apple','code':'2B'},
{'q':'orange','code':'2A'},
{'q':'plum','code':'2A'}]
What is the most efficient way to return the count of unique "codes" in this list?
In this case, the unique codes is 2, because o... | How do I most efficienty check the unique elements in a list? | let's say I have a list
li = [{'q':'apple','code':'2B'},
{'q':'orange','code':'2A'},
{'q':'plum','code':'2A'}]
What is the most efficient way to return the count of unique "codes" in this list?
In this case, the unique codes is 2, because only 2B and 2A are unique.
I could put everything in a list and comp... | [
"Probably the most efficient simple way is to create a set of the codes, which will filter out uniques, then get the number of elements in that set:\ncount = len(set(d[\"code\"] for d in li))\n\nAs always, I advise to not worry about this kind of efficiency unless you've measured your performance and seen that it's... | [
8
] | [] | [] | [
"dictionary",
"list",
"performance",
"python"
] | stackoverflow_0002569578_dictionary_list_performance_python.txt |
Q:
I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website
I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc.
In the end I got down to this.
stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 3... | I'm doing a lot of lists and dictionary sorting...and this is causing memory errors in Python website | I retrieved data from the log table in my database. Then I started finding unique users, comparing/sorting lists, etc.
In the end I got down to this.
stats = {'2010-03-19': {'date': '2010-03-19', 'unique_users': 312, 'queries': 1465}, '2010-03-18': {'date': '2010-03-18', 'unique_users': 329, 'queries': 1659}, '2010-03-... | [
"If you only want the values you could just do:\nmylist = stats.values()\n\nIf you need the key - value pair you should iterate the dict's items:\nmylist = []\nfor k,v in stats.iteritems():\n mylist.append(v)\n\nIn the code in your question you are just iterating over the dicts keys. \nSince you assign a single ... | [
7,
5,
1
] | [] | [] | [
"dictionary",
"list",
"optimization",
"performance",
"python"
] | stackoverflow_0002569677_dictionary_list_optimization_performance_python.txt |
Q:
downloading archives response corrupts files
wrapper = FileWrapper(file("C:/pics.zip"))
content_type = mimetypes.guess_type(result.files)[0]
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize("C:/pics.zip")
response['Cont... | downloading archives response corrupts files | wrapper = FileWrapper(file("C:/pics.zip"))
content_type = mimetypes.guess_type(result.files)[0]
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize("C:/pics.zip")
response['Content-Disposition'] = "attachment; filename=pics.zip... | [
"The problem is that you're not reading it as a binary file :)\nThis should work:\nwrapper = FileWrapper(file(\"C:/pics.zip\", 'rb'))\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002569875_django_python.txt |
Q:
How come I get a timed-out when I try to download something off my own domain?
def download(source_url):
socket.setdefaulttimeout(10)
agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/... | How come I get a timed-out when I try to download something off my own domain? | def download(source_url):
socket.setdefaulttimeout(10)
agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U; en)']
ree = urllib2.Request(source_url)
ree.add_hea... | [
"This will fail if you're running the development server, since it's single-threaded and it's busy serving the original request. Use mod_wsgi or strap on something like CherryPy if you want it to work.\n",
"When you say \"your own domain\", are you hitting it from inside a NAT firewall?\nSomething like this?\n123... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002569886_django_python.txt |
Q:
Can I filter a django model with a python list?
Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people:
l = ['Bob','Dave','Jane']
I would like to return a list of all Person records where the first name is not in the list of names defined in l.
What is the most py... | Can I filter a django model with a python list? | Say I have a model object 'Person' defined, which has a field called 'Name'. And I have a list of people:
l = ['Bob','Dave','Jane']
I would like to return a list of all Person records where the first name is not in the list of names defined in l.
What is the most pythonic way of doing this?
EDIT: After thinking about ... | [
"This should work:\nPerson.objects.exclude(name__in=['Bob','Dave','Jane'])\n",
"Renaming l for readability:\nnames = ['Bob','Dave','Jane']\n\nPerson.objects.[exclude][1](Name__[in][2]=names)\n\nUPDATE 1: Answer to the second question (in your 'EDIT' paragraph):\npresent = Person.objects.values_list('Name', flat=T... | [
4,
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002569982_django_django_models_python.txt |
Q:
Error in python - don't understand
I'm creating a game, and am quite new to Python generally.
I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it.
It seemed to be working, but every now and then it wouldn't work corr... | Error in python - don't understand | I'm creating a game, and am quite new to Python generally.
I created a function 'descriptionGenerator()' which generates a description for characters and objects either randomly or using variables passed to it.
It seemed to be working, but every now and then it wouldn't work correctly. So i placed it in a loop, and it ... | [
"You define height_string inside if/else statements:\nif float(height) > 1.8:\n height_string = 'tall'\n if float(height) > 2:\n height_string = 'very tall'\nelif float(height) < 1.8 and float(height) > 1.5:\n height_string = 'average'\nelif float(height) < 1.5:\n height_string = 'short'\n if ... | [
3,
2
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0002570023_macos_python.txt |
Q:
Should I mix wxpython and pyobjc?
I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g.
import Cocoa
import wx
app = wx.PySimpleApp()
frame = wx.Frame(None, title="mac alert test")
app.SetTopWind... | Should I mix wxpython and pyobjc? | I have a wxPython based app which I am porting to Mac OS X, in that I need to show some alerts which should look like native mac alerts, so I am using pyobjc for that e.g.
import Cocoa
import wx
app = wx.PySimpleApp()
frame = wx.Frame(None, title="mac alert test")
app.SetTopWindow(frame)
frame.Show()
def onclick(eve... | [
"One possible question to ask; I believe you must be using wx version for Mac that rests atop Carbon, because I think the Cocoa version hasn't been released yet. Once the cocoa version is released (for wx) then I would think there would have to be \"fewer\" issues. A mix of carbon and cocoa sounds problematic to ... | [
0,
0,
0
] | [] | [] | [
"objective_c",
"pyobjc",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0002561188_objective_c_pyobjc_python_wxpython_wxwidgets.txt |
Q:
Calculating Nearest Match to Mean/Stddev Pair With LibSVM
I'm new to SVMs, and I'm trying to use the Python interface to libsvm to classify a sample containing a mean and stddev. However, I'm getting nonsensical results.
Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the sim... | Calculating Nearest Match to Mean/Stddev Pair With LibSVM | I'm new to SVMs, and I'm trying to use the Python interface to libsvm to classify a sample containing a mean and stddev. However, I'm getting nonsensical results.
Is this task inappropriate for SVMs or is there an error in my use of libsvm? Below is the simple Python script I'm using to test:
#!/usr/bin/env python
# Si... | [
"The problem seems to be coming from combining multiclass prediction with probability estimates.\nIf you configure your code not to make probability estimates, it actually works, e.g.:\n<snip>\n# Test classifiers.\nkernels = [LINEAR, POLY, RBF]\nkname = ['linear','polynomial','rbf']\ncorrect = defaultdict(int)\nfor... | [
5,
3
] | [] | [] | [
"artificial_intelligence",
"libsvm",
"machine_learning",
"python",
"svm"
] | stackoverflow_0002567483_artificial_intelligence_libsvm_machine_learning_python_svm.txt |
Q:
Searching text for geonames
which part of huge package nltk I must study and use, if I need mark geonames in text?
A:
You'll want to use their named entity recognizer nltk.ne_chunk.
Once the text is tagged you'll want to look for phrases labeled LOC (location) and GPE (Geo-political Entity).
| Searching text for geonames | which part of huge package nltk I must study and use, if I need mark geonames in text?
| [
"You'll want to use their named entity recognizer nltk.ne_chunk. \nOnce the text is tagged you'll want to look for phrases labeled LOC (location) and GPE (Geo-political Entity).\n"
] | [
2
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0002568963_nlp_nltk_python.txt |
Q:
SECURITY Flaws in this design for User authentication
SECURITY Flaws in this design for User authentication.
From: http://wiki.pylonshq.com/display/pylonscookbook/Simple+Homegrown+Authentication
Note:
a. Project follows the MVC pattern.
b. Only a user with a valid username and password is allowed submit s... | SECURITY Flaws in this design for User authentication | SECURITY Flaws in this design for User authentication.
From: http://wiki.pylonshq.com/display/pylonscookbook/Simple+Homegrown+Authentication
Note:
a. Project follows the MVC pattern.
b. Only a user with a valid username and password is allowed submit something.
Design:
a. Have a base controller from which ... | [
"I prefer approach with decorating functions that require authentication because it does not require typing action name 2 times - in the function definition and in requires_auth list. In that case you can mistype action name and it would not be noticed by interpreter.\nDecorating actions does not have this problem:... | [
1
] | [] | [] | [
"authentication",
"pylons",
"python"
] | stackoverflow_0002567893_authentication_pylons_python.txt |
Q:
Counting problem: possible sudoko tables?
I'm working on a sudoko solver (python). my method is using a game tree and explore possible permutations for each set of digits by DFS Algorithm.
in order to analyzing problem, i want to know what is the count of possible valid and invalid sudoko tables?
-> a 9*9 table t... | Counting problem: possible sudoko tables? | I'm working on a sudoko solver (python). my method is using a game tree and explore possible permutations for each set of digits by DFS Algorithm.
in order to analyzing problem, i want to know what is the count of possible valid and invalid sudoko tables?
-> a 9*9 table that have 9 one, 9 two, ... , 9 nine.
(this isn'... | [
"The number of valid Sudoku solution grids for the standard 9×9 grid was calculated by Bertram Felgenhauer and Frazer Jarvis in 2005 to be 6,670,903,752,021,072,936,960.\nMathematics of Sudoku | \nsource\nI think problem with your solution is that deleting 9 cells each time from available cells does not necessarily... | [
2,
1,
1
] | [] | [] | [
"algorithm",
"discrete_mathematics",
"math",
"python"
] | stackoverflow_0002570799_algorithm_discrete_mathematics_math_python.txt |
Q:
Text-based game graphics in Python
I'm pretty new to programming, and I'm creating a simple text-based game.>
I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc.
Is there a graphics module well suited to this?
I'm using Mac, but I would like it to... | Text-based game graphics in Python | I'm pretty new to programming, and I'm creating a simple text-based game.>
I'm wondering if there is a simple way to create my own terminal-type window with which I can place coloured input etc.
Is there a graphics module well suited to this?
I'm using Mac, but I would like it to work on Windows as well
Thanks
| [
"You could use the termcolor library - it that what you're looking for?\nOn Windows things are trickier. See this SO answer - you should resort to win32console and some ctypes. The answer has some code and links to other articles.\n",
"The Tkinter Text Widget will do what you ask. the IDLE main window is implemen... | [
2,
2,
1
] | [] | [] | [
"graphics",
"python",
"terminal",
"textbox"
] | stackoverflow_0002570377_graphics_python_terminal_textbox.txt |
Q:
Optimising RSS parsing on App Engine to avoid high CPU warnings
I'm pulling some RSS feeds into a datastore in App Engine to serve up to an iPhone app. I use cron to schedule updating the RSS every x minutes. Each task only parses one RSS feed (which has 15-20 items). I frequently get warnings about high CPU usage... | Optimising RSS parsing on App Engine to avoid high CPU warnings | I'm pulling some RSS feeds into a datastore in App Engine to serve up to an iPhone app. I use cron to schedule updating the RSS every x minutes. Each task only parses one RSS feed (which has 15-20 items). I frequently get warnings about high CPU usage in the App Engine dashboard, so I'm looking for ways to optimise my ... | [
"Outsource feed parsing via for example superfeedr\nYou could also look into superfeedr.com. They have a reasonable free quota/paying plans. They will do the polling(within 15 minutes you get updates) for you/etc. If the feeds also support pubsubhubbub, then you will receive the feeds in realtime! This video will e... | [
4,
1,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002563568_google_app_engine_python.txt |
Q:
What do the arguments "name__icontains" and "description__icontains" mean in a Django query filter?
maps = (maps.filter(name__icontains=search_terms) |
maps.filter(description__icontains=search_terms))
I can't find the meaning of these filter arguments.
A:
It's a case-insensitive containment test.
E... | What do the arguments "name__icontains" and "description__icontains" mean in a Django query filter? | maps = (maps.filter(name__icontains=search_terms) |
maps.filter(description__icontains=search_terms))
I can't find the meaning of these filter arguments.
| [
"It's a case-insensitive containment test.\nExample:\nEntry.objects.get(headline__icontains='Lennon')\n\nSQL equivalent:\nSELECT ... WHERE headline ILIKE '%Lennon%';\n\n\nIn your case the code says maps should be True if either the name or the description field contains the value of search_terms.\n",
"xxx_icontai... | [
22,
2
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0002571149_django_django_queryset_python.txt |
Q:
How to convert tag-and-username-like text into proper links in a twitter message?
I'm writing a twitter-like note-taking web app.
In a page the latest 20 notes of the user will be listed,
and when the user scroll to the bottom of the browser window more items will be loaded and rendered.
The initial 20 notes are ... | How to convert tag-and-username-like text into proper links in a twitter message? | I'm writing a twitter-like note-taking web app.
In a page the latest 20 notes of the user will be listed,
and when the user scroll to the bottom of the browser window more items will be loaded and rendered.
The initial 20 notes are part of the generated html of my django template, but the other dynamically loaded item... | [
"There's a couple of pieces to consider here. On the server side, you have to be able to maintain what \"chunk\" of the notes list the user is on. The easiest way to do this is probably the Django paginator. It works basically by taking a QuerySet, setting a count for the number of items, then giving it the \"pa... | [
2,
1,
0
] | [] | [] | [
"django",
"python",
"twitter"
] | stackoverflow_0002570193_django_python_twitter.txt |
Q:
Python beautiful soup arguments
I have this code that fetches some text from a page using BeautifulSoup
soup= BeautifulSoup(html)
body = soup.find('div' , {'id':'body'})
print body
I would like to make this as a reusable function that takes in some htmltext and the tags to match it like the following
def parse(h... | Python beautiful soup arguments | I have this code that fetches some text from a page using BeautifulSoup
soup= BeautifulSoup(html)
body = soup.find('div' , {'id':'body'})
print body
I would like to make this as a reusable function that takes in some htmltext and the tags to match it like the following
def parse(html, atrs):
soup= BeautifulSoup(html... | [
"def parse(html, *atrs):\n soup= BeautifulSoup(html)\n body = soup.find(*atrs)\n return body\n\nAnd then:\nparse(htmlpage, 'div', {'id':'body'})\n\n",
"I think you just need to add an asterisk here:\nbody = soup.find(*atrs)\n\nWithout the asterisk you are passing a single parameter which is a tuple:\nbody = soup.... | [
8,
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0002571228_beautifulsoup_python.txt |
Q:
How to add a separator in a PyGTK combobox?
I'm using gtk.combo_box_new_text() to make combobox list, this uses a gtk.ListStore to store only strings, so there are some way to add a separator between items without use a complex gtk.TreeModel?
If this is not possible, what is the simplest way to use a gtk.TreeMode... | How to add a separator in a PyGTK combobox? | I'm using gtk.combo_box_new_text() to make combobox list, this uses a gtk.ListStore to store only strings, so there are some way to add a separator between items without use a complex gtk.TreeModel?
If this is not possible, what is the simplest way to use a gtk.TreeModel to able secuential widget addition?
| [
"I think that you should use ComboBox.set_row_separator_func to set a separator function where you would determine which items of your list will be separators. Since ListStore implements TreeModel interface, you should have no problem simply using it in your case.\nP.S.: nothing is easy in GTK :)\n"
] | [
4
] | [] | [] | [
"gnome",
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0002571202_gnome_gtk_pygtk_python_user_interface.txt |
Q:
Extracting a string between specified characters in python
I'm a newbie to regular expressions and I have the following string:
sequence = '["{\"First\":\"Belyuen,NT,0801\",\"Second\":\"Belyuen,NT,0801\"}","{\"First\":\"Larrakeyah,NT,0801\",\"Second\":\"Larrakeyah,NT,0801\"}"]'
I am trying to extract the text Bel... | Extracting a string between specified characters in python | I'm a newbie to regular expressions and I have the following string:
sequence = '["{\"First\":\"Belyuen,NT,0801\",\"Second\":\"Belyuen,NT,0801\"}","{\"First\":\"Larrakeyah,NT,0801\",\"Second\":\"Larrakeyah,NT,0801\"}"]'
I am trying to extract the text Belyuen,NT,0801 and Larrakeyah,NT,0801 in python. I have the follow... | [
"Don't use regex for this. It appears to be a rather strangely split set of JSON strings. Join them back together and use the json module to decode it.\nimport json\nsequence = '[%s]' % ','.join(sequence)\ndata = json.loads(sequence)\nprint data[0]['First'], data[0]['Second']\n\n(Note the json module is new in Pyth... | [
3,
3,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002571363_python_regex.txt |
Q:
What could cause Django to start failing its own tests after an OS and Django reinstall?
I had to reinstall my OS, and so, I reinstalled django 1.1. Since reinstalling, when I run tests in my app, I get several failures from django.contrib.auth.
Logs: http://dpaste.com/178153/
I asked on #django, and no one is too... | What could cause Django to start failing its own tests after an OS and Django reinstall? | I had to reinstall my OS, and so, I reinstalled django 1.1. Since reinstalling, when I run tests in my app, I get several failures from django.contrib.auth.
Logs: http://dpaste.com/178153/
I asked on #django, and no one is too sure what the cause of the errors are. Some of my own code fails its tests, because it's not ... | [
"These look like django.contib.auth failures. Are including django.contib.auth in your installed apps? Have you changed either the MIDDLEWARE_CLASSES or TEMPLATE_CONTEXT_PROCESSORS\nin your settings file? Both of these contain default settings used by the django.contib.auth that might cause these failures.\n",
"A... | [
0,
0
] | [] | [] | [
"django",
"python",
"testing"
] | stackoverflow_0002555629_django_python_testing.txt |
Q:
One hour difference in Python
I have a datetime.datetime property var.
I would like to know if it is less than one hour of the current time.
Something like
var.hour<datetime.datetime.today().hour - 1
Problem with the above syntax is that
datetime.datetime.today().hour
returns a number such as "10" and it is not... | One hour difference in Python | I have a datetime.datetime property var.
I would like to know if it is less than one hour of the current time.
Something like
var.hour<datetime.datetime.today().hour - 1
Problem with the above syntax is that
datetime.datetime.today().hour
returns a number such as "10" and it is not really a date comparation but more... | [
"Use datetime.timedelta.\nvar < datetime.datetime.today() - datetime.timedelta(hours=1)\n\n",
"You can use dateutil.relativedelta\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\n\nnow = datetime.now()\nother_time = now + timedelta(hours=8)\ndiff = relativedelta(other_t... | [
16,
3
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002571432_datetime_python.txt |
Q:
detect the most used colour in an image using python
I want to find the most used colour in an image using python. for example detect the colour of the object in the following image
http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg.
how to detect the base colour from the RGB codes(example - r... | detect the most used colour in an image using python | I want to find the most used colour in an image using python. for example detect the colour of the object in the following image
http://www.shopcrazy.com.ph/wp-content/images/2007/02/shiny-bags-01.jpg.
how to detect the base colour from the RGB codes(example - red in the above image).
| [
"Since you will most likely not want a histogram of all the million colors that are possible using a 24-bit color space, I suggest transforming the image into HSV space instead.\nThen you can partition the Hue part of that space into a number of bins that describe the hues you want to find (\"dark red\", \"orange r... | [
5,
3,
2,
1,
1,
0
] | [] | [] | [
"colors",
"image_processing",
"python"
] | stackoverflow_0002423743_colors_image_processing_python.txt |
Q:
Self-referential ReferenceProperty in Google App Engine
I'm having a bit of trouble with ReferencePropertys in App Engine (Python).
For a bit of fun, I'm trying to model a folder/file system, but having trouble getting folders to reference folders.
My first attempt was this:
class Folder(db.Model):
id = db.St... | Self-referential ReferenceProperty in Google App Engine | I'm having a bit of trouble with ReferencePropertys in App Engine (Python).
For a bit of fun, I'm trying to model a folder/file system, but having trouble getting folders to reference folders.
My first attempt was this:
class Folder(db.Model):
id = db.StringProperty()
name = db.StringProperty()
created = d... | [
"That's exactly what SelfReferenceProperty is for.\n",
"You could create a separate model to link the two, named something like FolderChild:\nclass FolderChild(db.Model):\n parent = db.ReferenceProperty(Folder)\n child = db.ReferenceProperty(Folder, collection_name=\"children\")\n\n"
] | [
9,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002571507_google_app_engine_python.txt |
Q:
Appengine Apps Vs Google bot web crawler
i built an appengine web app cricket.hover.in. The web app consists of about 15k url's
linked in it, But even after a long time of my launch, no pages are indexed on google.
Any base link place on my root site hover.in are being indexed with in minutes.
but i placed the sam... | Appengine Apps Vs Google bot web crawler | i built an appengine web app cricket.hover.in. The web app consists of about 15k url's
linked in it, But even after a long time of my launch, no pages are indexed on google.
Any base link place on my root site hover.in are being indexed with in minutes.
but i placed the same link home page of root site a long back. but... | [
"Well, from this corner of the cyberspace, there is no such domain cricket.hover.in. \n$ dig cricket.hover.in.\n; <<>> DiG 9.6.1-P2 <<>> cricket.hover.in.\n;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 30665\n\nI'd also guess that a URL that returns 15k hrefs is considered utterly useless spam by many spider... | [
2,
1
] | [] | [] | [
"bots",
"google_app_engine",
"python",
"seo",
"web_crawler"
] | stackoverflow_0002571701_bots_google_app_engine_python_seo_web_crawler.txt |
Q:
Is there a good way of automatically generating javascript client code from server side python
I basically want to be able to:
Write a few functions in python (with the minimum amount of extra meta data)
Turn these functions into a web service (with the minimum of effort / boiler plate)
Automatically generate som... | Is there a good way of automatically generating javascript client code from server side python | I basically want to be able to:
Write a few functions in python (with the minimum amount of extra meta data)
Turn these functions into a web service (with the minimum of effort / boiler plate)
Automatically generate some javascript functions / objects for rpc (this should prevent me from doing as many stupid things as... | [
"Yes there is, there is Pyjamas. Some people bill this as the \"GWT for Python\"\n",
"It looks like using a javascript XML RPC client (there is jquery plugin for this) together with an XML RPC server is a good way to go.\nThe jquery plugin will introspect your rpc service and will populate method names make it im... | [
6,
0
] | [] | [] | [
"javascript",
"python",
"rpc"
] | stackoverflow_0002541954_javascript_python_rpc.txt |
Q:
Python2.6 Decimal to Octal
How can i convert decimal to Octal in Python2.6, for 1 to 100000? I wanna get this converted result as .txt too. Can someone help me?
A:
Use the oct function:
print oct(9) # prints 011
A:
This should do the trick:
text = '\n'.join(str(oct(i)) for i in xrange(100000))
f = open('foo.tx... | Python2.6 Decimal to Octal | How can i convert decimal to Octal in Python2.6, for 1 to 100000? I wanna get this converted result as .txt too. Can someone help me?
| [
"Use the oct function:\nprint oct(9) # prints 011\n\n",
"This should do the trick:\ntext = '\\n'.join(str(oct(i)) for i in xrange(100000))\nf = open('foo.txt', 'w')\nf.write(text)\nf.close()\n\n"
] | [
15,
1
] | [] | [] | [
"decimal",
"octal",
"python"
] | stackoverflow_0002571840_decimal_octal_python.txt |
Q:
How can I configure vim syntax highlighting for mako templates?
I'd like to get the HTML elements highlighted as well as the MAKO / Python elements.
Thanks.
A:
This syntax file should (at least) highlight the mako elements.
| How can I configure vim syntax highlighting for mako templates? | I'd like to get the HTML elements highlighted as well as the MAKO / Python elements.
Thanks.
| [
"This syntax file should (at least) highlight the mako elements.\n"
] | [
4
] | [] | [] | [
"mako",
"python",
"vim"
] | stackoverflow_0002571893_mako_python_vim.txt |
Q:
Referencing other modules in atexit
I have a function that is responsible for killing a child process when the program ends:
class MySingleton:
def __init__(self):
import atexit
atexit.register(self.stop)
def stop(self):
os.kill(self.sel_server_pid, signal.SIGTERM)
However I get a... | Referencing other modules in atexit | I have a function that is responsible for killing a child process when the program ends:
class MySingleton:
def __init__(self):
import atexit
atexit.register(self.stop)
def stop(self):
os.kill(self.sel_server_pid, signal.SIGTERM)
However I get an error message when this function is cal... | [
"There are no strong guarantees about the order in which things are destroyed at program termination time, so it's best to ensure atexit-registered functions are self contained. E.g., in your case:\nclass MySingleton:\n def __init__(self):\n import atexit\n atexit.register(self.stop)\n self... | [
9
] | [] | [] | [
"atexit",
"python"
] | stackoverflow_0002572172_atexit_python.txt |
Q:
Using CookieJar in Python to log in to a website from "Google App Engine". What's wrong here?
I've been trying to find a python code that would log in to my mail box on yahoo.com from "Google App Engine"
.
Here (click here to see that page) I was given this code:
import urllib, urllib2, cookielib
url = "https://l... | Using CookieJar in Python to log in to a website from "Google App Engine". What's wrong here? | I've been trying to find a python code that would log in to my mail box on yahoo.com from "Google App Engine"
.
Here (click here to see that page) I was given this code:
import urllib, urllib2, cookielib
url = "https://login.yahoo.com/config/login?"
form_data = {'login' : 'my-login-here', 'passwd' : 'my-password-here'... | [
"You send MD5 hash and not plain password. Also you'd have to play along with all kinds of CSRF protections etc. that they're implementing. Look:\n <input type=\"hidden\" name=\".tries\" value=\"1\"> \n <input type=\"hidden\" name=\".src\" value=\"ym\"> \n <input type=\"hidden\" nam... | [
3
] | [] | [] | [
"cookiejar",
"google_app_engine",
"logging",
"python"
] | stackoverflow_0002571450_cookiejar_google_app_engine_logging_python.txt |
Q:
Python's urllib2 doesn't work on some sites
I found that you can't read from some sites using Python's urllib2(or urllib). An example...
urllib2.urlopen("http://www.dafont.com/").read()
# Returns ''
These sites work when you visit the site with a browser. I can even scrape them using PHP(didn't try other language... | Python's urllib2 doesn't work on some sites | I found that you can't read from some sites using Python's urllib2(or urllib). An example...
urllib2.urlopen("http://www.dafont.com/").read()
# Returns ''
These sites work when you visit the site with a browser. I can even scrape them using PHP(didn't try other languages). I have seen other sites with the same issue -... | [
"I believe it gets blocked by the User-Agent. You can change User-Agent using the following sample code:\nUSERAGENT = 'something'\nHEADERS = {'User-Agent': USERAGENT}\n\nreq = urllib2.Request(URL_HERE, headers=HEADERS)\nf = urllib2.urlopen(req)\ns = f.read()\nf.close()\n\n",
"Try setting a different user agent. C... | [
6,
3,
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0002572266_python_urllib_urllib2.txt |
Q:
Returning a list in this recursive coi function in python
I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this?
def makeChange2(amount, co... | Returning a list in this recursive coi function in python | I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this?
def makeChange2(amount, coinDenomination, listofcoins = None):
#makes a list of coins fro... | [
"You're not returning the value of the recursive calls to makeChange2.\nOnce control reaches either of those calls to makeChange2 and completes the call, the program continues to the next statement, which is the end of the function; thus, it returns None.\nIf that concept is still giving you trouble, try running th... | [
3
] | [] | [] | [
"list",
"python",
"recursion"
] | stackoverflow_0002572313_list_python_recursion.txt |
Q:
How do I change my current directory from a python script?
I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py for now, should th... | How do I change my current directory from a python script? | I'm trying to implement my own version of the 'cd' command that presents the user with a list of hard-coded directories to choose from, and the user has to enter a number corresponding to an entry in the list. The program, named my_cd.py for now, should then effectively 'cd' the user to the chosen directory. Example of... | [
"Change your sourced bash code to:\n#! /bin/bash\nfunction my_cd() {\n cd `/path/to/my_cd.py`\n}\n\nand your Python code to do all of its cosmetic output (messages to the users, menus, etc) on sys.stderr, and, at the end, instead of os.chdir, just print (to sys.stdout) the path to which the directory should be c... | [
7,
3,
2,
2,
1
] | [] | [] | [
"bash",
"cd",
"directory",
"python",
"shell"
] | stackoverflow_0002571524_bash_cd_directory_python_shell.txt |
Q:
Django ORM: Ordering w/ aggregate functions — None special treatment
I'm doing this query:
SomeObject.objects.annotate(something=Avg('something')).order_by(something).all()
I normally have an aggregate field in my model that I use with Django signals to keep in sync, however in this case perfomance isn't an issue... | Django ORM: Ordering w/ aggregate functions — None special treatment | I'm doing this query:
SomeObject.objects.annotate(something=Avg('something')).order_by(something).all()
I normally have an aggregate field in my model that I use with Django signals to keep in sync, however in this case perfomance isn't an issue so I thought I'd keep it simple and just use subqueries.
This approach, h... | [
"How about just adding a has_something=1,0 via extra() and then order on both has_something and something?\nwith_avg = SomeObject.objects.annotate(avg=Avg('something'))\nwith_avg_and_has = with_avg.extra(select={'has_something': 'something is NULL'})\nsorted_result = with_avg_and_has.order_by('-has_something', '-av... | [
2
] | [] | [] | [
"aggregate",
"django",
"orm",
"python"
] | stackoverflow_0002572201_aggregate_django_orm_python.txt |
Q:
Python lambda returning None instead of empty string
I have the following lambda function:
f = lambda x: x == None and '' or x
It should return an empty string if it receives None as the argument, or the argument if it's not None.
For example:
>>> f(4)
4
>>> f(None)
>>>
If I call f(None) instead of getting an em... | Python lambda returning None instead of empty string | I have the following lambda function:
f = lambda x: x == None and '' or x
It should return an empty string if it receives None as the argument, or the argument if it's not None.
For example:
>>> f(4)
4
>>> f(None)
>>>
If I call f(None) instead of getting an empty string I get None. I printed the type of what the func... | [
"use the if else construct\nf = lambda x:'' if x is None else x\n\n",
"The problem in your case that '' is considered as boolean False. bool('') == False.\nYou can use\nf =lambda x:x if x is not None else ''\n\n",
"The problem is that Python treats the empty string as False. When you pass None to your function... | [
27,
8,
4,
3,
2,
2
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0002572564_lambda_python.txt |
Q:
Using python to play two sine tones at once
I'm using python to play a sine tone. The tone is based off the computer's internal time in minutes, but I'd like to simultaneously play one based off the second for a harmonized or dualing sound.
This is what I have so far; can someone point me in the right direction?
... | Using python to play two sine tones at once | I'm using python to play a sine tone. The tone is based off the computer's internal time in minutes, but I'd like to simultaneously play one based off the second for a harmonized or dualing sound.
This is what I have so far; can someone point me in the right direction?
from struct import pack
from math import sin, pi
... | [
"What about the following minimal changes in your code...:\nfrom struct import pack\nfrom math import sin, pi\nimport time\n\ndef au_file(name, freq, freq1, dur, vol):\n fout = open(name, 'wb')\n # header needs size, encoding=2, sampling_rate=8000, channel=1\n fout.write('.snd' + pack('>5L', 24, 8*dur, 2, ... | [
1
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0002572651_audio_python.txt |
Q:
Talking with a Bittorrent client listening on a port?
I have one of my computers seeding a torrent file on port 45000. I am trying to write a small client in python (or perhaps perl) that helps me to determine the types of messages this client supports for which I need to perhaps do a handshake with the client. In... | Talking with a Bittorrent client listening on a port? | I have one of my computers seeding a torrent file on port 45000. I am trying to write a small client in python (or perhaps perl) that helps me to determine the types of messages this client supports for which I need to perhaps do a handshake with the client. In Azureus, this is done using a call like peer.getSupportedM... | [
"From what I can tell, the list of supported messages is a part of a custom handshake message supported only by Azureus (and possibly some Azureus-compliant tools) and is not part of the official BitTorrent system. However, you can probably craft a bencoded AZ handshake, send it to your seeder, decode the response,... | [
2
] | [] | [] | [
"bittorrent",
"p2p",
"perl",
"python"
] | stackoverflow_0002572634_bittorrent_p2p_perl_python.txt |
Q:
Are there Python ORMs out there that support multiple independent databases concurrently in use?
I'm writing an application in Python where I wish to use sqlite as the backing store for documents edited by the app, with documents generally living in memory, but being saved to disk-based databases when the applicat... | Are there Python ORMs out there that support multiple independent databases concurrently in use? | I'm writing an application in Python where I wish to use sqlite as the backing store for documents edited by the app, with documents generally living in memory, but being saved to disk-based databases when the application saves.
Ideally I'd like to use something like an ORM to make access to the data from my Python app... | [
"The upcoming django 1.2 release supports this.\nHere's a description of it:\nhttp://djangoadvent.com/1.2/multiple-database-support/\n",
"SQLAlchemy does support multiple database connections per class, as in this example: http://svn.sqlalchemy.org/sqlalchemy/trunk/examples/sharding/attribute_shard.py\n"
] | [
3,
3
] | [] | [] | [
"orm",
"python"
] | stackoverflow_0002572686_orm_python.txt |
Q:
Is frozenset adequate for caching of symmetric input data in a python dict?
The title more or less says it all:
I have a function which takes symmetric input in two arguments, e.g. something like
def f(a1, a2):
return heavy_stuff(abs(a1 - a2))
Now, I want to introduce some caching method. Would it be correct ... | Is frozenset adequate for caching of symmetric input data in a python dict? | The title more or less says it all:
I have a function which takes symmetric input in two arguments, e.g. something like
def f(a1, a2):
return heavy_stuff(abs(a1 - a2))
Now, I want to introduce some caching method. Would it be correct / pythonic / reasonably efficient to do something like this:
cache = {}
def g(a1,... | [
"Python always computes all arguments you're passing to a function, and only then does it call the function. In other words, like most other languages, Python is \"eager\" in its evaluation (the major exception today is probably Haskell, but that doesn't help you;-).\nSo setdefault is a very unsuitable approach fo... | [
2
] | [] | [] | [
"caching",
"python",
"set",
"symmetric"
] | stackoverflow_0002572899_caching_python_set_symmetric.txt |
Q:
What is float('123.987') in Python?
It's 123.98699999999999 !
Why is that?
A:
See Why can't decimal numbers be represented exactly in binary
A:
The Python FAQ and tutorial address this issue pretty well, I think. More generally, both are excellent resources, well worth your time to browse if you have any inte... | What is float('123.987') in Python? | It's 123.98699999999999 !
Why is that?
| [
"See Why can't decimal numbers be represented exactly in binary\n",
"The Python FAQ and tutorial address this issue pretty well, I think. More generally, both are excellent resources, well worth your time to browse if you have any interest in Python!-)\n",
"This has changed in/since Python 3.1.\nSee also: issu... | [
14,
5,
3
] | [] | [] | [
"floating_point",
"python"
] | stackoverflow_0002572936_floating_point_python.txt |
Q:
Creating Instance of Python Extension Type in C
I am writing a simple Vector implementation as a Python extension module in C that looks mostly like this:
typedef struct {
PyObject_HEAD
double x;
double y;
} Vector;
static PyTypeObject Vector_Type = {
...
};
It is very simple to create instances ... | Creating Instance of Python Extension Type in C | I am writing a simple Vector implementation as a Python extension module in C that looks mostly like this:
typedef struct {
PyObject_HEAD
double x;
double y;
} Vector;
static PyTypeObject Vector_Type = {
...
};
It is very simple to create instances of Vector while calling from Python, but I need to cr... | [
"Simplest is to call the type object you've created, e.g. with PyObject_CallFunction -- don't let the name fool you, it lets you call any callable, not just a function.\nIf you don't have a reference to your type object conveniently available as a static global to your C module, you can retrieve it in various ways,... | [
3
] | [] | [] | [
"extension_modules",
"python"
] | stackoverflow_0002573060_extension_modules_python.txt |
Q:
Changing models in django results in broken database?
I have added and removed fields in my models.py file and then run manage.py syncdb. Usually I have to quit out of the shell and restart it before syncdb does anything. And then even after that, I am getting errors when trying to access the admin pages, it seems... | Changing models in django results in broken database? | I have added and removed fields in my models.py file and then run manage.py syncdb. Usually I have to quit out of the shell and restart it before syncdb does anything. And then even after that, I am getting errors when trying to access the admin pages, it seems that certain new fields that I've added still don't show u... | [
"Django does not perform database migration for you, i.e., if you add new fields, Django won't modify your database schema.\nYou can either:\n\nDrop the tables that changed and perform syncdb again. This is reasonnable when you are developing your application and you don't have any real data in your database.\nUse ... | [
9,
4,
2
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0002571337_django_django_admin_django_models_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.