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:
How to handle 'self' argument with Python decorators
I am trying to setup some decorators so that I can do something like:
class Ball(object):
def __init__(self, owner):
self.owner = owner
class Example(CommandSource):
@command
@when(lambda self, ball: ball.owner == self)
def throwBall(se... | How to handle 'self' argument with Python decorators | I am trying to setup some decorators so that I can do something like:
class Ball(object):
def __init__(self, owner):
self.owner = owner
class Example(CommandSource):
@command
@when(lambda self, ball: ball.owner == self)
def throwBall(self, ball):
# code to throw the ball
pass
... | [
"Change your CommandSource as follow:\nclass CommandSource(object):\n\n def listCommands(self, *args, **kwargs):\n commands = []\n for command in dir(self.__class__):\n func = getattr(self, command, None)\n if func == None or getattr(func, 'command', False) == False:\n ... | [
2,
1
] | [] | [] | [
"decorator",
"dsl",
"python"
] | stackoverflow_0002546801_decorator_dsl_python.txt |
Q:
Optimization Techniques in Python
Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more users using that applications. Now the problem is that the application is now very... | Optimization Techniques in Python | Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more users using that applications. Now the problem is that the application is now very critical for the finance team. Now the... | [
"As I said in comment, you must start by finding what part of your code is slow.\nNobody can help you without this information.\nYou can profile your code with the Python profilers then go back to us with the result.\nIf it's a Web app, the first suspect is generally the database. If it's a calculus intensive GUI a... | [
11,
6,
4,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002545820_python.txt |
Q:
How to update the filename of a Django's FileField instance?
Here a simple django model:
class SomeModel(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='video')
I would like to save any instance so that the video's file name would be a valid file name of the tit... | How to update the filename of a Django's FileField instance? | Here a simple django model:
class SomeModel(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='video')
I would like to save any instance so that the video's file name would be a valid file name of the title.
For example, in the admin interface, I load a new instance wit... | [
"If it just happens during save, as per the docs, you can pass a function to upload_to that will get called with the instance and the original filename and needs to return a string to be used as the filename. Maybe something like:\nfrom django.template.defaultfilters import slugify\nclass SomeModel(models.Model):\n... | [
11
] | [] | [] | [
"django",
"field",
"file",
"model",
"python"
] | stackoverflow_0002546575_django_field_file_model_python.txt |
Q:
What is the equivalent for pycassa ColumnFamily.get_range() with Lazyboy?
I think everything is in the question.
I'm looking for the Lazyboy equivalent for Pycassa ColumnFamily.get_range() -- with features like column_start, column_finish et column_count --.
Thanks.
A:
check out this file in lazyboy:
http://gith... | What is the equivalent for pycassa ColumnFamily.get_range() with Lazyboy? | I think everything is in the question.
I'm looking for the Lazyboy equivalent for Pycassa ColumnFamily.get_range() -- with features like column_start, column_finish et column_count --.
Thanks.
| [
"check out this file in lazyboy:\nhttp://github.com/digg/lazyboy/blob/master/lazyboy/iterators.py\nit has a few different range methods. \nE.g., line 121: def key_range(key, start=\"\", finish=\"\", count=100):\nor you could use this when you need to apply slice predicates:\ndef slice_iterator(key, consistency, **p... | [
1
] | [] | [] | [
"cassandra",
"database",
"nosql",
"python"
] | stackoverflow_0002540040_cassandra_database_nosql_python.txt |
Q:
Python: fetching SVG file using urllib is returning binary when I need ASCII
I'm using urllib (in Python) to fetch an SVG file:
import urllib
urllib.urlopen('http://alpha.vectors.cloudmade.com/BC9A493B41014CAABB98F0471D759707/-122.2487,37.87588,-122.265823,37.868054?styleid=1&viewport=400x231').read()
which prod... | Python: fetching SVG file using urllib is returning binary when I need ASCII | I'm using urllib (in Python) to fetch an SVG file:
import urllib
urllib.urlopen('http://alpha.vectors.cloudmade.com/BC9A493B41014CAABB98F0471D759707/-122.2487,37.87588,-122.265823,37.868054?styleid=1&viewport=400x231').read()
which produces output of the sort:
xb6\xf6\x00\xb3\xfb2\xff\xda\xc5\xf2\xc2\x14\xef\xcd\x82\... | [
"It's gzip-compressed (check the Content-Encoding HTTP header). You can use the gzip module to decompress it.\n"
] | [
2
] | [] | [] | [
"ascii",
"binary_data",
"python",
"urllib"
] | stackoverflow_0002547937_ascii_binary_data_python_urllib.txt |
Q:
Problem with building OpenCV for Python 2.6
I've just downloaded OpenCV's trunk and now I'm trying to build it with MinGW. I read the manual and get .dll's compiled, but that's all - "interfaces/python" contains only some .i and .cmake files. How can I really get new python interface? Where I can find new cv.pyd/l... | Problem with building OpenCV for Python 2.6 | I've just downloaded OpenCV's trunk and now I'm trying to build it with MinGW. I read the manual and get .dll's compiled, but that's all - "interfaces/python" contains only some .i and .cmake files. How can I really get new python interface? Where I can find new cv.pyd/libcv.dll.a (because a compiled version from offic... | [
"Since you downloaded the source from trunk, you will also have to build all of OpenCV before you can use it or the Python wrappers. Have you compiled it?\nIf not, check the directions on http://opencv.willowgarage.com/wiki/InstallGuide under the \"Building OpenCV from source using CMake\" heading. There is also a ... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0002546151_opencv_python.txt |
Q:
Why is python decode replacing more than the invalid bytes from an encoded string?
Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like 'PREFIX\xe3\xabSUFFIX'
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragm... | Why is python decode replacing more than the invalid bytes from an encoded string? | Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like 'PREFIX\xe3\xabSUFFIX'
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragment.decode('utf-8', 'strict')
...
UnicodeDecodeError: 'utf8' codec can't decode bytes in... | [
"the 0xE3 byte is one (of the possible) first bytes indicative of a 3-bytes character.\nApparently Python's decode logic takes these three bytes and tries to decode them. They turn out to not match an actual code point (\"character\") and that is why Python produces a UnicodeDecodeError and emits a substitution ch... | [
9,
9,
4,
0
] | [] | [] | [
"python",
"screen_scraping",
"security",
"unicode"
] | stackoverflow_0002547262_python_screen_scraping_security_unicode.txt |
Q:
How to connect to local MQseries queue using Python?
I am new to mqseries and I started with IBM WebSphere MQ curses. There are examples with MQ_APPLE and MQ_ORANGE queue managers. I have no problem with sending messages to local or remote queue with MQ Explorer, but I wanted to send such message from code: Python... | How to connect to local MQseries queue using Python? | I am new to mqseries and I started with IBM WebSphere MQ curses. There are examples with MQ_APPLE and MQ_ORANGE queue managers. I have no problem with sending messages to local or remote queue with MQ Explorer, but I wanted to send such message from code: Python or Java. I tried Python pymqi library with code like this... | [
"Based on the error it appears that you are attempting to connect to a remote queue manager, but you are using the local queue manager bindings method to connect. I say this because the error is stating that the mqi client doesn't know which channel to connect to. Can you please clarify if you are using a local q... | [
3,
2
] | [] | [] | [
"ibm_mq",
"pymqi",
"python"
] | stackoverflow_0002536733_ibm_mq_pymqi_python.txt |
Q:
Design pattern for parsing data that will be grouped to two different ways and flipped
I'm looking for an easily maintainable and extendable design model for a script to parse an excel workbook into two separate workbooks after pulling data from other locations like the command line, and a database. The high level... | Design pattern for parsing data that will be grouped to two different ways and flipped | I'm looking for an easily maintainable and extendable design model for a script to parse an excel workbook into two separate workbooks after pulling data from other locations like the command line, and a database. The high level details are as follows.
I need to parse an excel workbook containing a sheet that lists uni... | [
"Not sure if I can help, but at the least, sympathy for you I do have :-)\nHave you tried using Strategies? If haven't check out the link, there is even a simple Python example. If your types differ only in the way they handle the URLs, you could encapsulate the different logics into strategy subclasses. In the wor... | [
1
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0002548790_design_patterns_oop_python.txt |
Q:
Converting a string into a list in Python
I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python?
1000
2... | Converting a string into a list in Python | I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python?
1000
2000
3000
4000
to
['1000','2000','3000','4000'... | [
"To convert a Python string into a list use the str.split method:\n>>> '1000 2000 3000 4000'.split()\n['1000', '2000', '3000', '4000']\n\nsplit has some options: look them up for advanced uses.\nYou can also read the file into a list with the readlines() method of a file object - it returns a list of lines. For exa... | [
24,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002545397_python.txt |
Q:
How to find the filename of a script being run when it is executed from a symlink on linux
If I have a python script that is executed via a symlink, is there a way that I can find the path to the script rather than the symlink? I've tried using the methods suggested in this question, but they always return the p... | How to find the filename of a script being run when it is executed from a symlink on linux | If I have a python script that is executed via a symlink, is there a way that I can find the path to the script rather than the symlink? I've tried using the methods suggested in this question, but they always return the path to the symlink, not the script.
For example, when this is saved as my "/usr/home/philboltt/s... | [
"You want the os.path.realpath() function.\n",
"os.readlink() will resolve a symlink, and os.path.islink() will tell you if it's a symlink in the first place.\n",
"I believe you will need to check if the file is a symlink, and if so, get where it is linked to. For example...\ntry:\n print os.readlink(__file... | [
8,
3,
0
] | [] | [] | [
"filenames",
"linux",
"python",
"symlink"
] | stackoverflow_0002548936_filenames_linux_python_symlink.txt |
Q:
: in node causing Keyerror in xmlparsing using ElementTree
Hi I'm using ElementTree to parse out an xml feed from Kuler. I'm only beginning in python but am stuck here.
The parsing works fine until I attempt to retrieve any nodes containing ':'
e.g kuler:swatchHexColor
Below is a cut down version of the full feed ... | : in node causing Keyerror in xmlparsing using ElementTree | Hi I'm using ElementTree to parse out an xml feed from Kuler. I'm only beginning in python but am stuck here.
The parsing works fine until I attempt to retrieve any nodes containing ':'
e.g kuler:swatchHexColor
Below is a cut down version of the full feed but same structure:
<rss xmlns:xs="http://www.w3.org/2001/XMLSch... | [
"Based on this article (and comments on this article) I think you have to substitute the namespace name with the actual URI (and remove the colon and put it in {}):\nnamespace = 'http://kuler.adobe.com/kuler/API/rss/'\n\ndef xml():\n kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=... | [
1
] | [] | [] | [
"django",
"elementtree",
"parsing",
"python",
"xml"
] | stackoverflow_0002549211_django_elementtree_parsing_python_xml.txt |
Q:
Exit python program when argument is less than 0
I'd like the program to exit if the input number is less than 0, but sys.exit() isn't doing the trick. This is what I have now:
if len( sys.argv ) > 1:
number = sys.argv[1]
if number <= 0:
print "Invalid number! Must be greater than 0"
sys.exit()
A:
Y... | Exit python program when argument is less than 0 | I'd like the program to exit if the input number is less than 0, but sys.exit() isn't doing the trick. This is what I have now:
if len( sys.argv ) > 1:
number = sys.argv[1]
if number <= 0:
print "Invalid number! Must be greater than 0"
sys.exit()
| [
"Your test is failing because number is a string.\n>>> '-1' <= 0\nFalse\n\nYou need to convert number to an integer:\nnumber = int(sys.argv[1])\n\nNote that in Python 3.0 your code would have given an error, allowing you to find your mistake more easily:\n>>> '-1' <= 0\nTraceback (most recent call last):\n File \"... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0002549300_python.txt |
Q:
working python xml
my question is the following, which is the best way of working XML (kml) with python?, especially script serializable.
thanks for your attention and answers
A:
For Python and XML I routinely use xml.etree (see its documentation). The good thing with xml.etree is that it's included in the Pytho... | working python xml | my question is the following, which is the best way of working XML (kml) with python?, especially script serializable.
thanks for your attention and answers
| [
"For Python and XML I routinely use xml.etree (see its documentation). The good thing with xml.etree is that it's included in the Python standard library. I've heard good things about lxml as well, which exposes an etree compatible api.\n",
"lxml is very fast. With large data its best choice.\nEdit: But \"Note th... | [
4,
3,
1
] | [] | [] | [
"kml",
"python",
"xml",
"xml_serialization"
] | stackoverflow_0002548659_kml_python_xml_xml_serialization.txt |
Q:
What is the difference between AF_INET and PF_INET constants?
Looking at examples about socket programming, we can see that some people use AF_INET while others use PF_INET. In addition, sometimes both of them are used at the same example. The question is: Is there any difference between them? Which one should we ... | What is the difference between AF_INET and PF_INET constants? | Looking at examples about socket programming, we can see that some people use AF_INET while others use PF_INET. In addition, sometimes both of them are used at the same example. The question is: Is there any difference between them? Which one should we use?
If you can answer that, another question would be... Why there... | [
"I think the Wikipedia notes on this sum it up pretty well:\n\nThe original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by ... | [
27
] | [] | [] | [
"c",
"python",
"sockets",
"unix"
] | stackoverflow_0002549461_c_python_sockets_unix.txt |
Q:
Django Timezone Confusion; Postgres and Apache
Setup: Multiple sites on Django on the same set of servers, being served by the same group of Apache processes. Some sites are Eastern TZ; some are Central. Database is PSQL running on a separate server.
When I started, I didn't put much thought into how the various s... | Django Timezone Confusion; Postgres and Apache | Setup: Multiple sites on Django on the same set of servers, being served by the same group of Apache processes. Some sites are Eastern TZ; some are Central. Database is PSQL running on a separate server.
When I started, I didn't put much thought into how the various sites would handle timezones; I guess I saw the TIMEZ... | [
"Here are some details on time zone handling in Django and Postgres, but I strongly recommend dealing exclusively with UTC on the backend and only converting to a local time zone in the frontend when presenting a UTC timestamp to a user. In Python, you can get the current time in UTC via datetime.datetime.utcnow().... | [
2
] | [] | [] | [
"django",
"python",
"timezone"
] | stackoverflow_0002518240_django_python_timezone.txt |
Q:
Is there a Python package similar to Perl's Archive::Extract?
I'm looking for a package that will automatically detect the type of and extract an archive (zip, tar.gz, etc). In Perl, this is easy - in Python, I can't find any simple package/class to do it...
A:
In Python you can use:
zipfile
tarfile - Note: Ta... | Is there a Python package similar to Perl's Archive::Extract? | I'm looking for a package that will automatically detect the type of and extract an archive (zip, tar.gz, etc). In Perl, this is easy - in Python, I can't find any simple package/class to do it...
| [
"In Python you can use:\n\nzipfile\ntarfile - Note: Tarfile can also handle bz2ed and gzipped tar files.\nbz2\ngzip\n\nI'm not aware of any wrapper that can choose the right format automatically. If it exists it doesn't seem to be mentioned in the documentation for any of the above modules.\n",
"Riding off of Mar... | [
1,
1
] | [] | [] | [
"archive",
"extract",
"gzip",
"python",
"zip"
] | stackoverflow_0002549134_archive_extract_gzip_python_zip.txt |
Q:
Django Form for date range
I am trying to come up with a form that lets the user select a date range to generate a web query in Django. I am having errors getting the date to filter with in my view, I am unable to strip the date.
Here is my forms.py:
class ReportFiltersForm(forms.Form):
start_date = forms.Date... | Django Form for date range | I am trying to come up with a form that lets the user select a date range to generate a web query in Django. I am having errors getting the date to filter with in my view, I am unable to strip the date.
Here is my forms.py:
class ReportFiltersForm(forms.Form):
start_date = forms.DateField(input_formats='%Y,%m,%d',w... | [
"There are many mistakes you are making here.\nFirst off, to fix your TypeError, you need to cast your data into int like so:\n...\nsdy = int(request.POST['start_date_year'])\n#Do the same with the other 5 fields\n\nHowever, this is a really bad way of doing things. For one, you will have to put try/except blocks a... | [
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002549655_django_django_forms_python.txt |
Q:
python socket.recv/sendall call blocking
This post is incorrectly tagged 'send' since I cannot create new tags.
I have a very basic question about this simple echo server. Here are some code snippets.
client
while True:
data = raw_input("Enter data: ")
mySock.sendall(data)
echoedData = mySock.recv(1024)
if not... | python socket.recv/sendall call blocking | This post is incorrectly tagged 'send' since I cannot create new tags.
I have a very basic question about this simple echo server. Here are some code snippets.
client
while True:
data = raw_input("Enter data: ")
mySock.sendall(data)
echoedData = mySock.recv(1024)
if not echoedData: break
print echoedData
server
w... | [
"More like, the sendall() call does nothing (since there's no data to send), and thus the recv() call on the client blocks waiting for data, but since nothing was sent to the server, the server never sends any data back since it's also blocked on its initial recv(), and thus both processes are blocked.\n"
] | [
4
] | [] | [] | [
"python",
"recv",
"send",
"sockets"
] | stackoverflow_0002549788_python_recv_send_sockets.txt |
Q:
Using ftplib for multithread uploads
I'm trying to do multithread uploads, but get errors.
I guessed that maybe it's impossible to use multithreads with ftplib?
Here comes my code:
class myThread (threading.Thread):
def __init__(self, threadID, src, counter, image_name):
self.threadID = threadID
... | Using ftplib for multithread uploads | I'm trying to do multithread uploads, but get errors.
I guessed that maybe it's impossible to use multithreads with ftplib?
Here comes my code:
class myThread (threading.Thread):
def __init__(self, threadID, src, counter, image_name):
self.threadID = threadID
self.src = src
self.counter ... | [
"Have you tried to put the connection code inside the thread? \nIn other words, make each thread do their own separate connection with FTP.host() and FTP.login(). The server may not like multiple uploads at the same time on a single connection, because it may be parsing commands one at a time and can't handle a s... | [
5
] | [] | [] | [
"ftplib",
"multithreading",
"python"
] | stackoverflow_0002549829_ftplib_multithreading_python.txt |
Q:
Populate a list from xml using python
I have an xml file in the following format:
<food>
<desert>
cake
<desert>
</food>
<history>
currently in my belly
</history>
I want to create two list, food and text populated with cake and history in string format. Is there an easy way to do it in python?
A:
ElementTree (a... | Populate a list from xml using python | I have an xml file in the following format:
<food>
<desert>
cake
<desert>
</food>
<history>
currently in my belly
</history>
I want to create two list, food and text populated with cake and history in string format. Is there an easy way to do it in python?
| [
"ElementTree (and the faster compatible implementations in cElementTree and lxml) let you very easily extract information from XML -- as long as the XML is correct and your goals are well defined.\nYour example XML has at least two problems (you're opening another dessert tag instead of closing the first one, and y... | [
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002549895_python_xml.txt |
Q:
Converting a Doc object into a string in python
I'm using minidom to parse through an xml document. I took the data with yum tags and stored them in a list and calculated the frequency of the words. However, its not storing or reading them as strings in the list. Is there another way to do it? Right now this is wh... | Converting a Doc object into a string in python | I'm using minidom to parse through an xml document. I took the data with yum tags and stored them in a list and calculated the frequency of the words. However, its not storing or reading them as strings in the list. Is there another way to do it? Right now this is what I have:
yumNodes = [node for node in doc.getElemen... | [
"Not directly related to your question, but as a remark that could improve your code...the pattern\nfreqDict = {}\n...\nif word not in freqDict:\n freqDict[word] = 1\nelse:\n freqDict[word] += 1\n\nis usually replaced with\nimport collections\nfreqDict = collections.defaultdict(int)\n...\nfreqDict[word] += 1\... | [
1,
0
] | [] | [] | [
"minidom",
"python"
] | stackoverflow_0002549789_minidom_python.txt |
Q:
How do I write this query in Django?
Suppose I have a datetime column.
"SELECT * FROM mytable WHERE thetime < INTERVAL 1 HOUR"
How do you write this in Django?
A:
MyModel.objects.extra(where=['thetime < INTERVAL 1 HOUR'])
| How do I write this query in Django? | Suppose I have a datetime column.
"SELECT * FROM mytable WHERE thetime < INTERVAL 1 HOUR"
How do you write this in Django?
| [
"MyModel.objects.extra(where=['thetime < INTERVAL 1 HOUR'])\n\n"
] | [
0
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002550164_database_django_mysql_python.txt |
Q:
How to concat a string in Python
query = "SELECT * FROM mytable WHERE time=%s", (mytime)
Currently, I"m doing this, but I want to split it into 2 strings (so I can do them separately)
cursor.execute("SELECT * FROM mytable WHERE time=%s",(mytime))
Then, I want to add a limit %s to it. How can I do that without me... | How to concat a string in Python | query = "SELECT * FROM mytable WHERE time=%s", (mytime)
Currently, I"m doing this, but I want to split it into 2 strings (so I can do them separately)
cursor.execute("SELECT * FROM mytable WHERE time=%s",(mytime))
Then, I want to add a limit %s to it. How can I do that without messing up the %s in mytime?
Edit: I wan... | [
"Being wary of SQL injection, you can dynamically compose your query as Ignacio suggests.\n>>> qry = 'SELECT t.mycol FROM mytable t WHERE t.mycol = %%s %s' % 'LIMIT %s,%s'\n\nYou ask: \n\nHow can I do that without messing up\n the %s in mytime?\n\nNotice that you escape the first %s with an additional %.\nThat gi... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002549672_python.txt |
Q:
figuring out objects created 30 min ago in django
I have a DateTimeField called created in my model and I would like to get all the objects where created date is 30 min or more. How would query this using MyModel.objects(....) in django?
A:
Maybe something like:
import datetime
created_time = datetime.datetime.n... | figuring out objects created 30 min ago in django | I have a DateTimeField called created in my model and I would like to get all the objects where created date is 30 min or more. How would query this using MyModel.objects(....) in django?
| [
"Maybe something like:\nimport datetime\ncreated_time = datetime.datetime.now() - datetime.timedelta(minutes=30)\nold_objects = MyModel.objects.filter(created__lte=created_time)\n\nSee http://docs.djangoproject.com/en/dev/topics/db/queries/ for more information on creating queries, filtering, etc.\n",
"Use this f... | [
9,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002550238_django_django_models_python.txt |
Q:
Django pagination | get current index of paginated item in page index, (not the page index range itself)
I am trying to build a photo gallery with Django.
It is set up by category.
I have paginated the results of a category by n amount of images per page. I want to also use the paginator on the page that shows ju... | Django pagination | get current index of paginated item in page index, (not the page index range itself) | I am trying to build a photo gallery with Django.
It is set up by category.
I have paginated the results of a category by n amount of images per page. I want to also use the paginator on the page that shows just the single image and have a prev/next button for the prev/next image in that category.
My thought was to g... | [
"I think the way you're describing it would work ok because behind the scenes I believe what Django is doing is using an SQL LIMIT to simply let the database do the heavy lifting of sorting out what and how much data to return. Because the database is optimized for doing this type of thing it's probably a reasonab... | [
1
] | [] | [] | [
"django",
"django_pagination",
"pagination",
"python"
] | stackoverflow_0002549549_django_django_pagination_pagination_python.txt |
Q:
Are there any libraries to allow Python or Ruby to get info from SVN?
I'm looking for plugins that will allow my codebase to interact with, browse, and poll an SVN server for information about a repository.
Trac can do this, but I was hoping there was an easy-to-use library available to accomplish the task, rather... | Are there any libraries to allow Python or Ruby to get info from SVN? | I'm looking for plugins that will allow my codebase to interact with, browse, and poll an SVN server for information about a repository.
Trac can do this, but I was hoping there was an easy-to-use library available to accomplish the task, rather than trolling through the Trac codebase. Googling for this returns mostly... | [
"pysvn\n",
"Apparently Subversion ships with Ruby bindings. There is some information on Ruby SVN bindings here and here.\n"
] | [
3,
2
] | [] | [] | [
"python",
"ruby",
"ruby_on_rails",
"svn"
] | stackoverflow_0002550198_python_ruby_ruby_on_rails_svn.txt |
Q:
Python unicode issues (2.6)
I'm currently working on a irc bot for a multi-lingual channel, and I'm encountering some issues with unicode which are proving nearly impossible to solve.
No matter what configuration of unicode encoding I seem to try, the list function which the below code sits within just flat out d... | Python unicode issues (2.6) | I'm currently working on a irc bot for a multi-lingual channel, and I'm encountering some issues with unicode which are proving nearly impossible to solve.
No matter what configuration of unicode encoding I seem to try, the list function which the below code sits within just flat out does nothing (c.notice is a class ... | [
"A few points:\n\nThe bytes \"天å\" are the UTF-8 encoding of \"天子\", so are you sure it's wrong that this is sent? Does the program/... that should process the data use UTF-8, or does it just interpret the input as a different encoding like Latin-1?\nunicode(uk,\"utf-8\").encode(\"utf-8\"): Decoding UTF-8 and th... | [
1,
1,
0
] | [] | [] | [
"encoding",
"irc",
"python",
"unicode",
"utf_8"
] | stackoverflow_0002547517_encoding_irc_python_unicode_utf_8.txt |
Q:
how to write re-usable views in django?
These are the techniques that I use regularly to make my views reusable:
take the template_name as an argument with a default
take an optional extra_context which defaults to empty {}
right before the template is rendered the context is updated with the extra_context
for f... | how to write re-usable views in django? | These are the techniques that I use regularly to make my views reusable:
take the template_name as an argument with a default
take an optional extra_context which defaults to empty {}
right before the template is rendered the context is updated with the extra_context
for further re-usability, call any callable in ex... | [
"I would think that doing all of those puts a large burden on your urlconf to get everything right. Perhaps making a function that takes all that and hardcoding your views to be a glorified wrapper around said function would be better.\n",
"\nwhenever the view needs a particular object from the ORM, it attempts t... | [
0,
0
] | [] | [] | [
"django",
"python",
"views"
] | stackoverflow_0002550308_django_python_views.txt |
Q:
Correct way to put long function calls on multiple lines
I have a long function, as seen below:
hash_correct = hashlib.md5(salt + password)).digest().encode("base64")
I'd like to split it up into two lines but am not sure of the correct way to do this in Python?
Thanks.
A:
The coding guidelines limiting length ... | Correct way to put long function calls on multiple lines | I have a long function, as seen below:
hash_correct = hashlib.md5(salt + password)).digest().encode("base64")
I'd like to split it up into two lines but am not sure of the correct way to do this in Python?
Thanks.
| [
"The coding guidelines limiting length of lines is there, in part, to make the code more readable. In your case of chained method calls, the meaning is not clear. You should pick some temporary variable names for the intermediate values so that a reader of the code can understand the chain easily.\nOne example m... | [
21,
3
] | [] | [] | [
"multiline",
"python"
] | stackoverflow_0002550439_multiline_python.txt |
Q:
Purpose of SQLAlchemy over MySQLdb
Why do people use SQLAlchemy instead of MySQLdb? What advantages does it offer?
A:
You don't use SQLAlchemy instead of MySQLdb—you use SQLAlchemy to access something like MySQLdb, oursql (another MySQL driver that I hear is nicer and has better performance), the sqlite3 module,... | Purpose of SQLAlchemy over MySQLdb | Why do people use SQLAlchemy instead of MySQLdb? What advantages does it offer?
| [
"You don't use SQLAlchemy instead of MySQLdb—you use SQLAlchemy to access something like MySQLdb, oursql (another MySQL driver that I hear is nicer and has better performance), the sqlite3 module, psycopg2, or whatever other database driver you are using. \nAn ORM (like SQLAlchemy) helps abstract away the details o... | [
34,
13,
5
] | [] | [] | [
"mysql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002550292_mysql_python_sql_sqlalchemy.txt |
Q:
Python - List and Loop in one def
I'm trying to get the def wfsc_pod1 and wfsc_ip into the same def. I'm not quite sure how to approach the problem. I want wfsc_pod1 to display all the information for name, subnet and gateway. Then wfsc_ip shows the ip addresses below it. I also get a None value when I run it as i... | Python - List and Loop in one def | I'm trying to get the def wfsc_pod1 and wfsc_ip into the same def. I'm not quite sure how to approach the problem. I want wfsc_pod1 to display all the information for name, subnet and gateway. Then wfsc_ip shows the ip addresses below it. I also get a None value when I run it as it. Not sure why. Anything more pythonic... | [
"First of all, you probably meant to write wfsc_pod1 like this:\ndef wfsc_pod1(self):\n return \"%s\\t%s\\t%s\" % (self.name[0], self.subnet[0], self.gateway[0])\n\nand call wfsc_ip like this:\nnetwork.wfsc_ip() # no print\n\nIf you want to combine wfsc_pod1 and wfsc_ip, you can do this:\ndef wfsc_combined(self)... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002550642_python.txt |
Q:
How do I use Django to insert a Geometry Field into the database?
class LocationLog(models.Model):
user = models.ForeignKey(User)
utm = models.GeometryField(spatial_index=True)
This is my database model. I would like to insert a row.
I want to insert a circle at point -55, 333. With a radius of 10. How ca... | How do I use Django to insert a Geometry Field into the database? | class LocationLog(models.Model):
user = models.ForeignKey(User)
utm = models.GeometryField(spatial_index=True)
This is my database model. I would like to insert a row.
I want to insert a circle at point -55, 333. With a radius of 10. How can I put this circle into the geometry field?
Of course, then I would wa... | [
"Solved.\nI created a square.\nfrom django.contrib.gis.geos import Polygon\n\ns = Polygon(( (x-rad,y+rad)\n ,(x+rad,y+rad)\n ,(x+rad,y-rad)\n ,(x-rad,y-rad)\n ,(x-rad,y+rad) )\n )\n\nThen you insert s into the database as a GeometryField.\n"
] | [
1
] | [] | [] | [
"database",
"django",
"geometry",
"mysql",
"python"
] | stackoverflow_0002550506_database_django_geometry_mysql_python.txt |
Q:
Disable Plone Archetypes index/convert doc/pdf files
If I rebuild my catalog in plone I get many of these infos:
2010-02-18T11:26:09 INFO Archetypes Error while trying to convert file contents to 'text/plain' in <Field file(file:rw)>.getIndexable() of <ATFile at /site/test1/test.doc>: Unable to find binary "wvHtml... | Disable Plone Archetypes index/convert doc/pdf files | If I rebuild my catalog in plone I get many of these infos:
2010-02-18T11:26:09 INFO Archetypes Error while trying to convert file contents to 'text/plain' in <Field file(file:rw)>.getIndexable() of <ATFile at /site/test1/test.doc>: Unable to find binary "wvHtml" in /sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/b... | [
"You can disable (remove) transforms in ZMI/portal_transforms tool. If Plone does not find transform from Word to plain text or PDF to plain text, it won't try to index the file contents.\nGo to ZMI/portal_transforms and remove word_to_html item.\n",
"It is trying to index your doc/pdf files by converting them to... | [
4,
2,
1
] | [] | [] | [
"archetypes",
"plone",
"plone_3.x",
"python",
"zope"
] | stackoverflow_0002288470_archetypes_plone_plone_3.x_python_zope.txt |
Q:
In Python, how would I do this Datetime?
right_now = datetime.datetime.now()
one_hour_before = ?????
How can I use right_now to get one_hour_before?
A:
right_now = datetime.datetime.now()
one_hour_before = right_now - datetime.timedelta(hours=1)
A:
You need to use datetime.timedelta like so:
right_now = datet... | In Python, how would I do this Datetime? | right_now = datetime.datetime.now()
one_hour_before = ?????
How can I use right_now to get one_hour_before?
| [
"right_now = datetime.datetime.now()\none_hour_before = right_now - datetime.timedelta(hours=1)\n\n",
"You need to use datetime.timedelta like so:\nright_now = datetime.datetime.now()\none_hour_before = right_now - datetime.timedelta(hours = 1)\n\n"
] | [
7,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002550812_datetime_python.txt |
Q:
How do I write this insert statement in Django?
newthing = Link(user=request.user,last_updated=datetime.datetime.now())
However, this uses datetime , not the MYSQL "now()".
How can I use mysql's now()?
A:
I'm not sure if this uses the MySQL now() call, but the right way to do this in Django is to use the auto_n... | How do I write this insert statement in Django? | newthing = Link(user=request.user,last_updated=datetime.datetime.now())
However, this uses datetime , not the MYSQL "now()".
How can I use mysql's now()?
| [
"I'm not sure if this uses the MySQL now() call, but the right way to do this in Django is to use the auto_now_add or auto_add options on a DateField/DateTimeField:\nclass Link(models.Model):\n ...\n last_updated = models.DateTimeField(auto_now_add = True)\n ...\n\nNote: I am assuming here that Link is a M... | [
2
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002550806_database_django_mysql_python.txt |
Q:
exe created by py2exe give error
i have created an exe from py2exe. After successfully creating the exe, i got the following error when i run main.exe.
File "_mssql.pyc", line 12, in <module>
File "_mssql.pyc", line 10, in __load
ImportError: DLL load failed: The specified module could not be found.
I am usin... | exe created by py2exe give error | i have created an exe from py2exe. After successfully creating the exe, i got the following error when i run main.exe.
File "_mssql.pyc", line 12, in <module>
File "_mssql.pyc", line 10, in __load
ImportError: DLL load failed: The specified module could not be found.
I am using pymssql module for sql server.
| [
"make sure you include the module under the options dictionary. I think it also needs a dll file called ntwdblib.dll. you can find that file and include it into your setup.py.\nimport os, pymssql\nfrom distutils.core import setup\nimport py2exe\ndll = []\ndll.append(os.path.join(os.path.split(pymssql.__file__)[0], ... | [
5
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0002551003_py2exe_python.txt |
Q:
Why does a JRuby application on App Engine take so long to start (versus a Python app)?
I'm considering using JRuby on App Engine but have heard that Juby app on App Engine have a long startup lag versus a Python app. Why is this?
Is it because the JRuby jar files are so large that a cold startup requires them to... | Why does a JRuby application on App Engine take so long to start (versus a Python app)? | I'm considering using JRuby on App Engine but have heard that Juby app on App Engine have a long startup lag versus a Python app. Why is this?
Is it because the JRuby jar files are so large that a cold startup requires them to be loaded into memory before the app can start serving? That would be my guess but I'm not ... | [
"That's basically it. When your app hasn't been used in a while, App Engine swaps it out until another request comes in.\nWhen that happens, it loads all the JARs your app requires, which may take a very long time, upwards of 10-15+ seconds in some cases.\nI don't have any experience with JRuby in particular, but t... | [
10,
0
] | [] | [] | [
"google_app_engine",
"java",
"jruby",
"python",
"ruby"
] | stackoverflow_0002547498_google_app_engine_java_jruby_python_ruby.txt |
Q:
String formatting: string specifier in a string constant
Is there a way to insert a string in a string constant/variable that contains a string specifier?
Example:
temp_body = 'Hello %s, please visit %s to confirm your registration.'
body = temp_body % (name, url)
But this raises a TypeError.
A:
Works on my ma... | String formatting: string specifier in a string constant | Is there a way to insert a string in a string constant/variable that contains a string specifier?
Example:
temp_body = 'Hello %s, please visit %s to confirm your registration.'
body = temp_body % (name, url)
But this raises a TypeError.
| [
"Works on my machine(TM).\nAre you sure that name and url really are strings? What do you get when you do\n>>> type(name), type(url)\n\n",
"Usually it is the way strings are generated e.g. msg template will be loaded from db or some file and things inserted in between, what is url and name in your case?\nThis wor... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002551236_python.txt |
Q:
django send_mail from queryset
I am trying to use the django send_mail method. I am running into 2 issues, notably converting mail addresses from a list into a csv to be used in the recipients. The second issue is getting the list of user emails from the notifications model.
my models
class notifications(models.Mo... | django send_mail from queryset | I am trying to use the django send_mail method. I am running into 2 issues, notably converting mail addresses from a list into a csv to be used in the recipients. The second issue is getting the list of user emails from the notifications model.
my models
class notifications(models.Model):
notID = models.AutoField(p... | [
"UserProfile.objects.filter(mailCom='1').values_list('email', flat=True)\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002551353_django_python.txt |
Q:
How can I write this query in Django? (datetime)
| time_before | datetime | YES | MUL | NULL | |
| time_after | datetime | YES | MUL | NULL | |
the_tag = Tag.objects.get(id=tag_id)
Log.objects.filter(blah).extra(where=['last_updated >'+the_tag.time_before, 'last_up... | How can I write this query in Django? (datetime) | | time_before | datetime | YES | MUL | NULL | |
| time_after | datetime | YES | MUL | NULL | |
the_tag = Tag.objects.get(id=tag_id)
Log.objects.filter(blah).extra(where=['last_updated >'+the_tag.time_before, 'last_updated' < the_tag.time_after])
Ok. Basically, I have a... | [
"To get the exact behaviour of your example:\nLog.objects.filter(last_updated__gt=the_tag.time_before, last_updated__lt=the_tag.time_after)\n\nFor an inclusive range (equivalent to __gte, __lte) the query is a bit simpler:\nLog.objects.filter(last_updated__range=(the_tag.time_before, the_tag.time_after))\n\n"
] | [
6
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002551475_database_django_mysql_python.txt |
Q:
Processing RSS/RDF via xml.dom.minidom
I'm trying to process a delicious rss feed via python. Here's a sample:
...
<item rdf:about="http://weblist.me/">
<title>WebList - The Place To Find The Best List On The Web</title>
<dc:date>2009-12-24T17:46:14Z</dc:date>
<link>http://weblist.me/</link>
...... | Processing RSS/RDF via xml.dom.minidom | I'm trying to process a delicious rss feed via python. Here's a sample:
...
<item rdf:about="http://weblist.me/">
<title>WebList - The Place To Find The Best List On The Web</title>
<dc:date>2009-12-24T17:46:14Z</dc:date>
<link>http://weblist.me/</link>
...
</item>
<item rdf:about="http://thumboo... | [
"You are passing the title nodes to getText, whose nodeTypes are not node.TEXT_NODE. You have to loop over all the children of the node instead in your getText method:\ndef getTextSingle(node):\n parts = [child.data for child in node.childNodes if child.nodeType == node.TEXT_NODE]\n return u\"\".join(parts)\n... | [
4
] | [] | [] | [
"python",
"rss"
] | stackoverflow_0002551214_python_rss.txt |
Q:
Python - CSV: Large file with rows of different lengths
In short, I have a 20,000,000 line csv file that has different row lengths. This is due to archaic data loggers and proprietary formats. We get the end result as a csv file in the following format. MY goal is to insert this file into a postgres database. How ... | Python - CSV: Large file with rows of different lengths | In short, I have a 20,000,000 line csv file that has different row lengths. This is due to archaic data loggers and proprietary formats. We get the end result as a csv file in the following format. MY goal is to insert this file into a postgres database. How Can I do the following:
Keep the first 8 columns and my last... | [
"Read a row with csv, then:\nnewrow = row[:8] + row[-2:]\n\nthen add your new field and write it out (also with csv).\n",
"You can open the file as a textfile and read the lines one at a time. Are there quoted or escaped commas that don't \"split fields\"? If not, you can do\nwith open('thebigfile.csv', 'r') as... | [
8,
2,
1,
1
] | [] | [] | [
"csv",
"etl",
"parsing",
"python"
] | stackoverflow_0002549746_csv_etl_parsing_python.txt |
Q:
How to list directory hierarchy in GtkTreeView widget?
I am trying to generate a hierarchical directory listing in pyGTK.
Currently, I have this following directory tree:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
I have written a function that -almost- s... | How to list directory hierarchy in GtkTreeView widget? | I am trying to generate a hierarchical directory listing in pyGTK.
Currently, I have this following directory tree:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
I have written a function that -almost- seem to work:
def go(root, piter=None):
for filename in ... | [
"About the performance, this is a FAQ.\nAbout your algorithm: when you reach subdirA piter points to subdirA, at the next iteration when you reach a.py piter still points to subdirA.\nAs you said, use os.walk.\n"
] | [
1
] | [] | [] | [
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0002551147_gtktreeview_pygtk_python.txt |
Q:
How to extend/patch an existing module or package?
I want to extend some locale-specific features of a python application named OpenERP. All I need is implementing a third party module.function that would be called every time OpenERP calls locale.setlocale() function without changing neither OpenERP nor locale mod... | How to extend/patch an existing module or package? | I want to extend some locale-specific features of a python application named OpenERP. All I need is implementing a third party module.function that would be called every time OpenERP calls locale.setlocale() function without changing neither OpenERP nor locale module source code.
The only way I can imagine is provide a... | [
"Look up Monkey Patching. It's not most elegant technique, but sometimes it's the only option.\nIn your case you can substitute your own function for locale.setlocale() which will do whatever you want. It would look something like that:\nimport locale\n\noriginal_setlocale = locale.setlocale\n\ndef my_setlocale(cat... | [
2
] | [] | [] | [
"extend",
"locale",
"python"
] | stackoverflow_0002551972_extend_locale_python.txt |
Q:
Hyphenate a random string to an exact format
I am creating a random ID using the below code:
from random import *
import string
# The characters to make up the random password
chars = string.ascii_letters + string.digits
def random_password():
return "".join(choice(chars) for x in range(32))
This will outp... | Hyphenate a random string to an exact format | I am creating a random ID using the below code:
from random import *
import string
# The characters to make up the random password
chars = string.ascii_letters + string.digits
def random_password():
return "".join(choice(chars) for x in range(32))
This will output something like:
60ff612332b741508bc4432e34ec1d3... | [
"The uuid module can be used for generating UUIDs.\n",
"What's wrong with generating every part separately? Like that:\ndef random_password():\n return \"-\".join([\"\".join(choice(chars) for x in range(n)) \n for n in (8, 4, 4, 4, 8)])\n\n",
"how about simple concat?\n>>> s=\"60ff612332b... | [
4,
3,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002552027_python_string.txt |
Q:
How do I do this Database Model in Django?
Django currently does not support the "Point" datatype in MySQL. That's why I created my own.
class PointField(models.Field):
def db_type(self):
return 'Point'
class Tag(models.Model):
user = models.ForeignKey(User)
utm = PointField()
As you can see,... | How do I do this Database Model in Django? | Django currently does not support the "Point" datatype in MySQL. That's why I created my own.
class PointField(models.Field):
def db_type(self):
return 'Point'
class Tag(models.Model):
user = models.ForeignKey(User)
utm = PointField()
As you can see, this works, and syncdb creates the model fine.
... | [
"Your question is a bit unclear - are you just asking how to calculate the distance between 2 points? Or are you hoping the ORM will give you some functionality to do it?\nIf the latter, then that's not going to happen without some external assistance; geometry and geography are beyond the remit of most typical dat... | [
0
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002549616_database_django_mysql_python.txt |
Q:
How do you invoke a python script inside a jar file using python?
I'm working on an application that intersperses a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really restricted to Python 2.1
We currently have a jar containing both java source and .py modules. The code ... | How do you invoke a python script inside a jar file using python? | I'm working on an application that intersperses a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really restricted to Python 2.1
We currently have a jar containing both java source and .py modules. The code is currently invoked using java, but I'd like to remove this in favor o... | [
"the following works for me :\nimport sys\nimport os\n\nimport java.lang.ClassLoader \nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\nloader = java.lang.ClassLoader.getSystemClassLoader()\nstream = loader.getResourceAsStream(\"com/example/action/myAction.py\")\nreader = java.io.BufferedReader(ja... | [
5
] | [] | [] | [
"import",
"jar",
"java",
"jython",
"python"
] | stackoverflow_0002551269_import_jar_java_jython_python.txt |
Q:
Losing 'post' requests sent to Pylons paster server
I'm sending post requests to a Pylons server (served by paster serve), and if I send them with any frequency many don't arrive at the server. One at a time is ok, but if I fire off a few (or more) within seconds, only a small number get dealt with. If I send with... | Losing 'post' requests sent to Pylons paster server | I'm sending post requests to a Pylons server (served by paster serve), and if I send them with any frequency many don't arrive at the server. One at a time is ok, but if I fire off a few (or more) within seconds, only a small number get dealt with. If I send with no post data, or with get, it works fine, but putting ju... | [
"Thanks for you reply.\nTracked it doen to the fact that paster serve only supports HTTP 1.0, and so wasn't responding to initial requests with a 100 code.\nSwitched to Apache, all working now!\n",
"Could you add logging on paster/pylons side to find where exactly these requests get lost? Are you sure that QT app... | [
1,
0
] | [] | [] | [
"http",
"paster",
"pylons",
"python",
"qt"
] | stackoverflow_0002545643_http_paster_pylons_python_qt.txt |
Q:
Google Apps shared contacts API get a contact for python
I'm having some issues trying to pull a shared contact using the gdata api for python that Google provides. Here is what I have to get the contacts.. but they are not all listed there
feed = gd_client.GetContactsFeed()
for i, entry in enumerate(feed.entry):
... | Google Apps shared contacts API get a contact for python | I'm having some issues trying to pull a shared contact using the gdata api for python that Google provides. Here is what I have to get the contacts.. but they are not all listed there
feed = gd_client.GetContactsFeed()
for i, entry in enumerate(feed.entry):
print entry.title
I can't figure out how to pull out a si... | [
"Google API lacks of features here.\nYou need to query all your contacts and then iter on them like this:\nfeedquery = gdata.contacts.service.ContactsQuery()\nfeedquery.query.max_results = 1000\ngmlf = gd_client.GetContactsFeed(feedquery.ToUri())\nfor index,gmc in enumerate(gmlf.entry):\n print str(index) +\... | [
4
] | [] | [] | [
"google_api",
"python"
] | stackoverflow_0002545711_google_api_python.txt |
Q:
How do I resolve this curl-related error?
please tell me the solution
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 6, in __bootstrap__
ImportError: libcurl.so.4: ca... | How do I resolve this curl-related error? | please tell me the solution
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 6, in __bootstrap__
ImportError: libcurl.so.4: cannot open shared object file: No such file or d... | [
"You're trying to invoke the cURL library, but you don't have curl installed (or it's not installed properly). It looks like you're running Linux, so simply install the appropriate package (for instance, sudo apt-get install curl if you're on Ubuntu).\n"
] | [
3
] | [] | [] | [
"pycurl",
"python"
] | stackoverflow_0002552865_pycurl_python.txt |
Q:
Missing multiprocessing module when freezing Python code
I'm using cx_Freeze to freeze my Python code so I can distribute it as executable on Windows systems. It works fine but it's missing a few modules. I use some open-source libraries in my project e.g. BeautifulSoup and Periscope. They use some libraries for b... | Missing multiprocessing module when freezing Python code | I'm using cx_Freeze to freeze my Python code so I can distribute it as executable on Windows systems. It works fine but it's missing a few modules. I use some open-source libraries in my project e.g. BeautifulSoup and Periscope. They use some libraries for backward compatibility which i don't need to include as Python ... | [
"There was a similar issue on Google App Engine. See this\nI fixed this my putting a _multiprocessing.py file into the multiprocessing module's folder. This file contained the code:\n\nimport multiprocessing\n\nThis works but it isn't a robust answer.\n"
] | [
1
] | [] | [] | [
"cx_freeze",
"distutils",
"python"
] | stackoverflow_0002552682_cx_freeze_distutils_python.txt |
Q:
Django JSON serializable error
With the following code below, There is an error saying
File "/home/user/web_pro/info/views.py", line 184, in headerview,
raise TypeError("%r is not JSON serializable" % (o,))
TypeError: <lastname: jerry> is not JSON serializable
In the models code
header(models... | Django JSON serializable error | With the following code below, There is an error saying
File "/home/user/web_pro/info/views.py", line 184, in headerview,
raise TypeError("%r is not JSON serializable" % (o,))
TypeError: <lastname: jerry> is not JSON serializable
In the models code
header(models.Model):
firstname = models.Forei... | [
"The quick read is that obj.lastname is a Lastname model not a String. You probably need to say something like:\nl_array_obj = [..., obj.lastname.value, .... ]\n\nto get the string value, rather than the Model object.\n",
"Have you considered using Django's own serialization functionality?\n"
] | [
2,
1
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0002552719_django_django_models_django_views_python.txt |
Q:
Which files to distribute using cx_Freeze?
I'm using cx_freeze to freeze a Python script for distribution to other windows systems. I did everything as instructed and cx_freeze generated a build\exe.win32-2.6 folder in the folder containing my sources. This directory now contains a a bunch of PYD files, a library... | Which files to distribute using cx_Freeze? | I'm using cx_freeze to freeze a Python script for distribution to other windows systems. I did everything as instructed and cx_freeze generated a build\exe.win32-2.6 folder in the folder containing my sources. This directory now contains a a bunch of PYD files, a library.zip file, the python DLL file and the main exec... | [
"You need all of them.\n"
] | [
10
] | [] | [] | [
"cx_freeze",
"distutils",
"python"
] | stackoverflow_0002553110_cx_freeze_distutils_python.txt |
Q:
Get a specific string from a service list using WSDiscovery
I am using the WSDiscovery module for python. I have been able to search for services on my network. I am trying to discover a client and get the XAddress from this. The WSDiscovery module has very little documentation, actually so little the only piece i... | Get a specific string from a service list using WSDiscovery | I am using the WSDiscovery module for python. I have been able to search for services on my network. I am trying to discover a client and get the XAddress from this. The WSDiscovery module has very little documentation, actually so little the only piece is in the readme file of the module which is a few lines long. I h... | [
"Looking at sources you could see that \n1.\nsearchServices signature has few parameters:\ndef searchServices(self, types=None, scopes=None, timeout=3)\n\nand i don't think filtering by types\\scopes can be useful, isn't it?\n2.\nservice CLASS has those parameters:\nclass Service:\n\ndef __init__(self, types, scope... | [
1
] | [] | [] | [
"list",
"python",
"search",
"string",
"ws_discovery"
] | stackoverflow_0002553582_list_python_search_string_ws_discovery.txt |
Q:
Unexplained file not found for an existing file
Following is the error that occurs in this part of the code. Although the path is valid, a RuntimeError occurs—strange. What is happening, and how can I get this to work?
for root,dirs,files in os.walk(self.path):
for f in files :
... | Unexplained file not found for an existing file | Following is the error that occurs in this part of the code. Although the path is valid, a RuntimeError occurs—strange. What is happening, and how can I get this to work?
for root,dirs,files in os.walk(self.path):
for f in files :
if (f.split('.')[1] == "mb"):
z = ut... | [
"Do you have write permission to all the files in the folder?\n"
] | [
0
] | [] | [] | [
"maya",
"python"
] | stackoverflow_0002553341_maya_python.txt |
Q:
How Do I code this in python with simplejson
how do i code a python program that return a json element that look like this
{1:{'name':foo,'age':xl}
2:{'name':vee,'age':xx}
....
}
What i meant is that i want return nested dictionaries
What i hoped to accomplish is something like this
var foo = 1.name # to... | How Do I code this in python with simplejson | how do i code a python program that return a json element that look like this
{1:{'name':foo,'age':xl}
2:{'name':vee,'age':xx}
....
}
What i meant is that i want return nested dictionaries
What i hoped to accomplish is something like this
var foo = 1.name # to the the value of name in the clientside
I hope a... | [
">>> import simplejson as json \n # \"simplejson\" works exactly the same as with \"json\"\n>>> json.dumps({})\n'{}'\n>>> json.dumps({'asdf':1,'poi':[2,3,4,{'qwer':5}]})\n'{\"asdf\": 1, \"poi\": [2, 3, 4, {\"qwer\": 5}]}'\n>>> \n\n"
] | [
3
] | [] | [] | [
"json",
"python"
] | stackoverflow_0002553954_json_python.txt |
Q:
Copy whole SQL Server database into JSON from Python
I facing an atypical conversion problem. About a decade ago I coded up a large site in ASP. Over the years this turned into ASP.NET but kept the same database.
I've just re-done the site in Django and I've copied all the core data but before I cancel my account ... | Copy whole SQL Server database into JSON from Python | I facing an atypical conversion problem. About a decade ago I coded up a large site in ASP. Over the years this turned into ASP.NET but kept the same database.
I've just re-done the site in Django and I've copied all the core data but before I cancel my account with the host, I need to make sure I've got a long-term ba... | [
"Have a look at the sysobjects and syscolumns tables. Also try:\nSELECT * FROM sysobjects WHERE name LIKE 'sys%'\n\nto find any other metatables of interest. See here for more info on these tables and the newer SQL2005 counterparts.\n",
"I've liked the ADOdb python module when I've needed to connect to sql server... | [
1,
1,
1,
0
] | [] | [] | [
"pymssql",
"python",
"sql_server"
] | stackoverflow_0002552629_pymssql_python_sql_server.txt |
Q:
Exponential distribution in Python
What's the easiest way to draw a random number from an exponential distribution in Python?
A:
random.expovariate of course.
A:
You can use the random module. For more information, consult its documentation.
| Exponential distribution in Python | What's the easiest way to draw a random number from an exponential distribution in Python?
| [
"random.expovariate of course.\n",
"You can use the random module. For more information, consult its documentation.\n"
] | [
18,
0
] | [] | [] | [
"exponential_distribution",
"python"
] | stackoverflow_0002553994_exponential_distribution_python.txt |
Q:
Django: Getting a Python encoding error when handling HTTP response in Latin1?
I'm working in Django, and using urllib2 and simplejson to parse some information from an API.
The problem is that the API returns information in the Latin-1 encoding, and just once in a while there's a character in there that causes Dj... | Django: Getting a Python encoding error when handling HTTP response in Latin1? | I'm working in Django, and using urllib2 and simplejson to parse some information from an API.
The problem is that the API returns information in the Latin-1 encoding, and just once in a while there's a character in there that causes Django to crash horribly with an encoding error. This is my code:
get_person_id_url = ... | [
"Call response.read() to get the data of the response. Then in a try/except do your latin1 decoding and json loading. In general, Django should never crash if you wrap potentially error-causing operations in exception handlers and take care of them appropriately (at least log them somewhere so you can deal with the... | [
0
] | [] | [] | [
"character_encoding",
"django",
"encoding",
"python"
] | stackoverflow_0002553748_character_encoding_django_encoding_python.txt |
Q:
how to ask user input a string with a timeout embeded in python on windows machine?
want to ask user to input something but not want to wait forever. There is a solution for Linux, Keyboard input with timeout in Python, but I am in windows environment. anybody can help me?
A:
Credit to Alex Martelli
Unfortunate... | how to ask user input a string with a timeout embeded in python on windows machine? | want to ask user to input something but not want to wait forever. There is a solution for Linux, Keyboard input with timeout in Python, but I am in windows environment. anybody can help me?
| [
"Credit to Alex Martelli\n\nUnfortunately, on Windows,\n select.select works only on sockets,\n not ordinary files nor the console.\n So, if you want to run on Windows, you\n need a different approach. On Windows\n only, the Python standard library has\n a small module named msvcrt, including\n functions suc... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002554187_python.txt |
Q:
How do I access session data in Jinja2 templates (Bottle framework on app engine)?
I'm running the micro framework Bottle on Google App Engine. I'm using Jinja2 for my templates. And I'm using Beaker to handle the sessions. I'm still a pretty big Python newbie and am pretty stoked I got this far :) My question... | How do I access session data in Jinja2 templates (Bottle framework on app engine)? | I'm running the micro framework Bottle on Google App Engine. I'm using Jinja2 for my templates. And I'm using Beaker to handle the sessions. I'm still a pretty big Python newbie and am pretty stoked I got this far :) My question is how do I access the session data within the templates? I can get the session data n... | [
"You can add things to the Jinja2 environment globals if you want them to be accessible to all templates. See this page for additional information.\nUpdate:\nA simple example is, for your setup code:\nfrom jinja2 import Environment, PackageLoader\nenv = Environment(loader=PackageLoader('yourapplication', 'templates... | [
11
] | [] | [] | [
"beaker",
"google_app_engine",
"jinja2",
"python",
"session"
] | stackoverflow_0002554174_beaker_google_app_engine_jinja2_python_session.txt |
Q:
GAE HTTP method support
I get an "unrecognized HTTP method" when trying to do a REPORT request using httplib and gae. Is there a workaround available? An httplib patch for gae? Do you I have to find another host in order to do this natively?
According to the docs, only certain fetch actions are valid: GET, POST, H... | GAE HTTP method support | I get an "unrecognized HTTP method" when trying to do a REPORT request using httplib and gae. Is there a workaround available? An httplib patch for gae? Do you I have to find another host in order to do this natively?
According to the docs, only certain fetch actions are valid: GET, POST, HEAD,
PUT, and DELETE: http:/... | [
"httplib on App Engine is a wrapper around the urlfetch API, which only supports the GET, POST, PUT, HEAD and DELETE methods. I'm afraid you're out of luck unless the API you're accessing supports some sort of X-HTTP-Method-Override functionality.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"httpwebrequest",
"python"
] | stackoverflow_0002553672_google_app_engine_httpwebrequest_python.txt |
Q:
Python: why does str() on some text from a UTF-8 file give a UnicodeDecodeError?
I'm processing a UTF-8 file in Python, and have used simplejson to load it into a dictionary. However, I'm getting a UnicodeDecodeError when I try to turn one of the dictionary values into a string:
f = open('my_json.json', 'r')
maste... | Python: why does str() on some text from a UTF-8 file give a UnicodeDecodeError? | I'm processing a UTF-8 file in Python, and have used simplejson to load it into a dictionary. However, I'm getting a UnicodeDecodeError when I try to turn one of the dictionary values into a string:
f = open('my_json.json', 'r')
master_dictionary = json.load(f)
#some json wrangling, then it fails on this line...
mysql_... | [
"Python 2.x uses ASCII by default. Use unicode.encode() if you want to turn a unicode into a str:\nv_dict['code'].encode('utf-8')\n\n",
"One way to make this work would be to set the default encoding to UTF-8 explicitly, like:\nimport sys\nsys.setdefaultencoding(\"utf-8\")\n\nThis could lead to unintended consequ... | [
6,
2
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0002554545_character_encoding_python.txt |
Q:
Parsing a file with hierarchical structure in Python
I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:
Fruits
Apple
Auxiliary
Core
Extras
Banana
Something
Coconut
Vegetables
Eggplant
R... | Parsing a file with hierarchical structure in Python | I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:
Fruits
Apple
Auxiliary
Core
Extras
Banana
Something
Coconut
Vegetables
Eggplant
Rutabaga
You can see that top-level items are indented by ... | [
">>> with open(\"food.txt\") as f:\n... res = []\n... s=[]\n... for line in f:\n... line=line.rstrip()\n... x=len(line)\n... line=line.lstrip()\n... indent = x-len(line)\n... s=s[:indent/2]+[line]\n... res.append(\"/\".join(s))\n... print res\n... \n['... | [
4,
1,
0,
0
] | [] | [] | [
"data_structures",
"file_io",
"python"
] | stackoverflow_0002554474_data_structures_file_io_python.txt |
Q:
Cheetah with Cherrypy: how to load base templates, and do so automatically on change during development
I am working on a cherrypy+cheetah app and would like to improve the development experience.
I have everything working when I manually compile templates beforehand. (Update: This is how things work for productio... | Cheetah with Cherrypy: how to load base templates, and do so automatically on change during development | I am working on a cherrypy+cheetah app and would like to improve the development experience.
I have everything working when I manually compile templates beforehand. (Update: This is how things work for production: precompile, don't ship *.tmpl and load templates as regular python modules.) However, during development I... | [
"Try this: \nReplace base.tmpl with:\n#from Cheetah.Template import Template\n#def body\n #set $base = Template(file=\"templates/base.tmpl\") \n $base.body()\n <br/>\nThis is the extended body\n#end def\n\n$body()\n<br/>\nThis is from index\n\n",
"Looks like this question was kind of answered in another SO que... | [
1,
1
] | [] | [] | [
"cheetah",
"cherrypy",
"python",
"template_engine"
] | stackoverflow_0002550511_cheetah_cherrypy_python_template_engine.txt |
Q:
Python enumerate built-in error when using the start parameter
I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g.
self.groups = [Groups(self, idx) for idx in range(n_groups)]
then later:
for idx, group in enumerate(self.groups):
# do some stuff
but when I change th... | Python enumerate built-in error when using the start parameter | I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g.
self.groups = [Groups(self, idx) for idx in range(n_groups)]
then later:
for idx, group in enumerate(self.groups):
# do some stuff
but when I change the enumerate call to start at the 2nd list element via the start para... | [
"The problem: Using an indexer with a single argument on a sequence will yield a single object from the sequence. The object picked from your sequence is of type Group, and that type is not iterable.\nThe solution: Use the slice construct to get a new sequence of items from a specific index:\nfor idx, group in enu... | [
3,
1,
1
] | [] | [] | [
"iterable",
"python"
] | stackoverflow_0002552287_iterable_python.txt |
Q:
python mongokit Connection() AssertionError
just installed mongokit and can't figure out why I get AssertionError
python console:
>>> from mongokit import Connection
>>> c = Connection()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/mongokit... | python mongokit Connection() AssertionError | just installed mongokit and can't figure out why I get AssertionError
python console:
>>> from mongokit import Connection
>>> c = Connection()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/mongokit-0.5.3-py2.6.egg/mongokit/connection.py", line 35... | [
"This is a known issue in PyMongo working against devel (>1.4.0) versions of MongoDB. Just released PyMongo 1.5.2 w/ a fix - try upgrading to that.\n"
] | [
1
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0002551530_mongodb_pymongo_python.txt |
Q:
long-index arrays in python
I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than s... | long-index arrays in python | I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:
x ... | [
"With a 32-bit address space, any language is going to be struggling to be able to address such an array. Then there's the problem of how much real memory you have on your computer.\nIf you want 10B array elements, each element representing either true or false, use an array.array('I', ...) ...\ncontainer = array.a... | [
5,
4,
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001436411_python.txt |
Q:
python sqlite3 syntax error when copying a row
I'm having trouble copying a row from one table to another using sqlite3 in python (2.6.1 don't ask). I can specify one column, but if I add a second, it gives me an error.
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
#this works: curs... | python sqlite3 syntax error when copying a row | I'm having trouble copying a row from one table to another using sqlite3 in python (2.6.1 don't ask). I can specify one column, but if I add a second, it gives me an error.
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
#this works: cursor.execute("insert into table2 (name) select (name) ... | [
"You shouldn't have the parentheses after select. It should be:\ninsert into table2 (name, title) select name, title from table1\n\n"
] | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0002555302_python_sqlite.txt |
Q:
custom format specifications in python
in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to
define a '%M' (or some such) which would then dump the entire contents of the matrix...
thanks
A:
Defining the __str__()/__unicode__() and/or __r... | custom format specifications in python | in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to
define a '%M' (or some such) which would then dump the entire contents of the matrix...
thanks
| [
"Defining the __str__()/__unicode__() and/or __repr__() methods will let you use the existing %s and %r format specifiers as you like.\n",
"I don't believe that it's possible to define a new format specifier for print. You might be able to add a method to your class that sets a format that you use, and define th... | [
5,
0,
0
] | [] | [] | [
"format",
"python",
"specifications"
] | stackoverflow_0002554758_format_python_specifications.txt |
Q:
How can I have my python file show its mercurial tag or revision as the module version?
I'd like to add a --version command line option to my python application that will show the right version depending on the tagged status of the command:
If the file comes from a version whose short hex ID was abcdef01 that was ... | How can I have my python file show its mercurial tag or revision as the module version? | I'd like to add a --version command line option to my python application that will show the right version depending on the tagged status of the command:
If the file comes from a version whose short hex ID was abcdef01 that was tagged TAG, --version should show this:
MyApp Version TAG (abcdef01)
If the file comes from ... | [
"Once you activate the keyword extension, you can have it in a variable which can be carved up for the hash.\n",
"Someone pointed out the KeywordExtension, and that's definitely one route to go.\nFor a little more control you can create an 'update' writes what you want into a version file which you don't add to t... | [
1,
1
] | [] | [] | [
"keyword",
"mercurial",
"python"
] | stackoverflow_0002554990_keyword_mercurial_python.txt |
Q:
good __eq__, __lt__, ..., __hash__ methods for image class?
I create the following class:
class Image(object):
def __init__(self, extension, data, urls=None, user_data=None):
self._extension = extension
self._data = data
self._urls = urls
self._user_data = user_data
self... | good __eq__, __lt__, ..., __hash__ methods for image class? | I create the following class:
class Image(object):
def __init__(self, extension, data, urls=None, user_data=None):
self._extension = extension
self._data = data
self._urls = urls
self._user_data = user_data
self._hex_digest = hashlib.sha1(self._data).hexDigest()
Images shoul... | [
"Do you really need the images to be ordered? If not, I would drop the __lt__ method. For __hash__, remember that two unequal objects can have the same hash value, so you can just pick one of your attributes (or use a tuple of multiple attributes) to derive the hash code. Ex:\ndef __hash__(self):\n return hash(... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0002555338_python.txt |
Q:
Including libraries in project. Best practice
I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.
I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this ... | Including libraries in project. Best practice | I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.
I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply write this i... | [
"Use the pip requirements text file.\nJust name the packages [and optionally version]\nAsk the users to execute the following command in the README. (If you provide an install script, then you should call this within that; In that case you should also use Virtualenv)\npip install -r requirements.txt\n\nand all the ... | [
3,
3,
1,
1,
1
] | [] | [] | [
"distribution",
"python"
] | stackoverflow_0002555393_distribution_python.txt |
Q:
Web framework for an application utilizing existing database?
A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.
I'm looking for suggestions on which framework would be most suitable for this... | Web framework for an application utilizing existing database? | A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.
I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Java.
Accordin... | [
"Use sqlalchemy. On any framework you choose. It can reflect your database as ORM.\n",
"I’m currently rebuilding a legacy PHP web application with a MySQL database my self. \nThe PHP code was kind of spaghetti and is now rewritten in Java as it type safe, promotes well-structured code, has excellent tooling and h... | [
5,
3,
2,
2,
2,
0,
0,
0
] | [] | [] | [
"java",
"php",
"python",
"ruby"
] | stackoverflow_0002507463_java_php_python_ruby.txt |
Q:
Why does setting this member in C fail?
I'm writing a Python wrapper for a C++ library, and I'm getting a really weird when trying to set a struct's field in C. If I have a struct like this:
struct Thing
{
PyOBJECT_HEAD
unsigned int val;
};
And have two functions like this:
static PyObject* Thing_GetBit(... | Why does setting this member in C fail? | I'm writing a Python wrapper for a C++ library, and I'm getting a really weird when trying to set a struct's field in C. If I have a struct like this:
struct Thing
{
PyOBJECT_HEAD
unsigned int val;
};
And have two functions like this:
static PyObject* Thing_GetBit(Thing* self, PyObject* args)
{
unsigned i... | [
"Is it possible that passing the address of a bool PyArg_ParseTuple is causing your trouble? The \"i\" format will write an int sized thing.\nWhat kind of machine are you running on?\n",
"Shouldn't it be:\nif (on)\n self->val |= mask;\nelse\n self->val &= ~mask;\n\n"
] | [
3,
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0002556172_c_python.txt |
Q:
python list mysteriously getting set to something within my django/piston handler
Note: (I've updated this since the first two suggestions... you can view the old post in txt form here: http://bennyland.com/old-2554127.txt). The update I made was to better understand what was going wrong - and now I at least sort... | python list mysteriously getting set to something within my django/piston handler | Note: (I've updated this since the first two suggestions... you can view the old post in txt form here: http://bennyland.com/old-2554127.txt). The update I made was to better understand what was going wrong - and now I at least sort of know what's happening but I have no clue how to fix it.
Anyway, using Django and Pi... | [
"I would say that there is a basic flaw in your code, if has_limit() can return True when limit is a list of length 2, but this line will fail if limit is shorter than 3 elements long:\ns_query = '%swith limit[%s,%s](limit,%s > traceback:%s),' % \n (s_query, self.limit[0], self.limit[1], kwargs['limit'], \... | [
0,
0
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0002554127_django_django_piston_python.txt |
Q:
Right way to create [self]respawning app in python
I am using jabber bot written in python to log some MUC talks. Sometimes it drops on some network or XMPP problems. In this case I have to start it again by myself. The goal is to make it "self-respawning".
I have some variants about how to do it.
Bot is one proc... | Right way to create [self]respawning app in python | I am using jabber bot written in python to log some MUC talks. Sometimes it drops on some network or XMPP problems. In this case I have to start it again by myself. The goal is to make it "self-respawning".
I have some variants about how to do it.
Bot is one process. Another process
monitors its activity and starts it... | [
"If you're using something like ubuntu, try looking into upstart and its automatic daemonization and \"respawn\" feature. Here's a good general blogpost about running vs. starting processes. \nI've also heard good things about supervisdord.\n"
] | [
4
] | [] | [] | [
"daemon",
"python",
"spawn",
"xmpp"
] | stackoverflow_0002555857_daemon_python_spawn_xmpp.txt |
Q:
Forwarding keypresses in GTK
I'm writing a bit of code for a Gedit plugin. I'm using Python and the interface (obviously) is GTK.
So, the issue I'm having is quite simple: I have a search box (a gtk.Entry) and right below I have a results box (a gtk.TreeView). Right after you type something in the search box you a... | Forwarding keypresses in GTK | I'm writing a bit of code for a Gedit plugin. I'm using Python and the interface (obviously) is GTK.
So, the issue I'm having is quite simple: I have a search box (a gtk.Entry) and right below I have a results box (a gtk.TreeView). Right after you type something in the search box you are presented a bunch of results, a... | [
"Not a proper answer to the question (I don't know how to forward key presses), but there's an alternative solution to your problem.\nManipulate the TreeView cursor/selection directly, for example:\npath, column = browser.get_cursor()\nbrowser.set_cursor((path[0] + 1,)) # Down\n\n",
"Did you include the key-press... | [
2,
1
] | [] | [] | [
"forwarding",
"gtk",
"keypress",
"python"
] | stackoverflow_0002526589_forwarding_gtk_keypress_python.txt |
Q:
Can I use XPCOM to create and manipulate a Firefox window as I would use win32 COM with IE?
With win32 COM I create an Internet Explorer instance and control it almost fully from my python code (manipulate windows, DOM elements, etc). More specifically, using DispatchEx('InternetExplorer.Application'). Can I do th... | Can I use XPCOM to create and manipulate a Firefox window as I would use win32 COM with IE? | With win32 COM I create an Internet Explorer instance and control it almost fully from my python code (manipulate windows, DOM elements, etc). More specifically, using DispatchEx('InternetExplorer.Application'). Can I do the same using XPCOM and C++/python?
I need to automate certain actions taken on the html ui of som... | [
"I don't know about programmatically creating and controlling full Firefox instances, but Mozilla can definitely be embedded using XPCOM.\nThe Mozilla embedding FAQ, embedding how-to and the embedding APIs overview should get you started. There are also other means for embedding.\n",
"I have used the nsIDOMXULEle... | [
1,
1
] | [] | [] | [
"browser_automation",
"c++",
"python",
"xpcom",
"xul"
] | stackoverflow_0002291034_browser_automation_c++_python_xpcom_xul.txt |
Q:
How to send mail in hotmail using Python?
Is there a way to login my hotmail account and send mails with a Python program?
A:
You can try using their SMTP server:
User name: Your Windows Live ID, for example yourname@hotmail.com
Password: The password you usually use to sign in to Hotmail or Windows Live
SMTP s... | How to send mail in hotmail using Python? | Is there a way to login my hotmail account and send mails with a Python program?
| [
"You can try using their SMTP server:\n\nUser name: Your Windows Live ID, for example yourname@hotmail.com\nPassword: The password you usually use to sign in to Hotmail or Windows Live\nSMTP server: smtp.live.com (Port 25) {Note: If port 25 has been blocked in your network or by your ISP, you can set SMTP port to 5... | [
2
] | [] | [] | [
"hotmail",
"python"
] | stackoverflow_0002556533_hotmail_python.txt |
Q:
What does represent the hexadecimal integer showed on print/repr in Python?
In an interactive session like the following one:
>>> f=open('test.txt','w')
>>> f
<open file 'test.txt', mode 'w' at 0x6e610>
what does 0x6e610 represent and what could I do with that hexadecimal number in Python?
A:
>>> f=open('test.t... | What does represent the hexadecimal integer showed on print/repr in Python? | In an interactive session like the following one:
>>> f=open('test.txt','w')
>>> f
<open file 'test.txt', mode 'w' at 0x6e610>
what does 0x6e610 represent and what could I do with that hexadecimal number in Python?
| [
">>> f=open('test.txt')\n>>> f\n<open file 'test.txt', mode 'r' at 0x10047c938>\n>>> hex(id(f))\n'0x10047c938'\n\nHave a look at id in the official documentation:\nReturn the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifeti... | [
5,
3
] | [] | [] | [
"core",
"python"
] | stackoverflow_0002556799_core_python.txt |
Q:
Distance by sea calculator, intermediate coordinates?
How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.
Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* a... | Distance by sea calculator, intermediate coordinates? | How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.
Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* algorithm. Then transform pixels to relative coordinates.
Th... | [
"Beware of the fact that maps can distort distances. For example, in a Mercator projections segments far away from the equator represent less actual distance than segments near the equator of equal length. If you just assign uniform cost to your pixels/squares/etc, you will end up with non-optimal routing and erron... | [
2,
1,
1
] | [] | [] | [
"distance",
"geo",
"maps",
"python"
] | stackoverflow_0002512322_distance_geo_maps_python.txt |
Q:
How to synchronize a python dict with multiprocessing
I am using Python 2.6 and the multiprocessing module for multi-threading. Now I would like to have a synchronized dict (where the only atomic operation I really need is the += operator on a value).
Should I wrap the dict with a multiprocessing.sharedctypes.syn... | How to synchronize a python dict with multiprocessing | I am using Python 2.6 and the multiprocessing module for multi-threading. Now I would like to have a synchronized dict (where the only atomic operation I really need is the += operator on a value).
Should I wrap the dict with a multiprocessing.sharedctypes.synchronized() call? Or is another way the way to go?
| [
"Intro\nThere seems to be a lot of arm-chair suggestions and no working examples. None of the answers listed here even suggest using multiprocessing and this is quite a bit disappointing and disturbing. As python lovers we should support our built-in libraries, and while parallel processing and synchronization is... | [
65,
3,
3,
2
] | [] | [] | [
"dictionary",
"multiprocessing",
"python"
] | stackoverflow_0002545961_dictionary_multiprocessing_python.txt |
Q:
python dict.fromkeys() returns empty
I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def enter_users_into_dict(userlist)... | python dict.fromkeys() returns empty | I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def enter_users_into_dict(userlist):
newusr = {}
newusr.fromkeys(user... | [
"fromkeys is a class method, meaning\nnewusr.fromkeys(userlist, 0)\n\nis exactly the same as calling\ndict.fromkeys(userlist, 0)\n\nBoth which return a dictionary of the keys in userlist. You need to assign it to something. Try this instead.\nnewusr = dict.fromkeys(userlist, 0)\nreturn newusr\n\n",
"You need to c... | [
10,
3,
2
] | [] | [] | [
"dictionary",
"fromkeys",
"python"
] | stackoverflow_0002557193_dictionary_fromkeys_python.txt |
Q:
Cheetah pre-compiled template usage
For performance reason as suggested here, I am studying how to used the pr-compiled template.
I edit hello.tmpl in template directory as
#attr title = "This is my Template"
<html>
<head>
<title>\${title}</title>
</head>
<body>
Hello \${who}!
</bod... | Cheetah pre-compiled template usage | For performance reason as suggested here, I am studying how to used the pr-compiled template.
I edit hello.tmpl in template directory as
#attr title = "This is my Template"
<html>
<head>
<title>\${title}</title>
</head>
<body>
Hello \${who}!
</body>
</html>
then issued cheetah-compile.e... | [
"Your main problem is that in runner.py inside myMethod() instead of\nprint tmpl\n\nYou need\nprint results\n\nAdditionally, your code has some formatting problems:\n\ndon't escape the ${title} with a backslash\nyou need if __name__ == '__main__': instead of if name == 'main':\n\n"
] | [
0
] | [] | [] | [
"cheetah",
"python",
"templates"
] | stackoverflow_0002550323_cheetah_python_templates.txt |
Q:
Exposing python api over the network for an iphone application
I have functionality built in python on a central server. I wish to expose this api over the network to an iphone application. What would be the best way to do that?
Is it possible to create web services in python and have the iphone app use those? If ... | Exposing python api over the network for an iphone application | I have functionality built in python on a central server. I wish to expose this api over the network to an iphone application. What would be the best way to do that?
Is it possible to create web services in python and have the iphone app use those? If so could anyone give me pointers as to how to create web services in... | [
"Simplest is xmlrpclib, if the app you want to consume this service can speak XML-RPC.\nAccording to this SO question, the iPhone can indeed support XML-RPC without too much trouble.\n",
"Look at using a REST style web service for that. I am currently working on an iPhone app that uses a Pylons based web service ... | [
2,
1
] | [] | [] | [
"iphone",
"python",
"web_services"
] | stackoverflow_0002557179_iphone_python_web_services.txt |
Q:
When I run Django on Dreamhost using SQLite, why do I get an OperationalError telling me that a table doesn’t exist?
I had a Django site running on Dreamhost. Although I used SQLite when developing locally, I initially used MySQL on Dreamhost, because that’s what the wiki page said to do, and because if I’m using ... | When I run Django on Dreamhost using SQLite, why do I get an OperationalError telling me that a table doesn’t exist? | I had a Django site running on Dreamhost. Although I used SQLite when developing locally, I initially used MySQL on Dreamhost, because that’s what the wiki page said to do, and because if I’m using an ORM, I might as well take advantage of it by running against a different database.
After a while, I switched the settin... | [
"It turned out that on the server, the DATABASE_NAME setting required a full path, e.g.\nDATABASE_NAME = '/home/USERNAME/SITE/DJANGOPROJECT/DATABASE.db'\n\nLocally (and I guess for manage.py on the server), just a filename was fine, e.g.\nDATABASE_NAME = 'DATABASE.db'\n\n"
] | [
1
] | [] | [] | [
"django",
"dreamhost",
"python",
"sqlite"
] | stackoverflow_0002557710_django_dreamhost_python_sqlite.txt |
Q:
Python dealing with dates and times
I'm looking for a solution to the following:
Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.
Then based on that, I need to be able to iterate through a dir... | Python dealing with dates and times | I'm looking for a solution to the following:
Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.
Then based on that, I need to be able to iterate through a directory and find all files that were creat... | [
"Simplest, where adate is an instance of datetime.date:\ndef previousmonth(adate):\n m = adate.month - 1\n return m if m else 12\n\nThere's no real way in most Unix filesystems to determine when a file was created, as they just don't keep that information around. Maybe you want the \"latest inode change time... | [
3,
2,
1,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002555904_datetime_python.txt |
Q:
Please explain this python behavior
class SomeClass(object):
def __init__(self, key_text_pairs = None):
.....
for key, text in key_text_pairs:
......
......
x = SomeClass([(1, "abc",), (2, "fff",)])
The value of key_text_pairs inside the init is None even if I pass a l... | Please explain this python behavior | class SomeClass(object):
def __init__(self, key_text_pairs = None):
.....
for key, text in key_text_pairs:
......
......
x = SomeClass([(1, "abc",), (2, "fff",)])
The value of key_text_pairs inside the init is None even if I pass a list as in the above statement. Why is it ... | [
"First of all, when you say for key, text in key_text_pairs, you are implying that the list has tuples. I tested your code exactly the way it is and that's what happened.\nChange x = SomeClass([1, 2, 3]) to x = SomeClass([(1, 1.0), (2, 2.0), (3, 3.0)]) and see if that helps\nCheers\n",
"So just looking at that co... | [
2,
0,
0
] | [] | [] | [
"initialization",
"python"
] | stackoverflow_0002557891_initialization_python.txt |
Q:
Sorting and indexing into a list in a Django template?
How can you perform complex sorting on an object before passing it to the template? For example, here is my view:
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all(... | Sorting and indexing into a list in a Django template? | How can you perform complex sorting on an object before passing it to the template? For example, here is my view:
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit'... | [
"As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.\nGetting a sorted list of a physician's patients:\nclass Physician(Model):\n ...\n def sorted_patients(self):\n ... | [
11,
4,
1,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0001191439_django_django_templates_python.txt |
Q:
delete Task / PeriodicTask in celery
How can I delete a regular Task or PeriodicTask in celery?
A:
You revoke the task: See documentation:
Control.revoke(task_id, destination=None, terminate=False, signal='SIGTERM', **kwargs)
Tell all (or specific) workers to revoke a task by id.
If a task is revoked, t... | delete Task / PeriodicTask in celery | How can I delete a regular Task or PeriodicTask in celery?
| [
"You revoke the task: See documentation:\nControl.revoke(task_id, destination=None, terminate=False, signal='SIGTERM', **kwargs)\n Tell all (or specific) workers to revoke a task by id.\n\n If a task is revoked, the workers will ignore the task and not execute it after all.\n\n Parameters: \n task_i... | [
16
] | [] | [] | [
"celery",
"python",
"rabbitmq"
] | stackoverflow_0002557424_celery_python_rabbitmq.txt |
Q:
Django serializer gives 'str' object has no attribute '_meta' error
I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.
'str' object has no attribute '_meta'
I have other serialization and it works.
Here is the code.
def... | Django serializer gives 'str' object has no attribute '_meta' error | I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.
'str' object has no attribute '_meta'
I have other serialization and it works.
Here is the code.
def get_calendar_limits(request):
result = serializers.serialize("json"... | [
"I get the same error when trying to serialize an object that is not derived from Django's Model\n",
"Python has \"json\" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.\n",
"Take a look at the following:\nobjects= Session.objects.aggregate(Max('date'), Min('date'))\... | [
1,
1,
0
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0000793095_django_json_python.txt |
Q:
how to get internet explorer address bar for python
i need grab to internet explorer address bar. how to get address bar url for python ? (i need second part other browsers grabbing address bar but internet explorer is urgently).
Thanks.
A:
The following works for me.
from win32com.client import Dispatch
SHELL ... | how to get internet explorer address bar for python | i need grab to internet explorer address bar. how to get address bar url for python ? (i need second part other browsers grabbing address bar but internet explorer is urgently).
Thanks.
| [
"The following works for me.\nfrom win32com.client import Dispatch\n\nSHELL = Dispatch(\"Shell.Application\")\n\ndef get_ie(shell):\n for win in shell.Windows():\n if win.Name == \"Windows Internet Explorer\":\n return win\n return None\n\ndef main():\n ie = get_ie(SHELL)\n if ie:\n ... | [
3,
1
] | [] | [] | [
"internet_explorer",
"python",
"pywin32"
] | stackoverflow_0002555905_internet_explorer_python_pywin32.txt |
Q:
Supported Audio Formats of Qt4 Phonon?
I am making a music player in PyQt4, and I am using Phonon to play the music itself. This application is aimed primarily at Windows, but I plan on also supporting Mac and Linux versions. What I want to know is which audio formats are supported by Phonon so that I can ensure t... | Supported Audio Formats of Qt4 Phonon? | I am making a music player in PyQt4, and I am using Phonon to play the music itself. This application is aimed primarily at Windows, but I plan on also supporting Mac and Linux versions. What I want to know is which audio formats are supported by Phonon so that I can ensure that the user only enters those files.
| [
"You need to call availableMimeTypes() to check what formats the backend supports.\n"
] | [
6
] | [] | [] | [
"phonon",
"pyqt4",
"python",
"qt4"
] | stackoverflow_0002551873_phonon_pyqt4_python_qt4.txt |
Q:
(Python/Django): How do I keep my production db in sync (scheme and data) and with dev pc db?
I have a local Postgres database which will be filled with data (daily) on my local development machine. What is a good solution to transfer/sync/mirror this data to a production Postgres database.
For what it's worth I'm... | (Python/Django): How do I keep my production db in sync (scheme and data) and with dev pc db? | I have a local Postgres database which will be filled with data (daily) on my local development machine. What is a good solution to transfer/sync/mirror this data to a production Postgres database.
For what it's worth I'm developing in Python using Django.
Thanks!
| [
"This seems like a strange workflow for me. Wouldn't it be much better to import the data in the production database and then just sync it with your development db from time to time?\nIMO, the development machine shouldn't be included in the production data workflow.\nThat's the way I do it using fabric. I've writt... | [
3,
2
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0002537253_django_postgresql_python.txt |
Q:
Simulate Network Presence in dbus
Is there a way using Python to simulate the presence of an active network connection using dbus? If I call getstate() on the dbus, I'm able to get the current network state. I want to set the current state to 4 (Connection Present). This is because Network Manager is not able to c... | Simulate Network Presence in dbus | Is there a way using Python to simulate the presence of an active network connection using dbus? If I call getstate() on the dbus, I'm able to get the current network state. I want to set the current state to 4 (Connection Present). This is because Network Manager is not able to connect using my modem and I use other t... | [
"I'm pretty sure that both Pidgin and Empathy assume you're online if you disable NM by right-clicking the Network Manager tray icon and untick Enable Networking. So you can do this when you're connecting via a non-NM mechanism. No code necessary!\n(You could write an application which implements the same D-Bus int... | [
1,
0
] | [] | [] | [
"dbus",
"linux",
"python"
] | stackoverflow_0002550523_dbus_linux_python.txt |
Q:
How do I do a semijoin using SQLAlchemy?
http://en.wikipedia.org/wiki/Relational_algebra#Semijoin
Let's say that I have two tables: A and B. I want to make a query that would work similarly to the following SQL statement using the SQLAlchemy orm:
SELECT A.*
FROM A, B
WHERE A.id = B.id
AND B.type = 'some type';
... | How do I do a semijoin using SQLAlchemy? | http://en.wikipedia.org/wiki/Relational_algebra#Semijoin
Let's say that I have two tables: A and B. I want to make a query that would work similarly to the following SQL statement using the SQLAlchemy orm:
SELECT A.*
FROM A, B
WHERE A.id = B.id
AND B.type = 'some type';
The thing is that I'm trying to separate out A... | [
"Let's assume you have models classes A and B mapped to corresponding tables. \nThe simplest case is when you have relation in A pointing to B, let's name it A.b. Then you just use either A.b.has(type='some type') or A.b.any(type='some type') (depending on whether A.b is scalar or represent a collection) as conditi... | [
2
] | [] | [] | [
"orm",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002554132_orm_python_sql_sqlalchemy.txt |
Q:
Django unable to update model
i have the following function to override the default save function in a model match
def save(self, *args, **kwargs):
if self.Match_Status == "F":
Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1)
Team.objects.filter(pk=self.Team_two.id).update(P... | Django unable to update model | i have the following function to override the default save function in a model match
def save(self, *args, **kwargs):
if self.Match_Status == "F":
Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1)
Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1)
if sel... | [
"add this in ur admin.py \ndef save_model(self, request ,obj ,form,change):\n if obj.Match_Status == \"F\":\n Team.objects.filter(pk=obj.Team_one.id).update(Played=F('Played')+1)\n Team.objects.filter(pk=obj.Team_two.id).update(Played=F('Played')+1)\n if obj.Winner !=\"\": \n Team.objects.filter(p... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0002437526_django_django_admin_django_models_python.txt |
Q:
Why is it that I cannot insert this into Django correctly?
new_thing = MyTable(last_updated=datetime.datetime.now())
new_thing.save()
>>>>select * from MyTable\G;
last_updated: 2010-04-01 05:26:21
However, in my Python console...this is what it says...
>>> print datetime.datetime.now()
2010-04-01 10:26:21.643041... | Why is it that I cannot insert this into Django correctly? | new_thing = MyTable(last_updated=datetime.datetime.now())
new_thing.save()
>>>>select * from MyTable\G;
last_updated: 2010-04-01 05:26:21
However, in my Python console...this is what it says...
>>> print datetime.datetime.now()
2010-04-01 10:26:21.643041
So obviously it's off by 5 hours.
By the way, the database use... | [
"Difference is between your timezone and whatever is set in Django settings.py TIME_ZONE. By default it's 'America/Chicago'.\n",
"I suspect that Django save the time in DB according to GMT and the ORM give it back to you according to your locale.\nTell use what does this code say :\nprint MyTable.objects.all().or... | [
2,
1
] | [] | [] | [
"database",
"django",
"mysql",
"python",
"time"
] | stackoverflow_0002559702_database_django_mysql_python_time.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.