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:
Accessing the Atlassian Crowd SOAP API with Suds (python SOAP library)
Has anybody had any recent success with accessing the Crowd SOAP API via the Suds Python library?
I've found a few people successfully doing it in the past but Atlassian seems to have changed their WSDL since then to make the existing advice no... | Accessing the Atlassian Crowd SOAP API with Suds (python SOAP library) | Has anybody had any recent success with accessing the Crowd SOAP API via the Suds Python library?
I've found a few people successfully doing it in the past but Atlassian seems to have changed their WSDL since then to make the existing advice not entirely helpful.
Below is the simplest example I've been trying:
from sud... | [
"There is a patch for the Crowd WSDL here:\nhttp://jira.atlassian.com/browse/CWD-159\n"
] | [
4
] | [] | [] | [
"atlassian_crowd",
"python",
"soap",
"suds"
] | stackoverflow_0002710086_atlassian_crowd_python_soap_suds.txt |
Q:
How to share memory buffer across sessions in Django?
I want to have one party (or more) sends a stream of data via HTTP request(s). Other parties will be able to receive the same stream of data in almost real-time.
The data stream should be accessible across sessions (according to access control list).
How can I ... | How to share memory buffer across sessions in Django? | I want to have one party (or more) sends a stream of data via HTTP request(s). Other parties will be able to receive the same stream of data in almost real-time.
The data stream should be accessible across sessions (according to access control list).
How can I do this in Django? If possible I would like to avoid databa... | [
"Use posix_ipc or sysv_ipc to use shared memory.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"web_applications"
] | stackoverflow_0002727355_django_python_web_applications.txt |
Q:
What does "str indices must be integers" mean?
I'm working with dicts in jython which are created from importing/parsing JSON. Working with certain sections I see the following message:
TypeError: str indices must be integers
This occurs when I do something like:
if jsondata['foo']['bar'].lower() == 'baz':
..... | What does "str indices must be integers" mean? | I'm working with dicts in jython which are created from importing/parsing JSON. Working with certain sections I see the following message:
TypeError: str indices must be integers
This occurs when I do something like:
if jsondata['foo']['bar'].lower() == 'baz':
...
Where jsondata looks like:
{'foo': {'bar':'baz'} ... | [
"As Marcelo and Ivo say, it sounds like you're trying to access the raw JSON string, without first parsing it into Python via json.loads(my_json_string).\n",
"You need to check the type for dict and existance of 'z' in the dict before getting data from dict.\n>>> jsondata = {'a': '', 'b': {'z': True} }\n>>> for k... | [
3,
2,
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0002720326_jython_python.txt |
Q:
How do I stop Python install on Mac OS X from putting things in my home directory?
I'm trying to install Python from source on my Mac. (OS X 10.6.2, Python-2.6.5.tar.bz2) I've done this before and it was easy, but for some reason, this time after ./configure, and make, the sudo make install puts things some thin... | How do I stop Python install on Mac OS X from putting things in my home directory? | I'm trying to install Python from source on my Mac. (OS X 10.6.2, Python-2.6.5.tar.bz2) I've done this before and it was easy, but for some reason, this time after ./configure, and make, the sudo make install puts things some things in my home directory instead of in /usr/local/... where I expect. The .py files are ... | [
"Doh. I've answered my own question. Recently I created a ~/.pydistutils.cfg file, for some stupid reason. I forgot to delete that file. It's contents were:\n[install]\ninstall_lib = ~/Library/Python/$py_version_short/site-packages\ninstall_scripts = ~/bin\nmake install calls setup.py, and this file was overrid... | [
2,
1,
0
] | [] | [] | [
"configure",
"installation",
"macos",
"python"
] | stackoverflow_0002727438_configure_installation_macos_python.txt |
Q:
add methods in subclasses within the super class constructor
I want to add methods (more specifically: method aliases) automatically to Python subclasses. If the subclass defines a method named 'get' I want to add a method alias 'GET' to the dictionary of the subclass.
To not repeat myself I'd like to define this... | add methods in subclasses within the super class constructor | I want to add methods (more specifically: method aliases) automatically to Python subclasses. If the subclass defines a method named 'get' I want to add a method alias 'GET' to the dictionary of the subclass.
To not repeat myself I'd like to define this modifation routine in the base class. But if I check in the base ... | [
"Your class's __init__ method adds a bound method as an attribute to instances of your class. This isn't exactly the same as adding the attribute to the class. Normally, methods work by storing functions in the class, as attributes, and then creating method objects as these functions are retrieved as attributes fro... | [
3,
2
] | [
"Create a derived constructor in your derived class which sets the attribute.\n"
] | [
-1
] | [
"constructor",
"inheritance",
"introspection",
"oop",
"python"
] | stackoverflow_0002727762_constructor_inheritance_introspection_oop_python.txt |
Q:
Passing parameter to base class constructor or using instance variable?
All classes derived from a certain base class have to define an attribute called "path". In the sense of duck typing I could rely upon definition in the subclasses:
class Base:
pass # no "path" variable here
def Sub(Base):
def __init_... | Passing parameter to base class constructor or using instance variable? | All classes derived from a certain base class have to define an attribute called "path". In the sense of duck typing I could rely upon definition in the subclasses:
class Base:
pass # no "path" variable here
def Sub(Base):
def __init__(self):
self.path = "something/"
Another possiblity would be to use... | [
"In Python 3.0+:\nI would go with a parameter to the base class's constructor like you have in the second example. As this forces classes which derive from Base to provide the necessary path property, which documents the fact that the class has such a property and that derived classes are required to provide it. Wi... | [
14
] | [] | [] | [
"constructor",
"oop",
"parameters",
"python",
"python_3.x"
] | stackoverflow_0002728346_constructor_oop_parameters_python_python_3.x.txt |
Q:
Parse a CSV file using python (to make a decision tree later)
First off, full disclosure: This is going towards a uni assignment, so I don't want to receive code. :). I'm more looking for approaches; I'm very new to python, having read a book but not yet written any code.
The entire task is to import the content... | Parse a CSV file using python (to make a decision tree later) | First off, full disclosure: This is going towards a uni assignment, so I don't want to receive code. :). I'm more looking for approaches; I'm very new to python, having read a book but not yet written any code.
The entire task is to import the contents of a CSV file, create a decision tree from the contents of the CS... | [
"Python has some pretty powerful language constructs builtin. You can read lines from a file like:\n\nwith open(name_of_file,\"r\") as file:\n for line in file:\n # process the line\n\nYou can use the string.split function to separate the line along commas, and you can use string.strip to eliminate inter... | [
4,
4,
2,
2,
1,
1,
0
] | [] | [] | [
"csv",
"decision_tree",
"python"
] | stackoverflow_0002726167_csv_decision_tree_python.txt |
Q:
what is this code mean in python,
def a():
print 'sss'
print getattr(a, "_decorated_function", a).__name__
it print :
a
thanks
updated
my code:
def a():
w='www'
print getattr(a,'w')
but it print :
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 8, in <module>
print getattr(a,'w'... | what is this code mean in python, | def a():
print 'sss'
print getattr(a, "_decorated_function", a).__name__
it print :
a
thanks
updated
my code:
def a():
w='www'
print getattr(a,'w')
but it print :
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 8, in <module>
print getattr(a,'w')
AttributeError: 'function' object has... | [
"See the documentation for getattr in Python. The reason it is printing \"a\", is because \"a\" has no attribute named \"_decorated_function\", and the third parameter to getattr() is a default value to return in the event that the first parameter has no attribute with the name of the second parameter. So, your cod... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002727449_python.txt |
Q:
how to create application(exe) from python script for linux
i'm newbie for python programming, i'm having a .py file, now what shall i do so i can create an application from .py file and it can be istall and run in any linux pc, i try to packaging it but its just create .tar file where i need python to run it, is... | how to create application(exe) from python script for linux | i'm newbie for python programming, i'm having a .py file, now what shall i do so i can create an application from .py file and it can be istall and run in any linux pc, i try to packaging it but its just create .tar file where i need python to run it, is it any to do so,
thanks
| [
"Make sure that the main python file has #! /usr/bin/env python as the first line, then make sure it has execute permission set (should be as easy as chmod +x file_name.py).\n",
"From link:\n\"PyInstaller is a program that converts (packages) Python programs into stand-alone executables, under Windows, Linux, and... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002728289_python.txt |
Q:
How to get path of stroke using opencv?
I want to get path stroke from image using opencv. I know how to get contours but I need path of stroke (path that runs through the center of the stroke). Is it possible to get this in opencv ?
A:
OpenCV does not have a skeletonization algorithm that allows one to get a s... | How to get path of stroke using opencv? | I want to get path stroke from image using opencv. I know how to get contours but I need path of stroke (path that runs through the center of the stroke). Is it possible to get this in opencv ?
| [
"OpenCV does not have a skeletonization algorithm that allows one to get a stroke path. You would need to implement an existing algorithm, good place to start is here:\nhttp://en.wikipedia.org/wiki/Topological_skeleton\n"
] | [
0
] | [] | [] | [
"2d",
"c++",
"image_processing",
"opencv",
"python"
] | stackoverflow_0002715766_2d_c++_image_processing_opencv_python.txt |
Q:
How to organize Python modules for PyPI to support 2.x and 3.x
I have a Python module that I would like to upload to PyPI. So far, it is working for Python 2.x. It shouldn't be too hard to write a version for 3.x now.
But, after following guidelines for making modules in these places:
Distributing Python Modules
... | How to organize Python modules for PyPI to support 2.x and 3.x | I have a Python module that I would like to upload to PyPI. So far, it is working for Python 2.x. It shouldn't be too hard to write a version for 3.x now.
But, after following guidelines for making modules in these places:
Distributing Python Modules
The Hitchhiker’s Guide to Packaging
it's not clear to me how to sup... | [
"I found that setup.py for httplib2 seems to have an elegant way to support Python 2.x and 3.x. So I decided to copy that method.\nThe task is to craft a single setup.py for the package distribution that works with all the supported Python distributions. Then with the same setup.py, you can do:\npython2 setup.py in... | [
18,
1
] | [] | [] | [
"python",
"python_2.x",
"python_3.x",
"software_distribution"
] | stackoverflow_0002398626_python_python_2.x_python_3.x_software_distribution.txt |
Q:
Django Forms Help needed
Im new to django and trying to make a user registration form with few validations.
Apart from this I also want a username suggestion code which will tell the user if the username he is trying to register is available or already in use. Then it should give few suggestions that might be avai... | Django Forms Help needed | Im new to django and trying to make a user registration form with few validations.
Apart from this I also want a username suggestion code which will tell the user if the username he is trying to register is available or already in use. Then it should give few suggestions that might be available to choose from. Can anyo... | [
"Check out the django-registration application. And have a look at the Class registration.forms.RegistrationForm and their method clean_username.\nIt should be easy to extend the form to suggest some usernames.\nhere is some sample code to generate unique username with numbered postfixes:\n username # filled wit... | [
1
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0002719292_django_forms_python.txt |
Q:
Python BOM error in Ascii file
I have a weird, annoying problem with Python 2.6. I'm trying to run this file (and the other), on my Embedded Linux ARM board.
http://svn.tuxisalive.com/software_suite_v3/smart-core/smart-server/trunk/TDSService.py
I get this error:
File "tuxhttpserver.py", line 1
SyntaxError: en... | Python BOM error in Ascii file | I have a weird, annoying problem with Python 2.6. I'm trying to run this file (and the other), on my Embedded Linux ARM board.
http://svn.tuxisalive.com/software_suite_v3/smart-core/smart-server/trunk/TDSService.py
I get this error:
File "tuxhttpserver.py", line 1
SyntaxError: encoding problem: with
BOM
I know t... | [
"Don't get too hung up on the \"with BOM\" remark. It's probably not relevant. What this error usually means is that the Python you are trying to run in does not support the encoding you declare. Observe:\n% head -1 tmp.py\n# -*- coding: asdfasdfasdf -*-\n% python tmp.py\n File \"tmp.py\", line 1\nSyntaxError: enc... | [
10
] | [] | [] | [
"ascii",
"byte_order_mark",
"encoding",
"python"
] | stackoverflow_0002729260_ascii_byte_order_mark_encoding_python.txt |
Q:
How to create a CFuncType in Python
I need to pass a callback function that is CFuncType (ctypes.CFUNCTYPE or ctypes.PYFUNCTYPE...).
How can I cast a python function to CFuncType or how can I create a CFuncType function in python.
A:
I forgot how awesome ctypes is:
Below is Copied from http://docs.python.org/li... | How to create a CFuncType in Python | I need to pass a callback function that is CFuncType (ctypes.CFUNCTYPE or ctypes.PYFUNCTYPE...).
How can I cast a python function to CFuncType or how can I create a CFuncType function in python.
| [
"I forgot how awesome ctypes is: \nBelow is Copied from http://docs.python.org/library/ctypes.html\nSo our callback function receives pointers to integers, and must return an integer. First we create the type for the callback function:\nCMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))\n\nFor the first imp... | [
12
] | [] | [] | [
"callback",
"ctypes",
"python"
] | stackoverflow_0002729223_callback_ctypes_python.txt |
Q:
Common elements between two lists not using sets in Python
I want count the same elements of two lists. Lists can have duplicate elements, so I can't convert this to sets and use & operator.
a=[2,2,1,1]
b=[1,1,3,3]
set(a) & set(b) work
a & b don't work
It is possible to do it withoud set and dictonary?
A:
In ... | Common elements between two lists not using sets in Python | I want count the same elements of two lists. Lists can have duplicate elements, so I can't convert this to sets and use & operator.
a=[2,2,1,1]
b=[1,1,3,3]
set(a) & set(b) work
a & b don't work
It is possible to do it withoud set and dictonary?
| [
"In Python 3.x (and Python 2.7, when it's released), you can use collections.Counter for this:\n>>> from collections import Counter\n>>> list((Counter([2,2,1,1]) & Counter([1,3,3,1])).elements())\n[1, 1]\n\nHere's an alternative using collections.defaultdict (available in Python 2.5 and later). It has the nice pro... | [
12,
8,
0
] | [] | [] | [
"list",
"python",
"set"
] | stackoverflow_0002727650_list_python_set.txt |
Q:
efficient list mapping in python
I have the following input:
input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)]
and trying to have the following output:
outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]]
outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse}
Any tips on how to handle given with sca... | efficient list mapping in python | I have the following input:
input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)]
and trying to have the following output:
outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]]
outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse}
Any tips on how to handle given with scalability in mind (var input can get re... | [
"You probably want something like:\nimport collections\nimport itertools\n\ndef build_catalog(L):\n counter = itertools.count().next\n names = collections.defaultdict(counter)\n result = []\n for t in L:\n new_t = [ names[item] for item in t ]\n result.append(new_t)\n catalog = dict((na... | [
6,
2,
0,
0
] | [] | [] | [
"dictionary",
"list",
"mapping",
"python",
"python_itertools"
] | stackoverflow_0002729135_dictionary_list_mapping_python_python_itertools.txt |
Q:
Does dict.update affect a function's argspec?
import inspect
class Test:
def test(self, p, d={}):
d.update(p)
return d
print inspect.getargspec(getattr(Test, 'test'))[3]
print Test().test({'1':True})
print inspect.getargspec(getattr(Test, 'test'))[3]
I would expect the argspec for Test.test not to chang... | Does dict.update affect a function's argspec? | import inspect
class Test:
def test(self, p, d={}):
d.update(p)
return d
print inspect.getargspec(getattr(Test, 'test'))[3]
print Test().test({'1':True})
print inspect.getargspec(getattr(Test, 'test'))[3]
I would expect the argspec for Test.test not to change but because of dict.update it does. Why?
| [
"Because dicts are mutable objects. When you call d.update(p), you are actually mutating the default instance of the dict. This is a common catch; in particular, you should never use a mutable object as a default value in the list of arguments.\nA better way to do this is as follows:\nclass Test:\n def test(self... | [
5,
2
] | [] | [] | [
"inspect",
"python"
] | stackoverflow_0002730107_inspect_python.txt |
Q:
Django ForeignModels
How do I get/set foreign key fields on a model object without touching the database and loading the related object?
A:
Django actually appends an '_id' to ForeignKey field names and with 'field_name_id' you can get or set the integer id value directly:
class MyModel(models.Model):
field ... | Django ForeignModels | How do I get/set foreign key fields on a model object without touching the database and loading the related object?
| [
"Django actually appends an '_id' to ForeignKey field names and with 'field_name_id' you can get or set the integer id value directly:\nclass MyModel(models.Model):\n field = models.ForeignKey(MyOtherModel)\n\nmymodel_instance = MyModel.objects.get(pk=1)\n# queries database for related object and the result is a... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002726417_django_python.txt |
Q:
Python Lambdas and Variable Bindings
I've been working on a basic testing framework for an automated build. The piece of code below represents a simple test of communication between two machines using different programs. Before I actually do any tests, I want to completely define them - so this test below is not... | Python Lambdas and Variable Bindings | I've been working on a basic testing framework for an automated build. The piece of code below represents a simple test of communication between two machines using different programs. Before I actually do any tests, I want to completely define them - so this test below is not actually run until after all the tests ha... | [
"The client variable is defined in the outer scope, so by the time the lambda is run it will always be set to the last client in the list.\nTo get the intended result, you can give the lambda an argument with a default value:\npassIf = lambda client=client: client.returncode(CMD2) == 0\n\nSince the default value is... | [
10,
5
] | [] | [] | [
"python"
] | stackoverflow_0002731111_python.txt |
Q:
Distutils - Where Am I going wrong?
I wanted to learn how to create python packages, so I visited http://docs.python.org/distutils/index.html.
For this exercise I'm using Python 2.6.2 on Windows XP.
I followed along with the simple example and created a small test project:
person/
setup.py
person/
... | Distutils - Where Am I going wrong? | I wanted to learn how to create python packages, so I visited http://docs.python.org/distutils/index.html.
For this exercise I'm using Python 2.6.2 on Windows XP.
I followed along with the simple example and created a small test project:
person/
setup.py
person/
__init__.py
person.py
My person.... | [
"person/\n __init__.py\n person.py\n\nYou've got a package called person, and a module inside it called person.person. You defined the class in that module, so to access it you'd have to say:\nimport person.person\np= person.person.Person('Tim', 42)\n\nIf you want to put members directly inside the package pers... | [
4,
2
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0002731452_distutils_python.txt |
Q:
SQL-wrappers (activerecord) to recommened for python?
is there an activerecord (any similar SQL-wrapper) for python? which is good for:
used in a server-side python script
light-weight
supports MySQL
what I need to do:
insert (filename, file size, file md5, the file itself) into (string, int, string, BLOB) colu... | SQL-wrappers (activerecord) to recommened for python? | is there an activerecord (any similar SQL-wrapper) for python? which is good for:
used in a server-side python script
light-weight
supports MySQL
what I need to do:
insert (filename, file size, file md5, the file itself) into (string, int, string, BLOB) columns
if the same file (checksum + filename) does not exist i... | [
"You might consider SQLAlchemy along with Elixir:\n\nElixir is a declarative layer on top of the SQLAlchemy library. It is a fairly thin wrapper, which provides the ability to create simple Python classes that map directly to relational database tables (this pattern is often referred to as the Active Record design ... | [
5
] | [] | [] | [
"activerecord",
"orm",
"python"
] | stackoverflow_0002727249_activerecord_orm_python.txt |
Q:
Automatic logout in python web app
I have a web application in python wherein the user submits their email and password. These values are compared to values stored in a mysql database. If successful, the script generates a session id, stores it next to the email in the database and sets a cookie with the session i... | Automatic logout in python web app | I have a web application in python wherein the user submits their email and password. These values are compared to values stored in a mysql database. If successful, the script generates a session id, stores it next to the email in the database and sets a cookie with the session id, with allows the user to interact with... | [
"You can encode the expiration time as part of your session id.\nThen when you validate the session id, you can also check if it has expired, and if so force the user to log-in again.\nYou can also clean your database periodically, removing expired sessions.\n",
"You'd have to add a timestamp to the session ID in... | [
1,
0
] | [] | [] | [
"logging",
"mysql",
"python",
"web_applications"
] | stackoverflow_0002731871_logging_mysql_python_web_applications.txt |
Q:
Python: Control timeout length
I have code similar to the following running in a script:
try:
s = ftplib.FTP('xxx.xxx.xxx.xxx','username','password')
except:
print ('Could not contact FTP serer')
sys.exit()
IF the FTP site is inaccessible, the script almost seems to 'hang' ... It is taking about 75 ... | Python: Control timeout length | I have code similar to the following running in a script:
try:
s = ftplib.FTP('xxx.xxx.xxx.xxx','username','password')
except:
print ('Could not contact FTP serer')
sys.exit()
IF the FTP site is inaccessible, the script almost seems to 'hang' ... It is taking about 75 seconds on average before sys.exit()... | [
"Starting with 2.6, the FTP constructor has an optional timeout parameter:\n\nclass ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])\nReturn a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) i... | [
7,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002355743_python.txt |
Q:
Javascript JQUERY AJAX: When Are These Implemented
I'm learning javascript. Poked around this excellent site to gather intel. Keep coming across questions / answers about javascript, JQUERY, JQUERY with AJAX, javascript with JQUERY, AJAX alone. My conclusion: these are all individually powerful and useful. My ... | Javascript JQUERY AJAX: When Are These Implemented | I'm learning javascript. Poked around this excellent site to gather intel. Keep coming across questions / answers about javascript, JQUERY, JQUERY with AJAX, javascript with JQUERY, AJAX alone. My conclusion: these are all individually powerful and useful. My confusion: how does one determine which/which combinatio... | [
"\nJavascript is code that runs client-side in the browser.\nAJAX is a term used to refer to the process of Javascript contacting the webserver directly and getting a response as opposed to the user navigating to a different page\njQuery is a javascript library that provides an easy-to-use abstraction over top of A... | [
4,
2,
1
] | [] | [] | [
"ajax",
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0002731825_ajax_django_javascript_jquery_python.txt |
Q:
How to add a constructor to a subclassed numeric type?
I want to subclass a numeric type (say, int) in python and give it a shiny complex constructor. Something like this:
class NamedInteger(int):
def __init__(self, value):
super(NamedInteger, self).__init__(value)
self.name = 'pony'
def _... | How to add a constructor to a subclassed numeric type? | I want to subclass a numeric type (say, int) in python and give it a shiny complex constructor. Something like this:
class NamedInteger(int):
def __init__(self, value):
super(NamedInteger, self).__init__(value)
self.name = 'pony'
def __str__(self):
return self.name
x = NamedInteger(5)
... | [
"As of Python 2.6, the preferred way to extend numeric types is not to directly inherit from them, but rather to register your class as a subclass of the Number abstract base class. Check out the abc module for documentation of the Abstract Base Class concept.\nThat module's documentation links to the numbers modu... | [
5,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0002732256_python.txt |
Q:
Problems serving static files in CherryPy 3.1
I'm having some trouble serving a static XML stylesheet to accompany some dynamically generated output from a CherryPy web app. Even my test case serving a static text file fails.
Static file blah.txt is in the /static directory in my application root directory.
In my ... | Problems serving static files in CherryPy 3.1 | I'm having some trouble serving a static XML stylesheet to accompany some dynamically generated output from a CherryPy web app. Even my test case serving a static text file fails.
Static file blah.txt is in the /static directory in my application root directory.
In my main site file (conesearch.py contains the CherryPy... | [
"cherrypy.config.update should only receive a single-level dictionary (mostly server.* entries), but you're passing it a multi-level dictionary of settings that should really be per-app (and therefore passed to tree.mount).\nMove those [/] and [/static] sections from your site.config file to your ucac3.config file,... | [
4,
3,
1
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0002496458_cherrypy_python.txt |
Q:
Words doesn't starts with numbers
I have a string "one two 9three 52eight four", so I only want to get "one two four", because "three" starts with "9" and "eight" starts with "52".
I tried:
"(?!\d)\w+"
but it's still taking the "three" and "eight". I don't want it.
A:
Try
\b[a-zA-Z]\w*
A:
that's because \w in... | Words doesn't starts with numbers | I have a string "one two 9three 52eight four", so I only want to get "one two four", because "three" starts with "9" and "eight" starts with "52".
I tried:
"(?!\d)\w+"
but it's still taking the "three" and "eight". I don't want it.
| [
"Try\n\\b[a-zA-Z]\\w*\n\n",
"that's because \\w includes number. what you need to do is:\n>>> s = \"one two 9three 52eight four\"\n>>> import re\n>>> re.findall(r'\\b[a-z]+\\b', s, re.I)\n['one', 'two', 'four']\n\nAlso, what you're using (?!...) is called negative look-ahead, while you probably meant negative loo... | [
4,
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002730094_python_regex.txt |
Q:
wx Python is not properly drawing customtree items
I am currently using wx.CustomTree, to use to display a series of configuration settings. I generally fill them with wx.TextCtrl / wx.Combobox, to allow the user to edit / enter stuff. Here is my code:
class ConfigTree(CT.CustomTreeCtrl):
"""
Holds all... | wx Python is not properly drawing customtree items | I am currently using wx.CustomTree, to use to display a series of configuration settings. I generally fill them with wx.TextCtrl / wx.Combobox, to allow the user to edit / enter stuff. Here is my code:
class ConfigTree(CT.CustomTreeCtrl):
"""
Holds all non gui drawing panel stuff
"""
def __init__(se... | [
"I tested it on window with wx version 2.8.10.1 and it works, which OS and wx version you are using?\nhere is self contained code, which can be copy-pasted and run\nimport wx\nimport wx.lib.customtreectrl as CT\n\nclass ConfigTree(CT.CustomTreeCtrl):\n \"\"\"\n Holds all non gui drawing panel stuff\n \... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002622843_python_wxpython.txt |
Q:
post_save signal on m2m field
I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?
... | post_save signal on m2m field | I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?
| [
"This is a new feature in Django 1.2:\nhttp://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed\n",
"You can do this by creating an intermediate model for the M2M relationship and use it as your hook for the post_save and post_delete signals to update the denormalised column in the Article table.\nFor exampl... | [
3,
2
] | [] | [] | [
"django",
"django_signals",
"python"
] | stackoverflow_0000240659_django_django_signals_python.txt |
Q:
Can I use an opened gzip file with Popen in Python?
I have a little command line tool that reads from stdin.
On the command line I would run either...
./foo < bar
or ...
cat bar | ./foo
With a gziped file I can run
zcat bar.gz | ./foo
in Python I can do ...
Popen(["./foo", ], stdin=open('bar'), stdout=PIPE, std... | Can I use an opened gzip file with Popen in Python? | I have a little command line tool that reads from stdin.
On the command line I would run either...
./foo < bar
or ...
cat bar | ./foo
With a gziped file I can run
zcat bar.gz | ./foo
in Python I can do ...
Popen(["./foo", ], stdin=open('bar'), stdout=PIPE, stderr=PIPE)
but I can't do
import gzip
Popen(["./foo", ], ... | [
"Because the 'stdin' and 'stdout' of the subprocess takes file descriptor (which is a number), which is an operating system resource. This is masked by the fact that if you pass an object, the subprocess module checks whether the object has a 'fileno' attribute and if it has, it will use it.\nThe 'gzip' object is n... | [
4
] | [] | [] | [
"python",
"scripting",
"subprocess"
] | stackoverflow_0002732811_python_scripting_subprocess.txt |
Q:
Eclipse Python Integration
I found this python plugin list but thought I'd ask if anyone has any experience with anything listed there?
I'm totally new to both python and dynamic programming languages if that makes any difference.
A:
PyDev is the most widely used IDE I think. I'm using it not very often, but if ... | Eclipse Python Integration | I found this python plugin list but thought I'd ask if anyone has any experience with anything listed there?
I'm totally new to both python and dynamic programming languages if that makes any difference.
| [
"PyDev is the most widely used IDE I think. I'm using it not very often, but if I do, it suits me quite well.\n",
"PyDev is the best I've used. I use it every day. When they had a pay version I paid for it. I use it on my Mac and Linux box and love it. \n",
"I'm using PyDev. It's come a long way since I sta... | [
5,
2,
2,
2,
1
] | [] | [] | [
"eclipse",
"eclipse_plugin",
"python"
] | stackoverflow_0002732805_eclipse_eclipse_plugin_python.txt |
Q:
Timed email reminder in python
I have written up a python script that allows a user to input a message, his email and the time and they would like the email sent. This is all stored in a mysql database.
However, how do I get the script to execute on the said time and date? will it require a cron job? I mean say a... | Timed email reminder in python | I have written up a python script that allows a user to input a message, his email and the time and they would like the email sent. This is all stored in a mysql database.
However, how do I get the script to execute on the said time and date? will it require a cron job? I mean say at 2:15 on april 20th, the script wil... | [
"If you cannot have a continuously running script, something must trigger it, so that would have to rely on your OS internals. In a unix environment a cron job, as you self state, would do the trick.\nSet cron to run the script, and make the script wait for a given time and then continue running and sending until t... | [
2,
2,
1
] | [] | [] | [
"email",
"mysql",
"python",
"reminders"
] | stackoverflow_0002732407_email_mysql_python_reminders.txt |
Q:
Access class instance "name" dynamically in Python
In plain english: I am creating class instances dynamically in a for loop, the class then defines a few attributes for the instance. I need to later be able to look up those values in another for loop.
Sample code:
class A:
def __init__(self, name, attr):
... | Access class instance "name" dynamically in Python | In plain english: I am creating class instances dynamically in a for loop, the class then defines a few attributes for the instance. I need to later be able to look up those values in another for loop.
Sample code:
class A:
def __init__(self, name, attr):
self.name=name
self.attr=attr
names=("a1"... | [
"Sometimes keeping it simple is best. Having a dict that stores your instances with their names as the keys would be both straightforward and fairly simple to implement.\nclass A:\n instances={}\n def __init__(self, name, attr):\n self.name=name\n self.attr=attr\n A.instances[name] = self... | [
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002733580_python.txt |
Q:
Python: does it make sense to refactor this check into its own method?
I'm still learning python. I just wrote this method to determine if a player has won a game of tic-tac-toe yet, given a board state like: '[['o','x','x'],['x','o','-'],['x','o','o']]'
def hasWon(board):
players = ['x', 'o']
for player in pl... | Python: does it make sense to refactor this check into its own method? | I'm still learning python. I just wrote this method to determine if a player has won a game of tic-tac-toe yet, given a board state like: '[['o','x','x'],['x','o','-'],['x','o','o']]'
def hasWon(board):
players = ['x', 'o']
for player in players:
for row in board:
if row.count(player) == 3:
return... | [
"I might use\ndef check(somelist, player):\n return somelist.count(player) == 3\n\nEdit: as @Andrew suggested in a comment (tx @Andrew!), you can do even better, e.g.:\ndef check(somelist, player):\n return somelist.count(player) == len(somelist)\n\nwithout hardcoding the 3 -- which also suggests another nice alt... | [
5,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"refactoring",
"tic_tac_toe"
] | stackoverflow_0002730228_python_refactoring_tic_tac_toe.txt |
Q:
In Python BeautifulSoup How to move tags
I have a partially converted XML document in soup coming from HTML. After some replacement and editing in the soup, the body is essentially -
<Text...></Text> # This replaces <a href..> tags but automatically creates the </Text>
<p class=norm ...</p>
<p class=norm ...</p... | In Python BeautifulSoup How to move tags | I have a partially converted XML document in soup coming from HTML. After some replacement and editing in the soup, the body is essentially -
<Text...></Text> # This replaces <a href..> tags but automatically creates the </Text>
<p class=norm ...</p>
<p class=norm ...</p>
<Text...></Text>
<p class=norm ...</p> and s... | [
"You can use insert to move tags. The docs say: \"An element can occur in only one place in one parse tree. If you give insert an element that's already connected to a soup object, it gets disconnected (with extract) before it gets connected elsewhere.\"\nIf your HTML looks like this:\n<text></text>\n<p class=\"nor... | [
4
] | [] | [] | [
"beautifulsoup",
"children",
"python",
"regex",
"xml"
] | stackoverflow_0002732391_beautifulsoup_children_python_regex_xml.txt |
Q:
Python + PyQt program freezes
I wrote PyQt application. After it's start I close it (GUI), but timer don't stops and Python sometimes freezes. Only thing to unfreeze it - Ctrl-C, after which following message appears:
Traceback (most recent call last):
File "", line 262, in timerEvent
KeyboardInterr... | Python + PyQt program freezes | I wrote PyQt application. After it's start I close it (GUI), but timer don't stops and Python sometimes freezes. Only thing to unfreeze it - Ctrl-C, after which following message appears:
Traceback (most recent call last):
File "", line 262, in timerEvent
KeyboardInterrupt
timer don't stops again, a... | [
"Without further information this is a complete guess. One of the more frequent reasons that an application doesn't exit when the GUI is closed is because of QApplication::quitOnLastWindowClosed property being set to false.\n"
] | [
0
] | [] | [] | [
"cpython",
"freeze",
"pyqt",
"python",
"qt"
] | stackoverflow_0002733456_cpython_freeze_pyqt_python_qt.txt |
Q:
dictionary interface for large data sets
I have a set of key/values (all text) that is too large to load in memory at once. I would like to interact with this data via a Python dictionary-like interface.
Does such a module already exist?
Reading key values should be efficient and values compressed on disk to sav... | dictionary interface for large data sets | I have a set of key/values (all text) that is too large to load in memory at once. I would like to interact with this data via a Python dictionary-like interface.
Does such a module already exist?
Reading key values should be efficient and values compressed on disk to save space.
Edit:
Ideally cross platform, but on... | [
"Take a look at the shelve module. It provides dictionaries with various backing database systems include BerkleyDB and dbm.\n",
"Try bsddb(Python bindings for Berkley db)\n",
"ended up creating my own solution based on this existing module. \n",
"Assuming you are on a *nix platform, you are just BEGGING for ... | [
2,
1,
1,
0
] | [] | [] | [
"dataset",
"dictionary",
"large_files",
"python"
] | stackoverflow_0002550980_dataset_dictionary_large_files_python.txt |
Q:
Apache + Mod_wsgi returning 502 Bad Gateway!
I'm serving Django with mod_wsgi and Apache... unfortunately requests are returning 502 Bad Gateway error messages...
Received a invalid response
HttpResponse('OK') is affected by this
render_to_response('...') is not!
any ideas?!?
A:
realy strange...
Because the r... | Apache + Mod_wsgi returning 502 Bad Gateway! | I'm serving Django with mod_wsgi and Apache... unfortunately requests are returning 502 Bad Gateway error messages...
Received a invalid response
HttpResponse('OK') is affected by this
render_to_response('...') is not!
any ideas?!?
| [
"realy strange...\nBecause the render_to_response is implemented with HttpResponse.\nMaybe there is a problem with your string inside HttpResponse(). \n\nUnicode Error? \nWrong Mimetype?\nproblem around your posted code..\n\n",
"Are you using a proxy front end such as nginx? The mod_wsgi module doesn't generate s... | [
1,
1
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0002728396_apache_django_mod_wsgi_python_wsgi.txt |
Q:
Webfaction apache + mod_wsgi + django configuration issue
A problem that I stumbled upon recently, and, even though I solved it, I would like to hear your opinion of what correct/simple/adopted solution would be.
I'm developing website using Django + python. When I run it on local machine with "python manage.py ru... | Webfaction apache + mod_wsgi + django configuration issue | A problem that I stumbled upon recently, and, even though I solved it, I would like to hear your opinion of what correct/simple/adopted solution would be.
I'm developing website using Django + python. When I run it on local machine with "python manage.py runserver", local address is http://127.0.0.1:8000/ by default.
H... | [
"You shouldn't need to do anything special. Django honours the SCRIPT_NAME environment variable that is set by mod_wsgi when you serve a Django site other than from the root, and prepends it to the url reversing code automatically.\nIf you're using mod_python (you shouldn't be), you may need to set django.root in y... | [
3,
2
] | [] | [] | [
"django",
"production_environment",
"python",
"url"
] | stackoverflow_0002729368_django_production_environment_python_url.txt |
Q:
Any good python open source projects exemplifying coding standards and best practices?
In the question
A:
Check out Flask's code, the comments on the release announcement noted that the code was very well written:
http://lucumr.pocoo.org/2010/4/16/flask-0-1-released
Armin, the author of Flask, also wrote Werkzeu... | Any good python open source projects exemplifying coding standards and best practices? | In the question
| [
"Check out Flask's code, the comments on the release announcement noted that the code was very well written:\nhttp://lucumr.pocoo.org/2010/4/16/flask-0-1-released\nArmin, the author of Flask, also wrote Werkzeug, which I use a lot, and find very well written. Here is the source:\nhttp://github.com/mitsuhiko/flask/... | [
3,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0002722758_coding_style_python.txt |
Q:
app-engine-patch and "object_detail" view didn't work
Hi(Sorry for my ugly english)
I want to use the app-engine-patch and google app engine to create a simple blog, and use the django generic views handle the blog entry page.
But when I use Django's generic views "django.views.generic.list_detail.object_detail", ... | app-engine-patch and "object_detail" view didn't work | Hi(Sorry for my ugly english)
I want to use the app-engine-patch and google app engine to create a simple blog, and use the django generic views handle the blog entry page.
But when I use Django's generic views "django.views.generic.list_detail.object_detail", I encountered an error in the following:
GenericViewError a... | [
"I believe your URL is missing 'object_id=' after the '?'.\n"
] | [
0
] | [] | [] | [
"app_engine_patch",
"django_views",
"python"
] | stackoverflow_0002734114_app_engine_patch_django_views_python.txt |
Q:
Match e-mail addresses not contained in HTML tag
I need to highlight an email addresses in text but not highlight them if contained in HTML tags, content, or attributes.
For example, the string example@example.com must be converted to <a href="mailto:example@example.com">example@example.com</a>
But email addresses... | Match e-mail addresses not contained in HTML tag | I need to highlight an email addresses in text but not highlight them if contained in HTML tags, content, or attributes.
For example, the string example@example.com must be converted to <a href="mailto:example@example.com">example@example.com</a>
But email addresses in the string <a href="mailto:example@example.com">ex... | [
"I'll guessing that your source text is an HTML file which is missing anchor tags for only some of the contained e-mail addresses. If this is true, then you will not be able to use a regexp to reliably match only untagged e-mail addresses. For example, given the input:\n...\n<P>You'll find a lot more written by <A ... | [
1
] | [] | [] | [
"email",
"python",
"regex"
] | stackoverflow_0002734329_email_python_regex.txt |
Q:
differences between "d.clear()" and "d={}"
On my machine, the execution speed between d.clear() and d={} is over 100ns so am curious why one would use one over the other.
import timeit
def timing():
d = dict()
if __name__=='__main__':
t = timeit.Timer('timing()', 'from __main__ import timing')
print ... | differences between "d.clear()" and "d={}" | On my machine, the execution speed between d.clear() and d={} is over 100ns so am curious why one would use one over the other.
import timeit
def timing():
d = dict()
if __name__=='__main__':
t = timeit.Timer('timing()', 'from __main__ import timing')
print t.repeat()
| [
"The difference is that d = {} creates a new dictionary and d.clear() just empties the dictionary you already have. This subtle difference matters if you have other places in your code holding references to your dictionary. In the first case those other objects won't see any change because you haven't modified the ... | [
19,
6
] | [] | [] | [
"python",
"timing"
] | stackoverflow_0002732550_python_timing.txt |
Q:
Could Python's logging SMTP Handler be freezing my thread for 2 minutes?
A rather confusing sequence of events happened, according to my log-file, and I am about to put a lot of the blame on the Python logger, which is a bold claim. I thought I should get some second opinions about whether what I am saying could b... | Could Python's logging SMTP Handler be freezing my thread for 2 minutes? | A rather confusing sequence of events happened, according to my log-file, and I am about to put a lot of the blame on the Python logger, which is a bold claim. I thought I should get some second opinions about whether what I am saying could be true.
I am trying to explain why there is are several large gaps in my log f... | [
"Stress-testing was revealing:\nMy logging configuration sent critical messages to SMTPHandler, and debug messages to a local log file.\nFor testing I created a moderately large number of threads (e.g. 50) that waited for a trigger, and then simultaneosly tried to log either a critical message or a debug message, d... | [
2,
1
] | [] | [] | [
"logging",
"python",
"smtp"
] | stackoverflow_0002722036_logging_python_smtp.txt |
Q:
Building an SNMP Request-Response service with Python Asyncore
I have a 3rd-party protocol module (SNMP) that is built on top of asyncore. The asyncore interface is used to process response messages. What is the proper technique to design a client that generate the request-side of the protocol, while the asyncore ... | Building an SNMP Request-Response service with Python Asyncore | I have a 3rd-party protocol module (SNMP) that is built on top of asyncore. The asyncore interface is used to process response messages. What is the proper technique to design a client that generate the request-side of the protocol, while the asyncore main loop is running. I can think of two options right now:
Use the... | [
"I solved this by adding a callback function into the asyncore loop for the receiver process.\nThe solution was somewhat specific to the module I was experiment with (pySNMP), but here is the general idea:\n\ndefine a function closure that returns a callable method with a stored reference to a dict and window varia... | [
1
] | [] | [] | [
"asyncore",
"client_server",
"pysnmp",
"python"
] | stackoverflow_0002626512_asyncore_client_server_pysnmp_python.txt |
Q:
Modifying Bresenham's line algorithm
I'm trying to use Bresenham's line algorithm to compute Field of View on a grid. The code I'm using calculates the lines without a problem but I'm having problems getting it to always return the line running from start point to endpoint. What do I need to do so that all lines ... | Modifying Bresenham's line algorithm | I'm trying to use Bresenham's line algorithm to compute Field of View on a grid. The code I'm using calculates the lines without a problem but I'm having problems getting it to always return the line running from start point to endpoint. What do I need to do so that all lines returned run from (x0,y0) to (x1,y1)
def b... | [
"Remember whether you switched x0 and x1 and then reverse the list if you did.\nif x0 > x1:\n x0, x1 = x1, x0\n y0, y1 = y1, y0\n\nbecomes\nswitched = False\nif x0 > x1:\n switched = True\n x0, x1 = x1, x0\n y0, y1 = y1, y0\n\nand at the end, just add:\nif switched:\n line.reverse()\n\n"
] | [
4
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0002734714_algorithm_python.txt |
Q:
Disadvantage of Python eggs?
Are there any disadvantages about using eggs through easy-install compared to the "traditional" packages/modules/libs?
A:
One (potential) disadvantage is that eggs are zipped by default unless zip_safe=False is set in their setup() function in setup.py. If an egg is zipped, you can... | Disadvantage of Python eggs? | Are there any disadvantages about using eggs through easy-install compared to the "traditional" packages/modules/libs?
| [
"One (potential) disadvantage is that eggs are zipped by default unless zip_safe=False is set in their setup() function in setup.py. If an egg is zipped, you can't get at the files in it (without unzipping it, obviously). If the module itself uses non-source files (such as templates) it will probably specify zip_sa... | [
8,
8
] | [] | [] | [
"comparison",
"egg",
"python"
] | stackoverflow_0002733629_comparison_egg_python.txt |
Q:
this is my Receiving Email code,but can't Receiving Email .. (google-app-engine)
import logging, email
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
class LogSenderHandler(InboundMailHand... | this is my Receiving Email code,but can't Receiving Email .. (google-app-engine) | import logging, email
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
class LogSenderHandler(InboundMailHandler):
def receive(self, message):
_subject = message.subject
_sen... | [
"I had the same problem after following the google tutorial as well. Thanks to this tute I discovered a rather important bit of code that slipped my mind and isn't in the google tutorial.\ndef main():\n run_wsgi_app(application)\nif __name__ == \"__main__\":\n main()\n\nHope that helps.\n",
"It looks like y... | [
3,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002706208_google_app_engine_python.txt |
Q:
Replacement for htmllib module in Python 3.0
I want to use the htmllib module but it's been removed from Python 3.0. Does anyone know what's the replacement for this module?
A:
It is Superseded by HTMLParser see Python library reorganization
A:
I haven't used it, but it looks like what you want is the html.par... | Replacement for htmllib module in Python 3.0 | I want to use the htmllib module but it's been removed from Python 3.0. Does anyone know what's the replacement for this module?
| [
"It is Superseded by HTMLParser see Python library reorganization\n",
"I haven't used it, but it looks like what you want is the html.parser library, and possibly also html.entity.\n",
"I heard Beautiful soup is getting a port to 3.0.\n",
"I believe lxml has been ported to Python 3\n"
] | [
10,
8,
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002730752_python_python_3.x.txt |
Q:
Documenting module/class/function bodies in Python Sphinx docs
Is there a way with Sphinx documentation to output a function or class body (the code itself) with the autodoc feature? I'm using autodoc to much success. In addition to the docstrings getting pulled in to the documentation I want like a link to click ... | Documenting module/class/function bodies in Python Sphinx docs | Is there a way with Sphinx documentation to output a function or class body (the code itself) with the autodoc feature? I'm using autodoc to much success. In addition to the docstrings getting pulled in to the documentation I want like a link to click for each function where it will show you the source... is that possi... | [
"If this still matters: The viewcode extension can do this, but needs the development version (1.0) of Sphinx\n",
"I don't believe so. Autodoc is only for pulling the documentation out of the source code.\n"
] | [
2,
1
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0001836633_python_python_sphinx.txt |
Q:
python script problem once build and package it
I've written python script to scan wifi and send data to the server, I set interval value, so it keep on scanning and send the data, it read from config.txt file where i set the interval value to scan, I also add yes/no in my config file, so is 'no' it will scan only... | python script problem once build and package it | I've written python script to scan wifi and send data to the server, I set interval value, so it keep on scanning and send the data, it read from config.txt file where i set the interval value to scan, I also add yes/no in my config file, so is 'no' it will scan only once and if 'yes' it will scan according to the inte... | [
"I think the problem is in the loop condition. Supposing that is_set() returns False, the second part is always False. While is intervalTime is not known, i think that it is positive (does has sense a negative interval time?) and count is never lesser than self.iterations: they are both 0.\nBut the code you posted ... | [
0
] | [] | [] | [
"build",
"package",
"python"
] | stackoverflow_0002735410_build_package_python.txt |
Q:
create_or_update in ModelForm
I want to have a ModelForm that can create_or_update a model instance based on the request parameters.
I've been trying to cobble something together, but am realizing that my python fu is not strong enough, and the ModelForm implementation code is a quite hairy.
I found this update_or... | create_or_update in ModelForm | I want to have a ModelForm that can create_or_update a model instance based on the request parameters.
I've been trying to cobble something together, but am realizing that my python fu is not strong enough, and the ModelForm implementation code is a quite hairy.
I found this update_or_create snipplet for working with a... | [
"This isn't really something that belongs in the ModelForm itself. Models already do this automatically - if the model instance has a value for pk, it is updated, otherwise it is inserted. So all you need to do when you instantiate your form is to pass in either an existing model instance, which will be updated on ... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0002733089_django_django_forms_django_models_python.txt |
Q:
How to get debugging of an App Engine application working?
I've got 10+ years in C/C++, and it appears Visual Studio has spoilt me during that time. In Visual Studio, debbuging issimple: I just add a breakpoint to a line of code, and as soon as that code is executed, my breakpoint triggers, at which point I can vi... | How to get debugging of an App Engine application working? | I've got 10+ years in C/C++, and it appears Visual Studio has spoilt me during that time. In Visual Studio, debbuging issimple: I just add a breakpoint to a line of code, and as soon as that code is executed, my breakpoint triggers, at which point I can view a callstack, local/member variables, etc.
I'm trying to achi... | [
"In fact setting a breakpoint in eclipse is very easy. You have two options:\nIn the grey area next to your line numbers, doubleclick or right mouseclick -> toggle breakpoint.\n"
] | [
1
] | [] | [] | [
"debugging",
"eclipse",
"google_app_engine",
"pydev",
"python"
] | stackoverflow_0002735968_debugging_eclipse_google_app_engine_pydev_python.txt |
Q:
Parse URL from plain text
How can I parse URLs from any give plain text (not limited to href attributes in tags)?
Any code examples in Python will be appreciated.
A:
You could use a Regular Expression to parse the string.
Look in this previously asked question:
What’s the cleanest way to extract URLs from a str... | Parse URL from plain text | How can I parse URLs from any give plain text (not limited to href attributes in tags)?
Any code examples in Python will be appreciated.
| [
"You could use a Regular Expression to parse the string.\nLook in this previously asked question:\nWhat’s the cleanest way to extract URLs from a string using Python?\n",
"See Jan Goyvaerts' blog.\nSo a Python code example could look like\nresult = re.findall(r\"\\b(?:(?:https?|ftp|file)://|www\\.|ftp\\.)[-A-Z0-9... | [
2,
1
] | [] | [] | [
"parsing",
"python",
"url"
] | stackoverflow_0002735181_parsing_python_url.txt |
Q:
How to render custom columns with a GenericTreeModel
I have to display some data in a treeview. The "real" data model is huge and I cannot copy all the stuff in a TreeStore, so I guess I should use a GenericTreeModel to act like a virtual treeview. Btw, the first column is the classic icon+text style and I think I... | How to render custom columns with a GenericTreeModel | I have to display some data in a treeview. The "real" data model is huge and I cannot copy all the stuff in a TreeStore, so I guess I should use a GenericTreeModel to act like a virtual treeview. Btw, the first column is the classic icon+text style and I think I should declare a column with a CellRendererPixbuf (faq sa... | [
"Look at the tutorial, there is an example that packs two cell renderer to one column. The difference is that you are using a custom tree model and the behavior depends on how you modeled your model. If you have one column with the text and one column with the pixbuf you can use set_attributes:\ncolumn = gtk.TreeVi... | [
0
] | [] | [] | [
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0002735803_gtktreeview_pygtk_python.txt |
Q:
python eval weirdness
I have the following code in one of my classes along with checks when the code does not eval:
filterParam="self.recipientMSISDN==tmpBPSS.split('_')[3].split('#')[0] and self.recipientIMSI==tmpBPSS.split('_')[3].split('#')[1]"
if eval(filterParam):
print "Evalled"
else:
print "Not Eva... | python eval weirdness | I have the following code in one of my classes along with checks when the code does not eval:
filterParam="self.recipientMSISDN==tmpBPSS.split('_')[3].split('#')[0] and self.recipientIMSI==tmpBPSS.split('_')[3].split('#')[1]"
if eval(filterParam):
print "Evalled"
else:
print "Not Evalled\nfilterParam\n'%s'\ntm... | [
"Most likely, the type of self.recipientIMSI or self.recipientMSISDN is int, and comparing them with strings returns False. Add this line to see if this is the case:\nprint type(self.recipientIMSI), type(self.recipientMSISDN)\n\nIf not, try checking what the same expression evaluates to without eval.\nThat said, Ar... | [
1,
0,
0
] | [] | [] | [
"eval",
"python"
] | stackoverflow_0002736460_eval_python.txt |
Q:
Django : presenting a form very different from the model and with multiple field values in a Django-ish way?
I'm currently doing a firewall management application for Django, here's the (simplified) model :
class Port(models.Model):
number = models.PositiveIntegerField(primary_key=True)
application = model... | Django : presenting a form very different from the model and with multiple field values in a Django-ish way? | I'm currently doing a firewall management application for Django, here's the (simplified) model :
class Port(models.Model):
number = models.PositiveIntegerField(primary_key=True)
application = models.CharField(max_length=16, blank=True)
class Rule(models.Model):
port = models.ForeignKey(Port)
ip_source... | [
"You can create usual Forms objects by subclassing Form and adding fields in constructor, as in:\nself.base_fields[field_name] = field_instance\n\nAs for the Rule, You can create a custom Field that will validate() itself according to Your rules and add it to Your custom form as above.\nSo Yes, it must be handmande... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002605886_django_python.txt |
Q:
how to generate py files without default windows crlf?
how can I write a .py file from python such that its type should not be like 'ASCII file with Windows CRLF'
because when i run file.write(data) inside windows it write the file but when I try to
eval(open(file.py).read()) it fails and gives syntax error becau... | how to generate py files without default windows crlf? | how can I write a .py file from python such that its type should not be like 'ASCII file with Windows CRLF'
because when i run file.write(data) inside windows it write the file but when I try to
eval(open(file.py).read()) it fails and gives syntax error because of windows CRLF on each line......
see the error log - tr... | [
"The problem is not with the CRLF, but that eval is for evaluating a single expression, not an entire program.\nYou can use exec to execute a program from a string, or execfile to execute it directly from a file.\nTo answer your original question anyway, you can avoid writing CRLF by opening the file in binary mode... | [
1,
1,
1,
0
] | [] | [] | [
"code_generation",
"eval",
"python"
] | stackoverflow_0002737208_code_generation_eval_python.txt |
Q:
Python: sort a list and change another one consequently
I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in tw... | Python: sort a list and change another one consequently | I have two lists: one contains a set of x points, the other contains y points. Python somehow manages to mix the x points up, or the user could. I'd need to sort them by lowest to highest, and move the y points to follow their x correspondants. They are in two separate lists.. how do I do it?
| [
"You could zip the lists and sort the result. Sorting tuples should, by default, sort on the first member.\n>>> xs = [3,2,1]\n>>> ys = [1,2,3]\n>>> points = zip(xs,ys)\n>>> points\n[(3, 1), (2, 2), (1, 3)]\n>>> sorted(points)\n[(1, 3), (2, 2), (3, 1)]\n\nAnd then to unpack them again:\n>>> sorted_points = sorted(p... | [
19,
16,
10,
4
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0002732994_list_python_sorting.txt |
Q:
Does Django cache url regex patterns somehow?
I'm a Django newbie who needs help: Even though I change some urls in my urls.py I keep on getting the same error message from Django. Here is the relevant line from my settings.py:
ROOT_URLCONF = 'mydjango.urls'
Here is my urls.py:
from django.conf.urls.defaults imp... | Does Django cache url regex patterns somehow? | I'm a Django newbie who needs help: Even though I change some urls in my urls.py I keep on getting the same error message from Django. Here is the relevant line from my settings.py:
ROOT_URLCONF = 'mydjango.urls'
Here is my urls.py:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the... | [
"Django compiles the URL regexes when it starts up for performance reasons - restart your server and you should see the new URL working correctly.\n"
] | [
7
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0002737400_django_django_urls_python.txt |
Q:
working on lists in python
'm trying to make a small modification to django lfs project, that will allow me to deactivate products with no stocks. Unfortunatelly I'm just beginning to learn python, so I have big trouble with its syntax. That's what I'm trying to do. I'm using method 'is_variant' returning tru if m... | working on lists in python | 'm trying to make a small modification to django lfs project, that will allow me to deactivate products with no stocks. Unfortunatelly I'm just beginning to learn python, so I have big trouble with its syntax. That's what I'm trying to do. I'm using method 'is_variant' returning tru if my product is a sub type. If it i... | [
"First, I wouldn't call the list set, because this is a Python built-in method (see set). Use append on the list (your syntax is just incorrect and the error you get explicitly tells you so ;) ) and you have to initialize the list before:\ndef deactivate(self):\n\"\"\"If there are no stocks, deactivate the product.... | [
8,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002611307_django_django_models_python.txt |
Q:
How to install pyobjc on SnowLeopard's non-default python installation
I'm having problems installing pyobjc on SnowLeopard.
It came with python 2.6 but I need 2.5 so I have installed 2.5 successfully. After that I have installed xcode. After that I have installed pyobjc with "easy_install-2.5 pyobjc"
But when I s... | How to install pyobjc on SnowLeopard's non-default python installation | I'm having problems installing pyobjc on SnowLeopard.
It came with python 2.6 but I need 2.5 so I have installed 2.5 successfully. After that I have installed xcode. After that I have installed pyobjc with "easy_install-2.5 pyobjc"
But when I start my python 2.5 and from cmd line try to import Foundation, it says "no m... | [
"Ok, found what's wrong.\nMy SnowLeopard came with BOTH python 2.6 (default) and 2.5 installed\nXCode installed objc for both.\nSo basically I have broken my pythonpath etc with additional python 2.5 and objc manual installations, somehow libraries weren't compatible (mine and original python are both 2.5.4 but sli... | [
4
] | [] | [] | [
"cocoa",
"import",
"macos",
"pyobjc",
"python"
] | stackoverflow_0002722730_cocoa_import_macos_pyobjc_python.txt |
Q:
Adding CSRF protection to simple comment forms in Django
I have blog comment forms in Django and I would like to know the following:
Should I add CSRF to the forms?
If I want to use the simple "render_comment_form" method, how do I add it?
If I can't add it like that, what is the best practice for doing it?
Each... | Adding CSRF protection to simple comment forms in Django | I have blog comment forms in Django and I would like to know the following:
Should I add CSRF to the forms?
If I want to use the simple "render_comment_form" method, how do I add it?
If I can't add it like that, what is the best practice for doing it?
Each tutorial or discussion on the subject seems to have a differe... | [
"My answer assumes that you are using Django 1.2:\n\nYes! You should protect all your data that is sent by POST requests to the server against CSRF attacks.\nYou don't need to add the token yourself. This is already done by django. Have a look at the default template that is used by the render_comment_form tag and ... | [
1
] | [] | [] | [
"blogs",
"django",
"python"
] | stackoverflow_0002738120_blogs_django_python.txt |
Q:
trying to run werkzeug on apache (wsgi error)
My data_site.wsgi file:
import main
application = application()
Error i get at apache:
[Thu Apr 29 07:07:41 2010] [error] [client 81.167.201.136] Traceback (most recent call last):
[Thu Apr 29 07:07:41 2010] [error] [client 81.167.201.136] File "/var/www/vhosts/data... | trying to run werkzeug on apache (wsgi error) | My data_site.wsgi file:
import main
application = application()
Error i get at apache:
[Thu Apr 29 07:07:41 2010] [error] [client 81.167.201.136] Traceback (most recent call last):
[Thu Apr 29 07:07:41 2010] [error] [client 81.167.201.136] File "/var/www/vhosts/data.oddprojects.net/htdocs/data_site.wsgi", line 1, in... | [
"The PYTHONPATH under mod_wsgi doesn't include the directory the .wsgi is in. I often use something like the below in my .wsgi files.\nimport os, sys; sys.path.append(os.path.dirname(__file__))\n\n(You might opt for .insert(0, ...) instead of .append(...) if that works better for you.)\n"
] | [
3
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"werkzeug"
] | stackoverflow_0002738214_apache_mod_wsgi_python_werkzeug.txt |
Q:
Conditional Regular Expressions
I'm using Python and I want to use regular expressions to check if something "is part of an include list" but "is not part of an exclude list".
My include list is represented by a regex, for example:
And.*
Everything which starts with And.
Also the exclude list is represented by a ... | Conditional Regular Expressions | I'm using Python and I want to use regular expressions to check if something "is part of an include list" but "is not part of an exclude list".
My include list is represented by a regex, for example:
And.*
Everything which starts with And.
Also the exclude list is represented by a regex, for example:
(?!Andrea)
Every... | [
"Why not put both in one regex?\nAnd(?!rea$).*\n\nSince the lookahead only \"looks ahead\" without consuming any characters, this works just fine (well, this is the whole point of lookaround, actually).\nSo, in Python:\nif re.match(r\"And(?!rea$).*\", subject):\n # Successful match \n # Note that re.match alw... | [
2
] | [] | [] | [
"conditional",
"python",
"regex"
] | stackoverflow_0002738349_conditional_python_regex.txt |
Q:
What's the advantage of using 'with .. as' statement in Python?
with open("hello.txt", "wb") as f:
f.write("Hello Python!\n")
seems to be the same as
f = open("hello.txt", "wb")
f.write("Hello Python!\n")
f.close()
What's the advantage of using open .. as instead of f = ?
Is it just syntactic sugar? Just sav... | What's the advantage of using 'with .. as' statement in Python? |
with open("hello.txt", "wb") as f:
f.write("Hello Python!\n")
seems to be the same as
f = open("hello.txt", "wb")
f.write("Hello Python!\n")
f.close()
What's the advantage of using open .. as instead of f = ?
Is it just syntactic sugar? Just saving one line of code?
| [
"In order to be equivalent to the with statement version, the code you wrote should look instead like this:\nf = open(\"hello.txt\", \"wb\")\ntry:\n f.write(\"Hello Python!\\n\")\nfinally:\n f.close()\n\nWhile this might seem like syntactic sugar, it ensures that you release resources. Generally the world is ... | [
32,
13,
3
] | [] | [] | [
"python",
"with_statement"
] | stackoverflow_0002738365_python_with_statement.txt |
Q:
Error when running mmap related function in python 2.6
I tried to run the following code from http://docs.python.org/library/mmap.html
import mmap
# write a simple example file
with open("hello.txt", "wb") as f:
f.write("Hello Python!\n")
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0... | Error when running mmap related function in python 2.6 | I tried to run the following code from http://docs.python.org/library/mmap.html
import mmap
# write a simple example file
with open("hello.txt", "wb") as f:
f.write("Hello Python!\n")
with open("hello.txt", "r+b") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), 0)
# r... | [
"I think you're doing something weird calling your module mmap.py, and the import is getting confused and importing the same file instead... Try changing the name to something else (preferably not a standard library module name :p)\n"
] | [
7
] | [] | [] | [
"mmap",
"python"
] | stackoverflow_0002738344_mmap_python.txt |
Q:
running python from an android app
I am trying to run a python script through an application I've written. I found some pages which say that this piece of code is doing it, but I can't figure it out.
http://code.google.com/p/android-scripting/source/browse/android/AndroidScriptingEnvironment/src/com/google/ase/loc... | running python from an android app | I am trying to run a python script through an application I've written. I found some pages which say that this piece of code is doing it, but I can't figure it out.
http://code.google.com/p/android-scripting/source/browse/android/AndroidScriptingEnvironment/src/com/google/ase/locale/LocaleReceiver.java
Can someone expl... | [
"That's not exactly supported yet via ASE. You can launch a script from ASE's script directory (/sdcard/ase/scripts) via an intent though. See http://code.google.com/p/android-scripting/source/browse/android/Common/src/com/google/ase/IntentBuilders.java for the code that ASE uses to launch scripts itself.\n"
] | [
1
] | [] | [] | [
"android",
"android_scripting",
"java",
"python"
] | stackoverflow_0002733881_android_android_scripting_java_python.txt |
Q:
Exposing members or make them private in Python?
Is there a general convention about exposing members in Python classes? I know that this is a case of "it depends", but maybe there is a rule of thumb.
Private member:
class Node:
def __init__(self):
self.__children = []
def add_children(self, *args):
... | Exposing members or make them private in Python? | Is there a general convention about exposing members in Python classes? I know that this is a case of "it depends", but maybe there is a rule of thumb.
Private member:
class Node:
def __init__(self):
self.__children = []
def add_children(self, *args):
self.__children += args
node = Node()
node.add_childr... | [
"The prefix for \"private\" is a single underscore.\n__ is used to mangle the name and avoid some problems e.g. when using multiple inheritance.\nPersonnally I've never used it.\nIn any case, the members will still be publicly accessible; this is just a convention.\n",
"I believe it is more Pythonic to leave memb... | [
5,
3,
2,
2,
1,
0,
0
] | [] | [] | [
"oop",
"python",
"visibility"
] | stackoverflow_0002738153_oop_python_visibility.txt |
Q:
Extending a form field to add new validations
I've written an app that uses forms to collect information that is then sent in an email. Many of these forms have a filefield used to attach files to the email. I'd like to validate two things, the size of the file (to ensure the emails are accepted by our mail serv... | Extending a form field to add new validations | I've written an app that uses forms to collect information that is then sent in an email. Many of these forms have a filefield used to attach files to the email. I'd like to validate two things, the size of the file (to ensure the emails are accepted by our mail server. I'd also like to check the file extension, to ... | [
"Just overload the \"clean\" method:\ndef clean(self, data, initial=None):\n try:\n if data.size > somesize:\n raise ValidationError('File is too big')\n\n (junk, ext) = os.path.splitext(data.name)\n if not ext in ('.jpg', '.gif', '.png'):\n raise ValidationError('Inval... | [
2,
1,
0
] | [] | [] | [
"django",
"django_forms",
"oop",
"python"
] | stackoverflow_0002733740_django_django_forms_oop_python.txt |
Q:
itertools.islice compared to list slice
I've been trying to apply an algorithm to reduce a python list into a smaller one based on a certain criteria. Due to the large volume of the original list, in the order of 100k elements, I tried to itertools for avoiding multiple memory allocations so I came up with this:
r... | itertools.islice compared to list slice | I've been trying to apply an algorithm to reduce a python list into a smaller one based on a certain criteria. Due to the large volume of the original list, in the order of 100k elements, I tried to itertools for avoiding multiple memory allocations so I came up with this:
reducedVec = [ 'F' if sum( 1 for x in islice(v... | [
"islice works with arbitrary iterables. To do this, rather than jumping straight to the nth element, it has to iterate over the first n-1, throwing them away, then yield the ones you want.\nCheck out the pure Python implementation from the itertools documentation:\ndef islice(iterable, *args):\n # islice('ABCDEF... | [
13,
1
] | [] | [] | [
"iteration",
"performance",
"python"
] | stackoverflow_0002738096_iteration_performance_python.txt |
Q:
In Windows shell scripting (cmd.exe) how do you assign the stdout of a program to an environment variable?
In UNIX you can assign the output of a script to an environment variable using the technique explained here - but what is the Windows equivalent?
I have a python utility which is intended to correct an enviro... | In Windows shell scripting (cmd.exe) how do you assign the stdout of a program to an environment variable? | In UNIX you can assign the output of a script to an environment variable using the technique explained here - but what is the Windows equivalent?
I have a python utility which is intended to correct an environment variable. This script simply writes a sequence of chars to stdout. For the purposes of this question, the ... | [
"Use:\nfor /f \"delims=\" %A in ('<insert command here>') do @set <variable name>=%A\n\nFor example: \nfor /f \"delims=\" %A in ('time /t') do @set my_env_var=%A\n\n...will run the command \"time /t\" and set the env variable \"my_env_var\" to the result.\nRemember to use %%A instead of %A if you're running this i... | [
12
] | [] | [] | [
"cmd",
"python",
"windows"
] | stackoverflow_0002738673_cmd_python_windows.txt |
Q:
Lisp's "some" in Python?
I have a list of strings and a list of filters (which are also strings, to be interpreted as regular expressions). I want a list of all the elements in my string list that are accepted by at least one of the filters. Ideally, I'd write
[s for s in strings if some (lambda f: re.match (f, ... | Lisp's "some" in Python? | I have a list of strings and a list of filters (which are also strings, to be interpreted as regular expressions). I want a list of all the elements in my string list that are accepted by at least one of the filters. Ideally, I'd write
[s for s in strings if some (lambda f: re.match (f, s), filters)]
where some is d... | [
"There is a function called any which does roughly want you want. I think you are looking for this:\n[s for s in strings if any(re.match(f, s) for f in filters)]\n\n",
"[s for s in strings if any(re.match (f, s) for f in filters)]\n\n",
"Python lambda's are only a fraction as powerful as their LISP counterparts... | [
22,
7,
1
] | [] | [] | [
"lisp",
"python"
] | stackoverflow_0002738777_lisp_python.txt |
Q:
Python - do big doc strings waste memory?
I understand that in Python a string is simply an expression and a string by itself would be garbage collected immediately upon return of control to a code's caller, but...
Large class/method doc strings in
your code: do they waste memory
by building the string objects up... | Python - do big doc strings waste memory? | I understand that in Python a string is simply an expression and a string by itself would be garbage collected immediately upon return of control to a code's caller, but...
Large class/method doc strings in
your code: do they waste memory
by building the string objects up?
Module level doc strings: are they
stored inf... | [
"\n\"I understand that in Python a string is simply an expression and a string by itself would be garbage collected immediately upon return of control to a code's caller\" indicates a misunderstanding, I think. A docstring is evaluated once (not on every function call) and stays alive at least as long as the functi... | [
10,
2
] | [] | [] | [
"docstring",
"memory_management",
"python"
] | stackoverflow_0002738904_docstring_memory_management_python.txt |
Q:
Python debugging in Eclipse+PyDev
I try Eclipse+PyDev pair for some of my work. (Eclipse v3.5.0 + PyDev v1.5.6) I couldn't find a way to expose all of my variables to the PyDev console (Through PyDev console -> Console for current active editor option) I use a simple code to describe the issue. When I step-by-step... | Python debugging in Eclipse+PyDev | I try Eclipse+PyDev pair for some of my work. (Eclipse v3.5.0 + PyDev v1.5.6) I couldn't find a way to expose all of my variables to the PyDev console (Through PyDev console -> Console for current active editor option) I use a simple code to describe the issue. When I step-by-step go through the code I can't access my ... | [
"Update:\nIn the latest PyDev versions, it's possible to right-click a frame in the stack and select PyDev > Debug console to have the interactive console with more functions associated to a context during a debug session.\n\nUnfortunately, the actual interactive console, which would be the preferred way of playing... | [
8,
2
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0002704932_eclipse_pydev_python.txt |
Q:
Python - question regarding the concurrent use of `multiprocess`
I want to use Python's multiprocessing to do concurrent processing without using locks (locks to me are the opposite of multiprocessing) because I want to build up multiple reports from different resources at the exact same time during a web request ... | Python - question regarding the concurrent use of `multiprocess` | I want to use Python's multiprocessing to do concurrent processing without using locks (locks to me are the opposite of multiprocessing) because I want to build up multiple reports from different resources at the exact same time during a web request (normally takes about 3 seconds but with multiprocessing I can do it i... | [
"You are barking up the wrong tree if you are trying to use multiprocess to add concurrency to a network app. You are barking up a completely wrong tree if you're creating processes for each request. multiprocess is not what you want (at least as a concurrency model).\nThere's a good chance you want an asynchronous... | [
2,
2,
1
] | [] | [] | [
"gil",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0002738959_gil_multiprocessing_multithreading_python.txt |
Q:
have you got a py-poppler-qt example?
I'm developing an application in PyQt4 that eventually has to open and show PDF files. For this task there is a python library: python-poppler (in various spelling flavours).
The problem is that it is terribly under documented and the only simple working example I found so fa... | have you got a py-poppler-qt example? | I'm developing an application in PyQt4 that eventually has to open and show PDF files. For this task there is a python library: python-poppler (in various spelling flavours).
The problem is that it is terribly under documented and the only simple working example I found so far uses Python+Gtk+Cairo, while the example ... | [
"There is an example buried deep within an experimental (unused) branch of an app, here is a link to the specific file containing the code. Don't know if it'll help? All the relevant poppler code is self contained within the PdfViewer class at the bottom of that file.\nhttp://bazaar.launchpad.net/~j-corwin/openlp/p... | [
5
] | [] | [] | [
"poppler",
"pyqt4",
"python",
"qt"
] | stackoverflow_0002507498_poppler_pyqt4_python_qt.txt |
Q:
2D list has weird behavor when trying to modify a single value
Possible Duplicate:
Unexpected feature in a Python list of lists
So I am relatively new to Python and I am having trouble working with 2D Lists.
Here's my code:
data = [[None]*5]*5
data[0][0] = 'Cell A1'
print data
and here is the output (formatted ... | 2D list has weird behavor when trying to modify a single value |
Possible Duplicate:
Unexpected feature in a Python list of lists
So I am relatively new to Python and I am having trouble working with 2D Lists.
Here's my code:
data = [[None]*5]*5
data[0][0] = 'Cell A1'
print data
and here is the output (formatted for readability):
[['Cell A1', None, None, None, None],
['Cell A1'... | [
"This makes a list with five references to the same list:\ndata = [[None]*5]*5\n\nUse something like this instead which creates five separate lists:\n>>> data = [[None]*5 for _ in range(5)]\n\nNow it does what you expect:\n>>> data[0][0] = 'Cell A1'\n>>> print data\n[['Cell A1', None, None, None, None],\n [None, No... | [
116,
18,
2
] | [] | [] | [
"2d",
"list",
"python",
"python_2.7"
] | stackoverflow_0002739552_2d_list_python_python_2.7.txt |
Q:
Extract list of attributes from list of objects in python
I have an uniform list of objects in python:
class myClass(object):
def __init__(self, attr):
self.attr = attr
self.other = None
objs = [myClass (i) for i in range(10)]
Now I want to extract a list with some attribute of that class (le... | Extract list of attributes from list of objects in python | I have an uniform list of objects in python:
class myClass(object):
def __init__(self, attr):
self.attr = attr
self.other = None
objs = [myClass (i) for i in range(10)]
Now I want to extract a list with some attribute of that class (let's say attr), in order to pass it so some function (for plotti... | [
"attrs = [o.attr for o in objs] was the right code for making a list like the one you describe. Don't try to subclass list for this. Is there something you did not like about that snippet?\n",
"You can also write:\nattr=(o.attr for o in objsm)\n\nThis way you get a generator that conserves memory. For more benefi... | [
115,
104
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0002739800_list_loops_python.txt |
Q:
Python: Created nested dictionary from list of paths
I have a list of tuples the looks similar to this (simplified here, there are over 14,000 of these tuples with more complicated paths than Obj.part)
[ (Obj1.part1, {<SPEC>}), (Obj1.partN, {<SPEC>}), (ObjK.partN, {<SPEC>}) ]
Where Obj goes from 1 - 1000, part fro... | Python: Created nested dictionary from list of paths | I have a list of tuples the looks similar to this (simplified here, there are over 14,000 of these tuples with more complicated paths than Obj.part)
[ (Obj1.part1, {<SPEC>}), (Obj1.partN, {<SPEC>}), (ObjK.partN, {<SPEC>}) ]
Where Obj goes from 1 - 1000, part from 0 - 2000. These "keys" all have a dictionary of specs a... | [
"Unless you prefer to access the specs with dot notation, try putting them into the dictionary directly. In the below code, the name d tracks the innermost dictionary visited on the path:\nspecs = {}\nfor path, spec in paths:\n parts = path.split('.')\n d = specs\n for p in parts[:-1]:\n d = d.setd... | [
8
] | [] | [] | [
"nested",
"path",
"python"
] | stackoverflow_0002738141_nested_path_python.txt |
Q:
Python raises a KeyError (for an out of dictionary key) even though the key IS in the dictionary
I'm getting a KeyError for an out of dictionary key, even though I know the key IS in fact in the dictionary. Any ideas as to what might be causing this?
print G.keys()
returns the following:
['24', '25', '20', '21', ... | Python raises a KeyError (for an out of dictionary key) even though the key IS in the dictionary | I'm getting a KeyError for an out of dictionary key, even though I know the key IS in fact in the dictionary. Any ideas as to what might be causing this?
print G.keys()
returns the following:
['24', '25', '20', '21', '22', '23', '1', '3', '2', '5', '4', '7', '6', '9', '8', '11', '10', '13', '12', '15', '14', '17', '16... | [
"That's simple, 17 != '17'\n",
"The keys are strings, you are trying to access them as ints.\n",
"try with v = '17'. You must convert your int to string\n"
] | [
28,
5,
3
] | [] | [] | [
"dictionary",
"exception",
"key",
"python"
] | stackoverflow_0002740036_dictionary_exception_key_python.txt |
Q:
Why are underscores better than hyphens for file names?
From Building Skills in Python:
A file name like exercise_1.py is better than the name exercise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisticated programs... | Why are underscores better than hyphens for file names? | From Building Skills in Python:
A file name like exercise_1.py is better than the name exercise-1.py. We can run both programs equally well from the command line, but the name with the hyphen limits our ability to write larger and more sophisticated programs.
Why is this?
| [
"The issue here is that importing files with the hyphen-minus (the default keyboard key -; U+002D) in their name doesn't work since it represents minus signs in Python. So, if you had your own module you wanted to import, it shouldn't have a hyphen in its name:\n>>> import test-1\n File \"<stdin>\", line 1\n im... | [
82,
23
] | [] | [] | [
"naming",
"python"
] | stackoverflow_0002740026_naming_python.txt |
Q:
Are there some cases where Python threads can safely manipulate shared state?
Some discussion in another question has encouraged me to to better understand cases where locking is required in multithreaded Python programs.
Per this article on threading in Python, I have several solid, testable examples of pitfalls ... | Are there some cases where Python threads can safely manipulate shared state? | Some discussion in another question has encouraged me to to better understand cases where locking is required in multithreaded Python programs.
Per this article on threading in Python, I have several solid, testable examples of pitfalls that can occur when multiple threads access shared state. The example race conditi... | [
"Appending to a list is thread-safe, yes. You can only append to a list while holding the GIL, and the list takes care not to release the GIL during the append operation (which is, after all, a fairly simple operation.) The order in which different thread's append operations go through is of course up for grabs, bu... | [
7,
1
] | [] | [] | [
"gil",
"multithreading",
"python"
] | stackoverflow_0002740435_gil_multithreading_python.txt |
Q:
Email attachment problem
I want to send an email with an attachment using the following code (Python 3.1)
(greatly simplified to show the example)
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = ... | Email attachment problem | I want to send an email with an attachment using the following code (Python 3.1)
(greatly simplified to show the example)
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
msg.attach(MIMEText(bo... | [
"Use:\nmsg.attach(msg1)\n\n"
] | [
3
] | [] | [] | [
"attachment",
"email",
"python"
] | stackoverflow_0002740605_attachment_email_python.txt |
Q:
Issue with python string join
I have some code in which I apply a join to a list.
The list before the join looks like this:
["'DealerwebAgcy_NYK_GW_UAT'", "'DealerwebAgcy'", "'UAT'", '@ECNPhysicalMarketCo
nfigId', "'GATEWAY'", "'DEALERWEB_MD_AGCY'", "'NU1MKVETC'", "'mkvetcu'", "'C:\te
mp'", '0', "'NYK'", '0',... | Issue with python string join | I have some code in which I apply a join to a list.
The list before the join looks like this:
["'DealerwebAgcy_NYK_GW_UAT'", "'DealerwebAgcy'", "'UAT'", '@ECNPhysicalMarketCo
nfigId', "'GATEWAY'", "'DEALERWEB_MD_AGCY'", "'NU1MKVETC'", "'mkvetcu'", "'C:\te
mp'", '0', "'NYK'", '0', '1', "'isqlw.exe'", 'GetDate()', '... | [
"\\t is a tab character.\nYou have two options: 1) make the string be \"c:\\\\temp\", or 2) use r\"c:\\temp\"\n"
] | [
5
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0002740772_list_python_string.txt |
Q:
Could somebody give me a high-level technical overview of WSGI details behind the scenes vs other web interface approaces with Python?
Firstly:
I understand what WSGI is and how to use it
I understand what "other" methods (Apache mod-python, fcgi, et al) are, and how to use them
I understand their practical diffe... | Could somebody give me a high-level technical overview of WSGI details behind the scenes vs other web interface approaces with Python? | Firstly:
I understand what WSGI is and how to use it
I understand what "other" methods (Apache mod-python, fcgi, et al) are, and how to use them
I understand their practical differences
What I don't understand is how each of the various "other" methods work compared to something like UWSGI, behind the scenes. Does yo... | [
"Except for CGI, a new Python interpreter is nearly never created per request. Read:\nhttp://blog.dscpl.com.au/2009/03/python-interpreter-is-not-created-for.html\nThis was written in respect of mod_python but also applies to mod_wsgi and any WSGI hosting mechanism that uses persistent processes.\nAlso read:\nhttp:/... | [
8
] | [] | [] | [
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0002739892_mod_wsgi_python_wsgi.txt |
Q:
Scraping *.aspx content using Python
I'm having difficulties scraping dynamically generated table in ASPX. Trying to scrape the gas prices from a site like this GasPrices. I can extract all the information in the gas price table (address, time submitted etc.), except for the actual gas price.
Is there a way I cou... | Scraping *.aspx content using Python | I'm having difficulties scraping dynamically generated table in ASPX. Trying to scrape the gas prices from a site like this GasPrices. I can extract all the information in the gas price table (address, time submitted etc.), except for the actual gas price.
Is there a way I could scrape the gas prices? i.e. somehow get... | [
"The origin of the page (aspx) is not an issue here.\nIt looks like they're actively trying to thwart scraping attempts. The numbers are not fonts, rather they several div elements next to one another with background images that are numbers. They really don't want to be scraped. \n(of course, if you were really det... | [
4
] | [] | [] | [
"asp.net",
"python",
"web_scraping"
] | stackoverflow_0002741425_asp.net_python_web_scraping.txt |
Q:
How to use a Python REPL in a script
I am learning Python to use QT with Python, not only C++, and am curious if I can embed a Python interpreter in my application as a REPL?
I want to allow users to script either loading a file and that file act as a plugin, or by evaluating code entered in a text box or somethin... | How to use a Python REPL in a script | I am learning Python to use QT with Python, not only C++, and am curious if I can embed a Python interpreter in my application as a REPL?
I want to allow users to script either loading a file and that file act as a plugin, or by evaluating code entered in a text box or something similar to embedding the interpreter in ... | [
"Well, this is all certainly possible, but it is not beginner stuff.\nPython offers a read-eval loop as a module, but you'd still have so create a console in QT where you can type in input and display results.\nThe same goes for a plugin system. It's very easy to import a script as a plugin and the plugin just has ... | [
2
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0002741368_python_scripting.txt |
Q:
a more pythonic way to express conditionally bounded loop?
I've got a loop that wants to execute to exhaustion or until some user specified limit is reached. I've got a construct that looks bad yet I can't seem to find a more elegant way to express it; is there one?
def ello_bruce(limit=None):
for i in xrange(... | a more pythonic way to express conditionally bounded loop? | I've got a loop that wants to execute to exhaustion or until some user specified limit is reached. I've got a construct that looks bad yet I can't seem to find a more elegant way to express it; is there one?
def ello_bruce(limit=None):
for i in xrange(10**5):
if predicate(i):
if not limit is Non... | [
"Maybe something like this would be a little better:\nfrom itertools import ifilter, islice\n\ndef ello_bruce(limit=None):\n for i in islice(ifilter(predicate, xrange(10**5)), limit):\n # do whatever you want with i here\n\n",
"I'd take a good look at the itertools library. Using that, I think you'd ha... | [
11,
2,
1,
1,
0,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0002711289_coding_style_python.txt |
Q:
How do I do an "OR" for my python regex?
re.compile("abc")
I would like to do "abc" OR "xyz".
A:
Use |:
re.compile("abc|xyz")
It's worth perusing regular-expression.info for detailed information as well as Regular Expression HOWTO and re — Regular expression operations from the Python documentation.
A:
I'll ... | How do I do an "OR" for my python regex? | re.compile("abc")
I would like to do "abc" OR "xyz".
| [
"Use |:\nre.compile(\"abc|xyz\")\n\nIt's worth perusing regular-expression.info for detailed information as well as Regular Expression HOWTO and re — Regular expression operations from the Python documentation.\n",
"I'll take this opportunity to point you to an excellent reference for many of life's problems: Wik... | [
11,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002734010_python_regex.txt |
Q:
about python scripting
I have this code
class HNCS (ThreadingTCPServer):
def verify_request(self, request, client_address):
for key in connections:
if connections[key].client_address[0] == client_address[0]:
if client_address[0] != '127.0.0.1':
retu... | about python scripting | I have this code
class HNCS (ThreadingTCPServer):
def verify_request(self, request, client_address):
for key in connections:
if connections[key].client_address[0] == client_address[0]:
if client_address[0] != '127.0.0.1':
return False
return Tru... | [
"Perhaps the dictionary is storing values which are objects that happen to have a client_address member property?\nIn other words, the .client_address there isn't the same thing as the client_address passed in as an argument. Instead, it's the name of a field within a class that happens to be stored in connections[... | [
2,
1,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002741440_oop_python.txt |
Q:
mysqldb python escaping ? or %s?
I am currently using mysqldb.
What is the correct way to escape strings in mysqldb arguments?
Note that E = lambda x: x.encode('utf-8')
1) so my connection is set with charset='utf8'.
These are the errors I am getting for these arguments: w1, w2 = u'你好', u'我好'
self.cur.execute("SEL... | mysqldb python escaping ? or %s? | I am currently using mysqldb.
What is the correct way to escape strings in mysqldb arguments?
Note that E = lambda x: x.encode('utf-8')
1) so my connection is set with charset='utf8'.
These are the errors I am getting for these arguments: w1, w2 = u'你好', u'我好'
self.cur.execute("SELECT dist FROM distance WHERE w1=? AND ... | [
"To be more specific ... the cursor.execute() method takes an optional argument which contains values to be quoted and interpolated into the SQL template/statement. This is NOT done with a simple % operator! cursor.execute(some_sql, some_params) is NOT the same as cursor.execute(some_sql % some_params)\nThe Pytho... | [
4,
1,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002490852_mysql_python.txt |
Q:
Search over multiple fields
I think I don't unterstand django-haystack properly:
I have a data model containing several fields, and I would to have two of them searched:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=None)
twitter_account = models.CharField(max_length=... | Search over multiple fields | I think I don't unterstand django-haystack properly:
I have a data model containing several fields, and I would to have two of them searched:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=None)
twitter_account = models.CharField(max_length=50, blank=False)
My search index... | [
"I guess thats because haystack uses the document field for generic searches unless you define a specific search for other fields like the twitter_account field.\nfrom haystack documentation\n\nEvery SearchIndex requires there be\n one (and only one) field with\n document=True. This indicates to both\n Haystack ... | [
9
] | [] | [] | [
"django",
"django_haystack",
"python"
] | stackoverflow_0002732898_django_django_haystack_python.txt |
Q:
Python Profiling In Windows, How do you ignore Builtin Functions
I have not been capable of finding this anywhere online. I was looking to find out using a profiler how to better optimize my code, and when sorting by which functions use up the most time cumulatively, things like str(), print, and other similar wi... | Python Profiling In Windows, How do you ignore Builtin Functions | I have not been capable of finding this anywhere online. I was looking to find out using a profiler how to better optimize my code, and when sorting by which functions use up the most time cumulatively, things like str(), print, and other similar widely used functions eat up much of the profile. What is the best way t... | [
"OK, I assume your real goal is to make your code as fast as reasonably possible, right?\nIt is natural to assume you do that by finding out how long your functions take, but there is another way to look at it.\nConsider as your program runs it traces out a call tree, which is kind of like a real tree outside your ... | [
9
] | [] | [] | [
"built_in",
"cprofile",
"optimization",
"profiling",
"python"
] | stackoverflow_0002741520_built_in_cprofile_optimization_profiling_python.txt |
Q:
Can't run os.system command in Django?
We have a Django app running on apache server (mod_python) on a windows machine which needs to call some r scripts. To do so it would be easiest to call r through os.system, however when django gets to the os.system command it freezes up. I've also tried subprocess with the... | Can't run os.system command in Django? | We have a Django app running on apache server (mod_python) on a windows machine which needs to call some r scripts. To do so it would be easiest to call r through os.system, however when django gets to the os.system command it freezes up. I've also tried subprocess with the same result.
We have a possibly related pro... | [
"Instead of os.system, would RPy2 meet your needs? I've used it in a similar case to the one you're describing with Django, and it's worked quite well.\n\nThe high-level interface in rpy2 is designed to facilitate the use of R by Python programmers. R objects are exposed as instances of Python-implemented classes,... | [
1
] | [] | [] | [
"apache",
"django",
"python",
"windows"
] | stackoverflow_0002741662_apache_django_python_windows.txt |
Q:
Url for the current page from a Mako template in Pylons
I need to know the full url for the current page from within a Mako template file in Pylons.
The url will be using in an iframe contained within the page so it needs to be known when the page is being generated rather than after the page hits the server or fr... | Url for the current page from a Mako template in Pylons | I need to know the full url for the current page from within a Mako template file in Pylons.
The url will be using in an iframe contained within the page so it needs to be known when the page is being generated rather than after the page hits the server or from the environment. (Not sure if I am communicating that last... | [
"Not sure if this is the Pylons way of doing things but ${request.url} seems to work for me.\n",
"I think you can use h.url_for('', qualified=True) to get the full URL. \nMake sure you have imported url_for in your helper file: from routes.util import helpers as h\nHave a look at http://pylonshq.com/docs/en/0.9.7... | [
4,
0
] | [] | [] | [
"mako",
"pylons",
"python",
"templates"
] | stackoverflow_0002741893_mako_pylons_python_templates.txt |
Q:
Unable to open images with Python's Image.open()
My code reads:
import Image
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
When I call this function, I get an error:
⇝ AttributeError: type object 'Image' has no attribute 'open'
H... | Unable to open images with Python's Image.open() | My code reads:
import Image
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
When I call this function, I get an error:
⇝ AttributeError: type object 'Image' has no attribute 'open'
However in the console:
import Image
im = Image.open('t... | [
"It's odd that you're getting an exception about Image being a type object, not a module. Is 'Image' being assigned to elsewhere in your code?\n",
"Does your actual code have the incorrect statements:\nfrom Image import Image\n\nor\nfrom Image import *\n\nThe Image module contains an Image class, but they are of... | [
4,
1,
0
] | [] | [] | [
"image",
"pylons",
"python"
] | stackoverflow_0002742085_image_pylons_python.txt |
Q:
installing python packages on android
I want to install a python package from source on android. Is this possible? I tried in the console to run the py install files, but distutils (.core, ccompiler) isn't being found. Is it possible to still install them?
A:
Android does not ship with a Python interpreter, nor ... | installing python packages on android | I want to install a python package from source on android. Is this possible? I tried in the console to run the py install files, but distutils (.core, ccompiler) isn't being found. Is it possible to still install them?
| [
"Android does not ship with a Python interpreter, nor does it ship with gcc or other compilers. You will need to get an ARM binary from somewhere or cross-compile one yourself. (BTW, I'm assuming ARM, but substitute in whatever architecture you happen to be running).\n",
"If you're using ASE (Android Scripting En... | [
1,
0
] | [] | [] | [
"android",
"android_scripting",
"java",
"python"
] | stackoverflow_0002733971_android_android_scripting_java_python.txt |
Q:
Using Android's `Timer.schedule` in Python
Could someone explain how to use the Timer.schedule - that is used for scheduling tasks - in Python?
Note that Python's time.sleep will not work in Android.
A:
time.sleep does work on the Android Scripting Environment (at least for the last 5 releases or so). I've just ... | Using Android's `Timer.schedule` in Python | Could someone explain how to use the Timer.schedule - that is used for scheduling tasks - in Python?
Note that Python's time.sleep will not work in Android.
| [
"time.sleep does work on the Android Scripting Environment (at least for the last 5 releases or so). I've just tested it on the interpreter console.\nOn the other hand, some dialogs (like makeToast, for instance) won't hold the script execution while they're being displayed. Perhaps that's why you may be feeling ti... | [
0
] | [] | [] | [
"android",
"android_scripting",
"python",
"timer"
] | stackoverflow_0002115227_android_android_scripting_python_timer.txt |
Q:
Python match and return string in between
I have following code
stringA = "xxxxxxFoundAaaaaaaaaaaaaaaFoundBxxxxxxx"
stringB = "FoundA"
stringC = "FoundB"
How do I do a regular expression in python in order to return aaaaaaaaaaaaaa?
A:
>>>
>>> stringA = "xxxxxxFoundAaaaaaaaaaaaaaaFoundBxxxxxxx"
>>> stringB = "Fo... | Python match and return string in between | I have following code
stringA = "xxxxxxFoundAaaaaaaaaaaaaaaFoundBxxxxxxx"
stringB = "FoundA"
stringC = "FoundB"
How do I do a regular expression in python in order to return aaaaaaaaaaaaaa?
| [
">>>\n>>> stringA = \"xxxxxxFoundAaaaaaaaaaaaaaaFoundBxxxxxxx\"\n>>> stringB = \"FoundA\"\n>>> stringC = \"FoundB\"\n>>>\n>>> import re\n>>> re.search(re.escape(stringB)+\"(.*?)\"+re.escape(stringC),stringA).group(1)\n'aaaaaaaaaaaaaa'\n>>>\n\n",
"re.search(re.escape(stringB) + \"(.*?)\" + re.escape(stringC), stri... | [
14,
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002742309_python_regex.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.