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:
Always getting the same path with A* implementation
I'm trying to implementing A* from the pseudo code from wikipedia however I'm getting some weird results.
The implementation finds what at first looks like a good path, but with a further look it always produces the same path!
Can anyone spot anything wrong? The ... | Always getting the same path with A* implementation | I'm trying to implementing A* from the pseudo code from wikipedia however I'm getting some weird results.
The implementation finds what at first looks like a good path, but with a further look it always produces the same path!
Can anyone spot anything wrong? The code is written in python 3.1 and uses pygame.
import pyg... | [
"You access came_from on time with y, and one time with y.index in\n if tentative_is_better:\n if y.index in came_from:\n if f_score[x.index] < f_score[came_from[y].index]: // index by y\n came_from[y.index] = x // index by y.index\n else:\n\nYou probably ... | [
0
] | [] | [] | [
"a_star",
"path_finding",
"pygame",
"python"
] | stackoverflow_0004353502_a_star_path_finding_pygame_python.txt |
Q:
Any write functions In python that have the same safety as ACID does in databases
The title could have probably been put better, but anyway. I was wondering if there are any functions for writing to files that are like what the ACID properties are for databases. Reason is, I would like to make sure that the file w... | Any write functions In python that have the same safety as ACID does in databases | The title could have probably been put better, but anyway. I was wondering if there are any functions for writing to files that are like what the ACID properties are for databases. Reason is, I would like to make sure that the file writes I am doin won't mess up and corrupt the file if the power goes out.
| [
"Depending on what exactly you're doing with your files and the platform there are a couple options:\n\nIf you're serializing a blob from memory to disk repeatedly to maintain state (example: dhcp leases file),\nif you're on a Posix system you can write your data to a temporary file and 'rename' the temporary file ... | [
6,
1,
1
] | [] | [] | [
"acid",
"python"
] | stackoverflow_0004352106_acid_python.txt |
Q:
unknown encoding to unicode
What would be this encoding's name?
smb://nas/music/_lib/v/voivod/voivod-rrr%C3%B6%C3%B6%C3%B6aaarrr/01%20-%20voivod%20-%20rrr%C3%B6%C3%B6%C3%B6aaarrr%20-%20korg%C3%BCll_the_exterminator.mp3
I would like to convert such string to unicode using Python. How would I do that?
A:
That's... | unknown encoding to unicode | What would be this encoding's name?
smb://nas/music/_lib/v/voivod/voivod-rrr%C3%B6%C3%B6%C3%B6aaarrr/01%20-%20voivod%20-%20rrr%C3%B6%C3%B6%C3%B6aaarrr%20-%20korg%C3%BCll_the_exterminator.mp3
I would like to convert such string to unicode using Python. How would I do that?
| [
"That's URL-encoded UTF-8. URL-decode it, then decode it as UTF-8.\n",
"Try urllib.unquote().\n",
"import urllib\n\n>>> m=\"smb://nas/music/_lib/v/voivod/voivod-rrr%C3%B6%C3%B6%C3%B6aaarrr/01%20-%20voivod%20-%20rrr%C3%B6%C3%B6%C3%B6aaarrr%20-%20korg%C3%BCll_the_exterminator.mp3\"\n>>> m1= urllib.unquote(m)\n>>>... | [
3,
0,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0004129658_python_unicode.txt |
Q:
Handling Single File Extraction From Corrupted GZ (TAR)
This is my first post on Stack Overflow, I have a question regarding extracting a single file from a TAR file using GZ compression. I'm not the best at Python so I may be doing this incorrectly, any help would be much appreciated.
Scenario:
Corrupted *.tar.... | Handling Single File Extraction From Corrupted GZ (TAR) | This is my first post on Stack Overflow, I have a question regarding extracting a single file from a TAR file using GZ compression. I'm not the best at Python so I may be doing this incorrectly, any help would be much appreciated.
Scenario:
Corrupted *.tar.gz file comes in, the first file in the GZ contains important... | [
"Using the manual Unix method it looks like gzip unzips the file up to the point where it breaks. \nPython gzip(or tar) module exits as soon as it notices you have a corrupt archive due to the failed CRC check.\nJust an idea but you could pre-process the damaged archives with gzip and re-compress them to correct th... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004350355_python.txt |
Q:
How can I program against SharePoint 2007 remotely in IronPython?
My current goal is to query a list on our SharePoint 2007 server from client machines (i.e., remotely), from a program, preferably written in IronPython (CPython is also fine). Can someone please provide me with an example of how this can be done? I... | How can I program against SharePoint 2007 remotely in IronPython? | My current goal is to query a list on our SharePoint 2007 server from client machines (i.e., remotely), from a program, preferably written in IronPython (CPython is also fine). Can someone please provide me with an example of how this can be done? I've searched quite a bit, and I have to say it's difficult to find info... | [
"Since your code will be running remotely. You cannot leverage the SharePoint .NET API to gain access, so IronPython is not required.\nFrom straight Python (or IronPython or CPython or whatever) your best route is using the SOAP-based web services to query the list in question.\nThe syntax is typical MS-XML, which ... | [
1
] | [] | [] | [
"ironpython",
"python",
"sharepoint_2007"
] | stackoverflow_0004347941_ironpython_python_sharepoint_2007.txt |
Q:
How can I create a ramdisk in Python?
I want to create a ramdisk in Python. I want to be able to do this in a cross-platform way, so it'll work on Windows XP-to-7, Mac, and Linux. I want to be able to read/write to the ramdisk like it's a normal drive, preferably with a drive letter/path.
The reason I want this is... | How can I create a ramdisk in Python? | I want to create a ramdisk in Python. I want to be able to do this in a cross-platform way, so it'll work on Windows XP-to-7, Mac, and Linux. I want to be able to read/write to the ramdisk like it's a normal drive, preferably with a drive letter/path.
The reason I want this is to write tests for a script that creates a... | [
"How about PyFilesystem? \nhttps://docs.pyfilesystem.org/en/latest/reference/memoryfs.html\nhttps://docs.pyfilesystem.org/en/latest/reference/tempfs.html\nThe downside is that you have to access the filesystem with PyFilesystem API, but you can also access the real fs with PyFilesystem.\n",
"Because file and dire... | [
21,
4,
1
] | [
"Please read this:\nhttp://docs.python.org/library/tempfile.html#tempfile.TemporaryFile\n\n\"Return a file-like object that can be\n used as a temporary storage area. The\n file is created using mkstemp(). It\n will be destroyed as soon as it is\n closed (including an implicit close\n when the object is garbag... | [
-7
] | [
"cross_platform",
"python",
"ramdisk",
"temporary_files",
"unit_testing"
] | stackoverflow_0004351048_cross_platform_python_ramdisk_temporary_files_unit_testing.txt |
Q:
How to get `http-equiv`s in python?
I am using urllib2.urlopen to fetch a URL and get header information like 'charset', 'content-length'.
But some page set their charset with something like
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
And urllib2 doesn't parse this for me.
Is there any bu... | How to get `http-equiv`s in python? | I am using urllib2.urlopen to fetch a URL and get header information like 'charset', 'content-length'.
But some page set their charset with something like
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
And urllib2 doesn't parse this for me.
Is there any built-in tool I can use to get http-equiv i... | [
"Find 'http-equiv' using BeautifulSoup\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nf = urllib2.urlopen(\"http://example.com\")\nsoup = BeautifulSoup(f) # trust BeautifulSoup to parse the encoding\nfor meta in soup.findAll('meta', attrs={\n 'http-equiv': lambda x: x and x.lower() == 'content-type... | [
2,
1,
1,
1
] | [] | [] | [
"http",
"python"
] | stackoverflow_0004352468_http_python.txt |
Q:
problem inheriting from list
class speciallist(list):
def __new__(self):
return self
def custommethod(self,param):
#do stuff
return value
listesp = speciallist()
listesp.custommethod(param)
I get "unbound method custommethod() must be called with speciallist instance as first... | problem inheriting from list | class speciallist(list):
def __new__(self):
return self
def custommethod(self,param):
#do stuff
return value
listesp = speciallist()
listesp.custommethod(param)
I get "unbound method custommethod() must be called with speciallist instance as first argument"
I thought it was going ... | [
"That's a sneaky one. Short answer, remove the __new__ method from your definition.\nThe __new__ method is a class method, so it takes the class, not the instance, as its first argument. It's designed to create an instance (possibly of another class) and return it. You're simply returning the class itself, not an i... | [
5
] | [] | [] | [
"class",
"object",
"python"
] | stackoverflow_0004354161_class_object_python.txt |
Q:
Connecting to Oracle database using cx_Oracle on Python
Am using Debian 5, Python 2.5 with cx_Oracle unicode version installed. I try to connect using the below script but its failing
>>> connection = cx_Oracle.connect('hr/XXXXX@local_xe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Ty... | Connecting to Oracle database using cx_Oracle on Python | Am using Debian 5, Python 2.5 with cx_Oracle unicode version installed. I try to connect using the below script but its failing
>>> connection = cx_Oracle.connect('hr/XXXXX@local_xe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument 1 must be unicode, not str
I think because... | [
"You should try \ncx_Oracle.connect(u'hr/XXXXX@local_xe')\n\nSince you have the unicode version of cx_Oracle, it expects the connection string to be a unicode sring (argument 1 must be unicode, not str) \nPutting a u'' infront of a string converts it into unicode, and hence it doesn't throw the error.\n",
"the so... | [
4,
-1
] | [] | [] | [
"cx_oracle",
"python"
] | stackoverflow_0004347261_cx_oracle_python.txt |
Q:
How to write an image to datastore?
UPDATE:
See the comment by systempuntoout. The form was missing the submit button. Now it all works.
I have this code that I think would write an image to datastore; but that's not happenning:
class AvatarSave(webapp.RequestHandler):
def post(self):
q = User.all()
... | How to write an image to datastore? | UPDATE:
See the comment by systempuntoout. The form was missing the submit button. Now it all works.
I have this code that I think would write an image to datastore; but that's not happenning:
class AvatarSave(webapp.RequestHandler):
def post(self):
q = User.all()
q.filter("userEmail =", "az@exampl... | [
"I think your code is missing the Submit button on the image form submission:\nself.response.out.write(\"\"\"\n <form action=\"/avatar-save\" enctype=\"multipart/form-data\" method=\"post\"> \n <div><label>Avatar:</label></div>\n <div><input type=\"file\" name=\"img\"/>... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004353939_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python map() with cases
Simple enough but I can't find a decent example; so I asked here!
Basically what I was is, resultList = map(if >0:do this, else:do this, listOfNumbers)
How do I do that?
A:
Use a lambda (docs) function. I've used placeholder functions foo() and bar() which you'll have to replace with your... | Python map() with cases | Simple enough but I can't find a decent example; so I asked here!
Basically what I was is, resultList = map(if >0:do this, else:do this, listOfNumbers)
How do I do that?
| [
"Use a lambda (docs) function. I've used placeholder functions foo() and bar() which you'll have to replace with your \"do this\" / \"do that\" bits.\nresultList = map(lambda x: foo(x) if x > 0 else bar(x), listOfNumbers)\n\nAn alternative, which as @hop rightfully says is the preferred method in Python, is to use ... | [
7,
4,
3
] | [] | [] | [
"functional_programming",
"mapping",
"python"
] | stackoverflow_0004354371_functional_programming_mapping_python.txt |
Q:
Best practices when building timezone enabled applications
I am building a timezone enabled web application, and I am looking for best practices around that.
For example, I have user A and User B, who have timezone set. User A enters a time. (in his timezone.) Now how do you store this in the DB.
[option 1] Origi... | Best practices when building timezone enabled applications | I am building a timezone enabled web application, and I am looking for best practices around that.
For example, I have user A and User B, who have timezone set. User A enters a time. (in his timezone.) Now how do you store this in the DB.
[option 1] Original time with original timezone
[Option 2] UCT time stored in UC... | [
"Semantically, almost all of the datetimes you manipulate are absolute times (for example: billing, creations and modifications, last seen, api throttles, SO bounties…). They should be stored in UTC so that there is no ambiguity about them. Otherwise, when some government changes a DST rule and your system rules ge... | [
4,
2
] | [] | [] | [
"datetime",
"python",
"time",
"timezone"
] | stackoverflow_0004353925_datetime_python_time_timezone.txt |
Q:
How can I read the title, text and icon name from a pynotify.Notification?
If I have a pynotify.Notification object like:
n = pynotify.Notification('title', 'content', 'icon')
How can I read the title (to give 'title'), the text body (to give 'content') and the icon (to give 'icon')?
A:
In [72]: n = pynotify.No... | How can I read the title, text and icon name from a pynotify.Notification? | If I have a pynotify.Notification object like:
n = pynotify.Notification('title', 'content', 'icon')
How can I read the title (to give 'title'), the text body (to give 'content') and the icon (to give 'icon')?
| [
"In [72]: n = pynotify.Notification('title', 'content', 'icon')\n\nIn [73]: n.props.summary\nOut[74]: 'title'\n\nIn [75]: n.props.body\nOut[75]: 'content'\n\nIn [76]: n.props.icon_name\nOut[77]: 'icon'\n\n"
] | [
1
] | [] | [] | [
"notifications",
"pynotify",
"python"
] | stackoverflow_0004354474_notifications_pynotify_python.txt |
Q:
Does app engine have a Deploy Hook or Event?
I want to increase the version number on a model whenever there is a new deployment to the server.
So the idea behind this is: Everytime there is a deployment I wanna run some code.
Is this possible within App Engine using hooks or events?
I'm using App Engine for Pytho... | Does app engine have a Deploy Hook or Event? | I want to increase the version number on a model whenever there is a new deployment to the server.
So the idea behind this is: Everytime there is a deployment I wanna run some code.
Is this possible within App Engine using hooks or events?
I'm using App Engine for Python.
| [
"No.\nHowever, you could get the desired behavior if you write your own deployment script. This script could be a thin wrapper around appcfg.py which makes a request to your app once the deployment is complete (the request handler can execute the logic you wanted to put in your \"deploy hook\").\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004354647_google_app_engine_python.txt |
Q:
How to wrap and indent long lines when using print()?
I'm using Python to gather data from a Web service. The data itself is a list that will presented to users. I've managed it that it's printed out like:
( 1) Example of strings
( 2) Example 4
( 3) Another Example
( 4) Another Example 2
I'm using rjust (2) f... | How to wrap and indent long lines when using print()? | I'm using Python to gather data from a Web service. The data itself is a list that will presented to users. I've managed it that it's printed out like:
( 1) Example of strings
( 2) Example 4
( 3) Another Example
( 4) Another Example 2
I'm using rjust (2) for the numbers. However, if the lines are very long, the pr... | [
"Use the textwrap module: http://docs.python.org/library/textwrap.html\n textwrap.fill(text, initial_indent='', subsequent_indent=' ')\n\n"
] | [
9
] | [] | [] | [
"indentation",
"printing",
"python"
] | stackoverflow_0004355061_indentation_printing_python.txt |
Q:
Using Python's FTP library to retrieve files
this is my first post on here so I'm happy to be a part of the community. I have a fairly mundane question to ask, but it's been a fairly annoying problem so I'm hoping to find answers.
So I'm trying to use Python's FTPLIB module to retrieve a binary file.
The code ent... | Using Python's FTP library to retrieve files | this is my first post on here so I'm happy to be a part of the community. I have a fairly mundane question to ask, but it's been a fairly annoying problem so I'm hoping to find answers.
So I'm trying to use Python's FTPLIB module to retrieve a binary file.
The code entered directly into the interpreter looked like thi... | [
"It looks like you are logging-in anonymously (no username/password specified in ftp.login()) thus you get permission error. Try logging-in with\nftp.login(user='foo', passwd='bar')\n\ninstead.\nEdit: here is a short example of ftplib usage (simplistic, without error handling):\n#!/usr/bin/env python\n\nfrom ftplib... | [
8,
1,
0
] | [] | [] | [
"ftp",
"python",
"sockets"
] | stackoverflow_0004355446_ftp_python_sockets.txt |
Q:
get_absolute_url returns an empty string/object has no attribute
http://pastebin.com/H7n1Juv0
http://pastebin.com/hJvcAdBG # full model, if needed..
How can I fix this ?
A:
Your get_absolute_url method must be present directly in your Model class (is nested a level deeper than necessary, thus being part of you... | get_absolute_url returns an empty string/object has no attribute | http://pastebin.com/H7n1Juv0
http://pastebin.com/hJvcAdBG # full model, if needed..
How can I fix this ?
| [
"Your get_absolute_url method must be present directly in your Model class (is nested a level deeper than necessary, thus being part of your save method).\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004355533_django_django_models_python.txt |
Q:
Cross platform way to read Excel files in Python?
I have some (Excel 2000) workbooks. I want to extract the data in each worksheet to a separate file.
I am running on Linux.
Is there a library I can use to access (read) XLS files on Linux from Python?
A:
http://www.lexicon.net/sjmachin/xlrd.htm might work for yo... | Cross platform way to read Excel files in Python? | I have some (Excel 2000) workbooks. I want to extract the data in each worksheet to a separate file.
I am running on Linux.
Is there a library I can use to access (read) XLS files on Linux from Python?
| [
"http://www.lexicon.net/sjmachin/xlrd.htm might work for you.\n",
"Get xlrd from PyPI. Also go to the python-excel website to find out about (a) a tutorial (b) a discussion group (c) xlwt and xlutils.\n[Dis]claimer: I'm the author & maintainer of xlrd, and maintainer of xlwt (which is a fork of pyExcelerator with... | [
7,
3,
0
] | [
"I've been using pyexcelerator for this purpose in the past with good results.\n"
] | [
-1
] | [
"excel",
"python"
] | stackoverflow_0004355435_excel_python.txt |
Q:
Django ORM: Organizing massive amounts of data, the right way
I have a Django app that uses django-piston to send out XML feeds to internal clients. Generally, these work pretty well but we have some XML feeds that currently run over 15 minutes long. This causes timeouts, and the feeds become unreliable.
I'm tryin... | Django ORM: Organizing massive amounts of data, the right way | I have a Django app that uses django-piston to send out XML feeds to internal clients. Generally, these work pretty well but we have some XML feeds that currently run over 15 minutes long. This causes timeouts, and the feeds become unreliable.
I'm trying to ponder ways that I can improve this setup. If it requires some... | [
"The problem in the piece of code you posted is that Django doesn't include objects that are connected through a reverse relationship automatically, so you have to make a query for each object. There's a nice way around this, as Daniel Roseman points out in his blog!\nIf this doesn't solve your problem well, you co... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004260851_django_python.txt |
Q:
How to create a dictionary from a line of text?
I have a generated file with thousands of lines like the following:
CODE,XXX,DATE,20101201,TIME,070400,CONDITION_CODES,LTXT,PRICE,999.0000,QUANTITY,100,TSN,1510000001
Some lines have more fields and others have fewer, but all follow the same pattern of key-value pair... | How to create a dictionary from a line of text? | I have a generated file with thousands of lines like the following:
CODE,XXX,DATE,20101201,TIME,070400,CONDITION_CODES,LTXT,PRICE,999.0000,QUANTITY,100,TSN,1510000001
Some lines have more fields and others have fewer, but all follow the same pattern of key-value pairs and each line has a TSN field.
When doing some anal... | [
"In Python 2 you could use izip in the itertools module and the magic of generator objects to write your own function to simplify the creation of pairs of values for the dict records. I got the idea for pairwise() from a similarly named (although functionally different) recipe in the Python 2 itertools docs.\nTo us... | [
27,
6,
2,
1
] | [] | [] | [
"dictionary",
"parsing",
"python"
] | stackoverflow_0004356329_dictionary_parsing_python.txt |
Q:
do not understand closures question in python
def a(b=[]):
b.append(1)
return b
print a()
print a()
All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time.
Thanks for the help
A:
Default arguments are only evaluated once, when the function is defined. I... | do not understand closures question in python | def a(b=[]):
b.append(1)
return b
print a()
print a()
All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time.
Thanks for the help
| [
"Default arguments are only evaluated once, when the function is defined. It retains the same object from one invocation to the next, which means that the same list keeps getting appended to. Use a default value of None and check for that instead if you want to get around this.\n",
"Nothing to do with closures, a... | [
10,
9,
3,
1
] | [] | [] | [
"closures",
"parameter_passing",
"python"
] | stackoverflow_0004356048_closures_parameter_passing_python.txt |
Q:
Python multiprocessing: no output with while-loop in worker function
I'm exploring the Python multiprocessing module and don't understand why the following code does not print anything at all. Without the while-loop the program prints Worker_1 as expected.
import multiprocessing, time
def worker1():
print 'Wo... | Python multiprocessing: no output with while-loop in worker function | I'm exploring the Python multiprocessing module and don't understand why the following code does not print anything at all. Without the while-loop the program prints Worker_1 as expected.
import multiprocessing, time
def worker1():
print 'Worker_1'
while 1:
print 'Worker_1'
time.sleep(3)
re... | [
"On my system (Python 2.6&2.7 on Linux), this works as expected. Which platform are you using? On some platforms(Windows), fork hast to be emulated by creating a totally new process and setting it up. I suspect some stdout is not transferred to the child process. Try:\n\nThe threading module. It's sufficient if you... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004355878_python.txt |
Q:
How do I get the email address of the person who clicked the link in the email?
I am working with Google App Engine python version. The app sends an
email to the user with a link to a page to upload an image as an
avatar. It would be nice to have the email so that I can associate the
avatar with that email. How... | How do I get the email address of the person who clicked the link in the email? | I am working with Google App Engine python version. The app sends an
email to the user with a link to a page to upload an image as an
avatar. It would be nice to have the email so that I can associate the
avatar with that email. How can I get the email of the person who just clicked the link? Thank you.
| [
"Put a hash in the URL that uniquely identifies the address you sent it to.\n"
] | [
9
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0004356776_email_google_app_engine_python.txt |
Q:
How do I generate a temporary token for someone to post to my S3 account?
http://boto.s3.amazonaws.com/s3_tut.html#setting-getting-the-access-control-list-for-buckets-and-keys
I'm using boto.
My friend says it's possible to just generate a temporary (expires in 5 min?) token so his iphone client can post to my S3.... | How do I generate a temporary token for someone to post to my S3 account? | http://boto.s3.amazonaws.com/s3_tut.html#setting-getting-the-access-control-list-for-buckets-and-keys
I'm using boto.
My friend says it's possible to just generate a temporary (expires in 5 min?) token so his iphone client can post to my S3.
How can I do that with boto? I'm reading the documentation and don't quite ge... | [
"Solved.\nI used boto.key's generate_url.\n"
] | [
2
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"boto",
"python"
] | stackoverflow_0004356643_amazon_s3_amazon_web_services_boto_python.txt |
Q:
How often are builtin exceptions dealt with in comparison to user defined ones?
I'm doing a bit of research for my final year project. It's mostly about creating a more convenient way of dealing with Exceptions thrown in programs. It does this by creating a custom handler for each type of Exception. I was wonderin... | How often are builtin exceptions dealt with in comparison to user defined ones? | I'm doing a bit of research for my final year project. It's mostly about creating a more convenient way of dealing with Exceptions thrown in programs. It does this by creating a custom handler for each type of Exception. I was wondering how often are builtin/standard library Exceptions are dealt with in comparison to E... | [
"Regardless of what you're trying to do with the answer, I'll answer your specific question:\n\nhow often are builtin/standard library\n Exceptions are dealt with in\n comparison to Exception by you/3rd\n party software?\n\nIt depends on the domain. Some areas lend themselves to defining specific exceptions (e.g... | [
1
] | [] | [] | [
"exception",
"exception_handling",
"python",
"testing"
] | stackoverflow_0004356644_exception_exception_handling_python_testing.txt |
Q:
Python PyMT script crashing on open
I am attempting to learn the PyMT library and am trying to implement a simple program that i found on the web. however every time i open the script in PyMT it crashes as soon as it opens is there any thing that is incorrect in my code that would be cause it to be crashing?
from ... | Python PyMT script crashing on open | I am attempting to learn the PyMT library and am trying to implement a simple program that i found on the web. however every time i open the script in PyMT it crashes as soon as it opens is there any thing that is incorrect in my code that would be cause it to be crashing?
from pymt import *
class Tracer(MTWidget):
d... | [
"SO apparently if you are importing the .py file which is what PyMT does you can't create the ui....does anyone know how i would go about setting up a UI then?\n",
"I've installed pymt in my mac, and I couldn't run the examples using python command.\nI've foolwed the instructions on README, and ran the examples u... | [
0,
0
] | [] | [] | [
"crash",
"python"
] | stackoverflow_0004356827_crash_python.txt |
Q:
Python zipfile threading for use with progress bar
I find myself coming to SO more and more lately. While trying to learn Python (by jumping right in and trying to port an application from C#), I've come across something that I had never heard of before: Threading. When I thought I had a basic understanding down, ... | Python zipfile threading for use with progress bar | I find myself coming to SO more and more lately. While trying to learn Python (by jumping right in and trying to port an application from C#), I've come across something that I had never heard of before: Threading. When I thought I had a basic understanding down, I tried converting the portion of the program that zips ... | [
"I'd guess the file_count is wrong and the consumer waits forever for another object to .get. Change the line to current = self.sharedObject.get(timeout=5) and if thats the case it should throw an error at the end.\nAlso, yes there are many issues with your code -- for example when you use GTK you don't want your o... | [
0
] | [] | [] | [
"multithreading",
"progress_bar",
"python"
] | stackoverflow_0004356994_multithreading_progress_bar_python.txt |
Q:
Does python's sys.stdin.read() block?
I'm adapting this Django management command for my own purposes. The script is a simple while-loop daemon that reads from sys.stdin (line 152, in command.handle()) according to a protocol and writes results to sys.stdout.
I would expect sys.stdin.read() to block until it recei... | Does python's sys.stdin.read() block? | I'm adapting this Django management command for my own purposes. The script is a simple while-loop daemon that reads from sys.stdin (line 152, in command.handle()) according to a protocol and writes results to sys.stdout.
I would expect sys.stdin.read() to block until it receives something, but I find that when I run t... | [
"By default, sys.stdin.read() and sys.stdin.read(n) are blocking calls. I would assume the consumption of 100% CPU is actually attributable to streaming data into your script or some other behavior not cited here.\nUpon looking at the help documentation for sys.stdin.read, I noticed this:\n\nread(...)\nread([size])... | [
2,
1,
0
] | [] | [] | [
"django",
"python",
"stdin"
] | stackoverflow_0004356989_django_python_stdin.txt |
Q:
Write DWORD Value with Python's _winreg?
I'm working on a project that requires me to write a DWORD value to the registry. I know how to write other values, but I'm not sure how to write this value.
I need it to be set to 1. How is this done using _winreg with Python?
A:
Use SetValueEx() to set the value and th... | Write DWORD Value with Python's _winreg? | I'm working on a project that requires me to write a DWORD value to the registry. I know how to write other values, but I'm not sure how to write this value.
I need it to be set to 1. How is this done using _winreg with Python?
| [
"Use SetValueEx() to set the value and the type, types are listed here: http://docs.python.org/library/_winreg.html#value-types\nYou probably want _winreg.REG_DWORD\n"
] | [
1
] | [] | [] | [
"python",
"registry",
"windows",
"winreg"
] | stackoverflow_0004357151_python_registry_windows_winreg.txt |
Q:
Accessing a PHP-set memcache key from Python
I'm storing a value in memcached using PHP's Memcache extension and trying to retrieve it in a daemon written in Python sitting behind my webapp. But, it keeps returning None or throwing "local variable 'val' referenced before assignment".
I'm sure I'm looking for the ... | Accessing a PHP-set memcache key from Python | I'm storing a value in memcached using PHP's Memcache extension and trying to retrieve it in a daemon written in Python sitting behind my webapp. But, it keeps returning None or throwing "local variable 'val' referenced before assignment".
I'm sure I'm looking for the same key, and there's only one mc server available... | [
"By default, the PHP client stores keys in PHP's serialized format (which Python won't understand by default). If the Python client does something similar (using its own serialization format), that'd be your problem.\nYou can always use telnet/netcat to see what exactly is getting stored.\n",
"You could serialis... | [
4,
1
] | [] | [] | [
"memcached",
"php",
"python"
] | stackoverflow_0001046847_memcached_php_python.txt |
Q:
With the rise of NoSQL, Is it more common these days to have a webapp without any model?
With the rise of NoSQL, is it more common these days to have a webapp without any model and process everything in the controller? Is this a bad pattern in web development? Why should we abstract our database related function i... | With the rise of NoSQL, Is it more common these days to have a webapp without any model? | With the rise of NoSQL, is it more common these days to have a webapp without any model and process everything in the controller? Is this a bad pattern in web development? Why should we abstract our database related function in a model when it is easy enough to fetch the data in nosql?
Note
I am not asking whether RDBM... | [
"I don't think \"NoSQL\" has anything to do with \"no model\".\nFor one, MVC originated in the Smalltalk world for desktop applications, long before the current web server architecture (or even the web itself) existed. Most apps I've written have used MVC (including the M), even those that didn't use a DBMS (R or ... | [
4,
0,
0
] | [] | [] | [
"mysql",
"nosql",
"python",
"ruby_on_rails"
] | stackoverflow_0004355909_mysql_nosql_python_ruby_on_rails.txt |
Q:
does django has a method like 'render_template' in gae (google app engine)
This is my gae code:
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_values={}):
values={
}
template_values.update(values)
path = os.path.join(os.path.dirname... | does django has a method like 'render_template' in gae (google app engine) | This is my gae code:
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_values={}):
values={
}
template_values.update(values)
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.out.write(template.rend... | [
"Yes, it's called render_to_response, and is explained here:\nhttp://docs.djangoproject.com/en/dev/topics/http/shortcuts/\n"
] | [
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004357358_django_google_app_engine_python.txt |
Q:
installing django on windows
I am having a bit of a time installing django on my local machine due to the fact that my local machine is windows. One thing I am having issues with is the includes
#!/usr/bin/env python
Every file has this inlclude. I set python in my global varibles so I can call on it like
python... | installing django on windows | I am having a bit of a time installing django on my local machine due to the fact that my local machine is windows. One thing I am having issues with is the includes
#!/usr/bin/env python
Every file has this inlclude. I set python in my global varibles so I can call on it like
python
or I can include it like
#!pyth... | [
"You just need to set PATH environment variable (add path to python) and leave django files as them are.\n"
] | [
2
] | [] | [] | [
"apache",
"django",
"python",
"unix",
"windows"
] | stackoverflow_0004357393_apache_django_python_unix_windows.txt |
Q:
New to web development. ASP.NET or Django?
Hello I am interested in hearing objective responses in what should a beginner dedicate his or her time into:
ASP.NET, Visual Studio, C#, IIS, Team Foundation Server?
or
Python, Django, PyCharm?
These are just some criteria that I am interested in:
Easy to start out wit... | New to web development. ASP.NET or Django? | Hello I am interested in hearing objective responses in what should a beginner dedicate his or her time into:
ASP.NET, Visual Studio, C#, IIS, Team Foundation Server?
or
Python, Django, PyCharm?
These are just some criteria that I am interested in:
Easy to start out with.
Good documentation.
Highly-scalable.
Big Care... | [
"C# or java will pay the bills, python will be way more fun\n",
"This is a big question, I'll give only several points according to your interests:\n\nIn general, Django is easier to start than ASP.NET. Simplicity is one of rules in Python's Zen. Also Django explicitly shows you all control flow, so you can under... | [
16,
9,
6
] | [] | [] | [
"asp.net",
"c#",
"django",
"python"
] | stackoverflow_0004357176_asp.net_c#_django_python.txt |
Q:
python ............. delete
Possible Duplicate:
Python delete in a string
I have the following list which has 3 elements:
YELLOW,SMALL,STRETCH,ADULT,T
YELLOW,SMALL,STRETCH,ADULT,T
YELLOW,SMALL,STRETCH,CHILD,F
I would like to remove everything after the last comma.. Note that I could have more than one character ... | python ............. delete |
Possible Duplicate:
Python delete in a string
I have the following list which has 3 elements:
YELLOW,SMALL,STRETCH,ADULT,T
YELLOW,SMALL,STRETCH,ADULT,T
YELLOW,SMALL,STRETCH,CHILD,F
I would like to remove everything after the last comma.. Note that I could have more than one character after the last comma. How can I ... | [
"If you name your string s it would be:\ns = s[:s.rfind(\",\")+ 1] \n\nremove the one if don't want the comma at the end.\n",
"If you refer to string elements, you can utilize\nstr.rsplit() to separate each string, setting maxsplit to 1.\n\nstr.rsplit([sep[, maxsplit]])\nReturn a list of the words in the string, ... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004357577_python.txt |
Q:
Python Global Variable: sharing between function class then function
I'm trying to get the following global variable storage_i to be accessible to the lvl1 function, I have been able to pass it to other functions inside of the class birdofprey but I can't get it outside of that framework. I have looked around at u... | Python Global Variable: sharing between function class then function | I'm trying to get the following global variable storage_i to be accessible to the lvl1 function, I have been able to pass it to other functions inside of the class birdofprey but I can't get it outside of that framework. I have looked around at using global variables between functions, etc, and I have also seen global ... | [
"Replace this:\nglobal storage_i\nstorage_i = i \n\nWith this:\nbirdofprey.storage_i = i\n\nYou also have a typo at line 75:\nstorage_ii = stroage_i + storage_ii\n\n(stroage_i was intended to be storage_i)\nThis line should actually be:\nstorage_ii = birdofprey.storage_i + storage_ii\n\nEDIT: Also, without having ... | [
1,
0
] | [] | [] | [
"class",
"function",
"global_variables",
"python"
] | stackoverflow_0004357611_class_function_global_variables_python.txt |
Q:
Python delete in a string
I have these 3 strings:
YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs
YELLOW,SMALL,STRETCH,ADULT,Tdsfs
YELLOW,SMALL,STRETCH,ADULT,TD
I would like to remove everything after the last , including the comma. So i want to remove these parts ,T21fdsfdsfs, ,Tdsfs and TD. How could i do that in P... | Python delete in a string | I have these 3 strings:
YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs
YELLOW,SMALL,STRETCH,ADULT,Tdsfs
YELLOW,SMALL,STRETCH,ADULT,TD
I would like to remove everything after the last , including the comma. So i want to remove these parts ,T21fdsfdsfs, ,Tdsfs and TD. How could i do that in Python?
| [
"You can't. Create a new string with the pieces you want to keep.\n','.join(s.split(',')[:4])\n\n",
"s.rsplit(',', 1)[0]\n\nAnyway, I suggest having a look at Ignacio Vazquez-Abrams's answer too, it might make more sense for your problem.\n",
"According to The Zen of Python:\n\nThere should be one-- and prefera... | [
6,
5,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004357499_python.txt |
Q:
In Django, how do I put a form error into my views.py?
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError("Please write more in Title.")
return title
In my models.py, this is usually how I set an error form my title.
Howeve... | In Django, how do I put a form error into my views.py? | def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError("Please write more in Title.")
return title
In my models.py, this is usually how I set an error form my title.
However, what if I want to do it in views.py? I want to set an err... | [
"Form errors are stored in a dictionary (ErrorDict from django.forms.util ) that maps field name to ErrorList class. Look at _clean_fields method - you would need to call your form clean() method, then delete appropriate field from cleaned_data attribute and do something like this:\nyour_form._errors[ \"your_field\... | [
1
] | [] | [] | [
"django",
"forms",
"html",
"python"
] | stackoverflow_0004357704_django_forms_html_python.txt |
Q:
python reverse tokens in a string
I have the following string:
apple.orange.red.green.yellow
How can i reverse it to get the following:
yellow.green.red.orange.apple
A:
I like this (more readable?) one:
>> s = "yellow.green.red.orange.apple"
>> '.'.join(reversed(s.split('.')))
'apple.orange.red.green.yellow'
A... | python reverse tokens in a string | I have the following string:
apple.orange.red.green.yellow
How can i reverse it to get the following:
yellow.green.red.orange.apple
| [
"I like this (more readable?) one:\n>> s = \"yellow.green.red.orange.apple\"\n>> '.'.join(reversed(s.split('.')))\n'apple.orange.red.green.yellow'\n\n",
"'.'.join(s.split('.')[::-1])\n\n"
] | [
7,
6
] | [] | [] | [
"python"
] | stackoverflow_0004357787_python.txt |
Q:
In Django, how do I print out only the error, but not the key?
{{ docform.errors }}
__all__
Please type in the location of this submission.
title
Please write more in Title.
When I pass a form to the template and do the above..it prints out everything.
But I don't want the all or "title".
I just want the error.
... | In Django, how do I print out only the error, but not the key? | {{ docform.errors }}
__all__
Please type in the location of this submission.
title
Please write more in Title.
When I pass a form to the template and do the above..it prints out everything.
But I don't want the all or "title".
I just want the error.
| [
"solved.\n {% for f in docform %}\n {{ f.errors }}\n {% endfor %}\n {{ docform.non_field_errors }}\n\n"
] | [
1
] | [] | [] | [
"css",
"django",
"html",
"python"
] | stackoverflow_0004357621_css_django_html_python.txt |
Q:
appending a string to another string
I have 2 lists :
list1 contains "T" "F" "T" "T"
list2 contains "a" "b" "c" "d"
I want to create a third list such that I append element1 in list1 to element1 in list2.
So list3 would be the following: "Ta" "Fb" "Tc" "Td"
How can i do that?
A:
Use zip: [x + y for x, y in zip(l... | appending a string to another string | I have 2 lists :
list1 contains "T" "F" "T" "T"
list2 contains "a" "b" "c" "d"
I want to create a third list such that I append element1 in list1 to element1 in list2.
So list3 would be the following: "Ta" "Fb" "Tc" "Td"
How can i do that?
| [
"Use zip: [x + y for x, y in zip(list1, list2)].\n",
"zip, as others have suggested, is good. izip, I would suggest, is better for longer lists.\n>>> from itertools import izip\n>>> list3 = [x+y for x,y in izip(list1, list2)]\n>>> list3\n['Ta', 'Fb', 'Tc', 'Td']\n\nSee also the documentation on list comprehension... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004357841_python.txt |
Q:
average of the list in Python
I have a problem: i need to find an average of the list using this scheme:
First of all, we find an average of two elements, three elements..... len(list) elements and form a new list using averages. The use .pop() and find all averages again. Function should stop when len(list) == 2.... | average of the list in Python | I have a problem: i need to find an average of the list using this scheme:
First of all, we find an average of two elements, three elements..... len(list) elements and form a new list using averages. The use .pop() and find all averages again. Function should stop when len(list) == 2. Recursion should be used.
Example:... | [
"Accept the list as the function argument. If the list has one item, return that. Create two iterators from the list. Pop one item off one of the lists, zip them together, then find the averages of the zip results. Recurse.\n",
"In short, you're finding the \"running average\" from a list of numbers.\nUsing recur... | [
3,
2,
0,
0
] | [] | [] | [
"average",
"list",
"python"
] | stackoverflow_0004357957_average_list_python.txt |
Q:
Platform-independent text-to-speech Python library to run on Windows, Linux and Mac?
Does anyone know if there is a Python library for text-to-speech that works on Windows, Mac and Linux?
A:
pyttsx.
| Platform-independent text-to-speech Python library to run on Windows, Linux and Mac? | Does anyone know if there is a Python library for text-to-speech that works on Windows, Mac and Linux?
| [
"pyttsx.\n"
] | [
4
] | [] | [] | [
"linux",
"macos",
"python",
"text_to_speech",
"windows"
] | stackoverflow_0004358165_linux_macos_python_text_to_speech_windows.txt |
Q:
What are the implications of calling NumPy's C API functions from multiple threads?
This is risky business, and I understand the Global Interpreter Lock to be a formidable foe of parallelism. However, if I'm using NumPy's C API (specifically the PyArray_DATA macro on a NumPy array), are there potential consequence... | What are the implications of calling NumPy's C API functions from multiple threads? | This is risky business, and I understand the Global Interpreter Lock to be a formidable foe of parallelism. However, if I'm using NumPy's C API (specifically the PyArray_DATA macro on a NumPy array), are there potential consequences to invoking it from multiple concurrent threads?
Note that I will still own the GIL and... | [
"Answering my own question here, but after poking into the source code for NumPy 1.3.0, I believe the answer is: Yes, PyArray_DATA is thread-safe.\n\nPyArray_DATA is defined in\nndarrayobject.h:\n#define PyArray_DATA(obj) ((void *)(((PyArrayObject *)(obj))->data))\n\nThe PyArrayObject struct type is\ndefined in the... | [
7
] | [] | [] | [
"gil",
"numpy",
"python",
"python_c_api"
] | stackoverflow_0004358320_gil_numpy_python_python_c_api.txt |
Q:
How does Django handle escaping when I use a TinyMCE editor?
How do I display only bolds, italics, and all the other non-security issue HTML on the page?
A:
Sanitizing HTML is a pretty hard problem to get right. Spammers and other nasty people come up with new ways to smuggle HTML through sanitation all the tim... | How does Django handle escaping when I use a TinyMCE editor? | How do I display only bolds, italics, and all the other non-security issue HTML on the page?
| [
"Sanitizing HTML is a pretty hard problem to get right. Spammers and other nasty people come up with new ways to smuggle HTML through sanitation all the time. The safest option is to define a white list of harmless tags and rigorously filter out all other tags with a true HTML parser (not with regular expressions).... | [
2,
2,
1
] | [] | [] | [
"css",
"django",
"html",
"python",
"templates"
] | stackoverflow_0004358423_css_django_html_python_templates.txt |
Q:
In Django, how do I make sure that my forms keep its initial value after being submitted but returned to the template due to an error?
Let's say someone submits a form.
It doesn't pass is_valid(), and I return them back to the template.
How do I display the form fields again, without having the person retype their... | In Django, how do I make sure that my forms keep its initial value after being submitted but returned to the template due to an error? | Let's say someone submits a form.
It doesn't pass is_valid(), and I return them back to the template.
How do I display the form fields again, without having the person retype their stuff?
I prefer not to use the { initial: } option.
| [
"You could implement your view like so:\ndef showForm(request):\n if request.method == \"POST\":\n form = MyForm(request.POST)\n if form.is_valid():\n # do stuff on success, like redirection\n else:\n form = MyForm()\n\n return render_to_response(...,\n ... | [
3
] | [] | [] | [
"django",
"forms",
"python",
"templates"
] | stackoverflow_0004358001_django_forms_python_templates.txt |
Q:
Renaming multiple files in python
I wanted to know what is the easiest way to rename multiple files using re module in python if at all it is possible.
In my directory their are 25 files all with the file names in the format ' A unique name followed by 20 same characters.mkv '
What I wanted was to delete all the ... | Renaming multiple files in python | I wanted to know what is the easiest way to rename multiple files using re module in python if at all it is possible.
In my directory their are 25 files all with the file names in the format ' A unique name followed by 20 same characters.mkv '
What I wanted was to delete all the 20 characters.
How can I do this using ... | [
"To get the new name:\n>>> re.sub(r'.{20}(.mkv)', r'\\1', 'unique12345678901234567890.mkv')\n'unique.mkv'\n\nOr without regex:\n>>> 'unique12345678901234567890.mkv'[:-24] + '.mkv'\n'unique.mkv'\n\nTo rename the file use os.rename(old, new): http://docs.python.org/library/os.html#os.rename\nTo get a list of the file... | [
6,
0,
0,
0
] | [
"You need to use glob and os.rename. The rest if for you to figure it out!\nAnd yes, this is entirely possible and easy to do in Python. \n"
] | [
-1
] | [
"python"
] | stackoverflow_0004358701_python.txt |
Q:
Calling a subprocess without having the system console open
Im trying to start a wxPython app that (I have converted to an exe with py2exe) from a process that is running in the background.
The problem is that when the gui app opens, so does a console window (c:\windows\system\cmd.exe)
I had a look at this quest... | Calling a subprocess without having the system console open | Im trying to start a wxPython app that (I have converted to an exe with py2exe) from a process that is running in the background.
The problem is that when the gui app opens, so does a console window (c:\windows\system\cmd.exe)
I had a look at this question where Alex Martelli suggests setting the creationflags parama... | [
"I figured out what I was doing wrong after reading the documentation for subprocess.Popen\nThe first string in the args parameter should be the name of the executable. I didn't include the name of the executable as I thought that was taken care of with the executable paramater.\n"
] | [
3
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004356365_python_subprocess.txt |
Q:
how to: convert dictionary to strings in Python?
Possible Duplicate:
Creating or assigning variables from a dictionary in Python
Hello
we have dictionary like this:
data = {'raw':'lores ipsum', 'code': 500}
how to convert this dict to strings? result must be like this:
print raw
print code
#output is
# lores ... | how to: convert dictionary to strings in Python? |
Possible Duplicate:
Creating or assigning variables from a dictionary in Python
Hello
we have dictionary like this:
data = {'raw':'lores ipsum', 'code': 500}
how to convert this dict to strings? result must be like this:
print raw
print code
#output is
# lores ipsum
# 500
EDIT:
OK, so what I want is to have raw... | [
"This is a pretty bad idea - using dicts as intended ends up with a much less confusing solution.\nA quick hack dirty way of making the key=value pairs into non-dict string variables is as follows:\nfor key in data:\n exec(\"{0} = '{1}'\".format(key,data[key]))\n\nThis is fragile and breaks with complex data types... | [
7,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004357470_python.txt |
Q:
Getting all possible value combinations
For an automatic test thing, I have a class with ~15 parameters. I want to automatically generate instances of the class for every possible value combination. For instance, if the class was defined like so:
class meep():
def __init__(self):
self.par1 = 0 # can be... | Getting all possible value combinations | For an automatic test thing, I have a class with ~15 parameters. I want to automatically generate instances of the class for every possible value combination. For instance, if the class was defined like so:
class meep():
def __init__(self):
self.par1 = 0 # can be in range {0-3}
self.par2 = 1 # can b... | [
"itertools.product()\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004359085_python.txt |
Q:
How can I calculate optimal column widths?
I have a small set of column data values that I want to display in a variable-width display. One column has a small range of plausible sizes (say, 8-10 characters), one displays a UUID (always 36 chars), and the others are variable-length identifiers.
I want to maximize t... | How can I calculate optimal column widths? | I have a small set of column data values that I want to display in a variable-width display. One column has a small range of plausible sizes (say, 8-10 characters), one displays a UUID (always 36 chars), and the others are variable-length identifiers.
I want to maximize the amount of data I can display, given that the ... | [
"def getMaxLen(xs):\n ys = map(lambda row: map(len, row), xs)\n return reduce(\n lambda row, mx: map(max, zip(row,mx)),\n ys)\n\ndef formatElem((e, m)):\n return e[0:m] + \" \"*(m - len(e))\n\n# reduceW is some heuristic that will try to reduce\n# width of some columns to fit table on a scree... | [
1
] | [] | [] | [
"algorithm",
"layout",
"ncurses",
"python"
] | stackoverflow_0004357275_algorithm_layout_ncurses_python.txt |
Q:
serializing JSON files with newlines in Python
I am using json and jsonpickle sometimes to serialize objects to files, using the following function:
def json_serialize(obj, filename, use_jsonpickle=True):
f = open(filename, 'w')
if use_jsonpickle:
import jsonpickle
json_obj = jsonpickle.encode(obj)... | serializing JSON files with newlines in Python | I am using json and jsonpickle sometimes to serialize objects to files, using the following function:
def json_serialize(obj, filename, use_jsonpickle=True):
f = open(filename, 'w')
if use_jsonpickle:
import jsonpickle
json_obj = jsonpickle.encode(obj)
f.write(json_obj)
else:
simplejson.dump... | [
"(simple)json.dump() has the indent argument. jsonpickle probably has something similar, or in the worst case you can decode it and encode it again.\n",
"Jsonpickle uses one of the json backends and so you can try this to your code:\njsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)\n\nUpdate... | [
5,
4
] | [] | [] | [
"json",
"jsonpickle",
"pickle",
"python",
"serialization"
] | stackoverflow_0002664818_json_jsonpickle_pickle_python_serialization.txt |
Q:
how can I replace the nth occurrences in a list of string without using the built in function
I'm kind of new in python and I have problem to write a script which take four element (ex str, Replacefrom, replaceto and n) find the characters and replace the nth occurrence.
Example:
>>> replaeceit("Mississippi", "s... | how can I replace the nth occurrences in a list of string without using the built in function | I'm kind of new in python and I have problem to write a script which take four element (ex str, Replacefrom, replaceto and n) find the characters and replace the nth occurrence.
Example:
>>> replaeceit("Mississippi", "s", "l", 2)
'Mislissippi'
>>> replaeceit("Mississippi", "s", "l", 0)
'Mississippi'
the n is 2 so th... | [
"Okay, maybe now I understood what you are looking for:\ndef replaceit(st, remove, put, pos):\nouts = \"\"\ncount = 0\nfor letter in st:\n if letter == remove:\n count += 1\n if count == pos:\n outs += put\n else:\n outs += letter\n else:\n outs += letter\nret... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004359128_python.txt |
Q:
Python3.1 - Open Opera
I have no idea why this won't work....I'm trying to open opera but it says cannot find runnable browser.
op = webbrowser.get('C:\\Program Files\\Opera\\opera.exe')
op.open_new_tab('http://www.stackoverflow.com')
op.open_new_tab('http://www.stackoverflow.com')
A:
The name parameter should ... | Python3.1 - Open Opera | I have no idea why this won't work....I'm trying to open opera but it says cannot find runnable browser.
op = webbrowser.get('C:\\Program Files\\Opera\\opera.exe')
op.open_new_tab('http://www.stackoverflow.com')
op.open_new_tab('http://www.stackoverflow.com')
| [
"The name parameter should just be 'opera':\nop = webbrowser.get('opera')\n\nMake sure you have installed Opera on your computer, and that the executable opera.exe is in the path.\n\n>>> import webbrowser\n>>> webbrowser.get('opera')\n<webbrowser.BackgroundBrowser object at 0x02095490>\n\nSee the table of allowed v... | [
2,
0,
0
] | [] | [] | [
"browser",
"python"
] | stackoverflow_0004359750_browser_python.txt |
Q:
How to reuse a widget tree from a glade file with GtkBuilder?
i want to populate a gtk.notebook on-the-fly. everytime a user opens a file, a new notebook-tab is generated. pretty straight forward. my problem is, that i use glade to build the ui and the notebook-tab should have a child widget tree (scrolledwindow->... | How to reuse a widget tree from a glade file with GtkBuilder? | i want to populate a gtk.notebook on-the-fly. everytime a user opens a file, a new notebook-tab is generated. pretty straight forward. my problem is, that i use glade to build the ui and the notebook-tab should have a child widget tree (scrolledwindow->viewport-> alignment->frame). in my glade-file, i have a template n... | [
"Do it this way with GtkBuilder:\nbuilder = gtk.Builder()\nbuilder.add_from_file(\"GUI.xml\")\nbuilder.connect_signals(self)\nself.window1 = builder.get_object(\"window1\")\nself.window1.show()\n\nedit:\nI was initially wrong, it seems that gtkbuilder does instantiate objects when it adds. So the ideal way to do th... | [
1
] | [] | [] | [
"glade",
"gtk",
"gtkbuilder",
"pygtk",
"python"
] | stackoverflow_0004359798_glade_gtk_gtkbuilder_pygtk_python.txt |
Q:
how can i separate from this list?
text = [('good', 'Title meta tag contains no errors.'), ('good', 'Title relevancy to page content is good.'), ('good', 'Description meta tag contains no errors.'), ('good', 'Description relevancy to page content is excellent.'), ('good', 'Keywords meta tag contains no errors.'), ... | how can i separate from this list? | text = [('good', 'Title meta tag contains no errors.'), ('good', 'Title relevancy to page content is good.'), ('good', 'Description meta tag contains no errors.'), ('good', 'Description relevancy to page content is excellent.'), ('good', 'Keywords meta tag contains no errors.'), ('good', 'Keyword relevancy to page cont... | [
"This should give you what you want:\nresult = [y for x in text for y in x]\n\nAnother alternative that you may find more readable is to use itertools.chain:\nfrom itertools import chain\nresult = list(chain(*text))\n\n",
"Take a look at this question, very nice solution:\n\nMaking a flat list out of list of list... | [
5,
1
] | [] | [] | [
"arraylist",
"list",
"python"
] | stackoverflow_0004359948_arraylist_list_python.txt |
Q:
Writing and image attachment to datastore as an avatar: Is it possible?
Has anyone worked with attachments in received emails? I was thinking, instead of the user uploading an image they can send it as an attachment that I can use to upload to datastore.
The documentation has sending attachments but I could not fi... | Writing and image attachment to datastore as an avatar: Is it possible? | Has anyone worked with attachments in received emails? I was thinking, instead of the user uploading an image they can send it as an attachment that I can use to upload to datastore.
The documentation has sending attachments but I could not find any documentation about receiving attachments. This page says:
attachment... | [
"This is a fragment from an incoming mail handler I use:\n bodies = message.bodies(content_type='text/html')\n allBodies = u\"\";\n for body in bodies:\n allBodies = allBodies + u\"\\n\" + unicode(goodDecode(body[1]), errors=\"ignore\")\n if not allBodies:\n bodies = message.bodies(content_type... | [
2,
1,
1
] | [] | [] | [
"email",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004357022_email_google_app_engine_google_cloud_datastore_python.txt |
Q:
Unable to install pip: Permission denied error
I am trying to install pip but currently unable to.
I navigate to the pip folder and
python setup.py install
Everything seems to go fine until the very end:
Extracting pip-0.8.2-py2.6.egg to /Library/Python/2.6/site-packages
Adding pip 0.8.2 to easy-install.pth file
... | Unable to install pip: Permission denied error | I am trying to install pip but currently unable to.
I navigate to the pip folder and
python setup.py install
Everything seems to go fine until the very end:
Extracting pip-0.8.2-py2.6.egg to /Library/Python/2.6/site-packages
Adding pip 0.8.2 to easy-install.pth file
Installing pip script to /usr/local/bin
error: /usr/... | [
"Looks like you're on an Linux/Unix box and you're not root ... which means you don't have permission to put things in /usr/local/bin (or a lot of other places).\nUpdate for comments:\nSince OS X is (under the hood) FreeBSD Unix, there is still the basic concept of 'root'. Your admin account is capable of doing roo... | [
17
] | [] | [] | [
"easy_install",
"egg",
"pypi",
"python"
] | stackoverflow_0004359870_easy_install_egg_pypi_python.txt |
Q:
Python win32com Error
I got the following traceback in my setup script:
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyc", line 1410, in __call__
File "Setup.py", line 233, in step6
File "Setup.py", line 203, in step7
File "Setup.py", line 143, in step8
File "Setup.py", ... | Python win32com Error | I got the following traceback in my setup script:
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyc", line 1410, in __call__
File "Setup.py", line 233, in step6
File "Setup.py", line 203, in step7
File "Setup.py", line 143, in step8
File "Setup.py", line 76, in step9
File "w... | [
"It means that COM could not instantiate the class with id {4FBE7FE9-4AD1-4D70-BB77-66963016FD09} (which probably is HNetCfg.FwMgr, the Windows Firewall scripting interface).\nI think you have be be an administrator to do that, so that might only be a permission problem.\nIn you have administration privileges and i... | [
0
] | [] | [] | [
"python",
"traceback",
"win32com"
] | stackoverflow_0004359913_python_traceback_win32com.txt |
Q:
circularly linked list in python
I am stuck implementing the add function of a circularly linked list in python. I have a head pointer that should be a reference to a node, but every time I add something to the list, head is always None. Here is the code I have so far:
class CircleList():
__slots__ = ('head',... | circularly linked list in python | I am stuck implementing the add function of a circularly linked list in python. I have a head pointer that should be a reference to a node, but every time I add something to the list, head is always None. Here is the code I have so far:
class CircleList():
__slots__ = ('head', 'size')
def __init__(self):
... | [
"You only assigning the new node to your local head variable in your add() method, not to the actual CircleList instance member.\nYou might want to do something like:\ndef add(self, element):\n head = self.head\n print(head)\n size = self.size\n if head is None:\n self.head = head = Node(element,... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004360050_python.txt |
Q:
python bluetooth discovery with pybluez
i am trying to run this script:
import PyOBEX
import bluetooth
print "performing inquiry..."
nearby_devices = bluetooth.discover_devices(lookup_names = True)
print "found %d devices" % len(nearby_devices)
for name, addr in nearby_devices:
print " %s - %s" % (addr, na... | python bluetooth discovery with pybluez | i am trying to run this script:
import PyOBEX
import bluetooth
print "performing inquiry..."
nearby_devices = bluetooth.discover_devices(lookup_names = True)
print "found %d devices" % len(nearby_devices)
for name, addr in nearby_devices:
print " %s - %s" % (addr, name)
however i am getting a not implemented e... | [
"The source code for init.py has\nelif sys.platform == \"darwin\":\n from osx import *\n\nAnd the source code for osx.py is\nfrom btcommon import *\n\nraise NotImplementedError\n\nThis is consistent with the web page that only mentions Linux and Windows implementations. You'll probably have to check with the de... | [
3
] | [] | [] | [
"bluetooth",
"python"
] | stackoverflow_0004359292_bluetooth_python.txt |
Q:
Why does `letter=="A" or "a"` always evaluate to True?
Please look at the code. I'm using a robot car to draw a letter and in this code, when I type b, it will still draw small case a.
import create
# Draw a:
def drawa():
#create robot
robot = create.Create(4)
#switch robot to full mode
robot.toFullMode()
f... | Why does `letter=="A" or "a"` always evaluate to True? | Please look at the code. I'm using a robot car to draw a letter and in this code, when I type b, it will still draw small case a.
import create
# Draw a:
def drawa():
#create robot
robot = create.Create(4)
#switch robot to full mode
robot.toFullMode()
for i in range(1280):
robot.go(20,30)
robot.stop()
robot.... | [
"It's because of your conditions. When you say...\nif letter == \"A\" or \"a\"\n\n...you are actually saying...\nif it's true that 'letter' equals 'A', or is true that 'a'\n\n... and \"a\", as a non-empty string, evaluates always to true. You are not asking anything from letter in the right-hand side of the or. Do ... | [
8,
1,
0,
0,
0,
0
] | [] | [] | [
"if_statement",
"or_operator",
"python",
"syntax"
] | stackoverflow_0004360066_if_statement_or_operator_python_syntax.txt |
Q:
Send value from python GUI to an external file
I need to have values from 2 sliders in a python GUI sent to an external file (just a text or csv file).Can anyone help?
Cheers
Alasdair
A:
Here's a quick example using wx.Python:
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, id = -1):
w... | Send value from python GUI to an external file | I need to have values from 2 sliders in a python GUI sent to an external file (just a text or csv file).Can anyone help?
Cheers
Alasdair
| [
"Here's a quick example using wx.Python:\nimport wx\n\nclass MyPanel(wx.Panel):\n def __init__(self, parent, id = -1):\n wx.Panel.__init__(self, parent, id)\n\n self.slider1 = wx.Slider(self, -1, 50, 0, 100, size=(300,25))\n self.slider2 = wx.Slider(self, -1, 50, 0, 100, size=(300,25))\n\n ... | [
2
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0004360313_python_user_interface.txt |
Q:
Framework design question
When committing data that has originally come from a webpage, sometimes data has to be converted to a data type or format which is suitable for the back-end database. For instance, a date in 'dd/mm/yyyy' format needs to be converted to a Python date-object or 'yyyy-mm-dd' in order to be ... | Framework design question | When committing data that has originally come from a webpage, sometimes data has to be converted to a data type or format which is suitable for the back-end database. For instance, a date in 'dd/mm/yyyy' format needs to be converted to a Python date-object or 'yyyy-mm-dd' in order to be stored in a SQLite date column ... | [
"I think it belongs in the validation. You want a date, but the web page inputs strings only, so the validator needs to check if the value van be converted to a date, and from that point on your application should process it like a date.\n",
"I could be wrong, but I think there is no definite answer to this quest... | [
2,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004360407_python_sqlite.txt |
Q:
take a char and print out from char to 'a' and reverse it should be recursive
this code should take a char as an argument and print out that char in alphabetically order to 'a' and reverse to char.
>>> characters('d')
d c b a b c d
this is what Ii wrote so far but it is not the correct output
def characters(char)... | take a char and print out from char to 'a' and reverse it should be recursive | this code should take a char as an argument and print out that char in alphabetically order to 'a' and reverse to char.
>>> characters('d')
d c b a b c d
this is what Ii wrote so far but it is not the correct output
def characters(char):
numb=ord(char)
while numb>ord('a'):
>> print chr(numb),
numb... | [
"Well, you're halfway there as it stands. Now you just have to figure out how to take numb back to your letter.\nIn order to make it go backwards in the alphabet, you're using numb=numb-1. So in order to make it go forward in the alphabet, what would be the opposite of that? Then you could put that in another loop ... | [
0,
0
] | [] | [] | [
"char",
"python",
"recursion"
] | stackoverflow_0004360459_char_python_recursion.txt |
Q:
Error in using Python/mechanize select_form()?
I am trying to scrap some data from a website.
The scripts I am trying to write, should get the content of the page:
http://www.atpworldtour.com/Rankings/Singles.aspx
Should simulate the user going trough every option for Additional Standings and the dates and simula... | Error in using Python/mechanize select_form()? | I am trying to scrap some data from a website.
The scripts I am trying to write, should get the content of the page:
http://www.atpworldtour.com/Rankings/Singles.aspx
Should simulate the user going trough every option for Additional Standings and the dates and simulate clicking on Go then after fetching the data shoul... | [
"I think you are using the library correctly, but the parser seems to be having trouble with that particular page. I'm using the library in the same way on another page (\"http://flashcarddb.com/login\") and it does not raise an error.\n",
"I just ran into this same problem. The page I was accessing passed W3C v... | [
1,
1,
0
] | [] | [] | [
"mechanize",
"python",
"web_scraping"
] | stackoverflow_0002067915_mechanize_python_web_scraping.txt |
Q:
My formencode.variabledecode is returning an empty list - Pylons
HTML:
<input type="text" name="blah-0" value="test" />
<input type="text" name="blah-1" value="another test" />
Controller:
class myvalidator(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
test = formencode.F... | My formencode.variabledecode is returning an empty list - Pylons | HTML:
<input type="text" name="blah-0" value="test" />
<input type="text" name="blah-1" value="another test" />
Controller:
class myvalidator(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
test = formencode.ForEach(formencode.validators.String())
def form_posted(self):
fo... | [
"Your example is incomplete but you must decode your variables before:\nfrom formencode import variabledecode\n\ndef form_posted(self):\n decoded = variabledecode.variable_decode(request.params)\n form_result = myvalidator().to_python(decoded)\n print form_result\n\nYou also should change that line if y... | [
1
] | [] | [] | [
"formencode",
"forms",
"pylons",
"python"
] | stackoverflow_0004351804_formencode_forms_pylons_python.txt |
Q:
admin only areas in django + app engine
i am using django-norel for deploying to app engine.what which one would be a better solution for admin only areas ?
1) using app.yaml to define admin only areas
2) writing a middleware for google userservice
update :
there is this entry
- url: /.*
script: djangoappen... | admin only areas in django + app engine | i am using django-norel for deploying to app engine.what which one would be a better solution for admin only areas ?
1) using app.yaml to define admin only areas
2) writing a middleware for google userservice
update :
there is this entry
- url: /.*
script: djangoappengine/main/main.py
in ap.yaml doesn't that me... | [
"Use app.yaml for admin areas because login: admin is an easy and clean solution.\nIf you want moderator functionality on public pages you can use users.is_current_user_admin().\nUpdate: You can't use login: admin to restrict access to some functions in one file. If you want to use it you have to create a separate ... | [
2,
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004358910_django_google_app_engine_python.txt |
Q:
Python Threading: Only two active threads, how do I get more?
So I have the following program:
https://github.com/eWizardII/homobabel/blob/master/Experimental/demo_async_falcon.py
However, when it's run I only get two active threads are running, how can I make it so that there are more threads running. I have trie... | Python Threading: Only two active threads, how do I get more? | So I have the following program:
https://github.com/eWizardII/homobabel/blob/master/Experimental/demo_async_falcon.py
However, when it's run I only get two active threads are running, how can I make it so that there are more threads running. I have tried doing stuff like urlv2 = birdofprey(ip2) where ip2 = str(host+1) ... | [
"line 75, urlv.join() blocks until the thread finishes. So you actually create one thread, wait until it's done and then start the next. The other thread is the main thread.\n",
"Active count=2 means that you have one of your designed thread (birdofprey), and the main thread. This is because you use lock, so the ... | [
1,
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004360636_multithreading_python.txt |
Q:
Authorization with htaccess
I'm using python and I have to login at some site, which asks for password. For asking it uses .htaccess like:
AuthType Basic
AuthName "Authorize please"
require valid-user
AuthUserFile "/home/*/admin/passwd"
So, when loading this page I'm getting browser's modal input window. How ca... | Authorization with htaccess | I'm using python and I have to login at some site, which asks for password. For asking it uses .htaccess like:
AuthType Basic
AuthName "Authorize please"
require valid-user
AuthUserFile "/home/*/admin/passwd"
So, when loading this page I'm getting browser's modal input window. How can I insert data with python scrip... | [
"You might want to look at these examples.\n"
] | [
3
] | [] | [] | [
"authentication",
"post",
"python",
"url"
] | stackoverflow_0004360672_authentication_post_python_url.txt |
Q:
A Simple Python Regular Expression Problem in Google App Engine
I am learning Google App Engine in Python.
Here is my problem:
I want the visitor to visit my website in the following format,
hxxp://www.example.com/wiki/A_Example_Title
The variable after /wiki/ only contains alphabets and underscore.
application ... | A Simple Python Regular Expression Problem in Google App Engine | I am learning Google App Engine in Python.
Here is my problem:
I want the visitor to visit my website in the following format,
hxxp://www.example.com/wiki/A_Example_Title
The variable after /wiki/ only contains alphabets and underscore.
application = webapp.WSGIApplication([
('/wiki/??????', wikipage),
What shou... | [
"try one of these:\nYour spec said 'alphabets and underscore' -- this one gets that and numbers as well:\nr'/wiki/(\\w+)'\n\n...if you really don't want numbers in there, use this:\nr'/wiki/([A-Za-z_]+)'\n\nThe characters captured by that regex will be passed as a parmeter to your wikipage get() handler.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python",
"regex"
] | stackoverflow_0004360972_google_app_engine_python_regex.txt |
Q:
Python ".write"
How can I "convert" this:
input=[(0.25 , 'x1'),(0.20 , 'x2'), ............................]
so that I can write in test.txt only this:
x1=0.25, x2=0.20, x3= ..................
f = open('test.txt', 'w')
f.write(input)
f.close()
I know for print, this work ok:
print ' '.join("%s=%s" % (y, x) for... | Python ".write" | How can I "convert" this:
input=[(0.25 , 'x1'),(0.20 , 'x2'), ............................]
so that I can write in test.txt only this:
x1=0.25, x2=0.20, x3= ..................
f = open('test.txt', 'w')
f.write(input)
f.close()
I know for print, this work ok:
print ' '.join("%s=%s" % (y, x) for x,y in input)
but I... | [
"Anything wrong with\nf.write(' '.join(\"%s=%s\" % (y, x) for x,y in input))\n\n?\nOr\nprint >>f, ' '.join(\"%s=%s\" % (y, x) for x,y in input)\n\nThere's a minor difference in that the former won't have a trailing newline character. Easily fixed though.\n",
"Try this:\ns = ', '.join(\"%s=%s\" % (y, x) for x,y in... | [
2,
1,
1,
1,
0,
0
] | [] | [] | [
"file",
"python",
"text_files"
] | stackoverflow_0004361021_file_python_text_files.txt |
Q:
Is there a way to debug Python code which runs on a `multiprocessing.Process`?
What I would like is to be able to step-debug code that runs in a separate process using the multiprocessing package.
I remember looking for a solution about a year ago and not finding one. I was told to just do a lot of logging, but of... | Is there a way to debug Python code which runs on a `multiprocessing.Process`? | What I would like is to be able to step-debug code that runs in a separate process using the multiprocessing package.
I remember looking for a solution about a year ago and not finding one. I was told to just do a lot of logging, but of course it is an inferior method. So maybe someone came up with a solution in the me... | [
"You could start the process You need to debug manually, without using the Process interface on this process.\n",
"You might find WingIDE useful. Its debugger is really nice, and it even supports debugging remote processes with some minimal instrumentation to the code being debugged. It's not free, but well wor... | [
1,
1,
0
] | [] | [] | [
"debugging",
"multiprocessing",
"python"
] | stackoverflow_0004298260_debugging_multiprocessing_python.txt |
Q:
Numpy time based vector operations where state of preceding elements matters - are for loops appropriate?
What do numpy arrays provide when performing time based calculations where state matters. In other words, where what has occurred in earlier or later in a sequence is important.
Consider the following time bas... | Numpy time based vector operations where state of preceding elements matters - are for loops appropriate? | What do numpy arrays provide when performing time based calculations where state matters. In other words, where what has occurred in earlier or later in a sequence is important.
Consider the following time based vectors,
TIME = np.array([0., 10., 20., 30., 40., 50., 60., 70., 80., 90.])
FLOW = np.array([100.,... | [
"While Joe Kington's answer is certainly correct (and quite flexible), it is rather more circuitous than need be. For someone trying to learn Numpy, I think a more direct route might be easier to understand.\nAs I noted under your question (and as Joe also noticed), there seems to be an inconsistency between your d... | [
4,
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004359829_numpy_python.txt |
Q:
Python: using subprocess to stream data without deadlocks?
I'm writing a little script for shuffling a lot of data around. It's something like this:
outproc = None
for input in input_files:
p = Popen('process_input "%s" | more_input_processing' %(input, ),
shell=True, stdout=PIPE)
for line in... | Python: using subprocess to stream data without deadlocks? | I'm writing a little script for shuffling a lot of data around. It's something like this:
outproc = None
for input in input_files:
p = Popen('process_input "%s" | more_input_processing' %(input, ),
shell=True, stdout=PIPE)
for line in p.stdout.xreadlines():
if linecount % 1000000 == 0:
... | [
"You're not using close on a pipe the subprocess actually reads, so it won't receive SIGPIPE or anything to cause it to exit. Just kill the process when you have enough data. Alternatively, pipe both input and output and use select to know when you should read or write.\n"
] | [
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004361399_python_subprocess.txt |
Q:
how to create a user interface that a user can signup and login using django
i love gae(google app engine),because it is easy to create a user interface for user login and signup,
but now , my boss want me to create a site use django ,
so the first is to create a site that someone can be login ,
which is the esai... | how to create a user interface that a user can signup and login using django | i love gae(google app engine),because it is easy to create a user interface for user login and signup,
but now , my boss want me to create a site use django ,
so the first is to create a site that someone can be login ,
which is the esaist way to create a user interface ?
thanks
| [
"User authentication in Django is fully documented online. The user interface itself is, AFAICT, your problem; I don't know if Django provides one out of the box.\n",
"Django auth also provide generic views for login/logout etc. You can use build-in templates or expand it.\nSee in documentation for generic views:... | [
1,
1
] | [] | [] | [
"authentication",
"django",
"python",
"user_interface"
] | stackoverflow_0004356234_authentication_django_python_user_interface.txt |
Q:
Python .write() change order
I have some problem:
f = open('OUTPUT.txt', 'w')
def function
if ........
......
f.write(XXX) #this must be in this loop #1.write
else:
....
....
....other code...
................
with open("INPUT.txt") as f_in:
for line in ... | Python .write() change order | I have some problem:
f = open('OUTPUT.txt', 'w')
def function
if ........
......
f.write(XXX) #this must be in this loop #1.write
else:
....
....
....other code...
................
with open("INPUT.txt") as f_in:
for line in f_in:
for char in line:
... | [
"What is preventing you from putting the character-frequency-counting loop before the f.write(XXX) loop?\n",
"You could use temp file to write to it first, then write 'input' data to OUTPUT.txt, then append temp file to output.\nIf the data isn't huge (ie. will fit in memory) you could use StringIO for that. For ... | [
1,
0
] | [] | [] | [
"python",
"text_files"
] | stackoverflow_0004361458_python_text_files.txt |
Q:
How can I ensure closing all connection in loadbalancer when something fails or hangs?
I'm trying to write a simple load-balancer. It works ok till one of servers (BalanceServer) doesn't close connection then...
Client (ReverseProxy) disconnects but the connection in with BalanceServer stays open.
I tried to add c... | How can I ensure closing all connection in loadbalancer when something fails or hangs? | I'm trying to write a simple load-balancer. It works ok till one of servers (BalanceServer) doesn't close connection then...
Client (ReverseProxy) disconnects but the connection in with BalanceServer stays open.
I tried to add callback (#3) to ReverseProxy.connectionLost to close the connection with one of the servers ... | [
"You may want to look at twisted.internet.protocols.portforward for an example of hooking up two connections and then disconnecting them. Or just use txloadbalancer and don't even write your own code.\nHowever, loseConnection will never forcibly terminate the connection if there is never any traffic going over it.... | [
1
] | [] | [] | [
"load_balancing",
"python",
"reverse_proxy",
"timeout",
"twisted"
] | stackoverflow_0001870251_load_balancing_python_reverse_proxy_timeout_twisted.txt |
Q:
using list to input data using psycoyg2 python (with missing data)
Want to get data with some missing values from cvs into postgresql. I am happy to insert using strings. I would like a fast was to do this using list or something similer. I also need to check for missing values and substitute as I get an error oth... | using list to input data using psycoyg2 python (with missing data) | Want to get data with some missing values from cvs into postgresql. I am happy to insert using strings. I would like a fast was to do this using list or something similer. I also need to check for missing values and substitute as I get an error other wise.
for w in csvReader:
if a ==0:
var = w
... | [
"Looking at the error message, it just looks like you are trying to insert a '.' just read from csv in your database in the field ORDER_ADM without putting it between quotes.\nAlso the three fileds DAY_ADM, MONTH_ADM, YEAR_ADM suggests that you probably should merge them into a date and put them in the same field o... | [
0
] | [] | [] | [
"psycopg2",
"python"
] | stackoverflow_0004361607_psycopg2_python.txt |
Q:
Calling class members from function Definition
Is there a way in Python to call class object from function definition ?
Let say I have class
class myClass():
def __init__(self, member1 = 0)
self.member1 = member1
and function definition
def myFunction(x):
var1 = ............
I would like ... | Calling class members from function Definition | Is there a way in Python to call class object from function definition ?
Let say I have class
class myClass():
def __init__(self, member1 = 0)
self.member1 = member1
and function definition
def myFunction(x):
var1 = ............
I would like to assign member1 to var1 in function definition.
T... | [
"Do you understand what classes are for?\nYou would like to assign member1 of which instance of the class to var1?\nIs x supposed to be an instance of myClass that you're passing to myFunction? Then it's simple: var1 = x.member1.\n",
"Sounds like you need member1 to be a static class variable. See Static class va... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004361815_python.txt |
Q:
Is it worth to ensure that non-callable Python classes do not get called?
If yes, can you suggest a better way than below? Please elaborate/justify.
class X:
...
if __name__ == '__main__':
# TODO: Should we bother doing this?
errorMessage = 'This class is not meant to have a main method. Do not execut... | Is it worth to ensure that non-callable Python classes do not get called? | If yes, can you suggest a better way than below? Please elaborate/justify.
class X:
...
if __name__ == '__main__':
# TODO: Should we bother doing this?
errorMessage = 'This class is not meant to have a main method. Do not execute directly.'
print(errorMessage)
raise Error(errorMessage)
| [
"A common pattern is to place unit tests for a Python module inside the module body. For example:\nif __name__ == \"__main__\":\n run_unit_tests()\n\nHowever, if you're not doing this, I wouldn't even bother adding any module body code. If executed as a script, a Python module with no body code will do nothing.\... | [
3,
3,
2,
1
] | [] | [] | [
"main_method",
"python"
] | stackoverflow_0004362059_main_method_python.txt |
Q:
query.values fails with Elixir
I have a problem with the Elixir declarative layer; I want to retrieve, for every instance of my model, the data of a particular column, like this:
File.query.values("column")
The thing is, it only works with filtered queries, with the simple query of the example it fails with this... | query.values fails with Elixir | I have a problem with the Elixir declarative layer; I want to retrieve, for every instance of my model, the data of a particular column, like this:
File.query.values("column")
The thing is, it only works with filtered queries, with the simple query of the example it fails with this error :
Could not locate a bind co... | [
"Use the form\nFile.query.values(Table.column)\n\nand it should work. It returns a generator, so wrap with list() to get a sequence. See this example interactive output:\n>>> User.query.values('display_name')\nTraceback (most recent call last):\n File \"<console>\", line 1, in ?\n[snip traceback]\nUnboundExecution... | [
2
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0004360141_python_python_elixir_sqlalchemy.txt |
Q:
linking two lists together with an iterator function in python
i have two lists, both with 128 items:
a= [0, 1, 2, 3, ...]
b= [6.4, 53.8, -5.2, 7.1, ...]
i have to run list b through two checks:
is b[n]>50.0
is b[n]<0
if check1 is true, than b[n]=b[n]-50, AND a[n]=a[n]+1
if check2 is true, than b[n]=b[n]+100, ... | linking two lists together with an iterator function in python | i have two lists, both with 128 items:
a= [0, 1, 2, 3, ...]
b= [6.4, 53.8, -5.2, 7.1, ...]
i have to run list b through two checks:
is b[n]>50.0
is b[n]<0
if check1 is true, than b[n]=b[n]-50, AND a[n]=a[n]+1
if check2 is true, than b[n]=b[n]+100, AND a[n]=a[n]-1
i can't figure out how to tie the two items in each ... | [
"Produce pairs of corresponding items from the two lists with zip and process each pair. You can use a generator comprehension to get all the processed pairs, and zip again to get lists back.\ndef process(a, b):\n if b > 50:\n a += 1\n b -= 50\n elif b < 0:\n a -= 1\n b += 100\n ... | [
4,
3
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0004362085_python_python_2.6.txt |
Q:
How to reference Sprite object property in one class from another?
I dont know how to reference the 'top' property of the Sprite object in Livewires in one class, from another class??
A:
Assuming that Sprite is the class you dealing with...
This is how you access an object attribute:
>>> a = Sprite()
>>> a.top
... | How to reference Sprite object property in one class from another? | I dont know how to reference the 'top' property of the Sprite object in Livewires in one class, from another class??
| [
"Assuming that Sprite is the class you dealing with...\nThis is how you access an object attribute:\n>>> a = Sprite()\n>>> a.top\n\nThis is how you access a class attribute:\n>>> Sprite.top\n\nIs this what you're looking for?\n"
] | [
0
] | [] | [] | [
"livewires",
"python"
] | stackoverflow_0004359539_livewires_python.txt |
Q:
Limiting response size with httplib2
Is it possible to limit the response size with httplib2? For instance if it sees an HTTP body over X bytes the connection will just close without consuming more bandwidth. Or perhaps only download the first X bytes of a file.
A:
Assuming that the server is sending the re... | Limiting response size with httplib2 | Is it possible to limit the response size with httplib2? For instance if it sees an HTTP body over X bytes the connection will just close without consuming more bandwidth. Or perhaps only download the first X bytes of a file.
| [
"Assuming that the server is sending the response body size in the Content-Length response header field, you can do it yourself.\nFirst, call Http.request(method=\"HEAD\") to retrieve only the headers and not the body. Then inspect the Content-Length field of the response to see if it is below your threshold. If it... | [
5
] | [] | [] | [
"http",
"python"
] | stackoverflow_0004362721_http_python.txt |
Q:
(English, Perl, Python, Ruby) comparison on a code fragment-by-fragment basis?
Looking for a code samples that present a code fragment in plain English, Perl, Python, and Ruby. Here's an example of a whole mini-solution present in that format, but I'd rather just have the code present in a fragment-by-fragment bas... | (English, Perl, Python, Ruby) comparison on a code fragment-by-fragment basis? | Looking for a code samples that present a code fragment in plain English, Perl, Python, and Ruby. Here's an example of a whole mini-solution present in that format, but I'd rather just have the code present in a fragment-by-fragment basis.
| [
"A good place to look would be Project Euler where (after solving the puzzles yourself) you get access to solutions by other people in all kinds of programming languages. Of course, sometimes there will be atrocious solutions, so you'd have to look at the answers carefully.\n",
"Rosetta Code currently has 449 tas... | [
2,
2
] | [] | [] | [
"comparison",
"perl",
"python",
"ruby"
] | stackoverflow_0004356309_comparison_perl_python_ruby.txt |
Q:
How to use django template dot notation inside a for loop
I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:
{% for dictkey in keys %}
<p> {{ mydict.dictkey }} </p>
{% endfor %}
(let's say 'keys' and 'mydict' have been passed into the template in the Conte... | How to use django template dot notation inside a for loop | I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:
{% for dictkey in keys %}
<p> {{ mydict.dictkey }} </p>
{% endfor %}
(let's say 'keys' and 'mydict' have been passed into the template in the Context)
Django renders the page but without the dictionary contents... | [
"See this answer to a (possibly duplicate) related question.\nIt creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.\nCode:\n@register.filter\ndef lookup(d, key):\n if key not in d:\n return None\n ... | [
4,
1,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004363032_django_django_templates_python.txt |
Q:
What would be the Python code to add time to a specific timestamp?
Trying to figure out datetime module and need some help.
I've got a string which looks like this:
00:03:12,200 --> 00:03:14,316
(that is hours:minutes:seconds,milliseconds)
and need to add let's say 10 seconds to each timestamp. To have as output:... | What would be the Python code to add time to a specific timestamp? | Trying to figure out datetime module and need some help.
I've got a string which looks like this:
00:03:12,200 --> 00:03:14,316
(that is hours:minutes:seconds,milliseconds)
and need to add let's say 10 seconds to each timestamp. To have as output:
00:03:22,200 --> 00:03:24,316
What would be the Python code to do that... | [
"To parse time, use strptime\n>>> x = '00:03:12,200 --> 00:03:14,316'\n>>> x1 = x.split('-->')\n>>> x1\n['00:03:12,200 ', ' 00:03:14,316']\n>>> t1 = datetime.datetime.strptime(x1[0], '%H:%M:%S,%f ')\n>>> t1\ndatetime.datetime(1900, 1, 1, 0, 3, 12, 200000)\n\nuse timedelta\n>>> t = datetime.timedelta(seconds=1)\n>>>... | [
7,
7
] | [] | [] | [
"datetimeoffset",
"python"
] | stackoverflow_0004363072_datetimeoffset_python.txt |
Q:
In Django, how do I display the message (using Message Framework) without looping through?
messages.success(request, "Success. Your settings have been saved.")
Ok, so now in my template, I do this:
{% if messages %}
{% for m in messages %}
<div class="notification_message" data-message="{{ m }}">{{ m... | In Django, how do I display the message (using Message Framework) without looping through? | messages.success(request, "Success. Your settings have been saved.")
Ok, so now in my template, I do this:
{% if messages %}
{% for m in messages %}
<div class="notification_message" data-message="{{ m }}">{{ m }}</div>
{% endfor %}
{% endif %}
But that's silly!!! I only have 1 message. I don't w... | [
"As far as I know, there is no way to do this from within the template itself (without a custom tag or filter, of course). It's fairly easy to accomplish outside of the template though (untested):\nfrom django.contrib.messages import get_messages, constants as message_level\n\ndef last_message(messages, level = Non... | [
0
] | [] | [] | [
"django",
"javascript",
"message",
"python",
"templates"
] | stackoverflow_0004363033_django_javascript_message_python_templates.txt |
Q:
How can I auto-crop a pre-defined polygon shape from an image file?
Ideally using a Python library or processing.org, I need to import an image and then crop a predefined polygon area from this image using x,y coordinates (vertices).
Thanks.
A:
Try PythonMagick. Your question appears to be a cut-and-dry applicat... | How can I auto-crop a pre-defined polygon shape from an image file? | Ideally using a Python library or processing.org, I need to import an image and then crop a predefined polygon area from this image using x,y coordinates (vertices).
Thanks.
| [
"Try PythonMagick. Your question appears to be a cut-and-dry application of crop through specification of image geometry.\n(More ImageMagick ports and documentation.)\n",
"Also check out PIL. \nThough this is hardly library specific and almost every library should support this.\n"
] | [
1,
0
] | [] | [] | [
"image_processing",
"processing",
"python"
] | stackoverflow_0004363339_image_processing_processing_python.txt |
Q:
(python)is generating and executing code at runtime considered bad practice?
I'm learning python and i want to learn good practices from the start i had a problem and i came up with a solution that involved generating variables on runtime, this is a sample of what i was doing
for i in range (10):
current = 'va... | (python)is generating and executing code at runtime considered bad practice? | I'm learning python and i want to learn good practices from the start i had a problem and i came up with a solution that involved generating variables on runtime, this is a sample of what i was doing
for i in range (10):
current = 'variable'+str(i)+' = '+str(i)
exec (current)
So, is doing things like this cons... | [
"No, this isn't a good practice. Whatever you're doing, the solution is probably to put your data in a dict, then you can just access mydict['variable1'] or whatever. \nThere ARE times when exec is reasonable, but they are typically cases of advanced metaprogramming.\nA guideline here: If you don't know exactly why... | [
4,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0004363554_python.txt |
Q:
Creating form using Generic_inlineformset_factory from the Model Form
I wanted to create a edit form with the help of ModelForm.
and my models contain a Generic relation b/w classes, so if any one could suggest me the view and a bit of template for the purpose I would be very thankful, as I am new to the language.... | Creating form using Generic_inlineformset_factory from the Model Form | I wanted to create a edit form with the help of ModelForm.
and my models contain a Generic relation b/w classes, so if any one could suggest me the view and a bit of template for the purpose I would be very thankful, as I am new to the language.
My models look like:-
class Employee(Person):
nickname = models.Char... | [
"posting the solution I found out. After taking a look at the source of Generic_inlineformset_factory.\nI made my view as:-\ndef edit_contact(request):\n c={}\n profile = request.user.get_profile()\n EmployeeFormSet = generic_inlineformset_factory(PhoneNumber,extra=0,can_delete=False)\n EmployeeForm... | [
19
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004304148_django_python.txt |
Q:
How to handle properties of a dbus interface with python?
I'm about to work on an implementation of mpris. But currently I am not sure how to read/write dbus interface properties with python-dbus. Is there any examples for this ?
A:
Finally got the answer:
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature... | How to handle properties of a dbus interface with python? | I'm about to work on an implementation of mpris. But currently I am not sure how to read/write dbus interface properties with python-dbus. Is there any examples for this ?
| [
"Finally got the answer:\n@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')\ndef Get(self, interface, prop):\n ...\n@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv')\ndef Set(self, interface, prop, value):\n ...\n@dbus.service.method(dbus.PROPERTIES_IFACE, in_sign... | [
4
] | [] | [] | [
"dbus",
"linux",
"python"
] | stackoverflow_0004277814_dbus_linux_python.txt |
Q:
Closing Pygame games made with PyScripter in Portable Python closes PyScripter too
I am using Portable Python to to some PyGame development because it has PyGame and PyScripter built in so there was minimal setup.
I write the code, then press run and my game launches. When I close the game (by the Windows "X", not... | Closing Pygame games made with PyScripter in Portable Python closes PyScripter too | I am using Portable Python to to some PyGame development because it has PyGame and PyScripter built in so there was minimal setup.
I write the code, then press run and my game launches. When I close the game (by the Windows "X", not some in-game close button), PyScripter closes too.
Are they both part of the same proce... | [
"You are running your game with PyScripter \"Internal\" engine. Thats why it closes PyScripter when you close your app. This is normal behavior of PyScripter but there is much more \"run modes\" you can use.\nYou can switch to use one of the Remote engines and then your app will run in \"external\" process. More in... | [
1
] | [] | [] | [
"portable_applications",
"pygame",
"pyscripter",
"python",
"python_2.6"
] | stackoverflow_0004359334_portable_applications_pygame_pyscripter_python_python_2.6.txt |
Q:
How to set the width of a Button in tkinter?
I'm trying to make a simple GUI calculator in Python with Tkinter. However the widths of the buttons will often be off by 1 or 2 pixels. Is there any way to force all the buttons to have the same width.
I know of the ipadx method; however, it adds pixels to both sides ... | How to set the width of a Button in tkinter? | I'm trying to make a simple GUI calculator in Python with Tkinter. However the widths of the buttons will often be off by 1 or 2 pixels. Is there any way to force all the buttons to have the same width.
I know of the ipadx method; however, it adds pixels to both sides of the button. This causes problems when the width... | [
"Use the sticky option of the grid geometry manager to \"stick\" the button to all four sides of its containing cell (i.e. Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W). If you want to enforce a minimum width then you can either set the button width or better use grid_columnconfigure.\nAlso, really consider not u... | [
3
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004364136_python_tkinter.txt |
Q:
How to lock function from multiple ajax requests in short period of time without threads
I'm dealing with the problem I've seen some people also struggling. I need some functionality based on Facebook like buttons events. So I catch the event of clicking button and on it call my function with ajax. But on each sin... | How to lock function from multiple ajax requests in short period of time without threads | I'm dealing with the problem I've seen some people also struggling. I need some functionality based on Facebook like buttons events. So I catch the event of clicking button and on it call my function with ajax. But on each single click my function is called multiple times, varying from 3 to 8. Problem is that this func... | [
"If I am getting your issue correct, I think you should define a global variable in javascript. Say you have a global variable busy which should be set once a request is sent and unset when the request is completed. \nBefore every request you should check whether the variable is set and if its set do not send the r... | [
0
] | [] | [] | [
"django",
"facebook_like",
"locking",
"python",
"xmlhttprequest"
] | stackoverflow_0004364005_django_facebook_like_locking_python_xmlhttprequest.txt |
Q:
Using C++ streams to serialize numbers crashes boost.python on the Mac
I think something is wrong with my linking (I am running on a mac, and had to change the library to be a MODULE?). Here's what I have:
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
project (testme)
FIND_PACKAGE( Boost REQUIRED )
FIND_PAC... | Using C++ streams to serialize numbers crashes boost.python on the Mac | I think something is wrong with my linking (I am running on a mac, and had to change the library to be a MODULE?). Here's what I have:
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
project (testme)
FIND_PACKAGE( Boost REQUIRED )
FIND_PACKAGE( Boost COMPONENTS python REQUIRED )
FIND_PACKAGE( PythonLibs REQUIRED )... | [
"In the example above the constructor call needs to be:\na= d.TestClass() \notherwise the example works fine on Ubuntu 10.04LTS with gcc 4.4.3 and boost 1.40\n"
] | [
1
] | [] | [] | [
"boost_python",
"cmake",
"macos",
"python"
] | stackoverflow_0004363967_boost_python_cmake_macos_python.txt |
Q:
Python:List:Out of Range cases
imagine that i have a list like l=[[10,50,90],[70,80,90],[88,90,55]]
10 50 90
70 80 40
88 90 55
I sum an item with the others around it(so the sum of 9 items).
but if I choose to sum an item on the border, the index will be out of range.
is it possible to when the index is out... | Python:List:Out of Range cases | imagine that i have a list like l=[[10,50,90],[70,80,90],[88,90,55]]
10 50 90
70 80 40
88 90 55
I sum an item with the others around it(so the sum of 9 items).
but if I choose to sum an item on the border, the index will be out of range.
is it possible to when the index is out of range, instead of bugging,to add... | [
"You can either use try-catch style error handling (http://wiki.python.org/moin/HandlingExceptions has some info) or write your code with if blocks like\nif (index == 0) then\n handleEdgeCase(index)\nelse\n handleGeneralCase(index)\n\nto notice the unusual situations and deal with them.\n",
"Define a functi... | [
1,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004364214_list_python.txt |
Q:
any django 's simple login/register demo to be download?
i will be write a login/register demo using django
i want to know that : Does django has a demo like this ?
thanks
A:
Django does not has any demo for login/registration.
One of the pillar reasons for Django's popularity is its wholesome documentatio... | any django 's simple login/register demo to be download? | i will be write a login/register demo using django
i want to know that : Does django has a demo like this ?
thanks
| [
"Django does not has any demo for login/registration.\nOne of the pillar reasons for Django's popularity is its wholesome documentation. You should be able to comfortably get going using the docs for Django auth.\nIf interested, you may explore Django registration, which is a custom app that you can easily integrat... | [
1
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0004362542_authentication_django_python.txt |
Q:
getting pyqt to use cocoa widgets
The widgets in my application are the old style mac widgets. How do I make them become the new style ones. I am using pyqt 4.6.3-1 with python 2.7 on os x 10.6. Everything was installed using fink and I installed both qt4-mac and qt4-x11. Not sure which is being used or how to... | getting pyqt to use cocoa widgets | The widgets in my application are the old style mac widgets. How do I make them become the new style ones. I am using pyqt 4.6.3-1 with python 2.7 on os x 10.6. Everything was installed using fink and I installed both qt4-mac and qt4-x11. Not sure which is being used or how to select one or the other.
| [
"I switched from Fink to Macports, and I got the nice widgets.\n"
] | [
1
] | [] | [] | [
"cocoa",
"pyqt",
"python",
"qt4"
] | stackoverflow_0004232228_cocoa_pyqt_python_qt4.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.