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:
Convert backward slash to forward slash in python
Hi
I have read articles related converting backward to forward slashes.
But sol was to use raw string.
But Problem in my case is :
I will get file path dynamically to a variable
var='C:\dummy_folder\a.txt'
In this case i need to convert it to Forward slashes.
But... | Convert backward slash to forward slash in python | Hi
I have read articles related converting backward to forward slashes.
But sol was to use raw string.
But Problem in my case is :
I will get file path dynamically to a variable
var='C:\dummy_folder\a.txt'
In this case i need to convert it to Forward slashes.
But due to '\a',i am not able to convert to forward slashe... | [
"Don't do this. Just use os.path and let it handle everything. You should not explicitly set the forward or backward slashes. \n>>> var=r'C:\\dummy_folder\\a.txt'\n>>> var.replace('\\\\', '/')\n'C:/dummy_folder/a.txt'\n\nBut again, don't. Just use os.path and be happy!\n",
"There is also os.path.normpath(), which... | [
13,
12,
2,
1,
0
] | [] | [] | [
"path",
"python",
"ruby"
] | stackoverflow_0004297450_path_python_ruby.txt |
Q:
returning a single instance of a regex object's contents
I am writing a matching function, and I am wondering whether or not I can return only the first occurrence of a match. Here is my code (which matches all of the instances of the url for a given line, not only the first)... this is before I attempted to sele... | returning a single instance of a regex object's contents | I am writing a matching function, and I am wondering whether or not I can return only the first occurrence of a match. Here is my code (which matches all of the instances of the url for a given line, not only the first)... this is before I attempted to select a single match:
def file_match(line, url):
allmatches =... | [
"My guess is that you need to do a little more reading on Match Objects.\nIn particular Groups.\nHope this helps.\n",
"yet another update.\nsorry for the trouble, but i think that it ended up being my fault. when i used line.replace() i wasn't using the correct search string, only the test for the re module, whi... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004788532_python.txt |
Q:
Reading from a text file
I'm not looking for an answer here but rather a guideline of how I should be approaching this task.
I have a txt file that contains the following information:
...
1947q2 -0.6
1947q3 -0.3
1947q4 6.2
1948q1 6.5
1948q2 7.6
1948q3 ... | Reading from a text file | I'm not looking for an answer here but rather a guideline of how I should be approaching this task.
I have a txt file that contains the following information:
...
1947q2 -0.6
1947q3 -0.3
1947q4 6.2
1948q1 6.5
1948q2 7.6
1948q3 2.2
1948q4 ... | [
"import sys\nwith open('file.txt') as f:\n for line in f:\n if '1947' in line: # or some complex regular expressions test\n sys.stdout.write(line)\n\nYou can just parse each line in the body of the for loop and then decide whether to accept it. If you want to get fancy, have a look at map and filter. The w... | [
5,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004785671_python.txt |
Q:
Authentication within python script
I'm writing a master-control script to control our infrastructure. Security is a major concern so I'd like to address two issues:
I want the user to be able to execute the application then be prompted to 'login' to the program using the root credentials on the system(Linux - Ubu... | Authentication within python script | I'm writing a master-control script to control our infrastructure. Security is a major concern so I'd like to address two issues:
I want the user to be able to execute the application then be prompted to 'login' to the program using the root credentials on the system(Linux - Ubuntu). Failure to authenticate will trigge... | [
"While this is a non-trivial solution, the most secure way to do this is taking a client/server approach, making your master-control script a system service, only readable and runnable by root. You can fire up the service via init.d startup infrastructure.\nWhen the service starts, you'd need to open a socket or RP... | [
2
] | [] | [] | [
"authentication",
"python"
] | stackoverflow_0004789359_authentication_python.txt |
Q:
xml processing options in python
I am currently writing a non-web program using mostly python and have gotten to the point where I need to create a structure for save and settings files.
I decided to use xml over creating my own format but have come into a bit of a barrier when trying to figure out what to use to... | xml processing options in python | I am currently writing a non-web program using mostly python and have gotten to the point where I need to create a structure for save and settings files.
I decided to use xml over creating my own format but have come into a bit of a barrier when trying to figure out what to use to actually process the xml. I want to k... | [
"If your data is only for the use of your Python programs, pickle might be an easier solution.\n",
"Don't use xml -- use yaml or json -- some would argue xml has outlived it's useful life...\nThat being said, I like ElementTree:\nimport xml.etree.cElementTree as ET\nfname = 'foo.xml'\nroot = ET.parse(open(fname))... | [
3,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004789397_python_xml.txt |
Q:
Set the value of XML file recursively with Python ElementTree?
I'm given a XML file as follows.
<?xml version="1.0" encoding="UTF-8"?>
<A value="?">
<B value="?">
<C value="10"/>
<C value ="20"/>
</B>
<B value="?">
<C value = "5" />
<C value = "10" />
</B>
</A>
How ... | Set the value of XML file recursively with Python ElementTree? | I'm given a XML file as follows.
<?xml version="1.0" encoding="UTF-8"?>
<A value="?">
<B value="?">
<C value="10"/>
<C value ="20"/>
</B>
<B value="?">
<C value = "5" />
<C value = "10" />
</B>
</A>
How can I sum the value of the children node to set up the parent recurs... | [
"The following code was run unchanged with Python 3.1.3 (shown) and Python 2.7.1 (not shown). The function which does all the work is version independent. You may want to change the other twiddly bits (parsing from a file instead of from a string, importing some other ElementTree implementation, etc) to suit yourse... | [
2,
1
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0004788574_elementtree_python_xml.txt |
Q:
Python Mechanize: UnicodeEncodeError when uploading UTF-8 file. 'ascii' codec
the mechanize framework works great for automating the first couple of web screens. The problem is where it needs to upload a file with in a form.
Here is the section of code just before the error:
br.select_form(name="form.uploadXMLData... | Python Mechanize: UnicodeEncodeError when uploading UTF-8 file. 'ascii' codec | the mechanize framework works great for automating the first couple of web screens. The problem is where it needs to upload a file with in a form.
Here is the section of code just before the error:
br.select_form(name="form.uploadXMLDataWizardForm")
xmlFile = codecs.open("MyFile.xml", "rt", "utf8")
br.form.add_file(fil... | [
"Mechanize seems to expect the file data as raw bytes, not Unicode data. Try opening the file using the usual open() function:\n...\nxmlFile = open(\"MyFile.xml\", \"rt\")\n...\n\n"
] | [
3
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004772482_mechanize_python.txt |
Q:
Importing a script into another script
I am trying to import this file
http://pastebin.com/bEss4J6Q
Into this file
def MainLoop(self): #MainLoop is used to make the commands executable ie !google !say etc;
try:
while True:
# This method sends a ping to th... | Importing a script into another script | I am trying to import this file
http://pastebin.com/bEss4J6Q
Into this file
def MainLoop(self): #MainLoop is used to make the commands executable ie !google !say etc;
try:
while True:
# This method sends a ping to the server and if it pings it will send a pong... | [
"A module is nothing but a python source file. You keep that python source file in the same directory as other source file and you can import that module in other source files. When you are importing that module, the classes and functions defined in that module are available for you to use.\nFor e.g. in your case, ... | [
4
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0004789660_import_module_python.txt |
Q:
Appengine urlfetch debugging
I'm trying to do what should be a fairly simple url fetch with google appengine. However, it keeps failing.
result = urlfetch.fetch(url=apiurl, method=urlfetch.POST)
I also tried using httplib:
conn = httplib.HTTPConnection("api.eve-online.com")
conn.request("POST", "/char/CharacterSh... | Appengine urlfetch debugging | I'm trying to do what should be a fairly simple url fetch with google appengine. However, it keeps failing.
result = urlfetch.fetch(url=apiurl, method=urlfetch.POST)
I also tried using httplib:
conn = httplib.HTTPConnection("api.eve-online.com")
conn.request("POST", "/char/CharacterSheet.xml.aspx", params, headers)
r... | [
"Are you using Python 2.7 ? It supports only 2.5.2. While 2.6 mostly works, 2.7 don't.\n"
] | [
5
] | [] | [] | [
"debugging",
"google_app_engine",
"python"
] | stackoverflow_0004789559_debugging_google_app_engine_python.txt |
Q:
Scope of imported modules/functions in Python
I'm new here and am not 100% sure how to ask this question so I'll just dive right in. Should I be using import statements at the beginning of every function I write that import all of the various modules/functions I need for that function's scope? i.e.
def func1()
... | Scope of imported modules/functions in Python | I'm new here and am not 100% sure how to ask this question so I'll just dive right in. Should I be using import statements at the beginning of every function I write that import all of the various modules/functions I need for that function's scope? i.e.
def func1()
import os.path
print func(2)
do something... | [
"Usually all imports are placed at the beginning of the file. Importing a module in a function body will import a module in that scope only:\ndef f():\n import sys\n print 'f', sys.version_info\n\ndef g():\n print 'g', sys.version_info\n\nif __name__ == '__main__':\n f() # will work\n g() # won't wor... | [
10,
7
] | [] | [] | [
"import",
"python",
"scope"
] | stackoverflow_0004789711_import_python_scope.txt |
Q:
How do I get a handle to the TreeWidgetItem being dropped in PyQt DragNDrop?
I am trying to handle a drop event on a TreeWidget from itself by overriding the dropEvent method. Ultimately, I need to get a handle to the TreeWidgetItem being dropped. So far, the only useful information I get from the event regardin... | How do I get a handle to the TreeWidgetItem being dropped in PyQt DragNDrop? | I am trying to handle a drop event on a TreeWidget from itself by overriding the dropEvent method. Ultimately, I need to get a handle to the TreeWidgetItem being dropped. So far, the only useful information I get from the event regarding the dropped item is a QByteArray that seems to contain text from the item being ... | [
"not quite sure I'm understanding the question correctly, but your mime data comes from the startDrag method, where you've created a QMimeData object, set it's type and supplied data accordingly. In your dropEvent method check the type of the incoming data and process it accordingly or ignore if you don't recognize... | [
2
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0004786470_pyqt_python_qt.txt |
Q:
file.write() and sys.stdout.write() are giving me two different outputs - Python
The code below takes a JPEG image and converts it to a string. That string is then saved into the image variable. Then, the string is written to a.jpg using File IO and then written to b.jpg by me piping stdout to the file.
import thu... | file.write() and sys.stdout.write() are giving me two different outputs - Python | The code below takes a JPEG image and converts it to a string. That string is then saved into the image variable. Then, the string is written to a.jpg using File IO and then written to b.jpg by me piping stdout to the file.
import thumb
import sys
x = thumb.Thumbnail('test.jpg')
x.generate(56, 56)
image = str(x)
wit... | [
"You write your data to a.jpg as binary, while b.jpg get written in text mode. When in binary mode otherwise special characters (such as newlines or EOF marker) are not treated special, while in text mode they are. \nIn Python 3 you can switch modes:\n\nhttp://docs.python.org/py3k/library/sys.html#sys.stdin\n\n\nTh... | [
2
] | [] | [] | [
"file_io",
"python",
"stdout"
] | stackoverflow_0004790035_file_io_python_stdout.txt |
Q:
Problems getting gae-sessions to work in App Engine, error isn't helpful
I've installed gae-sessions to my development environment but it doesn't seem to be storing anything. Here's a basic example:
session = get_current_session()
session.get('some_num', 3)
Then later on in some other function...
session = get_c... | Problems getting gae-sessions to work in App Engine, error isn't helpful | I've installed gae-sessions to my development environment but it doesn't seem to be storing anything. Here's a basic example:
session = get_current_session()
session.get('some_num', 3)
Then later on in some other function...
session = get_current_session()
session['some_num'] = 4
And here's the error I get in the co... | [
"Looking at the example app (here), it appears that all sessions start off inactive, and are automatically set to active the first time you store a value to them. You should simply be able to store a value to the session with session['foo'] = 'bar', and it'll automatically activate the session.\nAlso note that you ... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004789417_google_app_engine_python.txt |
Q:
django - convert a list back to a queryset
I have a handful of records that I would like to sort based on a computed value. Got the answer over here... like so:
sorted(Profile.objects.all(), key=lambda p: p.reputation)
on a Profile class like this:
class Profile(models.Model):
...
@property
def repu... | django - convert a list back to a queryset | I have a handful of records that I would like to sort based on a computed value. Got the answer over here... like so:
sorted(Profile.objects.all(), key=lambda p: p.reputation)
on a Profile class like this:
class Profile(models.Model):
...
@property
def reputation(self):
...
Unfortunately the gen... | [
"Ok...this post is now old BUT what you could do is get all the ids of the objects in your list, then perform a model.objects.filter(pk__in=list_of_ids)\n",
"There is no point in converting a data list back to a query. A query object never holds data; it just represents a query to the database. It would have to f... | [
113,
30
] | [] | [] | [
"django",
"django_queryset",
"list",
"python",
"sorting"
] | stackoverflow_0001058135_django_django_queryset_list_python_sorting.txt |
Q:
Insert a node for an element in XML with Python/ElementTree
I need to traverse the XML tree to add sub element when the value is less than 5.
For example, this XML can be modified into
<?xml version="1.0" encoding="UTF-8"?>
<A value="45">
<B value="30">
<C value="10"/>
<C value ="20"/>
</B... | Insert a node for an element in XML with Python/ElementTree | I need to traverse the XML tree to add sub element when the value is less than 5.
For example, this XML can be modified into
<?xml version="1.0" encoding="UTF-8"?>
<A value="45">
<B value="30">
<C value="10"/>
<C value ="20"/>
</B>
<B value="15">
<C value = "5" />
<C value =... | [
"You probably made a typo because in the example, an error element is appended as the child of an element whose value is 10, which is not less than 5. But I think this is the idea:\n#!/usr/bin/env python\n\nfrom xml.etree.ElementTree import fromstring, ElementTree, Element\n\ndef validate_node(elem):\n for child... | [
13,
2
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0004788633_elementtree_python_xml.txt |
Q:
Python server / client remote execute problem
I'm working on a project in Python that I'm having trouble with. I've asked so many people but they seem to not be able to help me :/ I'm coding a little program that executes system commands. The idea is that one machine opens the server and the other one opens the cl... | Python server / client remote execute problem | I'm working on a project in Python that I'm having trouble with. I've asked so many people but they seem to not be able to help me :/ I'm coding a little program that executes system commands. The idea is that one machine opens the server and the other one opens the client and connects to the IP / Port. From there they... | [
"I told you exactly what the problem was in this answer to your previous question:\nPython - Server and client problems\nI'm not joking or anything, I tried your code, I figured out what the problem was, and I told you how to fix it.\nOnce again, with emphasis:\nWhen you makefile() on the socket and then use readli... | [
1
] | [] | [] | [
"client",
"python",
"sockets"
] | stackoverflow_0004790104_client_python_sockets.txt |
Q:
How do I require HTTPS for this Django view?
(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),
How do I add HTTPS required to this? I usually have a decorator for it..
But in this case I can't apply it.
def secure_required(view_func):
... | How do I require HTTPS for this Django view? | (r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),
How do I add HTTPS required to this? I usually have a decorator for it..
But in this case I can't apply it.
def secure_required(view_func):
"""Decorator makes sure URL is accessed over h... | [
"I believe you can wrap the function in this manner:\nfrom django.contrib.auth.views import login\nfrom <<wherever>> import secure_required\n\n\nurlpatterns = patterns('',\n (r'^login/?$',secure_required(login),{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),\n)\n\n"
] | [
5
] | [] | [] | [
"django",
"http",
"https",
"python",
"rest"
] | stackoverflow_0004790430_django_http_https_python_rest.txt |
Q:
Python HTMLParser: UnicodeDecodeError
I'm using HTMLParser to parse pages I pull down with urllib, and am coming across UnicodeDecodeError exceptions when passing some to HTMLParser.
I tried using chardet to detect the encodings and to convert to ascii, or utf-8 (the docs don't seem to say what it should be). loss... | Python HTMLParser: UnicodeDecodeError | I'm using HTMLParser to parse pages I pull down with urllib, and am coming across UnicodeDecodeError exceptions when passing some to HTMLParser.
I tried using chardet to detect the encodings and to convert to ascii, or utf-8 (the docs don't seem to say what it should be). lossiness is acceptable, but while the decode/e... | [
"It is UTF-8, indeed. This works:\nfrom HTMLParser import HTMLParser\nimport urllib\n\nclass search_youtube(HTMLParser):\n\n def __init__(self, search_terms):\n HTMLParser.__init__(self)\n self.track_ids = []\n for search in search_terms:\n self.__in_result = False\n se... | [
18,
1
] | [] | [] | [
"character_encoding",
"html_parsing",
"python"
] | stackoverflow_0004790078_character_encoding_html_parsing_python.txt |
Q:
How do I correctly format a target time for a countdown?
Right now I'm trying to enter a time in 24 hour format and initiate a countdown from the current time to the specified time.
So currently the user is entering a target hour and a target minute. I'm not sure what to do with these values to begin a countdown f... | How do I correctly format a target time for a countdown? | Right now I'm trying to enter a time in 24 hour format and initiate a countdown from the current time to the specified time.
So currently the user is entering a target hour and a target minute. I'm not sure what to do with these values to begin a countdown from now until the specified time.
import datetime
now = datet... | [
"Well, you convert the values to a datetime, and then eneter a loop where display the remaining time from now to the expiring minute, and then sleep for a while, and then display it again, until it reaches zero.\n",
"Actually, the correct answer to this involves creating a datetime.datetime object and incrementin... | [
0,
0
] | [] | [] | [
"countdown",
"datetime",
"python"
] | stackoverflow_0004790329_countdown_datetime_python.txt |
Q:
Python PIL: How to draw an ellipse in the middle of an image?
I seem to be having some trouble getting this code to work:
import Image, ImageDraw
im = Image.open("1.jpg")
draw = ImageDraw.Draw(im)
draw.ellipse((60, 60, 40, 40), fill=128)
del draw
im.save('output.png')
im.show()
This should draw an ellipse at ... | Python PIL: How to draw an ellipse in the middle of an image? | I seem to be having some trouble getting this code to work:
import Image, ImageDraw
im = Image.open("1.jpg")
draw = ImageDraw.Draw(im)
draw.ellipse((60, 60, 40, 40), fill=128)
del draw
im.save('output.png')
im.show()
This should draw an ellipse at (60,60) which is 40 by 40 pixels. The image returns nothing.
This c... | [
"The bounding box is a 4-tuple (x0, y0, x1, y1) where (x0, y0) is the top-left bound of the box and (x1, y1) is the lower-right bound of the box.\nTo draw an ellipse to the center of the image, you need to define how large you want your ellipse's bounding box to be (variables eX and eY in my code snippet below).\nW... | [
21,
3
] | [] | [] | [
"ellipse",
"python",
"python_imaging_library"
] | stackoverflow_0004789894_ellipse_python_python_imaging_library.txt |
Q:
How to return an image in an HTTP response with CherryPy
I have code which generates a Cairo ImageSurface, and I expose it like so:
def preview(...):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
...
cherrypy.response.headers['Content-Type'] = "image/png"
return surface.get_data(... | How to return an image in an HTTP response with CherryPy | I have code which generates a Cairo ImageSurface, and I expose it like so:
def preview(...):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
...
cherrypy.response.headers['Content-Type'] = "image/png"
return surface.get_data()
preview.exposed = True
This doesn't work (browsers report t... | [
"Add these imports:\nfrom cherrypy.lib import file_generator\nimport StringIO\n\nand then go like this:\ndef index(self):\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n cherrypy.response.headers['Content-Type'] = \"image/png\"\n\n buffer = StringIO.StringIO()\n surface.write_to_png... | [
17,
1,
0,
0
] | [] | [] | [
"cairo",
"cherrypy",
"http",
"python"
] | stackoverflow_0003064374_cairo_cherrypy_http_python.txt |
Q:
how to control the buttons or tabs in the launch application using python
i launched the application using the following code i.e.
import os
cmd = r'start C:\WindowsMediaPlayer\wmplayer.exe'
os.system(cmd)
say i launched win media player.. now i want to control the buttons/the menus to open a file . or do some aud... | how to control the buttons or tabs in the launch application using python | i launched the application using the following code i.e.
import os
cmd = r'start C:\WindowsMediaPlayer\wmplayer.exe'
os.system(cmd)
say i launched win media player.. now i want to control the buttons/the menus to open a file . or do some audio settings.. any thing that is related to media player using the python script... | [
"Maybe you should use a framework such as pywinauto\nUsing this, you can launch windows applications and control them.\nCheck this out\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004791204_python.txt |
Q:
What is the trick in this website?
I can access this webpage in my firefox browser:
http://www.ip-adress.com/ip_tracer/74.82.190.99
So I can get the information about this IP.
However, when I fetch it using Python, there will be errors:
import urllib
f = urllib.urlopen("http://www.ip-adress.com/ip_tracer/74.82.190... | What is the trick in this website? | I can access this webpage in my firefox browser:
http://www.ip-adress.com/ip_tracer/74.82.190.99
So I can get the information about this IP.
However, when I fetch it using Python, there will be errors:
import urllib
f = urllib.urlopen("http://www.ip-adress.com/ip_tracer/74.82.190.99")
print f.read()
I get this error:
... | [
"Probably the server reads your User-Agent header and decides not to serve your request. Alternatively it can rely on some other headers being typically set by normal browsers (like FF).\nI tried this one:\nimport urllib2\n\nrequest = urllib2.Request(\"http://www.ip-adress.com/ip_tracer/74.82.190.99\")\nrequest.add... | [
11,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0004791253_python_urllib.txt |
Q:
Python: Regular expression... not working?
I have this code:
# If the username isn't alpha-numerics (inc: _, -, ., )
if re.match('^[a-zA-Z0-9 _\-\.]+$', repName) == False:
print 'DECLINE: '+repName
else:
print 'ACCEPTED: '+repName
And when i test it against this string: ɢᴀꜱᴛяɪᴄ (which ... | Python: Regular expression... not working? | I have this code:
# If the username isn't alpha-numerics (inc: _, -, ., )
if re.match('^[a-zA-Z0-9 _\-\.]+$', repName) == False:
print 'DECLINE: '+repName
else:
print 'ACCEPTED: '+repName
And when i test it against this string: ɢᴀꜱᴛяɪᴄ (which is grabbed from a website)
I get this returned:
... | [
"Unsuccessful re.match is not False. It is None.\nBut you can also try it this way:\nif re.match('^[a-zA-Z0-9 _\\-\\.]+$', repName):\n print 'ACCEPTED: '+repName\nelse:\n print 'DECLINE: '+repName\n\n"
] | [
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004791286_python_regex.txt |
Q:
How do I do greater than/less than using MongoDB?
I'm using the pymongo driver.
Can someone take a look at pymongo and tell me how to do greater than? I"m used to doing : for everything.
A:
Have you seen the doc ? Take from the manual :
>>> d = datetime.datetime(2009, 11, 12, 12)
>>> for post in posts.find({"dat... | How do I do greater than/less than using MongoDB? | I'm using the pymongo driver.
Can someone take a look at pymongo and tell me how to do greater than? I"m used to doing : for everything.
| [
"Have you seen the doc ? Take from the manual :\n>>> d = datetime.datetime(2009, 11, 12, 12)\n>>> for post in posts.find({\"date\": {\"$lt\": d}}).sort(\"author\"):\n... post\n...\n{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'... | [
52,
26,
6
] | [] | [] | [
"database",
"mongodb",
"python"
] | stackoverflow_0004791555_database_mongodb_python.txt |
Q:
Python- need fast algorithm that removes all words in a file that are derivatives in other words
We have a file named wordlist, which contains 1,876 KB worth of alphabetized words, all of which are longer than 4 letters and contain one carriage return between each new two-letter construction (ab, ac, ad, etc., wor... | Python- need fast algorithm that removes all words in a file that are derivatives in other words | We have a file named wordlist, which contains 1,876 KB worth of alphabetized words, all of which are longer than 4 letters and contain one carriage return between each new two-letter construction (ab, ac, ad, etc., words all contain returns between them):
wfile = open("wordlist.txt", "r+")
I want to create a new file... | [
"I would do something like this:\ndef bases(words):\n base = next(words)\n yield base\n for word in words:\n if word and not word.startswith(base):\n yield word\n base = word\n\n\ndef get_bases(infile, outfile):\n with open(infile) as f_in:\n words = (line.strip() for... | [
3,
2,
1
] | [] | [] | [
"algorithm",
"io",
"list",
"python"
] | stackoverflow_0004791567_algorithm_io_list_python.txt |
Q:
In python, how do I take the highest occurrence of something in a list, and sort it that way?
[3, 3, 3, 4, 4, 2]
Would be:
[ (3, 3), (4, 2), (2, 1) ]
The output should be sorted by highest count first to lowest count. In this case, 3 to 2 to 1.
A:
You can use a Counter in Python 2.7+ (this recipe works on 2.5+... | In python, how do I take the highest occurrence of something in a list, and sort it that way? | [3, 3, 3, 4, 4, 2]
Would be:
[ (3, 3), (4, 2), (2, 1) ]
The output should be sorted by highest count first to lowest count. In this case, 3 to 2 to 1.
| [
"You can use a Counter in Python 2.7+ (this recipe works on 2.5+):\nfrom collections import Counter\nprint Counter([3, 3, 3, 4, 4, 2]).most_common()\n# [(3, 3), (4, 2), (2, 1)]\n\n",
"data = [3, 3, 3, 4, 4, 2]\nresult = []\nfor entry in set(data):\n result.append((entry, data.count(entry)))\nresult.sort(key = ... | [
13,
3,
2,
2,
0
] | [] | [] | [
"list",
"list_manipulation",
"python"
] | stackoverflow_0004791599_list_list_manipulation_python.txt |
Q:
Python GData lib causes too much redirects
I'm using python GData to work with Google Calendar. I'm making really simple requests (e.g. create event), using OAuth authorization.
Usually this works OK, but sometimes I'm receiving lots of 302 redirects, that leads to "Maximum redirects count reached" exception.
If... | Python GData lib causes too much redirects | I'm using python GData to work with Google Calendar. I'm making really simple requests (e.g. create event), using OAuth authorization.
Usually this works OK, but sometimes I'm receiving lots of 302 redirects, that leads to "Maximum redirects count reached" exception.
If I re-try same request, it's usually works corre... | [
"Answer from Google support forum:\n\nThis might happen due to some issues in the Calendar servers and is not an error on your part. The best way to \"resolve\" this issue is to retry again.\n\n"
] | [
0
] | [] | [] | [
"gdata_api",
"gdata_python_client",
"google_data_api",
"python"
] | stackoverflow_0004657001_gdata_api_gdata_python_client_google_data_api_python.txt |
Q:
Python SQL select row from specific variable field
I'd like to grab a specific value from a row based on a random variable. Here's an example table the PID column is an "auto-increment primary key integer" and the other 2 columns are TEXT
example-table
PID NAME PHONE
--- ---- -----
1 bill 999... | Python SQL select row from specific variable field | I'd like to grab a specific value from a row based on a random variable. Here's an example table the PID column is an "auto-increment primary key integer" and the other 2 columns are TEXT
example-table
PID NAME PHONE
--- ---- -----
1 bill 999-9999
2 joe 888-8888
I'd like to throw a rando... | [
"I believe you're meant to use it like this\nrandomVariable = raw_input('Enter something: ')\nsql = \"SELECT name FROM example_table WHERE pid=?\"\nresult = cursor.execute(sql, randomVariable)\nprint result\n\n",
"Validate the user input, and %s is fine. Storing your rows and putting them into a list is not a goo... | [
3,
1
] | [] | [] | [
"python",
"select",
"sql"
] | stackoverflow_0004792514_python_select_sql.txt |
Q:
Upload to website from python
I need my program (Python) to upload files (large reports) to services like (rapidshare, megaupload or easyshare) and grab the URL the site gives me (to them forward to the user)
What's easiest way ( I think Selenium, but maybe it's overkill) ?
What's the fastest ( can I do it with me... | Upload to website from python | I need my program (Python) to upload files (large reports) to services like (rapidshare, megaupload or easyshare) and grab the URL the site gives me (to them forward to the user)
What's easiest way ( I think Selenium, but maybe it's overkill) ?
What's the fastest ( can I do it with mechanize? ) ?
How would you do it?
T... | [
"I would attack this with Selenium, even it beeing really heavy, I think the easy aspect of it is worth it.\nI would do what you need to do (upload file to service) by hand while on the FireFox plugin SeleniumIDE would be recording it. Them, just export as Python and you have your code.\nSeleniumIDE:\n\nSelenium is... | [
4,
0
] | [] | [] | [
"file_upload",
"python",
"upload"
] | stackoverflow_0004791736_file_upload_python_upload.txt |
Q:
file_downloads..want to download an uploaded file
hi to all
My project is to upload an excel file and display its content in a template.
i have uploaded to an excel file in django successfully by using models.FileField .now what i want is to download that particular file at my defined location(project).I am trying... | file_downloads..want to download an uploaded file | hi to all
My project is to upload an excel file and display its content in a template.
i have uploaded to an excel file in django successfully by using models.FileField .now what i want is to download that particular file at my defined location(project).I am trying to click on that uploaded file but it is giving me err... | [
"Shot in the dark, but omit the last slash in the url? Usually that indicates that you want a directory.\n"
] | [
0
] | [] | [] | [
"django",
"file_upload",
"python"
] | stackoverflow_0004792668_django_file_upload_python.txt |
Q:
Speeding up string splitting and concatenation
I'm trying to solve Project Euler's problem #35
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
How many circular primes are there below one million?
This is my solution:
import numpy as np
d... | Speeding up string splitting and concatenation | I'm trying to solve Project Euler's problem #35
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
How many circular primes are there below one million?
This is my solution:
import numpy as np
def problem(n=100):
circulars = np.array([], np.... | [
"\nUse a set for membership testing instead of an array. The hash lookup will be O(1) instead of O(n). This is the biggest bottleneck.\nBreak out of the loop as soon as you see that it's not a circular prime instead of trying the other rotations. This is another bottleneck.\n\n\nHere, I've isolated the circularity ... | [
8
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0004793247_primes_python.txt |
Q:
gui design question
I use tkinter, but my question is probably general.
This is the first time I'm designing GUI. Each of my objects is modeled as a class. I don't understand how to tie the GUI class hierarchy with the rest of the class hierarchy.
For example, I have creatures:
# this is before I had any GUI in my... | gui design question | I use tkinter, but my question is probably general.
This is the first time I'm designing GUI. Each of my objects is modeled as a class. I don't understand how to tie the GUI class hierarchy with the rest of the class hierarchy.
For example, I have creatures:
# this is before I had any GUI in my code
class Creature:
d... | [
"The generally accepted pattern for this is called model/view/controller. You have a controller object that both knows about all the creatures (your \"model\") and about the GUI (your \"view\"). The controller is then responsible for connecting the two. For example, your view could have a \"draw_creature\" method w... | [
4
] | [] | [] | [
"design_patterns",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004791810_design_patterns_python_tkinter_user_interface.txt |
Q:
Are variables in python functions reinitialized with each function call?
Assume I have two functions
def myfunction1(number):
biglist = [1,2,3,4,5,6,7,8,9]
print number*biglist
biglist = [1,2,3,4,5,6,7,8,9]
def myfunction2(number, biglist):
print number*biglist
I time them with ipython's magic %t... | Are variables in python functions reinitialized with each function call? | Assume I have two functions
def myfunction1(number):
biglist = [1,2,3,4,5,6,7,8,9]
print number*biglist
biglist = [1,2,3,4,5,6,7,8,9]
def myfunction2(number, biglist):
print number*biglist
I time them with ipython's magic %timeit:
In [5]: %timeit myfunction2(number, biglist)
1000000 loops, best of 3:... | [
"Python can't do what you suggest without doing some quite complicated analysis. the assignment statement is just an assignment statement if i type x=3 twice in the interpreter i expect x to be 3 just after i type it regardless of what i have done to x in between... this is really no different\nto illustrate - that... | [
2,
0,
0
] | [] | [] | [
"function_calls",
"python",
"timeit"
] | stackoverflow_0004791768_function_calls_python_timeit.txt |
Q:
Python: how can I get a thread to kill itself after a timeout?
I'm writing a multi threaded Python app that makes many TCP connections to servers. Each connection is done on a separate thread. Sometimes the thread hangs for a long time which I don't want. How can I get the thread to kill itself after some given ti... | Python: how can I get a thread to kill itself after a timeout? | I'm writing a multi threaded Python app that makes many TCP connections to servers. Each connection is done on a separate thread. Sometimes the thread hangs for a long time which I don't want. How can I get the thread to kill itself after some given time period? From the main thread how can I determine that the child t... | [
"Short answer: Just make the def run() end.\nSo, if you are waiting for data from a socket, do it with timeout, then if timeout occur just break the while that you should have, and the thread will be killed.\nYou can check from main thread if a thread is alive with isAlive() method.\n"
] | [
5
] | [] | [] | [
"multithreading",
"python",
"ubuntu_9.10"
] | stackoverflow_0004791815_multithreading_python_ubuntu_9.10.txt |
Q:
urllib.urlopen won't execute on a thread
I'm working with threads and I need to download a website with a thread. I also have a thread that sends the petition to the site but doesn't wait for an answer.
The one that doesn't wait is this:
class peticion(Thread):
def __init__(self, url):
Thread.__init__(... | urllib.urlopen won't execute on a thread | I'm working with threads and I need to download a website with a thread. I also have a thread that sends the petition to the site but doesn't wait for an answer.
The one that doesn't wait is this:
class peticion(Thread):
def __init__(self, url):
Thread.__init__(self)
self.url = url
def run(self... | [
"It appear to just be a problem with the URL, the code is fine and it does not appear to do something wrong.\nI bet you have some type of problem from the website, maybe a 404 or similar.\nTry opening something in localhost, just to test.\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"urllib"
] | stackoverflow_0004768052_multithreading_python_urllib.txt |
Q:
Regex match for a non-english language in Python
I'm trying to capture and match russian language characters in a python script. Since russian characters don't fall in [a-Z] type, what regex should I should to match them. I can't use a (.*) because it would match everything.
linkpat = re.compile('name=[a-Z]+;size... | Regex match for a non-english language in Python | I'm trying to capture and match russian language characters in a python script. Since russian characters don't fall in [a-Z] type, what regex should I should to match them. I can't use a (.*) because it would match everything.
linkpat = re.compile('name=[a-Z]+;size=[0-9]+')
| [
"Use unicode flag:\nre.compile('name=\\w+;size=\\d+', re.U)\n\nthis would also match any letter in any language (plus underscore), not just Russian, though.\n",
"You can try \\w with the correct LOCALE\n",
"Use character classes, which are locale dependent\n"
] | [
5,
1,
0
] | [] | [] | [
"python",
"python_2.x",
"regex",
"unicode"
] | stackoverflow_0004794326_python_python_2.x_regex_unicode.txt |
Q:
Access a method's local variables in Python
Was going through a Python Tutorial and have asked a related question here(Code from my previous example and thanks to @emmanuel)
Code:
import math, time
class PrimeFactor:
def __init__(self):
pass
def isprime(self,number):
start=time.clock()
... | Access a method's local variables in Python | Was going through a Python Tutorial and have asked a related question here(Code from my previous example and thanks to @emmanuel)
Code:
import math, time
class PrimeFactor:
def __init__(self):
pass
def isprime(self,number):
start=time.clock()
fnum = [1,]
print "Reticulating Spli... | [
"You need:\nprint eg.isprime(num)[2]\n\n(your method is returning a tuple, and you need the third member, that's all)\n",
"The problem with your modification is that you're duplicating the calculus. I understand you just want to get the calculated factors, which just involves creating fnum as an attribute:\nimpor... | [
3,
3,
2
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004794334_oop_python.txt |
Q:
Python list does not shuffle in a loop
I'm trying to create an randomized list of keys by iterating:
import random
keys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys
This works perfect. However, if I put it in a loop and capture the output:
a = []
for x in range(10):
random.shuffle(keys)
a.... | Python list does not shuffle in a loop | I'm trying to create an randomized list of keys by iterating:
import random
keys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys
This works perfect. However, if I put it in a loop and capture the output:
a = []
for x in range(10):
random.shuffle(keys)
a.append(keys)
I am getting 10 times of the s... | [
"The problem is that you are shuffling the list in place and then adding the reference of the list to the combined list. Thus you end up with same list structure 10 times.\n\"Fundamental change\" is that the list has to be copied before appending it.\nHere is a bit more \"pythonic\" way of achieving the same result... | [
16,
3
] | [] | [] | [
"for_loop",
"python",
"random"
] | stackoverflow_0004794663_for_loop_python_random.txt |
Q:
selecting the earliest entry in a list
If I have a list with people's names and dates, and I want only to keep the entry for the earliest date per person how do I do that? I want the final list to be alphabetical by last name, then first name and only contain the entry with the earliest date at the end.
Here is a... | selecting the earliest entry in a list | If I have a list with people's names and dates, and I want only to keep the entry for the earliest date per person how do I do that? I want the final list to be alphabetical by last name, then first name and only contain the entry with the earliest date at the end.
Here is an example of the list and what I tried, but ... | [
"Try\nL1.sort()\n[next(j) for i, j in itertools.groupby(L1, lambda x: x.rsplit(\",\", 1)[0])]\n\nYour code does not work since you are searching L2 for item.split(',')[:2], which is only the name. But the strings in the list consist of the name and the year -- that's why the not in always yields True.\n",
">>> f... | [
2,
0,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0004794850_list_python_sorting.txt |
Q:
How to disable Django's CSRF protection behind a proxy
I need to run a Django system (let's call it Alfred) behind a Proxy. Both are on the same network. As Proxy I use yuri vandermeer's django-httpproxy. (see his page yvandermeer.net)
Both Systems running Django version 1.2.4
Both systems are in the same (closed)... | How to disable Django's CSRF protection behind a proxy | I need to run a Django system (let's call it Alfred) behind a Proxy. Both are on the same network. As Proxy I use yuri vandermeer's django-httpproxy. (see his page yvandermeer.net)
Both Systems running Django version 1.2.4
Both systems are in the same (closed) network and also on the same IP. I have the proxy running o... | [
"You can use the @csrf_exempt decorator on the view functions to disable csrf for that view.\nSee the documentation\n",
"The fault was all on my side. By checking the server logs I realized that not Alfred was throwing the error but the Proxy (django-httpproxy). Probably, because both servers are running on local... | [
3,
0
] | [] | [] | [
"django",
"django_admin",
"django_authentication",
"proxy",
"python"
] | stackoverflow_0004791920_django_django_admin_django_authentication_proxy_python.txt |
Q:
Python encoding conversion
I wrote a Python script that processes CSV files with non-ascii characters, encoded in UTF-8. However the encoding of the output is broken. So, from this in the input:
"d\xc4\x9bjin hornictv\xc3\xad"
I get this in the output:
"d\xe2\x99\xafjin hornictv\xc2\xa9\xc6\xaf"
Can you suggest ... | Python encoding conversion | I wrote a Python script that processes CSV files with non-ascii characters, encoded in UTF-8. However the encoding of the output is broken. So, from this in the input:
"d\xc4\x9bjin hornictv\xc3\xad"
I get this in the output:
"d\xe2\x99\xafjin hornictv\xc2\xa9\xc6\xaf"
Can you suggest where the encoding error might c... | [
"It seems adding force_utf8 = True argument to the MARCReader constructor solved the problem:\nreader = MARCReader(inputFile, to_unicode = True, force_utf8 = True)\n\nAccording to the inspection of the source code (via inspect) it does something like:\nstring.decode(\"utf-8\", \"strict\")\n\n",
"You can try to op... | [
2,
0
] | [] | [] | [
"marc",
"python",
"python_2.x",
"unicode"
] | stackoverflow_0004793893_marc_python_python_2.x_unicode.txt |
Q:
Unit testing Django JSON View
I'm trying to write some unit tests for some Django json_view views and I'm having trouble passing the json_string to the view. I posted a related question yesterday about passing a json string to a Django view from the JS, the issue was that in my JS I was just passing the json strin... | Unit testing Django JSON View | I'm trying to write some unit tests for some Django json_view views and I'm having trouble passing the json_string to the view. I posted a related question yesterday about passing a json string to a Django view from the JS, the issue was that in my JS I was just passing the json string where I needed to be passing the ... | [
"Final edit\nI originally stated that header HTTP_X_REQUESTED_WITH='XMLHttpRequest' was necessary in the post call but this is currently false while in tests. This header is necessary for the csrf middleware but csrf is disabled in tests. However, I still believe it is a good practice to put in test even if middlew... | [
9,
4
] | [] | [] | [
"ajax",
"django",
"json",
"python",
"unit_testing"
] | stackoverflow_0004794457_ajax_django_json_python_unit_testing.txt |
Q:
Django SYNCDB failes when adding super-user (Windows 7, mySQL, Django 1.2.4, mySQL 5.5)
syncdb fails when creating super user
Django: v 1.2.4
Python: 2.6
MySQL Server: 5.5
Windows 7
Extra: MySQL-Python v1.2.3
What steps will reproduce the problem?
1. install the above programs
2. create a project
3. run syncdb
Not... | Django SYNCDB failes when adding super-user (Windows 7, mySQL, Django 1.2.4, mySQL 5.5) | syncdb fails when creating super user
Django: v 1.2.4
Python: 2.6
MySQL Server: 5.5
Windows 7
Extra: MySQL-Python v1.2.3
What steps will reproduce the problem?
1. install the above programs
2. create a project
3. run syncdb
Note: I have installed mySQL to support UTF 8. I also create the mysite_db database using CREATE... | [
"Looks like you have unicode characters somewhere in your models.py or a fixture. Convert the files to UTF-8 and add a comment as the very first line:\n#coding-utf-8\n\nAlso, before unicode strings add u, like this:\nname = CharField(maxlength=255, default=u\"утф-8 строка\");\n\n",
"It looks like your login on yo... | [
0,
0
] | [] | [] | [
"django",
"mysql",
"python",
"syncdb",
"windows_7"
] | stackoverflow_0004795045_django_mysql_python_syncdb_windows_7.txt |
Q:
Icon overlay issue with Python
I found some examples and topics on this forum about the way to implement an icon overlay handler with Python 2.7 & the win32com package but it does not work for me and I don't understand why.
I create the DLL and I have no error when I register it. I have also tried directly with t... | Icon overlay issue with Python | I found some examples and topics on this forum about the way to implement an icon overlay handler with Python 2.7 & the win32com package but it does not work for me and I don't understand why.
I create the DLL and I have no error when I register it. I have also tried directly with the script but it's the same. It's li... | [
"problem solved. i guess something was badly initialized but now it works.\nMy wish is to make something like the dropBox service.\ni need to be able to update the icon of a given file according to its upload status. I will create a class for each state (uploading, uploaded, failed) that will implements the IID_ISh... | [
0
] | [] | [] | [
"com",
"py2exe",
"python",
"shell",
"windows"
] | stackoverflow_0004775020_com_py2exe_python_shell_windows.txt |
Q:
Methods of sending web-generated config files to servers and restarting services
We're writing a web-based tool to configure our services provided by multiple servers. This includes interfaces configuration, dhcp configs etc. etc.
Having configs in database and views that generate proper output, how to send it/mak... | Methods of sending web-generated config files to servers and restarting services | We're writing a web-based tool to configure our services provided by multiple servers. This includes interfaces configuration, dhcp configs etc. etc.
Having configs in database and views that generate proper output, how to send it/make it available for servers?
I'm thinking about sending it through scp and invoking rel... | [
"I tried using Puppet for config management, mostly because of all the buzz around it. Unfortunately, I discovered (too late) that the puppetmaster scales horribly, and does not handle heterogeneous environments well. It works for tens of servers, but its inherent architecture prevents scaling.\nSo I switched to Cf... | [
1,
0,
0,
0
] | [] | [] | [
"administration",
"func",
"linux",
"python"
] | stackoverflow_0002932007_administration_func_linux_python.txt |
Q:
Retrieve HTTP POST request parameters (sent from flex app) in python
I am sending the parameters from flex application through HTTP POST request to Python/PSP script. I am able to call PSP script from flex app using HTTP POST request, but i am not able to use/retrieve these parameters in Python/PSP.
A:
You prob... | Retrieve HTTP POST request parameters (sent from flex app) in python | I am sending the parameters from flex application through HTTP POST request to Python/PSP script. I am able to call PSP script from flex app using HTTP POST request, but i am not able to use/retrieve these parameters in Python/PSP.
| [
"You probably want the cgi module from the standard library. See the documentation.\n"
] | [
2
] | [] | [] | [
"apache_flex",
"python"
] | stackoverflow_0004795295_apache_flex_python.txt |
Q:
plot time of day vs date in matplotlib
I want to plot, in a specific few ways, dates on the x axis and time of day on the y axis, and then have either line plots or interval (floating bar) plots.
This SO answer helps
But I have a few differences from that plot and I can't get it to work. I'm actually getting th... | plot time of day vs date in matplotlib | I want to plot, in a specific few ways, dates on the x axis and time of day on the y axis, and then have either line plots or interval (floating bar) plots.
This SO answer helps
But I have a few differences from that plot and I can't get it to work. I'm actually getting the y axis to plot both the DATES as well as t... | [
"I think you're slightly confused as to exactly how matplotlib handles times and dates behind the scenes. \nAll datetimes in matplotlib are represented as simple floats. 1 day corresponds to a difference of 1.0, and the dates are in days since 1900 (if I remember correctly, anyway).\nSo, in order to plot just the t... | [
12,
2
] | [] | [] | [
"date",
"matplotlib",
"python",
"timestamp"
] | stackoverflow_0004790265_date_matplotlib_python_timestamp.txt |
Q:
Bijective relations between ranges and some constants?
Please, move this question to Code Review -area. It is better suited there because I know the code below is junk and I wanted critical feedback to complete rewrite.
How can I write the set-to-constants relations in Python? So if A in a range, then return its c... | Bijective relations between ranges and some constants? | Please, move this question to Code Review -area. It is better suited there because I know the code below is junk and I wanted critical feedback to complete rewrite.
How can I write the set-to-constants relations in Python? So if A in a range, then return its corresponding constant.
[0,10] <-> a
]10,77] <-> b
]77,\... | [
"If the list was longer than a mere three entries, I would use bisect.bisect():\nlimits = [0, 2000, 7700]\nrates = [0.1, 0.15, 0.2]\nindex = bisect.bisect(limits, sold) - 1\nif index >= 0:\n rate = rates[index]\nelse:\n # sold is negative\n\nBut this seems a bit overengineered for just three values...\nEdit: ... | [
3,
1
] | [] | [] | [
"bijection",
"python",
"set"
] | stackoverflow_0004796010_bijection_python_set.txt |
Q:
Placing elements (panels) within a wx.GridBagSizer
I'm using a gridbagsizer to place two panels within a frame.
control_panel = wx.Panel(self, id=ID_CONTROL_PANEL)
main_panel = wx.Panel(self, id=ID_MAIN_PANEL)
frame_sizer = wx.GridBagSizer(1, 1)
frame_sizer.Add(control_panel, (0, 0), (2, 5), flag=wx.EXPAND)
frame... | Placing elements (panels) within a wx.GridBagSizer | I'm using a gridbagsizer to place two panels within a frame.
control_panel = wx.Panel(self, id=ID_CONTROL_PANEL)
main_panel = wx.Panel(self, id=ID_MAIN_PANEL)
frame_sizer = wx.GridBagSizer(1, 1)
frame_sizer.Add(control_panel, (0, 0), (2, 5), flag=wx.EXPAND)
frame_sizer.Add(main_panel, (2, 0), (5, 5), flag=wx.EXPAND)
f... | [
"Personally, I would use a BoxSizer in VERTICAL orientation. Here's a simple example:\nimport wx\n\nclass MyForm(wx.Frame):\n\n def __init__(self):\n wx.Frame.__init__(self, None, wx.ID_ANY, \"Tutorial\")\n\n # Add a panel so it looks the correct on all platforms\n panel = wx.Panel(self, wx.... | [
2,
1
] | [] | [] | [
"python",
"sizer",
"user_interface",
"wxpython"
] | stackoverflow_0004700967_python_sizer_user_interface_wxpython.txt |
Q:
Customizing a Django Form Field in Admin Based on Value
How do you customize the display of a form in Django's admin based on a form field's value? For example, I have a field whose default value is "0". If the field has been set to a non-zero value, I want to show an additional "Edit" link on the form, which woul... | Customizing a Django Form Field in Admin Based on Value | How do you customize the display of a form in Django's admin based on a form field's value? For example, I have a field whose default value is "0". If the field has been set to a non-zero value, I want to show an additional "Edit" link on the form, which would link to a separate page allowing edit other fields related ... | [
"Just did a shell session typing in random variables (ipython ftw) and found this:\nboundfield.data = data\nboundfield.field.initial = initial\n\n{% for field in form %}\n {% if field.data != field.field.initial %}Not Initial{% endif %}\n{% endfor %}\n\nGive it a shot!\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0004796331_django_django_admin_django_forms_django_templates_python.txt |
Q:
How to implement pause (and more) functionality?
My apologies beforehand for the length of the question, I didn't want to leave anything out.
Some background information
I'm trying to automate a data entry process by writing a Python application that uses the Windows API to simulate keystrokes, mouse movement and ... | How to implement pause (and more) functionality? | My apologies beforehand for the length of the question, I didn't want to leave anything out.
Some background information
I'm trying to automate a data entry process by writing a Python application that uses the Windows API to simulate keystrokes, mouse movement and window/control manipulation. I have to resort to this ... | [
"Keep in mind that although in your level of abstraction, \"executing a keystroke\" is a single atomic operation, it's implemented on the machine as a rather complicated sequence of machine instructions. So, pausing a thread at arbitrary points could lead to things being in an indeterminate state. Sending SIGSTOP i... | [
4,
2,
1,
0
] | [] | [] | [
"multithreading",
"python",
"windows"
] | stackoverflow_0004769432_multithreading_python_windows.txt |
Q:
Django - ModelForm is saving even though data is invalid
Sort of.
I have a modelform defined like so:
class EditUserForm(UserForm):
def __init__(self,data=None,instance=None):
UserForm.__init__(self,data=data,instance=instance)
del self.fields['username']
I did this because I wanted to exclude... | Django - ModelForm is saving even though data is invalid | Sort of.
I have a modelform defined like so:
class EditUserForm(UserForm):
def __init__(self,data=None,instance=None):
UserForm.__init__(self,data=data,instance=instance)
del self.fields['username']
I did this because I wanted to exclude the username field from displaying on my EditUserForm but bec... | [
"Your assumption is right. Upon validation, the ModelForm updates the given instance (user) with the given data, leaving it in an invalid state.\nYou could:\n\ntry to create a copy of user,\nreload the user from database,\nor store user.first_name in a temporary variable and set it back upon validation failure\n\nE... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0004789780_django_django_forms_django_templates_python.txt |
Q:
Urllib trouble across platforms
On Linux, urllib.urlopen("https://www.facebook.com/fql.php?query=SELECT first_name FROM user") will have the spaces automatically quoted and run smoothly.
(By the way, the URL is fictional)
However on mac, this is not the case. Somehow the URL is not escaped, and an error would be t... | Urllib trouble across platforms | On Linux, urllib.urlopen("https://www.facebook.com/fql.php?query=SELECT first_name FROM user") will have the spaces automatically quoted and run smoothly.
(By the way, the URL is fictional)
However on mac, this is not the case. Somehow the URL is not escaped, and an error would be thrown. I have checked both python ver... | [
"urlopen documentation doesn't promise you to escape anything. Use urllib.quote() to escape it yourself.\n"
] | [
6
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0004796720_networking_python.txt |
Q:
how to display graphs using canvas element
While learning graph algorithms and canvas HTML element it stuck me that i should have a small graph library of my own in javascript which shows the graphs using canvas element can you point me in right direction so as i can read some code[js/python] as on how to display ... | how to display graphs using canvas element | While learning graph algorithms and canvas HTML element it stuck me that i should have a small graph library of my own in javascript which shows the graphs using canvas element can you point me in right direction so as i can read some code[js/python] as on how to display the graphs and write my own little lib.
PS : i m... | [
"There are quite a few ways to display graphs using various layout algorithms. Two of the primary ones are a Force-Directed layout algorithm, which can be a continuous layout algorithm using a push-pull principle. Next is the GEM layout algorithm which uses a rudimentary physics approach to determine the best \"fit... | [
5,
2,
1
] | [] | [] | [
"algorithm",
"graph_theory",
"html",
"javascript",
"python"
] | stackoverflow_0004779409_algorithm_graph_theory_html_javascript_python.txt |
Q:
Getting specific data from list of dictionaries in Python using dot notation
I have a list of dictionaries and strings like so:
listDict = [{'id':1,'other':2}, {'id':3,'other':4},
{'name':'Some name','other':6}, 'some string']
I want a list of all the ids (or other attributes) from the dictio... | Getting specific data from list of dictionaries in Python using dot notation | I have a list of dictionaries and strings like so:
listDict = [{'id':1,'other':2}, {'id':3,'other':4},
{'name':'Some name','other':6}, 'some string']
I want a list of all the ids (or other attributes) from the dictionaries via dot operator. So, from the given list I would get the list:
listDict.id... | [
"python doesn't work this way. you'd have to redefine your listDict. the built-in list type doesn't support such access. the simpler way is just to get the new lists like this:\n>>> ids = [d['id'] for d in listDict if isinstance(d, dict) and 'id' in d]\n>>> ids\n[1, 3]\n\nP.S. your data structure seems to be awfull... | [
4,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004796787_list_python.txt |
Q:
Move items from one QListWidget to another
I have to QListWidgets, one source list, one destiny list and one button. Whenever the button is clicked, I want the selected item(s) from the source list to be removed and inserted into the destiny list. I tried to source_list.removeWidgetItem(aSelectedItem) but that doe... | Move items from one QListWidget to another | I have to QListWidgets, one source list, one destiny list and one button. Whenever the button is clicked, I want the selected item(s) from the source list to be removed and inserted into the destiny list. I tried to source_list.removeWidgetItem(aSelectedItem) but that does not even do a thing. :( What am I doing wrong?... | [
"takeItem will take the item from the source_list and give you a pointer to it you can use to append it to your destination list. Something like:\nsource_list = new QListWidget();\ndest_list = new QListWidget();\nnew QListWidgetItem(tr(\"Oak\"), source_list);\nnew QListWidgetItem(tr(\"Birch\"), source_list);\nconn... | [
5
] | [] | [] | [
"pyqt",
"python",
"qlistwidget",
"qt"
] | stackoverflow_0004797221_pyqt_python_qlistwidget_qt.txt |
Q:
lighttpd, mod_rewrite and web.py unexpected behavior
I have configured lighttpd to work with web.py. Now I want to process all requests in the form mysite.com/scripts/* via my web.py script. This is how the related part of lighttpd.conf looks like:
fastcgi.server = ("/code.py" =>
(("socket" => "/var/tmp/lighttpd/f... | lighttpd, mod_rewrite and web.py unexpected behavior | I have configured lighttpd to work with web.py. Now I want to process all requests in the form mysite.com/scripts/* via my web.py script. This is how the related part of lighttpd.conf looks like:
fastcgi.server = ("/code.py" =>
(("socket" => "/var/tmp/lighttpd/fastcgi.socket",
"bin-path" => "/var/www/code.py",
"max... | [
"\"/scripts/test\" and \"/test\" are matched by (.*) as whole. If you want to match only the \"test\" part of both URLs, you may write something like this.\nurls = (\n r'(.*)/(.*)', 'hello',\n)\n\napp = web.application(urls, globals(), True)\n\nclass hello(object):\n def GET(self, x, y):\n return 'i have recei... | [
0
] | [] | [] | [
"lighttpd",
"mod_rewrite",
"python",
"web.py"
] | stackoverflow_0004533109_lighttpd_mod_rewrite_python_web.py.txt |
Q:
Problem solving the max and min from an input file data
I am new with python and i need a little help with my python script named search_max.py.
It opens a file "xyz" format and then search for the min and max of each coord. The problem is when i do the same with an awk script i don't get the same resuts!!!
I wond... | Problem solving the max and min from an input file data | I am new with python and i need a little help with my python script named search_max.py.
It opens a file "xyz" format and then search for the min and max of each coord. The problem is when i do the same with an awk script i don't get the same resuts!!!
I wonder if there is a problem with the type of data or string oper... | [
"The reason why your code does not work as expected is given by eumiro in his above comment.\nThere is an far easier approach for this in Python though: Use NumPy. Example code for maxima and minima of each column of your file would be\nimport numpy\na = numpy.loadtxt(\"peamorphe.xyz\", skiprows=2, usecols=(1, 2,... | [
5
] | [] | [] | [
"file",
"find",
"input",
"max",
"python"
] | stackoverflow_0004797356_file_find_input_max_python.txt |
Q:
Tracking object allocation in python
Is there any method I can override that will allow me to use print statements / pdb / etc. to keep track of every time an instance of my class is allocated? While unpickling some objects I am seeming to get some that never have either __setstate__ or __init__ called on them. I ... | Tracking object allocation in python | Is there any method I can override that will allow me to use print statements / pdb / etc. to keep track of every time an instance of my class is allocated? While unpickling some objects I am seeming to get some that never have either __setstate__ or __init__ called on them. I tried overriding __new__ and printing out ... | [
"(This is more of a comment than an answer.)\nQuoting Guido's Unifying types and classes in Python 2.2:\n\nThere are situations where a new instance is created without calling __init__ (for example when the instance is loaded from a pickle). There is no way to create a new instance without calling __new__ (although... | [
5,
0,
0
] | [] | [] | [
"allocation",
"creation",
"python"
] | stackoverflow_0004797418_allocation_creation_python.txt |
Q:
ListProperty vs StringListProperty on Google App Engine
I want to store lists of integers (user ids), should I make them strings and use a StringListProperty, or just use a ListProperty, I'm wondering what is more optimized, the specific StringListProperty of the heterogeneous ListProperty (when used with only Int... | ListProperty vs StringListProperty on Google App Engine | I want to store lists of integers (user ids), should I make them strings and use a StringListProperty, or just use a ListProperty, I'm wondering what is more optimized, the specific StringListProperty of the heterogeneous ListProperty (when used with only Integers).
I will need to add users to the list until it reaches... | [
"StringListProperty is just a very thin wrapper around ListProperty. there's no meaningful difference other than element type.\nfrom the code itself:\nclass StringListProperty(ListProperty):\n def __init__(self, verbose_name=None, default=None, **kwds):\n super(StringListProperty, self).__init__(basestring,\n ... | [
10
] | [] | [] | [
"bigtable",
"datastore",
"google_app_engine",
"list",
"python"
] | stackoverflow_0004797433_bigtable_datastore_google_app_engine_list_python.txt |
Q:
Generating a graph with multiple (sets of multiple sets of multiple) X-axis data sets
I am looking for a way to generate a graph with multiple sets of data on the X-axis, each of which is divided into multiple sets of multiple sets. I basically want to take this graph and place similar graphs side by side with it... | Generating a graph with multiple (sets of multiple sets of multiple) X-axis data sets | I am looking for a way to generate a graph with multiple sets of data on the X-axis, each of which is divided into multiple sets of multiple sets. I basically want to take this graph and place similar graphs side by side with it. I am trying to graph the build a graph of the duration (Y-axis) of the same jobs (0-3) w... | [
"Here's some Python code that will produce what you're looking for. (The example uses 3 configurations rather than 2 to make sure the code was fairly general.)\nimport matplotlib.pyplot as plt\nimport random\n\nnconfigs, njobs, nservers = 3, 4, 4\n\nwidth = .9/(nconfigs*njobs) \njob_colors = [(0,0,1), (0,1,0), (1... | [
6,
0,
0
] | [] | [] | [
"graphing",
"matplotlib",
"perl",
"python"
] | stackoverflow_0001242270_graphing_matplotlib_perl_python.txt |
Q:
BeautifulSoup (Python) and parsing HTML table
##### Update ###### : renderContents() instead of contents[0] did the trick. I will still leave it open if someone can provide a better, elegant solution!
I am trying to parse a number of Web pages for the desired data. The table doesn't have a class/ID tag. So I have... | BeautifulSoup (Python) and parsing HTML table | ##### Update ###### : renderContents() instead of contents[0] did the trick. I will still leave it open if someone can provide a better, elegant solution!
I am trying to parse a number of Web pages for the desired data. The table doesn't have a class/ID tag. So I have to search for 'website' in tr contents.
Problem a... | [
"I answered a similar question here . Hope it will help you.\nA lay man solution:\nalltables = soup.findAll( \"table\", {\"border\":\"2\", \"width\":\"100%\"} )\n\nt = [x for x in soup.findAll('td')]\n\n[x.renderContents().strip('\\n') for x in t]\n\nOutput:\n['Website',\n 'Last Visited',\n 'Last Loaded',\n '<a hre... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"html_table",
"python"
] | stackoverflow_0004797085_beautifulsoup_html_parsing_html_table_python.txt |
Q:
How to Customize the full text search function provided by postgresql
I am trying to customize the postgresql full text search functionality so that
For example, I can enter "Stouffers" and get a match on Stouffer's frozen foods. If I leave off one of the "f"s and spell it "Stoufers" I don't get a match. That's ... | How to Customize the full text search function provided by postgresql | I am trying to customize the postgresql full text search functionality so that
For example, I can enter "Stouffers" and get a match on Stouffer's frozen foods. If I leave off one of the "f"s and spell it "Stoufers" I don't get a match. That's one of the things that the customized text search is supposed to handle. I... | [
"Maybe you can try using the ISpell dictionary for postgresql or Tsearch2 which has some spelling correction module.\n",
"Or get a standalone search engine such as Solr or Xapian with stemming, spelling, phonetic etc.\nDjango-haystack brings you both of them.\n"
] | [
1,
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0004794425_django_postgresql_python.txt |
Q:
Webpy: how to set http status code to 300
Maybe it is a stupid question but I cannot figure out how to a http status code in webpy.
In the documentation I can see a list of types for the main status codes, but is there a generic function to set the status code?
I'm trying to implement an unAPI server and it's requ... | Webpy: how to set http status code to 300 | Maybe it is a stupid question but I cannot figure out how to a http status code in webpy.
In the documentation I can see a list of types for the main status codes, but is there a generic function to set the status code?
I'm trying to implement an unAPI server and it's required to reply with a 300 Multiple Choices to a ... | [
"The way web.py does this for 301 and other redirect types is by subclassing web.HTTPError (which in turn sets web.ctx.status). For example:\nclass MultipleChoices(web.HTTPError):\n def __init__(self, choices):\n status = '300 Multiple Choices'\n headers = {'Content-Type': 'text/html'}\n dat... | [
17
] | [] | [] | [
"http_headers",
"http_status_codes",
"python",
"web.py"
] | stackoverflow_0004797704_http_headers_http_status_codes_python_web.py.txt |
Q:
XMPP server in python
I'm looking hard but I cannot find any XMPP server in python with the following features:
using epoll, just like http://www.gevent.org/
supporting BOSH
modular design
use little RAM/CPU for up to 1000 users
more important than the previous requirement: the CPU/RAM usage must be predictable
... | XMPP server in python | I'm looking hard but I cannot find any XMPP server in python with the following features:
using epoll, just like http://www.gevent.org/
supporting BOSH
modular design
use little RAM/CPU for up to 1000 users
more important than the previous requirement: the CPU/RAM usage must be predictable
Prosody looks quite good fe... | [
"For a rough idea of how Prosody is performance-wise, see this post on their ML. https://groups.google.com/d/topic/prosody-users/SlXpfwJfgY4/discussion\n",
"xmpp.org uses Prosody, any other questions? :P\nbtw, if you want to toy with it a little, you can always run prosody using luajit (didn't test that myself, b... | [
3,
1
] | [] | [] | [
"lua",
"python",
"xmpp"
] | stackoverflow_0004746015_lua_python_xmpp.txt |
Q:
What could cause a python module to be imported twice?
As far as I understand, a python module is never imported twice, i.e. the code in the module only gets executed the first time it is imported. Subsequent import statements just add the module to the scope of the import.
I have a module called "TiledConvC3D.py"... | What could cause a python module to be imported twice? | As far as I understand, a python module is never imported twice, i.e. the code in the module only gets executed the first time it is imported. Subsequent import statements just add the module to the scope of the import.
I have a module called "TiledConvC3D.py" that seems to be imported multiple times though. I use pdb ... | [
"A Python module can be imported twice if the module is found twice in the path. For example, say your project is laid out like so:\n\nsrc/\n\npackage1/\n\nspam.py\neggs.py\n\n\n\nSuppose your PYTHONPATH (sys.path) includes src and src/package1:\nPYTHONPATH=/path/to/src:/path/to/src/package1\n\nIf that's the case, ... | [
38
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0004798589_import_module_python.txt |
Q:
Doing math with Python lists
I have output like this:
LL= [['a', 2, 3, 4, 13], ['b', 6, 7, 8, 13], ['c', 10, 11, 12, 13]]
Instead of "13", I would like to get maximum of elements by "row" using 2, 3 ,4
where ['a', 2, 3, 4, 13] would be 4
['b', 6, 7, 8, 13], would be 8.
EDIT: I need to replace "13" with the ma... | Doing math with Python lists | I have output like this:
LL= [['a', 2, 3, 4, 13], ['b', 6, 7, 8, 13], ['c', 10, 11, 12, 13]]
Instead of "13", I would like to get maximum of elements by "row" using 2, 3 ,4
where ['a', 2, 3, 4, 13] would be 4
['b', 6, 7, 8, 13], would be 8.
EDIT: I need to replace "13" with the max value.
Then add "14" after 13
f... | [
"compute maximum of all but first and last element:\nfor row in LL:\n print max(row[1:-1])\n\nadd 14 to end of each row:\nfor row in LL:\n row.append(14)\n\n",
"Is this in the directions what you are looking for?\nLL= [['a', 2, 3, 4, 13], ['b', 6, 7, 8, 13], ['c', 10, 11, 12, 13]]\n\nfor row in LL:\n row[-1]... | [
5,
4
] | [] | [] | [
"math",
"python"
] | stackoverflow_0004798288_math_python.txt |
Q:
PyFlakes for Javascript?
Is there any such standalone package for Javascript, like PyFlakes for Python? I see there is JsLint, but it looks like it depends on some external things like Rhino.
I prefer something basic&compact like PyFlakes, because it shows me 80% of bugs I make and has only 20% (or even less) of c... | PyFlakes for Javascript? | Is there any such standalone package for Javascript, like PyFlakes for Python? I see there is JsLint, but it looks like it depends on some external things like Rhino.
I prefer something basic&compact like PyFlakes, because it shows me 80% of bugs I make and has only 20% (or even less) of complexity of other tools like ... | [
"If you want a standalone version of JSLint, take a look at my jslint4java project. It embeds rhino and JSLint into an executable jar file.\nThe is also an example of using it with emacs in this gist.\n",
"In JSLInt there is an 'Assume Rhino' option on JSLint which, when set to true assumes that Rhino is present ... | [
2,
1
] | [] | [] | [
"javascript",
"jslint",
"pyflakes",
"python"
] | stackoverflow_0004792847_javascript_jslint_pyflakes_python.txt |
Q:
datastore transaction restrictions
in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity):
user.cash is decreased
user.contracts is increased by the number
contracts.current_price is updated.
market.no_of_transactions is increased by 1.
i... | datastore transaction restrictions | in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity):
user.cash is decreased
user.contracts is increased by the number
contracts.current_price is updated.
market.no_of_transactions is increased by 1.
in a rdms, these would be placed within t... | [
"After a through research, I have found that a distributed transaction layer that provides a solution to the single entity group restriction has been developed in userland with the help of some google people. But so far, it is not released and is only available in java.\n",
"Let me add a quote from the Datastore ... | [
0,
0,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"transactions"
] | stackoverflow_0000836992_google_app_engine_google_cloud_datastore_python_transactions.txt |
Q:
Python list comprehension
Possible Duplicate:
List comprehension for running total
I'm trying to write a concise list comprehension statement to create a cdf:
For example:
print f([0.2, 0.3,0.1,0.4])
[0.2,0.5,0.6,1.0]
A standard procedure would look like this (I want to write a list comprehension for the func... | Python list comprehension |
Possible Duplicate:
List comprehension for running total
I'm trying to write a concise list comprehension statement to create a cdf:
For example:
print f([0.2, 0.3,0.1,0.4])
[0.2,0.5,0.6,1.0]
A standard procedure would look like this (I want to write a list comprehension for the function f()):
def f(probabilities... | [
"That operation is so common that many languages (mainly functional ones, but not only) provide abstractions for it, usually with the name scanl (it's like a reduce with intermediate results). Let's call it ireduce (\"iterative reduce\"): \ndef ireduce(f, state, it):\n for x in it:\n state = f(state, x)\n... | [
8,
6,
1
] | [] | [] | [
"functional_programming",
"list_comprehension",
"python"
] | stackoverflow_0004798657_functional_programming_list_comprehension_python.txt |
Q:
Google Chart API - Line Chart: Averaging data
I have data that maps across ~4 years on a line chart:
0 72 346 172 193 240 34 24 18 26 25 34 52 104 23 34 29 32 55 46 44 25 36 45 48 60 65 69 66 24 28 39 2 72 74 65 69 44 66 57 49 35 77 49 32 63 47 79 47
the line chart seems to limit you to 100 max value, so some of m... | Google Chart API - Line Chart: Averaging data | I have data that maps across ~4 years on a line chart:
0 72 346 172 193 240 34 24 18 26 25 34 52 104 23 34 29 32 55 46 44 25 36 45 48 60 65 69 66 24 28 39 2 72 74 65 69 44 66 57 49 35 77 49 32 63 47 79 47
the line chart seems to limit you to 100 max value, so some of my values are 'off the chart'. I figure they want yo... | [
"Let's say you had your numbers in a list l - you could do the following to scale the numbers to a percentage of the max value:\n[ float(i) * 100 / max(l) for i in l ]\n\nThen if you want to get back the original value from a value n:\nn / 100 * max(l)\n\n"
] | [
2
] | [] | [] | [
"average",
"google_visualization",
"python"
] | stackoverflow_0004798913_average_google_visualization_python.txt |
Q:
How to output coverage XML with nosetests?
I'm trying to output the coverage XML of my nosetests so they show up on Hudson. The line I'm executing is:
nosetests --with-gae -v --all-modules --with-xunit --with-coverage
I see the coverage output in the console, but there's no xml file containing the coverage data.... | How to output coverage XML with nosetests? | I'm trying to output the coverage XML of my nosetests so they show up on Hudson. The line I'm executing is:
nosetests --with-gae -v --all-modules --with-xunit --with-coverage
I see the coverage output in the console, but there's no xml file containing the coverage data. How can I get it to output the coverage xml?
| [
"Once you've run the nosetests command, there will be a .coverage data file in the directory. If you then run coverage xml, it will create a Cobertura-compatible XML file from the .coverage file.\n",
"There is a plugin written for nosetests to do just this. \nYou just have to add --with-xcoverage once this pack... | [
25,
8
] | [] | [] | [
"cobertura",
"code_coverage",
"nosetests",
"python"
] | stackoverflow_0004755131_cobertura_code_coverage_nosetests_python.txt |
Q:
Having problems getting data out of an xml element in Python
I am parsing xml output by another program.
Here's an example of the xml fragment:
<result test="Passed" stamp="2011-01-25T12:40:46.166-08:00">
<assertion>MultipleTestTool1</assertion>
<comment>MultipleTestTool1 Passed</comment>
</r... | Having problems getting data out of an xml element in Python | I am parsing xml output by another program.
Here's an example of the xml fragment:
<result test="Passed" stamp="2011-01-25T12:40:46.166-08:00">
<assertion>MultipleTestTool1</assertion>
<comment>MultipleTestTool1 Passed</comment>
</result>
I want to get the data out of the <comment> element.
Here ... | [
"Try ElementTree instead of minidom:\n>>> import xml.etree.cElementTree as et\n>>> data = \"\"\"\n... <result test=\"Passed\" stamp=\"2011-01-25T12:40:46.166-08:00\">\n... <assertion>MultipleTestTool1</assertion>\n... <comment>MultipleTestTool1 Passed</comment>\n... </result>\n... \"\"\"\n>>> ... | [
1,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004798774_python_xml.txt |
Q:
Please help parse this html table using BeautifulSoup and lxml the pythonic way
I have searched a lot about BeautifulSoup and some suggested lxml as the future of BeautifulSoup while that makes sense, I am having a tough time parsing the following table from a whole list of tables on the webpage.
I am interested i... | Please help parse this html table using BeautifulSoup and lxml the pythonic way | I have searched a lot about BeautifulSoup and some suggested lxml as the future of BeautifulSoup while that makes sense, I am having a tough time parsing the following table from a whole list of tables on the webpage.
I am interested in the three columns with varied number of rows depending on the page and the time it ... | [
">>> from lxml import html\n>>> table_html = \"\"\"\"\n... <table border=\"2\" width=\"100%\">\n... <tbody><tr>\n... <td width=\"33%\" class=\"BoldTD\">Website</td>\n... <td width=\"33%\" class=\"BoldTD\">Last Visited</td>\n... ... | [
4,
3,
2
] | [] | [] | [
"beautifulsoup",
"html_table",
"lxml",
"python"
] | stackoverflow_0004761158_beautifulsoup_html_table_lxml_python.txt |
Q:
Why can you omit the surrounding parentheses for generators in Python when passing it into a function?
I was just experimenting in Python with different syntax for passing in a generator as an argument to a function, and I realized that although I've been doing this,
>>> sum((j for j in xrange(5)))
10
this works ... | Why can you omit the surrounding parentheses for generators in Python when passing it into a function? | I was just experimenting in Python with different syntax for passing in a generator as an argument to a function, and I realized that although I've been doing this,
>>> sum((j for j in xrange(5)))
10
this works as well:
>>> sum(j for j in xrange(5))
10
This is tested on Python 2.6.6 on Linux. What's going on under th... | [
"I'm sure reading the python grammar will answer that question.\nIf you prefer plain English over grammars: PEP-289 explains it.\n"
] | [
6
] | [] | [] | [
"generator",
"language_implementation",
"python",
"syntax"
] | stackoverflow_0004799459_generator_language_implementation_python_syntax.txt |
Q:
How do I pull text from a specific text line in Python?
How would I pull text from a specific text line, inside a text file using Python?
A:
If you want to read the 10th line:
with open("file.txt") as f:
for i in range(9):
f.next()
print f.readline()
This doesn't read the whole file in memory.
... | How do I pull text from a specific text line in Python? | How would I pull text from a specific text line, inside a text file using Python?
| [
"If you want to read the 10th line:\nwith open(\"file.txt\") as f:\n for i in range(9):\n f.next()\n print f.readline()\n\nThis doesn't read the whole file in memory.\n",
"The following Python example should extract the correct line number, but it is horribly inefficient:\nf = open('file.txt')\nprint... | [
4,
0,
0
] | [] | [] | [
"editing",
"python",
"text_files"
] | stackoverflow_0004799456_editing_python_text_files.txt |
Q:
Python dictionaries, find similarities
I have a python dictionary with a thousand items. Each item is, itself, a dictionary. I'm looking for a clean and elegant way to parse through each item, and find & create templates.
Here's a simplified example of the individual dictionaries' structure:
{'id': 1,
'template... | Python dictionaries, find similarities | I have a python dictionary with a thousand items. Each item is, itself, a dictionary. I'm looking for a clean and elegant way to parse through each item, and find & create templates.
Here's a simplified example of the individual dictionaries' structure:
{'id': 1,
'template': None,
'height': 80,
'width': 120,
'len... | [
"Given dict of dicts items: \nimport itertools as it\n\nfor (height, width), itemIter in it.groupby (items.values(), lambda x: (x['height'], x['width'])):\n # in list(itemIter) you will find all items with dimensions (height, width)\n\n",
"@eumiro had an excellent core idea, namely that of using itertools.grou... | [
3,
0
] | [] | [] | [
"dictionary",
"python",
"templates",
"templating"
] | stackoverflow_0004797497_dictionary_python_templates_templating.txt |
Q:
twisted.pair.ethernet vs iptables
I need to implement some low-level IP filtering/tracking. Typically I would use iptables for this, but since I am currently using twisted in a few projects I'd consider using it's ethernet library, if it's possible. Actually, I would prefer it (it's easier to deploy than iptable... | twisted.pair.ethernet vs iptables | I need to implement some low-level IP filtering/tracking. Typically I would use iptables for this, but since I am currently using twisted in a few projects I'd consider using it's ethernet library, if it's possible. Actually, I would prefer it (it's easier to deploy than iptables rules).
Is it possible to use twisted... | [
"twisted.pair.ethernet will give you a little bit of the parsing, but it doesn't do anything for actually getting the data in the first place, nor putting it back on the network (if you don't filter it out). For that you need to talk to the tuntap system, which Twisted doesn't do anything with.\n"
] | [
1
] | [] | [] | [
"ethernet",
"iptables",
"python"
] | stackoverflow_0004798596_ethernet_iptables_python.txt |
Q:
Google App Engine Database Index
I need to store a undirected graph in a Google App Engine database.
For optimization purposes, I am thinking to use database indexes.
Using Google App Engine, is there any way to define the columns of a database table to create its index?
I will need some optimization, since my app... | Google App Engine Database Index | I need to store a undirected graph in a Google App Engine database.
For optimization purposes, I am thinking to use database indexes.
Using Google App Engine, is there any way to define the columns of a database table to create its index?
I will need some optimization, since my app uses this stored undirected graph on ... | [
"Perhaps this will help: http://code.google.com/intl/sv-SE/appengine/docs/python/datastore/queriesandindexes.html#Defining_Indexes_With_Configuration\n",
"are you actually seeing prohibitively slow queries? i'm guessing not. i suspect this is somewhat premature optimization. the app engine datastore doesn't do an... | [
3,
1
] | [] | [] | [
"database_indexes",
"google_app_engine",
"graph",
"python",
"recommendation_engine"
] | stackoverflow_0002859667_database_indexes_google_app_engine_graph_python_recommendation_engine.txt |
Q:
Django: Default ordering based on a many-to-many related field values and counts
Models look like the following:
class Weekday(models.Model):
'''
>>> for w in Weekday.objects.all():
... print w
...
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
'''
nam... | Django: Default ordering based on a many-to-many related field values and counts | Models look like the following:
class Weekday(models.Model):
'''
>>> for w in Weekday.objects.all():
... print w
...
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
'''
name = models.CharField(max_length=9)
def __unicode__(self):
return self.nam... | [
"You can only specify model fields in Meta.ordering, so if you want to implement that logic you described, you have to resort to custom manager.\nEDIT: \nYou could add some kind of weight field to your Stop model, update that field along with updating days_open and then you would be able to use ordering = ['-weight... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004798265_django_django_models_python.txt |
Q:
How do I install a user-specific configuration file with the distribute python
I'm creating a python package, and using distribute to package it as an egg. I'd like to install a user-editable configuration file for each user of my software. What is the best way to accomplish this? I'm using Python 2.6 and am ta... | How do I install a user-specific configuration file with the distribute python | I'm creating a python package, and using distribute to package it as an egg. I'd like to install a user-editable configuration file for each user of my software. What is the best way to accomplish this? I'm using Python 2.6 and am targeting the Windows platform.
| [
"Since the egg is hard to edit, it doesn't go in the egg.\nA user-editable configuration file goes in the user's HOME directory or a system-wide directory like /etc/myapp.\nYour app should search in a number of easy-to-find places. Follow the Linux guidelines for tracking down the .bashrc file for hints on how bes... | [
5,
3
] | [] | [] | [
"configuration_files",
"distribute",
"python"
] | stackoverflow_0004799298_configuration_files_distribute_python.txt |
Q:
Stop Text widget from scrolling when content is changed
I have a text widget with a scrollbar which looks something like this:
self.myWidget = Text(root)
self.myWidget.configure(state=DISABLED)
self.myWidget.pack()
self.myWidgetScrollbar = Scrollbar(root, command=self.myWidget.yview)
self.myWidget.configure(yscr... | Stop Text widget from scrolling when content is changed | I have a text widget with a scrollbar which looks something like this:
self.myWidget = Text(root)
self.myWidget.configure(state=DISABLED)
self.myWidget.pack()
self.myWidgetScrollbar = Scrollbar(root, command=self.myWidget.yview)
self.myWidget.configure(yscrollcommand=self.myWidgetScrollbar.set)
self.myWidgetScrollbar... | [
"You can safe the position and set it back after an update, like this Tcl code does:\nproc update_view {w s data} {\n # store position\n set pos [$s get]\n $w configure -state normal -yscrollcommand {}\n $w delete 1.0 end\n $w insert end $data\n $w configure -state disabled -yscrollcommand [list $s set]\n $s... | [
2,
1
] | [] | [] | [
"python",
"scrollbar",
"tkinter"
] | stackoverflow_0004704165_python_scrollbar_tkinter.txt |
Q:
Could not import Django settings into Google App Engine
Hello all you Google App Engine experts,
I have used Django a little before but am new to Google App Engine and
am trying to use it's development web server with Django for the first time.
I don't know if this is relevent but I previously had Django 1.1 an... | Could not import Django settings into Google App Engine | Hello all you Google App Engine experts,
I have used Django a little before but am new to Google App Engine and
am trying to use it's development web server with Django for the first time.
I don't know if this is relevent but I previously had Django 1.1 and
Python 2.6 on my Windows XP and even though I have uninsta... | [
"I had a similar problem and I put an empty settings.py file in my root directory and it worked.\nGood Luck\n",
"for local testing add these at the start of your main.py\nimport os, sys\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"appid.settings\"\nsys.path.append(\"/app/folder\")\n\n",
"How are you developing t... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001233326_django_google_app_engine_python.txt |
Q:
using unicode in Google translate url from python script
I'm trying to use my script to automatically using google translate apis from russian to english. Here is the code.
mytext = {some text in russian}
url = 'https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='+ mytext +'&langpair=ru%7Cen'
req... | using unicode in Google translate url from python script | I'm trying to use my script to automatically using google translate apis from russian to english. Here is the code.
mytext = {some text in russian}
url = 'https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='+ mytext +'&langpair=ru%7Cen'
request = urllib2.Request(url, None, {'Referer': 'http://www.mysi... | [
"Use\nurl = 'https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' \\\n + urllib2.quote(mytext) + '&langpair=ru%7Cen'\n\nto quote your text\n"
] | [
4
] | [] | [] | [
"api",
"google_translate",
"python",
"unicode"
] | stackoverflow_0004800313_api_google_translate_python_unicode.txt |
Q:
changing from tuple to list and vice versa
how could i change [('a', 1), ('c', 3), ('b', 2)] to ['a',1,'c',3,'b',2] and vice versa?
Thanks
A:
Going in the first direction from [('a', 1), ('c', 3), ('b', 2)] to ['a',1,'c',3,'b',2] is flattening a list. Taking the accepted answer from there and modifying for this... | changing from tuple to list and vice versa | how could i change [('a', 1), ('c', 3), ('b', 2)] to ['a',1,'c',3,'b',2] and vice versa?
Thanks
| [
"Going in the first direction from [('a', 1), ('c', 3), ('b', 2)] to ['a',1,'c',3,'b',2] is flattening a list. Taking the accepted answer from there and modifying for this example:\n>>> L = [('a', 1), ('c', 3), ('b', 2)]\n>>> list(itertools.chain(*L))\n['a', 1, 'c', 3, 'b', 2]\n\nThis uses itertools.chain which is... | [
10,
3,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004799785_list_python.txt |
Q:
Celery with Django - deployment
I am considering using celery in my project. I found a lot of information about how to use it etc. What I am interested in is how to deploy/package my solution.
I need to run two components - django app and then celeryd worker (component that sends emails). For example I would like... | Celery with Django - deployment | I am considering using celery in my project. I found a lot of information about how to use it etc. What I am interested in is how to deploy/package my solution.
I need to run two components - django app and then celeryd worker (component that sends emails). For example I would like my django app to use email_ticket ta... | [
"This is covered in the documentation here. The gist is you need to download some init scripts and setup some config. Once that's done celeryd will start on boot and you'll be off and running.\n"
] | [
4
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0004800514_celery_django_python.txt |
Q:
python regex [:alpha:]
I'm using this regex in Python:
import re
>>> ER = re.compile('^\w{0,30}$', re.U)
>>> ER.sub('.', 'Maçã')
>>>....
But a wanna catch only letters, [A-Z] does not work for me, because i need letters with accent .
Is there any way to use POSIX? [:alpha:], something like that or another sol... | python regex [:alpha:] | I'm using this regex in Python:
import re
>>> ER = re.compile('^\w{0,30}$', re.U)
>>> ER.sub('.', 'Maçã')
>>>....
But a wanna catch only letters, [A-Z] does not work for me, because i need letters with accent .
Is there any way to use POSIX? [:alpha:], something like that or another solution?
Thanks!
| [
"Modified the regex - how about\nER = re.compile(u'^[^\\W\\d_]{1,30}$', re.U)\ns = ER.sub(u'.', u'Maçã')\n\nmatches u'Maçã' but not u'Maçã01'.\n"
] | [
5
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004800665_python_regex.txt |
Q:
Google App Engine Task Queue Error using Python API
I've implemented a task queue action for a Flask + GAE project I'm playing with to learn more about Python web dev and I'm getting the following error, and I cannot track down any information about it.
----------------------------------------
Exception happened d... | Google App Engine Task Queue Error using Python API | I've implemented a task queue action for a Flask + GAE project I'm playing with to learn more about Python web dev and I'm getting the following error, and I cannot track down any information about it.
----------------------------------------
Exception happened during processing of request from ('0.1.0.2', 80)
Tracebac... | [
"Problem went away with Robert Kluin's suggestion. I'm starting up the dev server by using\npython2.5 /usr/local/bin/dev_appserver.py .\n\n"
] | [
4
] | [] | [] | [
"flask",
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0004777046_flask_google_app_engine_python_task_queue.txt |
Q:
Web2py on App Engine Local Environment: Cannot access admin interface
I have been trying to learn web2py for use on App Engine. However I cannot seem to be able to access the admin interface.
(The default page loads, when I access it from 127.0.0.1:8080. To access the admin interface, the url used should be 127.0.... | Web2py on App Engine Local Environment: Cannot access admin interface | I have been trying to learn web2py for use on App Engine. However I cannot seem to be able to access the admin interface.
(The default page loads, when I access it from 127.0.0.1:8080. To access the admin interface, the url used should be 127.0.0.1 (by default))
However when I click the admin interface link all I get ... | [
"You should set an admin password during the installation process.\nCheck this video at 00:35 or read this doc.\n",
"I don't think you'll be able to access the admin interface when the app is deployed on the remote GAE servers because admin requires access to a filesystem, and GAE doesn't allow writing to the fil... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"web2py"
] | stackoverflow_0004791832_google_app_engine_python_web2py.txt |
Q:
How to extract the first hit elements from an XML NCBI BLAST file?
Im trying to extract only the first hit from an NCBI xml BLAST file. next I would like to get only the first HSP. at the final stage I would like to get these based on best score.
to make things clear here a sample of the xml file:
<?xml version="1... | How to extract the first hit elements from an XML NCBI BLAST file? | Im trying to extract only the first hit from an NCBI xml BLAST file. next I would like to get only the first HSP. at the final stage I would like to get these based on best score.
to make things clear here a sample of the xml file:
<?xml version="1.0"?>
<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "http:... | [
"While building your own parser may be \"fun\" there is already a package out there that can parse BLAST xml files ... it can even do the intermediate calling of a local BLAST instance for you if you so desire.\nThe main site is here:\nhttp://biopython.org/wiki/Biopython\nand the XML BLAST parser is here:\nhttp://b... | [
9,
6,
1
] | [] | [] | [
"bioinformatics",
"elementtree",
"ncbi",
"python",
"xml"
] | stackoverflow_0001935385_bioinformatics_elementtree_ncbi_python_xml.txt |
Q:
Filtering / iterating through very large lists in python
If I have a list with say 10 million objects, how do I filter the list quickly. It takes about 4-5 seconds for a complete iteration thru a list comprehension. Are there any efficient data structures or libraries for this in python? Or is python not suited fo... | Filtering / iterating through very large lists in python | If I have a list with say 10 million objects, how do I filter the list quickly. It takes about 4-5 seconds for a complete iteration thru a list comprehension. Are there any efficient data structures or libraries for this in python? Or is python not suited for large sets of data?
| [
"If you have uniform types of numbers & if speed is your primary goal (and you want to use python), use a Numpy array.\n",
"Itertools is designed for efficient looping. Particularly, you might find that ifilter suits your purpose. Iterating through large data structures is always expensive, but if you only need... | [
4,
2,
0
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0004800858_data_structures_python.txt |
Q:
How to make invalidating Beaker cache work?
I have a function which is decorated with beaker cache decorator. The function is located in a module from which it is imported into the main app.
from caching import cache, my_cached_function
Now, in one function I used the decorated function:
def index():
data = m... | How to make invalidating Beaker cache work? | I have a function which is decorated with beaker cache decorator. The function is located in a module from which it is imported into the main app.
from caching import cache, my_cached_function
Now, in one function I used the decorated function:
def index():
data = my_cached_function() # no args
In another functio... | [
"You need to invalidate the cache before my_cached_function is called. See the beaker.cache.CacheManager documentation for an example.\n"
] | [
2
] | [] | [] | [
"beaker",
"bottle",
"caching",
"python"
] | stackoverflow_0004799765_beaker_bottle_caching_python.txt |
Q:
Are there any good tutorial about using buildout and pip?
I've been struggling all day to really understand how to use buildout and pip.
Watched a bunch of videos etc., but I still have a hard time figuring out the do and don't of buildout and pip.
Any help, tutorial, book is welcome.
A:
Is not the http://www.bu... | Are there any good tutorial about using buildout and pip? | I've been struggling all day to really understand how to use buildout and pip.
Watched a bunch of videos etc., but I still have a hard time figuring out the do and don't of buildout and pip.
Any help, tutorial, book is welcome.
| [
"Is not the http://www.buildout.org/ and http://pip.openplans.org/ tutorials helpful? Apart from that, there are couple of tutorials on Buildout1, PIP 2 which could be helpful for you to start.\nBest way to start, write a small buildout conf and using an existing recipe from PyPI and see how the package installs.\n... | [
6
] | [] | [] | [
"buildout",
"pip",
"python",
"virtualenv"
] | stackoverflow_0004800891_buildout_pip_python_virtualenv.txt |
Q:
Why am I getting a unicode-related ValidationError for python script on one server but not on another?
I'm running a python script to retrieve data from the Adwords API, and it runs successfully on a CentOS server. Using the same configuration file and script on a Ubuntu server, I get a unicode error. Is there s... | Why am I getting a unicode-related ValidationError for python script on one server but not on another? | I'm running a python script to retrieve data from the Adwords API, and it runs successfully on a CentOS server. Using the same configuration file and script on a Ubuntu server, I get a unicode error. Is there some configuration setting that I need to change?
Traceback (most recent call last):
File "adwords_sync.py"... | [
"Check your python, adsygoogle, and simplejson versions on each server. I'm guessing one of them is out of sync on one of your servers, causing AdWords to accept unicode strings on one but not the other (or causing the simplejson parse to generate unicode strings on one and not the other.)\nFailing that, can you c... | [
0
] | [] | [] | [
"google_ads_api",
"json",
"python",
"ubuntu",
"unicode"
] | stackoverflow_0004801150_google_ads_api_json_python_ubuntu_unicode.txt |
Q:
Django-ratings and Jquery integration?
How do I make django-ratings work with Jquery?
What I'm trying to do is allow the user to select how ever many stars they want to give the product, and to have the corresponding rating processed asynchronously. I realize this is probably basic AJAX, and I apologize if this is... | Django-ratings and Jquery integration? | How do I make django-ratings work with Jquery?
What I'm trying to do is allow the user to select how ever many stars they want to give the product, and to have the corresponding rating processed asynchronously. I realize this is probably basic AJAX, and I apologize if this is a stupid question.
Thank you in advanced.
| [
"I'm not sure if I understand your question, but is your question from the javascript side or from the model side? From javascript, I used something like this \nSTARS_ELEMENT.stars({\n callback: function(ui, type, value){\n $.post('URL_ADDRESS', {rate: value},\n function(data){\n ... | [
2,
1,
0
] | [] | [] | [
"django",
"jquery",
"python"
] | stackoverflow_0004777592_django_jquery_python.txt |
Q:
Django - decorators and error messages
This seems like a simple question but I can't seem to find a simple answer. Django seems to give this nifty simple way of limiting access to places using the permission required or login required decorators but I can't see from the Django docs how one would pass an error mes... | Django - decorators and error messages | This seems like a simple question but I can't seem to find a simple answer. Django seems to give this nifty simple way of limiting access to places using the permission required or login required decorators but I can't see from the Django docs how one would pass an error message (maybe using the messages framework). ... | [
"I think you're conflating security and permissions with Django's authentication system. For the most part, Django's tools are mainly designed for separating users into two groups: authenticated (logged in), and anonymous. This makes sense for 90% of the web sites out there, as you don't really need too much differ... | [
2,
0,
-1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004800650_django_python.txt |
Q:
How can I get a character in Python similar to Pascal readkey
In Pascal I can execute this code to get a character from keyboard input:
uses crt;
var ch: char;
begin
ch := '.';
while ch <> '\' do
begin
ch := readkey;
writeln( ch );
end;
end;
Is there a similar one in Python? :)
A:... | How can I get a character in Python similar to Pascal readkey | In Pascal I can execute this code to get a character from keyboard input:
uses crt;
var ch: char;
begin
ch := '.';
while ch <> '\' do
begin
ch := readkey;
writeln( ch );
end;
end;
Is there a similar one in Python? :)
| [
"import sys \n\ndef prog(): \n char = \"\" \n while char != \"/\": \n char = sys.stdin.read(1) \n print char\nprog()\n\n",
"You could do it by running Tkinter in the background:\nimport Tkinter\n\ndef keyPress(event, tk):\n ch = event.char\n if ch == '\\\\':\n tk.d... | [
3,
2,
0,
0
] | [] | [] | [
"character",
"pascal",
"python"
] | stackoverflow_0004799165_character_pascal_python.txt |
Q:
How to get self file name
Possible Duplicate:
python, path of script
Is there any way that i can print the self filename of a file and current location.
A:
Could __file__ be what you are looking for?
| How to get self file name |
Possible Duplicate:
python, path of script
Is there any way that i can print the self filename of a file and current location.
| [
"Could __file__ be what you are looking for?\n"
] | [
14
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004801597_file_python.txt |
Q:
My settings.py file in Django is getting too long. How do I split it into two?
How do I do that? split up 2 files?
A:
Just put it in any file you like and import it somewhere in your main settings file.
So you could set up new settings my_new_settings.py anywhere django can reach, and import it at the end of yo... | My settings.py file in Django is getting too long. How do I split it into two? | How do I do that? split up 2 files?
| [
"Just put it in any file you like and import it somewhere in your main settings file.\nSo you could set up new settings my_new_settings.py anywhere django can reach, and import it at the end of your real settings.py.\n# settings.py\n# ...\nfrom my_new_settings import *\n\n",
"These pages might help: discussion on... | [
2,
2,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004801395_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.