content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How do I update the python lib boto?
I am using python's boto script, and I haven't touched in a long time and sort of forgot basic python stuff.
How do I update the script? I'm not even sure how I installed it so please guide me to figure out what I have to do.
A:
If you have pip available: pip install -U bot... | How do I update the python lib boto? | I am using python's boto script, and I haven't touched in a long time and sort of forgot basic python stuff.
How do I update the script? I'm not even sure how I installed it so please guide me to figure out what I have to do.
| [
"If you have pip available: pip install -U boto\nIf you have easy_install available: easy_install -U boto\nOtherwise... install pip.\n"
] | [
21
] | [] | [] | [
"boto",
"python"
] | stackoverflow_0004940449_boto_python.txt |
Q:
Rebuild regex string based on match keywords in python
Example regular expression
regex = re.compile('^page/(?P<slug>[-\w]+)/(?P<page_id>[0-9]+)/$')
matches = regex.match('page/slug-name/5/')
>> matches.groupdict()
{'slug': 'slug-name', 'page_id': '5'}
Is there an easy way to pass a dict back to the regex to rebu... | Rebuild regex string based on match keywords in python | Example regular expression
regex = re.compile('^page/(?P<slug>[-\w]+)/(?P<page_id>[0-9]+)/$')
matches = regex.match('page/slug-name/5/')
>> matches.groupdict()
{'slug': 'slug-name', 'page_id': '5'}
Is there an easy way to pass a dict back to the regex to rebuild a string?
i.e. {'slug': 'new-slug', 'page_id': '6'} woul... | [
"Regex methods operate on strings. Since you have a dict, I think the string format method is a better fit:\nIn [16]: d={'slug': 'new-slug', 'page_id': '6'}\n\nIn [17]: 'page/{slug}/{page_id}'.format(**d)\nOut[17]: 'page/new-slug/6'\n\n\nThere are all sorts of more complicated regex for which the following won't wo... | [
5,
3,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004927971_python_regex.txt |
Q:
How to retrieve a specific element with from xml with python
I'm trying to read through an xml feed I'm getting, but I can't access the specific elements. I'm using python, and the python documentation is really unclear about what I should use.
Here is the feed:
<title>More eagle</title>
<summary>http://www.181.fm... | How to retrieve a specific element with from xml with python | I'm trying to read through an xml feed I'm getting, but I can't access the specific elements. I'm using python, and the python documentation is really unclear about what I should use.
Here is the feed:
<title>More eagle</title>
<summary>http://www.181.fm/winamp.plsstation=181eagle&style=&description=The%20Eagle... | [
"getElementsByTagName()\n\nreturns a list of elements. So if you want the first (or only) one, you need to use getElementsByTagName('name')[0]. \nBut this is an element object, not the text enclosed by it (which I presume you're interested in).\nSo you probably need to do something like this:\nnametag = feedxml.get... | [
1,
1
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0003188424_parsing_python_xml.txt |
Q:
Python module audiolab returns error when function is called
I need to install the Python module audiolab for a research project, and while I have managed to install it and get the module to import in the Python shell, it returns an error in calling one of the most basic functions in the module, wavread().
I am ... | Python module audiolab returns error when function is called | I need to install the Python module audiolab for a research project, and while I have managed to install it and get the module to import in the Python shell, it returns an error in calling one of the most basic functions in the module, wavread().
I am using Python2.7.1 mainly, though I did try backtracking and instal... | [
"The audiolab documentation is somewhat lacking, but wavread() requires an input file. In your code, that input is test.wav. If it doesn't exist in the working directory (usually the location of your python script), you need to provide the full path to the file.\n"
] | [
4
] | [] | [] | [
"audio",
"function",
"libsndfile",
"python",
"scikits"
] | stackoverflow_0004940708_audio_function_libsndfile_python_scikits.txt |
Q:
Why doesn't sqlalchemy modify the database when I add/remove a column?
If I run my python script, it creates the tables correctly.
However, if I add/remove a column and run the script again, it doesn't modify the database.
Why is this?
I am doing this after defining everything:
mapper(Product, products)
mapper(Cat... | Why doesn't sqlalchemy modify the database when I add/remove a column? | If I run my python script, it creates the tables correctly.
However, if I add/remove a column and run the script again, it doesn't modify the database.
Why is this?
I am doing this after defining everything:
mapper(Product, products)
mapper(Category, categories)
metadata.create_all(engine)
session = Session()
| [
"create_all only creates. It doesn't modify. \nhttp://www.sqlalchemy.org/docs/core/schema.html?highlight=create_all#sqlalchemy.schema.MetaData.create_all\nIf you've changed the columns you need to either drop/readd the table, or manually add the column outside of your script. There are tools to do this like sqlalch... | [
4,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004940839_python_sqlalchemy.txt |
Q:
Find all links inside a table
My html page has:
...
<table class="t1" ..>
<tr><td> ... <a href="">...</a> ... <a href="">..</a>
</table>
...
I have:
html = BeautifulSoup(page)
links = html.findAll('a', ?????????)
How can I find all links that are inside this table?
A:
Find the table (by class in this case), ... | Find all links inside a table | My html page has:
...
<table class="t1" ..>
<tr><td> ... <a href="">...</a> ... <a href="">..</a>
</table>
...
I have:
html = BeautifulSoup(page)
links = html.findAll('a', ?????????)
How can I find all links that are inside this table?
| [
"Find the table (by class in this case), then find all the links within it.\nhtml = BeautifulSoup(page)\ntable = html.find('table', 't1')\nlinks = table.findAll('a')\n\n",
"More efficient than a raw find, use SoupStrainer:\nhtml = BeautifulSoup(page, parseOnlyThese=SoupStrainer('table', 't1' ) )\nlinks = html.fi... | [
7,
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004940885_beautifulsoup_python.txt |
Q:
Sqlalchemy type for very long text for articles
What type should I define in my sqlalchemy definition for text for a article or blog entry? I'm using MySQL.
Column('article_text', ???)
A:
Column('article_text', sqlalchemy.UnicodeText())
That should work on any supported database, not just mysql.
| Sqlalchemy type for very long text for articles | What type should I define in my sqlalchemy definition for text for a article or blog entry? I'm using MySQL.
Column('article_text', ???)
| [
"Column('article_text', sqlalchemy.UnicodeText())\n\nThat should work on any supported database, not just mysql.\n"
] | [
11
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0004940742_mysql_python_sqlalchemy.txt |
Q:
How do I sort a column of Django elements inside a table?
How do I sort a column of Django elements inside a table?
I notice the Django Admin does this. How?
Any web resources available where I can read up on this?
*By "Django elements" I'm referring to the pluggable template objects that look like this:
{{ x.y }}... | How do I sort a column of Django elements inside a table? | How do I sort a column of Django elements inside a table?
I notice the Django Admin does this. How?
Any web resources available where I can read up on this?
*By "Django elements" I'm referring to the pluggable template objects that look like this:
{{ x.y }}
| [
"Worth having a look at the ChangeList view source code in the django admin:\nhttp://code.djangoproject.com/svn/django/branches/releases/1.2.X/django/contrib/admin/views/main.py\nThe ordering process is roughly:\n\nyou click on a column header in the admin, this reloads the page with the relevant order parameter in... | [
3,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004939866_django_python.txt |
Q:
Trouble parsing HTML using BeautifulSoup
I'm trying to use BeautifulSoup to parse some HTML in Python. Specifically, I'm trying to create two arrays of soup objects: one for the dates of postings on a website, and one for the postings themselves. However, when I use findAll on the div class that matches the postin... | Trouble parsing HTML using BeautifulSoup | I'm trying to use BeautifulSoup to parse some HTML in Python. Specifically, I'm trying to create two arrays of soup objects: one for the dates of postings on a website, and one for the postings themselves. However, when I use findAll on the div class that matches the postings, only the initial tag is returned, not the ... | [
"Which version of BeautifulSoup are you using? Version 3.1.0 performs significantly worse with real-world HTML (read: invalid HTML) than 3.0.8. This code works with 3.0.8:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\npage = urllib2.urlopen(\"http://harvardfml.com/\")\nsoup = BeautifulSoup(page)\nfor ... | [
3,
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004941190_beautifulsoup_python.txt |
Q:
How do I get redmine's activity log to show repository changes automatically?
I wrote a little python script to accept BitBucket POST callbacks of repository changes and update the local copy. That all works fine, but I noticed that redmine's activity log doesn't show those changes until I click on the repository... | How do I get redmine's activity log to show repository changes automatically? | I wrote a little python script to accept BitBucket POST callbacks of repository changes and update the local copy. That all works fine, but I noticed that redmine's activity log doesn't show those changes until I click on the repository tab.
Is there a way to trigger the activity log update programatically?
| [
"Misunderstood your question in IRC, you can find the answer to your question in the redmine faq\n"
] | [
2
] | [] | [] | [
"python",
"redmine",
"redmine_plugins",
"ruby_on_rails"
] | stackoverflow_0004941453_python_redmine_redmine_plugins_ruby_on_rails.txt |
Q:
Python error logging
I'd like to find a way to log every error that forces the python interpreter to quit to be saved to a file as well as being printed to the screen. The reason I would like to do this is that I want to keep stats on the types of errors I make while writing code, with an eye towards finding ways... | Python error logging | I'd like to find a way to log every error that forces the python interpreter to quit to be saved to a file as well as being printed to the screen. The reason I would like to do this is that I want to keep stats on the types of errors I make while writing code, with an eye towards finding ways to avoid mistakes I make ... | [
"I believe you can simply replace sys.excepthook with your own function. You can read about it in the Python documentation.\nBasically, it allows you to customize what happens when an exception percolates up to the point of forcing the Python interpreter to quit. You use it like this:\nimport sys\n\ndef my_except... | [
6
] | [] | [] | [
"error_logging",
"python"
] | stackoverflow_0004941543_error_logging_python.txt |
Q:
State of Python Packaging: Buildout, Distribute, Distutils, EasyInstall, etc
The last time I had to worry about installing Python packages was two years ago working with Enthought, NumPy and MayaVi2. That experience gave me lingering nightmares related to quirky behavior installing & updating Python packages in n... | State of Python Packaging: Buildout, Distribute, Distutils, EasyInstall, etc | The last time I had to worry about installing Python packages was two years ago working with Enthought, NumPy and MayaVi2. That experience gave me lingering nightmares related to quirky behavior installing & updating Python packages in non-standard locations (in $HOME/usr/local2.6/, for example).
Anyway, my work is ta... | [
"First of all, regardless of installation tool you decide on, start using virtualenv --no-site-packages! That way, python packages are not installed globally and you can easily get back to where you were in old as well as new projects.\nNow, your comparison is a little bit apples-to-pears as the tools you list are ... | [
10,
9,
9,
3,
0
] | [] | [] | [
"buildout",
"distribute",
"distutils",
"easy_install",
"python"
] | stackoverflow_0001977485_buildout_distribute_distutils_easy_install_python.txt |
Q:
Is there a math nCr function in python?
I'm looking to see if built in with the math library in python is the nCr (n Choose r) function:
I understand that this can be programmed but I thought that I'd check to see if it's already built in before I do.
A:
The following program calculates nCr in an efficient mann... | Is there a math nCr function in python? | I'm looking to see if built in with the math library in python is the nCr (n Choose r) function:
I understand that this can be programmed but I thought that I'd check to see if it's already built in before I do.
| [
"The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)\nimport operator as op\nfrom functools import reduce\n\ndef ncr(n, r):\n r = min(r, n-r)\n numer = reduce(op.mul, range(n, n-r, -1), 1)\n denom = reduce(op.mul, range(1, r+1), 1)\n return numer // deno... | [
352,
233
] | [] | [] | [
"function",
"math",
"python"
] | stackoverflow_0004941753_function_math_python.txt |
Q:
What is wrong with this code?
I'm using the code below to slug the link to a couchDb instance, so I can test what happens to the GUI if the database is slow.
# coding=utf8 slowCoach.py - a server that delays every message
# thus making the database crawl.
import eventlet
from time import sleep
def closed... | What is wrong with this code? | I'm using the code below to slug the link to a couchDb instance, so I can test what happens to the GUI if the database is slow.
# coding=utf8 slowCoach.py - a server that delays every message
# thus making the database crawl.
import eventlet
from time import sleep
def closed_callback():
print "called back... | [
"Ian says:\nTo answer my own question - I should have imported sleep from eventlet. Without that the green threads lock, and stuff is lost. I also had similar problem in caller, which sent next message to couch before last recieved, and who knows who got what reply!\n"
] | [
1
] | [] | [] | [
"eventlet",
"python"
] | stackoverflow_0004915629_eventlet_python.txt |
Q:
determinating if the input is even or odd numbers
Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"... | determinating if the input is even or odd numbers | Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "F... | [
"It sounds like homework, or worse an interview questions, but this will get you started.\ndef homework(s):\n counter = 0\n if '0' in s:\n for i in s:\n if i == '0':\n counter = counter + 1\n return counter\n\ndon't forget this part over here\ndef odd_or_even_or_none(num):\n if num == 0:\n return 'T... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004940672_python.txt |
Q:
Python: Getting baseclass values from derived class
Hope this is clear enough:
class myParent():
def __init__( self ):
self.parentNumber = 5
class Child( myParent ):
def __init__( self ):
self.childNumber = 4
def multiplyNumbers( self ):
print myParent.parentNumber * self.chil... | Python: Getting baseclass values from derived class | Hope this is clear enough:
class myParent():
def __init__( self ):
self.parentNumber = 5
class Child( myParent ):
def __init__( self ):
self.childNumber = 4
def multiplyNumbers( self ):
print myParent.parentNumber * self.childNumber
p = Child()
p.multiplyNumbers()
I wish to set t... | [
"class myParent( object ):\n def __init__( self ):\n self.parentNumber = 5\n\nclass Child( myParent ):\n def __init__( self ):\n myParent.__init__( self )\n self.childNumber = 4\n\n def multiplyNumbers( self ):\n print self.parentNumber * self.childNumber\n\np = Child()\np.multi... | [
12,
6
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004935587_oop_python.txt |
Q:
String variables in python function?
I'm writing a script in python, but not able to use multiple stings in cases like check directory, file creation etc,
I'm using this to get user input : drive = raw_input('enter drive name to make backup ')
if not os.path.exists('/media/%s/backup' %drive):
os.mkdir('/media... | String variables in python function? | I'm writing a script in python, but not able to use multiple stings in cases like check directory, file creation etc,
I'm using this to get user input : drive = raw_input('enter drive name to make backup ')
if not os.path.exists('/media/%s/backup' %drive):
os.mkdir('/media/%s/backup' %drive)
The above code is wor... | [
"Your string formatting is incorrect. You need to pass a tuple of variables equal to the amount of substitutions in your string.\ntarFile = tarfile.open(\"/media/%s/backup/%s.tar.bz2\" % (drive, dateVar), 'w:bz2')\n\n",
"I would suggest to keep the formatting stuff out of the tarfile.open() as in the following s... | [
6,
2
] | [] | [] | [
"function",
"python",
"string"
] | stackoverflow_0004941604_function_python_string.txt |
Q:
Django ModelForm Template?
I want to learn how can I add to template to my ModelForm i'm newbie. Below you can see my models.py, url.py and views.py:
My model.py looks like that:
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
class Yazilar(models.Mod... | Django ModelForm Template? | I want to learn how can I add to template to my ModelForm i'm newbie. Below you can see my models.py, url.py and views.py:
My model.py looks like that:
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
class Yazilar(models.Model):
yazi = models.CharField... | [
"It seems to me that your problem is in the view, you should be doing something like this:\n@login_required\ndef yazi_ekle(request):\n yazim = YaziForm() # Look at the (), they are needed for instantiation\n return render_to_response('yazi/save.html', {'YaziForm': yazim}) # Sending the form instance t... | [
11,
2
] | [] | [] | [
"django",
"django_forms",
"python",
"templates"
] | stackoverflow_0002281295_django_django_forms_python_templates.txt |
Q:
Trouble in regular expression
Matching G in 'Reference: G. ' using regular expression
I tried using this but error still occur
refresidue = re.compiler(r'(s/Reference: \ //n)')
Any other suggestions as I'm quite new in this. Any help is most appreciated.
'Reference: G. ' reference can be either A,C,G or T
I'm sor... | Trouble in regular expression | Matching G in 'Reference: G. ' using regular expression
I tried using this but error still occur
refresidue = re.compiler(r'(s/Reference: \ //n)')
Any other suggestions as I'm quite new in this. Any help is most appreciated.
'Reference: G. ' reference can be either A,C,G or T
I'm sorry about the confusion - what i wou... | [
"You're mixing regex syntax from JavaScript (or some other regex flavor) and Python; and the regex itself is also quite strange. Also, re.compile() compiles a regex, it doesn't match it to anything.\nAssuming you want to match a single alphanumeric character after the text Reference:, try the following:\nrefresidue... | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004942588_python_regex.txt |
Q:
Choosing a development stack for web based data vis/mining
I would like to know what various folks in the community think about tool/language choices for a small team (3-5) developers working build simple data driven applications. We want to do data munging/Analysis/Datavis.
We will likely ultimately have Hadoop o... | Choosing a development stack for web based data vis/mining | I would like to know what various folks in the community think about tool/language choices for a small team (3-5) developers working build simple data driven applications. We want to do data munging/Analysis/Datavis.
We will likely ultimately have Hadoop on the data crunching end and will have javascript on the front e... | [
"Instead of JVM you could check rApache and rserve also. Well, I have no idea though what extra would you get instead of using Rpy.\n"
] | [
2
] | [] | [] | [
"data_munging",
"jvm",
"programming_languages",
"python",
"r"
] | stackoverflow_0004941276_data_munging_jvm_programming_languages_python_r.txt |
Q:
How do I structure Python code into modules/packages?
Assume I have this barebones structure:
project/
main.py
providers/
__init.py__
acme1.py
acme2.py
acme3.py
acme4.py
acme5.py
acme6.py
Assume that main.py contains (partial):
if complexcondition():
print providers.acme5.get()
... | How do I structure Python code into modules/packages? | Assume I have this barebones structure:
project/
main.py
providers/
__init.py__
acme1.py
acme2.py
acme3.py
acme4.py
acme5.py
acme6.py
Assume that main.py contains (partial):
if complexcondition():
print providers.acme5.get()
Where __init__.py is empty and acme*.py contain (partial):
... | [
"hey! two years later but... maybe could be helpfull to some one\nmake your providers/__init__.py like that:\nimport os\nimport glob\n\nmodule_path = os.path.dirname(__file__)\nfiles = glob.glob(os.path.join(module_path, 'acme*.py'))\n__all__ = [os.path.basename(f)[:-3] for f in files]\n\nyou don't have to change i... | [
6,
5,
3
] | [] | [] | [
"module",
"package",
"python"
] | stackoverflow_0000770320_module_package_python.txt |
Q:
Preferable platform for video-editing and viewing - Executable program / Web-based?
I need to make a light-weight application for video editing and viewing.
I was thinking of either writing an executable program written in Python, or a light-weight web app using JavaScript and HTML5. Flash, as a third option, is p... | Preferable platform for video-editing and viewing - Executable program / Web-based? | I need to make a light-weight application for video editing and viewing.
I was thinking of either writing an executable program written in Python, or a light-weight web app using JavaScript and HTML5. Flash, as a third option, is pretty much out of the question, since it's too fat and has many security flaws.
EDIT: The... | [
"Python.\nReally, while you can do some fancy tricks with HTML5 Video e.g. apply effects to it and render it on a canvas, rotate the player etc. I don't know of any encoder that's written in JavaScript.\nSo unless you want to write your own version of FFMPEG for JavaScript, which will probably be the slowest thing ... | [
2,
1,
1,
1
] | [] | [] | [
"html",
"html5_video",
"javascript",
"python",
"video"
] | stackoverflow_0004241033_html_html5_video_javascript_python_video.txt |
Q:
How to rename files in directory with its sha1 hash with python?
I need to rename my files in directory with its hash with Python. I've done the same thing using C#:
Console.Write("enter path");
string path = Console.ReadLine();
foreach (var i in Directory.GetFiles(path))
{
... | How to rename files in directory with its sha1 hash with python? | I need to rename my files in directory with its hash with Python. I've done the same thing using C#:
Console.Write("enter path");
string path = Console.ReadLine();
foreach (var i in Directory.GetFiles(path))
{
try
{
using (SHA1Managed sha1 = new SHA1Ma... | [
"In Python if you want to compute some hash (MD5, SHA1) there is hashlib module.\nTo make some operations on filesystem there is os module. In those modules you will find: sha1 object with hexdigest() method and listdir() and rename() functions. Example code:\nimport os\nimport hashlib\n\ndef sha1_file(fn):\n f ... | [
4
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0004942471_hash_python.txt |
Q:
Using Python & XML-RPC to add a custom field to a Wordpress post?
I want to add an 'enclosure' custom field to an existing Wordpress post using Python & XML-RPC.
My code looks like this:
def add_enclosure(server, post_id, enclosure):
post_data = server.metaWeblog.getPost(post_id, username, password)
custom... | Using Python & XML-RPC to add a custom field to a Wordpress post? | I want to add an 'enclosure' custom field to an existing Wordpress post using Python & XML-RPC.
My code looks like this:
def add_enclosure(server, post_id, enclosure):
post_data = server.metaWeblog.getPost(post_id, username, password)
custom_fields = post_data['custom_fields']
new_id = max([int(field['id'])... | [] | [] | [
"Custom fields are a set of key/value pairs that look like:\n\"custom_fields\" = (\n {key = city; value = Sacramento; },\n {key = city; value = Sandy; }\n )\n\nTry fetching post data with metaWeblog.getPost for a post that already has custom fields and you'll see what they look like.\n"
] | [
-1
] | [
"python",
"wordpress",
"xml_rpc"
] | stackoverflow_0002419768_python_wordpress_xml_rpc.txt |
Q:
Many-to-many declarative SQLAlchemy definition for users, groups, and roles
I'm new to SQLAlchemy, and was wondering what the best way to go about defining such tables and a relationship would be. I want to be able to access groups from a user by user.groups, users in a group by group.users, and find out the role ... | Many-to-many declarative SQLAlchemy definition for users, groups, and roles | I'm new to SQLAlchemy, and was wondering what the best way to go about defining such tables and a relationship would be. I want to be able to access groups from a user by user.groups, users in a group by group.users, and find out the role of a user in a group (which I'm assuming will be logic defined in an association ... | [
"The key to simplifying your model is to use associationproxy, therefore you should definitely check it out.\nAssuming that the user can have only one role within a group, the code below should answer all your questions:\n\nhow to configure the model and relationships\nhow to add/remove/update the roles\nhow to ret... | [
8
] | [] | [] | [
"many_to_many",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004864240_many_to_many_python_sql_sqlalchemy.txt |
Q:
Read EXE, MSI, and ZIP file metadata in Python in Linux
I am writing a Python script to index a large set of Windows installers into a DB.
I would like top know how to read the metadata information (Company, Product Name, Version, etc) from EXE, MSI and ZIP files using Python running on Linux.
Software
I am using ... | Read EXE, MSI, and ZIP file metadata in Python in Linux | I am writing a Python script to index a large set of Windows installers into a DB.
I would like top know how to read the metadata information (Company, Product Name, Version, etc) from EXE, MSI and ZIP files using Python running on Linux.
Software
I am using Python 2.6.5 on Ubuntu 10.04 64-bit with Django 1.2.1.
Found ... | [
"Take a look at this library: http://bitbucket.org/haypo/hachoir/wiki/Home and this example program that uses the library: http://pypi.python.org/pypi/hachoir-metadata/1.3.3. The second link is an example program which uses the Hachoir binary file manipulation library (first link) to parse the metadata.\nThe librar... | [
4,
2,
1,
1
] | [] | [] | [
"md5",
"metadata",
"python",
"windows_installer"
] | stackoverflow_0003742583_md5_metadata_python_windows_installer.txt |
Q:
Python - Noob Question - What does it mean "Giving one of the optional arguments"?
What does this do?
giving one of the optional arguments:
ask_ok('OK to overwrite the file?', 2)
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', '... | Python - Noob Question - What does it mean "Giving one of the optional arguments"? | What does this do?
giving one of the optional arguments:
ask_ok('OK to overwrite the file?', 2)
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
... | [
"In Python there are several types of arguments:\n\npositional and keyword\nnamed and arbitrary\n\nThe function argument in Python is an attribution operation, that is, arguments are assigned to variables in the function local namespace.\nIf you have a declaration like this:\ndef some_func(pos_arg1, pos_arg2, kw_ar... | [
4,
2,
1
] | [] | [] | [
"arguments",
"default_value",
"python"
] | stackoverflow_0004944140_arguments_default_value_python.txt |
Q:
OpenCV: memory leak with Python interface but not in the C version
I am asking here because I haven't gotten any help from the OpenCV developers so far. I reduced the problem to a very simple test case so probably anyone with some background with CPython could help here.
This C code does not leak:
int main() {
... | OpenCV: memory leak with Python interface but not in the C version | I am asking here because I haven't gotten any help from the OpenCV developers so far. I reduced the problem to a very simple test case so probably anyone with some background with CPython could help here.
This C code does not leak:
int main() {
while(true) {
int hist_size[] = {40};
float range[] = {... | [
"It has been fixed.\n\nChanged 3 weeks ago by jamesb\n\nstatus changed from accepted to closed\nresolution set to fixed\n\nFixed in r4526\nThe ranges parameters were not being freed, and the iterator over ranges was not being DECREF'ed. Regressions now pass, and original loop does not leak.\n\n",
"I think you hav... | [
2,
0
] | [] | [] | [
"cpython",
"debugging",
"memory_leaks",
"opencv",
"python"
] | stackoverflow_0004178975_cpython_debugging_memory_leaks_opencv_python.txt |
Q:
PYTHONPATH missing from environment
Please help me understand this. Here you can see that I have PYTHONPATH set (it's from my .bashrc)
jean@klippie:~$ echo $PYTHONPATH
:/home/jean/local/lib/python2.6/site-packages
But if I try to launch something in my local site-packages it is ignored:
jean@klippie:~$ gtimelog
... | PYTHONPATH missing from environment | Please help me understand this. Here you can see that I have PYTHONPATH set (it's from my .bashrc)
jean@klippie:~$ echo $PYTHONPATH
:/home/jean/local/lib/python2.6/site-packages
But if I try to launch something in my local site-packages it is ignored:
jean@klippie:~$ gtimelog
Traceback (most recent call last):
File... | [
"Most probably, you only set the shell variable PYTHONPATH in your .bashrc, but you don't export this variable to the environment. Printing via echo only shows that the shell variable has the printed value. Try\nenv | grep PYTHONPATH\n\nto query if PYTHONPATH is really in the environment and make sure you really ... | [
4
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0004944502_bash_python.txt |
Q:
Python C APi Deep Copy
How do I do a deep copy of a python object using the C API? I know I can use copy.deepcopy, but I'd prefer to use the C API if I can.
A:
The functionality of copy.deepcopy() is completely written in Python. I don't think they would have done this if there was a single C call to achieve th... | Python C APi Deep Copy | How do I do a deep copy of a python object using the C API? I know I can use copy.deepcopy, but I'd prefer to use the C API if I can.
| [
"The functionality of copy.deepcopy() is completely written in Python. I don't think they would have done this if there was a single C call to achieve the same thing, so my guess is you will have to call copy.deepcopy().\n"
] | [
4
] | [] | [] | [
"c",
"copy",
"python"
] | stackoverflow_0004944792_c_copy_python.txt |
Q:
How to customize the label of a tkinter Scale widget by adding a percentage sign
I'm working with a Tkinter scale, where the selected value is somewhere between 0 and 100, representing a percentage. Is there a way for the value displayed to have a % percent sign following it?
I want it to look like the following (... | How to customize the label of a tkinter Scale widget by adding a percentage sign | I'm working with a Tkinter scale, where the selected value is somewhere between 0 and 100, representing a percentage. Is there a way for the value displayed to have a % percent sign following it?
I want it to look like the following (roughly):
75%
|-------------o----|
Currently I cannot figure a way to ... | [
"It's not possible with the options provided by the control.\nHowever, it is possible to turn the value off and use your own string. Since you know the value of the slider and you know the length, you can calculate the pixel that represents the center of the slider. With that information you can place a label widge... | [
1
] | [] | [] | [
"python",
"tk_toolkit",
"tkinter",
"tkinter_scale"
] | stackoverflow_0004942432_python_tk_toolkit_tkinter_tkinter_scale.txt |
Q:
How can a python object's classmethods be referred to inside the class attributes?
I would like to do something along the lines of...
class MyClassA(object):
an_attr = AnotherClassB(do_something=MyClassA.hello)
@classmethod
def hello(cls):
return "Hello"
however it will tell me MyClassA is no... | How can a python object's classmethods be referred to inside the class attributes? | I would like to do something along the lines of...
class MyClassA(object):
an_attr = AnotherClassB(do_something=MyClassA.hello)
@classmethod
def hello(cls):
return "Hello"
however it will tell me MyClassA is not defined when I try to run it.
an_attr must be a class attribute
I can't alter Another... | [
"While defining a class, the class does not exist yet. So you have to postpone the creation of an_attr until after the class definition:\nclass MyClassA(object):\n @classmethod\n def hello(cls):\n return \"Hello\"\nMyClassA.an_attr = AnotherClassB(do_something=MyClassA.hello)\n\n",
"You just have to... | [
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004944831_python.txt |
Q:
Detected a memory leak... no destructor found - for enums
This is about embedded python using swig.
I have an std::map<enum, std::string> exposed to python (embedded python). When the script is executed, swig spits out the below "warning" at the end (when the map goes out of scope - I guess):
swig/python detected... | Detected a memory leak... no destructor found - for enums | This is about embedded python using swig.
I have an std::map<enum, std::string> exposed to python (embedded python). When the script is executed, swig spits out the below "warning" at the end (when the map goes out of scope - I guess):
swig/python detected a memory leak of type 'std::map< MyEnum, std::string>
... no... | [
"Could be a problem with declaration order: the std::map %template must be declared AFTER MyEnum is added to the SWIG interface.\nI have failed to do this in the past (though in my case the map key was a typedef alias to an unsigned int), and saw the exact same set of symptoms reported here.\n"
] | [
0
] | [] | [] | [
"python",
"swig"
] | stackoverflow_0003989859_python_swig.txt |
Q:
Lightweight console/IDE for Python?
I often use ipython (or the regular python shell) to test python code snippets while coding, and it's been very useful. One shortcoming of this, though, is that if I want to test a multi-line segment of code, or want to write multiple lines of code before running, it isn't very ... | Lightweight console/IDE for Python? | I often use ipython (or the regular python shell) to test python code snippets while coding, and it's been very useful. One shortcoming of this, though, is that if I want to test a multi-line segment of code, or want to write multiple lines of code before running, it isn't very convenient to have to do it "line by line... | [
"You might give DreamPie a try. As far as I can tell from a quick read of the groovyConsole page you linked to, DreamPie features a similar input area/output area division (they call it \"code box\" and \"history box\"). The code you execute is by default cleared from the code box - which groovyConsole apparently d... | [
4,
3,
2,
1
] | [] | [] | [
"groovy_console",
"ide",
"ipython",
"python",
"shell"
] | stackoverflow_0004940791_groovy_console_ide_ipython_python_shell.txt |
Q:
Why "decimal.Decimal('0') < 1.0" yields False in Python 2.6.5
In Python 2.6.5 the following expression yields False:
>>> import decimal
>>> decimal.Decimal('0') < 1.0
False
Is there a rationale explaining why comparison of Decimal against float should behave like this?
A:
From the documentation of the decimal m... | Why "decimal.Decimal('0') < 1.0" yields False in Python 2.6.5 | In Python 2.6.5 the following expression yields False:
>>> import decimal
>>> decimal.Decimal('0') < 1.0
False
Is there a rationale explaining why comparison of Decimal against float should behave like this?
| [
"From the documentation of the decimal module:\n\nChanged in version 2.7: A comparison\n between a float instance x and a\n Decimal instance y now returns a\n result based on the values of x and y.\n In earlier versions x < y returned the\n same (arbitrary) result for any\n Decimal instance x and any float\n ... | [
13
] | [] | [] | [
"decimal",
"floating_point",
"python"
] | stackoverflow_0004945683_decimal_floating_point_python.txt |
Q:
Django TemplateSyntaxError: current transaction is aborted, what does this exception mean? Does postgresql 8.4 work fine with django?
The full text of the error is:
TemplateSyntaxError at /
Caught an exception while rendering:
current transaction is aborted,
commands ignored until end of
transaction block
... | Django TemplateSyntaxError: current transaction is aborted, what does this exception mean? Does postgresql 8.4 work fine with django? | The full text of the error is:
TemplateSyntaxError at /
Caught an exception while rendering:
current transaction is aborted,
commands ignored until end of
transaction block
I've recently reinstalled all the software on my computer. The code used to work no problem before. It also still works no problem on a fri... | [
"That exception means that there was an error in some SQL that is getting executed. Since Django runs all the SQL inside of a database transaction, all the SQL that is being executed after the error gets ignored. So:\nBEGIN;\nSELECT * FROM table;\nSELECT missing_column FROM table WHERE id = 1; -- generates an erro... | [
13,
4
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0001867407_django_postgresql_python.txt |
Q:
Is there a library for Python that gives the script name for a given unicode character or string?
Is there a library that tells what script a particular unicode character belongs to?
For example for the input "u'ሕ'" it should return Ethiopic or similar.
A:
Maybe the data in the unicodedata module is what you are... | Is there a library for Python that gives the script name for a given unicode character or string? | Is there a library that tells what script a particular unicode character belongs to?
For example for the input "u'ሕ'" it should return Ethiopic or similar.
| [
"Maybe the data in the unicodedata module is what you are looking for:\nprint unicodedata.name(u\"ሕ\")\n\nprints\nETHIOPIC SYLLABLE HHE\n\nThe printed name can be used to look up the corresponding character:\nunicodedata.lookup(\"ETHIOPIC SYLLABLE HHE\")\n\n",
"You can parse the Scripts.txt file:\n# -*- coding: u... | [
7,
2
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0004944377_python_unicode.txt |
Q:
how using django-filebrowser at apache?
hi all:
I have a quirky question about django-filebrowser,
my project at /home/q/django/myapp,
I save the django-filebrowser at /home/q/django/myapp/filebrowser .
**myapp.settings.py**
INSTALLED_APPS=(
.....
myapp.filebrowser,
....
)
**myapp.urls.p... | how using django-filebrowser at apache? | hi all:
I have a quirky question about django-filebrowser,
my project at /home/q/django/myapp,
I save the django-filebrowser at /home/q/django/myapp/filebrowser .
**myapp.settings.py**
INSTALLED_APPS=(
.....
myapp.filebrowser,
....
)
**myapp.urls.py**
urlpatterns=patterns('',
(r'filebr... | [
"You can modify all the settings, including those of django-filebrowser, in myapp.settings. The settings.py in filebrowser are the default values used if you don't specify them in your own settings. This is a widely used pattern for 3rd party django apps to define default values for settings.\nIf you look at filebr... | [
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004946258_django_django_admin_python.txt |
Q:
Random-access container for strings in python?
I manipulate with indexed instances (say, music tracks) and have to lookup object's name by its index (int->string). Dicts are too slow (I have about 10M objects). Memory is not a problem, so the most convinient solution would be to create a random-access array of str... | Random-access container for strings in python? | I manipulate with indexed instances (say, music tracks) and have to lookup object's name by its index (int->string). Dicts are too slow (I have about 10M objects). Memory is not a problem, so the most convinient solution would be to create a random-access array of strings from csv file with names.
However, I have faile... | [
"From what I remember, dictionaries in Python have O(1) average access time, but lists will definitely be faster. If your indices are not very sparse, you can try something like this:\nreader = [(1, 'a'), (2, 'b')] # Replace it with your CSV reader.\n\n# First, fill a dictionary:\ntext_dict = {}\nfor index, text in... | [
2
] | [] | [] | [
"performance",
"python",
"random_access"
] | stackoverflow_0004945693_performance_python_random_access.txt |
Q:
How do I control where an R plot is displayed, using python and rpy2?
I'm writing a program in Python. The first thing that happens is a window is displayed (I'm using wxPython) that has some buttons and text. When the user performs some actions, a plot is displayed in its own window. This plot is made with R, ... | How do I control where an R plot is displayed, using python and rpy2? | I'm writing a program in Python. The first thing that happens is a window is displayed (I'm using wxPython) that has some buttons and text. When the user performs some actions, a plot is displayed in its own window. This plot is made with R, using rpy2. The problem is that the plot usually pops up on top of the mai... | [
"Plot to a graphics file using jpeg(), png() or another device, then display that file on your wxWidget.\n",
"There are few lines about this in the documentation:\nhttp://rpy.sourceforge.net/rpy2/doc-2.2/html/graphics.html\nBy default R plots to the \"interactive\" plotting device (X11). Specifying a non-interact... | [
5,
0
] | [] | [] | [
"plot",
"python",
"r",
"rpy2"
] | stackoverflow_0004938556_plot_python_r_rpy2.txt |
Q:
Python List Variable - Is it using the memory location or something?
I'm trying to pop off the values I'm appending to the list M each time I've evaluated the difference between them and their expected values. I'm printing the result of a list before and after I use M.pop(). Is it using a location in memory and me... | Python List Variable - Is it using the memory location or something? | I'm trying to pop off the values I'm appending to the list M each time I've evaluated the difference between them and their expected values. I'm printing the result of a list before and after I use M.pop(). Is it using a location in memory and messing up my list inside of deltaL?
M=[]
delta = 3
while abs(delta) > 0.3:
... | [
"This line:\ndelta_mL.append([max(deltaL),M])\n\n...creates a list with two items, the second of which is a reference to the list M. When you later change M, you can see the changes in delta_mL because it references the same list. If you want to make a copy of M, try:\ndelta_mL.append([max(deltaL),list(M)])\n\nThis... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0004946596_python.txt |
Q:
Python CookieJar - Cookies Set By Google Analytics
I'm a little bit confused about this situation. I'm working on a script to login into a website. I'm using CookieJar and the login method is working just fine.
If I try to display the cookieJar content:
for index, cookie in enumerate(cw.cj):
print index, '... | Python CookieJar - Cookies Set By Google Analytics | I'm a little bit confused about this situation. I'm working on a script to login into a website. I'm using CookieJar and the login method is working just fine.
If I try to display the cookieJar content:
for index, cookie in enumerate(cw.cj):
print index, ':', cookie
I get a cookie as:
0 : <Cookie C4CSESSID... | [
"I think you get that cookie once the tracking code on that page has executed (in the response from the Google server). As it's javascript, you'll need to find a way to either interpret Javascript in your code, or mimic the request the tracking code issues.\nInterpreting Javascript out of the context of a browser c... | [
0,
0,
0
] | [] | [] | [
"cookiejar",
"google_analytics",
"python"
] | stackoverflow_0004943368_cookiejar_google_analytics_python.txt |
Q:
Problem bulk loading a csv file in Mysql using Python
I am loading a file called 'rec.csv' to my Mysql DB. I use the code below:
import MySQLdb,os
path='testData'
absPath = os.path.abspath(path)
print absPath
conn = MySQLdb.connect(host='localhost',
user='root',
... | Problem bulk loading a csv file in Mysql using Python | I am loading a file called 'rec.csv' to my Mysql DB. I use the code below:
import MySQLdb,os
path='testData'
absPath = os.path.abspath(path)
print absPath
conn = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='iens')
db_curso... | [
"Make a slight change in your load query.\nLOAD DATA LOCAL INFILE\n\ni.e., add LOCAL in the query.\nAs per MySQL docs:\nIf LOCAL is specified, the file is read by the client program on the client host and sent to the server. The file can be given as a full path name to specify its exact location. If given as a rela... | [
3
] | [] | [] | [
"load",
"mysql",
"python"
] | stackoverflow_0004947150_load_mysql_python.txt |
Q:
Python / Django Forms - Display Form Element Content Instead of Html Element
I am looping through some forms and I want to display some of the values of certain form elements. I have read that .data should take care of this for me. However, that returns "None" and the form does indeed have the field and correct ... | Python / Django Forms - Display Form Element Content Instead of Html Element | I am looping through some forms and I want to display some of the values of certain form elements. I have read that .data should take care of this for me. However, that returns "None" and the form does indeed have the field and correct stored value...
{% for document in documents: %}
{{ document.title.data }} <!-... | [
"Update:\n\nTo access an initial value directly forms.CharField(initial=X)\nUse {{ document.title.field.initial }}.\nAccessing an initial value passed into the form constructor (form = MyForm(initial={...})) doesn't look possible via the template. BoundField does data = self.form.initial.get(self.name, self.field.i... | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004947290_django_django_forms_python.txt |
Q:
Using strides for an efficient moving average filter
I recently learned about strides in the answer to this post, and was wondering how I could use them to compute a moving average filter more efficiently than what I proposed in this post (using convolution filters).
This is what I have so far. It takes a view of ... | Using strides for an efficient moving average filter | I recently learned about strides in the answer to this post, and was wondering how I could use them to compute a moving average filter more efficiently than what I proposed in this post (using convolution filters).
This is what I have so far. It takes a view of the original array then rolls it by the necessary amount a... | [
"For what it's worth, here's how you'd do it using \"fancy\" striding tricks. I was going to post this yesterday, but got distracted by actual work! :)\n@Paul & @eat both have nice implementations using various other ways of doing this. Just to continue things from the earlier question, I figured I'd post the N-dim... | [
28,
8,
5,
4
] | [] | [] | [
"filter",
"image_processing",
"numpy",
"python"
] | stackoverflow_0004936620_filter_image_processing_numpy_python.txt |
Q:
determining numerator and denominator in a relatively complex mathematical expression using python
I'm trying to convert calculator input to LaTeX. if a user inputs this:
(3x^(x+(5/x)+(x/33))+y)/(32 + 5)
I have to convert it to this:
frac{3x^(x+frac{5}{x}+frac{x}{33})+y}{32 + 5x}
however I am having issues with ... | determining numerator and denominator in a relatively complex mathematical expression using python | I'm trying to convert calculator input to LaTeX. if a user inputs this:
(3x^(x+(5/x)+(x/33))+y)/(32 + 5)
I have to convert it to this:
frac{3x^(x+frac{5}{x}+frac{x}{33})+y}{32 + 5x}
however I am having issues with determining when a numerator begins and ends. Any suggestions?
| [
"Have a look at compiler\ncompiler.parse('(3*x**(x+(5/x)+(x/33))+y)/(32 + 5)')\n\nreturns\nModule(None, Stmt([Discard(Div((Add((Mul((Const(3), Power((Name('x'), Add((Add((Name('x'), Div((Const(5), Name('x'))))), Div((Name('x'), Const(33))))))))), Name('y'))), Add((Const(32), Const(5))))))]))\n\nwhich could be more ... | [
5,
4,
2
] | [] | [] | [
"algebra",
"math",
"python"
] | stackoverflow_0004942657_algebra_math_python.txt |
Q:
Python : Why use "list[:]" when "list" refers to same thing?
Consider a list >>> l=[1,2,3].
What is the benefit of using >>> l[:] when >>> l prints the same thing as former does?
Thanks.
A:
It creates a (shallow) copy.
>>> l = [1,2,3]
>>> m = l[:]
>>> n = l
>>> l.append(4)
>>> m
[1, 2, 3]
>>> n
[1, 2, 3, 4]
>>>... | Python : Why use "list[:]" when "list" refers to same thing? | Consider a list >>> l=[1,2,3].
What is the benefit of using >>> l[:] when >>> l prints the same thing as former does?
Thanks.
| [
"It creates a (shallow) copy.\n>>> l = [1,2,3]\n>>> m = l[:]\n>>> n = l\n>>> l.append(4)\n>>> m\n[1, 2, 3]\n>>> n\n[1, 2, 3, 4]\n>>> n is l\nTrue\n>>> m is l\nFalse\n\n",
"l[:] is called slice notation. It can be used to extract only some of the elements in the list, but in this case the bounds are omitted so th... | [
35,
12
] | [] | [] | [
"python",
"slice"
] | stackoverflow_0004947762_python_slice.txt |
Q:
subprocess.Popen and buffered process output
From inside python code, I want to run a binary program that gets its parameters from stdin. Using the subprocess module, this should be straightforward:
import subprocess
command = [ 'my_program' ]
p = subprocess.Popen( command, \
stdin = subprocess.PIPE, stdo... | subprocess.Popen and buffered process output | From inside python code, I want to run a binary program that gets its parameters from stdin. Using the subprocess module, this should be straightforward:
import subprocess
command = [ 'my_program' ]
p = subprocess.Popen( command, \
stdin = subprocess.PIPE, stdout = subprocess.PIPE, \
env={ "GFORTRAN_UN... | [
"You should have better luck using Popen.communicate() to send strings to the process' stdin rather than manually writing to it.\nstdoutdata, stderrdata = p.communicate(stdin_stuff)\n\n",
"To complement Aphex's answer, here the relevant part of the documentation:\n\nWarning\nUse communicate() rather than .stdin.w... | [
4,
2
] | [] | [] | [
"fortran",
"gfortran",
"python"
] | stackoverflow_0004947782_fortran_gfortran_python.txt |
Q:
Error while filehandling in Blender using Python
I'm trying to read data in Blender from an external device connected to an Arduino and save onto a file. But it gives this error
SyntaxError: invalid syntax
Python script error from controller "contr#CONTR#1":
Traceback (most recent call last):
File "SerialBGE.py"... | Error while filehandling in Blender using Python | I'm trying to read data in Blender from an external device connected to an Arduino and save onto a file. But it gives this error
SyntaxError: invalid syntax
Python script error from controller "contr#CONTR#1":
Traceback (most recent call last):
File "SerialBGE.py", line 6, in <module>
f=open('abc.dat', 'r')
IOErr... | [
"You are getting the error because the file 'abc.dat' doesn't exist the first time you run the program. \nYou need to handle the initial case, when you run the program for the first time, before 'abc.dat' exists.\n"
] | [
3
] | [] | [] | [
"arduino",
"blender",
"python"
] | stackoverflow_0004947889_arduino_blender_python.txt |
Q:
Does anyone know of a asynchronous mysql lib for python?
I've been looking into non-blocking servers for python (tornado, twisted etc) but a lot of the benefits seems to be lost if there's no non-blocking connection to the database. Does anyone know if there are any projects that take care of this? (by non-blockin... | Does anyone know of a asynchronous mysql lib for python? | I've been looking into non-blocking servers for python (tornado, twisted etc) but a lot of the benefits seems to be lost if there's no non-blocking connection to the database. Does anyone know if there are any projects that take care of this? (by non-blocking a la node.js)
Edit: Clarified my question
| [
"You can use Twisted's ADBAPI to wrap a synchronous DBAPI implementation.\nE.g.:\nfrom twisted.internet import reactor\nfrom twisted.enterprise import adbapi\n\ndef result(rows):\n for row in rows:\n print row\n\n reactor.stop()\n\ndef fail(err):\n err.printDetailedTraceback()\n reactor.stop()\n\... | [
13,
4,
1
] | [] | [] | [
"asynchronous",
"mysql",
"python",
"tornado",
"twisted"
] | stackoverflow_0001897799_asynchronous_mysql_python_tornado_twisted.txt |
Q:
Visiting nodes in a syntax tree with Python ast module
I'm playing with python ast (abstract syntax tree).
I wrote the following and it visited all nodes of the AST.
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor... | Visiting nodes in a syntax tree with Python ast module | I'm playing with python ast (abstract syntax tree).
I wrote the following and it visited all nodes of the AST.
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node... | [
"Since your visit_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.\nIf you have a look at the NodeVisitor.generic_visit method in the implementation of ast.py, you'll see that it loops through the children of the current node. So, you can expli... | [
11,
4
] | [] | [] | [
"abstract_syntax_tree",
"parsing",
"python"
] | stackoverflow_0004947783_abstract_syntax_tree_parsing_python.txt |
Q:
How can remove a widget and resize the main window?
I have a test app that uses Python and Tkinter to present a number of text boxes to the user using the grid layout manager.
To reduce clutter on the screen I have a Show/Hide button that removes and show several non-critical widgets:
if show_all:
# Display ... | How can remove a widget and resize the main window? | I have a test app that uses Python and Tkinter to present a number of text boxes to the user using the grid layout manager.
To reduce clutter on the screen I have a Show/Hide button that removes and show several non-critical widgets:
if show_all:
# Display widget
widget.grid()
else :
# Hide widget
wid... | [
"By default the main window should resize, assuming the user hasn't resized the window. If the user has resized the window, you might want to rethink the need to shrink it. If they resized it, they probably want it at the size they resized it to. \nRegardless, try setting the window geometry of the main window (eg:... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004947027_python_tkinter.txt |
Q:
How to override systematically and transparently Python methods
I'm looking for a 'simple' solution to override systematically some inherited methods in Python (=>2.6). Based on my previous question here, I'll come up a solution:
def override(cls, o):
"""Override class method(s)."""
for t in o: # possible problem;... | How to override systematically and transparently Python methods | I'm looking for a 'simple' solution to override systematically some inherited methods in Python (=>2.6). Based on my previous question here, I'll come up a solution:
def override(cls, o):
"""Override class method(s)."""
for t in o: # possible problem; nondeterministic order
for name in o[t]:
mtbo= getattr(c... | [
"Instead of manually assigning __name__, __doc__, and possibly others, you can likely just call functools.update_wrapper to ensure the relevant attributes are copied.\n"
] | [
2
] | [] | [] | [
"inheritance",
"overriding",
"python",
"transform"
] | stackoverflow_0004735353_inheritance_overriding_python_transform.txt |
Q:
PYTHON:Tkinter.OptionMenu Question : option menu does not execute the command function to user selection
I am trying to create a python program as below.
it basically reads a file with bus time table and in the Tkinter, it displays the departure list and arrival bus stops with their corresponding time.
here i am u... | PYTHON:Tkinter.OptionMenu Question : option menu does not execute the command function to user selection | I am trying to create a python program as below.
it basically reads a file with bus time table and in the Tkinter, it displays the departure list and arrival bus stops with their corresponding time.
here i am using the following code so that it will update the time for each departure or arrival stops. but when i select... | [
"When you write command=self.update_departure() you are saying \"execute the command self._update_departure, and use the result of that call as the name of the command\". Since self._update_departure() returns None, it's the same as doing command=None\nIn other words, omit the () -- you need to pass a reference to ... | [
7
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004947592_python_tkinter.txt |
Q:
Overcoming the size entry size limit for appengine search?
I am trying to use a searchable model for blog entries and it worked fine on the development platform but when I try to add an entry in the cloud I get an error:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/app... | Overcoming the size entry size limit for appengine search? | I am trying to use a searchable model for blog entries and it worked fine on the development platform but when I try to add an entry in the cloud I get an error:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/init.py", line 517, in call
handler.post(*... | [
"What you seem to be running into are called Exploding Indexes. You can read more about them here: http://code.google.com/appengine/docs/python/datastore/queries.html#Big_Entities_and_Exploding_Indexes\nBasically you can't use AppEngine to create a full-text engine, unless you have a very small dataset. It's eith... | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"searchable"
] | stackoverflow_0004944483_google_app_engine_google_cloud_datastore_python_searchable.txt |
Q:
Python Slice Assignment Memory Usage
I read in a comment here on Stack Overflow that it is more memory efficient to do slice assignment when changing lists. For example,
a[:] = [i + 6 for i in a]
should be more memory efficient than
a = [i + 6 for i in a]
because the former replaces elements in the existing lis... | Python Slice Assignment Memory Usage | I read in a comment here on Stack Overflow that it is more memory efficient to do slice assignment when changing lists. For example,
a[:] = [i + 6 for i in a]
should be more memory efficient than
a = [i + 6 for i in a]
because the former replaces elements in the existing list, while the latter creates a new list and... | [
"The line\na[:] = [i + 6 for i in a]\n\nwould not save any memory. Python does evaluate the right hand side first, as stated in the language documentation:\n\nAn assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple)... | [
48
] | [] | [] | [
"benchmarking",
"memory_management",
"performance",
"python"
] | stackoverflow_0004948293_benchmarking_memory_management_performance_python.txt |
Q:
How to capture html frame as an image
I need to open a webpage from Python and capture what I see in browser as an image(or rather what should be seen, because I want to execute it in background).
The webpage contains JavaScript - one frame has caption dependent on script evaluation and I want it also to be captu... | How to capture html frame as an image | I need to open a webpage from Python and capture what I see in browser as an image(or rather what should be seen, because I want to execute it in background).
The webpage contains JavaScript - one frame has caption dependent on script evaluation and I want it also to be captured.
| [
"It's feasible, at least, using PyQt + QWebKit (an example here and here). \n"
] | [
2
] | [] | [] | [
"browser",
"javascript",
"printscreen",
"python"
] | stackoverflow_0004948945_browser_javascript_printscreen_python.txt |
Q:
Making massive numbers of HTTP requests in Python
I'm trying to test a web application, part of this involves making ~10K requests, taking the few <1K that return 200 OK and going through their data. The webapp is buggy and there are false positives, so each 200 OK needs to be at least triple-checked.
Working in P... | Making massive numbers of HTTP requests in Python | I'm trying to test a web application, part of this involves making ~10K requests, taking the few <1K that return 200 OK and going through their data. The webapp is buggy and there are false positives, so each 200 OK needs to be at least triple-checked.
Working in Python I was trying to do this with threading and urllib... | [
"I was testing whit apache ab web server TORNADO and was unable to go much over 1000 connections per second on my dual core athlon @ 2Ghz . 30% resources took testing tool ab and remaining was for server. I am pretty convinced that most resources are spent by OS and IP-eth layer.\nhttp://amix.dk/blog/post/19581\nn... | [
1,
0,
0,
0
] | [] | [] | [
"http",
"http_headers",
"multithreading",
"python"
] | stackoverflow_0004948911_http_http_headers_multithreading_python.txt |
Q:
Which method can I override for cleanup task when a Tkinter.Tk window in Python?
class MainGUI(Tkinter.Tk):
# some overrides
# MAIN
gui = MainGUI(None)
gui.mainloop()
But I need to do some cleanup when the window is closed by the user. Which method in Tkinter.Tk can I override?
A:
You can set up a bindi... | Which method can I override for cleanup task when a Tkinter.Tk window in Python? | class MainGUI(Tkinter.Tk):
# some overrides
# MAIN
gui = MainGUI(None)
gui.mainloop()
But I need to do some cleanup when the window is closed by the user. Which method in Tkinter.Tk can I override?
| [
"You can set up a binding that gets fired when the window is destroyed. Either bind to <Destroy> or add a protocol handler for WM_DELETE_WINDOW.\nFor example:\ndef callback():\n # your cleanup code here\n\n...\nroot.protocol(\"WM_DELETE_WINDOW\", callback)\n\n",
"if you want an action to occur when a specific ... | [
5,
5
] | [] | [] | [
"destructor",
"python",
"tkinter"
] | stackoverflow_0002954396_destructor_python_tkinter.txt |
Q:
Which of the three installed PyQt DLL directories do I want?
I've tried installing Python and Qt several times but keep running into the same problem: The examples included in the PyQt4 installation fail to run. In my latest attempt I used the instructions found here, and installed Python 3.1.3 and PyQt 4.8.3 fo... | Which of the three installed PyQt DLL directories do I want? | I've tried installing Python and Qt several times but keep running into the same problem: The examples included in the PyQt4 installation fail to run. In my latest attempt I used the instructions found here, and installed Python 3.1.3 and PyQt 4.8.3 for Python 3.1, all are the 32-bit versions.
I'm running WinXP with ... | [
"You don't need to install Qt yourself. As you can see, PyQt brings it's own versions - so why not try putting that first in the PATH?\n"
] | [
3
] | [] | [] | [
"dll",
"installation",
"pyqt",
"python"
] | stackoverflow_0004947731_dll_installation_pyqt_python.txt |
Q:
Testing Apache/mod_jk/Tomcat configuration upgrade
We have begun upgrading hardware and software to a 64-bit architecture using Apache with mod_jk and four Tomcat servers (the new hardware). We need to be able to test this equipment with a large number of simultaneous connections while still actually doing things ... | Testing Apache/mod_jk/Tomcat configuration upgrade | We have begun upgrading hardware and software to a 64-bit architecture using Apache with mod_jk and four Tomcat servers (the new hardware). We need to be able to test this equipment with a large number of simultaneous connections while still actually doing things in the app (logging in, etc.)
I currently am using Pytho... | [
"Open Source Testing Tools\nNot knowing the full requirements makes it difficult, however something from the list might fit the bill.\n",
"In order to accomplish what I wanted to do, I just went back to basics. Mechanize is somewhat bulky, and there was a lot of bloat involved in the main functionality tests I ha... | [
1,
0
] | [] | [] | [
"apache",
"mod_jk",
"python",
"tomcat",
"web_scraping"
] | stackoverflow_0004936524_apache_mod_jk_python_tomcat_web_scraping.txt |
Q:
Removing duplicated lines from a txt file
I am processing large text files (~20MB) containing data delimited by line.
Most data entries are duplicated and I want to remove these duplications to only keep one copy.
Also, to make the problem slightly more complicated, some entries are repeated with an extra bit of i... | Removing duplicated lines from a txt file | I am processing large text files (~20MB) containing data delimited by line.
Most data entries are duplicated and I want to remove these duplications to only keep one copy.
Also, to make the problem slightly more complicated, some entries are repeated with an extra bit of info appended. In this case I need to keep the e... | [
"How about the following (in Python):\nprev = None\nfor line in sorted(open('file')):\n line = line.strip()\n if prev is not None and not line.startswith(prev):\n print prev\n prev = line\nif prev is not None:\n print prev\n\nIf you find memory usage an issue, you can do the sort as a pre-processing step usi... | [
12,
3,
2,
2,
1,
1,
1,
1
] | [] | [] | [
"awk",
"linux",
"python"
] | stackoverflow_0004948509_awk_linux_python.txt |
Q:
Python 2.6 GC appears to cleanup objects, but memory is not released
I have a program written in python 2.6 that creates a large number of short lived instances (it is a classic producer-consumer problem). I noticed that the memory usage as reported by top and pmap seems to increase when these instances are create... | Python 2.6 GC appears to cleanup objects, but memory is not released | I have a program written in python 2.6 that creates a large number of short lived instances (it is a classic producer-consumer problem). I noticed that the memory usage as reported by top and pmap seems to increase when these instances are created and never goes back down. I was concerned that some python module I was ... | [
"Python will release the objects, but it will not release the memory back to the operating system immediately. Instead, it will re-use the same segments for future allocations within the same interpreter.\nHere's a blog post about the issue: http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete... | [
8,
4
] | [] | [] | [
"memory",
"memory_leaks",
"python"
] | stackoverflow_0004949335_memory_memory_leaks_python.txt |
Q:
objects as keys in python dictionaries
I'm trying to use an object as a key in a python dictionary, but it's behaving in a way that I can't quite understand.
First I create a dictionary with my object as the key:
package_disseminators = {
ContentType("application", "zip", "http://other/property") : "one",
Cont... | objects as keys in python dictionaries | I'm trying to use an object as a key in a python dictionary, but it's behaving in a way that I can't quite understand.
First I create a dictionary with my object as the key:
package_disseminators = {
ContentType("application", "zip", "http://other/property") : "one",
ContentType("application", "zip") : "two"
}
Now... | [
"From the python documentation:\n\nA dictionary’s keys are almost\n arbitrary values. Values that are not\n hashable, that is, values containing\n lists, dictionaries or other mutable\n types (that are compared by value\n rather than by object identity) may\n not be used as keys.\n\nHashable is defined as fol... | [
41,
34
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004950155_dictionary_python.txt |
Q:
Get value from a dynamic url
My url looks like:
http://www.example.com/blah/prod/4/x/blah.html
Now if this page has sub-pages, it will look like:
http://www.example.com/blah/prod/4_2343/x/blah.html
i.e. after /prod/4 there will be a underscore than another number.
Again if this page has sub-pages, it will be:
ht... | Get value from a dynamic url | My url looks like:
http://www.example.com/blah/prod/4/x/blah.html
Now if this page has sub-pages, it will look like:
http://www.example.com/blah/prod/4_2343/x/blah.html
i.e. after /prod/4 there will be a underscore than another number.
Again if this page has sub-pages, it will be:
http://www.example.com/blah/prod/4_2... | [
"For example like this. A regexp that matches the pattern prod/???/x/blah, where ??? is any string consisting of numbers and underscores:\nimport re\npattern = re.compile('prod/([\\d_]+)/x/blah')\nquery = \"http://www.example.com/blah/prod/4_2343_234/x/blah.html\"\nresult = pattern.search(query).group(1)\nprint ... | [
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004949686_python_regex.txt |
Q:
A python code to convert a number from any base to the base of 10 giving errors . What is wrong with this code?
import math
def baseencode(number, base):
##Converting a number of any base to base10
if number == 0:
return '0'
for i in range(0,len(number)):
if number[i]!= [A-Z]:
... | A python code to convert a number from any base to the base of 10 giving errors . What is wrong with this code? | import math
def baseencode(number, base):
##Converting a number of any base to base10
if number == 0:
return '0'
for i in range(0,len(number)):
if number[i]!= [A-Z]:
num = num + number[i]*pow(i,base)
else :
num = num + (9 + ord(number[i])) *pow(i,base)
... | [
"Isn't int(x, base) what you need?\nint('20',5) # returns the integer 10\n\n",
"You're confusing Python with... Perl or something...\nif not ('A' <= number[i] <= 'Z'):\n\n",
"A more comprehensive solution to this problem may look like this:\nimport string\n\n# Possible digits from the lowest to the highest\nDIG... | [
17,
7,
4,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004946696_python.txt |
Q:
Selecting An Embedded Language
I'm making an application that analyses one or more series of data using several different algorithms (agents). I came to the idea that each of these agents could be implemented as separate Python scripts which I run using either the Python C API or Boost.Python in my app.
I'm a litt... | Selecting An Embedded Language | I'm making an application that analyses one or more series of data using several different algorithms (agents). I came to the idea that each of these agents could be implemented as separate Python scripts which I run using either the Python C API or Boost.Python in my app.
I'm a little worried about runtime overhead TB... | [
"Yes, tons. Lua and Python seems to be the most popular:\nEmbedding Lua\n\nhttp://www.lua.org/pil/24.html\nhttps://stackoverflow.com/questions/38338/why-is-lua-considered-a-game-language\nLua as a general-purpose scripting language?\n\nEmbedding Python\n\nhttp://docs.python.org/extending/embedding.html\n\nEmbedding... | [
10,
9,
5,
3,
2,
1,
0
] | [] | [] | [
"c++",
"lua",
"performance",
"perl",
"python"
] | stackoverflow_0002103728_c++_lua_performance_perl_python.txt |
Q:
Appending/formatting a string
In C# to format a string I do:
string a = String.Format("/blah/blah/{0}_{1}/blah.html", int1, int2)
In Python, does it convert integer to string automatically?
How would I do something similar to above in Python.?
A:
In Python 2.6 and above:
a = "/blah/blah/{0}_{1}/blah.html".forma... | Appending/formatting a string | In C# to format a string I do:
string a = String.Format("/blah/blah/{0}_{1}/blah.html", int1, int2)
In Python, does it convert integer to string automatically?
How would I do something similar to above in Python.?
| [
"In Python 2.6 and above:\na = \"/blah/blah/{0}_{1}/blah.html\".format(int1, int2)\n\nIn Python 2.7/3.1 and above, you could also do\na = \"/blah/blah/{}_{}/blah.html\".format(int1, int2)\n\nSee the docs on String formatting.\n",
"a = \"/blah/blah/%s_%s/blah.html\" % (int1, int2)\n\n"
] | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004950609_python.txt |
Q:
Django trans problems - not working in 100% cases
I've got a problem with using django's {% trans %} template function. I have values translated in my messages file and it gets translated in some cases. But not all of them.
I'm trying to debug the issue. I have a block of code like this - in which I'm iterating th... | Django trans problems - not working in 100% cases | I've got a problem with using django's {% trans %} template function. I have values translated in my messages file and it gets translated in some cases. But not all of them.
I'm trying to debug the issue. I have a block of code like this - in which I'm iterating through form's fields and outputting them:
<tr>
<... | [
"field.label_tag wraps your label inside a <label> tag. To just get the text, use field.label. This is explained here.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004950388_django_python.txt |
Q:
simple inter-process communication
I'm looking for a simple way to pass messages from one process (Perl script, short-lived) to another (Python script, long-running) - both processes local to the same machine.
I've done some research, but what I've found was either over my head or seemed unnecessarily complex - le... | simple inter-process communication | I'm looking for a simple way to pass messages from one process (Perl script, short-lived) to another (Python script, long-running) - both processes local to the same machine.
I've done some research, but what I've found was either over my head or seemed unnecessarily complex - leaving me a bit lost and confused.
I imag... | [
"It turns out that interprocess communication is, while on the surface straightforward, actually fraught with complications. Whatever anyone tells you here in terms of a simplified answer, always keep in mind that there is probably a lot of caveats that are being left unsaid. \nNow with that disclaimer out of the... | [
20,
11,
3
] | [] | [] | [
"ipc",
"perl",
"python"
] | stackoverflow_0004950120_ipc_perl_python.txt |
Q:
How to wrap this into a recursive call
I'm writing a little spider in python. It hits a page, gets all the links on the page according to a pattern, goes to each of those pages, and repeats.
I need to make this recursive somehow. Below are the url patterns:
www.example.com
Then I get all links based on a regex, t... | How to wrap this into a recursive call | I'm writing a little spider in python. It hits a page, gets all the links on the page according to a pattern, goes to each of those pages, and repeats.
I need to make this recursive somehow. Below are the url patterns:
www.example.com
Then I get all links based on a regex, then I visit each page.
Recursive part:
Say I... | [
"Just-recursion, in the manner you are asking for, might not be the best approach.\nFor one thing, if there are more than 1000 pages to be indexed, you might 'bottom out' the call stack and crash. For another, if you are not careful about releasing variables during recursion, it might end up consuming quite a bit ... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0004950740_python.txt |
Q:
Where can I find discussions regarding choice of Python issue trackers?
Is there somewhere a summary of discussions regarding issue tracker choice for Python development? If not, do you have some links to such discussions?
A:
The Python infrastructure committee was once tasked to propose a new bug tracker for py... | Where can I find discussions regarding choice of Python issue trackers? | Is there somewhere a summary of discussions regarding issue tracker choice for Python development? If not, do you have some links to such discussions?
| [
"The Python infrastructure committee was once tasked to propose a new bug tracker for python-dev, replacing SourceForge. Brett Cannon's report gives the outcome. As you probably know: the choice was made for Roundup.\n"
] | [
2
] | [] | [] | [
"issue_tracking",
"python"
] | stackoverflow_0004950930_issue_tracking_python.txt |
Q:
What if beautifulsoups call returns null?
pagelinks = myhtml.findAll('a')
for link in pagelinks:
do_stuff()
If pagelinks is null, will this error out?
How can I make pagelinks a collection of 0 items in case it is null?
A:
findAll returns an empty list [] when nothing matches
for link in pagelinks:
do_... | What if beautifulsoups call returns null? | pagelinks = myhtml.findAll('a')
for link in pagelinks:
do_stuff()
If pagelinks is null, will this error out?
How can I make pagelinks a collection of 0 items in case it is null?
| [
"findAll returns an empty list [] when nothing matches\nfor link in pagelinks:\n do_stuff() # never executed when findAll returns []\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004950863_beautifulsoup_python.txt |
Q:
os.path.relpath not returning a relative path when using drive as start point
Why is os.path.relpath, on Windows, not returning the proper relative path when using a drive as the start point, either explicit or implied (current directory)
>>> os.getcwd()
'U:\\projects'
>>> os.path.relpath(r'D:\foo\something', r"D:... | os.path.relpath not returning a relative path when using drive as start point | Why is os.path.relpath, on Windows, not returning the proper relative path when using a drive as the start point, either explicit or implied (current directory)
>>> os.getcwd()
'U:\\projects'
>>> os.path.relpath(r'D:\foo\something', r"D:\\")
'..\\foo\\something'
>>> os.chdir("D:\\")
>>> os.getcwd()
'd:\\'
>>> os.path.r... | [
"Issue is fixed under python 2.7.1\n\nIssue #5117: Fixed root directory\n related issue on posixpath.relpath()\n and ntpath.relpath().\n\n"
] | [
3
] | [] | [] | [
"path",
"python"
] | stackoverflow_0004950940_path_python.txt |
Q:
Getting progress message from a subprocess
I want to start a program which needs several minutes to complete. During this time I want to read the progress message of the program (which are printed on the stdout). The problem is that I cannot find a way to read out its output during its run.
The only function I fou... | Getting progress message from a subprocess | I want to start a program which needs several minutes to complete. During this time I want to read the progress message of the program (which are printed on the stdout). The problem is that I cannot find a way to read out its output during its run.
The only function I found to read out the output of a program is Popen.... | [
"Simplest is to call Popen with the keyword argument stdout=subprocess.PIPE.\np = subprocess.Popen([\"ls\"], stdout=subprocess.PIPE)\nwhile True:\n line = p.stdout.readline()\n if not line:\n break\n print line\n\n\nTo see this in action, here are two sample scripts. Make them both in the same direc... | [
21,
3,
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004951099_python_subprocess.txt |
Q:
can't import python extension
I'm trying to learn python extensions, and I created the simple noddy example c file and setup.py.
python.exe setup.py build gives me:
running build
running build_ext
building 'noddy' extension
creating build
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
C:\Prog... | can't import python extension | I'm trying to learn python extensions, and I created the simple noddy example c file and setup.py.
python.exe setup.py build gives me:
running build
running build_ext
building 'noddy' extension
creating build
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
C:\Program Files\Microsoft Visual Studio 8... | [
"Use the Visual Studio 2008 compiler to build the module.\nVS8 is Visual Studio 2005 and the modules compiled with that version are incompatible with Python 2.7 (same applies to modules compiled with Visual Studio 2010 btw.).\n"
] | [
3
] | [] | [] | [
"python",
"python_c_extension",
"windows"
] | stackoverflow_0004950547_python_python_c_extension_windows.txt |
Q:
What are the default URLs for Django's User Authentication system?
Django's User Authentication system ( http://docs.djangoproject.com/en/dev/topics/auth/ ) is incredibly helpful in working with users. However, the documentation talks about password reset forms and makes it seem like it takes care of it the same w... | What are the default URLs for Django's User Authentication system? | Django's User Authentication system ( http://docs.djangoproject.com/en/dev/topics/auth/ ) is incredibly helpful in working with users. However, the documentation talks about password reset forms and makes it seem like it takes care of it the same way it does user login/logout.
The default URL for login and logout is
/... | [
"If you look at django.contrib.auth.urls you can see the default views that are defined. That would be login, logout, password_change and password_reset.\n\nThese URLs are normally mapped to /admin/urls.py. This URLs file is\n provided as a convenience to those who want to deploy these URLs\n elsewhere.\n This f... | [
25
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004951203_django_python.txt |
Q:
Python module logging with eclipse
I am trying to get logging going across a couple of different modules using logging.config.fileConfig() My directory looks something like this:
> Package
> Source
__init__.py
SomeSource.py
> Test
__init__.py
SomeTests.py
__init__.py
Insid... | Python module logging with eclipse | I am trying to get logging going across a couple of different modules using logging.config.fileConfig() My directory looks something like this:
> Package
> Source
__init__.py
SomeSource.py
> Test
__init__.py
SomeTests.py
__init__.py
Inside in Package.__init__.py I have the foll... | [
"By default the verbosity of logging in an interactive interpreter session will be WARNING, so your INFO messages won't show (Eclipse or a plugin may set the verbosity differently).\nChange your .info calls to .warning calls - you should see some output (depending on how your configuration is set up in the conf fil... | [
0
] | [] | [] | [
"eclipse",
"logging",
"module",
"package",
"python"
] | stackoverflow_0004950909_eclipse_logging_module_package_python.txt |
Q:
How to close Toplevel window after the function it calls completes?
Edit:
let me include my code so I can get some specific help.
import Tkinter
def goPush():
win2=Tkinter.Toplevel()
win2.geometry('400x50')
Tkinter.Label(win2,text="If you have prepared as Help describes select Go otherwise select Go ... | How to close Toplevel window after the function it calls completes? | Edit:
let me include my code so I can get some specific help.
import Tkinter
def goPush():
win2=Tkinter.Toplevel()
win2.geometry('400x50')
Tkinter.Label(win2,text="If you have prepared as Help describes select Go otherwise select Go Back").pack()
Tkinter.Button(win2,text="Go",command=bounceProg).pack(... | [
"@Kosig It won't quit root. Ie. self.foo = tk.Toplevel(self) and then self.foo.destroy()\nFor example:\nclass Foo(tk.Frame):\n \"\"\"Foo example\"\"\"\n\n def __init__(self, master=None):\n \"\"\"Draw Foo GUI\"\"\"\n tk.Frame.__init__(self, master)\n self.grid()\n self.draw_window_... | [
8,
5,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004950359_python_tkinter.txt |
Q:
Why doesn't Django's per-site cache middleware work for me?
I am using Django 1.3 beta 1 and set up memcached. I made changes to my settings.py per Django's instructions:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}... | Why doesn't Django's per-site cache middleware work for me? | I am using Django 1.3 beta 1 and set up memcached. I made changes to my settings.py per Django's instructions:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
'LOCATION': '127.0.0.1:11211',
}
}
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCac... | [
"It appears that you have everything set up correctly. The only possible caveat I can see in the documentation is the following:\nThe cache middleware caches every page that doesn't have GET or POST parameters.\n\nUnfortunately, I'm assuming you already know this and it won't help you.\n"
] | [
0
] | [] | [] | [
"django",
"django_cache",
"django_middleware",
"memcached",
"python"
] | stackoverflow_0004918075_django_django_cache_django_middleware_memcached_python.txt |
Q:
How to make a field non modifiable on edit page but able to create on add page?
I have a scenario given below:
In my models.py
class Room(models.Model):
pop = models.ForeignKey('Pop', verbose_name="POP",
help_text="Pop this room belongs to", null=True,
blank... | How to make a field non modifiable on edit page but able to create on add page? | I have a scenario given below:
In my models.py
class Room(models.Model):
pop = models.ForeignKey('Pop', verbose_name="POP",
help_text="Pop this room belongs to", null=True,
blank=True)
.... other fields ....
class Pop(models.Model):
.... fields ....
In ... | [
"Option 2 is the best. You can override the get_form method in your RoomAdmin class to exclude the pop field when there is an object to edit:\ndef get_form(self, request, obj=None, **kwargs):\n # if there's an object and it has been previously saved\n if obj is not None and obj.id is not None:\n # add ... | [
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004951513_django_django_admin_python.txt |
Q:
Python, Conditionals - Are these equivalent?
if config == 'H/2' or 'H' or '2H': pass
if config == 'H/2' or config == 'H' or config == '2H': pass
A:
>>> config = 'H/2'
>>> config == 'H/2' or 'H' or '2H'
True
>>> config == 'H/2' or config == 'H' or config == '2H'
True
>>> config = 'H'
>>> config == 'H/2' or 'H' o... | Python, Conditionals - Are these equivalent? | if config == 'H/2' or 'H' or '2H': pass
if config == 'H/2' or config == 'H' or config == '2H': pass
| [
">>> config = 'H/2'\n>>> config == 'H/2' or 'H' or '2H'\nTrue\n>>> config == 'H/2' or config == 'H' or config == '2H'\nTrue\n\n>>> config = 'H'\n>>> config == 'H/2' or 'H' or '2H'\n'H'\n>>> config == 'H/2' or config == 'H' or config == '2H'\nTrue\n\n>>> config = 'R'\n>>> config == 'H/2' or 'H' or '2H'\n'H'\n>>> con... | [
8,
2,
1
] | [] | [] | [
"conditional_statements",
"python"
] | stackoverflow_0004951928_conditional_statements_python.txt |
Q:
Import path for decorator-wrapped function?
Assuming I have a decorator and a wrapped function like this:
def squared(method):
def wrapper(x, y):
return method(x*x, y*y)
return wrapper
@squared
def sum(x, y):
return x+y
I have other code that would like to call the undecorated version of the... | Import path for decorator-wrapped function? | Assuming I have a decorator and a wrapped function like this:
def squared(method):
def wrapper(x, y):
return method(x*x, y*y)
return wrapper
@squared
def sum(x, y):
return x+y
I have other code that would like to call the undecorated version of the sum function. Is there an import trick that can... | [
"def unwrap(fn):\n return fn.__wrapped__\n\ndef squared(method):\n def wrapper(x, y):\n return method(x*x, y*y)\n wrapper.__wrapped__ = method\n return wrapper\n\n@squared\ndef sum(x, y):\n return x+y\n\nsum(2,3) -> 13\nunwrap(sum)(2,3) -> 5\n\n",
"What about this? \ndef squared(met... | [
4,
3
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0004952227_decorator_python.txt |
Q:
try: except: not working
So I'm running into a problem where the try: except: mechanism doesn't seem to be working correctly in python.
Here are the contents of my two files.
pytest1.py
import pytest2
class MyError( Exception ):
def __init__( self, value ):
self.value = value
def __str__( sel... | try: except: not working | So I'm running into a problem where the try: except: mechanism doesn't seem to be working correctly in python.
Here are the contents of my two files.
pytest1.py
import pytest2
class MyError( Exception ):
def __init__( self, value ):
self.value = value
def __str__( self ):
return repr( self... | [
"The main python program is always imported as the module __main__.\nWhen you import pytest2, it doesn't reuse the existing module because the originally imported module has the name __main__ not pytest2. The result is that pytest1 is run multiple times generating multiple exception classes. __main__.MyError and py... | [
9,
2,
1
] | [] | [] | [
"exception",
"exception_handling",
"python"
] | stackoverflow_0004952134_exception_exception_handling_python.txt |
Q:
Executing Error in python
import unittest
service = ('u', 'urn:schemas-upnp-org:service:SwitchPower:1')
binary_light_type = 'urn:schemas-upnp-org:device:BinaryLight:1'
def on_new_device(dev):
""" Callback triggered when a new device is found.
"""
print 'Got new device:', dev.udn
print "Type 'list... | Executing Error in python | import unittest
service = ('u', 'urn:schemas-upnp-org:service:SwitchPower:1')
binary_light_type = 'urn:schemas-upnp-org:device:BinaryLight:1'
def on_new_device(dev):
""" Callback triggered when a new device is found.
"""
print 'Got new device:', dev.udn
print "Type 'list' to see the whole list"
i... | [
"The first one is simple: call it with something that is defined.\nThe second one is also simple: call it with an object that has a start_search attribute.\nBeyond that we don't know. You haven't explained what any of this code is and what it's supposed to do.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004952698_python.txt |
Q:
Embed pickle (or arbitrary) data in python script
In Perl, the interpreter kind of stops when it encounters a line with
__END__
in it. This is often used to embed arbitrary data at the end of a perl script. In this way the perl script can fetch and store data that it stores 'in itself', which allows for quite nic... | Embed pickle (or arbitrary) data in python script | In Perl, the interpreter kind of stops when it encounters a line with
__END__
in it. This is often used to embed arbitrary data at the end of a perl script. In this way the perl script can fetch and store data that it stores 'in itself', which allows for quite nice opportunities.
In my case I have a pickled object tha... | [
"With pickle you can also work directly on strings.\ns = pickle.dumps(obj)\npickle.loads(s)\n\nIf you combine that with \"\"\" (triple-quoted strings) you can easily store any pickled data in your file.\n",
"If the data is not particularly large (many K) I would just .encode('base64') it and include that in a tri... | [
4,
3,
2,
2
] | [] | [] | [
"embed",
"python"
] | stackoverflow_0001887968_embed_python.txt |
Q:
TkInter: destroying a number of buttons then recreating a (possibly different) number of buttons
I am new to Tkinter and am writing a simple tile flipping game to learn the basics. The idea is that when I start the app i get a "start new game" button, quit button and a grid size slider. I can then select a grid si... | TkInter: destroying a number of buttons then recreating a (possibly different) number of buttons | I am new to Tkinter and am writing a simple tile flipping game to learn the basics. The idea is that when I start the app i get a "start new game" button, quit button and a grid size slider. I can then select a grid size and hit start which brings up a n*n grid of red or green buttons (tiles) . By clicking on one i cha... | [
"It looks like you aren't resetting self.game_buttons. You set it to the empty list in __init__ when you probably should be doing that in init_game. Because it's not reset, the second time you run the game self.view.update() iterates over a list that contains the buttons from both games. Since half of those button... | [
1
] | [] | [] | [
"button",
"callback",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004952798_button_callback_python_tkinter_user_interface.txt |
Q:
Get DC++ hub information with python
Is there any way in which i can get a DC++ hub information like the online status of the hub, no. of users online, amount of data shared. I have access to the hubs, so that is not an issue.
A:
Write your own client (maybe using some hints, the ADC protocol is not too complex)... | Get DC++ hub information with python | Is there any way in which i can get a DC++ hub information like the online status of the hub, no. of users online, amount of data shared. I have access to the hubs, so that is not an issue.
| [
"Write your own client (maybe using some hints, the ADC protocol is not too complex) or reuse parts of pyDC. Looks like all you want to do is connect to a hub, scrape some information, and drop off, so you don't need to handle searching or sharing.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004952665_python.txt |
Q:
python string differences
I am seeing that a string comparison of two identical strings ('fraiser') in Python is failing. When using repr(str1) and repr(str2) I get different results, but I don't know how to interpret them or why they return different things. Any help?
>>> repr(list(lowerAndMakeSet(fileChunks))[3]... | python string differences | I am seeing that a string comparison of two identical strings ('fraiser') in Python is failing. When using repr(str1) and repr(str2) I get different results, but I don't know how to interpret them or why they return different things. Any help?
>>> repr(list(lowerAndMakeSet(fileChunks))[3])
"'frasier'"
>>> repr(list(... | [
"Your second \"string\" that you are repring is actually a list and not a string. You can see this if you do type(list(lowerAndMakeSet(c))[2]).\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004952940_python.txt |
Q:
Can't listen to https port 443 on EC2 (Amazon Linux)
I am running an Amazon Linux image on EC2. However, I cannot open port 443 when I launch my twisted server.
I created a security group and verified that the instance was using it which allowed traffic on HTTPS. (HTTPS tcp 443 443 0.0.0.0/0).
Here is the output:... | Can't listen to https port 443 on EC2 (Amazon Linux) | I am running an Amazon Linux image on EC2. However, I cannot open port 443 when I launch my twisted server.
I created a security group and verified that the instance was using it which allowed traffic on HTTPS. (HTTPS tcp 443 443 0.0.0.0/0).
Here is the output:
ERROR:root:Exception launching the json rpc server
Traceb... | [
"You might be running the program that uses port lower than 1024. \nTry running the program using root or sudo.\n",
"Do you have another server on the machine already listening on port 443? It sounds to me like the port is opened by another process so your process can't access it.\n"
] | [
3,
0
] | [] | [] | [
"amazon_ec2",
"python",
"twisted"
] | stackoverflow_0004952881_amazon_ec2_python_twisted.txt |
Q:
How to match exact "multiple" strings in Python
I've got a list of exact patterns that I want to search in a given string. Currently I've got a real bad solution for such a problem.
pat1 = re.compile('foo.tralingString')
mat1 = pat1.match(mystring)
pat2 = re.compile('bar.trailingString')
mat2 = pat2.match(mystrin... | How to match exact "multiple" strings in Python | I've got a list of exact patterns that I want to search in a given string. Currently I've got a real bad solution for such a problem.
pat1 = re.compile('foo.tralingString')
mat1 = pat1.match(mystring)
pat2 = re.compile('bar.trailingString')
mat2 = pat2.match(mystring)
if mat1 or mat2:
# Do whatever
pat = re.comp... | [
"You could do a trivial regex that combines those two:\npat = re.compile('foo|bar')\nif pat.match(mystring):\n # Do whatever\n\nYou could then expand the regex to do whatever you need to, using the | separator (which means or in regex syntax)\nEdit: Based upon your recent edit, this should do it for you:\npat = ... | [
29,
10,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004953272_python_regex.txt |
Q:
how to estimate the (power of a signal at a given frequency) vs. time in python
I'm looking for a good way to estimate the power of a signal (regularly sampled say at 10 kHz) vs. time at just one frequency (say 50 Hz). I could calculate the spectrogram, and then take a slice of it at the target frequency. This s... | how to estimate the (power of a signal at a given frequency) vs. time in python | I'm looking for a good way to estimate the power of a signal (regularly sampled say at 10 kHz) vs. time at just one frequency (say 50 Hz). I could calculate the spectrogram, and then take a slice of it at the target frequency. This seems inefficient though, since I only care about the power at one frequency vs. time.... | [
"There's a ton of ways of doing this. One crude but effective way is to apply a bandpass filter (at 50Hz), thereby eliminating all other signals, and then calculate the RMS power of the last N samples.\nAnother is you can do a windowed FFT, but not actually FFT - just calculate the bin you want. The window can be w... | [
7
] | [] | [] | [
"matplotlib",
"python",
"scientific_computing",
"signal_processing"
] | stackoverflow_0004953250_matplotlib_python_scientific_computing_signal_processing.txt |
Q:
python byte file readign screwup
so I have
f = open(infile, mode = 'rb')
while f:
line = f.read(int(k))
ints = list(line)
print(type(line))
etc etc....theoretically this is supposed to read the file in byte mode since I added 'b' to the mode...but then when the console outputs the... | python byte file readign screwup | so I have
f = open(infile, mode = 'rb')
while f:
line = f.read(int(k))
ints = list(line)
print(type(line))
etc etc....theoretically this is supposed to read the file in byte mode since I added 'b' to the mode...but then when the console outputs the print(type(line))....it would return ... | [
"They are still characters. All 'b' does is prevent line endings from being changed.\nEDIT: Actually the byte type is new in python 3 and using 'b' will return a bytearray.\n",
"I think, you should be using Python 2. (2.6/2.7) There str is a 8bit byte, so the the out is displayed as 'str'. If you use Python 3 wit... | [
2,
0
] | [] | [] | [
"byte",
"file",
"file_io",
"python"
] | stackoverflow_0004953316_byte_file_file_io_python.txt |
Q:
How to guard against nulls in python
In python, how do I check if a string is either null or empty?
In c# we have String.IsNullOrEmpty(some_string)
Also, I'm doing some regex like:
p = re.compile(...)
a = p.search(..).group(1)
This will break if group doesn't have something at index 1, how do guard against this ... | How to guard against nulls in python | In python, how do I check if a string is either null or empty?
In c# we have String.IsNullOrEmpty(some_string)
Also, I'm doing some regex like:
p = re.compile(...)
a = p.search(..).group(1)
This will break if group doesn't have something at index 1, how do guard against this ? i.e. how would you re-write those 2 line... | [
"Just check for it. Explicit is better than implicit, and one more line won't kill you.\na = p.search(...)\nif a is not None:\n # ...\n\n",
"The typical way with re module is:\nm = p.search(..)\nif m: \n a = m.group(1)\n\nor \nm = p.search(..)\na = m.group(1) if m else ''\n\nUnfortunately (or fortunately), ... | [
6,
2,
1,
0
] | [
"This might be incorrect but I think you can use if p != None (or it might be null/NULL)\n"
] | [
-2
] | [
"python"
] | stackoverflow_0004950559_python.txt |
Q:
How do I access the original response headers that contain a redirect when using urllib2.urlopen
I'm trying to parse the location header of an HTTP response that is returned after using urllib2.urlopen, but the only response headers that I receive are from the target redirect --- not the original response that con... | How do I access the original response headers that contain a redirect when using urllib2.urlopen | I'm trying to parse the location header of an HTTP response that is returned after using urllib2.urlopen, but the only response headers that I receive are from the target redirect --- not the original response that contains the location header.
I have followed other questions on Stack Overflow that suggest to subclass ... | [
"urllib2 does a transparent redirection, but as you said, you can subclass HTTPRedirectHandler and use that as an opener to get your required values.\nimport urllib2\n\nclass SmartRedirectHandler(urllib2.HTTPRedirectHandler):\n def http_error_302(self, req, fp, code, msg, headers):\n result = urllib2.HTTP... | [
6
] | [] | [] | [
"header",
"location",
"python",
"urllib2",
"urlopen"
] | stackoverflow_0004953487_header_location_python_urllib2_urlopen.txt |
Q:
Python find first network hop
I need to find the first network hop is in a python program on Linux. I can't just depend on the default gateway being the first hop, because some of the network software on the box may (or may not) insert catch all routes:
0.0.0.0/1
128.0.0.0/1
I've thought about popen'ing a tracepa... | Python find first network hop | I need to find the first network hop is in a python program on Linux. I can't just depend on the default gateway being the first hop, because some of the network software on the box may (or may not) insert catch all routes:
0.0.0.0/1
128.0.0.0/1
I've thought about popen'ing a tracepath -m 1 <some ip> and parsing the o... | [
"What do the \"catch all\" routes do? If they are simply gateway routes, doing a route lookup would still work. You can do something like:\n$ ip route get <ip> | head -1 | awk '{ print $3 }'\n\nThis would print the gateway address for an off-link route:\n$ ip route get 8.8.8.8 | head -1 | awk '{ print $3 }'\n192.16... | [
1
] | [] | [] | [
"networking",
"python",
"routing"
] | stackoverflow_0004953629_networking_python_routing.txt |
Q:
Does Python 2.6 have a built in URL parameters parser?
Given a URl, how can I get a dictionary of parameters back?
A:
http://docs.python.org/library/urlparse.html
edit: It returns a tuple of the url parameters. If you absolutely need to have it be in a dictionnary looks like you will have to implement it yoursel... | Does Python 2.6 have a built in URL parameters parser? | Given a URl, how can I get a dictionary of parameters back?
| [
"http://docs.python.org/library/urlparse.html\nedit: It returns a tuple of the url parameters. If you absolutely need to have it be in a dictionnary looks like you will have to implement it yourself. (get the tuple then assign it to dict)\nstring = \"addressing scheme network location path query fragment_identifier... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0004953819_python.txt |
Q:
python: random letters from a given string
how can i take random letters from a given string in python..i've tried certain codes but all generated letters different from the string's.
A:
import random
random.choice('string')
# If you want more than 1 char, say n
''.join(random.sample('string',n))
| python: random letters from a given string | how can i take random letters from a given string in python..i've tried certain codes but all generated letters different from the string's.
| [
"import random\nrandom.choice('string')\n# If you want more than 1 char, say n\n''.join(random.sample('string',n))\n\n"
] | [
11
] | [] | [] | [
"python"
] | stackoverflow_0004953959_python.txt |
Q:
python function parameter screwing up
so I have
def gcd(a,b):
if a == 0:
return b
while b != 0:
if a > b:
a = a - b
else:
b = b - a
return a
but then when I call gcd(1,2) from the console, the error
Traceback (most recent c... | python function parameter screwing up | so I have
def gcd(a,b):
if a == 0:
return b
while b != 0:
if a > b:
a = a - b
else:
b = b - a
return a
but then when I call gcd(1,2) from the console, the error
Traceback (most recent call last):
File "", line 1, in
G.gcd... | [
"You're calling the function as a method. Add \"self\" as the first argument and it'll work.\n",
"You have not posted all of your code. The code you didn't post looks like this:\nclass SomeClass:\n\n def gcd(a,b):\n if a == 0:\n return b\n while b != 0:\n if a > b:\... | [
7,
5,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"function",
"parameters",
"python"
] | stackoverflow_0004953112_function_parameters_python.txt |
Q:
Create Excel XML files from Python
I need to create Excel XML files from Python.
The Excel XML format is fairly simple. I looked at a a sample xml file saved from Excel 2003 and it is fairly simple.
I'm looking for a a Pythonic, ready made library to create such xml files instead of reinventing one.
Something t... | Create Excel XML files from Python | I need to create Excel XML files from Python.
The Excel XML format is fairly simple. I looked at a a sample xml file saved from Excel 2003 and it is fairly simple.
I'm looking for a a Pythonic, ready made library to create such xml files instead of reinventing one.
Something that I can use as below:
book = Expy.Work... | [
"give pythonOffice a try \n",
"If you are on windows with Excel installed, you could look into Excel Automation.\nfrom win32com import client\nexcel_app = client.Dispatch(\"Excel.Application\")\n# check VBA documentation on automating excel...\n\n",
"xlwt will write Excel files from python, but I'm not sure if ... | [
3,
1,
1
] | [] | [] | [
"excel",
"python",
"xml"
] | stackoverflow_0003345530_excel_python_xml.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.