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:
Google App Engine cannot find gdata module
I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth".
I have installed the gdata module and added the following l... | Google App Engine cannot find gdata module | I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth".
I have installed the gdata module and added the following line to my .bashrc:
export PYTHONPATH=$PYTHONPATH... | [
"Your .bashrc is not known to Google App Engine. Make sure the gdata directory (with all its proper contents) is under your application's main directory!\nSee this article, particularly (and I quote):\n\nTo use this library with your Google\n App Engine application, simply place\n the library source files in your... | [
9,
1,
0
] | [] | [] | [
"gdata",
"google_app_engine",
"google_data_api",
"macos",
"python"
] | stackoverflow_0001035554_gdata_google_app_engine_google_data_api_macos_python.txt |
Q:
how to bring a background task to foreground in google app engine?
Currently I have tasks running in background. After the tasks are done executing I need to show output. How do I do this in Google App Engine?
Once the tasks are done the only thing I can do is create another task which is supposed to show output o... | how to bring a background task to foreground in google app engine? | Currently I have tasks running in background. After the tasks are done executing I need to show output. How do I do this in Google App Engine?
Once the tasks are done the only thing I can do is create another task which is supposed to show output or is there any other way?
| [
"You can't \"bring a task to the foreground\" -- it is a webserver. The server responds to requests from the client.\nBut, you have a couple choices to accomplish something similar:\n\nUse the Channel API to send the client notice that the work is finished, or a even the results of the processing.\nWrite status in... | [
5,
0
] | [] | [] | [
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0004379200_google_app_engine_python_task_queue.txt |
Q:
How can I create a status bar item with Cocoa and Python (PyObjC)?
I have created a brand new project in XCode and have the following in my AppDelegate.py file:
from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSL... | How can I create a status bar item with Cocoa and Python (PyObjC)? | I have created a brand new project in XCode and have the following in my AppDelegate.py file:
from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBa... | [
"The above usage of .retain() is required because the statusItem is being destroyed upon return from the applicationDidFinishLaunching() method. Bind that variable as a field in instances of MyApplicationAppDelegate using self.statusItem instead.\nHere is a modified example that does not require a .xib / etc...\nfr... | [
6,
5
] | [] | [] | [
"cocoa",
"pyobjc",
"python"
] | stackoverflow_0000141432_cocoa_pyobjc_python.txt |
Q:
Python: Definitions made in external shell get a bad `.__module__` attribute
I am making a wxPython app which supplies a shell for the user to use. (This is wx.lib.shell.PyShell, the shell that ships with wxPython.)
Problem is, definitions made in this shell have a bad .__module__ attribute. For example:
>>> def f... | Python: Definitions made in external shell get a bad `.__module__` attribute | I am making a wxPython app which supplies a shell for the user to use. (This is wx.lib.shell.PyShell, the shell that ships with wxPython.)
Problem is, definitions made in this shell have a bad .__module__ attribute. For example:
>>> def f(): 0
...
>>> f.__module__
>>> f.__module__ is None
True
>>> class A(object):
...... | [
"In IDLE and in the wxPython Demo's PyShell demo, I get the following:\n>>> def f(): 0\n\n>>> f.__module__\n'__main__'\n>>> f.__module__ is None\nFalse\n>>> class A(object):\n pass\n\n>>> A.__module__\n'__main__'\n\nIt seems to work correctly to me. I'm not sure what you're doing on your machine. I am using ... | [
1,
0
] | [] | [] | [
"module",
"python",
"read_eval_print_loop",
"shell",
"wxpython"
] | stackoverflow_0004370155_module_python_read_eval_print_loop_shell_wxpython.txt |
Q:
Removing a character in a string one at a time
Basically I want to remove a character in a string one at a time if it occurs multiple times .
For eg :- if I have a word abaccea and character 'a' then the output of the function should be baccea , abacce , abccea.
I read that I can make maketrans for a and empty str... | Removing a character in a string one at a time | Basically I want to remove a character in a string one at a time if it occurs multiple times .
For eg :- if I have a word abaccea and character 'a' then the output of the function should be baccea , abacce , abccea.
I read that I can make maketrans for a and empty string but it replaces every a in the string.
Is there ... | [
"Here is a quick way of doing it:\nIn [6]: s = \"abaccea\"\nIn [9]: [s[:key] + s[key+1:] for key,val in enumerate(s) if val == \"a\"]\nOut[10]: ['baccea', 'abccea', 'abacce']\n\nThere is the benefit of being able to turn this into a generator by simpling replacing square brackets with round ones.\n",
"You could t... | [
5,
3,
1
] | [
"how about this ?\n>>> def replace_a(word):\n... word = word[1:8]\n... return word\n... \n>>> replace_a(\"abaccea\")\n'baccea'\n>>>\n\n"
] | [
-2
] | [
"python"
] | stackoverflow_0004379570_python.txt |
Q:
Caching in urllib2?
Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?
A:
If you don't mind working at a slightly lower level, httplib2 (https://github.com/httplib2/httplib2) is an excellent HTTP library that includes caching functionality.
A:
This Acti... | Caching in urllib2? | Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?
| [
"If you don't mind working at a slightly lower level, httplib2 (https://github.com/httplib2/httplib2) is an excellent HTTP library that includes caching functionality.\n",
"This ActiveState Python recipe might be helpful:\nhttp://code.activestate.com/recipes/491261/\n",
"You could use a decorator function such ... | [
8,
7,
7,
5,
3,
3,
1
] | [] | [] | [
"caching",
"python",
"urllib2"
] | stackoverflow_0000148853_caching_python_urllib2.txt |
Q:
I have Data Models...Now What in Google App Engine With Python
I have what I think I need for models in google app engine. I'm building basically a classifieds ad system.
Here's what I have so far:
class Cities(db.Model):
name = db.StringProperty()
connectors = db.ListProperty()
catList = db.ListPrope... | I have Data Models...Now What in Google App Engine With Python | I have what I think I need for models in google app engine. I'm building basically a classifieds ad system.
Here's what I have so far:
class Cities(db.Model):
name = db.StringProperty()
connectors = db.ListProperty()
catList = db.ListProperty()
class Listings(db.model):
title = db.StringProperty()
... | [
"\nThere is nothing obviously wrong with them\nIn something like i_use_models.py have from dbmodels import Cities, Listings (assuming they are in the same folder), and use Cities and Listings\nIt is the right way, but make sure only administrators can edit that. (Or, better, read Thomas K's comment below)\n\n"
] | [
2
] | [] | [] | [
"data_modeling",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004379948_data_modeling_google_app_engine_google_cloud_datastore_python.txt |
Q:
Getting the general direction of motion using OpenCV and Python
Using the code I found at How do I track motion using OpenCV in Python? and http://appdelegateinc.com/blog/2010/08/02/motion-tracking-with-a-webcam/; I can track motion quite well using Python and OpenCV. I modified it slightly so instead of drawing c... | Getting the general direction of motion using OpenCV and Python | Using the code I found at How do I track motion using OpenCV in Python? and http://appdelegateinc.com/blog/2010/08/02/motion-tracking-with-a-webcam/; I can track motion quite well using Python and OpenCV. I modified it slightly so instead of drawing circles on the image, it will print out the (x,y) co-ords of what it d... | [
"No, I don't think OpenCV provides this facility. You are already doing it right by calculating the the gradient. How ever, you could do with a simple calculation of (x1, y1) and (x2, y2) to tell a gradient between two points. Using gnuplot may be heavy. You could also use Numdifftools.\nAdding additional links on ... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0004379799_opencv_python.txt |
Q:
Python style: lowercase class names for "namespaces"?
I know the PEP-8 convention for class names is ClassName. But we often use small classes as pseudo-namespaces, enums etc. In other words, not a real class that you're going to instantiate. We've opted for a lowercase naming convention for such "classes", becaus... | Python style: lowercase class names for "namespaces"? | I know the PEP-8 convention for class names is ClassName. But we often use small classes as pseudo-namespaces, enums etc. In other words, not a real class that you're going to instantiate. We've opted for a lowercase naming convention for such "classes", because they're really a namespace/enum name.
Does anyone else ha... | [
"For all enums and constants, I prefer to use capitalized versions.\nclass COUNTRIES: # pseudo-enum\n NEW_ZEALAND = 1\n UNITED_STATES = 2\n\nIt is still ok with me, if the class name is not all capitalized. Since, any way it is tied up with the enum values. I am always going to use it like Countries.NEW_ZEA... | [
5,
4,
1,
1
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0004380008_coding_style_python.txt |
Q:
Wxpython Application Fails On Some XP Installations
I am the developer or a simple software program written in Python/wxpython and packaged with py2exe. I've had reports from some users that the program doesn't run. All users who report this are running windows XP - but with my 2 XP test machines, I can't replicat... | Wxpython Application Fails On Some XP Installations | I am the developer or a simple software program written in Python/wxpython and packaged with py2exe. I've had reports from some users that the program doesn't run. All users who report this are running windows XP - but with my 2 XP test machines, I can't replicate the problem.
The weird thing - and what's making this ... | [
"Try running Dependency Walker on the user's PC and see what it comes back with: http://www.dependencywalker.com/\nAlso, if you're using bundle option 1 in py2exe, try switching to bundle option 3. I've had some screwy issues when I've used 1 before.\n"
] | [
1
] | [] | [] | [
"debugging",
"python",
"windows_xp",
"wxpython"
] | stackoverflow_0004379513_debugging_python_windows_xp_wxpython.txt |
Q:
PIL: How to make area transparent in PNG?
I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say
from PIL import Image
im = Image.open("sample.png")
transparent_area = (50,80,100,200)
...
A:
from PIL import Image
from PIL import ImageDraw
im = Image.open("image.png... | PIL: How to make area transparent in PNG? | I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say
from PIL import Image
im = Image.open("sample.png")
transparent_area = (50,80,100,200)
...
| [
"from PIL import Image\nfrom PIL import ImageDraw\nim = Image.open(\"image.png\")\ntransparent_area = (50,80,100,200)\n\nmask=Image.new('L', im.size, color=255)\ndraw=ImageDraw.Draw(mask) \ndraw.rectangle(transparent_area, fill=0)\nim.putalpha(mask)\nim.save('/tmp/output.png')\n\nI learned how to do this here.\n",
... | [
33,
4
] | [] | [] | [
"image",
"png",
"python",
"python_imaging_library",
"transparency"
] | stackoverflow_0004379978_image_png_python_python_imaging_library_transparency.txt |
Q:
python manage.py syncdb doesn't pull from models.py
I'm not getting a python manage.py syncdb to create tables for my models; this is apparently because an exception is thrown on attempted import of my models and I am somewhat puzzled by the exception:
jhayward@jhayward81QDLD1 ~/project
$ python manage.py shell
Py... | python manage.py syncdb doesn't pull from models.py | I'm not getting a python manage.py syncdb to create tables for my models; this is apparently because an exception is thrown on attempted import of my models and I am somewhat puzzled by the exception:
jhayward@jhayward81QDLD1 ~/project
$ python manage.py shell
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4... | [
"You must have an application package (e.g. myapp) and models must be within it (myapp/models.py)\nThen you can import myapp.models or from myapp import models. \nThe error is because django tries to find the appname as the package that contains the models module (the path to the models module must at least have 2 ... | [
3,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004380582_django_django_models_python.txt |
Q:
Why can't print() be used in a lambda expression?
Why is:
p = lambda s: print(s)
invalid syntax but:
def do_print(s):
print(s)
p = lambda s: do_print(s)
valid?
A:
The body of a lambda has to be an expression, not a statement. print is a statement.
Update: As pointed out, in 2.x, print is a statement while ... | Why can't print() be used in a lambda expression? | Why is:
p = lambda s: print(s)
invalid syntax but:
def do_print(s):
print(s)
p = lambda s: do_print(s)
valid?
| [
"The body of a lambda has to be an expression, not a statement. print is a statement.\nUpdate: As pointed out, in 2.x, print is a statement while in Python 3, it is a function.\n",
"which version of python are you using?; in python 2.7 (and before), print is a statement while in python 3 it's a function\n"
] | [
6,
5
] | [
"its the way the language is read it can't do p = lambda s: print(s) all in one step\n"
] | [
-1
] | [
"functional_programming",
"lambda",
"python"
] | stackoverflow_0004380812_functional_programming_lambda_python.txt |
Q:
Obtain all subtrees in value
Given "a.b.c.d.e" I want to obtain all subtrees, efficiently, e.g. "b.c.d.e" and "c.d.e", but not "a.d.e" or "b.c.d".
Real world situation:
I have foo.bar.baz.example.com and I want all possible subdomain trees.
A:
listed = "a.b.c.d.e".split('.')
subtrees = ['.'.join(listed[idx:]) fo... | Obtain all subtrees in value | Given "a.b.c.d.e" I want to obtain all subtrees, efficiently, e.g. "b.c.d.e" and "c.d.e", but not "a.d.e" or "b.c.d".
Real world situation:
I have foo.bar.baz.example.com and I want all possible subdomain trees.
| [
"listed = \"a.b.c.d.e\".split('.')\nsubtrees = ['.'.join(listed[idx:]) for idx in xrange(len(listed))]\n\nGiven your sample data, subtrees equals ['a.b.c.d.e', 'b.c.d.e', 'c.d.e', 'd.e', 'e'].\n",
"items = data.split('.')\n['.'.join(items[i:]) for i in range(0, len(items))]\n\n",
"def parts( s, sep ):\n whil... | [
5,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004380905_python.txt |
Q:
Inserting missing portions of a sequence in python
I have two sequences, for example:
Seq 1: MAT--LA-B
seq 2: MATATLAB
Is it possible in python to compare the two sequences and then insert the missing portion in Sequence 1 without changing the rest of sequence 1, i.e, the final sequence 1 should be MATAT--LA-B?
... | Inserting missing portions of a sequence in python | I have two sequences, for example:
Seq 1: MAT--LA-B
seq 2: MATATLAB
Is it possible in python to compare the two sequences and then insert the missing portion in Sequence 1 without changing the rest of sequence 1, i.e, the final sequence 1 should be MATAT--LA-B?
The insert could be at more than one position..(I have a... | [
"I'd suggest beginning your search for a solution by obtaining opcodes for transforming one sequence into the other. Opcodes can be generated with difflib.SequenceMatcher.get_opcodes. These will be tuples with instructions (insert, delete, or replace) and start/stop indices were the changes must occur to transform ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004378935_python.txt |
Q:
Install MySQLdb python module
i want to install MySQLdb module for Python on Windows 7, but I get an error
G:\python\python and mysql\MySQL-python-1.2.3b2\MySQL-python-1.2.3b2>setup.py
Traceback (most recent call last):
File "G:\python\python and mysql\MySQL-python-1.2.3b2\MySQL-python-1.2.3b2\set
up.py", line... | Install MySQLdb python module | i want to install MySQLdb module for Python on Windows 7, but I get an error
G:\python\python and mysql\MySQL-python-1.2.3b2\MySQL-python-1.2.3b2>setup.py
Traceback (most recent call last):
File "G:\python\python and mysql\MySQL-python-1.2.3b2\MySQL-python-1.2.3b2\set
up.py", line 15, in <module>
metadata, optio... | [
"This thread implies the problem is that you need mysql installed on the system you want to use the client libraries on, even if you don't use the server on the same system.\n"
] | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004381073_mysql_python.txt |
Q:
Difference between closures and lambdas?
Possible Duplicate:
What is the difference between a 'closure' and a 'lambda'?
Hello, World!
Forgive me if this is a tad of a newb q, but everyone always gets computersciencey about it..
What actually is a lambda? And what is a Closure?
As far as I understand a lambda is ... | Difference between closures and lambdas? |
Possible Duplicate:
What is the difference between a 'closure' and a 'lambda'?
Hello, World!
Forgive me if this is a tad of a newb q, but everyone always gets computersciencey about it..
What actually is a lambda? And what is a Closure?
As far as I understand a lambda is an anonymous function and a closure is a poin... | [
"That is totally correct. The term closure is describing the scope thing, the term lambda is describing the whole function as an object thing.\n"
] | [
1
] | [] | [] | [
"c#",
"computer_science",
"python",
"ruby",
"theory"
] | stackoverflow_0004381222_c#_computer_science_python_ruby_theory.txt |
Q:
django-tinymce fails to display the widget properly
I'm trying to use to django-tinymce (http://http://django-tinymce.googlecode.com/ ) app to display a WYSIWYG editor in the django admin.
I downloaded and installed it, downloaded the tinymce itself and put it into /js/tiny_mce, did not change anything in the sett... | django-tinymce fails to display the widget properly | I'm trying to use to django-tinymce (http://http://django-tinymce.googlecode.com/ ) app to display a WYSIWYG editor in the django admin.
I downloaded and installed it, downloaded the tinymce itself and put it into /js/tiny_mce, did not change anything in the settings.py and added an HTMLField to my model like so:
class... | [
"the cause of this was that lighttpd was sending improper content-types for .js'es and .css'es in response headers. Fixed by modifying lighttpd config. \n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"django_tinymce",
"python",
"tinymce"
] | stackoverflow_0004381181_django_django_admin_django_tinymce_python_tinymce.txt |
Q:
Python good for prototyping and not for large scale deployment?
I am new to python and one thing I read is python is good for making fast prototype of your product because of its extensive library support. But it is not good(used) for large scale deployment?
Is it true? your comments on this.
I have not seen a pla... | Python good for prototyping and not for large scale deployment? | I am new to python and one thing I read is python is good for making fast prototype of your product because of its extensive library support. But it is not good(used) for large scale deployment?
Is it true? your comments on this.
I have not seen a place (domain) where it is heavily used although its a beautiful languag... | [
"Google uses it, and I think this is a good example for large-scale deployment. It is not very fast, indeed, but it has awesome C/C++ integration support for the bottlenecks.\n",
"The example I would give would be CCP Games who use Python for almost all code, iirc. They run eve online, a MMORPG with the record fo... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004381239_python.txt |
Q:
Why is equivalent Python code so much slower
can somebody explain why is the following trivial code (implementation of Euclid's algorithm to find greatest common denominator) about 3 times slower then equivalent code in Ruby ?
contents of iter_gcd.py:
from sys import argv,stderr
def gcd(m, n):
if n > m:
... | Why is equivalent Python code so much slower | can somebody explain why is the following trivial code (implementation of Euclid's algorithm to find greatest common denominator) about 3 times slower then equivalent code in Ruby ?
contents of iter_gcd.py:
from sys import argv,stderr
def gcd(m, n):
if n > m:
m, n = n, m
while n != 0:
rem = m %... | [
"Summary\n\"Because the function call overhead in Python is much larger than in Ruby.\"\nDetails\nBeing a microbenchmark, this really doesn't say much about the performance of either language in proper use. Likely you would want to rewrite the program to take advantage of the strengths of Python and Ruby, but this ... | [
37,
22,
10,
0
] | [] | [] | [
"python",
"python_3.x",
"ruby"
] | stackoverflow_0004305518_python_python_3.x_ruby.txt |
Q:
More Pythonic/Django-esque way to write this?
Is there a more elegant way to write this?
try:
author = Author.objects.get \
(internal_id=line[5])
except:
author = Author.objects.get \
(internal_id=author_mapper[line[5]])
Or is this the best th... | More Pythonic/Django-esque way to write this? | Is there a more elegant way to write this?
try:
author = Author.objects.get \
(internal_id=line[5])
except:
author = Author.objects.get \
(internal_id=author_mapper[line[5]])
Or is this the best there is?
| [
"author_id = line[5]\ntry: \n author = Author.objects.get(internal_id=author_id)\nexcept Author.DoesNotExist: #blank excepts are bad and hide errors.\n author_id = author_mapper[line[5]]\n author = Author.objects.get(internal_id=author_id) \n\nYour version was good enough for jazz. However, you should add ... | [
5,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004381388_django_python.txt |
Q:
Ajax Request with Python Tornado Getting a 405
I have some javascript that makes a "POST" call via javascript (no libraries) to a local site running on a different port. If that site is running an app using mod_python, it just works. If it is running an app using Tornado - it fails with a 405 error. I've been s... | Ajax Request with Python Tornado Getting a 405 | I have some javascript that makes a "POST" call via javascript (no libraries) to a local site running on a different port. If that site is running an app using mod_python, it just works. If it is running an app using Tornado - it fails with a 405 error. I've been sure to implement post() and options() methods on the... | [
"It would help to see both your RequestHandler object, as well as how you dispatch URL's in Tornado. To my knowledge, only missing HTTP method implementations or a missing options() definition would cause tornado to emit a 405. \nMaybe the problem isn't that you're not implementing the proper methods, but that the ... | [
1,
0
] | [] | [] | [
"ajax",
"http_status_code_405",
"python",
"tornado"
] | stackoverflow_0004364830_ajax_http_status_code_405_python_tornado.txt |
Q:
Python os module open file above current directory with relative path
The documentation for the OS module does not seem to have information about how to open a file that is not in a subdirectory or the current directory that the script is running in without a full path. My directory structure looks like this.
/hom... | Python os module open file above current directory with relative path | The documentation for the OS module does not seem to have information about how to open a file that is not in a subdirectory or the current directory that the script is running in without a full path. My directory structure looks like this.
/home/matt/project/dir1/cgi-bin/script.py
/home/matt/project/fileIwantToOpen.tx... | [
"The path given to open should be relative to the current working directory, the directory from which you run the script. So the above example will only work if you run it from the cgi-bin directory.\nA simple solution would be to make your path relative to the script. One possible solution.\nfrom os import path\n\... | [
53,
6
] | [] | [] | [
"cgi",
"cgi_bin",
"file_io",
"python"
] | stackoverflow_0004381569_cgi_cgi_bin_file_io_python.txt |
Q:
NumPy: Comparing Elements in Two Arrays
Anyone ever come up to this problem? Let's say you have two arrays like the following
a = array([1,2,3,4,5,6])
b = array([1,4,5])
Is there a way to compare what elements in a exist in b? For example,
c = a == b # Wishful example here
print c
array([1,4,5])
# Or even better
... | NumPy: Comparing Elements in Two Arrays | Anyone ever come up to this problem? Let's say you have two arrays like the following
a = array([1,2,3,4,5,6])
b = array([1,4,5])
Is there a way to compare what elements in a exist in b? For example,
c = a == b # Wishful example here
print c
array([1,4,5])
# Or even better
array([True, False, False, True, True, False]... | [
"Actually, there's an even simpler solution than any of these:\nimport numpy as np\n\na = array([1,2,3,4,5,6])\nb = array([1,4,5])\n\nc = np.in1d(a,b)\n\nThe resulting c is then:\narray([ True, False, False, True, True, False], dtype=bool)\n\n",
"Use np.intersect1d. \n#!/usr/bin/env python\nimport numpy as np\n... | [
61,
23,
3,
3,
0
] | [
"Your example implies set-like behavior, caring more about existance in the array than having the right element at the right place. Numpy does this differently with its mathematical arrays and matrices, it will tell you only about items at the exact right spot. Can you make that work for you?\n>>> import numpy\n>>>... | [
-3
] | [
"numpy",
"python"
] | stackoverflow_0001613249_numpy_python.txt |
Q:
Matplotlib Legend in a Loop?
I'm trying to have the legend add an entry for each item that gets plotted in the loop. So, there may be 6 times that a 'vgs' gets plotted, and for each one I want to add an entry for the name 'vgs' and the color that was plotted for that specific instance of 'vgs'. My code seems to cu... | Matplotlib Legend in a Loop? | I'm trying to have the legend add an entry for each item that gets plotted in the loop. So, there may be 6 times that a 'vgs' gets plotted, and for each one I want to add an entry for the name 'vgs' and the color that was plotted for that specific instance of 'vgs'. My code seems to currently create a legend for the la... | [
"i=0\nfor n in range(len(eventBreakL)):\n if n < len(eventBreakL)-1:\n i+=1\n eventL = c_eventConditionL[eventBreakL[n]:eventBreakL[n+1]-1]\n tL,isubL,vgsL,vdsL = [],[],[],[]\n for m in eventL:\n tL.append(m[1])\n isubL.append(m[-1])\n vdsL.append(m[2]... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004379003_matplotlib_python.txt |
Q:
Is there such a thing as working threading in python?
I wrote a beautiful multithreaded script, and when I ran it, it performed worse with 25 threads than with just direct invocation of the thread handler.
Then I discovered the global interpreter lock. I want to ask, before I discard python for this script and re... | Is there such a thing as working threading in python? | I wrote a beautiful multithreaded script, and when I ran it, it performed worse with 25 threads than with just direct invocation of the thread handler.
Then I discovered the global interpreter lock. I want to ask, before I discard python for this script and rewrite the thing in something else, is there any way to do a... | [
"The other approach is to abandon threads and instead use the Multiprocessing module (Python 2.6+), which gets around the GIL, and has an API that's at least similar to the one in the threading module.\n",
"Now this is an interesting question - I don't think there's an escaping the GIL in straight CPython.\nStack... | [
8,
3,
1,
0,
0
] | [] | [] | [
"multithreading",
"python",
"python_stackless"
] | stackoverflow_0004381176_multithreading_python_python_stackless.txt |
Q:
Python subprocess: why won't the list of arguments work analogous to the full shell string?
Thanks in advance for any help. I am new to python, but not particularly new to scripting. I am trying to run a simple, automated email program, but the email module seems to be installed incorrectly on our system (I don'... | Python subprocess: why won't the list of arguments work analogous to the full shell string? | Thanks in advance for any help. I am new to python, but not particularly new to scripting. I am trying to run a simple, automated email program, but the email module seems to be installed incorrectly on our system (I don't have 75% of the functions described in the python examples, only "message_from_string" and "mes... | [
"| and < are not arguments; they are shell redirections. To replace the | in your code, see these instructions.\nTo replace <, use:\n subprocess.Popen([\"command\", \"args\"], stdin=open(\"file.txt\", 'r'))\n\neg.\nsubprocess.Popen([\"cat\"], stdin=open(\"file.txt\", 'r')) is the same as cat < file.txt\n",
"The P... | [
5,
5,
4,
2
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0004381673_python_subprocess.txt |
Q:
How do I determine the high and low values in a series of cyclic data?
I've got some data that represents periodic motion. So, it goes from a high to a low and back again; if you were to plot it, it would like a sine wave. However, the amplitude varies slightly in each cycle. I would like to make a list of each ma... | How do I determine the high and low values in a series of cyclic data? | I've got some data that represents periodic motion. So, it goes from a high to a low and back again; if you were to plot it, it would like a sine wave. However, the amplitude varies slightly in each cycle. I would like to make a list of each maximum and minimum in the entire sequence. If there were 10 complete cycles, ... | [
"This isn't an overly complicated problem if you didn't want to use a library, something like this should do what you want. Basically as you iterate through the data if you go from ascending to descending you have a high, and from descending to ascending you have a low.\ndef get_highs_and_lows(data):\n prev = d... | [
2,
1,
0
] | [] | [] | [
"python",
"statistics"
] | stackoverflow_0004381744_python_statistics.txt |
Q:
Finding smallest contiguous integers in a Python set
What is the best way to get a list of the smallest N contiguous integers in a Python set?
>>> s=set([5,6,10,12,13,15,30,40,41,42,43,44,55,56,90,300,500])
>>> s
set([42, 43, 44, 5, 6, 90, 300, 30, 10, 12, 13, 55, 56, 15, 500, 40, 41])
>>> smallest_contiguous(s,5)... | Finding smallest contiguous integers in a Python set | What is the best way to get a list of the smallest N contiguous integers in a Python set?
>>> s=set([5,6,10,12,13,15,30,40,41,42,43,44,55,56,90,300,500])
>>> s
set([42, 43, 44, 5, 6, 90, 300, 30, 10, 12, 13, 55, 56, 15, 500, 40, 41])
>>> smallest_contiguous(s,5)
[40,41,42,43,44]
>>> smallest_contiguous(s,6)
[]
Edit: T... | [
"Sven has the right idea. You can avoid having to check supersets by just checking the number N - 1 ahead.\ndef smallest_contiguous(s, N):\n lst = list(s)\n lst.sort()\n Nm = N-1\n for i in xrange(len(lst) - Nm):\n if lst[i] + Nm == lst[i + Nm]:\n return range(lst[i], lst[i]+N)\n re... | [
3,
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"set"
] | stackoverflow_0004378384_python_set.txt |
Q:
How do I handle an accented character on a batch database import in Python and Postgres
When running a batch import script in Python (openblock), I'm getting the following invalid byte sequence for encoding "UTF8": 0xca4e error for an accented character:
It shows up as:
GRAND-CH?NE, COUR DU
But is actually "GRAND-... | How do I handle an accented character on a batch database import in Python and Postgres | When running a batch import script in Python (openblock), I'm getting the following invalid byte sequence for encoding "UTF8": 0xca4e error for an accented character:
It shows up as:
GRAND-CH?NE, COUR DU
But is actually "GRAND-CHÊNE, COUR DU"
What is the best way to handle this? Ideally I'd like to keep the accented ch... | [
"More information please. What platform - Windows / Linux / ???\nWhat version of Python?\nIf you are running Windows, your encoding is much more likely to be cp1252 or similar than ISO-8859-1. It's definitely not UTF-8.\nYou will need to: (1) Find out what your input data is encoded with. Try cp1252; it's the usual... | [
3,
1
] | [
"You can try something like:\nuString = unicode(item.field, \"utf-8\")\nSee http://evanjones.ca/python-utf8.html for more details about Unicode and Python.\n"
] | [
-3
] | [
"django",
"postgresql",
"python"
] | stackoverflow_0004362716_django_postgresql_python.txt |
Q:
Python augmented assignment issue
i ran into something interesting about the python augmented assignment +=
it seems to be automatic data type conversion is not always done for a += b if a is a 'simpler' data type, while a = a + b seems to work always
cases where the conversion is done
a = 1
b = 1j
a = 1
b = 0.5
... | Python augmented assignment issue | i ran into something interesting about the python augmented assignment +=
it seems to be automatic data type conversion is not always done for a += b if a is a 'simpler' data type, while a = a + b seems to work always
cases where the conversion is done
a = 1
b = 1j
a = 1
b = 0.5
case where the conversion is not done
... | [
"For the + operator, Python defines three \"special\" methods that an object may implement:\n\n__add__: adds two items (+ operator). When you do a + b, the __add__ method of a is called with b as an argument.\n__radd__: reflected add; for a + b, the __radd__ method of b is called with a as an instance. This is only... | [
16,
8,
1,
0
] | [] | [] | [
"arrays",
"complex_numbers",
"numbers",
"numpy",
"python"
] | stackoverflow_0004382246_arrays_complex_numbers_numbers_numpy_python.txt |
Q:
parse_str for python?
Is there a parse_str (used in php) alternative for python?
http://php.net/manual/en/function.parse-str.php
parse_str — Parses the string into variables
A:
urlparse.parse_qs: http://docs.python.org/library/urlparse.html#urlparse.parse_qs
If you are using a Python older than 2.6, the previous... | parse_str for python? | Is there a parse_str (used in php) alternative for python?
http://php.net/manual/en/function.parse-str.php
parse_str — Parses the string into variables
| [
"urlparse.parse_qs: http://docs.python.org/library/urlparse.html#urlparse.parse_qs\nIf you are using a Python older than 2.6, the previous location of this function was in the cgi module: http://docs.python.org/library/cgi.html#cgi.parse_qs\n",
"If you are using Python<2.6\nparse_qs is in the cgi module\nIt's sti... | [
2,
1
] | [] | [] | [
"php",
"python"
] | stackoverflow_0004382468_php_python.txt |
Q:
Threading and Signals problem in PyQt
I'm having some problems with communicating between Threads in PyQt. I'm using signals to communicate between two threads, a Sender and a Listener. The sender sends messages, which are expected to be received by the listener. However, no messages are receieved. Can anyone sugg... | Threading and Signals problem in PyQt | I'm having some problems with communicating between Threads in PyQt. I'm using signals to communicate between two threads, a Sender and a Listener. The sender sends messages, which are expected to be received by the listener. However, no messages are receieved. Can anyone suggest what might be going wrong? I'm sure it ... | [
"I'm not sure if that is what you need, but it works fine...\nfrom PyQt4 import QtCore,QtGui\nimport time\n\nclass Listener(QtCore.QThread):\n def __init__(self):\n super(Listener,self).__init__()\n\n def run(self):\n print('listener: started')\n while True:\n time.sleep(2)\n\n... | [
5,
5
] | [] | [] | [
"multithreading",
"pyqt",
"python",
"signals"
] | stackoverflow_0004323678_multithreading_pyqt_python_signals.txt |
Q:
Using web.py as non blocking http-server
while learning some basic programming with python, i found web.py. i
got stuck with a stupid problem:
i wrote a simple console app with a main loop that proccesses items
from a queue in seperate threads. my goal is to use web.py to add
items to my queue and report status of... | Using web.py as non blocking http-server | while learning some basic programming with python, i found web.py. i
got stuck with a stupid problem:
i wrote a simple console app with a main loop that proccesses items
from a queue in seperate threads. my goal is to use web.py to add
items to my queue and report status of the queue via web request. i
got this running... | [
"I found a working solution. In a seperate module i create my webserver:\nimport web\nimport threading\nclass MyWebserver(threading.Thread):\n\n def run (self):\n urls = ('/', 'MyWebserver')\n app = web.application(urls, globals())\n app.run()\n\n def POST ...\n\nIn the main programm i ju... | [
8,
1,
1,
0
] | [] | [] | [
"multithreading",
"python",
"web.py",
"web_services"
] | stackoverflow_0000500935_multithreading_python_web.py_web_services.txt |
Q:
Handling IRI in Django
The Django documentation has a [nice section] on handling strings with non-ASCII data in URLs. In particular, it presents the following example on how to transform Unicode strings for use in URLs:
>>> urlquote(u'Paris & Orléans')
u'Paris%20%26%20Orl%C3%A9ans'
>>> iri_to_uri(u'/favorites/Fran... | Handling IRI in Django | The Django documentation has a [nice section] on handling strings with non-ASCII data in URLs. In particular, it presents the following example on how to transform Unicode strings for use in URLs:
>>> urlquote(u'Paris & Orléans')
u'Paris%20%26%20Orl%C3%A9ans'
>>> iri_to_uri(u'/favorites/François/%s' % urlquote(u'Paris ... | [
"The standard urllib.unquote() should work just fine in this case:\n>>> urllib.unquote('/favorites/Fran%C3%A7ois/Paris%20%26%20Orl%C3%A9ans')\n'/favorites/Fran\\xc3\\xa7ois/Paris & Orl\\xc3\\xa9ans'\n\n",
"That's because urllib.unquote does this for you:\n>>> import urllib\n>>> print urllib.unquote('/favorites/Fr... | [
3,
1
] | [] | [] | [
"django",
"python",
"unicode",
"url"
] | stackoverflow_0004382875_django_python_unicode_url.txt |
Q:
Post Forms and Upload Files using Linux Command Line
I need to Post Forms and Upload Files to a website using Linux Command Line.
I have done some search, and I would like to write the script in Python.
I need to first log in the website, save the cookies and then post form data and upload files to that website.
... | Post Forms and Upload Files using Linux Command Line | I need to Post Forms and Upload Files to a website using Linux Command Line.
I have done some search, and I would like to write the script in Python.
I need to first log in the website, save the cookies and then post form data and upload files to that website.
Here is the details:
The website's log in page is:hxxp://w... | [
"You could of course use urllib2 to accomplish this task. Read the docs on how to deal with cookies and how to upload files. However, I think using mechanize could save a lot of time. Mechanize allows you to deal with webpages as if you were using a browser:\nimport mechanize\n\nbr = mechanize.Browser()\nbr.open(\"... | [
2
] | [] | [] | [
"command_line",
"http",
"linux",
"python"
] | stackoverflow_0004382788_command_line_http_linux_python.txt |
Q:
Comparing lists in Python
Say I have list1 = [1,2,3,4] and list2 = [5,6,7,8]. How would I compare the first element, 1, in list1 with the first element, 5, in list2? And 2 with 6, 3 with 7, and so on.
I'm trying to use a for loop for this, but I'm not sure how to do it. I understand that doing for x in list1 jus... | Comparing lists in Python | Say I have list1 = [1,2,3,4] and list2 = [5,6,7,8]. How would I compare the first element, 1, in list1 with the first element, 5, in list2? And 2 with 6, 3 with 7, and so on.
I'm trying to use a for loop for this, but I'm not sure how to do it. I understand that doing for x in list1 just checks an element x to all el... | [
"You can traverse both lists simultaneously using zip:\nfor (x, y) in zip(list1, list2): do_something\n\nThe 'zip' function gives you [(1,5), (2,6), (3,7), (4,8)], so in loop iteration N you get the Nth element of each list. \n",
"The default comparison operators compare lists in lexicographical order. So you ca... | [
8,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004382301_python.txt |
Q:
Python regex separate space-delimited words into a list
If I have a string = "hello world sample text"
I want to be able to convert it to a list = ["hello", "world", "sample", "text"]
How can I do that with regular expressions? (other methods not using re are acceptable)
A:
"hello world sample text".split()
wil... | Python regex separate space-delimited words into a list | If I have a string = "hello world sample text"
I want to be able to convert it to a list = ["hello", "world", "sample", "text"]
How can I do that with regular expressions? (other methods not using re are acceptable)
| [
"\"hello world sample text\".split()\n\nwill split on any whitespace. If you only want to split on spaces\n\"hello world sample text\".split(\" \")\n\nregex version would be something like this\nre.split(\" +\", \"hello world sample text\")\n\nwhich works if you have multiple spaces between the words\n"
] | [
18
] | [] | [] | [
"list",
"python",
"regex",
"string"
] | stackoverflow_0004383082_list_python_regex_string.txt |
Q:
Which of the languages does Python resemble in its class syntax?
I want to start programming in python and I was wondering,
which languages does Python resemble in syntax? I am familiar with .net.
A:
None, really. Python syntax is kind of unique.
ie ( taken from: Python tutorial - classes )
>>> class Complex:... | Which of the languages does Python resemble in its class syntax? | I want to start programming in python and I was wondering,
which languages does Python resemble in syntax? I am familiar with .net.
| [
"None, really. Python syntax is kind of unique. \nie ( taken from: Python tutorial - classes ) \n>>> class Complex:\n... def __init__(self, realpart, imagpart):\n... self.r = realpart\n... self.i = imagpart\n...\n>>> x = Complex(3.0, -4.5)\n>>> x.r, x.i\n(3.0, -4.5)\n\nIt was heavily inspired i... | [
6,
4,
1,
1
] | [] | [] | [
".net",
"python"
] | stackoverflow_0004381806_.net_python.txt |
Q:
Keeping connections alive
Is it possible to keep a client connect (http) to my server alive and return data via that connection when data is available at the server end?
A:
What you are describing is in essence COMET.
A:
I think twisted can handle this kind of thing very well. external link
| Keeping connections alive | Is it possible to keep a client connect (http) to my server alive and return data via that connection when data is available at the server end?
| [
"What you are describing is in essence COMET. \n",
"I think twisted can handle this kind of thing very well. external link\n"
] | [
3,
1
] | [] | [] | [
"apache",
"http",
"javascript",
"jquery",
"python"
] | stackoverflow_0004377872_apache_http_javascript_jquery_python.txt |
Q:
Why is there no speed-up when using pythons multiprocessing for embarassingly parallel problem within a for-loop, with shared numpy data?
I want to speed up an embarassingly parallel problem related to Bayesian Inference. The aim is to infer coefficents u for a set of images x, given a matrix A, such that X = A*U.... | Why is there no speed-up when using pythons multiprocessing for embarassingly parallel problem within a for-loop, with shared numpy data? | I want to speed up an embarassingly parallel problem related to Bayesian Inference. The aim is to infer coefficents u for a set of images x, given a matrix A, such that X = A*U.
X has dimensions mxn, A mxp and U pxn. For each column of X, one has to infer the optimal corresponding column of the coefficients U. In the ... | [
"Every time you create a Process you are creating a new process. If you're doing that within your for loop, then yes, you are starting new processes every time through the loop. It sounds like what you want to do is initialize your Queue and Processes outside of the loop, then fill the Queue inside the loop.\nI've ... | [
6,
3
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0004373131_multiprocessing_python.txt |
Q:
counting a sequence of item, python
The task is to define a function count_vowels(text) that takes a string text, counts the
vowels in text (using a Python dictionary for the counting), and returns the
vowel frequency information as a string.
Example:
>>> count_vowels('count vowels')
'e: 1\nu: 1\no: 2'
>>> print c... | counting a sequence of item, python | The task is to define a function count_vowels(text) that takes a string text, counts the
vowels in text (using a Python dictionary for the counting), and returns the
vowel frequency information as a string.
Example:
>>> count_vowels('count vowels')
'e: 1\nu: 1\no: 2'
>>> print count_vowels('count vowels')
e: 1
u: 1
o: ... | [
"return '\\n'.join( '%s: %s' % item for item in counts.items())\n\n",
"If you are using Python 2.7, try using a counter:\nfrom collections import Counter\ncounts = Counter(c for c in 'count vowels' if c in 'aeoiu')\nfor k, v in counts.iteritems():\n print k, v\n\nThis results in the output:\ne 1\nu 1\no 2\n\nI... | [
2,
2,
1,
1,
0
] | [] | [] | [
"dictionary",
"nltk",
"python"
] | stackoverflow_0004381846_dictionary_nltk_python.txt |
Q:
custom print statement for python function objects
I know that if I write a class, I can definite a custom print function as below.
>>> class F:
... def __str__(self):
... return 'This describes the data of F.'
...
>>> f = F()
>>> print f
This describes the data of F.
But, what if I want to do th... | custom print statement for python function objects | I know that if I write a class, I can definite a custom print function as below.
>>> class F:
... def __str__(self):
... return 'This describes the data of F.'
...
>>> f = F()
>>> print f
This describes the data of F.
But, what if I want to do the same for a function object? For example,
>>> def f():... | [
"Others have suggested doc strings, but a doc string should probably be more descriptive of what the function does. If you want a short attribute describing the function, one of the options below may be what you are looking for:\nOption 1\nAre you saying you want to change the default description of a function obj... | [
8,
3,
2,
0,
0
] | [] | [] | [
"functional_programming",
"python"
] | stackoverflow_0004383178_functional_programming_python.txt |
Q:
How to use traceit to report function input variables in stack trace
I've been using the following code to trace the execution of my programs:
import sys
import linecache
import random
def traceit(frame, event, arg):
if event == "line":
lineno = frame.f_lineno
filename = frame.f_globals["__fil... | How to use traceit to report function input variables in stack trace | I've been using the following code to trace the execution of my programs:
import sys
import linecache
import random
def traceit(frame, event, arg):
if event == "line":
lineno = frame.f_lineno
filename = frame.f_globals["__file__"]
if filename == "<stdin>":
filename = "traceit.py... | [
"The traceit function that you posted can be used to print information as each line of code is executed. If all you need is the function name and arguments when certain functions are called, I would suggest using this trace decorator instead:\nimport functools\n\ndef trace(f):\n '''This decorator shows how the f... | [
3,
2,
1,
0
] | [] | [] | [
"debugging",
"python",
"stack_trace",
"trace"
] | stackoverflow_0002617120_debugging_python_stack_trace_trace.txt |
Q:
Drawing mathematical stuff with Python
I had asked in my previous question for a package that lets me draw circles and arrows with python and it was suggested that I should try out PyQt4.
My problem is that I have tried to find functions that would let me draw such widgets but have been unable to do so.
So my ques... | Drawing mathematical stuff with Python | I had asked in my previous question for a package that lets me draw circles and arrows with python and it was suggested that I should try out PyQt4.
My problem is that I have tried to find functions that would let me draw such widgets but have been unable to do so.
So my question is that if anybody knows how to draw ci... | [
"Using graphviz you can make diagrams like this\n\nusing code like this:\n#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport subprocess\nimport shlex\n\n# dot code based on http://www.graphviz.org/Gallery/directed/fsm.html\ndot=''' \ndigraph finite_state_machine {\n bgcolor=\"#ffffff\"\n r... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004381473_python.txt |
Q:
boost.python argument type mismatch (numpy.int64 -> int)
I'm running into this problem:
Boost.Python.ArgumentError: Python argument types in
Dirichlet.Observe(int, numpy.int64, float)
did not match C++ signature:
Observe(unsigned int, unsigned int, double)
Seems close enough?
After doing some replacement,... | boost.python argument type mismatch (numpy.int64 -> int) | I'm running into this problem:
Boost.Python.ArgumentError: Python argument types in
Dirichlet.Observe(int, numpy.int64, float)
did not match C++ signature:
Observe(unsigned int, unsigned int, double)
Seems close enough?
After doing some replacement, it seems that the middle argument is the problem. How do I c... | [
"You could you try...\nint(numpyint)\n\n"
] | [
3
] | [] | [] | [
"boost_python",
"numpy",
"python"
] | stackoverflow_0004383515_boost_python_numpy_python.txt |
Q:
How come I can't insert into Mongo? It used to work
con = pymongo.Connection(MONGO_DOC_HOST, MONGO_DOC_PORT)
db = con.testdb
datasets = db.datasets
for post in db.datasets.find({"test_set":"xyz"}).sort("num_favs",pymongo.DESCENDING).limit(2):
print post #this works, and it prints fine!
post = {"hi":"abc"}
mo... | How come I can't insert into Mongo? It used to work | con = pymongo.Connection(MONGO_DOC_HOST, MONGO_DOC_PORT)
db = con.testdb
datasets = db.datasets
for post in db.datasets.find({"test_set":"xyz"}).sort("num_favs",pymongo.DESCENDING).limit(2):
print post #this works, and it prints fine!
post = {"hi":"abc"}
mongo_id = datasets.insert(post)
When I do datasets.insert... | [
"are you definitely hitting the same database (\"testdb\") in both cases?\nthe default db in the shell is \"test\"\n"
] | [
1
] | [] | [] | [
"database",
"django",
"mongodb",
"python"
] | stackoverflow_0004382631_database_django_mongodb_python.txt |
Q:
Implementing classes in python
Hey this is one of the classes that I had for homework in my cs class and now i'm playing around with python. I want to learn how to design classes in python and would like to implement this one. It's a relatively straight forward class. Help would be appreciated. Here's the code:
#i... | Implementing classes in python | Hey this is one of the classes that I had for homework in my cs class and now i'm playing around with python. I want to learn how to design classes in python and would like to implement this one. It's a relatively straight forward class. Help would be appreciated. Here's the code:
#include <iostream>
#include <string>
... | [
"Python Tutorial, §9, \"Classes\"\n",
"Some things you will need to know to make the transition:\n\nIn Python, you do the initialization of a class in a method called __init__() (instead of Flight(), or in the class body itself)\nAll instance methods in Python take self as an argument\nTo refer to an instance var... | [
3,
2,
1,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004368364_c++_python.txt |
Q:
Using zeromq in a distributed load pipeline, can I get the address of the last server a message was sent to
If I set up a pipeline which distributes load across a cluster, I would like to log where the messages get sent. This is what I have in mind (python):
import zmq
context = zmq.Context()
socket = context.soc... | Using zeromq in a distributed load pipeline, can I get the address of the last server a message was sent to | If I set up a pipeline which distributes load across a cluster, I would like to log where the messages get sent. This is what I have in mind (python):
import zmq
context = zmq.Context()
socket = context.socket(zmq.DOWNSTREAM)
socket.connect("tcp://127.0.0.1:5000")
socket.connect("tcp://127.0.0.1:6000")
msg = "Hello W... | [
"It think you'll want to use the X(REP|REQ) sockets somewhere in the topology for this. You might want to checkout the monitered queue device:\nhttp://github.com/zeromq/pyzmq/blob/master/zmq/devices.pyx\nAnd for general info have a look at the diagram and explanations of the patterns here too:\nhttp://ipython.scipy... | [
0,
0,
0
] | [] | [] | [
"python",
"zeromq"
] | stackoverflow_0003836554_python_zeromq.txt |
Q:
Passing bool by reference using SWIG and Python
I've wrapped a C++ library API using SWIG, which works well, but I'm stumped by a "bool &" parameter.
The original API looks like this:
void foo(bool & bar);
when I call it from Python, the _wrap.cxx drops out of the wrap process at
int res = SWIG_ConvertPtr(arg... | Passing bool by reference using SWIG and Python | I've wrapped a C++ library API using SWIG, which works well, but I'm stumped by a "bool &" parameter.
The original API looks like this:
void foo(bool & bar);
when I call it from Python, the _wrap.cxx drops out of the wrap process at
int res = SWIG_ConvertPtr(argv[1], &vptr, SWIGTYPE_p_bool, 0);
_v = SWIG_CheckS... | [
"This should work:\n%include <typemaps.i>\n%apply bool & INOUT { bool & bar };\n\nWhenever SWIG sees a bool & bar parameter, it should treat it as an in/out parameter. If you only need it as an output parameter, use OUTPUT.\n"
] | [
2
] | [] | [] | [
"python",
"swig"
] | stackoverflow_0004383719_python_swig.txt |
Q:
Logging in Python with Config File - Using handlers defined in file through code
I am using logging module of python. How can I access the handlers defined in config file from the code. As an example, I have a logger defined and two handlers - one for screen and other for file. I want to use appropriate handler ba... | Logging in Python with Config File - Using handlers defined in file through code | I am using logging module of python. How can I access the handlers defined in config file from the code. As an example, I have a logger defined and two handlers - one for screen and other for file. I want to use appropriate handler based on user preference (whether they want to log on screen or to a file). How can I dy... | [
"Instead of having to dynamically change the config file, just use Logger.addHandler(handler).\nfileHandler = logging.handlers.RotatingFileHandler('file.log', mode='a', maxBytes=10000, backupCount=5)\nlogger = logging.getLogger('netmap')\n\nif LOG_TO_FILE:\n logger.addHandler(fileHandler)\n\nThen to load in form... | [
5,
1,
0
] | [] | [] | [
"logging",
"python",
"python_2.x"
] | stackoverflow_0004375669_logging_python_python_2.x.txt |
Q:
Using Tweepy with Apigee
I am using Tweepy, but I am trying to use it with the api from apigee, but to do so would require me to change auth.py https://github.com/joshthecoder/tweepy/blob/master/tweepy/auth.py it looks like and remake the package some how. Is there anyways to use tweepy with another api? Or anothe... | Using Tweepy with Apigee | I am using Tweepy, but I am trying to use it with the api from apigee, but to do so would require me to change auth.py https://github.com/joshthecoder/tweepy/blob/master/tweepy/auth.py it looks like and remake the package some how. Is there anyways to use tweepy with another api? Or another way to set up Python to use ... | [
"Short version: need to sign requests as if they're going to Twitter but then to route them via Apigee (i.e. a proxy use-case).\nLonger response with links here:\nhttp://support.apigee.com/apigee/topics/using_python_and_apigees_twitter_api_with_oauth\n"
] | [
2
] | [] | [] | [
"apigee",
"python",
"tweepy",
"twitter",
"twitter_oauth"
] | stackoverflow_0004383577_apigee_python_tweepy_twitter_twitter_oauth.txt |
Q:
What could be a reason why a class can't be accessed from within another class's function?
I have 2 classes:
import follow
class User(object):
def __init__(self):
pass
import user
class Follow(object):
def doSomething(self):
u = User()
>> f = Follow()
>> f.doSomething()
>> NameError: glob... | What could be a reason why a class can't be accessed from within another class's function? | I have 2 classes:
import follow
class User(object):
def __init__(self):
pass
import user
class Follow(object):
def doSomething(self):
u = User()
>> f = Follow()
>> f.doSomething()
>> NameError: global name 'User' is not defined
Is this causing a problem because both classes import each other?... | [
"\nu = user.User()\n\nor, alternatively:\n\nfrom user import User\nu = User()\n\n",
"user.py\nclass User(object):\n def __init__(self):\n pass\n\nfollow.py\nfrom user import User\n\nclass Follow(object):\n def doSomething(self):\n u = User()\n\n",
"The problem seems to be that you're are imp... | [
3,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004383850_python.txt |
Q:
What is the point of Python egg files?
When I run python setup.py install django, it generates an egg file.
What is the usefulness of Python egg files?
A:
The "egg" is Python's binary distribution format. It's basically a zipped file with some extra metadata that you can give another Python user. He can "install... | What is the point of Python egg files? | When I run python setup.py install django, it generates an egg file.
What is the usefulness of Python egg files?
| [
"The \"egg\" is Python's binary distribution format. It's basically a zipped file with some extra metadata that you can give another Python user. He can \"install\" and use them. For details on what they are, please refer to http://peak.telecommunity.com/DevCenter/PythonEggs.\nSince it's a \"native\" format, Python... | [
7,
1
] | [] | [] | [
"django",
"egg",
"python"
] | stackoverflow_0004384402_django_egg_python.txt |
Q:
How to use a decorator in class level correctly?
I have a message bus, and a class subscribes many methods to the message bus, for example:
class BookingService(object):
def start(self):
self.msg_bus.login(self.user, self.password)
self.msg_bus.subscribe('/broadcast/aliveResponse', self.handleA... | How to use a decorator in class level correctly? | I have a message bus, and a class subscribes many methods to the message bus, for example:
class BookingService(object):
def start(self):
self.msg_bus.login(self.user, self.password)
self.msg_bus.subscribe('/broadcast/aliveResponse', self.handleAliveResponse)
self.msg_bus.subscribe('/broadca... | [
"Rather than putting it into a list on the instance, put it into a list on the function or class.\nclass BookingService(object):\n\n def subscribe(dest):\n \"\"\"Decorator for subscribing function to destination\n\n \"\"\"\n def callee(func):\n if not hasattr(func, 'subscriptions'... | [
1,
0
] | [] | [] | [
"class",
"decorator",
"python"
] | stackoverflow_0004383702_class_decorator_python.txt |
Q:
SCons in Python
I would like to load SCons in an interactive Python session and enter directives that way as opposed to through an SConstruct or SConscript file. Is this possible? I'm trying to embed SCons functionality into another Python application.
A:
It would appear so,
Just add Scons to your PYTHONPATH an... | SCons in Python | I would like to load SCons in an interactive Python session and enter directives that way as opposed to through an SConstruct or SConscript file. Is this possible? I'm trying to embed SCons functionality into another Python application.
| [
"It would appear so,\n\nJust add Scons to your PYTHONPATH and\n import whatever you need. Copy the\n appropriate bits out of scons' main\n that suit you - Scons/Script/Main.py -\n or just run its main from the\n appropriate folder.\n\nhttp://osdir.com/ml/programming.tools.scons.user/2005-03/msg00058.html\n"
] | [
4
] | [] | [] | [
"python",
"scons"
] | stackoverflow_0004384420_python_scons.txt |
Q:
Is this a Pythonic API design strategy?
Here's a prelude to the question I'm asking: I've taken to building a gateway agnostic payment API in Python for my company. At the moment I've only written code to support Authorize.net and wanted some feedback on the clarity of my API design from Python programmers with a ... | Is this a Pythonic API design strategy? | Here's a prelude to the question I'm asking: I've taken to building a gateway agnostic payment API in Python for my company. At the moment I've only written code to support Authorize.net and wanted some feedback on the clarity of my API design from Python programmers with a bit more experience than I.
I chose to roll m... | [
"Deeply nested dictionaries may not be unusual in Python, and maybe they then are \"Pythonic\" but it shure as heck isn't a good idea, so I would claim that it isn't Pythonic.\nI'd make a nested hierarcy of classes instead. That would be much clearer, IMO, and also have the benefit of enabling you to do type checki... | [
2
] | [] | [] | [
"api",
"authorize.net",
"payment_processing",
"python"
] | stackoverflow_0004380749_api_authorize.net_payment_processing_python.txt |
Q:
(Py)GTK: How can I force my window to be repainted / call expose-event?
Currently I'm drawing some things in a subclass of DrawingArea, where I get a cairo context inside an expose-event and call a draw method from there. (according to some PyGTK tutorial I found)
I'm used to doing a repaint() with java, but how c... | (Py)GTK: How can I force my window to be repainted / call expose-event? | Currently I'm drawing some things in a subclass of DrawingArea, where I get a cairo context inside an expose-event and call a draw method from there. (according to some PyGTK tutorial I found)
I'm used to doing a repaint() with java, but how can I get the same effect here?
| [
"Using queue_draw (which is actually defined for each widget) as you suggested is the correct way for doing it asynchronously. The documentation clearly states this:\n\ngtk_widget_draw is deprecated and should not be used in newly-written code.\n In GTK+ 1.2, this function would immediately render the region area ... | [
6,
0
] | [] | [] | [
"drawing",
"gtk",
"pygtk",
"python"
] | stackoverflow_0004383614_drawing_gtk_pygtk_python.txt |
Q:
Different versions of the same script with packages on the same python installation
I have a script, which contains some packages/modules. Now, the development and the production environment run on the same server on the same python installation (version 2.6). What is the best way to manage my script so that it wo... | Different versions of the same script with packages on the same python installation | I have a script, which contains some packages/modules. Now, the development and the production environment run on the same server on the same python installation (version 2.6). What is the best way to manage my script so that it would be easy to change the development or the production version of the script (eg install... | [
"Your question is not totally clear to me. \nDo you want to deploy different branches of your application to your development and productions servers? It's a version control/deployment question then. \nOn the other hand, if you want to install the package (i.e. your application) into different Python \"environments... | [
1
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0004384743_installation_python.txt |
Q:
Iterating through Expando's Dynamic properties in Django Templates
I'm trying to iterate through an Expando-Model's dynamic properties in order to output them all. Is there a way of doing this other than creating your own method like such:
class Event(db.Expando):
platform = db.ReferenceProperty(Platform)
... | Iterating through Expando's Dynamic properties in Django Templates | I'm trying to iterate through an Expando-Model's dynamic properties in order to output them all. Is there a way of doing this other than creating your own method like such:
class Event(db.Expando):
platform = db.ReferenceProperty(Platform)
date = db.DateTimeProperty()
def getValues(self):
return se... | [
"You can use a db.Model's 'dynamic_properties' method to retrieve an Expando's properties, in the same format as the 'properties' method (as documented under the Model class)\nRemember that those functions don't return a property's value, though... 'properties' returns a dictionary of property names mapped to their... | [
0
] | [] | [] | [
"expando",
"google_app_engine",
"iteration",
"python",
"templates"
] | stackoverflow_0003389236_expando_google_app_engine_iteration_python_templates.txt |
Q:
One python multiprocess errors
I have one multprocess demo here, and I met some problems with it. Researched for a night, I cannot resolve the reason.
Any one can help me?
I want to have one parent process acts as producer, when there are tasks come, the parent can fork some children to consume these tasks. The pa... | One python multiprocess errors | I have one multprocess demo here, and I met some problems with it. Researched for a night, I cannot resolve the reason.
Any one can help me?
I want to have one parent process acts as producer, when there are tasks come, the parent can fork some children to consume these tasks. The parent monitors the child, if any one ... | [
"Main proc is waiting for all child procs to be terminated before exits itself so there's a blocking call (i.e. wait4) registered as at_exit handles. The signal you sent interrupts that blocking call thus the stack trace.\nThe thing I'm not clear about is that if the signal sent to child would be redirected to the ... | [
1
] | [] | [] | [
"multiprocess",
"python"
] | stackoverflow_0004030277_multiprocess_python.txt |
Q:
Tkinter: How to make a system tray application?
i have a small application. I want my target users(windows,linux) to be able to start and exit the application from the system tray. I intend to use Tkinter because of its low footprint but, i dont know how to implement it.
Can tkinter do this or are there better al... | Tkinter: How to make a system tray application? | i have a small application. I want my target users(windows,linux) to be able to start and exit the application from the system tray. I intend to use Tkinter because of its low footprint but, i dont know how to implement it.
Can tkinter do this or are there better alternatives. I need a GUI library that won't change my... | [
"I don't know any direct examples but I found a TCL/Tk extension to use the systray over here http://wiki.tcl.tk/4090 and a page on the wiki giving information on how to use TCL/Tk extensions from Tkinter. \nOn a more general note, you might want to consider using a more \"advanced\" toolkit (like wx) that provides... | [
15
] | [] | [] | [
"python",
"system",
"tkinter",
"tray",
"user_interface"
] | stackoverflow_0004385656_python_system_tkinter_tray_user_interface.txt |
Q:
Cloned list seems to be functioning as an alias, even though explicitly declared as a a clone
I am having some trouble with the following script. It should make 3 copies of the following list so that they can be modified independently. However, it seems to be creating 3 clones of the same list, and when you modify... | Cloned list seems to be functioning as an alias, even though explicitly declared as a a clone | I am having some trouble with the following script. It should make 3 copies of the following list so that they can be modified independently. However, it seems to be creating 3 clones of the same list, and when you modify one you modify them all. Here is the function:
def calculateProportions(strategies,proportions):
... | [
"You're only performing a shallow copy when you clone columns, i.e. the list is cloned but its items are not, so the same item references are used in both combinations and columns.\nYou can use the copy.deepcopy() function to perform a deep copy of the object:\ndef calculateProportions(strategies,proportions):\n ... | [
4,
0,
0,
0,
0
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0004385617_nested_lists_python.txt |
Q:
Distance from str to the end (python)
Ok, so I'm trying to get the distance in a str (called bigstr), from a small other variable called smallstr until it ends.
For example:
bigstr = 'What are you saying?'
smallstr = 'you'
then
distance = 8
I'm trying to use re, but I'm a total noob with this library.
A:
dista... | Distance from str to the end (python) | Ok, so I'm trying to get the distance in a str (called bigstr), from a small other variable called smallstr until it ends.
For example:
bigstr = 'What are you saying?'
smallstr = 'you'
then
distance = 8
I'm trying to use re, but I'm a total noob with this library.
| [
"distance = len(bigstr) - (bigstr.index(smallstr) + len(smallstr))\n\n",
"I am not sure if you need re for that, following should suffice:\nUsing split:\n>>> bigstr = 'What are you saying?'\n>>> smallstr = 'you'\n>>> bigstr.split(smallstr)\n['What are ', ' saying?']\n>>> words = bigstr.split(smallstr)\n>>> len(wo... | [
5,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0004385755_python.txt |
Q:
Connecting to .NET Sslstream x.509 socket with Python or Ruby or Perl
I have a weird requirement. I am trying to communicate with a server written in C#. It looks like this basically:
SslStream sslStream = new SslStream(client.GetStream(), true,
ValidateServerCertificate,
... | Connecting to .NET Sslstream x.509 socket with Python or Ruby or Perl | I have a weird requirement. I am trying to communicate with a server written in C#. It looks like this basically:
SslStream sslStream = new SslStream(client.GetStream(), true,
ValidateServerCertificate,
SelectLocalCertificate);
sslStream.Authentica... | [
"You can simplify your SslStream constructor call:\nSslStream sslStream = new SslStream(client.GetStream()); \nsslStream.AuthenticateAsServer(_pushCert);\n\nThis server sends _pushCert and does not expect the client to send a certificate back. The server needs the private key for the certificate to make the SSL con... | [
0
] | [] | [] | [
"c#",
"python",
"ssl",
"sslstream"
] | stackoverflow_0004262648_c#_python_ssl_sslstream.txt |
Q:
Finding data gaps with bit masking
I'm faced with a problem of finding discontinuities (gaps) of a given length in a sequence of numbers. So, for example, given [1,2,3,7,8,9,10] and a gap of length=3, I'll find [4,5,6]. If the gap is length=4, I'll find nothing. The real sequence is, of course, much longer. I've s... | Finding data gaps with bit masking | I'm faced with a problem of finding discontinuities (gaps) of a given length in a sequence of numbers. So, for example, given [1,2,3,7,8,9,10] and a gap of length=3, I'll find [4,5,6]. If the gap is length=4, I'll find nothing. The real sequence is, of course, much longer. I've seen this problem in quite a few posts, a... | [
"Find the differences between adjacent numbers, and then look for a difference that's large enough. We find the differences by constructing two lists - all the numbers but the first, and all the numbers but the last - and subtracting them pairwise. We can use zip to pair the values up.\ndef find_gaps(numbers, gap_s... | [
2,
2,
1,
1,
1
] | [] | [] | [
"arrays",
"bitmask",
"performance",
"python"
] | stackoverflow_0004375310_arrays_bitmask_performance_python.txt |
Q:
libpcap for Python2.6 (Windows)
Currently want to use libpcap under Python2.6 in windows.
I tried Pypcap, but it only have binary build for python 2.5 or older, pylibpcap seems doesn't have any binary build.
I also can't install them from source, seems that I have to build libpcap first.
I want to develop an app, ... | libpcap for Python2.6 (Windows) | Currently want to use libpcap under Python2.6 in windows.
I tried Pypcap, but it only have binary build for python 2.5 or older, pylibpcap seems doesn't have any binary build.
I also can't install them from source, seems that I have to build libpcap first.
I want to develop an app, and then pack it using py2exe, then I... | [
"There are two python libpcap modules that you can use. \n\nhttp://oss.coresecurity.com/projects/pcapy.html\nhttp://pylibpcap.sourceforge.net/\n\n"
] | [
0
] | [] | [] | [
"libpcap",
"python"
] | stackoverflow_0004384451_libpcap_python.txt |
Q:
How to do date comparison
How can I compare two dates in python to determine if the second one is after the first one?
A:
Hint: datetime.strptime()
A:
def dateAfter(d1, d2):
from datetime import date
d1list = d1.split(".")
day1 = int(d1list[0])
month1 = int(d1list[1])
year1 = int(d1list[2])... | How to do date comparison | How can I compare two dates in python to determine if the second one is after the first one?
| [
"Hint: datetime.strptime()\n",
"def dateAfter(d1, d2):\n from datetime import date\n d1list = d1.split(\".\")\n day1 = int(d1list[0])\n month1 = int(d1list[1])\n year1 = int(d1list[2])\n\n d2list = d2.split(\".\")\n day2 = int(d2list[0])\n month2 = int(d2list[1])\n year2 = int(d2list[2]... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004386617_python.txt |
Q:
Python list.remove() seems to malfunction
fileHandle = open(filedir, 'r')
content = fileHandle.read().split('\n')
for e in content:
if (e == '' or (e[0] != r"@"):
content.remove(e)
fileHandle.close()
So, what I'm trying to do here is open a file with some text and split it into lines, and then remove ... | Python list.remove() seems to malfunction | fileHandle = open(filedir, 'r')
content = fileHandle.read().split('\n')
for e in content:
if (e == '' or (e[0] != r"@"):
content.remove(e)
fileHandle.close()
So, what I'm trying to do here is open a file with some text and split it into lines, and then remove those lines that doesn't start with @. But inst... | [
"Never remove items of a list while iterating over it.\nWhy not just do the following:\nwith open(filedir) as f:\n lines = [line.rstrip(\"\\r\\n\") for line in f if line.startswith(\"@\")]\n\n",
"Don't modify a container while you're iterating over it.\nYou're over-complicating this in many ways: you don't nee... | [
3,
2,
1,
0
] | [] | [] | [
"file",
"python",
"string"
] | stackoverflow_0004387015_file_python_string.txt |
Q:
Import error in python
In file1.py:
def test1():
print "hi"
In file2.py:
from file1 import test1
def test2():
print "hello"
test1()
test2()
Output:
hi
hello
Now in file 1 if i include test2 i get the following error:
from file2 import test2
de... | Import error in python | In file1.py:
def test1():
print "hi"
In file2.py:
from file1 import test1
def test2():
print "hello"
test1()
test2()
Output:
hi
hello
Now in file 1 if i include test2 i get the following error:
from file2 import test2
def test1():
print "hi"
... | [
"This is a circular import problem. You are importing file2 from file1 and then at the top level of file2, importing file1 again. This means that 1 cannot load unless you import 2 and 2 cannot load unless you import `1.\nAs for how to make it work, can you explain what you want to do? Why don't you just put both th... | [
4,
2
] | [] | [] | [
"import",
"python",
"python_import"
] | stackoverflow_0004387517_import_python_python_import.txt |
Q:
problem executing Javascript from a python cgi
I'm running a Python program on a server and want to provide a client side interface. I'm using a simple web server (from the O'Reilly Programming Python book).
I can generate HTML pages without problems. However now I want to generate a page which includes some Jav... | problem executing Javascript from a python cgi | I'm running a Python program on a server and want to provide a client side interface. I'm using a simple web server (from the O'Reilly Programming Python book).
I can generate HTML pages without problems. However now I want to generate a page which includes some JavaScript to validate user input on the client before ... | [
"Your web server thinks that FormChecks.js is meant to be executed as a CGI script, which of course it's not. Move it outside of cgi-bin/ and change the path in your script tag accordingly. You could also try removing the executable bit from it instead.\n",
"What are all those backticks for?\nThe error seems to b... | [
3,
0,
0
] | [] | [] | [
"cgi",
"javascript",
"python"
] | stackoverflow_0004387146_cgi_javascript_python.txt |
Q:
Basic example of saving & retrieving a relationship in Flask with SQLAlchemy
I'm trying to glue Flask and SQLAlchemy together but with little luck. I'm following the example from the official Flask page.
Using the console, I can create & retrieve individual users and posts, but can't do stuff like user.posts to g... | Basic example of saving & retrieving a relationship in Flask with SQLAlchemy | I'm trying to glue Flask and SQLAlchemy together but with little luck. I'm following the example from the official Flask page.
Using the console, I can create & retrieve individual users and posts, but can't do stuff like user.posts to get the users posts.
from flask import Flask
from flaskext.sqlalchemy import SQLAlc... | [
"To get the users' posts, you need to set up a relationship between Users and Posts:\nclass User:\n # ...\n posts = relationship(child='Post', backref='user')\n\n"
] | [
4
] | [] | [] | [
"flask",
"python",
"sqlalchemy"
] | stackoverflow_0004386954_flask_python_sqlalchemy.txt |
Q:
where python saves the result of the last operation?
Where does Python save the result of the last operation?
For example, If the last operation was math.sqrt(9), where does Python save the value 3.0?
Or if the last operation was "hello " + "world!", where is the value 'hello world!' saved?
I want to approach thi... | where python saves the result of the last operation? | Where does Python save the result of the last operation?
For example, If the last operation was math.sqrt(9), where does Python save the value 3.0?
Or if the last operation was "hello " + "world!", where is the value 'hello world!' saved?
I want to approach this from a C program (using Python's C API) and pass this va... | [
"Python itself does not save the result of the last operation. The Python REPL saves the last result in _, but you would not be using the REPL in this situation.\n",
"It doesn't.\nIt sounds like you want to call Python code from C, and use the result in the rest of the C code.\nWhat you do is write a function in ... | [
6,
6
] | [] | [] | [
"api",
"c",
"python"
] | stackoverflow_0004387579_api_c_python.txt |
Q:
Monitoring files with twisted
Is it possible to write a Twisted application to monitor addtion of new files/folders to a specific folder? If yes, could someone point me to some code/link trying to do it, or give an idea how to do that?
A:
On Linux, you can have inotify with nice Twisted integration.
Hopefully so... | Monitoring files with twisted | Is it possible to write a Twisted application to monitor addtion of new files/folders to a specific folder? If yes, could someone point me to some code/link trying to do it, or give an idea how to do that?
| [
"On Linux, you can have inotify with nice Twisted integration.\nHopefully someday there will be something similar for Windows and perhaps *BSD (based on kqueue), but for now Twisted only ships with support for this on Linux.\n",
"You do not need twisted, but of course you can integrate it. Basically you need yo u... | [
4,
1,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0004388277_python_twisted.txt |
Q:
Python Regex to parse apart Blackberry browser user agent
I need to parse apart blackberry browser user agents so I can get what device and version it is using python 2.5. For example:
BlackBerry9630/4.7.1.65 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/-1,gzip(gfe),gzip(gfe)
In the above user agent I would l... | Python Regex to parse apart Blackberry browser user agent | I need to parse apart blackberry browser user agents so I can get what device and version it is using python 2.5. For example:
BlackBerry9630/4.7.1.65 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/-1,gzip(gfe),gzip(gfe)
In the above user agent I would like to gather the following groups:
Browser: Blackberry
Devic... | [
"Something like this will work for your case, but not necessarily all cases:\n'^(\\D*)(\\d*)/(\\d*)\\.(\\d*)\\.'\n\n\\D means \"any character that's not a decimal digit\", and \\d means \"any decimal digit\".\n",
"browser, version = useragent.split()[0].split(\"/\")\nbrowsername = re.findall(r\"[a-zA-Z]+\", brows... | [
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004388323_python_regex.txt |
Q:
Python "safe" eval (string to bool/int/float/None/string)
I'm making a webapp that does some data processing, so I frequently find myself parsing strings (from an URL or a text file) into Python values.
I use a function that is "kind of" a safer version of eval (except that if it can't read the string, it stays a ... | Python "safe" eval (string to bool/int/float/None/string) | I'm making a webapp that does some data processing, so I frequently find myself parsing strings (from an URL or a text file) into Python values.
I use a function that is "kind of" a safer version of eval (except that if it can't read the string, it stays a string):
def str_to_value(string):
for atom in (True, False... | [
"ast.literal_eval()\n>>> ast.literal_eval('{False: (1, 0x2), True: [3.14, 04, 0b101], None: (\"6\", u\"7\", r\\'8\\')}')\n{False: (1, 2), True: [3.1400000000000001, 4, 5], None: ('6', u'7', '8')}\n\n"
] | [
29
] | [] | [] | [
"parsing",
"python",
"type_conversion"
] | stackoverflow_0004388626_parsing_python_type_conversion.txt |
Q:
improving stack trace hook in python
All,
I have a question similar to question 2617120, found here:
how to use traceit to report function input variables
where the questioner wanted pointers on how to make python printout function parameters when they were executed via a tracing hook.
I'm looking for something v... | improving stack trace hook in python | All,
I have a question similar to question 2617120, found here:
how to use traceit to report function input variables
where the questioner wanted pointers on how to make python printout function parameters when they were executed via a tracing hook.
I'm looking for something very similar to this but with a twist. Inst... | [
"Here's a quick hack that might give you something of a start, given a line of text in line and the current stack frame in frame (this is meant to be an inner function of traceit by the way).\nimport re\nfrom types import *\n\ndef interpolatevar(matchobj):\n excludetypes = set((NoneType, TypeType, FunctionType, ... | [
0
] | [] | [] | [
"debugging",
"printstacktrace",
"python",
"stack_trace",
"trace"
] | stackoverflow_0004383895_debugging_printstacktrace_python_stack_trace_trace.txt |
Q:
How to implement a two way jsonrpc + twisted server/client
Hello I am working on develop a rpc server based on twisted to serve several microcontrollers which make rpc call to twisted jsonrpc server. But the application also required that server send information to each micro at any time, so the question is how co... | How to implement a two way jsonrpc + twisted server/client | Hello I am working on develop a rpc server based on twisted to serve several microcontrollers which make rpc call to twisted jsonrpc server. But the application also required that server send information to each micro at any time, so the question is how could be a good practice to prevent that the response from a remot... | [
"You need to add a enough information to each message so that the recipient can determine how to interpret it. Your requirements sounds very similar to those of AMP, so you could either use AMP instead or use the same structure as AMP to identify your messages. Specifically:\n\nIn requests, put a particular key -... | [
2
] | [] | [] | [
"json_rpc",
"microcontroller",
"python",
"twisted"
] | stackoverflow_0004387477_json_rpc_microcontroller_python_twisted.txt |
Q:
Load list with content of object
I have an object that can't be dumped by simplejson, so I need to create a list from it first. Currently this is what I'm using:
messages = h.flash.pop_messages()
items = []
for message in messages:
item = {}
item['category'] = message.category
i... | Load list with content of object | I have an object that can't be dumped by simplejson, so I need to create a list from it first. Currently this is what I'm using:
messages = h.flash.pop_messages()
items = []
for message in messages:
item = {}
item['category'] = message.category
item['message'] = message.message
... | [
"items = [{'category': m.category, 'message': m.message}\n for m in h.flash.pop_messages()]\n\n",
"If you can, then simply get message to inherit from object\nobject provides a __dict__ attribute which is a dictionary of all instance attributes of your object (and not class attributes or inherited attributes). U... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004389046_python.txt |
Q:
Python Regex to parse apart android user agent device name
I'm working on parsing apart Android user agents, with Python 2.5, and so far I've been able to figure out a regex which works for "most" android user agents that gathers the major and minor version.
(?P<browser>Android) (?P<major_version>\d*).(?P<minor_ve... | Python Regex to parse apart android user agent device name | I'm working on parsing apart Android user agents, with Python 2.5, and so far I've been able to figure out a regex which works for "most" android user agents that gathers the major and minor version.
(?P<browser>Android) (?P<major_version>\d*).(?P<minor_version>\d*)
The above regex works for the example below:
Mozilla... | [
"Try this:\n(?P<browser>Android) (?P<major_version>\\d*)\\.(?P<minor_version>\\d*);[^;]*;(?P<device>[ \\w]+) Build\\/\n\n",
"(?P<browser>Android)\\s(?P<major_version>\\d+)\\.(?P<minor_version>\\d+);[^;]*;\\s(?P<device>.+)\\sBuild\n\n"
] | [
2,
1
] | [] | [] | [
"parsing",
"python",
"regex",
"user_agent"
] | stackoverflow_0004389407_parsing_python_regex_user_agent.txt |
Q:
cookielib: How to save Python cookies and load it?
I am using CentOS 5.5 and Python.
The following code works perfectly,
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : 'myname', 'password' : '123456'})
resp = opener.open('http:/... | cookielib: How to save Python cookies and load it? | I am using CentOS 5.5 and Python.
The following code works perfectly,
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : 'myname', 'password' : '123456'})
resp = opener.open('http://www.example.com/signin.html', login_data)
However, I w... | [
"cookielib defines a separate FileCookieJar class that has the functionality you're looking for.\n"
] | [
0
] | [] | [] | [
"command_line",
"cookies",
"linux",
"python"
] | stackoverflow_0004389487_command_line_cookies_linux_python.txt |
Q:
Noob Question: How to import some imodule in Python?
I am using Python 2.5 on CentOS 5.5
I have got a file called MultipartPostHandler.py, I am supposed to use it like this:
import MultipartPostHandler
But I dont know where should I put the file MultipartPostHandler.py so I can use it. Thanks a lot!
A:
http://d... | Noob Question: How to import some imodule in Python? | I am using Python 2.5 on CentOS 5.5
I have got a file called MultipartPostHandler.py, I am supposed to use it like this:
import MultipartPostHandler
But I dont know where should I put the file MultipartPostHandler.py so I can use it. Thanks a lot!
| [
"http://docs.python.org/tutorial/modules.html#the-module-search-path\n\nWhen a module named spam is imported,\nthe interpreter searches for a file\nnamed spam.py in the current\ndirectory, and then in the list of\ndirectories specified by the\nenvironment variable PYTHONPATH. This\nhas the same syntax as the shell\... | [
3,
2,
1,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0004389813_linux_python.txt |
Q:
Replacing variable text in between two known elements
s = """Comment=This is a comment
Name=Frank J. Lapidus
GenericName=Some name"""
replace_name = "Dr. Jack Shephard"
I have some text in a file and have been trying to figure out how to search and replace a line so Name=Frank J. Lapidus becomes Name=Dr. Jack She... | Replacing variable text in between two known elements | s = """Comment=This is a comment
Name=Frank J. Lapidus
GenericName=Some name"""
replace_name = "Dr. Jack Shephard"
I have some text in a file and have been trying to figure out how to search and replace a line so Name=Frank J. Lapidus becomes Name=Dr. Jack Shephard
How could I do this in Python? Edited: (BTW, the sec... | [
"Use string.replace (documented under http://docs.python.org/library/stdtypes.html#string-methods):\n>>> s = \"\"\"Comment=This is a comment\n... Name=Frank J. Lapidus\n... GenericName=Some name\"\"\"\n>>> replace_name = \"Dr. Jack Shephard\"\n>>> s.replace(\"Frank J. Lapidus\", replace_name)\n'Comment=This is a co... | [
1,
0,
0
] | [] | [] | [
"python",
"replace",
"text"
] | stackoverflow_0004388365_python_replace_text.txt |
Q:
PyTable Column Order
Is there a way to create a PyTable with a specific column order?
By default, the columns are alphabetically ordered when using both dictionary or class for schema definition for the call to createTable(). My need is to establish a specific order and then use numpy.genfromtxt() to read and stor... | PyTable Column Order | Is there a way to create a PyTable with a specific column order?
By default, the columns are alphabetically ordered when using both dictionary or class for schema definition for the call to createTable(). My need is to establish a specific order and then use numpy.genfromtxt() to read and store my data from text. Unfor... | [
"See:\nIs there a way to store PyTable columns in a specific order?\n",
"For example, assuming text file is named mydata.txt and is organized as follows:\ntime(row1) bVar(row1) dVar(row1) aVar(row1) cVar(row1)\ntime(row2) bVar(row2) dVar(row2) aVar(row2) cVar(row2)\n...\ntime(rowN) bVar(rowN) dVar(rowN... | [
4,
0
] | [] | [] | [
"numpy",
"pytables",
"python"
] | stackoverflow_0003940679_numpy_pytables_python.txt |
Q:
best version control system for personal/home use when developing with eclipse and python/django
I am working on a small django project at home. I would like to install and use a small version control system for personal use for free. I don't want to use a web service like github because I am not always connected.... | best version control system for personal/home use when developing with eclipse and python/django | I am working on a small django project at home. I would like to install and use a small version control system for personal use for free. I don't want to use a web service like github because I am not always connected. I would like to have the VCS server/daemon installed and use it at my home pc (windows 7).
I would a... | [
"GIT is built in a way that you can use it 'offline': doing commit, reverting change, browsing history.\nI don't see any advantage in your case to use SVN instead of GIT (you can host your own GIT server, no need to use github.com)\nhttp://book.git-scm.com/4_setting_up_a_public_repository.html\nThere are also GIT a... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"eclipse",
"python",
"version_control"
] | stackoverflow_0004213457_eclipse_python_version_control.txt |
Q:
Django: chaining 'startswith' and 'iexact' query filters?
I want to do do a case-insensitive startswith query in Django:
books = Book.objects.filter(title__iexact__startswith=query)
But I get the following error message:
FieldError at /names/
Join on field 'title' not permitted
How can I specify a case-ins... | Django: chaining 'startswith' and 'iexact' query filters? | I want to do do a case-insensitive startswith query in Django:
books = Book.objects.filter(title__iexact__startswith=query)
But I get the following error message:
FieldError at /names/
Join on field 'title' not permitted
How can I specify a case-insensitive startswith in Django?
| [
"istartswith\n"
] | [
29
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0004390227_django_django_queryset_python.txt |
Q:
Own params to PeriodicTask run() method in Celery
I am writing a small Django application and I should be able to create
for each model object its periodical task which will be executed with
a certain interval. I'm use for this a Celery application, but i can't understand one thing:
class ProcessQueryTask(Periodic... | Own params to PeriodicTask run() method in Celery | I am writing a small Django application and I should be able to create
for each model object its periodical task which will be executed with
a certain interval. I'm use for this a Celery application, but i can't understand one thing:
class ProcessQueryTask(PeriodicTask):
run_every = timedelta(minutes=1)
def run(... | [
"This was answered wonderfully by Ask Solem in his response to your question on the celery-users Google group.\nPeriodic tasks doesn't use arguments, so you need to make several\nclasses or make a periodic task that processes more than one \"model\".\nE.g.:\nfrom celery.task import PeriodicTask\nfrom celery.decorat... | [
5
] | [] | [] | [
"celery",
"python",
"rabbitmq"
] | stackoverflow_0002850017_celery_python_rabbitmq.txt |
Q:
merging 2 hdf5 files with pytables
ptrepack is almost what i want except that it only has the options to overwrite or ignore duplicate paths. the example below illustrates what i want to happen with the structures
input file one
/ (RootGroup) ''
/data_set_name (Group) 'group of images files'
/data_set_name_Set (EA... | merging 2 hdf5 files with pytables | ptrepack is almost what i want except that it only has the options to overwrite or ignore duplicate paths. the example below illustrates what i want to happen with the structures
input file one
/ (RootGroup) ''
/data_set_name (Group) 'group of images files'
/data_set_name_Set (EArray(7913, 128)) ''
/data_set_name/image... | [
"You mean to automagically enlarge datasets with the same paths? Hmmm, I haven't thought about this, but looks like a nice feature to implement (although only valid for enlargeable arrays). Added a ticket:\nhttp://pytables.org/trac/ticket/325\n"
] | [
1
] | [] | [] | [
"hdf5",
"merging_data",
"pytables",
"python"
] | stackoverflow_0004363010_hdf5_merging_data_pytables_python.txt |
Q:
Working with Multiple objects with foreign key relationship in inlineform_set
I have the following Django models:
class Order:
order_id
order_date
class OrderItem
models.ForeignKey(Order)
models.ForeignKey(Product)
quantity
unit_price
To explain, an order can contain multiple order items.
... | Working with Multiple objects with foreign key relationship in inlineform_set | I have the following Django models:
class Order:
order_id
order_date
class OrderItem
models.ForeignKey(Order)
models.ForeignKey(Product)
quantity
unit_price
To explain, an order can contain multiple order items.
Now, I want to create a template which would allow the creation of an order. So in ... | [
"You can't have multiply nested formsets. But you don't need them here. All you really want is for the orderitem form to have a product field, which is a select box of all the available products and their codes. And you get that automatically, as long as you define the __unicode__ method of the Product model to ret... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004389439_django_python.txt |
Q:
Django + Google Federated Login
I would like to enable the visitors of my website to login using their Google Accounts instead of having to sign up and create a new one.
A few things:
I am NOT using the Django authentication framework, instead, I do my own authentication and keep information about users in my own... | Django + Google Federated Login | I would like to enable the visitors of my website to login using their Google Accounts instead of having to sign up and create a new one.
A few things:
I am NOT using the Django authentication framework, instead, I do my own authentication and keep information about users in my own set of tables
consequently, various ... | [
"I think your problem stems from a basic misunderstanding of how OpenID and/or OAuth work.\nIt looks like you just want authentication, so let's stick to OpenID for now. You are correct to look at existing libraries. python-openid is the one to use if you only need OpenID and not OAuth, and you are not using Djan... | [
10,
3
] | [] | [] | [
"django",
"openid",
"python",
"single_sign_on"
] | stackoverflow_0004307677_django_openid_python_single_sign_on.txt |
Q:
playing WAV files in python using Snack
So I downloaded Snack and put the Snacklib in python/tcl and put the tkSnack.py into python/Lib but i still dont get any sound. I'm not getting any errors but im still not getting any sound.Here's my code...
from Tkinter import *
from tkSnack import *
root = Tk()
tkSnack.... | playing WAV files in python using Snack | So I downloaded Snack and put the Snacklib in python/tcl and put the tkSnack.py into python/Lib but i still dont get any sound. I'm not getting any errors but im still not getting any sound.Here's my code...
from Tkinter import *
from tkSnack import *
root = Tk()
tkSnack.initializeSnack(root)
snd = Sound()
snd.rea... | [
"Shouldn't you be adding the mainloop for tk?\nfrom Tkinter import *\nfrom tkSnack import *\n\nroot = Tk()\n\ntkSnack.initializeSnack(root)\n\nsnd = Sound() \nsnd.read('ex1.wav') <--- Also good to give full path to file\nsnd.play()\nroot.mainloop() <------ main loop \n\nSee the manual, it suggests other ways of... | [
1
] | [] | [] | [
"python",
"tkinter",
"wav"
] | stackoverflow_0004390527_python_tkinter_wav.txt |
Q:
Named Pipes between C# and Python
I'm trying to create a two-way communication channel between two programs (one in Python and another in C#)
When I create a named pipe between two C# programs or two Python programs, everything is OK, but when I try to (for example) connect to the C# server from Python code, it do... | Named Pipes between C# and Python | I'm trying to create a two-way communication channel between two programs (one in Python and another in C#)
When I create a named pipe between two C# programs or two Python programs, everything is OK, but when I try to (for example) connect to the C# server from Python code, it does not work:
C# code:
NamedPipeServerSt... | [
"According to MS, ConnectNamedPipe is the \"server-side function for accepting a connnection\". That's why it never returns - it's waiting for a connection from a client. Here's some sample code showing C# as the server and python as the client:\nC#:\nusing (var server = new NamedPipeServerStream(\"Demo\"))\n{\n ... | [
10,
1,
0
] | [] | [] | [
"c#",
"named_pipes",
"python",
"windows"
] | stackoverflow_0001749001_c#_named_pipes_python_windows.txt |
Q:
How to take a function as an argument? (Python)
I'm writing a program to calculate the volume of a solid of rotation. The first step of this is to calculate an integral. I'm using scipy.integrate for this, but I can't figure out the best way to have a equation (like x=x**2 input at the command line. I was original... | How to take a function as an argument? (Python) | I'm writing a program to calculate the volume of a solid of rotation. The first step of this is to calculate an integral. I'm using scipy.integrate for this, but I can't figure out the best way to have a equation (like x=x**2 input at the command line. I was originally planning on adding an argument 'with respect to: x... | [
"If there are absolutely no concerns about security risks from letting the user run arbitrary Python code, then you can use eval to create a callable object:\nvolume(eval('lambda x: %s' % args.equation), args.a, args.b)\n\n",
"You should be able to use eval() on the string you get from your arguments:\n>>> f = ev... | [
6,
2
] | [] | [] | [
"argparse",
"input",
"lambda",
"python",
"scipy"
] | stackoverflow_0004390737_argparse_input_lambda_python_scipy.txt |
Q:
recursive function
I'm trying to write a recursive function which take an integer ,n, and give all the even number to zero and then every number to n...
this is what I have so far
def kaboom(n):
if n>=0:
if n%2==0:
print n,
print kaboom(n-2),
else:
n=n-1
p... | recursive function | I'm trying to write a recursive function which take an integer ,n, and give all the even number to zero and then every number to n...
this is what I have so far
def kaboom(n):
if n>=0:
if n%2==0:
print n,
print kaboom(n-2),
else:
n=n-1
print n,
print... | [
"Print the even numbers on the way \"down\" through the recursion, and print each number on the way \"back\", reducing by 1 each time. Use , after the print statement to follow the number with a space instead of a newline. Don't return a value and don't print a returned value.\ndef kaboom(n):\n if (n % 2) == 0: ... | [
8,
2,
1
] | [
"I think you need 2 recursive functions (in VB.Net because I don't know python) :\nFunction AllNumbers(ByVal n As Integer) As String\n If n > 0 Then\n Return AllNumbers(n - 1) & \" \" & n\n Else\n Return \"\"\n End If\nEnd Function\n\nFunction EvenNumbers(ByVal n As Integer) As String\n If... | [
-2
] | [
"python",
"recursion"
] | stackoverflow_0004389581_python_recursion.txt |
Q:
Python different functions depending on input
I wrote a program to solve the problems for my physics chapter which takes all the given data and does everything it can with it. I used a long string of if statements to check which functions are safe to call (the functions themselves are not safe), but I feel like th... | Python different functions depending on input | I wrote a program to solve the problems for my physics chapter which takes all the given data and does everything it can with it. I used a long string of if statements to check which functions are safe to call (the functions themselves are not safe), but I feel like there must be a better way to do this.
the full code ... | [
"Put the functions in a list, then filter that list on making sure that for each variable name in that function those arguments are not none.\nExample:\ndef func_filter(item, arguments):\n needed_args = item.func_code.co_varnames\n all(map(lambda x: getattr(arguments, x) , needed_args))\n\nfuncs = (find_veloc... | [
3,
1,
0
] | [] | [] | [
"arguments",
"exists",
"python",
"switch_statement"
] | stackoverflow_0004390812_arguments_exists_python_switch_statement.txt |
Q:
Twitter Rate limit exceeded. Clients may not make more than 350 requests per hour
using Tweepy in my app, I get this Exception very often, just after sending no more than 10 twetts and updating the timeline around 20~30 times.
Rate limit exceeded. Clients may not make more than 350 requests per hour.
To update th... | Twitter Rate limit exceeded. Clients may not make more than 350 requests per hour | using Tweepy in my app, I get this Exception very often, just after sending no more than 10 twetts and updating the timeline around 20~30 times.
Rate limit exceeded. Clients may not make more than 350 requests per hour.
To update the timeline I'm using the timeline function with a limit of 40 tweets.
So I don't what i... | [
">>> 3600./350\n10.285714285714286\n\nOnly send a tweet every 11 seconds.\n",
"Here is your friend -> Twitter api rate-limiting\nSpend some time reading this document.\nHeaders\nThere are some rate limit status headers returned in the responses that may help you.\nConsider logging them at a debug level. If your ... | [
4,
4,
1
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0004390913_python_tweepy_twitter.txt |
Q:
Two different python paths in showing up Django
I see two different python paths in django.
This one shows up with the development server(i.e. python manage.py runserver etc.):
['/var/www/html/django/congressticketing',
'/usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg', '/usr/lib/py... | Two different python paths in showing up Django | I see two different python paths in django.
This one shows up with the development server(i.e. python manage.py runserver etc.):
['/var/www/html/django/congressticketing',
'/usr/lib/python2.4/site-packages/MySQL_python-1.2.3c1-py2.4-linux-i686.egg', '/usr/lib/python2.4/site-packages/pisa-3.0.32-py2.4.egg',
'/usr/... | [
"It could be a permissions problem. Check the file and directory permissions on the missing site-packages. It could be that those files are not accessible to the user name under which mod_python or Apache is running.\n"
] | [
1
] | [] | [] | [
"django",
"path",
"python"
] | stackoverflow_0004387233_django_path_python.txt |
Q:
Django ForeignKey Required?
I have a three classes:
class Location(models.Model):
name = models.CharField(max_length = 200)
class Student(models.Model):
name = models.CharField(max_length = 200)
email = models.EmailField()
class Exam(models.Model):
place = models.ForeignKey(Location)
taker = ... | Django ForeignKey Required? | I have a three classes:
class Location(models.Model):
name = models.CharField(max_length = 200)
class Student(models.Model):
name = models.CharField(max_length = 200)
email = models.EmailField()
class Exam(models.Model):
place = models.ForeignKey(Location)
taker = models.ForeignKey(Student)
sc... | [
"It sounds like your actual database is out of sync with your model. You'll want to either drop and recreate your database using manage.py syncdb (easiest, but you will lose the data unless you use something like fixtures to reload initial data) or use a migration tool like South to upgrade your existing database ... | [
1,
1,
0
] | [] | [] | [
"django",
"entity_relationship",
"one_to_many",
"python",
"sql"
] | stackoverflow_0004391125_django_entity_relationship_one_to_many_python_sql.txt |
Q:
Is there a better way to do mappings with regex?
I am mapping some human-input text to part names today, and came across a case that might be of general interest. Here is the human-input text:
Seat (Dis.)
Disc seat
seats
Seat (Suc.)
Suct seat
The two parts names to map to are SEAT, DISCHARGE and SEAT, SUCTION. W... | Is there a better way to do mappings with regex? | I am mapping some human-input text to part names today, and came across a case that might be of general interest. Here is the human-input text:
Seat (Dis.)
Disc seat
seats
Seat (Suc.)
Suct seat
The two parts names to map to are SEAT, DISCHARGE and SEAT, SUCTION. We will also map the ambiguous seats to SEAT, DISCHARGE... | [
"Rather than look for all permutations of uppercase/lowercase letters, try just lowercasing the string and searching for the lowercase version.\nlinput = input.lower()\nif 'seat' in linput:\n if 'suc' in linput:\n return 'SEAT, SUCTION'\n else:\n return 'SEAT, DISCHARGE'\n\nI'm not sure in this ... | [
4,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004390160_python_regex.txt |
Q:
python, dynamically implement a class onthefly
Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on_the_fly.
from example
class RemoveNoise():
pass
then methods are added as wanted
RemoveNo... | python, dynamically implement a class onthefly | Assuming i have a class that implements several methods. We want a user to chose to which methods to run among the exisiting methods or he can decide to add any method on_the_fly.
from example
class RemoveNoise():
pass
then methods are added as wanted
RemoveNoise.raw = Raw()
RemoveNoise.bais = Bias()
etc
he ca... | [
"Functions can be added to a class at runtime.\nclass Foo(object):\n pass\n\ndef bar(self):\n print 42\n\nFoo.bar = bar\nFoo().bar()\n\n",
"There is no solving needed, you just do it. Here is your code, with the small changes needed:\nclass RemoveNoise():\n pass\n\nRemoveNoise.raw = Raw\nRemoveNoise.bias ... | [
6,
2,
0
] | [] | [] | [
"add",
"function",
"interface",
"methods",
"python"
] | stackoverflow_0004387847_add_function_interface_methods_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.