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:
nosetest deprecation warnings
I am getting deprecation warnings from nosetest for 3rd party modules imported by my code.
Does anybody know how to silence these warnings?
I know of the following flag which works for arbitrary python runs of the same code:
python -W ignore::DeprecationWarning
But, calling nose... | nosetest deprecation warnings | I am getting deprecation warnings from nosetest for 3rd party modules imported by my code.
Does anybody know how to silence these warnings?
I know of the following flag which works for arbitrary python runs of the same code:
python -W ignore::DeprecationWarning
But, calling nosetest does not appear to offer me a ... | [
"Put \nimport warnings\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\n\nat the start of your test script, before you import any problematic libraries.\n"
] | [
3
] | [] | [] | [
"deprecated",
"python",
"suppress_warnings",
"unit_testing"
] | stackoverflow_0003728325_deprecated_python_suppress_warnings_unit_testing.txt |
Q:
Python USSD via com port
I am new to python. Is there anyway i can use python to send ussd with a phone via at+cusd commands. i can do that using hyperterminal. i want to automate using python. thanks.
A:
Yes. Use pyserial.
>>> import serial
>>> ser = serial.Serial(0) # open first serial port
>>> print ser.port... | Python USSD via com port | I am new to python. Is there anyway i can use python to send ussd with a phone via at+cusd commands. i can do that using hyperterminal. i want to automate using python. thanks.
| [
"Yes. Use pyserial.\n>>> import serial\n>>> ser = serial.Serial(0) # open first serial port\n>>> print ser.portstr # check which port was really used\n>>> ser.write(\"hello\") # write a string\n>>> ser.close() # close port\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003727938_python.txt |
Q:
Getting current user home directory on OS X?
How to find current user home directory on OS X?
HOME environmental variable is not always set, for example when you do not run in console (GUI apps).
For this reason I'm looking for a generic solution, one that will fall-back if os.environ['HOME'] is not set.
There is ... | Getting current user home directory on OS X? | How to find current user home directory on OS X?
HOME environmental variable is not always set, for example when you do not run in console (GUI apps).
For this reason I'm looking for a generic solution, one that will fall-back if os.environ['HOME'] is not set.
There is a similar question (C) but it already has an accep... | [
"It looks that os.path.expanduser(\"~\") always returns the home directory, even on Windows.\n"
] | [
1
] | [] | [] | [
"home_directory",
"macos",
"python"
] | stackoverflow_0003726113_home_directory_macos_python.txt |
Q:
How to quickly fail a python script if it is called from wrong interpreter?
I have inherited a few Python scripts from someone who has left my employer. Some are meant to be run from Jython, others are not.
I'd like to add them to svn, but before I do I want to modify these files so that if a "requires Jython" fi... | How to quickly fail a python script if it is called from wrong interpreter? | I have inherited a few Python scripts from someone who has left my employer. Some are meant to be run from Jython, others are not.
I'd like to add them to svn, but before I do I want to modify these files so that if a "requires Jython" file is run from python, the user gets a message like "please run with Jython" and ... | [
"What I have seen done is to try to import a module exclusive to a given version or implementation, and raise ImportError if the module does not exist. \nImagine that Jython (and not Python) has a module called special, then you add:\n# at the top of your module:\ntry:\n import special\nexcept ImportError:\n ra... | [
3
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0003728546_jython_python.txt |
Q:
Python scoping and threading question
I have one thread that inserts into the queueStream (not shown here) and FlowController which is another thread that pops from the queue if the queue is not empty.
I verified that the data is inserted into the queue correctly with the debug code in addToQueue()
Problem is, the... | Python scoping and threading question | I have one thread that inserts into the queueStream (not shown here) and FlowController which is another thread that pops from the queue if the queue is not empty.
I verified that the data is inserted into the queue correctly with the debug code in addToQueue()
Problem is, the 'if queueStream' statement in FlowControll... | [
"It's hard to debug this problem without seeing RunStream.\nSo I tried to dream up a simple RunStream that might exhibit the problem.\nI wasn't able to reproduce the problem, but this code seems to work. \nIf it does work and is similar enough to your RunStream, perhaps you can compare this code to your own to find... | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"scoping"
] | stackoverflow_0003728577_multithreading_python_scoping.txt |
Q:
How can I programmatically change the argspec of a function in a python decorator?
Given a function:
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
How can I create a decorator such that b... | How can I programmatically change the argspec of a function in a python decorator? | Given a function:
def func(f1, kw='default'):
pass
bare_argspec = inspect.getargspec(func)
@decorator
def func2(f1, kw='default'):
pass
decorated_argspec = inspect.getargspec(func2)
How can I create a decorator such that bare_argspec == decorated_argspec?
(As to why, the framework that calls the decorated fun... | [
"Michele Simionato's decorator module has a decorator called decorator which preserves function argspecs.\nimport inspect\nimport decorator\n\ndef func(f1, kw='default'):\n pass\nbare_argspec = inspect.getargspec(func)\nprint(bare_argspec)\n# ArgSpec(args=['f1', 'kw'], varargs=None, keywords=None, defaults=('def... | [
13,
2,
0
] | [] | [] | [
"decorator",
"inspect",
"python",
"reflection"
] | stackoverflow_0003729378_decorator_inspect_python_reflection.txt |
Q:
python re: r'\b \$ \d+ \b' won't match 'aug 12, 2010 abc $123'
so i'm just making a script to collect $ values from a transaction log type file
for line in sys.stdin:
match = re.match( r'\b \$ (\d+) \b', line)
if match is not None:
for value in match.groups():
print value
r... | python re: r'\b \$ \d+ \b' won't match 'aug 12, 2010 abc $123' | so i'm just making a script to collect $ values from a transaction log type file
for line in sys.stdin:
match = re.match( r'\b \$ (\d+) \b', line)
if match is not None:
for value in match.groups():
print value
right now I'm just trying to print those values
it would match a line... | [
"re.match:\n\nIf zero or more characters at the beginning of string match this regular expression, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.\n\nWhat your are looking for is either re.search or re.findall:\... | [
6,
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003728292_python_regex.txt |
Q:
Python: Execute a command in a subshell without cmd interface or hidden or in background
I would like to know how I could execute a command whitout appears the cmd window.
My code is in Python and the O.S. is Windows7.
The problematic line is:
os.system(pathandarguments)
The program works fine, execute the given p... | Python: Execute a command in a subshell without cmd interface or hidden or in background | I would like to know how I could execute a command whitout appears the cmd window.
My code is in Python and the O.S. is Windows7.
The problematic line is:
os.system(pathandarguments)
The program works fine, execute the given path with the arguments but I loose the control of my program because my program window minimiz... | [
"For a long time I've been using an open source Python module for process control called process-python. The Project Status there says \"In its current state it was used heavily in the commercial Komodo IDE project.\" It's multiplatform, but one of the main reasons I started using it was because on Windows it will ... | [
1
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0003729061_cmd_python.txt |
Q:
Uses of self referencing lists
I know it is possible to create a self referencing list in languages like Python:
>>> my_list = [1,2]
>>> my_list.append(my_list)
>>> print my_list
[1,2,[...]]
>>> print my_list[0]
1
>>> print my_list[2]
[1,2,[...]]
What algorithms benefit from self referencing lists? I cannot think... | Uses of self referencing lists | I know it is possible to create a self referencing list in languages like Python:
>>> my_list = [1,2]
>>> my_list.append(my_list)
>>> print my_list
[1,2,[...]]
>>> print my_list[0]
1
>>> print my_list[2]
[1,2,[...]]
What algorithms benefit from self referencing lists? I cannot think of one.
Thanks.
| [
"Self-referencing lists, and, generally speaking, circular data structures, can be caused when representing a graph using data structures.\nFor example, consider this naive representation of a graph: Each node is either an atomic value, or a list of nodes that it is linked to. A circle may cause a list to contain a... | [
4,
0,
0
] | [] | [] | [
"algorithm",
"language_agnostic",
"list",
"python",
"self_reference"
] | stackoverflow_0003728667_algorithm_language_agnostic_list_python_self_reference.txt |
Q:
a list of pygame sprites loses its first element, and gains a duplicate of the last
I have a function that loads a sprite sheet, finds a block of sprites, and then puts each individual sprite into a list. Before it appends a sprite into the list, it will blit it onto the screen. Once it's done loading sprites, i... | a list of pygame sprites loses its first element, and gains a duplicate of the last | I have a function that loads a sprite sheet, finds a block of sprites, and then puts each individual sprite into a list. Before it appends a sprite into the list, it will blit it onto the screen. Once it's done loading sprites, it will then iterate through the list, blitting each sprite as it goes. The two sets of b... | [
"image.blit(spritesheet, (0,0), rect)\n\nYou haven't re-initialised image each time around the loop, it's still the same surface you used in the previous iteration, a surface that is already in the list. Each time round the loop you overwrite the sprite you appended to the list in the previous step.\nI suggest grab... | [
7
] | [] | [] | [
"list",
"pygame",
"python"
] | stackoverflow_0003729648_list_pygame_python.txt |
Q:
Issue with Django admin registering an inline user profile admin
I'm currently working on a django project. I'm attempting to add a UserProfile model inline to my User model. In my models.py I have:
class UserProfile(models.Model):
'''
Extension to the User model in django admin.
'''
user = models.... | Issue with Django admin registering an inline user profile admin | I'm currently working on a django project. I'm attempting to add a UserProfile model inline to my User model. In my models.py I have:
class UserProfile(models.Model):
'''
Extension to the User model in django admin.
'''
user = models.ForeignKey(User)
site_role = models.CharField(max_length=128, choi... | [
"my guess is that you either are doing some crazy module importing... or... you have an ordering problem in your settings.INSTALLED_APPS list. Make sure that 'django.contrib.auth' appears on your list before your app that is replacing the default admin. The list should look something like this:\nINSTALLED_APPS = (\... | [
21
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003729866_django_django_admin_python.txt |
Q:
Why can't I "save as" an Excel file from my Python code?
I have an Python ExcelDocument class that provides basic convenience methods for reading/writing/formatting Excel files, and I'm getting a strange error in seemingly simple Python code. I have a save and saveAs method:
def save(self):
''' Save the file ''... | Why can't I "save as" an Excel file from my Python code? | I have an Python ExcelDocument class that provides basic convenience methods for reading/writing/formatting Excel files, and I'm getting a strange error in seemingly simple Python code. I have a save and saveAs method:
def save(self):
''' Save the file '''
self.workbook.Save()
def saveAs(self, newFileName):
'... | [
"I've found (the hard way) that SaveAs doesn't support slash /.\nTry saveAs(\"C:\\\\test.xlx\") instead.\n"
] | [
18
] | [] | [] | [
"python",
"save_as"
] | stackoverflow_0003730428_python_save_as.txt |
Q:
Trying to group similar text rows in a column of a million row table - Open to Non-MySQL approaches
I have a large number (about 40 million) of VARCHAR entries in a MySQL table. The length of the string can be anywhere between 5-80 characters. I am trying to group similar text together and thought of a possible ap... | Trying to group similar text rows in a column of a million row table - Open to Non-MySQL approaches | I have a large number (about 40 million) of VARCHAR entries in a MySQL table. The length of the string can be anywhere between 5-80 characters. I am trying to group similar text together and thought of a possible approach:
Take a row and calculate a similarity measure (like Edit Distance) with every other row and decid... | [
"Have you looked at MySQL's FULLTEXT functiality?\nUPDATE -- MySQL's FULLTEXT doesn't seem to support fuzzy searching, which is what you are looking for here. Check out MySQL Full Text Search Boolean Mode Partial Match\nMySQL does support the SOUNDEX() function, which will match words that sound similar to what is... | [
1
] | [] | [] | [
"database",
"mysql",
"php",
"python",
"text"
] | stackoverflow_0003730643_database_mysql_php_python_text.txt |
Q:
How can I store testing data for python nosetests?
I want to write some tests for a python MFCC feature extractor for running with nosetest. As well as some lower-level tests, I would also like to be able to store some standard input and expected-output files with the unit tests.
At the moment we are hard-coding ... | How can I store testing data for python nosetests? | I want to write some tests for a python MFCC feature extractor for running with nosetest. As well as some lower-level tests, I would also like to be able to store some standard input and expected-output files with the unit tests.
At the moment we are hard-coding the paths to the files on our servers, but I would prefe... | [
"I think that using __file__ to figure out where the test is located and storing data alongside the it is a good idea. I'm doing the same for some tests that I write.\nThis:\nos.path.dirname(os.path.abspath(__file__))\n\nis probably the best you are going to get, and that's not bad. :-)\n",
"Based on the idea of ... | [
6,
0
] | [] | [] | [
"nosetests",
"python",
"unit_testing"
] | stackoverflow_0003724072_nosetests_python_unit_testing.txt |
Q:
need Advice on ID3 implementation and Datatype to be used
Need advice:
I am implementing ID3 algorithm in Machine Learning. I am using dictionary to read the training file and store into. But as I am going forward I am understanding that in dictionary v dont have fixed places for each key,value pair as in list or ... | need Advice on ID3 implementation and Datatype to be used | Need advice:
I am implementing ID3 algorithm in Machine Learning. I am using dictionary to read the training file and store into. But as I am going forward I am understanding that in dictionary v dont have fixed places for each key,value pair as in list or array. Now I might have problem in getting the position of the ... | [
"Python 2.7 and 3.x have an OrderedDict that could be an option for you.\n"
] | [
2
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0003730118_machine_learning_python.txt |
Q:
Using a loop to generate unique bitmap buttons with separate events when clicked
I'm pretty new to Python, so I'll hope you forgive me for such amateurish code. I've tried pouring over examples that do similar things but I'm having trouble figuring out what they're doing that is different. In examples I've seen ea... | Using a loop to generate unique bitmap buttons with separate events when clicked | I'm pretty new to Python, so I'll hope you forgive me for such amateurish code. I've tried pouring over examples that do similar things but I'm having trouble figuring out what they're doing that is different. In examples I've seen each button generated with the loop had a different action, for mine only the last butto... | [
"Only the last button is working because each time you go through the __DoButtons loop you reassign self.b to a different button. So after the loop has finished self.b is only assigned to the last button. You can get the button pressed using the event.GetEventObject() method.\nChange your OnClick method to:\ndef O... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003730448_python_wxpython.txt |
Q:
Equivalent of objects.latest() in App Engine
What would be the best way to get the latest inserted object using AppEngine ?
I know in Django this can be done using
MyObject.objects.latest()
in AppEngine I'd like to be able to do this
class MyObject(db.Model):
time = db.DateTimeProperty(auto_now_add=True)
# Re... | Equivalent of objects.latest() in App Engine | What would be the best way to get the latest inserted object using AppEngine ?
I know in Django this can be done using
MyObject.objects.latest()
in AppEngine I'd like to be able to do this
class MyObject(db.Model):
time = db.DateTimeProperty(auto_now_add=True)
# Return latest entry from MyObject.
MyObject.all().la... | [
"Your best bet will be to implement a latest() classmethod directly on MyObject and call it like\nlatest = MyObject.latest()\n\nAnything else would require monkeypatching the built-in Query class.\nUpdate\nI thought I'd see how ugly it would be to implement this functionality. Here's a mixin class you can use if y... | [
5,
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003730810_django_google_app_engine_python.txt |
Q:
How to update $PATH
I am writing a python/pygtk application that is adding some custom scripts (bash) in a certain folder in $HOME (eg. ~/.custom_scripts).
I want to make that folder available in $PATH. So every time the python app is adding the script, that script could be instantly available when the user is op... | How to update $PATH | I am writing a python/pygtk application that is adding some custom scripts (bash) in a certain folder in $HOME (eg. ~/.custom_scripts).
I want to make that folder available in $PATH. So every time the python app is adding the script, that script could be instantly available when the user is opening a terminal (eg. gno... | [
".profile would be a reasonable place if it's a per-user install; /etc/profile.d for system-wide installs. (You'll need root to do that, of course.) \nYour installer won't be able to change the path of the current shell (unless it's being run via source, which would be...odd.)\n",
"For scripts that go in the $H... | [
2,
2,
1,
1,
1,
1
] | [
"Why don't you establish the appropriate PATH upon the first call to your module (i.e. in your module's __init__.py):\n# this is your module's __init__.py\nimport sys\neggs = ['/path/to/egg/1.egg', '/path/to/egg/2.egg']\nfor egg in eggs:\n sys.path.append(egg)\n\n"
] | [
-1
] | [
"bash",
"path",
"python",
"scripting"
] | stackoverflow_0003729965_bash_path_python_scripting.txt |
Q:
Send from Twisted client to Twisted server, only this one way
I want to use Twisted to rebuild the communication part of an existing application. This application does send data from the client to the server, only this way round, the server does not send anything.
How do I accomplish this with the event-driven con... | Send from Twisted client to Twisted server, only this one way | I want to use Twisted to rebuild the communication part of an existing application. This application does send data from the client to the server, only this way round, the server does not send anything.
How do I accomplish this with the event-driven concept of Twisted? I currently use the connectionMade method of Proto... | [
"No, that is definitely not the right way to do that. Never, ever call doWrite.\nThe problem here is that I bet queue.get() just blocks until there is some data. If possible, use a non-blocking means of message passing rather than threads. For example, have your thread just callFromThread to your Send protocol t... | [
2,
1
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0003730951_networking_python_twisted.txt |
Q:
Passing 'None' as function parameter (where parameter is a function)
I am writing a small app that has to perform some 'sanity checks' before entering execution. (eg. of a sanity check: test if a certain path is readable / writable / exists)
The code:
import logging
import os
import shutil
import sys
from paths im... | Passing 'None' as function parameter (where parameter is a function) | I am writing a small app that has to perform some 'sanity checks' before entering execution. (eg. of a sanity check: test if a certain path is readable / writable / exists)
The code:
import logging
import os
import shutil
import sys
from paths import PATH
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogge... | [
"update\nI would normally delete this post because THC4k saw through all the complexity and rewrote your function correctly. However in a different context, the K combinator trick might come in handy, so I'll leave it up.\n\nThere is no builtin that does what you want AFIK. I believe that you want the K combinator ... | [
8,
8,
3,
1,
1
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0003730831_lambda_python.txt |
Q:
Python: binascii.a2b_hex gives "Odd-length string"
I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b_hex to convert it to the proper binary representation. Here is what I have:
k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)
When I pri... | Python: binascii.a2b_hex gives "Odd-length string" | I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b_hex to convert it to the proper binary representation. Here is what I have:
k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)
When I print k1, it is as expected: 81e3d6df
Here is the error mes... | [
"Are you sure the file doesn't have something extra in it? Whitespace, for instance?\nTry k1.strip()\n",
"I suspect there is a trailing newline at the end of the file. Strip the string before passing it to binascii.\nNote there's now also a simpler spelling: k1.strip().decode('hex').\n",
"I'm more interested wh... | [
8,
6,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0003731278_python.txt |
Q:
Python runs a if-case that it should not!
I have this code:
def random_answerlist(self):
self.li = []
self.winning_button = random.randint(0, 3)
i = 0
while i < 20 and len(self.li) is not 4:
if i == self.winning_button:
self.li.append(self.flags[self.current_flag][0])
el... | Python runs a if-case that it should not! | I have this code:
def random_answerlist(self):
self.li = []
self.winning_button = random.randint(0, 3)
i = 0
while i < 20 and len(self.li) is not 4:
if i == self.winning_button:
self.li.append(self.flags[self.current_flag][0])
else:
new_value = self.random_value()... | [
"One glaring problem is the usage of is not for a value comparision against len(self.li). The tests is not and != are not the same. is tests for identity (are these references to the same object?), != tests for equality (do these objects have the same value?).\nChange your while to:\nwhile i < 20 and len(self.li) !... | [
1,
0
] | [] | [] | [
"case",
"if_statement",
"loops",
"python",
"while_loop"
] | stackoverflow_0003731228_case_if_statement_loops_python_while_loop.txt |
Q:
How do I create a url pattern like controller/action/id in django?
I'm trying to create a url pattern that will behave like controller/action/id route in rails. So far here is what I have :
from django.conf.urls.defaults import *
import views
urlpatterns = ('',
(r'^(?P<app>\w+)/(?P<view>\w+)/$', vie... | How do I create a url pattern like controller/action/id in django? | I'm trying to create a url pattern that will behave like controller/action/id route in rails. So far here is what I have :
from django.conf.urls.defaults import *
import views
urlpatterns = ('',
(r'^(?P<app>\w+)/(?P<view>\w+)/$', views.select_view),
)
Here is my 'views.py':
def select_view... | [
"Try something like this:\nfrom django.utils.importlib import import_module\n\ndef select_view(request, app, view):\n mod = import_module('%s.views' % app)\n return getattr(mod, view)(request)\n\nIt is obviously oversimplified example, what you do is import views.py from your app and see if it has view functi... | [
1
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003731132_django_django_urls_python.txt |
Q:
how to replace the characters in strings with '#'s by using regex in Python
How can I replace the contents of strings with #'s in Python? Assume no comments, no multiple lines for one string. Like if there is a line in a python file:
print 'Hello' + "her mom's shirt".
This will be translated into:
print '#####' +... | how to replace the characters in strings with '#'s by using regex in Python | How can I replace the contents of strings with #'s in Python? Assume no comments, no multiple lines for one string. Like if there is a line in a python file:
print 'Hello' + "her mom's shirt".
This will be translated into:
print '#####' + "###############".
It's like a filter to deal with every line in a python file.... | [
"If you're using Python and the thing you're parsing is Python there's no need to use regexp since there's a built-in parser.\n",
">>> import re\n>>> s=\"The Strings\"\n>>> s=re.sub(\"\\w\",\"#\",s)\n>>> s\n'### #######'\n>>> s='Hello' + \"her mom's shirt\"\n>>> s\n\"Helloher mom's shirt\"\n>>> re.sub(\"\\w\",\"#... | [
5,
2,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003731341_python_regex_string.txt |
Q:
Conditional Class Creation (Python)
From the tutorial: "A class definition is an executable statement."
Is the following recommended in a script?
my_switch = False
if my_switch:
class Hello:
def __init__(self):
self.greeting = "Hello!"
else:
class Hello:
def __init__(self):
... | Conditional Class Creation (Python) | From the tutorial: "A class definition is an executable statement."
Is the following recommended in a script?
my_switch = False
if my_switch:
class Hello:
def __init__(self):
self.greeting = "Hello!"
else:
class Hello:
def __init__(self):
self.greeting = "Salut!"
| [
"You can even do\nclass Hello:\n def __init__(self):\n self.greeting = \"Hello!\"\n\nclass Salut:\n def __init__(self):\n self.greeting = \"Salut!\"\n\nif my_switch:\n Hello = Salut\n\n(note that your code needs lower-case Class keywords...)\n",
"If you like it better, you could put each cl... | [
11,
6,
5,
5,
4,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003729419_python.txt |
Q:
How do I divide the members of a list by the corresponding members of another list in Python?
Let's say I have two data sets. I have a week-by-week tally of users who tried my service.
trials = [2,2,2,8,8,4]
And I have a week by week tally of trial users who signed up.
conversions = [1,0,2,4,8,3]
I can do it pre... | How do I divide the members of a list by the corresponding members of another list in Python? | Let's say I have two data sets. I have a week-by-week tally of users who tried my service.
trials = [2,2,2,8,8,4]
And I have a week by week tally of trial users who signed up.
conversions = [1,0,2,4,8,3]
I can do it pretty quickly this way:
conversion_rate = []
for n in range(len(trials)):
conversion_rate.append(c... | [
"Use zip:\n[c/t for c,t in zip(conversions, trials)]\n\nThe most elegant way to get floats is to upgrade to Python 3.x.\nIf you need to use Python 2.x then you could write this:\n>>> [float(c)/t for c,t in zip(conversions, trials)]\n[0.5, 0.0, 1.0, 0.5, 1.0, 0.75]\n\nAlternatively you could add this at the start of... | [
15,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003731426_python.txt |
Q:
Getting Started with PyQt
I'm testing out some of the examples in Rapid GUI Programming with Python and Qt, but running into a stumbling block here or where. When I copied to following exercise (verbatim, from the book):
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplicatio... | Getting Started with PyQt | I'm testing out some of the examples in Rapid GUI Programming with Python and Qt, but running into a stumbling block here or where. When I copied to following exercise (verbatim, from the book):
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
app = QApplication(sys.argv)
try:
due = QTi... | [
"You probably forgot to add a shebang to your script, to tell your shell to actually run it with the Python interpreter. Try adding\n#!/usr/bin/python\n\nas the first line in your script, provided that's where your Python interpreter is installed. You might want to try\nwhich python\n\nin case you're not sure.\n"
] | [
8
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0003731558_pyqt_python_qt.txt |
Q:
beep sound in python audiolab
How do i generate a gentle "beep" sound in python audiolab, without the use of external .wav files? I found the following example to generate random noise:
play(0.05 * np.random.randn(2, 48000))
Unfortunately i do not have enough knowledge of audio representations to create a beep (o... | beep sound in python audiolab | How do i generate a gentle "beep" sound in python audiolab, without the use of external .wav files? I found the following example to generate random noise:
play(0.05 * np.random.randn(2, 48000))
Unfortunately i do not have enough knowledge of audio representations to create a beep (of a certain frequency) and i have n... | [
"To be precise:\nimport audiolab\nimport scipy\nx = scipy.cos((2*scipy.pi*f/fs)*scipy.arange(fs*T))\naudiolab.play(x, fs)\n\nwhere f is the frequency of the tone in Hertz, fs is the sampling rate, and T is the length of the tone in seconds.\n",
"I figured it out:\nplay(0.05 * np.array([math.cos(x/40) for x in ran... | [
3,
0
] | [] | [] | [
"audio",
"numpy",
"python"
] | stackoverflow_0003725173_audio_numpy_python.txt |
Q:
Python import problem with Django management commands
For whatever reason, when I was new to Python and Django, I wrote some import statements like this at the top of a models.py file:
from django.contrib import auth
And I'd use it like this:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.U... | Python import problem with Django management commands | For whatever reason, when I was new to Python and Django, I wrote some import statements like this at the top of a models.py file:
from django.contrib import auth
And I'd use it like this:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.User)
# ...
This worked fine. A long time later, I wrot... | [
"If some random module ever imports module x.y.z, then a later person who imports just x.y will see a z in the x.y namespace.\nThe reason this happens is that import x.y.z is actually three import statements in one. It works something like this:\nx = __internal_import('x')\nx.y = __internal_import('x/y')\nx.y.z = ... | [
5,
0,
0
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0003711869_django_import_python.txt |
Q:
Is there a ready-to-use form to display lists of objects in the django forms api?
Is there a form(or any other solution) that allows me to quickly build forms that display lists of models(with filtering, ordering etc) like the django admin site does?
A:
Short answer: Yes.
Long answer: Yes, but the filtering, or... | Is there a ready-to-use form to display lists of objects in the django forms api? | Is there a form(or any other solution) that allows me to quickly build forms that display lists of models(with filtering, ordering etc) like the django admin site does?
| [
"Short answer: Yes. \nLong answer: Yes, but the filtering, ordering, etc. are left up to you to come up with. In Django \"generic view\" really does mean generic.\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003731808_django_django_admin_django_models_python.txt |
Q:
Reading a file in Python while logging data in screen
Background
To capture data from a logic controller, I'm using screen as a terminal emulator and connecting my MacBook via the KeySpan USA-19HS USB Serial Adapter. I've created the following bash script, so that I can type talk2controller <filename> where filena... | Reading a file in Python while logging data in screen | Background
To capture data from a logic controller, I'm using screen as a terminal emulator and connecting my MacBook via the KeySpan USA-19HS USB Serial Adapter. I've created the following bash script, so that I can type talk2controller <filename> where filename is the name of the data file.
#!/bin/bash
if [ -z "$1" ]... | [
"Both option 1 and 2 will work, but oh boy, in the name of all things good, avoid using threads for this! You'll end up with the worst of both worlds: locking problems, and an exception in the graphing thread will kill the whole program (including the logging thread) anyway. As someone else mentioned, using two s... | [
3,
1,
1
] | [] | [] | [
"gnu_screen",
"logging",
"matplotlib",
"python"
] | stackoverflow_0003709698_gnu_screen_logging_matplotlib_python.txt |
Q:
Qt4: Write a function that creates a dialog and returns the choice of the user
Not sure if this has a straightforward solution, but I want to write a function that shows a dialog (defined elsewhere in a class that inherits QDialog) and returns the user input when the user has finished interacting with the dialog. ... | Qt4: Write a function that creates a dialog and returns the choice of the user | Not sure if this has a straightforward solution, but I want to write a function that shows a dialog (defined elsewhere in a class that inherits QDialog) and returns the user input when the user has finished interacting with the dialog. In other words, something similar to the QFileDialog::getOpenFileName static method,... | [
"It sounds like you have everything in place that you need. You can make a static function in your QDialog derived class that does what you want. You can create a struct or class that encapsulates the data the user will generate and return it from your static function. Qt includes all the source code so you can loo... | [
1
] | [] | [] | [
"python",
"qt",
"user_interface"
] | stackoverflow_0003731702_python_qt_user_interface.txt |
Q:
Appengine - how to get an entity and display values
I'm having trouble with my project. I have 2 models
class UserPrefs(db.Model):
user = db.UserProperty()
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
phone = db.PhoneNumberProperty()
userPrefs = db.ReferencePr... | Appengine - how to get an entity and display values | I'm having trouble with my project. I have 2 models
class UserPrefs(db.Model):
user = db.UserProperty()
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
phone = db.PhoneNumberProperty()
userPrefs = db.ReferenceProperty(UserPrefs)
class PersonHandler(webapp.RequestHand... | [
"Your code is a bit disorganised.\nDebugging is generally easier with better-organised code.\nAnyway, enough of the trash-talking.\nYou're assigning the result of a datastore query to persons... \npersons = person.fetch(limit = 1)\n\n...but then in your template you use person:\n<tr>\n <td>Nome: </td>\n <td>{{ p... | [
0
] | [] | [] | [
"bigtable",
"djangoappengine",
"google_app_engine",
"python"
] | stackoverflow_0003730575_bigtable_djangoappengine_google_app_engine_python.txt |
Q:
how can i get the geo_pt on another Model using google app engine(python)
this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
class BaseRequestHandler(webapp.RequestHandl... | how can i get the geo_pt on another Model using google app engine(python) | this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
class BaseRequestHandler(webapp.RequestHandler):
def render_template(self, filename, template_values={}):
value... | [
"Did you mean:\nq = Marker_info.all() \nq.filter(\"info =\", \"sss\")\n\n?\nMaybe try this:\nmarker_data.push([{{i.marker_latlng.geo_pt}}]) \n\nOr maybe:\nmarker_data.push([{{i.marker_latlng.geo_pt.lat}}, {{i.marker_latlng.geo_pt.lon}}]) \n\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"javascript",
"model",
"python"
] | stackoverflow_0003732214_google_app_engine_javascript_model_python.txt |
Q:
how to get the info which contains 'sss', not "= ",
this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
q = Marker_info.all()
q.filter("info =", "sss")
but how to get th... | how to get the info which contains 'sss', not "= ", | this is my code:
class Marker_latlng(db.Model):
geo_pt = db.GeoPtProperty()
class Marker_info(db.Model):
info = db.StringProperty()
marker_latlng =db.ReferenceProperty(Marker_latlng)
q = Marker_info.all()
q.filter("info =", "sss")
but how to get the info which contains 'sss', not "=",
has a method like "... | [
"Instead of using a StringProperty, you could use a StringListProperty. Before saving the info string, split it into a list of strings, containing each word.\nThen, when you use q.filter(\"info =\", \"sss\") it will match any item which contains a word which is each to \"sss\".\nFor something more general, you coul... | [
1
] | [] | [] | [
"filter",
"google_app_engine",
"python"
] | stackoverflow_0003732351_filter_google_app_engine_python.txt |
Q:
Using Python quick insert many columns into Sqlite\Mysql
If Newdata is list of x columns, How would get the number unique columns--number of members of first tuple. (Len is not important.) Change the number of "?" to match columns and insert using the statement below.
csr = con.cursor()
csr.execute('Trun... | Using Python quick insert many columns into Sqlite\Mysql | If Newdata is list of x columns, How would get the number unique columns--number of members of first tuple. (Len is not important.) Change the number of "?" to match columns and insert using the statement below.
csr = con.cursor()
csr.execute('Truncate table test.data')
csr.executemany('INSERT INTO test.data ... | [
"By \"Newdata is list of x columns\", I imagine you mean x tuples, since then you continue to speak of \"the first tuple\". If Newdata is a list of tuples, y = len(Newdata[0]) is the number of items in the first one of those tuples.\nAssuming that's the number you want (and all tuples had better have the same numb... | [
6,
1
] | [] | [] | [
"mysql",
"python",
"python_db_api",
"sqlite"
] | stackoverflow_0003732490_mysql_python_python_db_api_sqlite.txt |
Q:
Get new selection in a GtkTreeView during the signal
I want to detect whenever the selection of my gtk.TreeView changes and, when it does, to call a function w/ this information. The only way I've found to do it so far is to attach to all these signals:
...
self.sitterView.connect("cursor-changed", self.select... | Get new selection in a GtkTreeView during the signal | I want to detect whenever the selection of my gtk.TreeView changes and, when it does, to call a function w/ this information. The only way I've found to do it so far is to attach to all these signals:
...
self.sitterView.connect("cursor-changed", self.selectionChanged)
self.sitterView.connect("unselect-all", se... | [
"I'm not sure what toggle-cursor-row does (the documentation is frustratingly empty), but I think that's the wrong signal to handle.\nInstead, you should connect to the GtkTreeSelection changed signal. It should take care of all selection change events, so you don't need to connect to the other signals either.\n"
] | [
7
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003731549_gtk_gtktreeview_pygtk_python.txt |
Q:
urllib2.proxyhandler in python 2.5
In windows XP, python 2.5 and 2.6 I tested the following code:
import urllib2
proxy= urllib2.ProxyHandler({'http': '127.0.0.1:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com/')
In the above code I get a BadStatus... | urllib2.proxyhandler in python 2.5 | In windows XP, python 2.5 and 2.6 I tested the following code:
import urllib2
proxy= urllib2.ProxyHandler({'http': '127.0.0.1:8080'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com/')
In the above code I get a BadStatusLine exception from line 349 of httplib.... | [
"The urllib2 ProxyHandler is not designed to support the SOCKS protocol. Perhaps this answer would help.\n",
"Assuming your local proxy is an HTTP proxy and not a socks proxy. Try this:\nimport urllib2\nproxy= urllib2.ProxyHandler({'http': 'http://127.0.0.1:8080/'})\nopener = urllib2.build_opener(proxy)\nurllib2.... | [
2,
0,
0
] | [] | [] | [
"httplib",
"python",
"urllib2"
] | stackoverflow_0003726152_httplib_python_urllib2.txt |
Q:
Search Crawling "Bot"?
I am working on a project that requires me to collect a large list of URLs to websites about certain topics. I would like to write a script that will use google to search specific terms, then save the URLs from the results to a file. How would I go about doing this? I have used a module call... | Search Crawling "Bot"? | I am working on a project that requires me to collect a large list of URLs to websites about certain topics. I would like to write a script that will use google to search specific terms, then save the URLs from the results to a file. How would I go about doing this? I have used a module called xgoogle, but it always re... | [
"google has an API library. I'd recommend you use that: http://code.google.com/apis/ajaxsearch/\nit's a restful API, which means its easy to grab results via python/js. You're limited to 32 results, I think, but that should be enough. it'll return a nice structured object that you'll be able to work with without ha... | [
1,
0
] | [] | [] | [
"hyperlink",
"python",
"search",
"windows"
] | stackoverflow_0003732595_hyperlink_python_search_windows.txt |
Q:
Prototype for python?
I just learned Prototype for Javascript. It's super convenient: using the $ shortcut, accessing xml elements is not painful any more!
The question: is there a Prototype-like extension for Python?
A:
Python has lxml which has the xpath method wherein you could use xpath expressions to selec... | Prototype for python? | I just learned Prototype for Javascript. It's super convenient: using the $ shortcut, accessing xml elements is not painful any more!
The question: is there a Prototype-like extension for Python?
| [
"Python has lxml which has the xpath method wherein you could use xpath expressions to select elements. As I understand it, $ in prototype searches and returns an element that has a particular id, in which case could be translated in xpath to *[@id=<someid>] like so:\n>>> import lxml.etree\n>>> tree = lxml.etree.XM... | [
1
] | [] | [] | [
"prototypejs",
"python"
] | stackoverflow_0003732740_prototypejs_python.txt |
Q:
What are the errors in this code?
Assume you have written a new function that checks to see if your game character has any life left. If the character does not have any life left, the function should print 'dead', if it has less than or equal to 5 life points left the function should print 'almost dead', otherwise... | What are the errors in this code? | Assume you have written a new function that checks to see if your game character has any life left. If the character does not have any life left, the function should print 'dead', if it has less than or equal to 5 life points left the function should print 'almost dead', otherwise it should print 'alive'.
am_i_alive(... | [
"def am_i_alive(): \n hit_points = 20\n if hit_points == 0: \n print 'dead'\n elif hit_points <= 5: \n print 'almost dead'\n else: \n print 'alive'\n\nam_i_alive()\n\n\nYou need the def keyword to define a function.\nYou need to use == and not = for comparisons.\nYou chain if statem... | [
8
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0003732899_error_handling_python.txt |
Q:
TCP server: how to avoid message overlapping
I am going to write a TCP server, the client sends me XML message, I am wondering if below condition will happen and how to avoid that:
1) client sends <cmd ...></cmd>
2) sever is busy doing something
3) clients sends <cmd ...></cmd>
4) server does a recv() and put the ... | TCP server: how to avoid message overlapping | I am going to write a TCP server, the client sends me XML message, I am wondering if below condition will happen and how to avoid that:
1) client sends <cmd ...></cmd>
2) sever is busy doing something
3) clients sends <cmd ...></cmd>
4) server does a recv() and put the string to buffer
Will the buffer be filled with <c... | [
"This is impossible to guarantee at the TCP level, since it only knows about streams.\nDepending on the XML parser you're using, you should be able to feed it the stream and have it tell you when it has a complete object, leaving the second <cmd... in its buffer until it is closed also.\n",
"You need a higher ord... | [
4,
3,
0
] | [] | [] | [
"networking",
"python",
"tcp"
] | stackoverflow_0003733363_networking_python_tcp.txt |
Q:
Python : how to prevent a class variable that is a function to be understood as a method?
I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...
So here is what I am trying :
class Blablabla(Model):
#this contains Blablabla's options
class Meta:
... | Python : how to prevent a class variable that is a function to be understood as a method? | I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...
So here is what I am trying :
class Blablabla(Model):
#this contains Blablabla's options
class Meta:
sort_key = lambda e: e
sort_key is a key function (for sorting purposes), but of course, it ... | [
"In general,\nclass Meta(object):\n sort_key= staticmethod(lambda e: e)\n\nI've no idea if whatever magic Django does to transplant ‘meta’ members copes OK with decorated methods like this, but I don't see any inherent reason why not.\n",
"Why are you trying to put sort_key into Meta? Meta is used for Django ... | [
2,
2,
0,
0
] | [] | [] | [
"django",
"function",
"metaclass",
"methods",
"python"
] | stackoverflow_0003731632_django_function_metaclass_methods_python.txt |
Q:
Django How to show user's name in his profile in admin console
I attached a UserProfile class to User this way:
class UserProfile(models.Model):
url = models.URLField()
home_address = models.TextField()
user = models.ForeignKey(User, unique=True)
I have also implemented auto-creating of UserProfile if... | Django How to show user's name in his profile in admin console | I attached a UserProfile class to User this way:
class UserProfile(models.Model):
url = models.URLField()
home_address = models.TextField()
user = models.ForeignKey(User, unique=True)
I have also implemented auto-creating of UserProfile if needed this way:
def user_post_save(sender, instance, signal, *args... | [
"Define a __unicode__ method for the UserProfile class:\ndef __unicode__(self):\n return u\"Profile for %s\" % self.user.get_full_name() \n\n"
] | [
4
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003733502_django_django_admin_python.txt |
Q:
Is this a good reason to check types in Python?
I know that checking types in Python is bad and you should probably never do it. But I can't seem to find the disadvantage to this.
class O(object):
def __init__(self, name):
'''Can only be called in derived classes.'''
if type(self) is ... | Is this a good reason to check types in Python? | I know that checking types in Python is bad and you should probably never do it. But I can't seem to find the disadvantage to this.
class O(object):
def __init__(self, name):
'''Can only be called in derived classes.'''
if type(self) is O:
message = "%(class)s cannot be instant... | [
"Look at Abstract Base Classes as they will provide more fine grained control over how the subclasses are instantiated if this is something that you really want to do.\nAll in all, this might be a valid use because you are not preventing me from passing whatever I want to your code but I still wouldn't consider it ... | [
5,
5,
1
] | [] | [] | [
"python",
"typechecking"
] | stackoverflow_0003733730_python_typechecking.txt |
Q:
Using DC to draw wx.BitMapButtons on the fly?
I'm currently able to get this to do most of what I want to. It draws buttons based on lines from a text file as well as handles the way different button states look. What's really tripping me up right now is when self.input writes to the text file I have no idea how t... | Using DC to draw wx.BitMapButtons on the fly? | I'm currently able to get this to do most of what I want to. It draws buttons based on lines from a text file as well as handles the way different button states look. What's really tripping me up right now is when self.input writes to the text file I have no idea how to get it to redraw everything to add or update butt... | [
"Theres no point in calling Update() Refresh() etc by themselves. They won't auto-magically create your buttons, you need to do that. \nFor starters I would refactor your __DoButtons() into two methods, one to create your buttons, and another to get your button data from your file and format it into an appropriate... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003732907_python_wxpython.txt |
Q:
How to install Trac Plugin and what is a python egg?
In Trac on Admin -> Plugins there is an option to install Plug-ins. Now this option expect you to upload an Python egg.
This would be all well but for the fact that all the Trac plug-ins I found are either plain .py files or zip files and are incompatible with t... | How to install Trac Plugin and what is a python egg? | In Trac on Admin -> Plugins there is an option to install Plug-ins. Now this option expect you to upload an Python egg.
This would be all well but for the fact that all the Trac plug-ins I found are either plain .py files or zip files and are incompatible with the upload function (I tried it).
This leaves my with a bun... | [
"Haven't used trac for a year, but what I remember is that most plugins are available trough subversion and already packed as an egg (which is kind of an installer in the python world, but I am not very familiar with the concept).\nMost plugins are available at http://trac-hacks.org/ and the easiest way to install ... | [
4,
3
] | [] | [] | [
"egg",
"python",
"trac"
] | stackoverflow_0003733970_egg_python_trac.txt |
Q:
Trouble using Selenium Grid/RC with Python
I have built a couple of test cases as stand alone python classes using Selenium. I can run each of them using Selenium RC. Ultimately I want to use Selenium Grid to run all of the test cases.
How would I do this?
Do I need some kind of wrapper to hold of of the python t... | Trouble using Selenium Grid/RC with Python | I have built a couple of test cases as stand alone python classes using Selenium. I can run each of them using Selenium RC. Ultimately I want to use Selenium Grid to run all of the test cases.
How would I do this?
Do I need some kind of wrapper to hold of of the python test cases together? How do I get Selenium Grid t... | [
"I would suggest having a look at running your tests in Parallel using Nose\nThere is documentation on how to get it running here\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_grid",
"selenium_rc"
] | stackoverflow_0003731299_python_selenium_selenium_grid_selenium_rc.txt |
Q:
Python RegEx Matching Newline
I have the following regular expression:
[0-9]{8}.*\n.*\n.*\n.*\n.*
Which I have tested in Expresso against the file I am working with and the match is sucessful.
I want to match the following:
Reference number 8 numbers long
Any character, any number of times
New Line
Any character... | Python RegEx Matching Newline | I have the following regular expression:
[0-9]{8}.*\n.*\n.*\n.*\n.*
Which I have tested in Expresso against the file I am working with and the match is sucessful.
I want to match the following:
Reference number 8 numbers long
Any character, any number of times
New Line
Any character, any number of times
New Line
Any ... | [
"Don't use re.DOTALL or the dot will match newlines, too. Also use raw strings (r\"...\") for regexes:\nfor m in re.findall(r'[0-9]{8}.*\\n.*\\n.*\\n.*\\n.*', l):\n print m\n\nHowever, your version still should have worked (although very inefficiently) if you have read the entire file as binary into memory as one... | [
12
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003734023_python_regex.txt |
Q:
Serializing IronPython Objects Which Inherit From CLR Types
This may be a bit of a weird question, but is there any reliable way to serialize IronPython objects whose classes extend CLR types?
For instance:
class Foo(System.Collections.Generic.List[str]):
def Test(self):
print "test!"
System.Collectio... | Serializing IronPython Objects Which Inherit From CLR Types | This may be a bit of a weird question, but is there any reliable way to serialize IronPython objects whose classes extend CLR types?
For instance:
class Foo(System.Collections.Generic.List[str]):
def Test(self):
print "test!"
System.Collections.Generic.List<string> is serializable with Pickle, as it implem... | [
"I don't know if it is what you are after, but you could consider the python version of protobuf (here)? I haven't tested it specifically on ironpython, mind. This has the added advantage that there are also C# implementations that may help, while keeping it platform independent. When possible I want to get protobu... | [
2,
1
] | [] | [] | [
"c#",
"ironpython",
"pickle",
"python",
"serialization"
] | stackoverflow_0003734063_c#_ironpython_pickle_python_serialization.txt |
Q:
What is the equivalent for heapq of Python in Java?
I would like to know if there is any api available for Java which is just like heapq in Python.
A:
Have you looked at java.util.PriorityQueue?
| What is the equivalent for heapq of Python in Java? | I would like to know if there is any api available for Java which is just like heapq in Python.
| [
"Have you looked at java.util.PriorityQueue?\n"
] | [
2
] | [] | [] | [
"heap",
"java",
"python"
] | stackoverflow_0003734463_heap_java_python.txt |
Q:
unable to compile python program using jython
I'm trying to compile a python program using jython and it's throwing below error
C:\jython2.2.1>jython test.py
Traceback (innermost last):
(no code object) at line 0
File "test.py", line 30
html = html if html else download(url, user_agent).rea... | unable to compile python program using jython | I'm trying to compile a python program using jython and it's throwing below error
C:\jython2.2.1>jython test.py
Traceback (innermost last):
(no code object) at line 0
File "test.py", line 30
html = html if html else download(url, user_agent).read()
^
SyntaxError: ... | [
"Jython 2.2.1 is (AFAIK) equivalent to Cpython 2.2.1 as far as syntax is concerned. The line that causes the problem uses the ternary operator which was introduced later. the solution is to replace it with an if statement.\nif not html:\n html = download(url, user_agent).read() \n\nThat should take care of that... | [
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0003734496_jython_python.txt |
Q:
When to use * and ** as a function argument in python function
When can I pass * and ** in the argument of a Python function? i.e.:
def fun_name(arg1, *arg2 , ** arg3):
A:
As you've stated your question, you aren't using them in the arguments (which occur when you are calling a function), you are using them in t... | When to use * and ** as a function argument in python function | When can I pass * and ** in the argument of a Python function? i.e.:
def fun_name(arg1, *arg2 , ** arg3):
| [
"As you've stated your question, you aren't using them in the arguments (which occur when you are calling a function), you are using them in the parameters which occur when you are creating a function. The * and ** operators serve different purposes in each of those situations.\nWhen you are defining a function, th... | [
11,
2,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003734720_python_syntax.txt |
Q:
How to deploy a Python/SQLAlchemy application?
SQLAlchemy allowed me to create a powerful database utility. Now I don't know how to deploy it. Let me explain how is it built with an example:
# objects.py
class Item(object):
def __init__(self, name):
self.name = name
# schema.py
from sqlalchemy import *
from ob... | How to deploy a Python/SQLAlchemy application? | SQLAlchemy allowed me to create a powerful database utility. Now I don't know how to deploy it. Let me explain how is it built with an example:
# objects.py
class Item(object):
def __init__(self, name):
self.name = name
# schema.py
from sqlalchemy import *
from objects import Item
engine=create_engine('sqlite:///my... | [
"Connection pooling happens within the same python instance, so when your users connect from remote to the database, you have to write a small server anyways, if you want to use it. You can also connect directly to a database server, resulting in (at least) one connection per user. Depends on what you want to achie... | [
0
] | [] | [] | [
"deployment",
"python",
"sqlalchemy"
] | stackoverflow_0003525783_deployment_python_sqlalchemy.txt |
Q:
Help with Python urllib2 and openers - How to make only 1 remote file read
I am trying to download content from a content provider that charges me every time I access a document. The code I have written correctly downloads the content and saves them in a local file but apparently it requests the file twice and I ... | Help with Python urllib2 and openers - How to make only 1 remote file read | I am trying to download content from a content provider that charges me every time I access a document. The code I have written correctly downloads the content and saves them in a local file but apparently it requests the file twice and I am being double charged. I'm not sure where the file is being requested twice, ... | [
"Could it be that it requests the file twice, but only downloads it once? The first request would be a normal GET (without an \"Authorization\" header), followed by a response of HTTP 401 (Authorization Required), followed by the same request with the Authorization header. \nIf thats the case, you shold talk to you... | [
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003722017_python_urllib2.txt |
Q:
How to Format dict string outputs nicely
I wonder if there is an easy way to format Strings of dict-outputs such as this:
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
..., where a simple str(dict) just would give you a ... | How to Format dict string outputs nicely | I wonder if there is an easy way to format Strings of dict-outputs such as this:
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
..., where a simple str(dict) just would give you a quite unreadable ...
{'planet' : {'has': {'pla... | [
"Depending on what you're doing with the output, one option is to use JSON for the display.\nimport json\nx = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}\n\nprint json.dumps(x, indent=2)\n\nOutput:\n{\n \"planet\": {\n \"has\": {\n \"plants\": \"yes\", \n ... | [
116,
42,
7
] | [] | [] | [
"formatting",
"python",
"string"
] | stackoverflow_0003733554_formatting_python_string.txt |
Q:
Convert the input from telnet to a list in twisted
input from telnet
GET /learn/tutorials/351079-weekend-project-secure-your-system-with-port-knocking?name=MyName&married=not+single♂=yes HTTP/1.1
Host: merch1.localhost
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: t... | Convert the input from telnet to a list in twisted | input from telnet
GET /learn/tutorials/351079-weekend-project-secure-your-system-with-port-knocking?name=MyName&married=not+single♂=yes HTTP/1.1
Host: merch1.localhost
User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11
Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=... | [
"Assuming you're getting those lines of text from a text file-like object f (maybe sys.stdin, whatever), list(f) or f.readlines() are almost what you want except that there are line-end markers at the end of each line. f.read().split('\\n') may be closer to what you want (the same split call works if you have the ... | [
1,
0
] | [] | [] | [
"http",
"python",
"twisted"
] | stackoverflow_0003732345_http_python_twisted.txt |
Q:
Django - alert when memcached is down
Is there some ready-made addon that alerts admins about memcached instance being inaccessible from a Django application? I don't mean here monitoring memcached daemon itself, but something that checks if my Django app benefits from caching.
My basic idea is to check if cache.g... | Django - alert when memcached is down | Is there some ready-made addon that alerts admins about memcached instance being inaccessible from a Django application? I don't mean here monitoring memcached daemon itself, but something that checks if my Django app benefits from caching.
My basic idea is to check if cache.get that follow cache.set actually returns s... | [
"You should monitor your infrastructure. You can use a huge variety of tools for this, look on server fault for more discussions on monitoring.\nYou should probably monitor your cache hit rate and trend it in your monitoring system; if it falls below a figure (say 90%) then you can alert that the cache has stopped ... | [
5,
2
] | [] | [] | [
"django",
"memcached",
"python",
"python_memcached"
] | stackoverflow_0003735183_django_memcached_python_python_memcached.txt |
Q:
Determine whether a key is present in a dictionary
Possible Duplicate:
'has_key()' or 'in'?
I have a Python dictionary like :
mydict = {'name':'abc','city':'xyz','country','def'}
I want to check if a key is in dictionary or not.
I am eager to know that which is more preferable from the following two cases and w... | Determine whether a key is present in a dictionary |
Possible Duplicate:
'has_key()' or 'in'?
I have a Python dictionary like :
mydict = {'name':'abc','city':'xyz','country','def'}
I want to check if a key is in dictionary or not.
I am eager to know that which is more preferable from the following two cases and why?
1> if mydict.has_key('name'):
2> if 'name' in mydic... | [
"if 'name' in mydict:\n\nis the preferred, pythonic version. Use of has_key() is discouraged, and this method has been removed in Python 3.\n",
"In the same vein as martineau's response, the best solution is often not to check. For example, the code\nif x in d:\n foo = d[x]\nelse:\n foo = bar\n\nis normally... | [
78,
38,
13,
10
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003733992_dictionary_python.txt |
Q:
Python unicode problems on Windows XP
Having the following django view code that generates a CSV response from a database view:
def _get_csv_stats(request, **filterargs):
result = GlobalStats.objects.select_related().filter(**filterargs).values_list('user__username',
... | Python unicode problems on Windows XP | Having the following django view code that generates a CSV response from a database view:
def _get_csv_stats(request, **filterargs):
result = GlobalStats.objects.select_related().filter(**filterargs).values_list('user__username',
'user... | [
"Whether the text is displayed properly depends on whether the font that is is being drawn in supports all Unicode characters. This is not a problem with your django.\n",
"First: I don't know django, so maybe this is far off.\nCheck whether your writer actually outputs UTF-8, if you write an UTF-8 BOM into the fi... | [
0,
0
] | [] | [] | [
"django",
"python",
"unicode",
"windows"
] | stackoverflow_0003187295_django_python_unicode_windows.txt |
Q:
Python lxml and stdin
I have a xml file, book.xml (http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx)
I would like to cat books.xml and get all book ids and genres for the book id.
Similar to
cat books.xml | python reader.py
Any tips or help would be appreciated. Thanks.
A:
To read an XML file from... | Python lxml and stdin | I have a xml file, book.xml (http://msdn.microsoft.com/en-us/library/ms762271(VS.85).aspx)
I would like to cat books.xml and get all book ids and genres for the book id.
Similar to
cat books.xml | python reader.py
Any tips or help would be appreciated. Thanks.
| [
"To read an XML file from stdin, just use etree.parse. This function accepts a file object, which can be sys.stdin.\nimport sys\nfrom lxml import etree\n\ntree = etree.parse(sys.stdin)\n\nprint ( [(b.get('id'), b.findtext('genre')) for b in tree.iterfind('book')] )\n\n"
] | [
12
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0003735364_lxml_python_xml.txt |
Q:
How to display a PostScript file in a Python GUI application
I would like to build a cross-platform GUI application in Python that displays PostScript files I generate, among some other stuff. What is the best way to accomplish this? Ideally I would be able to do things like zoom and pan the displayed graphic.
Do... | How to display a PostScript file in a Python GUI application | I would like to build a cross-platform GUI application in Python that displays PostScript files I generate, among some other stuff. What is the best way to accomplish this? Ideally I would be able to do things like zoom and pan the displayed graphic.
Do any/some/all of the GUI toolkits have something I can drop in to ... | [
"I asked pretty much the same question a little time ago. Here it is. Hope it helps.\nNote: Poppler is highly undocumented. If you use Gtk for your GUI there are a few working examples. In Qt things are a little harder, and I haven't figured out a way myself yet.\n",
"In a word Ghostscript. It's been a while sinc... | [
1,
1
] | [] | [] | [
"postscript",
"python",
"user_interface"
] | stackoverflow_0002534474_postscript_python_user_interface.txt |
Q:
mixing super and classic calls in Python
firstly, let me quote a bit an essay from "Expert Python Programming" book:
In the following example, a C class that calls its base classes using the __init__ method will
make B class be called twice!
class A(object):
def __init__(self):
print "A"
su... | mixing super and classic calls in Python | firstly, let me quote a bit an essay from "Expert Python Programming" book:
In the following example, a C class that calls its base classes using the __init__ method will
make B class be called twice!
class A(object):
def __init__(self):
print "A"
super(A, self).__init__()
class B(object):
... | [
"To understand this behaviour, you have to understand that super calls not the base class, but searches the next matching method along the order in the __mro__. So, the call super(A, self).__init__() looks at the __mro__ == ['C', 'A', 'B', 'object'], sees B as the next class with a matching method and calls the met... | [
10,
4
] | [] | [] | [
"python"
] | stackoverflow_0003735569_python.txt |
Q:
Split with single colon but not double colon using regex
I have a string like this
"yJdz:jkj8h:jkhd::hjkjh"
I want to split it using colon as a separator, but not a double colon. Desired result:
("yJdz", "jkj8h", "jkhd::hjkjh")
I'm trying with:
re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")
but I got a wrong result... | Split with single colon but not double colon using regex | I have a string like this
"yJdz:jkj8h:jkhd::hjkjh"
I want to split it using colon as a separator, but not a double colon. Desired result:
("yJdz", "jkj8h", "jkhd::hjkjh")
I'm trying with:
re.split(":{1}", "yJdz:jkj8h:jkhd::hjkjh")
but I got a wrong result.
In the meanwhile I'm escaping "::", with string.replace("::"... | [
"You could split on (?<!:):(?!:). This uses two negative lookarounds (a lookbehind and a lookahead) which assert that a valid match only has one colon, without a colon before or after it.\nTo explain the pattern:\n(?<!:) # assert that the previous character is not a colon\n: # match a literal : character\n(?... | [
31,
13
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0003735841_python_regex_split.txt |
Q:
SQL in Python 3.0?
How to use any SQL database eg. mysql, pgsql or other except the ones Python has built-in support for?
def example():
con= Mysql("root", blablabla)
con->query("SELECT * bla bla bla")
....
A:
What DB and what extension are you using? For sqlite3 (and any other extension compatible with DB-A... | SQL in Python 3.0? | How to use any SQL database eg. mysql, pgsql or other except the ones Python has built-in support for?
def example():
con= Mysql("root", blablabla)
con->query("SELECT * bla bla bla")
....
| [
"What DB and what extension are you using? For sqlite3 (and any other extension compatible with DB-API 2.0) you can use something like this:\nconn = sqlite3.connect('/tmp/example')\nc = conn.cursor()\n\n# Create table\nc.execute('''create table stocks(date text, trans text, symbol text, qty real, price real)''')\n\... | [
3,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0003735948_python_sql.txt |
Q:
How do I test a WSGI application from a script?
I'm debugging a really weird problem with a mod_wsgi-deployed application resulting in Django/Apache (not yet known which) giving status 500 errors to some users instead of the correct 404. I want to exclude Apache from the debugging environment to determine which pa... | How do I test a WSGI application from a script? | I'm debugging a really weird problem with a mod_wsgi-deployed application resulting in Django/Apache (not yet known which) giving status 500 errors to some users instead of the correct 404. I want to exclude Apache from the debugging environment to determine which part of the setup is at fault and send my requests manu... | [
"\nit's as easy as setting the environment and running python wsgi_handler.py, \n\nCorrect.\n\nWhat should the enviroment contain additionally? Any pointers to existing documentation?\n\nDid you read this? http://docs.python.org/library/wsgiref.html\nYou can easily run a web server from your desktop for testing. I... | [
4
] | [] | [] | [
"django",
"python",
"testing",
"wsgi"
] | stackoverflow_0003735637_django_python_testing_wsgi.txt |
Q:
How can I remove the axes in an Axes3D class?
I am using mplot3d like this:
fig = plt.figure(figsize=(14,10))
ax = Axes3D(fig,azim=azimuth,elev=elevation)
ax.grid(on=False)
# Additional axes
xspan = np.linspace(0,80+20)
yspan = np.linspace(0,60+20)
zspan = np.linspace(0,60+20)
ax.plot3D(xspan,np.zeros(xspan.s... | How can I remove the axes in an Axes3D class? | I am using mplot3d like this:
fig = plt.figure(figsize=(14,10))
ax = Axes3D(fig,azim=azimuth,elev=elevation)
ax.grid(on=False)
# Additional axes
xspan = np.linspace(0,80+20)
yspan = np.linspace(0,60+20)
zspan = np.linspace(0,60+20)
ax.plot3D(xspan,np.zeros(xspan.shape[0]),np.zeros(xspan.shape[0]),'k--')
ax.plot3D(... | [
"If I understand your question correctly, all you need to do is call ax.axis(\"off\") or equivalently, ax.set_axis_off().\nJust to make sure we're on the same page, your example code might produce something like this (if it could be executed as you posted it...):\n\nWhile you want something like this:\n\nHere's the... | [
10
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003732787_matplotlib_python.txt |
Q:
Need regular expression expert: round bracket within stringliteral
I'm searching for strings within strings using Regex. The pattern is a string literal that ends in (, e.g.
# pattern
" before the bracket ("
# string
this text is before the bracket (and this text is inside) and this text is after the bracket
I k... | Need regular expression expert: round bracket within stringliteral | I'm searching for strings within strings using Regex. The pattern is a string literal that ends in (, e.g.
# pattern
" before the bracket ("
# string
this text is before the bracket (and this text is inside) and this text is after the bracket
I know the pattern will work if I escape the character with a backslash, i.... | [
"You didn't specify the language, but it looks like Python, so if you have a string in Python whose special regex characters you need to escape, use re.escape():\n>>> import re\n>>> re.escape(\"Wow. This (really) is *cool*\")\n'Wow\\\\.\\\\ This\\\\ \\\\(really\\\\)\\\\ is\\\\ \\\\*cool\\\\*'\n\nNote that spaces ar... | [
2,
1,
0
] | [
"The following regex will capture everything from the beginning of the string to the first (. The first captured group $1 will contain the portion before (.\n^([^(]+)\\(\n\nDepending on your language, you might have to escape it as:\n\"^([^(]+)\\\\(\"\n\n"
] | [
-1
] | [
"python",
"regex",
"vba"
] | stackoverflow_0003723038_python_regex_vba.txt |
Q:
Add advanced features to a tkinter Text widget
I am working on a simple messaging system, and need to add the following to a Tkinter text widget:
Spell Check
Option To Change Font ( on selected text )
Option to change font color ( on selected text )
Option to Change Font Size ( on selected text )
I understand t... | Add advanced features to a tkinter Text widget | I am working on a simple messaging system, and need to add the following to a Tkinter text widget:
Spell Check
Option To Change Font ( on selected text )
Option to change font color ( on selected text )
Option to Change Font Size ( on selected text )
I understand that the tkinter Text widget has the ability to use m... | [
"The Tkinter text widget is remarkably powerful, but you do have to do some advanced features yourself. It doesn't have built-in spell check or built-in buttons for bolding text, etc, but they are quite easy to implement. All the capabilities are there in the widget, you just need to know how to do it.\nThe followi... | [
37,
5
] | [] | [] | [
"message",
"python",
"text",
"tkinter",
"windows"
] | stackoverflow_0003732605_message_python_text_tkinter_windows.txt |
Q:
How do I read an image file using Python?
How do I read an image file and decode it using Python?
A:
The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.
from PIL import Image
jpgfile = Image.open("picture.jpg")
print(jpgfile.bits, jpg... | How do I read an image file using Python? | How do I read an image file and decode it using Python?
| [
"The word \"read\" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it. \nfrom PIL import Image\njpgfile = Image.open(\"picture.jpg\")\n\nprint(jpgfile.bits, jpgfile.size, jpgfile.format)\n\n"
] | [
53
] | [] | [] | [
"file",
"image",
"python"
] | stackoverflow_0003735553_file_image_python.txt |
Q:
Distinguishable characters?
I have a bunch of items in my database. Each is assigned a unique ID. I want to shorten this ID and display it on the page, so that if I user needs to contact us (over the phone) regarding a particular item, he can give us the shortened ID, rather than a really big number. Similar to th... | Distinguishable characters? | I have a bunch of items in my database. Each is assigned a unique ID. I want to shorten this ID and display it on the page, so that if I user needs to contact us (over the phone) regarding a particular item, he can give us the shortened ID, rather than a really big number. Similar to the SKU, on sites like NCIX. Thus, ... | [
"Yes, you should eliminate sources of confusion. Because if a mistake can be made, someone will make it. Very easy to confuse 0 with O and I with l or 1 - hence should not use them both. Well that's easy - since you won't use 3 chars (i, L and o), just get the number in base 36-3 = 33 and convert\nSKU.replace('I','... | [
6,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003082812_python.txt |
Q:
Handle user-raised deprecation warning by pylint
Is there a way to tell pylint that it must show warning message when it see user-defined deprecation warning?
I've tried warnings.warn, DeprecationWarning - but pylint ignores them.
A:
Since warnings.warn &c are intended to happen at runtime, Pylint by default do... | Handle user-raised deprecation warning by pylint | Is there a way to tell pylint that it must show warning message when it see user-defined deprecation warning?
I've tried warnings.warn, DeprecationWarning - but pylint ignores them.
| [
"Since warnings.warn &c are intended to happen at runtime, Pylint by default doesn't see them as anything strange. To change that I think you need to follow the (advanced and scarce) docs for writing your own checker, with which you can emit warnings on any characteristics of the sources (either the raw ones or th... | [
2
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0003736203_pylint_python.txt |
Q:
How to determine if CherryPy is caching responses?
Is it possible that CherryPy, in its default configuration, is caching the responses to one or more of my request handlers? And, if so, how do I turn that off?
A:
Per the docs, there is indeed a cache (for GET), and you can disable it by having in your configur... | How to determine if CherryPy is caching responses? | Is it possible that CherryPy, in its default configuration, is caching the responses to one or more of my request handlers? And, if so, how do I turn that off?
| [
"Per the docs, there is indeed a cache (for GET), and you can disable it by having in your configuration\ntools.caching.on = False\n\n",
"CherryPy has a caching Tool, but it's never on by default. Most HTTP responses are cacheable by default, though, so look for an intermediate cache between your client and serve... | [
6,
4
] | [] | [] | [
"cherrypy",
"http",
"python"
] | stackoverflow_0003736606_cherrypy_http_python.txt |
Q:
Access an injected object's containing object?
Given an object A, which contains a callable object B, is there a way to determine "A" from inside B.__call__()?
This is for use in test injection, where A.B is originally a method.
The code is something like this:
# Class to be tested.
class Outer(object):
def __in... | Access an injected object's containing object? | Given an object A, which contains a callable object B, is there a way to determine "A" from inside B.__call__()?
This is for use in test injection, where A.B is originally a method.
The code is something like this:
# Class to be tested.
class Outer(object):
def __init__(self, arg):
self.arg = arg
def func(self,... | [
"\nGiven an object A, which contains a\n callable object B, is there a way to\n determine \"A\" from inside\n B.call()?\n\nNot in the general case, i.e., with the unbounded generality you require in this text -- unless B keeps a reference to A in some way, Python most surely doesn't keep it on B's behalf.\nFor y... | [
2,
0
] | [] | [] | [
"code_injection",
"python"
] | stackoverflow_0003736612_code_injection_python.txt |
Q:
Where is the raise object in Python?
When you want to print a bunch of variables in Python, you have quite a few options, such as:
for i in range(len(iterable)):
print iterable[i].name
OR
map(lambda i: sys.stdout.write(i.name), iterable)
The reason I use sys.stdout.write instead of print in the second exampl... | Where is the raise object in Python? | When you want to print a bunch of variables in Python, you have quite a few options, such as:
for i in range(len(iterable)):
print iterable[i].name
OR
map(lambda i: sys.stdout.write(i.name), iterable)
The reason I use sys.stdout.write instead of print in the second example is that lambdas won't accept print, but ... | [
"There is no Python \"object\" (built-in or in the standard library) for raise, you have to build one yourself (typical short snippet that goes in one's util.py...!):\ndef do_raise(exc): raise exc\n\ntypically to be called as do_raise(InvalidObjectError(o.name)).\n",
"I don't think it's possible to use raise in a... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"raise"
] | stackoverflow_0003732358_python_raise.txt |
Q:
How to pause python execution in eclipse and return to an interactive prompt
I am using Eclipse as a Python IDE. Is there anyway for me to Debug my program and break to an interactive prompt. I am interested in exploring the existing data and running/testing commands.
I believe there has to be a way, but I am so ... | How to pause python execution in eclipse and return to an interactive prompt | I am using Eclipse as a Python IDE. Is there anyway for me to Debug my program and break to an interactive prompt. I am interested in exploring the existing data and running/testing commands.
I believe there has to be a way, but I am so used to compiling languages that I have not been able to find where the options ar... | [
"You can easily do that by using PDB (Python Debugger) inside a python shell.\nLook at http://docs.python.org/library/pdb.html for more info.\nAnyway I believe Eclipse will let you inspect you data when setting a breakpoint.\n"
] | [
2
] | [] | [] | [
"database",
"eclipse",
"interactive",
"ipython",
"python"
] | stackoverflow_0003737565_database_eclipse_interactive_ipython_python.txt |
Q:
Memory consumption in Cherrypy
I am using Cherrypy in a RESTful web service and server returns XML as a result (lxml is being used to create XML). Some of those XMLs are quite large. I have noticed that memory is not being released after such request (that return large XML) has been processed.
So, I have isolated... | Memory consumption in Cherrypy | I am using Cherrypy in a RESTful web service and server returns XML as a result (lxml is being used to create XML). Some of those XMLs are quite large. I have noticed that memory is not being released after such request (that return large XML) has been processed.
So, I have isolated a problem and created this one very... | [
"This is a generic Python problem, not really a CherryPy one per se. effbot has a great answer to this question at http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm\nAnd there's a similar SO question with a great answer at How can I explicitly free memory in Python?\n"
] | [
1
] | [] | [] | [
"cherrypy",
"consumption",
"lxml",
"memory",
"python"
] | stackoverflow_0003737268_cherrypy_consumption_lxml_memory_python.txt |
Q:
python threads - how do "condition.wait" and "condition.notifyAll" work
I have the following "consumer" code:
....
while 1:
time.sleep(self.sleeptime)
cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
while itemq.isEmpty():
cond.wait()
... | python threads - how do "condition.wait" and "condition.notifyAll" work | I have the following "consumer" code:
....
while 1:
time.sleep(self.sleeptime)
cond.acquire() #acquire the lock
print currentThread(), "lock acquired"
while itemq.isEmpty():
cond.wait()
itemq.consume()
print currentThread(),"Consumed One Item"
... | [
"I think the docs are very clear:\n\nThe wait() method releases the lock,\n and then blocks until it is awakened\n by a notify() or notifyAll() call for\n the same condition variable in another\n thread. Once awakened, it re-acquires\n the lock and returns. It is also\n possible to specify a timeout.\n\nand:\... | [
4,
1
] | [] | [] | [
"conditional_statements",
"multithreading",
"python",
"wait"
] | stackoverflow_0003737755_conditional_statements_multithreading_python_wait.txt |
Q:
How do you convert a stringed dictionary to a Python dictionary?
I have the following string which is a Python dictionary stringified:
some_string = '{123: False, 456: True, 789: False}'
How do I get the Python dictionary out of the above string?
A:
Use ast.literal_eval:
Safely evaluate an expression node or a... | How do you convert a stringed dictionary to a Python dictionary? | I have the following string which is a Python dictionary stringified:
some_string = '{123: False, 456: True, 789: False}'
How do I get the Python dictionary out of the above string?
| [
"Use ast.literal_eval:\n\nSafely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.\nThis can be used for safely evaluating strings containing Pyt... | [
12,
10,
3
] | [] | [] | [
"python"
] | stackoverflow_0003737900_python.txt |
Q:
How to quit the running python program to python prompt?
I wrote a implementation of conway's game of life. I set up two modes, one is auto and the other is manual, which I mean the way to ouput the result of the game. For the auto mode, I cannot stop the running progran without ctrl + q or ctrl + c (which prints ... | How to quit the running python program to python prompt? | I wrote a implementation of conway's game of life. I set up two modes, one is auto and the other is manual, which I mean the way to ouput the result of the game. For the auto mode, I cannot stop the running progran without ctrl + q or ctrl + c (which prints out the error message). So is there any way which can allow me... | [
"You can't use arbitrary keypresses, but to handle the normal interrupt (e.g. control-C) without errors all you need is to catch the KeyboardInterrupt exception it causes, i.e., just wrap all of your looping code with\ntry:\n functionthatloopsalot()\nexcept KeyboardInterrupt:\n \"\"\"user wants control back\"... | [
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003737922_python.txt |
Q:
What are the possible pitfalls in porting Psyco to 64-bit?
The Psyco docs say:
Just for reference, Psyco does not
work on any 64-bit systems at all.
This fact is worth being noted again,
now that the latest Mac OS/X 10.6
"Snow Leopart" comes with a default
Python that is 64-bit on 64-bit
machines. The... | What are the possible pitfalls in porting Psyco to 64-bit? | The Psyco docs say:
Just for reference, Psyco does not
work on any 64-bit systems at all.
This fact is worth being noted again,
now that the latest Mac OS/X 10.6
"Snow Leopart" comes with a default
Python that is 64-bit on 64-bit
machines. The only way to use Psyco on
OS/X 10.6 is by recompiling a custom... | [
"Christian Tismer, one of the Psyco developers also seems to disagree with the \"how hard could it be\" - assumption (quoted from here):\n\nNeeds to come to x86-64? Why that!\n Seriously, I would love to do that,\n but this would be much harder than\n anybody would expect. Due to the way\n psyco is written, it ... | [
4,
3,
3,
1
] | [] | [] | [
"64_bit",
"c",
"porting",
"psyco",
"python"
] | stackoverflow_0002374233_64_bit_c_porting_psyco_python.txt |
Q:
How to write find-all function (with regex) in awk or sed
I have bash function which run python (which return all finded regex from stdin)
function find-all() {
python -c "import re
import sys
print '\n'.join(re.findall('$1', sys.stdin.read()))"
}
When I use this regex find-all 'href="([^"]*)"' < index.html i... | How to write find-all function (with regex) in awk or sed | I have bash function which run python (which return all finded regex from stdin)
function find-all() {
python -c "import re
import sys
print '\n'.join(re.findall('$1', sys.stdin.read()))"
}
When I use this regex find-all 'href="([^"]*)"' < index.html it should return first group from the regex (value of href attri... | [
"I suggest you use grep -o.\n-o, --only-matching\n Show only the part of a matching line that matches PATTERN.\n\nE.g.:\n$ cat > foo\ntest test test\ntest\nbar\nbaz test\n$ grep -o test foo\ntest\ntest\ntest\ntest\ntest\n\n\nUpdate\nIf you were extracting href attributes from html files, using a command like:... | [
3,
2
] | [] | [] | [
"awk",
"bash",
"python",
"sed"
] | stackoverflow_0003707625_awk_bash_python_sed.txt |
Q:
Draw text image without crop need by PIL
I would like to draw a text by using PIL. But my problem is I need to crop the text image again after run the program. The thing i need is only text, no border. Any one can suggest?
Thank you.
This is my code:
import Image, ImageDraw, ImageFont
def draw (text, size, color... | Draw text image without crop need by PIL | I would like to draw a text by using PIL. But my problem is I need to crop the text image again after run the program. The thing i need is only text, no border. Any one can suggest?
Thank you.
This is my code:
import Image, ImageDraw, ImageFont
def draw (text, size, color) :
fontPath = '/home/FreeSansBold.ttf'
... | [
"Could you clarify what you mean by no border? Are you wanting text tight against edge of the image? If so this should work:\n\nimport Image, ImageDraw, ImageFont\n\ndef draw (text, size, color) :\n fontPath = '/home/FreeSansBold.ttf'\n font = ImageFont.truetype(fontPath, size)\n size2 = font.getsize(tex... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003706142_python.txt |
Q:
Python namespace in between builtins and global?
As I understand it python has the following outermost namespaces:
Builtin - This namespace is global across the entire interpreter and all scripts running within an interpreter instance.
Globals - This namespace is global across a module, ie across a single file.
... | Python namespace in between builtins and global? | As I understand it python has the following outermost namespaces:
Builtin - This namespace is global across the entire interpreter and all scripts running within an interpreter instance.
Globals - This namespace is global across a module, ie across a single file.
I am looking for a namespace in between these two, whe... | [
"There is no namespace \"between\" builtins and globals -- but you can easily create your own namespaces and insert them with a name in sys.modules, so any other module can \"import\" them (ideally not using the from ... import syntax, which carries a load of problems, and definitely not using tghe import ... from ... | [
4,
0,
0
] | [] | [] | [
"global_variables",
"module",
"namespaces",
"python"
] | stackoverflow_0003010657_global_variables_module_namespaces_python.txt |
Q:
How to insert arrays into a database?
In my previous question a lot of users wanted me to give some more data to toy with. So I got working on exporting all my data and processing it with Python, but then I realized: where do I leave all this data?
Well I decided the best thing would be to stick them in a databas... | How to insert arrays into a database? | In my previous question a lot of users wanted me to give some more data to toy with. So I got working on exporting all my data and processing it with Python, but then I realized: where do I leave all this data?
Well I decided the best thing would be to stick them in a database, so at least I don't have to parse the ra... | [
"You'll probably want to start out with a dogs table containing all the flat (non array) data for each dog, things which each dog has one of, like a name, a sex, and an age:\nCREATE TABLE `dogs` (\n `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n `name` VARCHAR(64),\n `age` INT UNSIGNED,\n `sex` ENUM('... | [
9,
7,
2,
2,
1,
0
] | [] | [] | [
"database_design",
"numpy",
"python"
] | stackoverflow_0003738269_database_design_numpy_python.txt |
Q:
Generating parser in Python language from JavaCC source?
I do mean the ??? in the title because I'm not exactly sure. Let me explain the situation.
I'm not a computer science student & I never did any compilers course. Till now I used to think that compiler writers or students who did compilers course are outstand... | Generating parser in Python language from JavaCC source? | I do mean the ??? in the title because I'm not exactly sure. Let me explain the situation.
I'm not a computer science student & I never did any compilers course. Till now I used to think that compiler writers or students who did compilers course are outstanding because they had to write Parser component of the compiler... | [
"Why do you call this \"XML-style\" markup? - this looks like pretty standard/basic XML to me.\nTry elementTree or lxml. Instead of writing a parser, use one of the stable, well-hardened libraries that are already out there.\n",
"You can't build a parser - let alone a whole compiler - from a(n E)BNF grammar - it'... | [
2,
1
] | [] | [] | [
"javacc",
"parsing",
"python"
] | stackoverflow_0003738239_javacc_parsing_python.txt |
Q:
Django, unable to import validators in form class, getting "name 'validatorname' is not defined"
I am trying to use validators in my form fields but am getting an error:
from django import forms
from django.db import models
from django.core.exceptions import ValidationError
class Register(forms.Form):
usernam... | Django, unable to import validators in form class, getting "name 'validatorname' is not defined" | I am trying to use validators in my form fields but am getting an error:
from django import forms
from django.db import models
from django.core.exceptions import ValidationError
class Register(forms.Form):
username = forms.CharField(max_length=100,label="Username",validators=[validate_email])
>>>> name 'validate... | [
"You seem to be missing an import. Try adding\nfrom django.core.validators import validate_email\n\nto your imports\n"
] | [
5
] | [] | [] | [
"django",
"forms",
"python",
"validation"
] | stackoverflow_0003739411_django_forms_python_validation.txt |
Q:
Django trying to set up a project and find out which Django I have
I'm on a Mac OS X Snow Leopard with Python 2.6.5, I'm trying to get django working but I keep getting this error. Do I need to add it to the path? I'm not sure where django is installed is there any way that I can find it?
solidariti:~/home/solidar... | Django trying to set up a project and find out which Django I have | I'm on a Mac OS X Snow Leopard with Python 2.6.5, I'm trying to get django working but I keep getting this error. Do I need to add it to the path? I'm not sure where django is installed is there any way that I can find it?
solidariti:~/home/solidariti
→ python
Python 2.6.5 (r265:79063, Aug 8 2010, 21:45:26)
[GCC 4.... | [
"This shows that there's definitely no Django in your Python include path.\nYou can try searching for the directory using regular file searching tools.\n",
"Yeah, you need to add Django to your python path. I'm not sure where you have Django installed, but for what it's worth, I set things up so I don't have to r... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003739266_django_python.txt |
Q:
How to fix a circular dependency for imports
I have three files:
testimports module:
#import moduleTwo
import moduleOne
hiString = "Hi!"
moduleOne.sayHi()
moduleOne:
import moduleTwo
class sayHi():
moduleTwo.printHi()
moduleTwo:
import testimports
def printHi():
print(testimports.hiString)
If I run ... | How to fix a circular dependency for imports | I have three files:
testimports module:
#import moduleTwo
import moduleOne
hiString = "Hi!"
moduleOne.sayHi()
moduleOne:
import moduleTwo
class sayHi():
moduleTwo.printHi()
moduleTwo:
import testimports
def printHi():
print(testimports.hiString)
If I run testimports, I get:
Traceback (most recent call la... | [
"verisimilidude is along the right direction. I would expand a little to give more details.\nIn both cases, this is what happens:\n\ntestimports is executed as __main__\ntestimports imports moduleOne. Now moduleOne is read from file and added to the list of imported modules sys.modules.\nThe execution of importing ... | [
9,
2,
2
] | [] | [] | [
"circular_dependency",
"import",
"python",
"python_3.x"
] | stackoverflow_0003739654_circular_dependency_import_python_python_3.x.txt |
Q:
is there a compatible TCL environment variable for cygwin and python idle
Idle stopped working after installing cygwin and after some troubleshooting (on windows if its not obvious), it looks like the issue is with a TCL library. They both use an environment variable to locate tcl. when I installed cygwin, it over... | is there a compatible TCL environment variable for cygwin and python idle | Idle stopped working after installing cygwin and after some troubleshooting (on windows if its not obvious), it looks like the issue is with a TCL library. They both use an environment variable to locate tcl. when I installed cygwin, it overwrote the variable to a different (and incompatible to python) version. Now I f... | [
"If you could change the variable, you know already which it is, and to which value it is set. Would you kindly share this information, maybe someone can make an educated guess?\n"
] | [
0
] | [] | [] | [
"cygwin",
"python",
"tcl"
] | stackoverflow_0003739837_cygwin_python_tcl.txt |
Q:
Converting a hex-string representation to actual bytes in Python
i need to load the third column of this text file as a hex string
http://www.netmite.com/android/mydroid/1.6/external/skia/emoji/gmojiraw.txt
>>> open('gmojiraw.txt').read().split('\n')[0].split('\t')[2]
'\\xF3\\xBE\\x80\\x80'
how do i open the file... | Converting a hex-string representation to actual bytes in Python | i need to load the third column of this text file as a hex string
http://www.netmite.com/android/mydroid/1.6/external/skia/emoji/gmojiraw.txt
>>> open('gmojiraw.txt').read().split('\n')[0].split('\t')[2]
'\\xF3\\xBE\\x80\\x80'
how do i open the file so that i can get the third column as hex string:
'\xF3\xBE\x80\x80'
... | [
"You can:\n\nRemove the \\x-es\nUse .decode('hex') on the resulting string\n\nCode:\n>>> '\\\\xF3\\\\xBE\\\\x80\\\\x80'.replace('\\\\x', '').decode('hex')\n'\\xf3\\xbe\\x80\\x80'\n\nNote the appropriate interpretation of backslashes. When the string representation is '\\xf3' it means it's a single-byte string with ... | [
7,
7,
5,
1,
0
] | [] | [] | [
"hex",
"python",
"representation"
] | stackoverflow_0003519125_hex_python_representation.txt |
Q:
Trying to find all the combinations of values inside N lists
I am trying to compare all combinations of the values in N lists. Each list is identical holding values 1 through 9 in order. I am having a very hard time figuring out how to code this because I cannot create N nested loops beforehand. N is user defined ... | Trying to find all the combinations of values inside N lists | I am trying to compare all combinations of the values in N lists. Each list is identical holding values 1 through 9 in order. I am having a very hard time figuring out how to code this because I cannot create N nested loops beforehand. N is user defined and won't be known until run time. The place I always get stuck on... | [
"import itertools\nfor combo in itertools.product(xrange(1, 10), repeat=N):\n ...\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0003740178_python.txt |
Q:
i got this error: "ImportError: cannot import name python" How do I fix it?
File "G:\Python25\Lib\site-packages\PyAMF-0.6b2-py2.5-win32.egg\pyamf\util\__init__.py", line 15, in <module>
ImportError: cannot import name python
How do I fix it?
If you need any info to know how to fix this problem, I can explain, jus... | i got this error: "ImportError: cannot import name python" How do I fix it? | File "G:\Python25\Lib\site-packages\PyAMF-0.6b2-py2.5-win32.egg\pyamf\util\__init__.py", line 15, in <module>
ImportError: cannot import name python
How do I fix it?
If you need any info to know how to fix this problem, I can explain, just ask.
Thanks
Code:
from google.appengine.ext.webapp.util import run_wsgi_app
fro... | [
"You need to post your full traceback. What you show here isn't all that useful. I ended up digging up line 15 of pyamf/util/init.py. The code you should have posted is\nfrom pyamf import python\n\nThis should not fail unless your local environment is messed up.\nCan you 'import pyamf.util' and 'import pyamf.python... | [
1
] | [] | [] | [
"pyamf",
"python"
] | stackoverflow_0003738110_pyamf_python.txt |
Q:
extending scripting integration to an existing lib
I found swig can generate script wrapper for various scripting languages.
I've a 3rd party static library, a header file and a lib.
How can I use swig so that I can call functions from that library from a scripting language, say python?
Thanks
A:
Try reading the... | extending scripting integration to an existing lib | I found swig can generate script wrapper for various scripting languages.
I've a 3rd party static library, a header file and a lib.
How can I use swig so that I can call functions from that library from a scripting language, say python?
Thanks
| [
"Try reading the swig documentation. It walks through examples of how to do exactly this.\n"
] | [
0
] | [] | [] | [
"python",
"scripting",
"swig"
] | stackoverflow_0003733380_python_scripting_swig.txt |
Q:
How can I call a inner function from the Python shell?
I have some code (that I can't easily modify), of the following form:
def foo(x):
do_other_stuff_that_I_do_not_want_to_do()
def bar():
"do something"
str(x)
bar()
I would like to call bar(), directly, from the Python shell. I don't mind ... | How can I call a inner function from the Python shell? | I have some code (that I can't easily modify), of the following form:
def foo(x):
do_other_stuff_that_I_do_not_want_to_do()
def bar():
"do something"
str(x)
bar()
I would like to call bar(), directly, from the Python shell. I don't mind using co_globals, or other internal bits. I have the feelin... | [
"It is impossible to get at the inner function object with the code as you've stated it -- said object is only created (by the def statement) when the outer function runs (i.e., when it gets called).\nAs an aside, note that outer functions like foo are often coded to return the inner function as their result (e.g. ... | [
4
] | [] | [] | [
"nested",
"private_methods",
"python"
] | stackoverflow_0003740467_nested_private_methods_python.txt |
Q:
List sorted by categories in Tkinter?
I'm building a graphical program that will need to show files on both the user's computer and on a remote server. I'm using Tkinter, and I'm definitely a novice with this toolkit. I want to have the files displayed in a box similar to what you would get from a "Details" view i... | List sorted by categories in Tkinter? | I'm building a graphical program that will need to show files on both the user's computer and on a remote server. I'm using Tkinter, and I'm definitely a novice with this toolkit. I want to have the files displayed in a box similar to what you would get from a "Details" view in Windows, so that each file has several ca... | [
"TreeView widget should help you\n\nhttp://www.tkdocs.com/tutorial/tree.html\nhttp://docs.python.org/dev/library/tkinter.ttk.html#ttk-treeview\nhttp://m-eken.com/2010/03/02/treeview-in-python-tkinter/\n\nYeah , So already has one on this topic\n\nTk treeview column sort\n\nYou should be able to get started from the... | [
1
] | [] | [] | [
"detailsview",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0003740590_detailsview_python_tkinter_user_interface.txt |
Q:
Python. Showing text from a file in fragments of 20 lines every time ENTER is pressed
This is the code i have at the moment
print "Please input the filename:"
n = raw_input()
f = open(n,"r")
x = 0
for line in f.readlines():
print line
x+=1
if x % 20 == 0:
break
q = raw_input()
i... | Python. Showing text from a file in fragments of 20 lines every time ENTER is pressed | This is the code i have at the moment
print "Please input the filename:"
n = raw_input()
f = open(n,"r")
x = 0
for line in f.readlines():
print line
x+=1
if x % 20 == 0:
break
q = raw_input()
if q == "":
x+= 20
continue
Things the program should do:
1) Ask for a ... | [
"Basically, you want to pause every 20 lines. Currently, you're breaking out of your loop after the first 20 lines.\nfor line in f:\n print line\n x += 1\n if x % 20 == 0:\n raw_input(\"Hit enter\")\n\nshould suffice.\n",
"filename = raw_input(\"Please enter the file name: \")\nwith open(filename)... | [
1,
0
] | [] | [] | [
"input",
"loops",
"python"
] | stackoverflow_0003740915_input_loops_python.txt |
Q:
Total number of live sessions on GAE
Is there a way to count total number of active sessions (e.g. in 10 minutes) on Google App Engine (Python)?
I want to show something on frontpage like, This site currently haz 200 people online
A:
Considering the distributed nature of GAE, I don't think you can do this direct... | Total number of live sessions on GAE | Is there a way to count total number of active sessions (e.g. in 10 minutes) on Google App Engine (Python)?
I want to show something on frontpage like, This site currently haz 200 people online
| [
"Considering the distributed nature of GAE, I don't think you can do this directly. \nYou can store visits in the database (with timestamp) and query this (use a cookie to check if a user is already counted, avoid writing on each request!).\nAlternatively, you can use some external service that uses included javasc... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003740932_google_app_engine_python.txt |
Q:
Raw input and printing simultaneously
So I have a threaded Python program that takes input from a user and prints data simultaneously. The problem is that when the program is sitting at raw_input(), it won't print anything and will print it all after the user presses enter.
Is there any way to have user input and ... | Raw input and printing simultaneously | So I have a threaded Python program that takes input from a user and prints data simultaneously. The problem is that when the program is sitting at raw_input(), it won't print anything and will print it all after the user presses enter.
Is there any way to have user input and print at the same time?
| [
"You have two options, basically: threading and asynchronous IO. \nYou can have one thread fill a Queue with entered data and have the other thread print its contents. Be warned that threading is hard (impossible?) to do right.\nAsynchronous IO means you have a main dispatcher that invokes callbacks when data is av... | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003740960_multithreading_python.txt |
Q:
WxPython - Resize WxFrame when adding new content?
Pretty much exactly as it sounds. I have buttons in a Wx.Frame that are created on the fly and I'd like the parent frame to increase in height as I add new buttons. The height is already being acquire from the total number of buttons multiplied by an integer equal... | WxPython - Resize WxFrame when adding new content? | Pretty much exactly as it sounds. I have buttons in a Wx.Frame that are created on the fly and I'd like the parent frame to increase in height as I add new buttons. The height is already being acquire from the total number of buttons multiplied by an integer equal the each button's height, but I don't know how to get t... | [
"Don't double-prefix your methods unless you know what you're doing. This is not directly related to your question, but it'll result in bugs you won't understand later.\nSee this stackoverflow question and the python documentation what/why.\n",
"AFAIK there no way automatically resize the frame, but you can manua... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003740640_python_wxpython.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.