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:
Set ZipInfo mime type
When creating zip archive using python ZipFile, how can i set file mime types?
A:
The ZIP format doesn't carry MIME content-type for the individual files contained in the archive, though the ZIP format itself has a MIME content-type: application\zip.
The only way you've got to determine the... | Set ZipInfo mime type | When creating zip archive using python ZipFile, how can i set file mime types?
| [
"The ZIP format doesn't carry MIME content-type for the individual files contained in the archive, though the ZIP format itself has a MIME content-type: application\\zip.\nThe only way you've got to determine the appropriate MIME content-type for a file contained in a ZIP archive is by examination of the file name ... | [
3,
0
] | [] | [] | [
"mime",
"python",
"zip"
] | stackoverflow_0005120558_mime_python_zip.txt |
Q:
printing the number of times an attack occured each day from a syslog file using python
I've got a syslog file named auth and I would like to print out the number of times an attack has occurred each day.
I'm under the impression that the date is the key to achieving this. I'm considering inserting one date (Jan 0... | printing the number of times an attack occured each day from a syslog file using python | I've got a syslog file named auth and I would like to print out the number of times an attack has occurred each day.
I'm under the impression that the date is the key to achieving this. I'm considering inserting one date (Jan 08) for each time an attack has occurred on that day into the dictionary and then repeating th... | [
"This looks like a job for defaultdict:\nfrom collections import defaultdict\nattacks = defaultdict(int)\nfor line in logfile:\n date = extract_date_from_line(line)\n attacks[date] += 1\n\nEvery time you assign a value to a key that doesn't exist yet, defaultdict doesn't throw a KeyError exception like a norm... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005120733_python.txt |
Q:
Is there a way to set metaclass after the class definition?
In order to set metaclass of a class, we use the __metaclass__ attribute. Metaclasses are used at the time the class is defined, so setting it explicitly after the class definition has no effect.
This is what happens when I try to set metaclasses explici... | Is there a way to set metaclass after the class definition? | In order to set metaclass of a class, we use the __metaclass__ attribute. Metaclasses are used at the time the class is defined, so setting it explicitly after the class definition has no effect.
This is what happens when I try to set metaclasses explicitly;
>>> class MetaClass(type):
def __new__(cls, name, bases,... | [
"You can change the metaclass after class creation the same way that you can change the class of an object, however you'd have a lot of issues. For starters, the initial metaclass needs to be different from type, the __init__ and __new__ of the new metaclass won't be called (though you can manually call __init__ or... | [
14,
6,
2
] | [
"Why do you need this? I don't believe this is possible, but if you can explain the use case, I can probably suggest an alternative.\nAlong the lines of re-defining the whole class, what you could do is this:\nimport types\nNewClass = types.ClassType('NewClass', (object, ), {'__metaclass__':MetaClass})\n\nThen just... | [
-4,
-5
] | [
"metaclass",
"python"
] | stackoverflow_0005120688_metaclass_python.txt |
Q:
Asynchronous call into a Synchronous call in Python
In essence I am going to make a call to a remote XMLRPC server and it will process the request asynchronously.
import xmlrpclib
client = xmlrpclib.ServerProxy('http://localhost:8080')
client.add(3,5)
def add_result(result):
print result
I know at some poi... | Asynchronous call into a Synchronous call in Python | In essence I am going to make a call to a remote XMLRPC server and it will process the request asynchronously.
import xmlrpclib
client = xmlrpclib.ServerProxy('http://localhost:8080')
client.add(3,5)
def add_result(result):
print result
I know at some point in the future that add_result will get called with th... | [
"Your claim is nonsense. xmlrpclib operations are synchronous and blocking. For performing asynchrous operations etc. you need to implement something using threads.\n",
"I agree with pynator... \nBut in case you need help on the blocking piece...the design to block is pretty simple:\nclass GUI():\n def __init_... | [
0,
0
] | [] | [] | [
"asynchronous",
"python",
"synchronous"
] | stackoverflow_0005121440_asynchronous_python_synchronous.txt |
Q:
mac easy_install problem
I've tried to install a python package using easy_install. I used the easy_install from /usr/local/bin as I thought that was the one supplied by macpython. I've encountered this problem:
ValueError: numpy >= 1.4 is required (detected 1.2.1 from /System/Library/Frameworks/Python.framework/V... | mac easy_install problem | I've tried to install a python package using easy_install. I used the easy_install from /usr/local/bin as I thought that was the one supplied by macpython. I've encountered this problem:
ValueError: numpy >= 1.4 is required (detected 1.2.1 from /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/... | [
"You can use virtualenv with --no-site-packages then install your package into there. You might also want to investigate pip instead of easy_install.\n",
"If you are running a different version of python from the system supplied one,\nfind the framework bin directory for that version, for example:\n$ ls -l $(whi... | [
1,
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0005121365_macos_python.txt |
Q:
How to cancel a curl request from a WRITEFUNCTION?
I have a curl request in python which outputs a large amount of data to a writefunction (CURLOPT_WRITEFUNCTION). I want to be able to cancel the curl request from the writefunction if a certain condition is met. I've tried using ch.close(), but that errors saying ... | How to cancel a curl request from a WRITEFUNCTION? | I have a curl request in python which outputs a large amount of data to a writefunction (CURLOPT_WRITEFUNCTION). I want to be able to cancel the curl request from the writefunction if a certain condition is met. I've tried using ch.close(), but that errors saying that it cant close a request while its being performed. ... | [
"pycurl raises an error if the number returned from your write function isn't equal to the number it thinks it's writing, so returning -1 or raising an exception inside your write function will cause it to raise pycurl.error. Note that returning 'None' is interpreted as 'all bytes written'.\n>>> class Writer:\n... ... | [
2
] | [] | [] | [
"curl",
"pycurl",
"python"
] | stackoverflow_0005111353_curl_pycurl_python.txt |
Q:
Is there a way to submit several like inputs as a List from a Form?
I have a form that has 10 text input fields for first names, and 10 text input fields for last names. Only the first is required, so I expect 1-10 variables from both first and last name fields.
Right now I'm pulling out all 20 from the query Str... | Is there a way to submit several like inputs as a List from a Form? | I have a form that has 10 text input fields for first names, and 10 text input fields for last names. Only the first is required, so I expect 1-10 variables from both first and last name fields.
Right now I'm pulling out all 20 from the query String and ignoring the empty ones.
QUESTION: is there a way I can pass th... | [
"You may want to take a look at the jQuery serialize() method. It'll do all the work for you and send all the form values to the server where you can iterate through them. So you could change your code to:\nvar data = $(\"form\").serialize();\n$.ajax({ \n type: \"POST\", \n url: \"/foo/\", \n data: data... | [
0,
0
] | [] | [] | [
"ajax",
"forms",
"jquery",
"json",
"python"
] | stackoverflow_0005121855_ajax_forms_jquery_json_python.txt |
Q:
Trouble Querying Against int Field using MYSQL
Hey,
I'm trying to run the following query:
self.cursor.execute('SELECT courses.courseid, days, starttime, bldg, roomnum, '
'area, title, descrip, prereqs, endtime FROM '
'classes, courses, crosslistings, coursesprofs, pro... | Trouble Querying Against int Field using MYSQL | Hey,
I'm trying to run the following query:
self.cursor.execute('SELECT courses.courseid, days, starttime, bldg, roomnum, '
'area, title, descrip, prereqs, endtime FROM '
'classes, courses, crosslistings, coursesprofs, profs WHERE '
'classes.courseid = c... | [
"Try: \n\nselect * from classes where classes.classid = 3454; \n\n",
"I resolved this on my own. Based on my db structure, I was querying the wrong fields. I was looking for values that weren't there so that's why I was always returning an empty result set. Thanks for the help on the = operator though, that was u... | [
2,
0
] | [] | [] | [
"database",
"mysql",
"python",
"sql"
] | stackoverflow_0005096686_database_mysql_python_sql.txt |
Q:
Invoke an run-time SOAP method via Python/SUDS
I have a suds.client.Client object. I can invoke a method by hardcoding the method name, e.g.
myclient = suds.client.Client
result = myclient.service.some_method(args)
I would like to be able to execute a method whose name is not known until run time. I'm sure th... | Invoke an run-time SOAP method via Python/SUDS | I have a suds.client.Client object. I can invoke a method by hardcoding the method name, e.g.
myclient = suds.client.Client
result = myclient.service.some_method(args)
I would like to be able to execute a method whose name is not known until run time. I'm sure this is quite simple, but I'm pretty new to suds and i... | [
"result = getattr(myclient.service, 'some_method')(...)\n\n"
] | [
1
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0005122048_python_soap_suds.txt |
Q:
can't get python logging using apache2 CustomLog to work properly
I'm trying to use apache's CustomLog directive to pass log lines into a python script (which should log into a django backend). I'm using the following customlog line in a virtual host:
CustomLog "|/usr/bin/python -u /home/rolf/feedmemore/myproject/... | can't get python logging using apache2 CustomLog to work properly | I'm trying to use apache's CustomLog directive to pass log lines into a python script (which should log into a django backend). I'm using the following customlog line in a virtual host:
CustomLog "|/usr/bin/python -u /home/rolf/feedmemore/myproject/logger.py > /tmp/out.txt 2> /tmp/err.txt" combined
This is the main lo... | [
"Just focusing on your last line of the message. You probably don't want to be running a python script for every request. You're tossing in a ~20MB program to read a single line of text.\nRead up on modern syslogs, such as syslog-ng. You're paying too much of a price for something very simple.\nhttp://www.balabit.c... | [
0,
0
] | [] | [] | [
"apache",
"apache2",
"django",
"logging",
"python"
] | stackoverflow_0005118697_apache_apache2_django_logging_python.txt |
Q:
Reason for uncommon OOP in Python?
Instead of using common OOP, like Java and C# do with their base class Object or object, Python uses special methods for basic behaviour of objects. Python uses __str__ which is used when the object is passed to print:
>>> class Demo:
>>> def __str__(self):
>>> return "repr... | Reason for uncommon OOP in Python? | Instead of using common OOP, like Java and C# do with their base class Object or object, Python uses special methods for basic behaviour of objects. Python uses __str__ which is used when the object is passed to print:
>>> class Demo:
>>> def __str__(self):
>>> return "representation"
>>> d = Demo()
>>> print(d)... | [
"The reason for this is explained well in the Python documentation here:\nhttp://docs.python.org/faq/design.html#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list\n\nThe major reason is history. Functions\n were used for those operations that\n were generic for... | [
13,
3,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0005122034_oop_python.txt |
Q:
Which port should I set my service to listen to?
I want to create a website which will serve more like a web-application. There will be two parts: the front-end (probably in PHP, Apache) and the back-end services (in Python, using Twisted)
The front-end will usually provide some JavaScript which would send Ajax r... | Which port should I set my service to listen to? | I want to create a website which will serve more like a web-application. There will be two parts: the front-end (probably in PHP, Apache) and the back-end services (in Python, using Twisted)
The front-end will usually provide some JavaScript which would send Ajax requests to the Python services and receive data back.
... | [
"The normal choice is http-alt(8080).\n",
"You can be blocked all and everywhere. Any uncommon port is likely to be blocked by serious firewall configurations. Either get a dedicated IP address and listen to port 80. Best to talk to your IT network guys.\n",
"If you're intending for this to be distributed, you'... | [
3,
1,
1,
1
] | [] | [] | [
"port",
"python",
"rest",
"service",
"standards"
] | stackoverflow_0005122070_port_python_rest_service_standards.txt |
Q:
Printing tabular data in Python
What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like
for val1 in my_dic... | Printing tabular data in Python | What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like
for val1 in my_dict:
for val2 in my_dict:
if val... | [
"print \"%20s\" % somevar \n\nWill print the value 'somevar' and use up to 20 spaces. Add a comma behind the print statement in order to avoid the line-break - and of course: read the string formatting operations docs on the '%' operator\n",
"Do you know about PyPi?\nDataGrid and PrettyTable seem like two good al... | [
15,
10,
6
] | [] | [] | [
"python",
"tabular"
] | stackoverflow_0005122347_python_tabular.txt |
Q:
How to set Excel option button value (via python)?
Hey there,
I'm writing a python plugin for a geo referencing program called QGIS where I want an Excel sheet to do all my calculations for me. For different data points I need to set certain input values into the spreadsheet (which was already written by someone e... | How to set Excel option button value (via python)? |
Hey there,
I'm writing a python plugin for a geo referencing program called QGIS where I want an Excel sheet to do all my calculations for me. For different data points I need to set certain input values into the spreadsheet (which was already written by someone else).
I'm fine setting the simple int values (using win... | [
"You need to refer to the option button as a shape on the sheet\nI don't know how you access the excel object model in python, but in vb it's something like\nYourSheetObject.Shapes(\"opt_name\").Value = 1\n\n"
] | [
1
] | [] | [] | [
"button",
"excel",
"python"
] | stackoverflow_0005117820_button_excel_python.txt |
Q:
multiple send on httplib.HTTPConnection, and multiple read on HTTPResponse?
Should it be possible to send a plain, single http POST request (not chunk-encoded), in more than one segment? I was thinking of using httplib.HTTPConnection and calling the send method more than once (and calling read on the response obj... | multiple send on httplib.HTTPConnection, and multiple read on HTTPResponse? | Should it be possible to send a plain, single http POST request (not chunk-encoded), in more than one segment? I was thinking of using httplib.HTTPConnection and calling the send method more than once (and calling read on the response object after each send).
(Context: I'm collaborating to the design of a server that ... | [
"After being convinced by friends that this should be possible, I found a way to do it. I override httplib.HTTPResponse (n.b. httplib.HTTPConnection is nice enough to let you specify the response_class it will instantiate).\nLooking at socket.py and httplib.py (especially _fileobject.read()), I had noticed that re... | [
1
] | [] | [] | [
"http",
"python"
] | stackoverflow_0005093622_http_python.txt |
Q:
What happens to the variable in this case when it is overwritten with self?
I am downloading URLs in Python and need to detect 404s, so after some search I came up with:
import urllib
class MyUrlOpener(urllib.FancyURLopener):
def retrieve(self, url, filename=None, reporthook=None, data=None):
self.file... | What happens to the variable in this case when it is overwritten with self? | I am downloading URLs in Python and need to detect 404s, so after some search I came up with:
import urllib
class MyUrlOpener(urllib.FancyURLopener):
def retrieve(self, url, filename=None, reporthook=None, data=None):
self.file_was_found = True
val = urllib.FancyURLopener.retrieve(self, url, filenam... | [
"In Python, any class instance's method has self passed in by the Python interpreter and all of the other arguments are shifted down one place automatically.\nIn other words the Python interpreter rewrites:\nurlaccess.retrieve(url, saveas)\n\ninto something that looks like this:\nurlaccess.retrieve(urlaccess, url, ... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0005122593_python.txt |
Q:
Setting attributes on the request object when testing a django view
I'm writing some tests for a view function in django. The view function is decorated with an @facebook.require_login decorator from the pyFacebook library. This deciorator checks whether the user is logged in to facebook and provides access to an ... | Setting attributes on the request object when testing a django view | I'm writing some tests for a view function in django. The view function is decorated with an @facebook.require_login decorator from the pyFacebook library. This deciorator checks whether the user is logged in to facebook and provides access to an object which represents the facebook api if they are. The checking and po... | [
"Have you looked at the RequestFactory [1]?\n[1] http://docs.djangoproject.com/en/dev/topics/testing/#the-request-factory\n"
] | [
0
] | [] | [] | [
"django",
"python",
"testing"
] | stackoverflow_0005121852_django_python_testing.txt |
Q:
More efficient way to write this small bit of Python code?
I've been going through a beginning Python book, and I've been trying to write a small block of code that will take users input, check to make sure it can be converted to an int and check if it's higher than 49152.
I know there's an easier way to do this, ... | More efficient way to write this small bit of Python code? | I've been going through a beginning Python book, and I've been trying to write a small block of code that will take users input, check to make sure it can be converted to an int and check if it's higher than 49152.
I know there's an easier way to do this, but I can't get my mind to figure it out.
port_input = raw_input... | [
"What you have isn't functionaly correct anyway. Consider if someone puts \"123\" then \"abc\". The 123 will get them through the while check block, but when they get to the while < 49152 block there's no checking.\nHere's what I come up with (I don't do python, I just hacked it in based on your existing code...)\n... | [
3,
3,
1,
1,
1,
0
] | [
"I tried to avoid code duplication and make things a bit more pythonic with this rendition. Notice that I do not 'except:' but instead specifically catch ValueError. Often people forget that 'except:' also catches the SyntaxError exception which can make hunting down a stupid typo extremely frustrating. I assumed t... | [
-1
] | [
"input",
"python"
] | stackoverflow_0005119457_input_python.txt |
Q:
model.__unicode__() returning russian string cause TemplateSyntaxError
code:
class Gallery(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True)
class Meta:
verbose_name = 'галерея'
verbos... | model.__unicode__() returning russian string cause TemplateSyntaxError | code:
class Gallery(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
created = models.DateField(auto_now_add=True)
class Meta:
verbose_name = 'галерея'
verbose_name_plural = 'галереи'
def __unicode__(self):
return 'Галерея... | [
"Try\nreturn u'Галерея %s' % self.title\n\n",
"Because self.title is a unicode string and your string literal is not (its type is str), when Python executes the expression 'Галерея %s' % self.title, it needs to coerce the string literal into unicode before performing the interpolation. It needs a character encodi... | [
1,
0,
0
] | [] | [] | [
"ascii",
"django",
"python",
"unicode"
] | stackoverflow_0002335213_ascii_django_python_unicode.txt |
Q:
Need Advice on ide choice for Django Development
I've been programming with PHP for about 6 years, and wanna start developing on django.
Now I have some questions for you django pros. I've been using PHPDesigner for about a year, because I could never be relieved and code well with eclipse/aptana/similar. I just f... | Need Advice on ide choice for Django Development | I've been programming with PHP for about 6 years, and wanna start developing on django.
Now I have some questions for you django pros. I've been using PHPDesigner for about a year, because I could never be relieved and code well with eclipse/aptana/similar. I just feel weird with them.
I also have used Komodo Edit and ... | [
"I suggest you to use PyCharm. It has a great built-in django support, and continuously improved with new features.\n",
"Personally, I stick with Netbeans. It does have support for Python and Django, as well as your other languages (PHP, Java, etc). It's nice and quick, and is quite configurable. And it's open... | [
3,
3,
3,
2
] | [] | [] | [
"django",
"ide",
"python"
] | stackoverflow_0005123030_django_ide_python.txt |
Q:
How do I calculate the length of an x/y coordinate in Python?
I'm constructing a program where the user clicks two points in the graphics window and the length of x and y must be shown. I've creating a clone and multiplying it by itself, but no luck. Any ideas? Thanks!
Edit:
My program is supposed to create a 'mon... | How do I calculate the length of an x/y coordinate in Python? | I'm constructing a program where the user clicks two points in the graphics window and the length of x and y must be shown. I've creating a clone and multiplying it by itself, but no luck. Any ideas? Thanks!
Edit:
My program is supposed to create a 'money bin' based off the users data and 2 point clicks in the graphics... | [
"To get the absolute difference in the x coordinates use this formula:\ndx = math.abs(x2 - x1)\n\nSimilarly for the y-coordinates:\ndy = math.abs(y2 - y1)\n\nOn a related note, the formula for the distance between two points in two dimensions is:\ndist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)\n\n",
"Do you mean y... | [
5,
1
] | [] | [] | [
"computer_science",
"python"
] | stackoverflow_0005123363_computer_science_python.txt |
Q:
What is the proper model to reduce logic in this situation?
I am setting up a model where two players are involved in a competition. I'm leaning towards this model:
def match(models.Model):
player = ForeignKey(Player)
opponent = ForeignKey(Player)
score = PositiveSmallIntegerField()
games_won = Pos... | What is the proper model to reduce logic in this situation? | I am setting up a model where two players are involved in a competition. I'm leaning towards this model:
def match(models.Model):
player = ForeignKey(Player)
opponent = ForeignKey(Player)
score = PositiveSmallIntegerField()
games_won = PositiveSmallIntegerField()
games_lost = PositiveSmallIntegerFie... | [
"If you're looking to reduce redundancy and maintain consistiency of logic...\nMatch: \n- id\n- name \nMatch_Player: (2 records per match)\n- match_id\n- player_id\n- is_home \nMatch_Player_Score:\n- match_id\n- player_id\n- score \n",
"Id go with the first model and use select_related() to avoid the extra db ... | [
1,
1,
0
] | [] | [] | [
"django",
"python",
"schema",
"sql"
] | stackoverflow_0005121159_django_python_schema_sql.txt |
Q:
python - extract coordinates from a variable string
I have a latitude and longitude that come in a string like this:
my_string ='(31.251, -98.877)'
I would like to use Python to extract the coordinates from the above string.
The problem is that sometimes the string has variable length so one time it might look l... | python - extract coordinates from a variable string | I have a latitude and longitude that come in a string like this:
my_string ='(31.251, -98.877)'
I would like to use Python to extract the coordinates from the above string.
The problem is that sometimes the string has variable length so one time it might look like this (31.25134, -98.877) or (31.25134, -98.877435).
... | [
">>> ast.literal_eval('(31.251, -98.877)')\n(31.251, -98.877)\n\n",
"How about this:\nmystr = '(31.251, -98.877)'\n\nlat, lng = map(float, mystr.strip('()').split(','))\n\nShould work without regard to the length of the values.\n",
"(x, y) = (float(x) for x in my_string[1:-1].split(\",\"))\n\n"
] | [
12,
9,
2
] | [] | [] | [
"python"
] | stackoverflow_0005123508_python.txt |
Q:
Custom auth handler with mechanize
I would like to use python-ntlm with mechanize.Browser() I have got HTTPNtlmAuthHandler working with urllib2 and mechanize.urlopen() and tried to use it with Browser() but it doesn't work
Here is the code I'm using for urlopen
passman = mechanize.HTTPPasswordMgrWithDefaultRealm()... | Custom auth handler with mechanize | I would like to use python-ntlm with mechanize.Browser() I have got HTTPNtlmAuthHandler working with urllib2 and mechanize.urlopen() and tried to use it with Browser() but it doesn't work
Here is the code I'm using for urlopen
passman = mechanize.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, p... | [
"There may be better options, but the only way I could get it to work was to remove the HTTPRobotRulesProcessor handler which was somehow preventing the HTTPNtlmAuthHandler from being called.\nNote: The following code also happens to remove the ProxyHandler in order to bypass the proxy server - remove if applicabl... | [
1
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0002153095_mechanize_python.txt |
Q:
How to efficiently combine two (or more) associative arrays with common keys
More generally, let's say we have two lists of different lengths with one common attribute:
list1: {
{"orderID":1234, "FirstName":"shaheeb", "LastName":"roshan"},
{"orderID":9183, "FirstName":"robert", "LastName":"gibbon... | How to efficiently combine two (or more) associative arrays with common keys | More generally, let's say we have two lists of different lengths with one common attribute:
list1: {
{"orderID":1234, "FirstName":"shaheeb", "LastName":"roshan"},
{"orderID":9183, "FirstName":"robert", "LastName":"gibbons"},
{"orderID":2321, "FirstName":"chester"},
}
list2: {
... | [
"For a general solution in Python, for any number of lists:\norders = defaultdict(dict)\nfor order_list in order_lists:\n for order in order_list:\n orders[order['orderID']].update(order)\n\nSee it working online: ideone\n",
"A generic solution that can merge any number of dicts (or a list of dicts - if... | [
4,
2,
1
] | [] | [] | [
"arrays",
"merge",
"php",
"python"
] | stackoverflow_0005123544_arrays_merge_php_python.txt |
Q:
reading output from a text file
For instance, the following test.py script can be displayed at ../cgi-bin/test.py, but is there a way I could display the same output from a text file (like test.txt) instead of text.py, so that the url would be something like ../text.txt?
--- test.py ---
def printxt():
print "Con... | reading output from a text file | For instance, the following test.py script can be displayed at ../cgi-bin/test.py, but is there a way I could display the same output from a text file (like test.txt) instead of text.py, so that the url would be something like ../text.txt?
--- test.py ---
def printxt():
print "Content-Type: text/plain"
print """my ... | [
"If you point your browser to www.yoursite.com/yourtext.txt, you'll discover that most browsers are fully capable of displaying text files without any additional code.\n",
"You appear to be asking if web servers can serve, and web browsers display text files. The answer is yes. Put the text file underneath DOCUME... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005123122_python.txt |
Q:
How to get record by url, insert if not found
I'm doing this currently and getting an error:
Attribute Error 'Table' object has not attribute url
p = session.query(pages.url == someurl).first()
if p is None:
p = Page()
p....
..
session.add(p)
session.commit()
SomeFunction(p)
I am weary if somet... | How to get record by url, insert if not found | I'm doing this currently and getting an error:
Attribute Error 'Table' object has not attribute url
p = session.query(pages.url == someurl).first()
if p is None:
p = Page()
p....
..
session.add(p)
session.commit()
SomeFunction(p)
I am weary if something returns null my code is going to fail, is it ... | [
"No, your approach is not correct, and the error is not of the 'no row' nature. From the error message, 'pages' is obviously a Table object, and not a class mapped to a table. Either you change the expression to Pages.url==someurl or you use pages.c.url==someurl, thus, specifying that you are looking for a (c) colu... | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004952957_python_sqlalchemy.txt |
Q:
Why is the "file" command get confused on .py files?
I have several python modules that I've written. Randomly, I used file on this directory, and I was really surprised by what I saw. Here's the resulting count of what it thought the files were:
1 ASCII Java program text, with very long lines
1 a /bin/env p... | Why is the "file" command get confused on .py files? | I have several python modules that I've written. Randomly, I used file on this directory, and I was really surprised by what I saw. Here's the resulting count of what it thought the files were:
1 ASCII Java program text, with very long lines
1 a /bin/env python script text executable
1 a python script text exec... | [
"I just ran a test and in every case of incorrect identification, there was no shebang line.\nFor every file that had:\n#!/usr/bin/env python\n\nfile correctly identified it.\nLooking at the magic file, another thing that triggers recognition as a Python file is a triple quote on the first line.\n$ echo '\"\"\"' | ... | [
6,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0005120412_python.txt |
Q:
Validation logic in Google App Engine
Part of the app I'm coding is structured roughly like this:
class PostModel(db.Model):
some_property = db.WhateverProperty()
some_other_property = db.WhateverProperty()
class PostHandler(webapp.RequestHandler):
def get(self):
#code to generate form
def... | Validation logic in Google App Engine | Part of the app I'm coding is structured roughly like this:
class PostModel(db.Model):
some_property = db.WhateverProperty()
some_other_property = db.WhateverProperty()
class PostHandler(webapp.RequestHandler):
def get(self):
#code to generate form
def post(self):
#code to validate inpu... | [
"There are a few ways of doing it. Some form libraries will do most of the basic validation, but some things are inevitably left out when you have more complex data.\nI think it is a good idea to pass a dictionary of values to a @classmethod of the model, and let it validate the data. I usually have a class method ... | [
3
] | [] | [] | [
"google_app_engine",
"model_view_controller",
"python"
] | stackoverflow_0005120659_google_app_engine_model_view_controller_python.txt |
Q:
How to use Ruby CLI client to launch a JobFlow based on a JSON JobFlow description on Amazon Elastic MapReduce
I have written a mapreduce application for hadoop and tested it at the command line on a single machine. My application uses two steps Map1 -> Reduce1 -> Map2 -> Reduce2
To run this job on aws mapreduce,... | How to use Ruby CLI client to launch a JobFlow based on a JSON JobFlow description on Amazon Elastic MapReduce | I have written a mapreduce application for hadoop and tested it at the command line on a single machine. My application uses two steps Map1 -> Reduce1 -> Map2 -> Reduce2
To run this job on aws mapreduce, I am following this link http://aws.amazon.com/articles/2294. But I am not clear how to use Ruby CLI client provide... | [
"You start by creating the default streaming jobflow (which runs the wordcount example). At this point you use the jobflow ID to add your other steps. In my example, the first mapreduce job stores its results in an S3 bucket. That result then becomes the input for the second job. If you go into the AWS console ... | [
0
] | [] | [] | [
"amazon_web_services",
"hadoop",
"mapreduce",
"python",
"ruby"
] | stackoverflow_0004063519_amazon_web_services_hadoop_mapreduce_python_ruby.txt |
Q:
Forking Greenlets
Perhaps I'm missing something obvious (and it is a Friday), but is there a way to do the equivalent of an os.fork() on a greenlet? I'm not necessarily looking to fork the process, I'm looking to take the greenlet and run one set of code, then another, but with independent scopes (as with os.fork(... | Forking Greenlets | Perhaps I'm missing something obvious (and it is a Friday), but is there a way to do the equivalent of an os.fork() on a greenlet? I'm not necessarily looking to fork the process, I'm looking to take the greenlet and run one set of code, then another, but with independent scopes (as with os.fork()).
Any ideas or should... | [
"In order to conceptually fork a greenlet, just create another greenlet wrapping your \"child function\". I also highly recommend gevent, which is built on greenlet. The gevent code has a fork() method, but it forks the Python process and then restarts gevent in the child. I bet that you can implement whatever you ... | [
4
] | [] | [] | [
"fork",
"greenlets",
"python"
] | stackoverflow_0005122727_fork_greenlets_python.txt |
Q:
Extracting Express Checkout Tokens
When it comes to PayPal I'm a total newbie, so, sorry if this is answered somewhere else. I've checked in multiple locations including here and have been unable to find any information.
I want to integrate paypal with python.
My problem is I'm trying to implement Express Checkou... | Extracting Express Checkout Tokens | When it comes to PayPal I'm a total newbie, so, sorry if this is answered somewhere else. I've checked in multiple locations including here and have been unable to find any information.
I want to integrate paypal with python.
My problem is I'm trying to implement Express Checkout in an e-commerce site. I'm working on... | [
"My apologies. I answered off the top of my head without trying it. Here's what actually works.\nfrom cgi import parse_qs\n...\n\nredirect_url_template = 'https://www.paypal.com/webscr?cmd=_ap-payment&paykey='\n\n...\n\nparsed_response = parse_qs(response.content)\nack = parsed_response['responseEnvelope.ack'][0]\n... | [
0
] | [] | [] | [
"paypal",
"python"
] | stackoverflow_0004645669_paypal_python.txt |
Q:
Python - invalid mode('w') or filename
I've encountered a very odd error.
I have this code as part of many of my functions in my python script:
url=['http://API_URL/query/query.aspx?name=', name, '&md=user']
url=''.join(url)
file = open("QueryESO.xml", "w")
filehandle = urllib.urlopen(url)
for lines in filehandle.... | Python - invalid mode('w') or filename | I've encountered a very odd error.
I have this code as part of many of my functions in my python script:
url=['http://API_URL/query/query.aspx?name=', name, '&md=user']
url=''.join(url)
file = open("QueryESO.xml", "w")
filehandle = urllib.urlopen(url)
for lines in filehandle.readlines():
file.write(lines)
file.clos... | [
"Some observations:\n(1) If the problem was invalid characters in the actual file name, it would be obvious from the error message; see below:\n>>> open('fu\\x01bar', 'w')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nIOError: [Errno 22] invalid mode ('w') or filename: 'fu\\x01bar'\n... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0005110807_python.txt |
Q:
Python/Scipy Interpolation (map_coordinates)
I'm trying to do some interpolation with scipy. I've gone through many examples, but I'm not finding exactly what I want.
Let's say I have some data where the row and column variable can vary from 0 to 1. The delta changes between each row and column is not always the... | Python/Scipy Interpolation (map_coordinates) | I'm trying to do some interpolation with scipy. I've gone through many examples, but I'm not finding exactly what I want.
Let's say I have some data where the row and column variable can vary from 0 to 1. The delta changes between each row and column is not always the same (see below).
| 0.00 0.25 0.80 1.00... | [
"I think you want a bivariate spline on a rectangular structured mesh:\nimport numpy\nfrom scipy import interpolate\nx = numpy.array([0.0, 0.60, 1.0])\ny = numpy.array([0.0, 0.25, 0.80, 1.0])\nz = numpy.array([ \n [ 1.4 , 6.5 , 1.5 , 1.8 ],\n [ 8.9 , 7.3 , 1.1 , 1.09],\n [ 4.5 , 9.2 , 1.8 , 1.2 ]])\n... | [
16
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scipy"
] | stackoverflow_0005124126_interpolation_numpy_python_scipy.txt |
Q:
Converting to and from '<' and '>' automatically with Python
I use TextMate in Mac, and it allows me to program with Python just like emacs with Lisp.
The problem is the Python code is stored in XML in such a way that '>' and '<', characters are stored in >/<. I expect some other characters are changed.
How ca... | Converting to and from '<' and '>' automatically with Python | I use TextMate in Mac, and it allows me to program with Python just like emacs with Lisp.
The problem is the Python code is stored in XML in such a way that '>' and '<', characters are stored in >/<. I expect some other characters are changed.
How can I use python to convert those characters automatically? I could ... | [
"Load it with a lib like lxml.\n",
"Have a look at http://wiki.python.org/moin/EscapingHtml:\nimport cgi\nescaped = cgi.escape(unescaped)\n\n"
] | [
2,
2
] | [] | [] | [
"html",
"python"
] | stackoverflow_0005124251_html_python.txt |
Q:
What is the difference between import modx and from modx import *?
If I were to import some module called modx, how would that be different from saying
from modx import *
Wouldn't all the contents be imported from each either way? This is in python just to clarify.
A:
If you import somemodule the contained glo... | What is the difference between import modx and from modx import *? | If I were to import some module called modx, how would that be different from saying
from modx import *
Wouldn't all the contents be imported from each either way? This is in python just to clarify.
| [
"If you import somemodule the contained globals will be available via somemodule.someglobal. If you from somemodule import * ALL its globals (or those listed in __all__ if it exists) will be made globals, i.e. you can access them using someglobal without the module name in front of it.\nUsing from module import * i... | [
36,
19,
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0005124232_import_module_python.txt |
Q:
Python GUI does not update until entire process is finished
I have a process that gets a files from a directory and puts them in a list. It then iterates that list in a loop. The last line of the loop being where it should update my gui display, then it begins the loop again with the next item in the list.
My pr... | Python GUI does not update until entire process is finished | I have a process that gets a files from a directory and puts them in a list. It then iterates that list in a loop. The last line of the loop being where it should update my gui display, then it begins the loop again with the next item in the list.
My problem is that it does not actually update the gui until the entir... | [
"Create a worker thread/process that does your processing in the background and updates the GUI after the processing is done, maybe reporting progress during work.\nHave a look at the threading or multiprocessing modules.\n",
"This is a common problem with GUI programs. Controls don't get updated until a \"repain... | [
4,
3,
0
] | [] | [] | [
"listview",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0004939675_listview_python_user_interface_wxpython.txt |
Q:
What protocol to use in client-server app communication with python?
I need to do a client-server application, the client will be made with python-gtk,
all procedures will be on server-side to free the client of this workload.
So i did search on google about client-server protocols and i found that CORBA and RPC ... | What protocol to use in client-server app communication with python? | I need to do a client-server application, the client will be made with python-gtk,
all procedures will be on server-side to free the client of this workload.
So i did search on google about client-server protocols and i found that CORBA and RPC are closer from what i had in mind, BUT also i want to made this app ready... | [
"I've implemented webservices using SOAP/XMLRPC (it was easy to support both, the framework I was using at the time made it pretty trivial) before; I had thought about using standard HTTP without the SOAP/XMLRPC layer (before I was aware that REST had a name :) but decided against it in the end because \"I didn't w... | [
4,
3
] | [] | [] | [
"corba",
"python",
"rest",
"rpc",
"soap"
] | stackoverflow_0005124408_corba_python_rest_rpc_soap.txt |
Q:
Set C/C++ compiler for Python extensions
I would like to setup a default C and C++ compiler when building Python extensions under Linux. I noticed the --compiler option to python setup.py build, but I am wondering if there is a way of setting this as an environmental variable so that I can specify them just once.... | Set C/C++ compiler for Python extensions | I would like to setup a default C and C++ compiler when building Python extensions under Linux. I noticed the --compiler option to python setup.py build, but I am wondering if there is a way of setting this as an environmental variable so that I can specify them just once.
| [
"It's not possible to use an environment variable, but you can create a setup.cfg file. See Writing the Setup Configuration File. The following setup.cfg file will try to use the Intel C Compiler:\n[build_ext] \ncompiler=icc\n\n"
] | [
4
] | [] | [] | [
"c++",
"linux",
"python"
] | stackoverflow_0005124328_c++_linux_python.txt |
Q:
Problems on select module on Python 2.5
I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro.
On that computer, when I try to run it I get this error:
Traceback (most recent call last):
File "jobs.py", lin... | Problems on select module on Python 2.5 | I have an application in Python 2.5 that listens to a beanstalk queue. It works fine on all machines I tested so far, except from my newly acquired MacBook Pro.
On that computer, when I try to run it I get this error:
Traceback (most recent call last):
File "jobs.py", line 181, in <module>
Jobs().start()
File ... | [
"According to this macports ticket Apple's implementation of poll() is straight up broken. Apple worked around this by disabling poll() in Python and macports now disables poll in their Pythons as well. I think this means you need to look into Python's select.kevent() instead of poll on mac.\n",
"I think your a... | [
6,
2,
0,
0
] | [] | [] | [
"beanstalkd",
"macos",
"python"
] | stackoverflow_0000584575_beanstalkd_macos_python.txt |
Q:
editing text via python
i have Text file and the content is
Johan
Sara
robert
how to add next each one :OK
like that
Johan:OK
sara:OK
robert:OK
by python ... and thanks
A:
with open('file.txt', 'r') as f:
for line in f:
print '%s:OK' % line.rstrip('\r\n')
A:
import fileinput
for line in fileinput.F... | editing text via python | i have Text file and the content is
Johan
Sara
robert
how to add next each one :OK
like that
Johan:OK
sara:OK
robert:OK
by python ... and thanks
| [
"with open('file.txt', 'r') as f:\n for line in f:\n print '%s:OK' % line.rstrip('\\r\\n')\n\n",
"import fileinput\nfor line in fileinput.FileInput(\"file\",inplace=1):\n print line.rstrip()+\":OK\"\n\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005124250_python.txt |
Q:
How to properly save and fetch JSON from Datastore?
I'm using Google App Engine and Python.
class Spam(db.Model)
eggs = db.TextProperty
# Create some json and store it to a Spam Entity
eggs_dict = {"large":10, "medium":5, "small":24}
eggs_json = simplejson.dumps(eggs)
spam = Spam(eggs=db.Text(eggs_json))
# L... | How to properly save and fetch JSON from Datastore? | I'm using Google App Engine and Python.
class Spam(db.Model)
eggs = db.TextProperty
# Create some json and store it to a Spam Entity
eggs_dict = {"large":10, "medium":5, "small":24}
eggs_json = simplejson.dumps(eggs)
spam = Spam(eggs=db.Text(eggs_json))
# Later, fetch spam and then return the json as part of a Re... | [
"What you've got looks good, but maybe you should look into using a custom property like: JsonProperty(1) or JsonProperty(2).\nThat way the data is automatically serialized/deserialized for you.\n",
"You shouldn't need to do any encoding when inserting a 'string' (you've serialized your dictionary to a string) in... | [
4,
1
] | [] | [] | [
"google_app_engine",
"json",
"python"
] | stackoverflow_0005124781_google_app_engine_json_python.txt |
Q:
Python ctypes: passing to function with 'const char ** ' argument
I want to pass a python list of strings to a C function expecting const char **. I saw the question and solution here but it does not seem to work for me. The following sample code:
argList = ['abc','def']
options = (ctypes.c_char_p * len(argList))(... | Python ctypes: passing to function with 'const char ** ' argument | I want to pass a python list of strings to a C function expecting const char **. I saw the question and solution here but it does not seem to work for me. The following sample code:
argList = ['abc','def']
options = (ctypes.c_char_p * len(argList))()
options[:] = argList
gives the following error:
Traceback (most rece... | [
"Another syntax to consider:\n>>> from ctypes import *\n>>> a = 'abc def ghi'.split()\n>>> b=(c_char_p * len(a))(*a)\n>>> b[0]\n'abc'\n>>> b[1]\n'def'\n>>> b[2]\n'ghi'\n\nWorks on my 2.7.1 and 3.1.3 installation. Works on 3.2 if the array is a bytes instance, not str instance:\nPython 3.2 (r32:88445, Feb 20 2011, ... | [
3,
1
] | [] | [] | [
"c",
"ctypes",
"python"
] | stackoverflow_0005104015_c_ctypes_python.txt |
Q:
is GAE throttling me?
I have a Google App Engine HTTP resource that takes 20 seconds to respond. The resource does a calculation requiring very little bandwidth and no storage access. Billing is not enabled. If my desktop application spawns 100 threads to POST 500 times (each thread will on average POST 5 times... | is GAE throttling me? | I have a Google App Engine HTTP resource that takes 20 seconds to respond. The resource does a calculation requiring very little bandwidth and no storage access. Billing is not enabled. If my desktop application spawns 100 threads to POST 500 times (each thread will on average POST 5 times). I believe that 500 POST... | [
"Search the groups for 1000ms. Your app will not be given as many resources if your user-requests do not return in less than 1000ms. You might also face additional issues with requests that are taking 20 seconds, I believe if your requests sit in the pending queue it counts against the run-time increasing the lik... | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005125372_google_app_engine_python.txt |
Q:
Generate a Dex file with python or other language
Is it possible to generate dalvik bytecode at runtime using a language such as python, perl or something similar?
Thanks
A:
I think the best way is to create a smali compatible file and compile it with smali http://code.google.com/p/smali/
A:
Take a look at and... | Generate a Dex file with python or other language | Is it possible to generate dalvik bytecode at runtime using a language such as python, perl or something similar?
Thanks
| [
"I think the best way is to create a smali compatible file and compile it with smali http://code.google.com/p/smali/\n",
"Take a look at android-scripting, a toolkit for running Python, Perl, JRuby, Lua, BeanShell, JavaScript, Tcl, and shell.\n"
] | [
2,
0
] | [] | [] | [
"dalvik",
"dex",
"python"
] | stackoverflow_0005118658_dalvik_dex_python.txt |
Q:
Download / Install Windows Updates from Python
I am working on a script to automate the installation of Windows Updates, that I can deploy on several machines so I do not have to worry about updating them manually. I would like to write this in Python, but could not find anythng on how this would be done. I need t... | Download / Install Windows Updates from Python | I am working on a script to automate the installation of Windows Updates, that I can deploy on several machines so I do not have to worry about updating them manually. I would like to write this in Python, but could not find anythng on how this would be done. I need to know how to search for updates, download the updat... | [
"Let me start with this: I don't think a Python script is the best tool for the job. If you want to do enterprise-level management of updates (e.g., for all machines on a network), then you should seriously consider using the existing MS tools. \nWith that said, here is how you might go about this:\n\nHave a look a... | [
2,
1
] | [] | [] | [
"download",
"installation",
"python",
"windows"
] | stackoverflow_0005125144_download_installation_python_windows.txt |
Q:
Why I get urllib2.HTTPError with urllib2 and no errors with urllib?
I have the following simple code:
import urllib2
import sys
sys.path.append('../BeautifulSoup/BeautifulSoup-3.1.0.1')
from BeautifulSoup import *
page='http://en.wikipedia.org/wiki/Main_Page'
c=urllib2.urlopen(page)
This code generates the follow... | Why I get urllib2.HTTPError with urllib2 and no errors with urllib? | I have the following simple code:
import urllib2
import sys
sys.path.append('../BeautifulSoup/BeautifulSoup-3.1.0.1')
from BeautifulSoup import *
page='http://en.wikipedia.org/wiki/Main_Page'
c=urllib2.urlopen(page)
This code generates the following error messages:
c=urllib2.urlopen(page)
File "/usr/lib64/python... | [
"The original urllib simply does not raise an exception on a 403 code. If you add print c.getcode() to the last line of your program, urllib will reach it and still print out 403.\nThen if you do print c.read() at the end, you will see that you did indeed get an error page from Wikipedia. It's just a matter of ur... | [
10,
4,
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0001482028_python_urllib_urllib2.txt |
Q:
Python pip - install documentation for packages?
Is there a way to install/generate the documentation for the packages installed using pip?
I wish to install all the required packages for a project, as well as all the associated documentation (e.g. Django documentation when installing django, dateutil documentatio... | Python pip - install documentation for packages? | Is there a way to install/generate the documentation for the packages installed using pip?
I wish to install all the required packages for a project, as well as all the associated documentation (e.g. Django documentation when installing django, dateutil documentation with dateutil etc.).
Pip requirements files are a gr... | [
"I think you're looking for an equivalent to the way that ruby automatically (unless suppressed) generates rdoc from installed gems/packages.\nIn python, there is a standardized mechanism for annotating code with documentation -- docstrings with optional formatting. However there isn't a standardized way of generat... | [
4
] | [] | [] | [
"package",
"pip",
"python"
] | stackoverflow_0004183692_package_pip_python.txt |
Q:
how to sort a list by the nth element in v2.3?
This is a simple script I wrote:
#!/usr/bin/env python
file = open('readFile.txt', 'r')
lines = file.readlines()
file.close()
del file
sortedList = sorted(lines, key=lambda lines: lines.split('\t')[-2])
file = open('outfile.txt', 'w')
for line in sortedList:
f... | how to sort a list by the nth element in v2.3? | This is a simple script I wrote:
#!/usr/bin/env python
file = open('readFile.txt', 'r')
lines = file.readlines()
file.close()
del file
sortedList = sorted(lines, key=lambda lines: lines.split('\t')[-2])
file = open('outfile.txt', 'w')
for line in sortedList:
file.write(line)
file.close()
del file
to rewrite a... | [
"file = open('readFile.txt', 'r')\nlines = file.readlines()\nfile.close()\ndel file\n\nlines = [line.split(' ') for line in lines]\nlines.sort(lambda x,y: cmp(x[2], y[2])\nlines = [' '.join(line) for line in lines]\n\n",
"In reply to your final query, you can create a datetime object from a time_t-like \"seconds ... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0005126237_python.txt |
Q:
Dynamic casts returns null when library with C++ python extensions is used as a plugin on RHEL5
I have a library with C++ python extensions (C++ calls python which in turn calls C++) using boost::python and python libraries (this is messy, but a lot of it is legacy) which when tested standalone works correctly. In... | Dynamic casts returns null when library with C++ python extensions is used as a plugin on RHEL5 | I have a library with C++ python extensions (C++ calls python which in turn calls C++) using boost::python and python libraries (this is messy, but a lot of it is legacy) which when tested standalone works correctly. In particular, a certain dynamic_cast works correctly.
But when the library is packaged for use as a p... | [
"Take a look at similar question and GCC FAQ\nIf you use dlopen to explicitly load code from a shared library, you must do several things. First, export global symbols from the executable by linking it with the \"-E\" flag (you will have to specify this as \"-Wl,-E\" if you are invoking the linker in the usual mann... | [
0
] | [] | [] | [
"boost_python",
"c++",
"dynamic_cast",
"python",
"rhel5"
] | stackoverflow_0005123992_boost_python_c++_dynamic_cast_python_rhel5.txt |
Q:
receive delivery list of send mail in django
I want use send_mass_mail() in django and then want receive list of delivery mail
list with email address and problem for failed or delivered ok status
how i can make this modules ?
A:
List of delivered emails is outside of the scope of Django, which is a web framewor... | receive delivery list of send mail in django | I want use send_mass_mail() in django and then want receive list of delivery mail
list with email address and problem for failed or delivered ok status
how i can make this modules ?
| [
"List of delivered emails is outside of the scope of Django, which is a web framework and not a replacement for services like Mailchimp.\n"
] | [
4
] | [] | [] | [
"django",
"email",
"email_confirmation",
"python",
"smtp"
] | stackoverflow_0005125544_django_email_email_confirmation_python_smtp.txt |
Q:
PyQT - Positioning and Displaying a Custom Widget
I am attempting to use PyQT to position and display a custom widget. Thus far, I have a widget, and my window. I have been successful in displaying the widget through a layout, however, I am interested in using .move(x,y,) to position my widget before show()'ing it... | PyQT - Positioning and Displaying a Custom Widget | I am attempting to use PyQT to position and display a custom widget. Thus far, I have a widget, and my window. I have been successful in displaying the widget through a layout, however, I am interested in using .move(x,y,) to position my widget before show()'ing it. Thus far my code is as follows:
import sys, random
fr... | [
"Couple of things I noticed in your code:\n\nyou don't really need to define store x, y, width and height for your custom widget. Just call setGeometry with coordinates passed into the constructor. Widget already providers getGeometry, getHeight, getWidth, etc. methods which you can use to manipulate and paint your... | [
2
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0005114222_pyqt_python_qt.txt |
Q:
basic inheritance (in python)
users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
Is there a... | basic inheritance (in python) | users,
I have a basic question concerning inheritance (in python). I have two classes and one of them is inherited from the other like
class p:
def __init__(self,name):
self.pname = name
class c(p):
def __init__(self,name):
self.cname = name
Is there any possibility that I can create a ... | [
"\nIt should work like that that the parent object contains several variables and whenever I access the corresponding variables from a child I actually access the variable form the parent. I.e. if I change it for one child it is changed also for all other childes and the data are only stored once in memory (and not... | [
5,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0005104366_inheritance_oop_python.txt |
Q:
How to speed-up a HTTP request
I need to get json data and I'm using urllib2:
request = urllib2.Request(url)
request.add_header('Accept-Encoding', 'gzip')
opener = urllib2.build_opener()
connection = opener.open(request)
data = connection.read()
but although the data aren't so big it is too slow.
Is there a way t... | How to speed-up a HTTP request | I need to get json data and I'm using urllib2:
request = urllib2.Request(url)
request.add_header('Accept-Encoding', 'gzip')
opener = urllib2.build_opener()
connection = opener.open(request)
data = connection.read()
but although the data aren't so big it is too slow.
Is there a way to speed it up? I can use 3rd party l... | [
"Accept-Encoding:gzip means that the client is ready to gzip Encoded content if the Server is ready to send it first. The rest of the request goes down the sockets and to over your Operating Systems TCP/IP stack and then to physical layer.\nIf the Server supports ETags, then you can send a If-None-Match header to e... | [
6,
3,
1,
0
] | [] | [] | [
"http",
"python",
"urllib2"
] | stackoverflow_0005126021_http_python_urllib2.txt |
Q:
Newbie python error in regards to import
I'm a python newbie and starting out with using the Bottle web framework on Google App Engine. I've been messing with the super small, super easy Hello World sample and have already ran into problems. Heh. I finally got the code to work with this...
import bottle
from bo... | Newbie python error in regards to import | I'm a python newbie and starting out with using the Bottle web framework on Google App Engine. I've been messing with the super small, super easy Hello World sample and have already ran into problems. Heh. I finally got the code to work with this...
import bottle
from bottle import route
from google.appengine.ext.we... | [
"In your code you have two different ways of calling methods from bottle package.\nroute('/hello')\n\nand \nbottle.default_app()\n\nFirst call requires from bottle import route or from bottle import * and second one requires import bottle.\nfrom foo import bar is letting you to use method or parameter bar in your c... | [
8,
5,
3,
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002452567_google_app_engine_python.txt |
Q:
Unable to resolve url. Received error- Reverse for 'satchmo_search' with arguments '()' and keyword arguments '{}' not found
I'm installing Satchmo following these instructions: http://forum.webfaction.com/viewtopic.php?pid=10579#p10579
When I want to check my installation, I get the following error:
$ python mana... | Unable to resolve url. Received error- Reverse for 'satchmo_search' with arguments '()' and keyword arguments '{}' not found | I'm installing Satchmo following these instructions: http://forum.webfaction.com/viewtopic.php?pid=10579#p10579
When I want to check my installation, I get the following error:
$ python manage.py satchmo_check
Checking your satchmo configuration.
Using Django version 1.2.5
Using Satchmo version 0.9.2-pre hg-unknown
The... | [
"You are overriding the urls you are importing.\nChange your urls.py file like so:\nfrom django.conf.urls.defaults import *\nfrom satchmo_store.urls import urlpatterns\n\nurlpatterns += patterns('',\n\n # Your urls go here\n\n)\n\nor \nfrom django.conf.urls.defaults import *\nfrom satchmo_store.urls import urlpa... | [
3
] | [] | [] | [
"django",
"python",
"satchmo",
"webfaction"
] | stackoverflow_0005127686_django_python_satchmo_webfaction.txt |
Q:
is json the answer to this: python program will talk and javascript will listen?
the same problem haunting me a month ago is still haunting me now. i know ive asked several questions regarding this on this site and i am truly sorry for that. your suggestions have all been excellent but the answer is still elusive.... | is json the answer to this: python program will talk and javascript will listen? | the same problem haunting me a month ago is still haunting me now. i know ive asked several questions regarding this on this site and i am truly sorry for that. your suggestions have all been excellent but the answer is still elusive. i now realize that this is a direct result of me not being able to phrase my question... | [
"If I understand what you're asking, the \"cellphone\" is TCP/IP. The javascript is not server-side; it runs on the client side, and alters what the client's browser displays based on json data that it downloads from the server -- data that in this case is generated by Python. \nThis question provides a relevant ex... | [
2,
1,
0,
0,
0
] | [] | [] | [
"javascript",
"json",
"python"
] | stackoverflow_0005128454_javascript_json_python.txt |
Q:
How do I enforce domain integrity in a Django app transparently?
Here's the situation. I've got an app with multiple users and each user has a group/company they belong to. There is a company field on all models meaning there's a corresponding company_id column in every table in the DB. I want to transparently enf... | How do I enforce domain integrity in a Django app transparently? | Here's the situation. I've got an app with multiple users and each user has a group/company they belong to. There is a company field on all models meaning there's a corresponding company_id column in every table in the DB. I want to transparently enforce that, when a user tries to access any object, they are always res... | [
"You could do something like this:\nfrom django.db import models\nfrom django.db.models.query import QuerySet\n\nclass DomainQuerySet(QuerySet):\n def applicable(self, user=None):\n if user is None:\n return self\n else:\n return self.filter(company=user.company)\n\nclass Doma... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005127811_django_python.txt |
Q:
Performance of running code in stani python editor vs IDLE/terminal/gvim
Am just curious and wondering why it takes longer for python code to execute when run from inside Stani Python Editor in comparison to when run from IDLE or the terminal or even inside gvim.
A:
SPE has an object explorer, and debugger. Mayb... | Performance of running code in stani python editor vs IDLE/terminal/gvim | Am just curious and wondering why it takes longer for python code to execute when run from inside Stani Python Editor in comparison to when run from IDLE or the terminal or even inside gvim.
| [
"SPE has an object explorer, and debugger. Maybe these slow things down a bit.\n"
] | [
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0005127521_performance_python.txt |
Q:
python parse configuration file, containing list of filenames
I would like to parse a config file, containing list of filenames, divided in sections:
[section1]
path11/file11
path12/file12
...
[section2]
path21/file21
..
I tried ConfigParser, but it requires pairs of name-value. How can I parse such a file?
A:
... | python parse configuration file, containing list of filenames | I would like to parse a config file, containing list of filenames, divided in sections:
[section1]
path11/file11
path12/file12
...
[section2]
path21/file21
..
I tried ConfigParser, but it requires pairs of name-value. How can I parse such a file?
| [
"Likely you have to implement the parser on your own.\nBlueprint:\nkey = None\ncurrent = list()\nfor line in file(...):\n\n if line.startswith('['):\n if key:\n print key, current\n key = line[1:-1]\n current = list()\n\n else:\n current.append(line)\n\n",
"Here is an iterato... | [
1,
1
] | [] | [] | [
"config",
"parsing",
"python"
] | stackoverflow_0005126187_config_parsing_python.txt |
Q:
Python: sorting an array with another array's elements as keys?
import numpy as np
x = np.array(range(10 * 30)).reshape(100, 3)
y = np.array(range(1010, 10, -10))
res = sorted(x, key = lambda y:y) #ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
res = sorted(... | Python: sorting an array with another array's elements as keys? | import numpy as np
x = np.array(range(10 * 30)).reshape(100, 3)
y = np.array(range(1010, 10, -10))
res = sorted(x, key = lambda y:y) #ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
res = sorted(x, key=y) #TypeError: 'tuple' object is not callable
| [
"Try argsort:\nimport numpy as np\nx = np.array(range(10 * 30)).reshape(100, 3)\ny = np.array(range(1010, 10, -10))\nargs = y.argsort(axis = 0)\nprint x[args]\n\n"
] | [
2
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0005128787_python_sorting.txt |
Q:
For in In lists
I'm trying to do something like that, in a nutshell...
house = ['yes', 'no','maybe']
x = range(3)
for x in house
print[x]
I want to loop over a list but I got 'type error: list indices must be integers not Tags.' How can I achieve this ?
A:
If you want to iterate over a list, you don't need ... | For in In lists | I'm trying to do something like that, in a nutshell...
house = ['yes', 'no','maybe']
x = range(3)
for x in house
print[x]
I want to loop over a list but I got 'type error: list indices must be integers not Tags.' How can I achieve this ?
| [
"If you want to iterate over a list, you don't need an index at all:\nfor x in house:\n print x # prints every house\n\nIf you want an index, you can use different approaches:\n# generate indexes on the fly\nfor i, a_house in enumerate(house):\n print i, a_house # prints 0 yes, 1 no, 2 maybe\n\n# access by index\... | [
7,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005128836_python.txt |
Q:
Django / psycopg2 / postgresql probably broken models give useless stack trace
I'm working on integrating OpenID with my own authentication Stack for Django. I'm using python-openid, django 1.2.5 with postgresql, following the examples from the djopenid folder under examples/
What's happening is this. I'm using a ... | Django / psycopg2 / postgresql probably broken models give useless stack trace | I'm working on integrating OpenID with my own authentication Stack for Django. I'm using python-openid, django 1.2.5 with postgresql, following the examples from the djopenid folder under examples/
What's happening is this. I'm using a view that calls python-openid's various mechanisms, which rely on models I've fed in... | [
"Run it via manage.py on some port, place ipdb.set_trace() call in your view and trace it step by step - like in any other debugging process.\nAlso you can use built-in python/django logging features and just print our stuff to the log file.\nLook here for more tips - maybe some of them will be usefull for you.\n"
... | [
3
] | [] | [] | [
"django",
"postgresql",
"python",
"stack_trace"
] | stackoverflow_0005128713_django_postgresql_python_stack_trace.txt |
Q:
Python - "NameError: name 'c_bool' is not defined"
I am trying to use the python library mosquitto for writing a program for maemo. I am using the package libmosquitto, which provides a mosquitto.py library file (http://mosquitto.org/documentation/python/).
The program import mosquitto using the following line of... | Python - "NameError: name 'c_bool' is not defined" | I am trying to use the python library mosquitto for writing a program for maemo. I am using the package libmosquitto, which provides a mosquitto.py library file (http://mosquitto.org/documentation/python/).
The program import mosquitto using the following line of code:
import mosquitto
The program runs fine on my des... | [
"c_bool isn't defined in python 2.5. It's new in 2.6:\nhttp://docs.python.org/library/ctypes.html#ctypes.c_bool\nPossibly you could get away with adding\nc_bool = c_int\n\nafter the line that reads\nfrom ctypes import *\n\nin mosquitto.py. Seems sketchy though...\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0005128946_python.txt |
Q:
Help with ping via Popen
I'm developing a software to monitor communication to different locations.
the principle is simple: send ping every second and display the results in real time (ms delay, packet loss etc)
It's also important to mention that I'm running the software from Linux, so in order to ping from my s... | Help with ping via Popen | I'm developing a software to monitor communication to different locations.
the principle is simple: send ping every second and display the results in real time (ms delay, packet loss etc)
It's also important to mention that I'm running the software from Linux, so in order to ping from my software i choose the subporoce... | [
"This looks like a good starting point:\nhttp://pypi.python.org/pypi/ping/0.1\nOf course, it's not clear that there is any problem with what you're doing now really. Since the ping time is being parsed from the output of ping it's not like we can blame process spawning overhead or something.\n",
"Try adding clos... | [
1,
0
] | [] | [] | [
"linux",
"multithreading",
"ping",
"popen",
"python"
] | stackoverflow_0005128727_linux_multithreading_ping_popen_python.txt |
Q:
Searching for a random python program generator
I'm searching for a program that can generate random but valid python programs, similar to the
Random C program generator.
I was trying to do this myself giving random input to the python tokenize.untokenize() function, but of course most of the generated source cod... | Searching for a random python program generator | I'm searching for a program that can generate random but valid python programs, similar to the
Random C program generator.
I was trying to do this myself giving random input to the python tokenize.untokenize() function, but of course most of the generated source code was not a valid program I could interpret with eval... | [
"A google search for python \"random program generator\" turned up the Random Python Program Generator.\nIf you want a downloadable script, take a look at pyfuzz.\n",
"Performing genetic programming to evolve imperative programs is not completely trivial.\nIt is probably worth some consideration as to what repres... | [
4,
2
] | [
"I recommend PushGP. Here is a link to a python class.\n"
] | [
-1
] | [
"genetic_programming",
"metaprogramming",
"python",
"random"
] | stackoverflow_0005128612_genetic_programming_metaprogramming_python_random.txt |
Q:
How do I change the look and feel of the wxPython tool bar?
The wxPython ToolBar look and feel does not match that of the current operating system - it has a gradient similar to the Windows Vista / 7 menubar I.E. a silver gradient.
Is there any way to change this so that it blends in with the operating systems loo... | How do I change the look and feel of the wxPython tool bar? | The wxPython ToolBar look and feel does not match that of the current operating system - it has a gradient similar to the Windows Vista / 7 menubar I.E. a silver gradient.
Is there any way to change this so that it blends in with the operating systems look and feel?
Note: There is a style flag that can be set when crea... | [
"It seems the solution to my problem is actually quite simple. Instead of trying to apply some custom paint logic all that was required was a call to the toolbars SetBackgroundColour() method.\nThe system look and feel can be maintained by using the colours from the wx.SystemSettings class.\nself.toolbar.SetBackgro... | [
6,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004704913_python_wxpython.txt |
Q:
How can I serve a (never ending) system call with Tornado
For instance, suppose I have this code:
def dump():
tcpdump = subprocess.Popen("tcpdump -nli any",
stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
outputfile = tcpdump.stdout
for line in outputfile:
print line,
How ... | How can I serve a (never ending) system call with Tornado | For instance, suppose I have this code:
def dump():
tcpdump = subprocess.Popen("tcpdump -nli any",
stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
outputfile = tcpdump.stdout
for line in outputfile:
print line,
How can I serve the output of such to the browser?
Since there is n... | [
"Redirect tcpdump's output to a file and use this:\nhttps://bitbucket.org/silverspell/tornadolog\nHope it helps :)\n"
] | [
1
] | [] | [] | [
"epoll",
"io",
"python",
"system_calls",
"tornado"
] | stackoverflow_0005090828_epoll_io_python_system_calls_tornado.txt |
Q:
Pylons application Internationalization
What the best way to make pylons application internationalist?
A:
A Google search finds these docs.
A:
PyICU and I highly recommend Babel.
Also if you need SEO you should read this:
http://my.opera.com/WebApplications/blog/2008/03/17/search-engine-friendly
If want more i... | Pylons application Internationalization | What the best way to make pylons application internationalist?
| [
"A Google search finds these docs.\n",
"PyICU and I highly recommend Babel.\nAlso if you need SEO you should read this:\nhttp://my.opera.com/WebApplications/blog/2008/03/17/search-engine-friendly\nIf want more info (you can start using babel in five minutes), read the pylons book its free:\nhttp://pylonsbook.com/... | [
2,
0
] | [] | [] | [
"internationalization",
"pylons",
"python"
] | stackoverflow_0002341387_internationalization_pylons_python.txt |
Q:
What is a cofunction and how would it work in Python?
I am reading PEP-3153, but I don't understand what the problem is it wants to address.
Could you please explain?
A:
You can Google "Python coroutines" and get a lot of good information. Here is a presentation (PDF) I ran across some time ago that seemed prett... | What is a cofunction and how would it work in Python? | I am reading PEP-3153, but I don't understand what the problem is it wants to address.
Could you please explain?
| [
"You can Google \"Python coroutines\" and get a lot of good information. Here is a presentation (PDF) I ran across some time ago that seemed pretty good to me about the how and why. The source code is also available (this includes the PDF, so if you want both, just download this). The home page for this presentatio... | [
6,
3,
1
] | [] | [] | [
"language_design",
"language_features",
"python"
] | stackoverflow_0005122994_language_design_language_features_python.txt |
Q:
Ubuntu access rights - Mod_Python Permission denied
I am running Ubuntu with an Apache webserver with Mod_python. The root directory of the web server is /var/www
I have a form for uploading files. The uploaded files should be stored in folder /var/www/xy/uploads by a python script.
But when I use this script, I r... | Ubuntu access rights - Mod_Python Permission denied | I am running Ubuntu with an Apache webserver with Mod_python. The root directory of the web server is /var/www
I have a form for uploading files. The uploaded files should be stored in folder /var/www/xy/uploads by a python script.
But when I use this script, I receive an error:
Permission denied: '/var/www/xy/uploads... | [
"Your directory permissions are set for only allowing writing for the owner of the directory.\ntry this:\nsudo chown www-data:www-data /var/www/xy/\nsudo chmod -R g+rw /var/wwww/xy/uploads\n\nAlso, I'd advise against using mod_python as it is deprecated, look into mod_wsgi instead.\n"
] | [
2
] | [] | [] | [
"mod_python",
"python",
"rights_management",
"ubuntu"
] | stackoverflow_0005129819_mod_python_python_rights_management_ubuntu.txt |
Q:
Read flat file as transpose, python
I'm interested in reading fixed width text files in Python in as efficient a manner as I can. Specifically, most of the time I'm interested in one or more columns in the flat file but not entire records.
It strikes me as inefficient to read the file a line at a time and extrac... | Read flat file as transpose, python | I'm interested in reading fixed width text files in Python in as efficient a manner as I can. Specifically, most of the time I'm interested in one or more columns in the flat file but not entire records.
It strikes me as inefficient to read the file a line at a time and extract the desired columns after reading the e... | [
"Files are laid out as a (one-dimensional) sequence of bits. 'Lines' are just a convenience we added to make things easy to read for humans. So, in general, what you're asking is not possible on plain files. To pull this off, you would need some way of finding where a record starts. The two most common ways are:\n\... | [
4,
3,
3,
1
] | [] | [] | [
"flat_file",
"python",
"transpose"
] | stackoverflow_0005129840_flat_file_python_transpose.txt |
Q:
Are there any live Pinax demos out there?
Pinax package wraps some pretty fancy stuff. Are there any live demos out there that one could browse without installing/setting up Pinax?
A:
There is mention of sites built with pinax at their project page itself. You may want to choose any of the site, create an accoun... | Are there any live Pinax demos out there? | Pinax package wraps some pretty fancy stuff. Are there any live demos out there that one could browse without installing/setting up Pinax?
| [
"There is mention of sites built with pinax at their project page itself. You may want to choose any of the site, create an account and login to see their customization page. This may perhaps give you some idea.\n"
] | [
4
] | [
"There used to be cloud27. It was their official demo. But it's disabled for some reason.\n"
] | [
-1
] | [
"demo",
"django",
"pinax",
"python"
] | stackoverflow_0004928672_demo_django_pinax_python.txt |
Q:
Python - Set class property to depend on values of other properties in the same class
Sorry if this already exists somewhere in the question archives, but I'm not sure how to ask it and searching didn't lead to any great revelations.
In Python (2.6.x) I have created a class
class timetuple(object):
def __init_... | Python - Set class property to depend on values of other properties in the same class | Sorry if this already exists somewhere in the question archives, but I'm not sure how to ask it and searching didn't lead to any great revelations.
In Python (2.6.x) I have created a class
class timetuple(object):
def __init__(self):
self.weekday = 6
self.month = 1
self.day = 1
... | [
"You want to actually define a property, as opposed to a variable:\nclass A(object):\n\n def __init__(self):\n self.a = 1\n self.b = 1\n\n @property\n def a_plus_b(self):\n return self.a + self.b\n\nfoo = A()\nprint foo.a_plus_b # prints \"2\"\nfoo.a = 3\nprint foo.a_plus_b # prints \"... | [
10
] | [] | [] | [
"class",
"function",
"methods",
"properties",
"python"
] | stackoverflow_0005130301_class_function_methods_properties_python.txt |
Q:
Order list by queryset count in Django/Python
Sorry this is basic, but I'm new to Python and Django.
I have a list of users who have performed an action that is being saved in a separate table. I want to show a list of these users, sorted by how many times they've taken the other action.
I understand how to get th... | Order list by queryset count in Django/Python | Sorry this is basic, but I'm new to Python and Django.
I have a list of users who have performed an action that is being saved in a separate table. I want to show a list of these users, sorted by how many times they've taken the other action.
I understand how to get the counts:
users = User.objects.all()
for user in us... | [
"Annotate / Aggregation\nhttp://docs.djangoproject.com/en/dev/topics/db/aggregation/\nfrom django.db.models import Count\nusers = User.objects.annotate(action_count=Count('action')).order_by('action_count')\n# note that this also saves your extra query PER user object.\n\n{% for user in users %}\n {{ user.action_... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005130836_django_python.txt |
Q:
Facing problem in returning the ongoing upload status back to the HTML using AJAX in Django
I am trying to implement "Upload Progress Bar" in Django.
Following is my code in the template file:
{% extends "index_base.html" %}
{% block content %}
<script src="/media/js/functions.js" type="text/javascrip... | Facing problem in returning the ongoing upload status back to the HTML using AJAX in Django | I am trying to implement "Upload Progress Bar" in Django.
Following is my code in the template file:
{% extends "index_base.html" %}
{% block content %}
<script src="/media/js/functions.js" type="text/javascript"></script>
<script src="/media/js/jquery.js" type="text/javascript"> </script>
<scrip... | [
"I recently had to do a bit of digging to find a solution for this myself.\nCheck out :-\nhttp://fairviewcomputing.com/blog/2008/10/21/ajax-upload-progress-bars-jquery-django-nginx/\nI have not tried the solution referenced yet, but it looks reasonable enough.\nIt involves registering a custom file upload class to ... | [
2
] | [] | [] | [
"ajax",
"django",
"file_upload",
"python"
] | stackoverflow_0005102920_ajax_django_file_upload_python.txt |
Q:
Partial matches in a dictionary
Assume I have the following dictionary mapping of domain names to it's human readable description
domain_info = {"google.com" : "A Search Engine",
"facebook.com" : "A Social Networking Site",
"stackoverflow.com" : "Q&A Site for Programmers"}
I would ... | Partial matches in a dictionary | Assume I have the following dictionary mapping of domain names to it's human readable description
domain_info = {"google.com" : "A Search Engine",
"facebook.com" : "A Social Networking Site",
"stackoverflow.com" : "Q&A Site for Programmers"}
I would like to get the description from resp... | [
"What does \"too slow for large number of operations\" mean? It's still going to work in constant time (for each URL) and you can't get any better than that. The above seems to be a perfectly good way to do it.\nIf you need it to be a bit faster (but it wouldn't be terribly faster), you could write your own regex. ... | [
2,
1,
1,
1
] | [] | [] | [
"dictionary",
"python",
"url"
] | stackoverflow_0005130799_dictionary_python_url.txt |
Q:
Django models and multilingual websites
I have a model that has multiple text properties - title, short and long description etc. I want to have multilanguage site so I need a way to easy by able to add new languages and translations for this field for every item. What is the best way to achieve this?
A:
Django ... | Django models and multilingual websites | I have a model that has multiple text properties - title, short and long description etc. I want to have multilanguage site so I need a way to easy by able to add new languages and translations for this field for every item. What is the best way to achieve this?
| [
"Django has built-in support for I18N (read internationalization):\n\nhttp://docs.djangoproject.com/en/dev/topics/i18n/internationalization/\n\nSome possible multilingual model candidates:\n\nhttp://code.google.com/p/django-multilingual-model/\nhttp://and-other-things.blogspot.com/2009/04/list-of-django-multilingua... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"multilingual",
"python"
] | stackoverflow_0003690715_django_django_models_multilingual_python.txt |
Q:
Custom Python Encryption algorithm
Hey, I have been working on this for a while, and I can remebr my brother stepped me through this very same alogorithm.
Basicly, it just adds the ascii values of both the characters from the key, and the phrase.
I can encrypt it with this:
def encrypt(key, string):
encoded = ... | Custom Python Encryption algorithm | Hey, I have been working on this for a while, and I can remebr my brother stepped me through this very same alogorithm.
Basicly, it just adds the ascii values of both the characters from the key, and the phrase.
I can encrypt it with this:
def encrypt(key, string):
encoded = ''
for i in range(len(string)):
... | [
"That's simple, let's see how it works. First of all, the encrypted message is obtained by subtracting the key.\nenc = msg + key (mod 127)\n\nHow can we obtain the original message? That's easy, subtract the key in both sides\nenc - key = msg + key - key (mod 127)\n\nAnd here we get:\nenc - key = msg (mod 127)\n\nF... | [
14,
2,
0
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0005131227_encryption_python.txt |
Q:
How to recognize any four ints in Python
I am trying to scrape a series of websites that look like the following three examples:
www.examplescraper.com/fghxbvn/17901234.html
www.examplescraper.com/fghxbvn/17911102.html
www.examplescraper.com/fghxbvn/17921823.html
Please, keep in mind that there are 200 of these w... | How to recognize any four ints in Python | I am trying to scrape a series of websites that look like the following three examples:
www.examplescraper.com/fghxbvn/17901234.html
www.examplescraper.com/fghxbvn/17911102.html
www.examplescraper.com/fghxbvn/17921823.html
Please, keep in mind that there are 200 of these websites and I'd like to iterate through a loop... | [
"I don't exactly follow your question, but you can use the re module to easily parse out text of a specific format like you have here. For instance:\n>>> import re\n>>> url = \"www.examplescraper.com/fghxbvn/17901234.html\"\n>>> re.match( \"(\\S+/)(\\d{4})(\\d{4}).html\", url ).groups()\n('www.examplescraper.com/fg... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005131347_python.txt |
Q:
OpenCV 2.0 and Python
I cannot get the example Python programs to run. When executing the Python command "from opencv import cv" I get the message "ImportError: No module named _cv". There is a stale _cv.pyd in the site-packages directory, but no _cv.py anywhere. See step 5 below.
MS Windows XP, VC++ 2008, Pytho... | OpenCV 2.0 and Python | I cannot get the example Python programs to run. When executing the Python command "from opencv import cv" I get the message "ImportError: No module named _cv". There is a stale _cv.pyd in the site-packages directory, but no _cv.py anywhere. See step 5 below.
MS Windows XP, VC++ 2008, Python 2.6, OpenCV 2.0
Here's wh... | [
"You should install opencv using python dist utils. This can be accomplished by going to the opencv directory, and typing:\npython setup.py install\n\nEdit:\nopenCV uses distutils, but somewhat indirectly. On UNIX the installation is more along the lines of: \nconfigure\nmake -j 8\nmake install\n\nFor Windows, the ... | [
4,
3,
1,
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0002195441_opencv_python.txt |
Q:
multiplication result is negative zero
can someone tell me why the output of the code mentioned below is negative zero??
a * b = -0
here 'a' is of type long, b is an object of decimal class.....and if a=-28 and b=0, then the output is -0
A:
From the Python decimal docs:
The signed zeros can result from
ca... | multiplication result is negative zero | can someone tell me why the output of the code mentioned below is negative zero??
a * b = -0
here 'a' is of type long, b is an object of decimal class.....and if a=-28 and b=0, then the output is -0
| [
"From the Python decimal docs:\n\nThe signed zeros can result from\n calculations that underflow. They keep\n the sign that would have resulted if\n the calculation had been carried out\n to greater precision. Since their\n magnitude is zero, both positive and\n negative zeros are treated as equal\n and thei... | [
7,
0
] | [] | [] | [
"python"
] | stackoverflow_0005131428_python.txt |
Q:
Writing Python packages with multiple C modules
I am writing a Python C extension which uses the pygame C API. So far so good. Now I wonder how I organize my source code so that I can have multiple submodules in the package. All the tutorials out there focus on one .c file extensions. I tried looking at some proje... | Writing Python packages with multiple C modules | I am writing a Python C extension which uses the pygame C API. So far so good. Now I wonder how I organize my source code so that I can have multiple submodules in the package. All the tutorials out there focus on one .c file extensions. I tried looking at some projects setup.py files but they blew my mind with complex... | [
"I think the easiest way to do this would be to create the package in \"pure python\"; in other words, create mypackage/, create an empty mypackage/__init__.py , and then put your extension modules at mypackage/module1.so, mypackage/module2.so, and so on.\nIf you want things in mypackage instead of it being empty, ... | [
14,
1
] | [] | [] | [
"module",
"organization",
"python"
] | stackoverflow_0002185197_module_organization_python.txt |
Q:
Deploying flask on cherokee and uwsgi
I'm attempting to deploy a flask web app I've developed using cherokee and uwsgi. I got cherokee and uwsgi installed and working (i think uwsgi works), but when I configure the app in cherokee, i just get an error saying uWSGI Error wsgi application not found. I used an xml co... | Deploying flask on cherokee and uwsgi | I'm attempting to deploy a flask web app I've developed using cherokee and uwsgi. I got cherokee and uwsgi installed and working (i think uwsgi works), but when I configure the app in cherokee, i just get an error saying uWSGI Error wsgi application not found. I used an xml config file (I think you need to with cheroke... | [
"Always try uWSGI deploy without a webserver, before going in production.\nuwsgi -x <xmlfile>\nIt will print a lot of information/errors\n",
"Roberto's suggestion is a good one; it will help diagnose where the error is occurring (i.e. whether it's uWSGI or Cherokee).\nI've also recently fought to get uWSGI and Ch... | [
2,
2
] | [] | [] | [
"cherokee",
"flask",
"python",
"uwsgi"
] | stackoverflow_0005131459_cherokee_flask_python_uwsgi.txt |
Q:
Shortest/Best way to do this list task in Python
I'm learning Python. I'd like to do the following task:
Input: a list: e.g., ['a', 'b', 'c']
Output: a single string that concatenate all elements in the list, while each element is modifed in the same way for all elements.
For example, I'd like to add "-temp" to ... | Shortest/Best way to do this list task in Python | I'm learning Python. I'd like to do the following task:
Input: a list: e.g., ['a', 'b', 'c']
Output: a single string that concatenate all elements in the list, while each element is modifed in the same way for all elements.
For example, I'd like to add "-temp" to each element in the list. So, the output would be:
"a-... | [
">>> ' '.join( x+'-temp' for x in ['a', 'b', 'c'] )\n'a-temp b-temp c-temp'\n\n",
"List comprehensions are your friend:\nlst = ['a', 'b', 'c']\nprint ' '.join(['%s-temp' % item for item in lst])\n\n",
"Use list comprehensions when you need to access and use each element of a list. Example:\nl = ['a', 'b', 'c']... | [
8,
3,
3,
3,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005132036_list_python.txt |
Q:
Call method dynamically if it exists in Django
I'm creating website based on Django (I know it's pure Python, so maybe it could be also answered by people who knows Python well) and I need to call some methods dynamically.
For example I have few applications (modules) in my website with the method "do_search()" in... | Call method dynamically if it exists in Django | I'm creating website based on Django (I know it's pure Python, so maybe it could be also answered by people who knows Python well) and I need to call some methods dynamically.
For example I have few applications (modules) in my website with the method "do_search()" in the views.py. Then I have one module called for exa... | [
"I'm not sure if I truly understand the question, but please clarify in a comment to my answer if I'm off.\n# search.py\nsearchables = []\n\ndef search(search_string):\n return [s.do_search(search_string) for s in searchables]\n\ndef register_search_engine(searchable):\n if hasattr(searchable, 'do_search'):\n... | [
3,
0
] | [] | [] | [
"django",
"dynamic",
"python"
] | stackoverflow_0005132134_django_dynamic_python.txt |
Q:
Getting a count of action from today's date from filtered results in Python
I have an action that a user can do many times a day. I'm trying to get a count of how many times the user has taken that action, but only for today's date. Here's the way I'm currently solving this, but is there an easier way? I feel lik... | Getting a count of action from today's date from filtered results in Python | I have an action that a user can do many times a day. I'm trying to get a count of how many times the user has taken that action, but only for today's date. Here's the way I'm currently solving this, but is there an easier way? I feel like I should be able to fit this in one line. :)
today_slaps = 0
slaps = Slap.objec... | [
"slap_count = Slap.objects.filter(from_user=request.user, \\ \n date__gte=datetime.date.today()).count()\n\n# specifically setting datetimefield=datetime.date.today() won't work\n# gte = will work for datetimefield vs datetime object starting at that date\n# it's also assumed there will never b... | [
2,
0
] | [] | [] | [
"datetime",
"django",
"python"
] | stackoverflow_0005131384_datetime_django_python.txt |
Q:
python IRC buffer not clearing
I have a simply buffer system for my IRC bot so it never misses a line due to network lag and such.
I am using the following code to start the loop that processes information received from the server:
while 1: #Start the main loop
self.readbuffer += s.recv(1024).decode()
temp... | python IRC buffer not clearing | I have a simply buffer system for my IRC bot so it never misses a line due to network lag and such.
I am using the following code to start the loop that processes information received from the server:
while 1: #Start the main loop
self.readbuffer += s.recv(1024).decode()
temp=self.readbuffer.split("\n")
sel... | [
"Where do you try to clear the buffer?\nself.readbuffer += s.recv(1024).decode() adds more data to readbuffer.\ntemp=self.readbuffer.split(\"\\n\") turns readbuffer into a list of one-line strings\nself.readbuffer=temp.pop() makes readbuffer the last line\nIf readbuffer never gets smaller, it must be because you ne... | [
0
] | [] | [] | [
"buffer",
"irc",
"python"
] | stackoverflow_0005132027_buffer_irc_python.txt |
Q:
Why urllib returns garbage from some wikipedia articles?
>>> import urllib2
>>> good_article = 'http://en.wikipedia.org/wiki/Wikipedia'
>>> bad_article = 'http://en.wikipedia.org/wiki/India'
>>> req1 = urllib2.Request(good_article)
>>> req2 = urllib2.Request(bad_article)
>>> req1.add_header('User-Agent', 'Mozill... | Why urllib returns garbage from some wikipedia articles? | >>> import urllib2
>>> good_article = 'http://en.wikipedia.org/wiki/Wikipedia'
>>> bad_article = 'http://en.wikipedia.org/wiki/India'
>>> req1 = urllib2.Request(good_article)
>>> req2 = urllib2.Request(bad_article)
>>> req1.add_header('User-Agent', 'Mozilla/5.0')
>>> req2.add_header('User-Agent', 'Mozilla/5.0')
>>> r... | [
"It's not an environment, locale, or encoding problem. The offending stream of bytes is gzip-compressed. The \\x1f\\x8B at the start is what you get at the start of a gzip stream with the default settings.\nLooks as though the server is ignoring the fact that you didn't do\nreq2.add_header('Accept-encoding', 'gzip'... | [
9,
1,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0005131985_python_urllib2.txt |
Q:
Is it safe to refer to a possibly nonexistant variable after a check in an if statement?
Say I have a myObject class with a member called prop. I have a variable var which may or may not be a myObject. I want to check if prop holds a certain value, and if so, do something, and if it doesn't, or var is not a myObje... | Is it safe to refer to a possibly nonexistant variable after a check in an if statement? | Say I have a myObject class with a member called prop. I have a variable var which may or may not be a myObject. I want to check if prop holds a certain value, and if so, do something, and if it doesn't, or var is not a myObject, do nothng.
Would it be safe to do the following:
if isinstance(var, myObject) and var.prop... | [
"To answer your question, yes, and short circuits. But I wouldn't do it that way. A better method is to use hasattr or a try, except block.\nif hasattr(var, 'prop') and var.prop == 10:\n print var.prop\n\nOr (if it's unusual for a propless var to come along):\ntry:\n print var.prop\nexcept AttributeError:\n ... | [
5
] | [] | [] | [
"boolean",
"if_statement",
"logic",
"python"
] | stackoverflow_0005132267_boolean_if_statement_logic_python.txt |
Q:
Python Logic in searching String
filtered=[]
text="any.pdf"
if "doc" and "pdf" and "xls" and "jpg" not in text:
filtered.append(text)
print(filtered)
This is my first Post in Stack Overflow, so excuse if there's something annoying in Question, The Code suppose to append text if text doesn't include any of the... | Python Logic in searching String | filtered=[]
text="any.pdf"
if "doc" and "pdf" and "xls" and "jpg" not in text:
filtered.append(text)
print(filtered)
This is my first Post in Stack Overflow, so excuse if there's something annoying in Question, The Code suppose to append text if text doesn't include any of these words:doc,pdf,xls,jpg.
It works fin... | [
"If you open up a python interpreter, you'll find that \"doc\" and \"pdf\" and \"xls\" and \"jpg\" is the same thing as 'jpg':\n>>> \"doc\" and \"pdf\" and \"xls\" and \"jpg\"\n'jpg'\n\nSo rather than testing against all the strings, your first attempt only tests against 'jpg'. \nThere are a number of ways to do wh... | [
6,
4,
3,
1,
1
] | [] | [] | [
"logic",
"python"
] | stackoverflow_0005131977_logic_python.txt |
Q:
producer/consumer problem with python multiprocessing
I am writing a server program with one producer and multiple consumers,
what confuses me is only the first task producer put into the queue gets
consumed, after which tasks enqueued no longer get consumed, they remain
in the queue forever.
from multiprocessing ... | producer/consumer problem with python multiprocessing | I am writing a server program with one producer and multiple consumers,
what confuses me is only the first task producer put into the queue gets
consumed, after which tasks enqueued no longer get consumed, they remain
in the queue forever.
from multiprocessing import Process, Queue, cpu_count
from http import httpserv
... | [
"I think there must be something wrong with the web server part, as this works perfectly:\nfrom multiprocessing import Process, Queue, cpu_count\nimport random\nimport time\n\n\ndef serve(queue):\n works = [\"task_1\", \"task_2\"]\n while True:\n time.sleep(0.01)\n queue.put(random.choice(works)... | [
12,
4,
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0000914821_multiprocessing_python.txt |
Q:
unable to install PunJab
I am unable to install PunJab on my system.
PunJab is a HTTP jabber client
interface. It is a BOSH connection
manager that allows persistent client
connections to a XMPP server.
When I type the following command
python setup.py install
It says invalid syntax error.. I have pyth... | unable to install PunJab | I am unable to install PunJab on my system.
PunJab is a HTTP jabber client
interface. It is a BOSH connection
manager that allows persistent client
connections to a XMPP server.
When I type the following command
python setup.py install
It says invalid syntax error.. I have python 2.7 and twisted python 10.2... | [
"wat the heck is punjab?? I have no clue what it is.. But anyways when you add it to your system path it doesnt become part of your system path immediately.. A restart is normally required.\nInstead what I would suggest is go to your python install directory and find the executable or python script that is needed ... | [
1
] | [] | [] | [
"python",
"xmpp"
] | stackoverflow_0005132809_python_xmpp.txt |
Q:
Reading a website with asyncore
I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell.
I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manu... | Reading a website with asyncore | I would like to read a website asynchronously, which isnt possible with urllib as far as I know. Now I tried reading with with plain sockets, but HTTP is giving me hell.
I run into all kind of funky encodings, for example transfer-encoding: chunked, have to parse all that stuff manually, and I feel like coding C, not p... | [
"You can implement an asynchronous call yourself. For each call, start a new thread (or try to get one from a pool) and use a callback to process it.\nYou can do this very nicely with a decorator:\ndef threaded(callback=lambda *args, **kwargs: None, daemonic=False):\n \"\"\"Decorate a function to run in its own... | [
7,
5,
1,
1
] | [] | [] | [
"python",
"sockets",
"web_services"
] | stackoverflow_0001367453_python_sockets_web_services.txt |
Q:
Drawing rectangular nodes in graph + python
I am trying to visualise a btree in python and would like help for it.
I have a node list of elements and I want it to be displayed in a rectangular node of its exact size.
I know that one method is simply create a node and have its label as a complete list but I am want... | Drawing rectangular nodes in graph + python | I am trying to visualise a btree in python and would like help for it.
I have a node list of elements and I want it to be displayed in a rectangular node of its exact size.
I know that one method is simply create a node and have its label as a complete list but I am want it look more nice that is create a rectangular n... | [
"Try Graphviz, a graph visualization tool that's been around for a long time. \nHere's a Python binding: http://networkx.lanl.gov/pygraphviz/\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005132531_python.txt |
Q:
printSoln module problem
Hi I found in book:Numerical Methods in engineering with Python the module run_kut5, but for that module I need module printSoln, all provided in the book. Now I cp the code, made necessary line adjustments and so. The code looks like:
# -*- coding: cp1250 -*-
## module printSoln
''' pri... | printSoln module problem | Hi I found in book:Numerical Methods in engineering with Python the module run_kut5, but for that module I need module printSoln, all provided in the book. Now I cp the code, made necessary line adjustments and so. The code looks like:
# -*- coding: cp1250 -*-
## module printSoln
''' printSoln(X,Y,freq).
Prints X... | [
"I would guess it's a tabs/spaces problem - check that you don't have mixed tabs and spaces in the indentation.\nEDIT: If it's not indentation, and since your error message contains \"<module>\" and not a filename, I'm guessing you're pasting this into an interactive interpreter.\nInstead, you should paste the code... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005133134_python.txt |
Q:
What does ImportError mean in Python?
I try to import a module:
import cv
And I get the following error message:
ImportError: DLL load failed: The specified module could not be found.
But if I try to import a library that definitely does not exist, for example:
import blabla
I get:
ImportError: No module named ... | What does ImportError mean in Python? | I try to import a module:
import cv
And I get the following error message:
ImportError: DLL load failed: The specified module could not be found.
But if I try to import a library that definitely does not exist, for example:
import blabla
I get:
ImportError: No module named blabla
So, I conclude the the cv library i... | [
"In this particular case, \"DLL load failed\" is caused by using Python 2.6 with OpenCV 2.2. You should use Python 2.7, because cv.pyd is linked with python27.dll.\n",
"ImportError can be confusing because it can be thrown when the module you are trying to import tries to import something else and because all of ... | [
3,
1,
0
] | [] | [] | [
"dll",
"import",
"importerror",
"python"
] | stackoverflow_0005064760_dll_import_importerror_python.txt |
Q:
pyOpenSSL and the WantReadError
I have a socket server that I am trying to move over to SSL on python 2.5, but I've run into a snag with pyOpenSSL. I can't find any good tutorials on using it, so I'm operating largely on guesses.
Here is how my server sets up the socket:
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.us... | pyOpenSSL and the WantReadError | I have a socket server that I am trying to move over to SSL on python 2.5, but I've run into a snag with pyOpenSSL. I can't find any good tutorials on using it, so I'm operating largely on guesses.
Here is how my server sets up the socket:
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_privatekey_file ("mykey.pem")
ctx.u... | [
"Sometimes in order to send application bytes of an SSL connection, you need to be able to read more bytes from the connection first. WantReadError is how this case is indicated. The only thing you're doing wrong is that you're not handling the WantReadError and then waiting until select indicates that the socket... | [
6
] | [] | [] | [
"pyopenssl",
"python",
"ssl"
] | stackoverflow_0002427947_pyopenssl_python_ssl.txt |
Q:
python: abstract base class' __init__(): initializion or validation?
class ABC is an "abstract base class". class X is its subclass.
There's some work that needs to be done in any subclass of ABC, which is easy to forget or do incorrectly. I'd like ABC.__init__() to help catch such mistakes by either:
(1) startin... | python: abstract base class' __init__(): initializion or validation? | class ABC is an "abstract base class". class X is its subclass.
There's some work that needs to be done in any subclass of ABC, which is easy to forget or do incorrectly. I'd like ABC.__init__() to help catch such mistakes by either:
(1) starting that work, or
(2) validating it
This impacts whether super().__init__() ... | [
"Certainly, one prefers approach 1 to approach 2 (as approach 2 relegates the base to a tag interface rather than fulfilling abstract functionality). But, approach 1 doesn't, by itself, meet your goal of preventing the subtype developer from forgetting to implement the super() call properly, ensuring initialization... | [
16,
2,
1
] | [] | [] | [
"abstract_class",
"oop",
"python",
"software_design"
] | stackoverflow_0005133262_abstract_class_oop_python_software_design.txt |
Q:
Process RGBA data efficiently using python?
I'm trying to process an RGBA buffer (list of chars), and run "unpremultiply" on each pixel. The algorithm is color_out=color*255/alpha.
This is what I came up with:
def rgba_unpremultiply(data):
for i in range(0, len(data), 4):
a = ord(data[i+3])
if ... | Process RGBA data efficiently using python? | I'm trying to process an RGBA buffer (list of chars), and run "unpremultiply" on each pixel. The algorithm is color_out=color*255/alpha.
This is what I came up with:
def rgba_unpremultiply(data):
for i in range(0, len(data), 4):
a = ord(data[i+3])
if a != 0:
data[i] = chr(255*ord(data[i]... | [
"This is exactly the kind of code NumPy is great for.\nimport numpy\n\ndef rgba_unpremultiply(data):\n a = numpy.fromstring(data, 'B') # Treat the string as an array of bytes\n a = a.astype('I') # Cast array of bytes to array of uints, since temporary values needs to be larger than byte\n alpha = a[3::4] #... | [
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005133495_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.