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:
Why won't this python script work on wild cards in filenames in Win XP?
What should I change to make in work on Windows-XP keeping in mind we are working on Python 2-4 ?
"""
Author: Matt Weber
Date: 03/04/07
Renames files based on the input options.
"""
import os
import sys
from optparse import OptionParser
d... | Why won't this python script work on wild cards in filenames in Win XP? | What should I change to make in work on Windows-XP keeping in mind we are working on Python 2-4 ?
"""
Author: Matt Weber
Date: 03/04/07
Renames files based on the input options.
"""
import os
import sys
from optparse import OptionParser
def RenameFile(options, filepath):
"""
Renames a file with the given optio... | [
"Programming languages generally don't support shell globbing without you telling it to. You're going to want to use the Globbing module to get that functionality.\n",
"I think smth like this must work for you\nimport glob#on the top of script\n#.....\nfor filename in args:\n for match in glob.iglob(filename)... | [
2,
2
] | [] | [] | [
"python",
"python_2.4",
"wildcard"
] | stackoverflow_0004068383_python_python_2.4_wildcard.txt |
Q:
Python: NameError: global name 'foobar' is not defined
I have written the following class:
class myClass(object):
def __init__(self):
pass
def foo(self, arg1, arg2):
pp = foobar(self, arg1, arg2)
if pp:
return 42
else
return -666
def foobar(self... | Python: NameError: global name 'foobar' is not defined | I have written the following class:
class myClass(object):
def __init__(self):
pass
def foo(self, arg1, arg2):
pp = foobar(self, arg1, arg2)
if pp:
return 42
else
return -666
def foobar(self, arg1, arg2):
if arg1 == arg2:
return ... | [
"Python doesn't scope code to the local class automatically; you need to tell it to.\npp = self.foobar(arg1, arg2)\n\nhttp://docs.python.org/tutorial/classes.html\n"
] | [
52
] | [] | [] | [
"nameerror",
"namespaces",
"python"
] | stackoverflow_0004068785_nameerror_namespaces_python.txt |
Q:
Making specific frequency (ranges) louder
I want to make certain frequencies in a sequence of audio data louder. I have already analyzed the data using FFT and have gotten a value for each audio frequency in the data. I just have no idea how I can use the frequencies to manipulate the sound data itself.
From what ... | Making specific frequency (ranges) louder | I want to make certain frequencies in a sequence of audio data louder. I have already analyzed the data using FFT and have gotten a value for each audio frequency in the data. I just have no idea how I can use the frequencies to manipulate the sound data itself.
From what I understand so far, data is encoded in such a ... | [
"You are looking for a graphic equalizer. Some quick Googling turned up rbeq, which seems to be a plugin for Rhythmbox written in Python. I haven't looked through the code to see if the actual EQ part is written in Python or is just controlling something in the host, but I recommend looking through their source.\... | [
1
] | [] | [] | [
"audio",
"frequency",
"python"
] | stackoverflow_0004069157_audio_frequency_python.txt |
Q:
Backport of builtin function bin() for python 2.4
I wrote a program that uses builtin function bin(), but this function is new in Python version 2.6 and I would like to run this application also in Python versions 2.4 and 2.5.
Is there some backport of bin() for 2.4?
A:
You can try this version (credit goes to t... | Backport of builtin function bin() for python 2.4 | I wrote a program that uses builtin function bin(), but this function is new in Python version 2.6 and I would like to run this application also in Python versions 2.4 and 2.5.
Is there some backport of bin() for 2.4?
| [
"You can try this version (credit goes to the original author):\ndef bin(x):\n \"\"\"\n bin(number) -> string\n\n Stringifies an int or long in base 2.\n \"\"\"\n if x < 0: \n return '-' + bin(-x)\n out = []\n if x == 0: \n out.append('0')\n while x > 0:\n out.append('01... | [
6
] | [] | [] | [
"backport",
"binary",
"built_in",
"python"
] | stackoverflow_0004069392_backport_binary_built_in_python.txt |
Q:
How does Python evaluate this expression?
How does Python evaluate the following expression? anim1 gets executed after anim2. How does a simple + operator that?
anim1 = Animation(duration=1, center=(100,100) type='delta')
anim2 = Animation(duration=1, rotation=45 type='delta')
anim = anim1 + anim2
A:
This will... | How does Python evaluate this expression? | How does Python evaluate the following expression? anim1 gets executed after anim2. How does a simple + operator that?
anim1 = Animation(duration=1, center=(100,100) type='delta')
anim2 = Animation(duration=1, rotation=45 type='delta')
anim = anim1 + anim2
| [
"This will call anim1.__add__(anim2).\nIn order to understand what is happening under the hood you have to inspect the definition of __add__ method from Animation class.\n",
"In Python, you can redefine the behavior of the mathematical operators. If I understood your question, Animation probably redefines the \"+... | [
8,
3,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0004069366_python_syntax.txt |
Q:
Python: problems with csvwriter
I am attempting to write data (mostly dates, booleans and float data types) into a CSV file format. Here is a snippet of my code:
# Write data to file
with open(OUTPUT_DIR + output_filename,'w') as outputfile:
wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
for ... | Python: problems with csvwriter | I am attempting to write data (mostly dates, booleans and float data types) into a CSV file format. Here is a snippet of my code:
# Write data to file
with open(OUTPUT_DIR + output_filename,'w') as outputfile:
wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
for x, y in datarows.items():
a,b... | [
"Try wrtr.writerow([a,b,c,d,e,f,g]) instead.\nwriterow() parameter must be a list of values, not a text line. The idea of csv.writer is that it will format row values according to CSV rules.\nThe result you have is due to the fact that writerow() interpreted your rowstr string as a list of characters.\n",
"look a... | [
5,
3
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004069418_csv_python.txt |
Q:
How to add hooks in twisted.web (or twisted.web2)?
How can I add a hook before and after processing a request on twisted.web (twisted.web2 is fine too)? The equivalent of webpy's:
app = web.application(urls, globals())
app.add_processor(web.loadhook(my_attach_callback))
app.add_processor(web.unloadhook(my_detach_c... | How to add hooks in twisted.web (or twisted.web2)? | How can I add a hook before and after processing a request on twisted.web (twisted.web2 is fine too)? The equivalent of webpy's:
app = web.application(urls, globals())
app.add_processor(web.loadhook(my_attach_callback))
app.add_processor(web.unloadhook(my_detach_callback))
Thanks!
| [
"One approach Twisted Web allows is to insert an extra resource into the resource hierarchy the only purpose of which is to run your custom hooks, rather than to actually handle a segment of the request URL as resources typically do.\nYou can find an implementation of this approach in twisted/web/_auth/wrapper.py w... | [
1
] | [] | [] | [
"callback",
"hook",
"python",
"twisted"
] | stackoverflow_0001058300_callback_hook_python_twisted.txt |
Q:
Python. Replacing text between html tags
I want to write a function that highlights some text.
It takes a HTML string as input and returns HTML string with additional html tags.
Example:
Input string (need to highlight the word "text"):
<div>
<a href="..." title="text to highlight">Some text to highlight</a>
<a hr... | Python. Replacing text between html tags | I want to write a function that highlights some text.
It takes a HTML string as input and returns HTML string with additional html tags.
Example:
Input string (need to highlight the word "text"):
<div>
<a href="..." title="text to highlight">Some text to highlight</a>
<a href="..." title="text to highlight">Some other ... | [
"Look at Beautiful Soup. \n"
] | [
4
] | [] | [] | [
"html",
"python",
"regex",
"replace",
"tags"
] | stackoverflow_0004069453_html_python_regex_replace_tags.txt |
Q:
Python and psycopg detect network error
When connected to a postgresql database using psycopg and I pull the network cable I get no errors. How can I detect this in code to notify the user?
A:
You will definitely get an error the next time you try and execute a query, so I wouldn't worry if you can't alert t... | Python and psycopg detect network error | When connected to a postgresql database using psycopg and I pull the network cable I get no errors. How can I detect this in code to notify the user?
| [
"You will definitely get an error the next time you try and execute a query, so I wouldn't worry if you can't alert the user at the exact instance they lose there network connection.\n",
"psycopg can't detect what happens with the network. For example, if you unplug your ethernet cable, replug it and execute a qu... | [
0,
0
] | [] | [] | [
"postgresql",
"psycopg",
"python"
] | stackoverflow_0004061635_postgresql_psycopg_python.txt |
Q:
How can I build web file uploader that will allow multiple file uploads at once?
When you upload files to attach to a gmail message it lets you select multiple files from the browser file selector to attach at once. How could I build the same effect with a Django/Python/jquery site? I want to let the user upload... | How can I build web file uploader that will allow multiple file uploads at once? | When you upload files to attach to a gmail message it lets you select multiple files from the browser file selector to attach at once. How could I build the same effect with a Django/Python/jquery site? I want to let the user upload multiple files at once (if you hold down ctrl gmail file selector can select multiple... | [
"I recommend you using a jQuery plugin called Uploadify\n",
"This is only supported in the latest browsers (read: not IE), but to enable the ability to select multiple files from a single file input field is done by adding multiple=\"multiple\" to the input element, like so:\n<input type=\"file\" multiple=\"multi... | [
2,
1
] | [] | [] | [
"browser",
"django",
"file_upload",
"jquery",
"python"
] | stackoverflow_0004070127_browser_django_file_upload_jquery_python.txt |
Q:
Fetching nested child records in django framework
This project is being developed in python and django.
As per my requirement I want to querying all the products from the categories upto two to three level up...
My entity structure is as follows.
Category:
- Name
- ParentCategory
Product:
- ID
- Name
- Category
... | Fetching nested child records in django framework | This project is being developed in python and django.
As per my requirement I want to querying all the products from the categories upto two to three level up...
My entity structure is as follows.
Category:
- Name
- ParentCategory
Product:
- ID
- Name
- Category
Here are sample records which I want to query.
Category... | [
"What about thinking an implementation of 2-interval graphs ?\n",
"You can use something like django-mptt to store hierarchical data(your Categories model) in a database. It provides additional methods to retrieve all descendants of certain element. \nAnd using \nProduct.objects.filter(category__in=...)\nyou can ... | [
1,
1,
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004070082_django_django_models_python.txt |
Q:
'Unloading' a Python module and 'unbinding' associated APIs
I have a program which embeds Python (via Boost.Python), and provides an 'extension' framework. I wish to unify these two parts by allowing extensions to load a set of Python bindings for their API, however I'm confused as to how I would I 'unregister' t... | 'Unloading' a Python module and 'unbinding' associated APIs | I have a program which embeds Python (via Boost.Python), and provides an 'extension' framework. I wish to unify these two parts by allowing extensions to load a set of Python bindings for their API, however I'm confused as to how I would I 'unregister' these APIs when the plugin is unloaded.
Is this even possible with... | [
"There is a related discussion about unloading/reloading python modules. Check out the 3rd answer (here), the one that starts off with:\n\nTo cover my shame, here is a Python list thread that discusses how to delete a module. The summary: it can be especially difficult if the module is not pure python.\n\n"
] | [
3
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0004070424_boost_boost_python_c++_python.txt |
Q:
extract a methods block from a module/class
I would like to extract a block of statments (function) from souce code if some condition is met. e.g in the following code snippet, i would like to extract the function method2() and all its statements to another file for analyis
class MyClass:
def __init__(self):
... | extract a methods block from a module/class | I would like to extract a block of statments (function) from souce code if some condition is met. e.g in the following code snippet, i would like to extract the function method2() and all its statements to another file for analyis
class MyClass:
def __init__(self):
pass
def method1(self):
pass
def me... | [
"use inspect.getsource\nimport inspect\n\nclass MyClass:\n def __init__(self):\n pass\n def method1(self):\n pass\n def method2(self):\n a = 1\n def method2(self):\n print 'xyz'\n\nprint inspect.getsource(MyClass.method2)\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004070774_python.txt |
Q:
South django.db.utils.IntegrityError: django_content_type.name may not be NULL while running unit tests
I'm getting this error django.db.utils.IntegrityError: django_content_type.name may not be NULL while running tests via nosetest.
I've done everything as told in south tutorial - initial migration, fake migratio... | South django.db.utils.IntegrityError: django_content_type.name may not be NULL while running unit tests | I'm getting this error django.db.utils.IntegrityError: django_content_type.name may not be NULL while running tests via nosetest.
I've done everything as told in south tutorial - initial migration, fake migration etc.
Running site normally via runserver command works like charm, but while using test command - above err... | [
"Ok - I've managed to solve the problem on my own. \nSeems to me that there is a problem integrating south, nose and in-memory db which is created by the django test command.\nAll I had to do is to define TEST_NAME in my developement settings - like this:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.... | [
0
] | [] | [] | [
"django",
"django_south",
"nose",
"python",
"unit_testing"
] | stackoverflow_0004065806_django_django_south_nose_python_unit_testing.txt |
Q:
Objects seems to be deleted if not assigned to object variable in PySide
I'm trying to use QStandardItemModel to represent a hierarchy of data, but when I'm adding QStandardItems to the model, I have to assign them in object member variables, or the objects seems to be deleted.
For example
self.tree_model = QStand... | Objects seems to be deleted if not assigned to object variable in PySide | I'm trying to use QStandardItemModel to represent a hierarchy of data, but when I'm adding QStandardItems to the model, I have to assign them in object member variables, or the objects seems to be deleted.
For example
self.tree_model = QStandardItemModel()
self.tree_model.setHorizontalHeaderLabels(['Category'])
self.ou... | [
"Your object get garbage collected since no more (Python) references to it exist.\nThis behavior is described in the 'things to be aware of' in the PyQt documentation.\nMost of these problems (in PyQt land) can be avoided by correct parenting (which makes Qt take ownership instead of PyQt).\n"
] | [
4
] | [] | [] | [
"pyside",
"python",
"qt4"
] | stackoverflow_0004071740_pyside_python_qt4.txt |
Q:
How to compare an item in a queue to an item in a set?
REDIT: Was trying to avoid just placing the entire block of code on the forum and saying fix it for me, but here it is, to simply the process of determining the error:
#! /usr/bin/python2.6
import threading
import Queue
import sys
import urllib
import urllib2
... | How to compare an item in a queue to an item in a set? | REDIT: Was trying to avoid just placing the entire block of code on the forum and saying fix it for me, but here it is, to simply the process of determining the error:
#! /usr/bin/python2.6
import threading
import Queue
import sys
import urllib
import urllib2
from urlparse import urlparse
from lxml.html import parse, t... | [
"I don't understand one detail of this code: the queue is marked as task_done if there is any new link found in self.queue_links, but not as a matter of course in self.crawl. I'd have thought that this code would make more sense:\ndef crawl(self, tgt):\n try:\n url = urlparse(tgt)\n self.crawled_li... | [
0
] | [] | [] | [
"python",
"queue",
"set"
] | stackoverflow_0004070650_python_queue_set.txt |
Q:
Infinite yield problem
Here is my simple code
class Fibonacci:
@staticmethod
def series():
fprev = 1
fnext = 1
yield fnext
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
under10 = (i for i in Fibonacci.series() if i<10)
for i in under10 :
... | Infinite yield problem | Here is my simple code
class Fibonacci:
@staticmethod
def series():
fprev = 1
fnext = 1
yield fnext
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
under10 = (i for i in Fibonacci.series() if i<10)
for i in under10 :
print i
It's absolutely o... | [
"How should the interpreter know that all future numbers will be < 10? It would have to either know (somehow) that it’s churning out the Fibonacci series, or it would have to inspect the whole series.\nIt can’t do the first, so it does the second.\nYou can fix this by using itertools.takewhile:\nimport itertools\n\... | [
16,
1,
0
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0004071207_generator_python.txt |
Q:
SqlAlchemy Select Relation Type
I have a simple One-to-Many relation mapped with SqlAlchemy:
Base = declarative_base()
class Type(Base):
__tablename__ = "entity_types"
type = Column(String(100), primary_key=True)
description = Column(String(300))
class Entity(Base):
__tablename__ = "entities"
... | SqlAlchemy Select Relation Type | I have a simple One-to-Many relation mapped with SqlAlchemy:
Base = declarative_base()
class Type(Base):
__tablename__ = "entity_types"
type = Column(String(100), primary_key=True)
description = Column(String(300))
class Entity(Base):
__tablename__ = "entities"
id = Column(Integer, primary_key... | [
"I've just figured it out:\nsession.query(ActionType).filter(ActionType.actions.any()).all()\n\nThe any() does the trick.\n"
] | [
1
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004071455_python_sql_sqlalchemy.txt |
Q:
Python - datetime of a specific timezone
I am having the hardest time trying to get the current time in EDT timezone.
print datetime.time(datetime.now()).strftime("%H%M%S")
datetime.now([tz]) has an optional tz argument, but it has to be of type datetime.tzinfo... I have not ben able to figure out how to define a... | Python - datetime of a specific timezone | I am having the hardest time trying to get the current time in EDT timezone.
print datetime.time(datetime.now()).strftime("%H%M%S")
datetime.now([tz]) has an optional tz argument, but it has to be of type datetime.tzinfo... I have not ben able to figure out how to define a tzinfo object for Eastern timezone... Seems l... | [
"I am not very conversent about the EDT time zone but this example should serve your purpose.\nimport datetime\n\ndatetime.datetime.now must be passed the time zone info which should be of type datetime.tzinfo. Here is a class that implements that with some of the required functions. I am providing no day light sav... | [
20,
8
] | [] | [] | [
"datetime",
"python",
"timezone"
] | stackoverflow_0004071924_datetime_python_timezone.txt |
Q:
does anybody know a simple base for a plug in python application?
I'm discovering python, and I want to create a plug in application, I guess this is simple using python, but it will be nice create a generic start point application.
To be more specific, it could be a file.py that reads a XML or INI file to get the... | does anybody know a simple base for a plug in python application? | I'm discovering python, and I want to create a plug in application, I guess this is simple using python, but it will be nice create a generic start point application.
To be more specific, it could be a file.py that reads a XML or INI file to get the plug in's directory path, then load all .py files as plug in
Any Ideas... | [
"Since you are just starting out, I think it would be best to do all the work yourself so you really understand what is happening. It's not rocket science, and actually makes a fun learning experience IMO. \nStart by forcing a hard-coded path to plugins. For example, ~/.myapp/plugins. In there, assume each .py file... | [
2,
0
] | [] | [] | [
"plugins",
"python"
] | stackoverflow_0004033698_plugins_python.txt |
Q:
Django Paginate CPU Time scaling with number of selected objects not displayed objects
I have a simple database with about 3900 entries, and am using a generic view (django.views.generic.list_detail.object_list) with its django-pagination (through paginate_by) to browse the data in the database, but some queries a... | Django Paginate CPU Time scaling with number of selected objects not displayed objects | I have a simple database with about 3900 entries, and am using a generic view (django.views.generic.list_detail.object_list) with its django-pagination (through paginate_by) to browse the data in the database, but some queries are very slow.
The weird thing is that despite only showing 50 objects per page the rendering... | [
"When django does pagination it will use standard QuerySet slicing to get the results, this means it will use LIMIT and OFFSET. \nYou can view the SQL the ORM generates by calling str() on the .query attribute of the QuerySet:\n print MyModel.objects.all().query\n print MyModel.objects.all()[50:100].query\n\n... | [
3
] | [] | [] | [
"django",
"django_pagination",
"python"
] | stackoverflow_0004072063_django_django_pagination_python.txt |
Q:
how to send a tuple value as an arg to a function started as a thread?
I have a class function that I want to start up as a thread. The function takes as its argument a tuple value. The function works fine but my initial setup throws a TypeError. Here's some sample code:
import threading
class Test:
def __... | how to send a tuple value as an arg to a function started as a thread? | I have a class function that I want to start up as a thread. The function takes as its argument a tuple value. The function works fine but my initial setup throws a TypeError. Here's some sample code:
import threading
class Test:
def __init__(self):
t = threading.Thread(target=self.msg, args=(2,1))
... | [
"args takes a tuple of arguments to pass to the function. When you say args=(2,1) you're not telling it to call msg with a single argument (2,1); you're telling it to call it with two arguments, 2 and 1.\nYou want args=((2,1),).\n",
"This is going to look really ugly, but I believe it should be args=((2,1),) (or... | [
6,
1
] | [] | [] | [
"arguments",
"multithreading",
"python"
] | stackoverflow_0004072397_arguments_multithreading_python.txt |
Q:
Cutting down a list based on events being in between two datetimes
I have a list of object that, among other bits of data, include a date, and I need to create a list of all the objects where that date falls anytime last month, i.e. midnight on the 1st of last month < target data < midnight on the 1st of this mont... | Cutting down a list based on events being in between two datetimes | I have a list of object that, among other bits of data, include a date, and I need to create a list of all the objects where that date falls anytime last month, i.e. midnight on the 1st of last month < target data < midnight on the 1st of this month.
I also need the number of total objects that meet this criteria.
Righ... | [
"Instead of get_recent_posts() I would use get_page_list():\nfrom datetime import datetime, timedelta\n\nthis_month_start = datetime.now().date().replace(day=1)\nprev_month_start = (this_month_start - timedelta(days=1)).replace(day=1)\n\npages = blog.get_page_list()\nlast_month_pages = [\n p for p in pages\n if p... | [
2
] | [] | [] | [
"datetime",
"python",
"python_datetime"
] | stackoverflow_0004072561_datetime_python_python_datetime.txt |
Q:
How to wrap a proper generator function around a SAX Parser
I've got 35.5Mb .XLSM file. When the actual usable content is expanded, it swamps DOM parsers like element tree exhausting memory after a long, long running time.
When using a SAX parser, however, the ContentHandler seems to be constrained to accumulate ... | How to wrap a proper generator function around a SAX Parser | I've got 35.5Mb .XLSM file. When the actual usable content is expanded, it swamps DOM parsers like element tree exhausting memory after a long, long running time.
When using a SAX parser, however, the ContentHandler seems to be constrained to accumulate rows in a temporary file. Which is a little irritating because t... | [
"\"\"\"I've got 35.5Mb .XLSM file. When the actual usable content is expanded, it swamps DOM parsers like element tree exhausting memory after a long, long running time.\"\"\"\nI don't understand this. Things you should be using:\nimport xml.etree.cElementTree as ET\n\nET.iterparse(sourcefile) # sourcefile being a ... | [
5,
1
] | [] | [] | [
"python",
"sax"
] | stackoverflow_0004071856_python_sax.txt |
Q:
Add more sample points to data
Given some data of shape 20x45, where each row is a separate data set, say 20 different sine curves with 45 data points each, how would I go about getting the same data, but with shape 20x100?
In other words, I have some data A of shape 20x45, and some data B of length 20x100, and I ... | Add more sample points to data | Given some data of shape 20x45, where each row is a separate data set, say 20 different sine curves with 45 data points each, how would I go about getting the same data, but with shape 20x100?
In other words, I have some data A of shape 20x45, and some data B of length 20x100, and I would like to have A be of shape 20x... | [
"Ubuntu beat me to it while I was typing this example, but his example just uses linear interpolation, which can be more easily done with numpy.interpolate... (The difference is only a keyword argument in scipy.interpolate.interp1d, however).\nI figured I'd include my example, as it shows using scipy.interpolate.i... | [
11,
1,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0004072844_numpy_python_scipy.txt |
Q:
how to create a Storm table with no primary key?
I'm trying to use Storm to create an ORM to an existing MySQL db. I'm trying to create a table Class for one of the tables but I'm getting this error:
storm.exceptions.ClassInfoError: <class 'statsstorm.Aggframe'> has no primary key information
This table has no pr... | how to create a Storm table with no primary key? | I'm trying to use Storm to create an ORM to an existing MySQL db. I'm trying to create a table Class for one of the tables but I'm getting this error:
storm.exceptions.ClassInfoError: <class 'statsstorm.Aggframe'> has no primary key information
This table has no primary key, or any combination of columns that produce ... | [
"I don't recommend that you create a table without a PK.\nIf anything, add an IDENTITY column in that table and use as PK.\n",
"You can create a compound key:\nhttps://storm.canonical.com/Manual#Defining_compound_keys\n"
] | [
1,
1
] | [] | [] | [
"database",
"mysql",
"orm",
"python",
"storm_orm"
] | stackoverflow_0003703552_database_mysql_orm_python_storm_orm.txt |
Q:
Inheriting assigned properties from a mix-in
I would like to use a mix-in class to add properties to a model.
from google.appengine.ext import db
class Taggable(object):
tag_list = db.StringListProperty()
def attach_tag(self, tag):
self.tag_list.append(tag)
self.put()
def remove_tag(... | Inheriting assigned properties from a mix-in | I would like to use a mix-in class to add properties to a model.
from google.appengine.ext import db
class Taggable(object):
tag_list = db.StringListProperty()
def attach_tag(self, tag):
self.tag_list.append(tag)
self.put()
def remove_tag(self, tag):
self.tag_list.pop(self.tag_lis... | [
"Should not Taggable be based on db.Model instead of object?\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004073627_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I design and implement a programming language?
This question is related to
This question on Aardvark
This question on here
The past couple of years I've been thinking about things I like and don't like about languages I use. I always wanted to write my own language, but never did so.
I also own both the L... | How do I design and implement a programming language? | This question is related to
This question on Aardvark
This question on here
The past couple of years I've been thinking about things I like and don't like about languages I use. I always wanted to write my own language, but never did so.
I also own both the Lego RCX and NXT, but most of the time I never actually make... | [
"\nNow what? Where do I start? What do I need to know?\n\nStart by learning more programming languages.\nAfter learning several languages, buy a book on compilers. There are many. Google will help. It doesn't matter which one you buy. You'll need several. It's okay to read many books.\nOnce you've learned lang... | [
23,
5,
4,
4
] | [] | [] | [
"clojure",
"forth",
"nxt",
"programming_languages",
"python"
] | stackoverflow_0004014267_clojure_forth_nxt_programming_languages_python.txt |
Q:
Having trouble parsing a txt file into a list full of zip codes in my zipcode lookup program
Hello everyone thanks for looking into my problem. What I am trying to do is write a "Structured" program in python that takes txt from a file and parses it into lists. Then after closing the file, I need to reference th... | Having trouble parsing a txt file into a list full of zip codes in my zipcode lookup program | Hello everyone thanks for looking into my problem. What I am trying to do is write a "Structured" program in python that takes txt from a file and parses it into lists. Then after closing the file, I need to reference the user input (zipcode) in those lists and then print out the city and state according to the zipco... | [
"why you fill the lists zipcode, city , state like that, i mean in each user entry we get the next line from the file \ni think that you should do :\ndef loadList():\n # Fill all the list first , make the readRecord() return eof (True or False).\n while readRecord():\n pass\n\n # than process data ... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004073694_python.txt |
Q:
Better way to write this if statement?
I have this tkinter GUI, and I need to get the values from the entries and compare.
self.hystInt.get() is the way to access the string in the string variable in the Entry. *I have to write this for every variable so it ends up looking really ugly.
if (self.hystInt.get().isdig... | Better way to write this if statement? | I have this tkinter GUI, and I need to get the values from the entries and compare.
self.hystInt.get() is the way to access the string in the string variable in the Entry. *I have to write this for every variable so it ends up looking really ugly.
if (self.hystInt.get().isdigit() and int(self.hystInt.get()) >= 200 and ... | [
"def validate(num):\n try:\n return 200 <= int(num) <= 500\n except ValueError:\n return False\n\nSimple is good!\n",
"At the very least you can use Python's unusual comparison syntax like this:\nif (self.hystInt.get().isdigit() and (200 <= int(self.hystInt.get()) <= 500)):\n\n",
"Do this.\n... | [
10,
1,
1,
1,
0
] | [] | [] | [
"comparison",
"python"
] | stackoverflow_0004072871_comparison_python.txt |
Q:
Advanced SQL query with sub queries, group by, count and sum functions in to SQLalchemy
I have written the following query.
select distinct(table3.*),
(select count(*)
from table2
where table2.cus_id = table3.id) as count,
(select sum(amount)
from table2
where ... | Advanced SQL query with sub queries, group by, count and sum functions in to SQLalchemy | I have written the following query.
select distinct(table3.*),
(select count(*)
from table2
where table2.cus_id = table3.id) as count,
(select sum(amount)
from table2
where table2.cus_id = table3.id) as total
from table2,
table1,
table3
where ta... | [
"Here's my re-write of your query:\nSELECT t3.*,\n x.count,\n x.amount\n FROM TABLE3 t3\n JOIN (SELECT t2.cus_id\n COUNT(*) AS count,\n SUM(t2.amount) AS total\n FROM TABLE2 t2\n WHERE EXISTS(SELECT NULL\n FROM TABLE1 t1\n ... | [
3
] | [] | [] | [
"postgresql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004073918_postgresql_python_sql_sqlalchemy.txt |
Q:
Access from external to python development server
I can't access externally to python development server, I have a very small django project running on my machine, and now I want to enable computers in the same LAN have access to it, but it can't do.
There is no firewall running on my machine. Is there a way aroun... | Access from external to python development server | I can't access externally to python development server, I have a very small django project running on my machine, and now I want to enable computers in the same LAN have access to it, but it can't do.
There is no firewall running on my machine. Is there a way around this?
| [
"How are you running the server?\nHave you tried something like this? \nmanage.py runserver 0.0.0.0:8080\n\nFrom the documentation:\n\nNote that the default IP address, 127.0.0.1, is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use i... | [
21,
6
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004073977_django_python.txt |
Q:
Writing a parallel programming framework, what have I missed?
Clarification: As per some of the comments, I should clarify that this is intended as a simple framework to allow execution of programs that are naturally parallel (so-called embarrassingly parallel programs). It isn't, and never will be, a solution for... | Writing a parallel programming framework, what have I missed? | Clarification: As per some of the comments, I should clarify that this is intended as a simple framework to allow execution of programs that are naturally parallel (so-called embarrassingly parallel programs). It isn't, and never will be, a solution for tasks which require communication or synchronisation between proce... | [
"I have actually written something that probably satisfies your needs: jug. If it does not solve your problems, I promise you I'll fix any bugs you find.\nThe architecture is slightly different: workers all run the same code, but they effectively generate a similar dictionary and ask the central backend \"has this ... | [
8,
5
] | [] | [] | [
"parallel_processing",
"python",
"python_2.x"
] | stackoverflow_0004073695_parallel_processing_python_python_2.x.txt |
Q:
Django - Access ForeignKey value without hitting database
I have a django model like so:
class Profile_Tag(models.Model):
profile = models.ForeignKey(Profile)
tag = models.ForeignKey(Tag)
and a view like so:
pts = Profile_Tag.objects.all()
for pt in pts:
print pt.profile.id
is there any way to access... | Django - Access ForeignKey value without hitting database | I have a django model like so:
class Profile_Tag(models.Model):
profile = models.ForeignKey(Profile)
tag = models.ForeignKey(Tag)
and a view like so:
pts = Profile_Tag.objects.all()
for pt in pts:
print pt.profile.id
is there any way to access the profile foreignKey without hitting the database each time?... | [
"You can do something like this:\npt_ids = Profile_Tag.objects.values_list('profile', flat=True)\n\nThis will return you list of IDs. For model instance, there's another way:\npts = Profile_Tag.objects.all()\nfor pt in pts:\n print pt.profile_id\n\n"
] | [
20
] | [] | [] | [
"django",
"foreign_key_relationship",
"python"
] | stackoverflow_0004074038_django_foreign_key_relationship_python.txt |
Q:
Slice an audio file into ten second segments
Recommendations welcome on how to slice a .wav1 file into time-delimited segments using a Python library.
1 The actual file type isn't really that material, I'm sure I'll be able to convert between different types if needed.
A:
I would use the wave module to open the... | Slice an audio file into ten second segments | Recommendations welcome on how to slice a .wav1 file into time-delimited segments using a Python library.
1 The actual file type isn't really that material, I'm sure I'll be able to convert between different types if needed.
| [
"I would use the wave module to open the file, read the headers, figure out how many frames are in 10 seconds, then read that many frames. Write those frames out to files with the same header info (except length) until done.\n",
"I would suggest looking at the data structure for a given file, and 'cutting' the da... | [
3,
2
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0004066009_audio_python.txt |
Q:
ideal thread structure question (involves multiple thread communication)
I'm writing an application that listens for sound events (using messages passed in with Open Sound Control), and then based on those events pauses or resumes program execution. My structure works most of the time but always bombs out in the ... | ideal thread structure question (involves multiple thread communication) | I'm writing an application that listens for sound events (using messages passed in with Open Sound Control), and then based on those events pauses or resumes program execution. My structure works most of the time but always bombs out in the main loop, so I'm guessing it's a thread issue. Here's a generic, simplified ... | [
"Umm.. I don't completely understand your question but i'll do my best to explain what I think you need to fix your problems.\n1) The thread of your Loop.loop function should be set as a daemon thread so that it exits with your main thread (so you don't have to kill the python process every time you want to shut do... | [
4
] | [] | [] | [
"multithreading",
"python",
"structure"
] | stackoverflow_0004072816_multithreading_python_structure.txt |
Q:
Is there a way to add marked text into a variable in pyqt?
I've just had my first course in programming at the university and for the following three months I have no additional programming classes so I've decided to do a small project during this "break".
What I'm trying to do is a edit-program for a smaller Wiki... | Is there a way to add marked text into a variable in pyqt? | I've just had my first course in programming at the university and for the following three months I have no additional programming classes so I've decided to do a small project during this "break".
What I'm trying to do is a edit-program for a smaller Wiki I used to work on. It's suppose to make it easier for the users... | [
"from PyQt4.QtGui import *\nfrom PyQt4.QtCore import SIGNAL\n\nclass Widget(QWidget): \n def __init__(self, parent=None): \n QWidget.__init__(self) \n\n self.textedit = QTextEdit()\n self.clip = QApplication.clipboard()\n self.button = QPushButton(\"Bold\") \n self.conn... | [
1
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0004065902_pyqt_python.txt |
Q:
Relay/Send through NAT in Python
I'm looking for a solution to exchange data (protocols build on TCP) between NAT separated endpoints - more or less directly.
I can setup a relay service for example - which is what I have in mind. However I want to route traffic without losing too much performance.
or I can buil... | Relay/Send through NAT in Python | I'm looking for a solution to exchange data (protocols build on TCP) between NAT separated endpoints - more or less directly.
I can setup a relay service for example - which is what I have in mind. However I want to route traffic without losing too much performance.
or I can build a VPN with a central VPN server
Are... | [
"I'm not sure about Python implementations, but you may want to look at Samy Kamkar's example implementations of mechanisms for relay-free NAT traversal when both endpoints are NATed. (and the papers he references)\n\npwnat\nchownat\nNAT Pinning\n\n"
] | [
4
] | [] | [] | [
"networking",
"python",
"routing"
] | stackoverflow_0004067971_networking_python_routing.txt |
Q:
Getting the next specified element in lxml?
I'm struggling trying to parse this html. There are h2s acting as titles for paragraphs. Both are in separate divs, and separated by more divs. The paragraph isn't a child of the h2. I'd like to group them together, but I can't figure how out. I thought find would do it ... | Getting the next specified element in lxml? | I'm struggling trying to parse this html. There are h2s acting as titles for paragraphs. Both are in separate divs, and separated by more divs. The paragraph isn't a child of the h2. I'd like to group them together, but I can't figure how out. I thought find would do it but it didn't work:
html = doc.cssselect('h2.titl... | [
"lxml.html.HtmlElement.find only takes a tag name or a path - it doesn't accept full CSS selectors.\nA better idea would just be to use doc.cssselect with advanced selectors. lxml.html will convert them to XPath selectors for you.\nPerhaps:\nfor elem in doc.cssselect('h2.title div.content'):\n elem.text_content... | [
2
] | [] | [] | [
"html",
"lxml",
"python"
] | stackoverflow_0004075335_html_lxml_python.txt |
Q:
Django: How to get field value dynamically using custom template tags?
I'm writing a generic template tag that could return a model's field value dynamically based on user inputs in template files. The idea follows which mentioned in the book "Practical Django Project 2nd Edition", but the book version is getting ... | Django: How to get field value dynamically using custom template tags? | I'm writing a generic template tag that could return a model's field value dynamically based on user inputs in template files. The idea follows which mentioned in the book "Practical Django Project 2nd Edition", but the book version is getting a list of objects where I want to get only a object's value. I want to get t... | [
"I found the solution for this:\non the commented lines, use this code:\nvar = self.model.objects.get(site_id__exact=current_site.id)\ncontext[self.varname] = var.__dict__[self.field]#this will get the field's value dynamically, which is what I was looking for\n\n",
"The normal way in Python to get an attribute w... | [
4,
4
] | [] | [] | [
"django",
"dynamic",
"model",
"python",
"templatetags"
] | stackoverflow_0004074927_django_dynamic_model_python_templatetags.txt |
Q:
Python Mechanize with Dynamic Dropdown Selection
I'm using mechanize to fill forms and I run into a problem with dynamically-filled dropdown lists that are dependent on a previous selection.
In mechanize, I do something like this to select the category:
import mechanize
br = mechanize.Browser()
"""Select the form ... | Python Mechanize with Dynamic Dropdown Selection | I'm using mechanize to fill forms and I run into a problem with dynamically-filled dropdown lists that are dependent on a previous selection.
In mechanize, I do something like this to select the category:
import mechanize
br = mechanize.Browser()
"""Select the form and set up the browser"""
br["state"] = ["California"]... | [
"mechanize doesn't support JavaScript. Instead, you should use urllib2 to send the desired values.\nimport urllib2\nimport urllib\n\nvalues = dict(state=\"CA\", city=\"SF\") # examine form for actual vars\ntry:\n req = urllib2.Request(\"http://example.com/post.php\",\n urllib.urlencode(v... | [
1
] | [] | [] | [
"drop_down_menu",
"mechanize",
"python",
"webforms"
] | stackoverflow_0004075666_drop_down_menu_mechanize_python_webforms.txt |
Q:
Convert shoutcast stream to playable samples in Python?
I have a shoutcat radio station and now want to build a player for it. I know how to "get" thet stream from the server, thanks a lot to bobince , but I am not sure how to convert that stream into playable samples. How is it done?
A:
Shoutcast streams are ty... | Convert shoutcast stream to playable samples in Python? | I have a shoutcat radio station and now want to build a player for it. I know how to "get" thet stream from the server, thanks a lot to bobince , but I am not sure how to convert that stream into playable samples. How is it done?
| [
"Shoutcast streams are typically (but not always) MP3. To get playable samples, you have to decode the stream's MP3 data.\nHave you seen the resource at http://codeboje.de/playing-mp3-stream-python/? Looks like a simple solution, but requires an awful lot of libraries.\n",
"There are quite a few possibilities f... | [
2,
1,
0
] | [] | [] | [
"audio_player",
"python",
"sample",
"shoutcast",
"stream"
] | stackoverflow_0002881230_audio_player_python_sample_shoutcast_stream.txt |
Q:
Phylo BioPython building trees
I trying to build a tree with BioPython, Phylo module.
What I've done so far is this image:
each name has a four digit number followed by - and a number: this number refer to the number of times that sequence is represented. That means 1578 - 22, that node should represent 22sequenc... | Phylo BioPython building trees | I trying to build a tree with BioPython, Phylo module.
What I've done so far is this image:
each name has a four digit number followed by - and a number: this number refer to the number of times that sequence is represented. That means 1578 - 22, that node should represent 22sequences.
the file with the sequences alig... | [
"I finally got this working. The basic premise is that you're going to use the labels/nodelist to build your node_sizes. This way they correlate properly. I'm sure I'm missing some important options to make the tree look 100% but it appears the node sizes are showing up properly.\n#basically a stripped down rewrite... | [
8
] | [] | [] | [
"biopython",
"graphviz",
"numpy",
"python"
] | stackoverflow_0004051414_biopython_graphviz_numpy_python.txt |
Q:
Django + alwaysdata.com Noob Question
I'm learning Django and working on sample sites.. I registered at alwaysdata but am unable to view the site after I go 'manage.py runserver' in the SSH (this is after I've created the project and navigated to the appropriate directory, of course).
I appreciate any help.
Thanks... | Django + alwaysdata.com Noob Question | I'm learning Django and working on sample sites.. I registered at alwaysdata but am unable to view the site after I go 'manage.py runserver' in the SSH (this is after I've created the project and navigated to the appropriate directory, of course).
I appreciate any help.
Thanks
| [
"Have you taken a look at the wiki entry regarding the django dev server? Google translate seems to indicate that you need to request some ports open first, and that once you've got them assigned you can pass in one of those port numbers to runserver to run it on that port.\nIf you need the translated-to-English v... | [
3,
3,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004073352_django_python.txt |
Q:
s-t cut algorithm in Python
I'm looking for an implementation of s-t cut algorithm for flow network (directed graph) in Python.
Is there vertex cut version of the algorithm?
A:
igraph has it:
>>> from igraph import Graph
>>> from random import randint
>>> g = Graph.GRG(100, 0.2) # generate a geometric ran... | s-t cut algorithm in Python | I'm looking for an implementation of s-t cut algorithm for flow network (directed graph) in Python.
Is there vertex cut version of the algorithm?
| [
"igraph has it:\n>>> from igraph import Graph\n>>> from random import randint\n>>> g = Graph.GRG(100, 0.2) # generate a geometric random graph\n>>> g.es[\"capacity\"] = [randint(0, 1000) for i in xrange(g.ecount())]\n>>> cut = g.maxflow(0, 99, \"capacity\")\n\ncut.membership then gives you the membership of ... | [
1
] | [] | [] | [
"algorithm",
"graph",
"python"
] | stackoverflow_0004076245_algorithm_graph_python.txt |
Q:
What is the best way to store change history of website articles?
Our client wants us to implement change history for website articles. What is the best way to do it?
A:
Without knowing too much about your particular application stack (framework, language), you have at least two basic approaches:
Versioned Reco... | What is the best way to store change history of website articles? | Our client wants us to implement change history for website articles. What is the best way to do it?
| [
"Without knowing too much about your particular application stack (framework, language), you have at least two basic approaches:\n\nVersioned Records - Instead of storing articles as a single row in a database (or single file in a filesystem) and updating with changes, simply create a new record with a pointer to i... | [
1,
0
] | [
"There is a wide variety of ways to do this as you alluded by tagging php, .net, python, and ruby. You missed a few off the top of my head perl and jsp. Each of these have their plusses and minuses and is really a question of what best suits your needs.\nPHP is probably the fastest reward for time spent.\nRuby, i... | [
-1
] | [
".net",
"php",
"python",
"ruby"
] | stackoverflow_0004075309_.net_php_python_ruby.txt |
Q:
eliminate trailing spaces in url
If a url has trailing spaces in it.how to find them and eliminate the trailing space ..
http://www.youtube.com/watch?v=cs3ROFNxa5M
Thanks
A:
myString.strip()
| eliminate trailing spaces in url | If a url has trailing spaces in it.how to find them and eliminate the trailing space ..
http://www.youtube.com/watch?v=cs3ROFNxa5M
Thanks
| [
"myString.strip() \n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004076776_python.txt |
Q:
How to connect pyqtSignal between classes in PyQT
How to connect pyqtSignal between two different objects (classes) PROPERLY? I mean best practice.
Look what I have done to achieve the goal: The Thermometer class is notified when Pot increases its temperature:
from PyQt4 import QtCore
class Pot(QtCore.QObject):
... | How to connect pyqtSignal between classes in PyQT | How to connect pyqtSignal between two different objects (classes) PROPERLY? I mean best practice.
Look what I have done to achieve the goal: The Thermometer class is notified when Pot increases its temperature:
from PyQt4 import QtCore
class Pot(QtCore.QObject):
temperatureRaisedSignal = QtCore.pyqtSignal()
d... | [
"from PyQt4 import QtCore\n\nclass Pot(QtCore.QObject):\n\n temperatureRaisedSignal = QtCore.pyqtSignal()\n\n def __init__(self, parent=None):\n QtCore.QObject.__init__(self)\n self.temperature = 1\n\n def Boil(self):\n self.temperatureRaisedSignal.emit()\n self.temperature += 1... | [
23
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0003891465_pyqt_pyqt4_python.txt |
Q:
Printing a formatted numerical range strings from a list of numbers in python
I wrote this class to compress and expand number lists to sequence strings, including step values when the the step value is greater than 1. The code still feels clunky. Are there libraries that can do something like this? Possibly sim... | Printing a formatted numerical range strings from a list of numbers in python | I wrote this class to compress and expand number lists to sequence strings, including step values when the the step value is greater than 1. The code still feels clunky. Are there libraries that can do something like this? Possibly simpler code?
import re
class Foo( object ):
def __init__( self, num_list ):
... | [
"One. Remove all #END comments. They are monstrously useless. Your indentation speaks for itself. Use it. \nTwo. Don't make this a class. It isn't a distinct object with distinct responsibilities. It's just an algorithm. Made up of functions. At best it's a class with all static methods.\nThree. Never do ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004074373_python.txt |
Q:
a good solution to set up a rdf triplestore in python?
i'm looking for something as easy and tidy as the ARC2 class for PHP to use in python.
so far i've taken a look at rdflib, but the lack of support for SPARQL and inaccurate docs are putting me off!
is there another python library which will enable me to set up... | a good solution to set up a rdf triplestore in python? | i'm looking for something as easy and tidy as the ARC2 class for PHP to use in python.
so far i've taken a look at rdflib, but the lack of support for SPARQL and inaccurate docs are putting me off!
is there another python library which will enable me to set up and use a triple store quickly and easily, or am i stuck wi... | [
"Yes, I agree RDFLib is not great as a SPARQL engine and it doesn't scale much.\nAn option that always works for me is 4store as a triple store with the Python client 4store-client. In the 4store IRC channel and Google Group you'll find helpful support.\n",
"There is a new python SQLAlchemy and RDFLib module for ... | [
4,
2
] | [] | [] | [
"python",
"rdf",
"sparql"
] | stackoverflow_0004073002_python_rdf_sparql.txt |
Q:
How implement .NET server and Python client?
I've got a problem. I Have a tool(threads manager) that receives some data and do some computation. I need to write Python client to send data to that tool...I thing I should use .NET Remoting, but how to do that?
pls share some links where I can read or post some code.... | How implement .NET server and Python client? | I've got a problem. I Have a tool(threads manager) that receives some data and do some computation. I need to write Python client to send data to that tool...I thing I should use .NET Remoting, but how to do that?
pls share some links where I can read or post some code...I can't google info about that...
P.S Python 2.7... | [
".Net Remoting is designed for when you have .net at both ends so will be very hard to use from the Python end. (Event the XML encoding of .net remoting is not easy to use from other platforms)\nI am assuming that Python has support for soap, if so I would look at using WCF at the .net end running over the “basic ... | [
1,
1,
0
] | [] | [] | [
"c#",
"python",
"remoting"
] | stackoverflow_0004076114_c#_python_remoting.txt |
Q:
Hash+mapping or index+mapping to condense use of strings
I have ~200K named properties and ~25K files. I extract whether the properties hold or not for each file using Python as a set of properties that hold, one set for each file.
To do this extraction I might run hundreds of individual python extraction scripts ... | Hash+mapping or index+mapping to condense use of strings | I have ~200K named properties and ~25K files. I extract whether the properties hold or not for each file using Python as a set of properties that hold, one set for each file.
To do this extraction I might run hundreds of individual python extraction scripts on a compute farm, in parallel. Each leaving behind some repre... | [
"Do you know the properties in advance? If you do than you might want to consider Perfect hashing (i.e. you can distribute the settings of the hash instead of the full list of properties/files). \nA very crude (but possibly working way) would be having a few different hash functions (h1, h2...); start e.g. with the... | [
2,
0
] | [] | [] | [
"data_structures",
"hash",
"python",
"set"
] | stackoverflow_0004076822_data_structures_hash_python_set.txt |
Q:
Python Listbox selection cleared whenever something is highlighted when it is working with Text or Entry widget
I found a problem with Tkinter.Listbox when it is working with Entry or Text widgets.
Whenever something is highlighted in the Entry or Text widget, it clears the listbox selection.
I am using Python 2.6... | Python Listbox selection cleared whenever something is highlighted when it is working with Text or Entry widget | I found a problem with Tkinter.Listbox when it is working with Entry or Text widgets.
Whenever something is highlighted in the Entry or Text widget, it clears the listbox selection.
I am using Python 2.6.5. The following is the testing scripts.
from Tkinter import *
root = Tk()
List = ['It is a listbox: item1','item... | [
"You need to set the exportselection attribute of the listbox to False\n"
] | [
0
] | [] | [] | [
"listbox",
"python",
"text",
"tkinter",
"tkinter_entry"
] | stackoverflow_0004076926_listbox_python_text_tkinter_tkinter_entry.txt |
Q:
Python Tkinter Embed Matplotlib in GUI
I'm trying to embed a plot in my Tkinter GUI coded in Python. I believe the code below succeeds in simply putting a graph into a canvas, but I don't have any control of the canvas location within the GUI grid. I want to be able to have a subsection of my GUI be the plot...not... | Python Tkinter Embed Matplotlib in GUI | I'm trying to embed a plot in my Tkinter GUI coded in Python. I believe the code below succeeds in simply putting a graph into a canvas, but I don't have any control of the canvas location within the GUI grid. I want to be able to have a subsection of my GUI be the plot...not the entirety of it. How can I position this... | [
"You don't have any other widgets so it's hard to know where you want other widgets. Here's what I can tell you though: by doing dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) you are asking Tkinter to fill the screen with the plot. This, because you ask it to fill in all directions (fill=BOTH) and ex... | [
23
] | [] | [] | [
"grid",
"matplotlib",
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0004073660_grid_matplotlib_python_tkinter_tkinter_canvas.txt |
Q:
Define todo keyword in Python and Sublime Text
Can I define #@TODO or something like that as a keyword to be highlighted in Python?
Is this specific to the text editor or to the language/platform?
A:
This is very specific to the editor.
Language/Platform has nothing to do with highlighting.
A:
it s editor feat... | Define todo keyword in Python and Sublime Text | Can I define #@TODO or something like that as a keyword to be highlighted in Python?
Is this specific to the text editor or to the language/platform?
| [
"This is very specific to the editor.\nLanguage/Platform has nothing to do with highlighting.\n",
"it s editor feature, eclipse has highlighter, in emacs you can define and ...\nalso you can use bash script to find all todo in your project\ngrep \"# TODO\" ./ -Rn\n\n"
] | [
0,
0
] | [] | [] | [
"keyword",
"python",
"sublimetext",
"syntax_highlighting",
"todo"
] | stackoverflow_0004076695_keyword_python_sublimetext_syntax_highlighting_todo.txt |
Q:
regression test dealing with hard coded path
I need to extend a python code which has plenty of hard coded path
In order not to mess everything, I want to create unit-tests for the code before my modifications: it will serve as non-regression tests with my new code (that will not have hard-coded paths)
But because... | regression test dealing with hard coded path | I need to extend a python code which has plenty of hard coded path
In order not to mess everything, I want to create unit-tests for the code before my modifications: it will serve as non-regression tests with my new code (that will not have hard-coded paths)
But because of hard coded system path, I shall run my test in... | [
"In your test set-up you could override the built-in open in the module that you are testing with your own version that reads from your \"fake\" directory structure:\nimport mymod\nimport os.path\n\ndef chroot_open(filename,*args):\n filename = os.path.join(\"/home/you/fakeroot\",filename)\n return open(filen... | [
5,
0
] | [] | [] | [
"linux",
"python",
"regression",
"unit_testing"
] | stackoverflow_0004077338_linux_python_regression_unit_testing.txt |
Q:
Python logger to dictionary
I am new in python...i am trying to read a python log file and make a dictionary. How will it be done with logger?
A:
read a python log file and make a dictionary. How will it be done with logger?
It won't.
logging writes logs.
file reads logs.
What are you asking?
First, search... | Python logger to dictionary | I am new in python...i am trying to read a python log file and make a dictionary. How will it be done with logger?
| [
"\nread a python log file and make a dictionary. How will it be done with logger?\n\nIt won't. \nlogging writes logs.\nfile reads logs.\nWhat are you asking? \nFirst, search for [Python] log parsing: https://stackoverflow.com/search?q=%5Bpython%5D+log+parsing\nSecond, please post some sample code.\n",
"As other... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004076416_python.txt |
Q:
Memory leak in Python Twisted: where is it?
I have a Twisted server under load. When the server is under load, memory usage increases, and it is never reclaimed (even when there are no more clients). Next time it goes into high load, memory usage increases again. Here's a snapshot of the situation at that point:
... | Memory leak in Python Twisted: where is it? | I have a Twisted server under load. When the server is under load, memory usage increases, and it is never reclaimed (even when there are no more clients). Next time it goes into high load, memory usage increases again. Here's a snapshot of the situation at that point:
RSS memory is 400 MB (should be 200MB with usual ... | [
"If the code is only leaking under load (did you verify this?), I'd have a look at all spots where messages are buffered. Does the memory usage of the process itself increase? Or does the memory use of the system increase? If it's the latter case, your server might simply be too slow to keep up with the incoming me... | [
2
] | [] | [] | [
"garbage_collection",
"memory_leaks",
"memory_management",
"python",
"twisted"
] | stackoverflow_0004078084_garbage_collection_memory_leaks_memory_management_python_twisted.txt |
Q:
Why is subtraction faster than addition in Python?
I was optimising some Python code, and tried the following experiment:
import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = tim... | Why is subtraction faster than addition in Python? | I was optimising some Python code, and tried the following experiment:
import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
The second loop is reli... | [
"I can reproduce this on my Q6600 (Python 2.6.2); increasing the range to 100000000:\n('+=', 11.370000000000001)\n('-=', 10.769999999999998)\n\nFirst, some observations:\n\nThis is 5% for a trivial operation. That's significant.\nThe speed of the native addition and subtraction opcodes is irrelevant. It's in the ... | [
86,
13,
7,
5,
4,
2,
0,
0,
0
] | [
"The running loop backwards is faster because the computer has an easier time comparing if a number is equal to 0.\n"
] | [
-1
] | [
"addition",
"performance",
"python",
"subtraction"
] | stackoverflow_0001396564_addition_performance_python_subtraction.txt |
Q:
Python: print unicode char escaped
I have tried to convert an ascii string to an escaped pseudo unicode escaped string using python, but failed so far.
What I want to do: Convert ASCII 'a' to ASCII String "<U0061>"
I can convert "a" with unicode('a'), but can not safe the numerical value of a in an ascii string.
H... | Python: print unicode char escaped | I have tried to convert an ascii string to an escaped pseudo unicode escaped string using python, but failed so far.
What I want to do: Convert ASCII 'a' to ASCII String "<U0061>"
I can convert "a" with unicode('a'), but can not safe the numerical value of a in an ascii string.
How can I do that?
| [
"You can use ord() to convert a character to its character value (str) or code point (unicode). You can then use the appropriate string formatting to convert it into a text representation.\n'U+%04X' % (ord(u'A'),)\n\n",
"Here goes a minimalist sample that allows you to use Ignacio's solution with Python's built-i... | [
7,
1
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0004076194_python_unicode.txt |
Q:
How to calculate efficient local average of each coordinate of large matrix (average filter) in python
I have large matrix, 4000x4000
I need to calculate local average of 11x11 window for each x,y of this matrix
Generally it must be something like
for x in range(4000)
for y in range(4000)
b[x,y]=mean(a[x-5:x... | How to calculate efficient local average of each coordinate of large matrix (average filter) in python | I have large matrix, 4000x4000
I need to calculate local average of 11x11 window for each x,y of this matrix
Generally it must be something like
for x in range(4000)
for y in range(4000)
b[x,y]=mean(a[x-5:x+5,y-5:y+5]
But this will run a lot of time
Is it some more efficient way to do this?
Thanks.
| [
"You essentially want a two-dimensional convolution. Scipy can do that for you: http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html\nIn fact there's a similar answer right here on SO:\n2d convolution using python and numpy\n",
"You can use a dynamic programming technique to make it ma... | [
7,
4
] | [] | [] | [
"arrays",
"average",
"local",
"matrix",
"python"
] | stackoverflow_0004078811_arrays_average_local_matrix_python.txt |
Q:
What do I put in the visit dict passed to my user-defined __deepcopy__ function?
I need to define my own deepcopy function for one of my classes. The documentation says that the function __deepcopy__() is passed a memo dictionary for tracking which objects have already been copied, to avoid getting caught in copin... | What do I put in the visit dict passed to my user-defined __deepcopy__ function? | I need to define my own deepcopy function for one of my classes. The documentation says that the function __deepcopy__() is passed a memo dictionary for tracking which objects have already been copied, to avoid getting caught in coping a recursive object. However it doesn't say what to put in the dictionary. Do I put o... | [
"To be consistent with the built-in copy.deepcopy behavior, you should use the id of the object as a key.\nMore Details:\nWhile you can often get away with using a different key scheme (such as the object itself, if it's hashable), as long as you're consistent, you can still run into trouble. Frequently __deepcopy_... | [
1,
0
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0004078725_deep_copy_python.txt |
Q:
Printing hex string
print 'Payload: ', struct.unpack('%dB'%len(payload), payload)
print '%08x (%d bits) DATA: ' % (identifier, width), repr(payload)
These two code statements generate the following results:
Payload: (125, 255, 255, 125, 255, 255, 125, 255)
18feef00 (29 bits) DATA: '}\xff\xff}\xff\xff}\xff'
I'd l... | Printing hex string | print 'Payload: ', struct.unpack('%dB'%len(payload), payload)
print '%08x (%d bits) DATA: ' % (identifier, width), repr(payload)
These two code statements generate the following results:
Payload: (125, 255, 255, 125, 255, 255, 125, 255)
18feef00 (29 bits) DATA: '}\xff\xff}\xff\xff}\xff'
I'd like to have ONE final str... | [
">>> tup = (125, 255, 255, 125, 255, 255, 125, 255)\n>>> \"\".join('%02x' % i for i in tup)\n'7dffff7dffff7dff'\n\nSo, in your case, you can use struct.unpack to construct the tuple and then use the \"\".join() to construct the string.\nIt's unclear what you are starting with, but if it's the string '}\\xff\\xff}\\... | [
2
] | [] | [] | [
"hex",
"python",
"string_formatting"
] | stackoverflow_0004079277_hex_python_string_formatting.txt |
Q:
How do I find which version of Python to use with Mercurial?
I read here that
On Windows, your Python version must match the version used to compile Mercurial. Otherwise, you'll get "Invalid Magic Number" errors when trying to run the CGI. The pre-compiled Windows binaries for Mercurial 1.0.x, 1.1.x, 1.2.x and 1... | How do I find which version of Python to use with Mercurial? | I read here that
On Windows, your Python version must match the version used to compile Mercurial. Otherwise, you'll get "Invalid Magic Number" errors when trying to run the CGI. The pre-compiled Windows binaries for Mercurial 1.0.x, 1.1.x, 1.2.x and 1.3.x were compiled with Python 2.5.
I looked online but I dont se... | [
"If you're on Windows you want to install TortoiseHG. It provides the full Mercurial command line, a GUI with Windows shell integration, and the right version of Python all compiled in together.\n",
"The various HG installation packages have the required Python version in their name. You can also look it up in th... | [
4,
1
] | [] | [] | [
"mercurial",
"python",
"version",
"windows"
] | stackoverflow_0004079377_mercurial_python_version_windows.txt |
Q:
Access local variable in function from module
I have a function in my main program that attempts to retrieve information from an imported module, which is a different script I wrote. This module spits out a variable which I access from the main program by making it a global.
However, since I'm threading the functi... | Access local variable in function from module | I have a function in my main program that attempts to retrieve information from an imported module, which is a different script I wrote. This module spits out a variable which I access from the main program by making it a global.
However, since I'm threading the function that requests the information, the global variab... | [
"Well, the only cases when func locals makes sense are closures and generators. You can access them via __closure__ attribute, but you would have to spawn closure for each separate thread, and it would be easier to just pass thread-local list to function instead.\nOther approach, which is actually used sometimes, i... | [
2
] | [] | [] | [
"python",
"python_multithreading"
] | stackoverflow_0004076799_python_python_multithreading.txt |
Q:
How to get absolute url in Pylons?
How to get absolute url in Pylons ?
A:
To generate a fully qualified URL with Routes, use qualified=True keyword in url() call.
Example:
print url("blog", id=123, qualified=True)
# depending on routing configuration,
# would print something like "http://somehost/blog/123"
If... | How to get absolute url in Pylons? | How to get absolute url in Pylons ?
| [
"To generate a fully qualified URL with Routes, use qualified=True keyword in url() call.\nExample:\nprint url(\"blog\", id=123, qualified=True) \n# depending on routing configuration,\n# would print something like \"http://somehost/blog/123\"\n\nIf your web application is running behind load balancer or reverse p... | [
8
] | [] | [] | [
"pylons",
"python",
"routes"
] | stackoverflow_0004071837_pylons_python_routes.txt |
Q:
Problem with multiprocessing python 2.6
I'm trying to build a simple program that will fire off a load of processes, and if the main process is killed, the sub processes will die. My code looks like this:
import time
def test_proc(name, conn):
x = 0
while True:
print x
x += 1
conn.p... | Problem with multiprocessing python 2.6 | I'm trying to build a simple program that will fire off a load of processes, and if the main process is killed, the sub processes will die. My code looks like this:
import time
def test_proc(name, conn):
x = 0
while True:
print x
x += 1
conn.poll()
from multiprocessing import Process,... | [
"This works fine for me in Ubuntu:\n>>> from time import sleep\n>>> from multiprocessing import Process, Pipe\n>>> \n>>> def test_proc(name, conn):\n... x = 0\n... while True:\n... #print x\n... x += 1\n... conn.poll()\n... \n>>> def main():\n... proc_name= ['a', 'b',... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0004078925_multiprocessing_python.txt |
Q:
wxPython - implementing a scrollable view on a page similar to Visio or MS Word's print layout view
I want to be able to embedd a panel (with size A4, A5, A6 custom etc) in a scrollable a page with a drop-shaddow, similar to how visio or ms word displays.
I'm a bit of a beginner to python - been using it for 6 mon... | wxPython - implementing a scrollable view on a page similar to Visio or MS Word's print layout view | I want to be able to embedd a panel (with size A4, A5, A6 custom etc) in a scrollable a page with a drop-shaddow, similar to how visio or ms word displays.
I'm a bit of a beginner to python - been using it for 6 months full-time now. Ideas of how to do this or links to examples / tutorial would be welcome.
Thx
DM
| [
"This is the closest I've got. No drop shaddow but at least a scrollable panel that almost looks like a piece of paper.\nimport wx\nfrom wx.lib.scrolledpanel import ScrolledPanel\n\napp = wx.PySimpleApp()\nframe = wx.Frame(None, id=wx.ID_ANY, name=\"Just one child\", size=(100,100))\nscrollablePanel = ScrolledPanel... | [
0
] | [] | [] | [
"graphics",
"python",
"wxpython"
] | stackoverflow_0004076596_graphics_python_wxpython.txt |
Q:
Unpack string with hexadecimals
I have a string that contains a float value in hexadecimal characters like this:
"\\64\\2e\\9b\\38"
I want to extract the float, but in order to do that I have to make Python see the string as 4 hex characters, instead of 16 regular characters. First I tried replacing the forward s... | Unpack string with hexadecimals | I have a string that contains a float value in hexadecimal characters like this:
"\\64\\2e\\9b\\38"
I want to extract the float, but in order to do that I have to make Python see the string as 4 hex characters, instead of 16 regular characters. First I tried replacing the forward slashes, but I got an error:
>>>> hexs... | [
"Whenever I see a (malformed) string, such as one composed of this list of characters:\n['\\\\', '\\\\', '6', '4', '\\\\', '\\\\', '2', 'e', '\\\\', '\\\\', '9', 'b', '\\\\', '\\\\', '3', '8']\n\nwhen what was intended was this list of characters\n['\\x64', '\\x2e', '\\x9b', '\\x38']\n\nI reach for the decode('stri... | [
6,
0
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0004078929_python_struct.txt |
Q:
python thread exception errors when exit the whole program
HI, guys,
I am developing a GUI with python 2.4.3 and wxpython. Everything works fine except when I exit main program(close the main window of GUI). The wierd thing is that sometimes there is such error, sometimes there is no error at all. Although I foun... | python thread exception errors when exit the whole program | HI, guys,
I am developing a GUI with python 2.4.3 and wxpython. Everything works fine except when I exit main program(close the main window of GUI). The wierd thing is that sometimes there is such error, sometimes there is no error at all. Although I found the same error reports from the python mailing list(the link i... | [
"The problem is caused by the use of threading.Thread.setDaemon. Threads set daemonic don't prevent the Python intepreter from exiting, but they still keep running. Because Python cleans up the environment before the process is terminated, the threads can run into trouble when stuff is removed from under them. That... | [
5
] | [] | [] | [
"exception",
"multithreading",
"python",
"wxpython"
] | stackoverflow_0004079810_exception_multithreading_python_wxpython.txt |
Q:
Generating Python code from XML tree
What is the best way in Python to read XML from a file, build a tree, do some rewriting in the tree and generate Python code? (I'm slightly confused as in Python there seem to be multiple options such as expat, ElementTree, XSLT, ...).
A:
You should check out lxml. It is easy... | Generating Python code from XML tree | What is the best way in Python to read XML from a file, build a tree, do some rewriting in the tree and generate Python code? (I'm slightly confused as in Python there seem to be multiple options such as expat, ElementTree, XSLT, ...).
| [
"You should check out lxml. It is easy to use and does what you want in a few steps. If you want to stick to the stdlib, then you check out ElementTree (Python 2.5+) . The type of XML processing you want depends on your needs and for high performance XML parsing, read this.\nEDIT: My answer is for XML parsing with ... | [
3,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004079829_python_xml.txt |
Q:
the smart way to recombine these two lists in python
i have the following lists in python which i want to recombine into a dictionary/list:
names = ['banana','grapefruit','apple']
colors = ['yellow','pink','green']
to
fruits = [
{'name':'banana','color':'yellow'},
{'name':'grapefruit','color':'pink'},
{'name':'a... | the smart way to recombine these two lists in python | i have the following lists in python which i want to recombine into a dictionary/list:
names = ['banana','grapefruit','apple']
colors = ['yellow','pink','green']
to
fruits = [
{'name':'banana','color':'yellow'},
{'name':'grapefruit','color':'pink'},
{'name':'apple','color':'green'}
]
what's the best way to do it? i'... | [
"fruits = [{\"name\": name, \"color\": color} for name, color in zip(names, colors)]\n\n",
"[ {'name': name, 'color': color} for name, color in zip(names, colors) ]\n\nThe usual terms and conditions apply:\n\nIn Python 2, itertools.izip is advisable for potentially large lists\nIf the actual data has many lists/a... | [
11,
9
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004079940_dictionary_list_python.txt |
Q:
django query eliminate duplicates
In the following query how to eliminate the duplicates,
d_query = Profile.objects.filter(company="12")
search_string ="Tom"
if search_string != "":
d_query = d_query.filter(Q(profiles__name__icontains=search_string) | Q(first_name__icontains=search_string)| Q(last_name__ic... | django query eliminate duplicates | In the following query how to eliminate the duplicates,
d_query = Profile.objects.filter(company="12")
search_string ="Tom"
if search_string != "":
d_query = d_query.filter(Q(profiles__name__icontains=search_string) | Q(first_name__icontains=search_string)| Q(last_name__icontains=search_string))
| [
"Assuming you mean you want to avoid getting back the same record more than once, you can just add .distinct() to your queryset before evaluating it\n",
"For the record - .distinct() has some caveeats described in its documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct\n"
] | [
3,
0
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004076285_django_django_models_django_templates_django_views_python.txt |
Q:
Issue in string matching in Python
I am trying to read from a file and match for a certain combination of strings. PFB my program:
def negative_verbs_features(filename):
# Open and read the file content
file = open (filename, "r")
text = file.read()
file.close()
# Create a list of negative ve... | Issue in string matching in Python | I am trying to read from a file and match for a certain combination of strings. PFB my program:
def negative_verbs_features(filename):
# Open and read the file content
file = open (filename, "r")
text = file.read()
file.close()
# Create a list of negative verbs from the MPQA lexicon
file_negat... | [
"You said the file has lines like this: abandoned,adj so those are word, pos pairs. But you wrote pos, word = line.split(\",\") which means that pos == 'abandoned' and word == 'adj' ... I think it's clear why the list will be empty now :-)\n",
"Replace the line pos, word = line.split(\",\") by \nword, pos = line.... | [
2,
1
] | [] | [] | [
"file_io",
"python",
"special_characters",
"string"
] | stackoverflow_0004080123_file_io_python_special_characters_string.txt |
Q:
User specified date time
I need to parse a date/time string from user input, and convert to UTC based on timzeone info not available in the string for datetime.strptime() (any suggestions?). Is there a straightforward way of doing this?
Ideally, on google app engine i'd like to grab local time with tzinfo from th... | User specified date time | I need to parse a date/time string from user input, and convert to UTC based on timzeone info not available in the string for datetime.strptime() (any suggestions?). Is there a straightforward way of doing this?
Ideally, on google app engine i'd like to grab local time with tzinfo from the browser if possible also.
t... | [
"While searching for similar information I came across a demo app engine app (with source included) that demonstrates how to convert timezones in a way that's similar to what you've requested. Unfortunately, though, you'll need to create custom tzinfo classes (explanation/code in the demo app linked above) for each... | [
0
] | [] | [] | [
"google_app_engine",
"python",
"python_datetime"
] | stackoverflow_0003692869_google_app_engine_python_python_datetime.txt |
Q:
Perl or Python: Convert date from dd/mm/yyyy to yyyy-mm-dd
I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python?
A:
If you are guaranteed to have well-formed data... | Perl or Python: Convert date from dd/mm/yyyy to yyyy-mm-dd | I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python?
| [
"If you are guaranteed to have well-formed data consisting of nothing else but a singleton date in the DD-MM-YYYY format, then this works:\n# FIRST METHOD\nmy $ndate = join(\"-\" => reverse split(m[/], $date));\n\nThat works on a $date holding \"07/04/1776\" but fails on \"this 17/01/2010 and that 01/17/2010 there\... | [
30,
20,
11,
6,
5,
1,
0
] | [
"In glorious perl-oneliner form:\necho 17/01/2010 | perl -p -e \"chomp; join('-', reverse split /\\//);\"\n\nBut seriously I would do it like this:\n#!/usr/bin/env perl\nwhile (<>) {\n chomp;\n print join('-', reverse split /\\//), \"\\n\";\n}\n\nWhich will work on a pipe, converting and printing one date pe... | [
-2
] | [
"date",
"perl",
"python",
"text_processing"
] | stackoverflow_0004077896_date_perl_python_text_processing.txt |
Q:
Python: os.stat().st_size gives different value than du
I'm creating a utility that will walk through directories and get the sizes of child directories and files for all directories and store the value. However, the sizes aren't computed correctly.
Here's my class, which automatically recurses through all sub-di... | Python: os.stat().st_size gives different value than du | I'm creating a utility that will walk through directories and get the sizes of child directories and files for all directories and store the value. However, the sizes aren't computed correctly.
Here's my class, which automatically recurses through all sub-directories:
class directory:
'''
Class that automatica... | [
"Consider this file foo\n-rw-rw-r-- 1 unutbu unutbu 25334 2010-10-31 12:55 foo\n\nIt consists of 25334 bytes.\ntune2fs tells me foo resides on a filesystem with block size 4096 bytes:\n% sudo tune2fs -l /dev/mapper/vg1-OS1\n...\nBlock size: 4096\n...\n\nThus, the smallest file on the filesystem will o... | [
9,
1,
0,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0004080254_linux_python.txt |
Q:
How to place a widget in a Canvas widget in Tkinter?
I want basically to be able to use a Canvas as a meta container for other widgets.
I want to divide my GUI into a left, center and middle section. Within each section I would like to be able to place widgets like: Checkbutton, Button, Label, etc.
How to place ... | How to place a widget in a Canvas widget in Tkinter? | I want basically to be able to use a Canvas as a meta container for other widgets.
I want to divide my GUI into a left, center and middle section. Within each section I would like to be able to place widgets like: Checkbutton, Button, Label, etc.
How to place widgets in a Canvas widget?
| [
"Your choices depend on what you're really trying to accomplish. Why is using a canvas preferable to using a frame?\nYou can easily add widgets to a canvas just like you do any other container, using pack or grid or place. when you do this, the items will not scroll when you scroll the canvas because they aren't ac... | [
6
] | [] | [] | [
"python",
"python_3.x",
"tkinter_canvas",
"widget"
] | stackoverflow_0004080413_python_python_3.x_tkinter_canvas_widget.txt |
Q:
importing other python file functions not working
I have two script one does the work and the other has a function that gives correct values to variables. Anyway I get the following error when calling a function in script(2) using a parameter from script(1)
SCRIPT 1 (PROBLEM WITH LAST LINE COUNT_help.months() :
wh... | importing other python file functions not working | I have two script one does the work and the other has a function that gives correct values to variables. Anyway I get the following error when calling a function in script(2) using a parameter from script(1)
SCRIPT 1 (PROBLEM WITH LAST LINE COUNT_help.months() :
while True:
day = raw_input("Please Enter The Day: ")... | [
"You need to assign the result of COUNT_help.months(months = month) somewhere. Also look into the datetime library.\nif correctcheck == \"3\": \n months = COUNT_help.months(months = month) \n print month \n print months \n\n"
] | [
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0004080496_function_python.txt |
Q:
syntax error with glfloat python?
I am getting this error (note the code is from openGL red book:
GLfloat mat_specular[] = { 0.8, 0.8, 0.8, 1.0 };
^
SyntaxError: invalid syntax
for the following code, i know i need to import something use GLfloat, can you any one tell me what do i need to impor... | syntax error with glfloat python? | I am getting this error (note the code is from openGL red book:
GLfloat mat_specular[] = { 0.8, 0.8, 0.8, 1.0 };
^
SyntaxError: invalid syntax
for the following code, i know i need to import something use GLfloat, can you any one tell me what do i need to import for doing this in python.
GLfloat... | [
"Basic Python syntax issues here. First, in Python, you don't declare the variable type (GLfloat). Second (related to the first), you don't need the square braces after the variable name ([]) to denote that it is an array. And third, to use a list in Python (similar to an array), you need to wrap the contents in sq... | [
2
] | [] | [] | [
"opengl",
"python"
] | stackoverflow_0004080572_opengl_python.txt |
Q:
Can you change the way numpy prints arrays?
I have a 3d, 3x3x3 array of integers. Numpy will print these as a block of the first 3x3, then below it the 2nd 3x3, then below that the 3rd 3x3.
If I wanted to print these 3 3x3 blocks BESIDE each other, rather than underneath each other, how would I tell numpy to pr... | Can you change the way numpy prints arrays? | I have a 3d, 3x3x3 array of integers. Numpy will print these as a block of the first 3x3, then below it the 2nd 3x3, then below that the 3rd 3x3.
If I wanted to print these 3 3x3 blocks BESIDE each other, rather than underneath each other, how would I tell numpy to print differently?
| [
"class MyArray(numpy.array):\n def __str__(self):\n print [[[d for d in c] for c in b] for b in a]\n\nThis essentially subclasses numpy.array and just changes the __str__ function (which is called when getting the string representation of an object) which converts it into a regular array and prints that.\... | [
3,
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004080622_numpy_python.txt |
Q:
Python: extracting a list from an array of dictionaries with arrays in them
This question is a bit of a convoluted brain-twister, I'm afraid. I'm writing a function test on an api, that when I query it, returns a bunch of json with embedded lists. Here is a significant fragment of what that looks like (with all th... | Python: extracting a list from an array of dictionaries with arrays in them | This question is a bit of a convoluted brain-twister, I'm afraid. I'm writing a function test on an api, that when I query it, returns a bunch of json with embedded lists. Here is a significant fragment of what that looks like (with all the data anonymized for this question):
[{u'account': {u'account_name': u'Autotest ... | [
"Shouldn't something like this work?\nnames = [child['institution_name'] for child in inst_array[0]['children']]\n\n",
"I guess a list comprehension is still a form of iteration, but at least concise:\nyour_list = [elem['institution_name'] for elem in inst_array[0]['children']]\n\n",
"Not sure about what you me... | [
5,
1,
0,
0,
0
] | [] | [] | [
"arrays",
"dictionary",
"nested",
"python"
] | stackoverflow_0004080304_arrays_dictionary_nested_python.txt |
Q:
How can I add a command to the Python interactive shell?
I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
#... | How can I add a command to the Python interactive shell? | I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this funct... | [
"You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.\n",
"I think you want the cmd module.\nSee a tutorial here:\nhttp://wiki.python.org/moin/CmdModule\n",
"Hate to answer my own question, but there h... | [
7,
0,
0
] | [] | [] | [
"cpython",
"interactive",
"python",
"readline"
] | stackoverflow_0004017204_cpython_interactive_python_readline.txt |
Q:
Python and subprocess input piping
I have a small script that launches and, every half hour, feeds a command to a java program (game server manager) as if the user was typing it. However, after reading documentation and experimenting, I can't figure out how I can get two things:
1) A version which allows the user... | Python and subprocess input piping | I have a small script that launches and, every half hour, feeds a command to a java program (game server manager) as if the user was typing it. However, after reading documentation and experimenting, I can't figure out how I can get two things:
1) A version which allows the user to type commands into the terminal wind... | [
"Replace your sleep() with a call to select((sys.stdin, ), (), (), saveInterval*60) -- that will have the same timeout but listens on stdin for user commands. When select says you have input, read a line from sys.stdin and feed it to your process. When select indicates a timeout, perform the \"save\" command that y... | [
2,
1,
1
] | [] | [] | [
"pipe",
"popen",
"python",
"subprocess"
] | stackoverflow_0004080906_pipe_popen_python_subprocess.txt |
Q:
Reverse an explicit assignment of _ in python?
In python, if I create a local variable _ (underscore) and assign it to something:
_ = 3
Is it possible to reverse that assignment to regain usage of the underscore as the last returned output in the REPL?
A:
Yes. Use the del statement.
$ python
>>> _ = 3
>>> _
3
>... | Reverse an explicit assignment of _ in python? | In python, if I create a local variable _ (underscore) and assign it to something:
_ = 3
Is it possible to reverse that assignment to regain usage of the underscore as the last returned output in the REPL?
| [
"Yes. Use the del statement.\n$ python\n>>> _ = 3\n>>> _\n3\n>>> 5\n5\n>>> _\n3\n>>> del _\n>>> 6\n6\n>>> _\n6\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004081308_python.txt |
Q:
Finding the best "deal" in a "group buy", given a table of values
Using PHP or Python, but I'm sure the basic functions are agnostic.
I am unsure what the proper term, mathematical theory, or algorithm is, otherwise I'm sure Google would have fixed this for me in minutes.
I have a data set similar to the followi... | Finding the best "deal" in a "group buy", given a table of values | Using PHP or Python, but I'm sure the basic functions are agnostic.
I am unsure what the proper term, mathematical theory, or algorithm is, otherwise I'm sure Google would have fixed this for me in minutes.
I have a data set similar to the following:
cost | qty | ppl | store
------------------------
30| 500| 1... | [
"Compute qty / (cost * ppl) and sort the list by that number. This number will be higher for higher qty and lower cost and ppl.\nYou might want to use something like this (python):\ndef cmp(a, b):\n return (a[\"qty\"] / (a[\"cost\"] * a[\"ppl\"])) - (b[\"qty\"] / (b[\"cost\"] * b[\"ppl\"]))\n\nlist = sorted(list... | [
5,
1,
0
] | [] | [] | [
"math",
"php",
"python"
] | stackoverflow_0004081720_math_php_python.txt |
Q:
Using the --quiet tag when extending Mercurial
I'm writing a Mercurial extension in Python and need to call the "Pull" command using the Mercurial API, but I want to suppress its output using the --quiet flag.
In Hg terms, I want to execute the following code, but from within my extension:
hg pull --quiet
Given t... | Using the --quiet tag when extending Mercurial | I'm writing a Mercurial extension in Python and need to call the "Pull" command using the Mercurial API, but I want to suppress its output using the --quiet flag.
In Hg terms, I want to execute the following code, but from within my extension:
hg pull --quiet
Given the Mercurial API documentation, I thought it would b... | [
"Global options are affected through the ui object. It allows you to control many of the things you would normally set in your (or the repository's) hgrc. In this case, you want to set the quiet option in the ui section to True.\nui.setconfig('ui', 'quiet', True)\ncommands.pull(ui, repo)\n\n"
] | [
8
] | [] | [] | [
"mercurial",
"mercurial_extension",
"python"
] | stackoverflow_0004081717_mercurial_mercurial_extension_python.txt |
Q:
why does python inspect.isclass think an instance is a class?
Given the following module:
class Dummy(dict):
def __init__(self, data):
for key, value in data.iteritems():
self.__setattr__(key, value)
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__=dict.... | why does python inspect.isclass think an instance is a class? | Given the following module:
class Dummy(dict):
def __init__(self, data):
for key, value in data.iteritems():
self.__setattr__(key, value)
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__=dict.__setitem__
__delattr__=dict.__delitem__
foo=Dummy({"one":1, ... | [
"Prior to Python v2.7, inspect.isclass naively assumed anything with a __bases__ attribute must be a class.\nDummy's __getattr__ makes Dummy instances appear to have every attribute (with a value of None).\nTherefore, to inspect.isclass, foo appears to be a class.\nNote: __getattr__ should raiseAttributeError when ... | [
11,
6
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0004081819_introspection_python.txt |
Q:
Using python for commercial web application development
We (there are 2 of us) are new to web application development and are trying to develop a web based application product targeted at medium sized businesses.
The following is a basic flow of the work flow of the application:
Collect data through file upload p... | Using python for commercial web application development | We (there are 2 of us) are new to web application development and are trying to develop a web based application product targeted at medium sized businesses.
The following is a basic flow of the work flow of the application:
Collect data through file upload process (100K to 5 million records)
Collect control data from... | [
"To answer your first question, yes you absolutely should use a 3rd party web framework. There's no use in reinventing the wheel.\nThe two Python web frameworks that I am familiar with are Pylons and Django. This question covers the pros and cons for using either. Based on your description I would recommend Django.... | [
3,
1
] | [] | [] | [
"python",
"web_applications",
"web_frameworks"
] | stackoverflow_0004082109_python_web_applications_web_frameworks.txt |
Q:
Please help extract text from HTML tags using Python Regex
I have the following HTML text :
Country/<i>List it here</i><br><font color="#ff00ff">Dubai</font><br><br>
How do I extract 'Dubai' out of the above HTML? I have few hundreds such lines, kind of urgent, so not researching BeautifulSoup or XML parser impl... | Please help extract text from HTML tags using Python Regex | I have the following HTML text :
Country/<i>List it here</i><br><font color="#ff00ff">Dubai</font><br><br>
How do I extract 'Dubai' out of the above HTML? I have few hundreds such lines, kind of urgent, so not researching BeautifulSoup or XML parser implementation.
Thanks much!
| [
"Since you just want something quick and dirty, you could use:\nre.match(r'.*>([^<>]*)</font>.*', s).group(1)\n\nThis just grabs all of the non angle-brackety things before a closing font tag. Again, not suitable for \"real\" parsing.\n"
] | [
2
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0004082205_parsing_python_regex.txt |
Q:
How should I share code ("modules") between my templates?
If I had two controllers in my Pylons website that server up two different template files, what would be the best way to show the same piece of HTML on each template?
For example, lets say I had a blog. The front page would show the list of recent entries a... | How should I share code ("modules") between my templates? | If I had two controllers in my Pylons website that server up two different template files, what would be the best way to show the same piece of HTML on each template?
For example, lets say I had a blog. The front page would show the list of recent entries and each entry would have a 'permanent link' linking to a page s... | [
"Being able to share common HTML fragments like headers, footers, \"logged in\" area of page, sidebars etc. is a very common requirement. Template engines usually provide means for this. \nIf you're using Mako, here are the two main mechanisms you can use:\nIncludes\nCheck out the <%include> tag. In your page templ... | [
2,
0
] | [] | [] | [
"module",
"pylons",
"python",
"templates"
] | stackoverflow_0004075183_module_pylons_python_templates.txt |
Q:
Google Search with Python
From this question I've learned how to google-search using Python 3. But in the example given there you can retrieve only the first 4 results. I need to retrieve information about the first 25 results (at least).
For each result I want to be able to get its:
title
url
visible url (the vi... | Google Search with Python | From this question I've learned how to google-search using Python 3. But in the example given there you can retrieve only the first 4 results. I need to retrieve information about the first 25 results (at least).
For each result I want to be able to get its:
title
url
visible url (the visible url of http://en.wikipedi... | [
"This thread should tell you what you need to know. In short, add &rsz=large to the URI to get eight results at a time, and &start=8 (or 16, 24, etc.) gets you results starting with the indicated number. In no case can you get more than 64, and some searches allow only 8.\n",
"Use the JSON/Atom Custom Search API ... | [
2,
1
] | [] | [] | [
"python",
"search"
] | stackoverflow_0004082714_python_search.txt |
Q:
Scaling disqus using Django, horizontal and vertical partitioning helper methods, please explain
http://www.slideshare.net/zeeg/djangocon-2010-scaling-disqus
Vertical partitioning helper:
class ApplicationRouter(object)
def db_for_read(self, model, **hints):
instance = hints.get('instance')
... | Scaling disqus using Django, horizontal and vertical partitioning helper methods, please explain | http://www.slideshare.net/zeeg/djangocon-2010-scaling-disqus
Vertical partitioning helper:
class ApplicationRouter(object)
def db_for_read(self, model, **hints):
instance = hints.get('instance')
if not instance:
return None
app_label = instance._meta.app_label
return... | [
"He's discussing how Disqus leverages the database routing technique used in Django 1.2 and above, which allows you to have connections to multiple databases alive at the same time.\nUnlike earlier versions of Django, Django 1.2 and above use a dictionary of dictionaries, with the key of the initial dictionary bein... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004055213_django_python.txt |
Q:
Using Python 2.X's locale module to format numbers and currency
The task is to format numbers, currency amounts and dates as unicode strings in a locale-aware manner.
First naive attempt with numbers gave hope:
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyrig... | Using Python 2.X's locale module to format numbers and currency | The task is to format numbers, currency amounts and dates as unicode strings in a locale-aware manner.
First naive attempt with numbers gave hope:
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>... | [
"The thing about the locale module you seem to have missed is that it exposes your operating system vendor's (really: C library vendor's) notion of locales. So on Windows, you will have to use Windows locale names, use your OS vendor's documentation to find out what supported names are. Googling for \"windows local... | [
3
] | [] | [] | [
"internationalization",
"locale",
"python"
] | stackoverflow_0004082645_internationalization_locale_python.txt |
Q:
Hide information in a PDF file in Python
In Python, I have files generated by ReportLab. Now, i need to extract some pages from that PDF and hide confidential information.
I can create a PDF file with blacked-out spots and use pyPdf to mergePage, but people can still select and copy-paste the information under the... | Hide information in a PDF file in Python | In Python, I have files generated by ReportLab. Now, i need to extract some pages from that PDF and hide confidential information.
I can create a PDF file with blacked-out spots and use pyPdf to mergePage, but people can still select and copy-paste the information under the blacked-out spots.
Is there a way to make tho... | [
"Basically you'll have to remove the corresponding text drawing commands in the PDF's page content stream. It's much easier to generate the pages twice, once with the confidential information, once without them.\nIt might be possible (I don't know ReportLab enough) to specially craft the PDF in a way that the confi... | [
1,
0
] | [] | [] | [
"pypdf",
"python",
"reportlab"
] | stackoverflow_0004082725_pypdf_python_reportlab.txt |
Q:
Python/Django: Getting random articles from huge table
I have a huge table in my database (MySQL)with millions of data. I need to populate 10 random data and show it on the UI. What would be a good approach considering performance?
I was thinking about creating MySQL View to populate 10 random rows and read it fr... | Python/Django: Getting random articles from huge table | I have a huge table in my database (MySQL)with millions of data. I need to populate 10 random data and show it on the UI. What would be a good approach considering performance?
I was thinking about creating MySQL View to populate 10 random rows and read it from UI. Or is there any other efficient way to handle this si... | [
"This may be expensive and slow, but:\nMyModel.objects.order_by('?')[:10]\n\nThe main advantages being clarity and that it is not raw SQL.\n",
"First of all (it's my proper opinion) i'm against using raw SQL when we are already working with a hight level framework like Django unless we don't find what we are look... | [
3,
2
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0004083040_django_mysql_python.txt |
Q:
List comprehension and len() vs. simple for loop
I'm supposed to take a list of words and count all words in it which are 2 or more characters long and where the first and last character are equal.
I came up with two possible solutions:
result = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
... | List comprehension and len() vs. simple for loop | I'm supposed to take a list of words and count all words in it which are 2 or more characters long and where the first and last character are equal.
I came up with two possible solutions:
result = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
result += 1
return result
vs.
return len([word... | [
"In your second example a generator expression would be better than list-comp if your list is large.\nsum(1 for word in words if len(word) >= 2 and word[0] == word[-1])\n\n",
"The first one would definitely be the preferred solution in Python.\nDon't forget your Zen of Python:\n\nThe Zen of Python, by Tim Peters ... | [
17,
3,
2,
1,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0004083098_list_comprehension_python.txt |
Q:
How can I improve the quality of this python remote service code?
I wrote several small Python scripts to start clusters inside cloud infrastructures with distributed filesystems. Now, I integrated the code into a single command-line application but the code quality is very bad.
http://code.google.com/p/diffuser/... | How can I improve the quality of this python remote service code? | I wrote several small Python scripts to start clusters inside cloud infrastructures with distributed filesystems. Now, I integrated the code into a single command-line application but the code quality is very bad.
http://code.google.com/p/diffuser/source/browse/trunk/diffuser.py
The application needs to send lots of c... | [
"Commands are executed in a shell, so you can use regular shell syntax to combine them together. As a first step, I'd issue a batch of commands in a single exec_command:\n stdin, stdout, stderr = client.exec_command(\n \"sudo hostname;\"\n \"sudo apt-get update;\"\n \"sudo apt-get -y ... | [
2,
1
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0004082699_paramiko_python.txt |
Q:
Python Twisted with callInThread
I stripped down my app but this should give you an example of what i'm doing
def run_app(f):
p = Popen(['/usr/bin/app'],stdout=PIPE)
while True:
o = p.stdout.readline()
if o == '' and p.poll() != None: break
reactor.callFromThread(f, o)
class Echo(... | Python Twisted with callInThread | I stripped down my app but this should give you an example of what i'm doing
def run_app(f):
p = Popen(['/usr/bin/app'],stdout=PIPE)
while True:
o = p.stdout.readline()
if o == '' and p.poll() != None: break
reactor.callFromThread(f, o)
class Echo(Protocol):
def connectionMade(self... | [
"Don't use threads and Popen. Use Twisted's process support. Also, your Echo protocol needs framing or there's no guarantee that it will ever receive the \"getmore\" string.\n",
"There are few suggestions that I can make and hopefully it will resolve your issues.\nDon't use reactor.callFromThread, instead use d... | [
3,
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0004081578_python_twisted.txt |
Q:
Proper location to set up MySQLdb connection in Pylons: app_globals? Thread safety?
I want to use MySQLdb in Pylons, but can't figure out where to actually connect. It would seem that making the connection in app_globals.py would be convenient:
class Globals(object):
def __init__(self):
self.db = MySQL... | Proper location to set up MySQLdb connection in Pylons: app_globals? Thread safety? | I want to use MySQLdb in Pylons, but can't figure out where to actually connect. It would seem that making the connection in app_globals.py would be convenient:
class Globals(object):
def __init__(self):
self.db = MySQLdb.connect()
Then controllers can access the db via the globals. However, this seems to ... | [
"Summarizing the comments on your question: you should probably use SQLAlchemy's non-ORM features such as the SQL Expression Language and the engine API, which each let you still get some of the benefits of SQLAlchemy without needing to go all the way up to ORM-ness.\n"
] | [
1
] | [] | [] | [
"mysql",
"pylons",
"python"
] | stackoverflow_0004040890_mysql_pylons_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.