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:
Potential use of Python decorator or other refactorization: iterative optimization
Forgive me for yet another question on Python decorators. I did read through many of them, but I wonder what the best solution to the specific following problem is.
I have written several functions that do some form of gradient desc... | Potential use of Python decorator or other refactorization: iterative optimization | Forgive me for yet another question on Python decorators. I did read through many of them, but I wonder what the best solution to the specific following problem is.
I have written several functions that do some form of gradient descent in numpy/scipy. Given a matrix X, I try to iteratively minimize some distance, d(X, ... | [
"The following should work well as the decorator you want to use:\nimport functools\n\ndef iterate(update):\n @functools.wraps(update)\n def inner(X, A=None, S=None, K=2, maxiter=10, c=0.1):\n M, N = X.shape\n O = matrix(ones([M, N]))\n if A is None:\n A = matrix(rand(M, K))\n ... | [
5
] | [] | [] | [
"decorator",
"numpy",
"python",
"refactoring"
] | stackoverflow_0002306171_decorator_numpy_python_refactoring.txt |
Q:
How to write XML elements with namespaces in python
I just tried this python 2.5 snippet to write some XML:
xmldoc = xml.dom.minidom.Document()
feed = xmldoc.createElementNS("http://www.w3.org/2005/Atom", "feed")
xmldoc.appendChild(feed)
print xmldoc.toprettyxml()
I expected the output to look like this:
<?xml ve... | How to write XML elements with namespaces in python | I just tried this python 2.5 snippet to write some XML:
xmldoc = xml.dom.minidom.Document()
feed = xmldoc.createElementNS("http://www.w3.org/2005/Atom", "feed")
xmldoc.appendChild(feed)
print xmldoc.toprettyxml()
I expected the output to look like this:
<?xml version="1.0" ?>
<feed xmlns="http://www.w3.org/2005/Atom" ... | [
"minidom does not support namespace normalization. The only workaround I'm aware of is explicitely setting the xmlns attribute with\nxmldoc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2005/Atom')\n\n"
] | [
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002306149_python_xml.txt |
Q:
Fast python XML validator with XPath support
I need to read a large XML (65 Mb), validate it against a xsd, and run XPath queries on it. Below, I've given an lxml version of that. It takes a lot of time (over 5 minutes) to run the query but validation seems to be pretty quick.
I've a couple of questions. How woul... | Fast python XML validator with XPath support | I need to read a large XML (65 Mb), validate it against a xsd, and run XPath queries on it. Below, I've given an lxml version of that. It takes a lot of time (over 5 minutes) to run the query but validation seems to be pretty quick.
I've a couple of questions. How would a performance minded Python programmer write the... | [
"I wonder if you can rewrite the xpath expression to run faster? One thing that may work is to avoid building the name_list nodeset (if you don't need it later) and have the nodes counted inside of lxml. Something like this:\nstart = datetime.now()\nname_list_len = root.xpath(\"count(/book/author/name/text())\")\np... | [
0,
0
] | [] | [] | [
"python",
"validation",
"xml",
"xpath",
"xsd"
] | stackoverflow_0002302709_python_validation_xml_xpath_xsd.txt |
Q:
Reading text files into list, then storing in dictionay fills system memory ? (A what am I doing wrong?) Python
I have 43 text files that consume "232.2 MB on disk (232,129,355 bytes) for 43 items". what to read them in to memory (see code below). The problem I am having is that each file which is about 5.3mb on d... | Reading text files into list, then storing in dictionay fills system memory ? (A what am I doing wrong?) Python | I have 43 text files that consume "232.2 MB on disk (232,129,355 bytes) for 43 items". what to read them in to memory (see code below). The problem I am having is that each file which is about 5.3mb on disk is causing python to use an additional 100mb of system memory. If check the size of the dict() getsizeof() (see s... | [
"The dictionary itself is very small - the bulk of the data is the whole content of the files stored in lists, containing one tuple per line. The 20x size increase is bigger than I expected but seems to be real. Splitting a 27-bytes line from your example input into a tuple, gives me 309 bytes (counting recursive... | [
3,
2
] | [] | [] | [
"file",
"memory",
"python"
] | stackoverflow_0002306523_file_memory_python.txt |
Q:
python random.random() causes "'module' object is not callable" when used in custom template tag
If I start python from the command line and type:
import random
print "Random: " + str(random.random())
It prints me a random number (Expected, excellent).
If I include the above-two lines in my django application's ... | python random.random() causes "'module' object is not callable" when used in custom template tag | If I start python from the command line and type:
import random
print "Random: " + str(random.random())
It prints me a random number (Expected, excellent).
If I include the above-two lines in my django application's models.py and start my django app with runserver I get the output on the command line showing me a ran... | [
"The answer is ... strange.\nWhen I originally wrote my custom tag, I called it random.py. I quickly realized that this name may not be good and renamed it randomchoice.py and deleted my random.py file. Python kept the compiled random.pyc file around, and it was getting loaded whenever I did import random. I remove... | [
18,
5,
2
] | [] | [] | [
"django",
"python",
"random",
"templatetags"
] | stackoverflow_0000837916_django_python_random_templatetags.txt |
Q:
Seeing if a list exists within another list?
Basically lets say i have:
>>> a = [1,3,2,2,2]
>>> b = [1,3,2]
I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.
I am kinda hoping theres a really simple one line answer.
A:
This is a ... | Seeing if a list exists within another list? | Basically lets say i have:
>>> a = [1,3,2,2,2]
>>> b = [1,3,2]
I want to see if the all the elements in b, exists within a, and in the same order. So for the above example b would exist within a.
I am kinda hoping theres a really simple one line answer.
| [
"This is a simple O(n * m) algorithm:\nany(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))\n\nNote that is not the fastest way of doing this. If you need high performance you could use similar techniques to those used in string searching algorithms.\n",
"If by 'in the same order' you meant subsequence (... | [
6,
2,
1,
0,
0
] | [
"if its \"in the same order\", \n>>> a = [1,3,2,2,2]\n>>> b = [1,3,2]\n>>> ' '.join(map(str,b)) in ' '.join(map(str,a))\nTrue\n\n>>> a = [1,1,2,2,2,13,2]\n>>> b = [1,3,2]\n>>> ' '.join(map(str,b)) in ' '.join(map(str,a))\nFalse\n\n"
] | [
-2
] | [
"list",
"python"
] | stackoverflow_0002305729_list_python.txt |
Q:
Is there a open-search solution for python?
lucene-like would be preferred.
thanks
A:
You can also check ElasticSearch, it has native JSON interface so integrating with it in python should be simpler. Seems like Simon Willison thinks it got potential...
A:
Why you need lucene-like when you can use lucene (PyLu... | Is there a open-search solution for python? | lucene-like would be preferred.
thanks
| [
"You can also check ElasticSearch, it has native JSON interface so integrating with it in python should be simpler. Seems like Simon Willison thinks it got potential...\n",
"Why you need lucene-like when you can use lucene (PyLucene) :)\nhttp://lucene.apache.org/pylucene/\nIt is great and builds against the lates... | [
12,
10,
3,
1,
0,
0
] | [] | [] | [
"lucene",
"python",
"search"
] | stackoverflow_0002305026_lucene_python_search.txt |
Q:
Python class syntax - is this a good idea?
I'm tempted to define my Python classes like this:
class MyClass(object):
"""my docstring"""
msg = None
a_variable = None
some_dict = {}
def __init__(self, msg):
self.msg = msg
Is declaring the object variables (msg, a_variable, etc) at the ... | Python class syntax - is this a good idea? | I'm tempted to define my Python classes like this:
class MyClass(object):
"""my docstring"""
msg = None
a_variable = None
some_dict = {}
def __init__(self, msg):
self.msg = msg
Is declaring the object variables (msg, a_variable, etc) at the top, like Java good or bad or indifferent? I kno... | [
"Defining variables in the class defintion like that makes the variable accessible between every instance of that class. In Java terms it is a bit like making the variable static. However, there are major differences as show below.\nclass MyClass(object):\n msg = \"ABC\"\n\nprint MyClass.msg #prints ABC\na =... | [
8,
6,
4,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0002307590_python_syntax.txt |
Q:
Uploading a HTML file to Google App Engine - getting 405
I'm trying to do a simple echo app using Python. I want to submit a file with a POST form and echo it back (an HTML file).
Here's the handlers section of the YAML I'm using:
handlers:
- url: /statics
static_dir: statics
- url: .*
script: main.py
It's ... | Uploading a HTML file to Google App Engine - getting 405 | I'm trying to do a simple echo app using Python. I want to submit a file with a POST form and echo it back (an HTML file).
Here's the handlers section of the YAML I'm using:
handlers:
- url: /statics
static_dir: statics
- url: .*
script: main.py
It's basically the hello world example in main.py and I added a dir... | [
"You are submitting your form with the POST method, but you implemented a get() handler instead of a post() handler. Changing def get(self): to def post(self): should fix the HTTP 405 error.\n"
] | [
8
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002307645_google_app_engine_python.txt |
Q:
Integrating pygame with a C module
In my Python2_6/include directory is a folder with pygame headers. I assumed that my python C module can access pygame stuff directly in C. Is this the case? How do I integrate a C module that wants to use pygame, with a python script using pygame? Right now my brain sees:
pygame... | Integrating pygame with a C module | In my Python2_6/include directory is a folder with pygame headers. I assumed that my python C module can access pygame stuff directly in C. Is this the case? How do I integrate a C module that wants to use pygame, with a python script using pygame? Right now my brain sees:
pygame <-- MyCModule <-- MyScript --> pygame
i... | [
"\nI assumed that my python C module can\n access pygame stuff directly in C. Is\n this the case?\n\nNo, that stuff is most likely just there because it was necessary to compile the pygame Python extension.\nI don't understand what you mean when you say you see 2 pygame instances. There are as many instances as y... | [
0,
0
] | [] | [] | [
"module",
"pygame",
"python"
] | stackoverflow_0002171746_module_pygame_python.txt |
Q:
Python equivalent to Java's JNLP Web Start?
Is there any way to achieve the same functionality in Python, i.e., launching a script from a browser and automatically updating it from a central server location?
A:
Run your app on Jython and use Java Web Start?
From a comment below, http://blog.pyproject.ninja/posts... | Python equivalent to Java's JNLP Web Start? | Is there any way to achieve the same functionality in Python, i.e., launching a script from a browser and automatically updating it from a central server location?
| [
"Run your app on Jython and use Java Web Start?\nFrom a comment below, http://blog.pyproject.ninja/posts/2016-03-31-web-start-on-jython.html, provides a complete example.\nNote that Jython is not Python- some stuff does not work, and notably Jython is only Python-2.7 compatible.\n",
"Well this is still not a full... | [
8,
2,
1
] | [] | [] | [
"jnlp",
"python"
] | stackoverflow_0002248921_jnlp_python.txt |
Q:
Encoding detection library in python
This is somehow related to my question here.
I process tons of texts (in HTML and XML mainly) fetched via HTTP. I'm looking for a library in python that can do smart encoding detection based on different strategies and convert texts to unicode using best possible character enco... | Encoding detection library in python | This is somehow related to my question here.
I process tons of texts (in HTML and XML mainly) fetched via HTTP. I'm looking for a library in python that can do smart encoding detection based on different strategies and convert texts to unicode using best possible character encoding guess.
I found that chardet does auto... | [
"BeautifulSoup's UnicodeDammit, which in turn uses chardet.\nchardet by itself is quite useful for the general case (determining text's encoding) but slow as you say. UnicodeDammit adds extra features on top of chardet, in particular that it can look up the encoding explicitly specified in XML's encoding tags.\nAs ... | [
10,
3
] | [] | [] | [
"character_encoding",
"html",
"http",
"python",
"xml"
] | stackoverflow_0002307795_character_encoding_html_http_python_xml.txt |
Q:
How to find out the summarized text of a given URL in python / Django?
How to find out the summarized text for a given URL?
What do i mean by summarized text?
Merck $41.1 Billion Schering-Plough Bid Seeks Science
Link Descrption
Merck & Co.’s $41.1 billion purchase of Schering-Plough Corp. adds experimental drugs... | How to find out the summarized text of a given URL in python / Django? | How to find out the summarized text for a given URL?
What do i mean by summarized text?
Merck $41.1 Billion Schering-Plough Bid Seeks Science
Link Descrption
Merck & Co.’s $41.1 billion purchase of Schering-Plough Corp. adds experimental drugs for blood clots, infections and schizophrenia and allows the companies to s... | [
"I had the same need, and lemur, although it has summarization capabilities, I found it buggy to the point of being unusable. Over the weekend I used nltk to code up a summarize module in python: https://github.com/thavelick/summarize\nI took the algorithm from the Java library Classifier4J here: http://classifier... | [
22,
4,
4
] | [
"Your best bet in this case would be to use a HTML parsing library like BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/)\nFrom there, you can fetch for example, all the pages p tags:\n\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\npage = urllib2.urlopen(\"http://www.bloomberg.com/apps/newsp... | [
-4
] | [
"django",
"python"
] | stackoverflow_0000626754_django_python.txt |
Q:
Variable Files with Python
I am trying to have a file path like 'C:\Programfiles\file.txt' but i would like to have file.txt be a variable that i can change whenever i need to. I am trying to compare 2 directories then copy files from one to another if they arent already there. i have this code so far.
import os
i... | Variable Files with Python | I am trying to have a file path like 'C:\Programfiles\file.txt' but i would like to have file.txt be a variable that i can change whenever i need to. I am trying to compare 2 directories then copy files from one to another if they arent already there. i have this code so far.
import os
import shutil
A= set(os.listdir(r... | [
"Please use os.path.join to construct paths. Also, you should put the directories in variables for reuse. Furthermore you need to iterate over the difference between the folders (B - A) in order to get each filename that's in the difference set (C is the set of files that have been added!).\nHere's the corrected ve... | [
4,
2,
1
] | [] | [] | [
"file",
"python",
"python_3.x",
"variables"
] | stackoverflow_0002306947_file_python_python_3.x_variables.txt |
Q:
How does assignment of a function as a class attribute become a method in Python?
>>> class A(object): pass
>>> def func(cls): pass
>>> A.func = func
>>> A.func
<unbound method A.func>
How does this assignment create a method? It seems unintuitive that assignment does the following for classes:
Turn functions in... | How does assignment of a function as a class attribute become a method in Python? | >>> class A(object): pass
>>> def func(cls): pass
>>> A.func = func
>>> A.func
<unbound method A.func>
How does this assignment create a method? It seems unintuitive that assignment does the following for classes:
Turn functions into unbound instance methods
Turn functions wrapped in classmethod() into class methods ... | [
"Descriptors are the magic1 that turns an ordinary function into a bound or unbound method when you retrieve it from an instance or class, since they’re all just functions that need different binding strategies. The classmethod and staticmethod decorators implement other binding strategies, and staticmethod actuall... | [
4,
4,
3,
0,
0
] | [] | [] | [
"class_method",
"python"
] | stackoverflow_0002307653_class_method_python.txt |
Q:
Python - Spaces in Filenames
Possible Duplicate:
How to escape os.system() calls in Python?
Is there a Python method of making filenames safe (ie. putting \ infront of spaces and escaping ( , ), symbols) programatically in Python?
A:
Spaces are already "safe" for Python in open(). As for os.system() and simila... | Python - Spaces in Filenames |
Possible Duplicate:
How to escape os.system() calls in Python?
Is there a Python method of making filenames safe (ie. putting \ infront of spaces and escaping ( , ), symbols) programatically in Python?
| [
"Spaces are already \"safe\" for Python in open(). As for os.system() and similar functions, use subprocess instead.\n",
">>> import pipes\n>>> pipes.quote(\"\\&*!\")\n\"'\\\\&*!'\"\n\n"
] | [
3,
2
] | [] | [] | [
"file_io",
"linux",
"module",
"python"
] | stackoverflow_0002308394_file_io_linux_module_python.txt |
Q:
How to convert a numeric string with place-value commas into an integer?
In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?
A:
It really depends where you get your number from.
If the number you are trying to convert comes from user inp... | How to convert a numeric string with place-value commas into an integer? | In Python, what is a clean and elegant way to convert strings like "1,374" or "21,000,000" to int values like 1374 or 21000000?
| [
"It really depends where you get your number from.\nIf the number you are trying to convert comes from user input, use locale.atoi(). That way, the number will be parsed in a way that is consistent with the user's settings and thus expectations.\nIf on the other hand you read it, let's say, from a file, that always... | [
9,
4,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002308443_python.txt |
Q:
How can I have an encrypted input in Python?
I am writing a Python program that requires a user to input their gmail usernames and passwords. When the user types in their password, I want the characters to be displayed as asterisks. Is this possible for a command-line program?
A:
getpass.getpass() doesn't show a... | How can I have an encrypted input in Python? | I am writing a Python program that requires a user to input their gmail usernames and passwords. When the user types in their password, I want the characters to be displayed as asterisks. Is this possible for a command-line program?
| [
"getpass.getpass() doesn't show asterisks but instead suppresses all output, which is expected behavior on some systems.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0002308536_python.txt |
Q:
Pass array of structs from Python to C
[Update: Problem solved! See bottom of the post]
I need to allow python developers to pass an array of packed data (in this case vertices) into my API, which is a series of C++ interfaces exposed manually through the Python C API. My initial impression with this is to use the... | Pass array of structs from Python to C | [Update: Problem solved! See bottom of the post]
I need to allow python developers to pass an array of packed data (in this case vertices) into my API, which is a series of C++ interfaces exposed manually through the Python C API. My initial impression with this is to use the ctypes Structure class to allow for an inte... | [
"Not tested but you should give this a try and let us know if its fast enough for your needs.\nOn the python side, pack the vertices into a string instead of an object.\nstr = \"\" # byte stream for encoding data\nstr += struct.pack(\"5f i\", vert1.x, vert1.y, vert1.z, vert1.u, vert1.v, vert1.color) # 5 floats and ... | [
2,
1
] | [] | [] | [
"python",
"python_3.x",
"python_c_api",
"structure"
] | stackoverflow_0002307290_python_python_3.x_python_c_api_structure.txt |
Q:
why class creation throws error
Just playin around class
def func(*args, **kwargs):
print args, kwargs
class Klass(func): pass
it throws error
TypeError: Error when calling the
metaclass bases
function() argument 1 must be code, not str
What does it mean, i am passing no str nowhere?
and yes I shou... | why class creation throws error | Just playin around class
def func(*args, **kwargs):
print args, kwargs
class Klass(func): pass
it throws error
TypeError: Error when calling the
metaclass bases
function() argument 1 must be code, not str
What does it mean, i am passing no str nowhere?
and yes I should be passing class in bases but why ... | [
"see here for the reason for the cryptic msg\nhttp://bugs.python.org/issue6829\nquestions Error when calling the metaclass bases: function() argument 1 must be code, not str has same problem.\nEdit: play-around\nThough you can use metaclass to make it work in a twisted way ;)\ndef func(name, klassDict):\n return... | [
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002308945_class_python.txt |
Q:
Get class in Python decorator
In this code:
def online_only(func, self):
def f(*args, **kwargs):
if self.running:
return func(*args, **kwargs)
else:
return False
return f
class VM(object):
@property
def running(self):
return True
@property
@onlin... | Get class in Python decorator | In this code:
def online_only(func, self):
def f(*args, **kwargs):
if self.running:
return func(*args, **kwargs)
else:
return False
return f
class VM(object):
@property
def running(self):
return True
@property
@online_only
def diskinfo(self):
... | [
"self is passed as the first parameter to the wrapping function, so just treat the first parameter specially in f:\ndef online_only(func):\n def f(self, *args, **kwargs):\n if self.running:\n return func(self, *args, **kwargs)\n else:\n return False\n return f\n\n",
"\nYo... | [
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0002309124_python.txt |
Q:
IMEI number of a mobile phone using python
How can I get the IMEI number of a mobile phone using Python?
A:
Sending AT+CGSN through the appropriate serial device will have it return the IMEI.
| IMEI number of a mobile phone using python | How can I get the IMEI number of a mobile phone using Python?
| [
"Sending AT+CGSN through the appropriate serial device will have it return the IMEI.\n"
] | [
0
] | [] | [] | [
"imei",
"mobile_phones",
"python"
] | stackoverflow_0002309108_imei_mobile_phones_python.txt |
Q:
cx_Oracle, generators, and threads in Python
What is the behavior of cx_Oracle cursors when the connection object is used by different threads? How would generators affect this behavior? Specifically...
Edit: The original example function was incorrect; a generator was being returned by a sub function, yield was... | cx_Oracle, generators, and threads in Python | What is the behavior of cx_Oracle cursors when the connection object is used by different threads? How would generators affect this behavior? Specifically...
Edit: The original example function was incorrect; a generator was being returned by a sub function, yield wasn't used directly in the loop. This clarifies whe... | [
"See the docs: threadsafety is, and I quote,\n\nCurrently 2, which means that threads\n may share the module and connections,\n but not cursors.\n\nSo your \"pool of cursors\" construct (where one cursor may be used by different threads) seems to be beyond the threadsafety level. It's not an issue of sharing con... | [
2
] | [] | [] | [
"cx_oracle",
"generator",
"multithreading",
"python",
"yield"
] | stackoverflow_0002308698_cx_oracle_generator_multithreading_python_yield.txt |
Q:
How to fix the wxpython events called?
with this code:
import wx
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
panel = wx.Panel.__init__(self, parent, *args, **kwargs)
self.colorOver = ((89,89,89))
self.colorLeave = ((110,110,110))
self.colorFont = ((145... | How to fix the wxpython events called? | with this code:
import wx
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
panel = wx.Panel.__init__(self, parent, *args, **kwargs)
self.colorOver = ((89,89,89))
self.colorLeave = ((110,110,110))
self.colorFont = ((145,145,145))
self.SetBackgroundColour... | [
"Problem is you are hiding and showing bitmap on mouseover, so when you move mouseover bitmap, mouse goes off panel, onPanelMouseLeave is called and you hide bitmap, which means now mouse if over panel, onPanelMouseOver is called and in that event you again show bitmap and that means now mouse if over bitmap again ... | [
2
] | [] | [] | [
"button",
"events",
"panel",
"python",
"wxpython"
] | stackoverflow_0002306000_button_events_panel_python_wxpython.txt |
Q:
Sizing controls for items in wx.lib.CustomTreeCtrl
Is there a trick to sizing controls for wx.lib.CUstomTreeCtrl? I've been trying to create my own custom controls (just panels with sub-controls in them) and add them as items in my CustomTreeCtrl, but when the tree renders, it's as if the panels aren't expanded t... | Sizing controls for items in wx.lib.CustomTreeCtrl | Is there a trick to sizing controls for wx.lib.CUstomTreeCtrl? I've been trying to create my own custom controls (just panels with sub-controls in them) and add them as items in my CustomTreeCtrl, but when the tree renders, it's as if the panels aren't expanded to the appropriate size. I can set the panel size manual... | [
"Can you put a self contained sample code and we can try to fix that.\nHave you tried adding custom items which return correct height for your panel?\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002219514_python_wxpython.txt |
Q:
Modifiying a Django view for a certain project
So I simply want to use the delete() from the django.contrib.comments.views.moderation module, but only allowing the users with permission to delete their comments. In order to do this, all I have to do is uncomment #@permission_required("comments.delete_comment"), bu... | Modifiying a Django view for a certain project | So I simply want to use the delete() from the django.contrib.comments.views.moderation module, but only allowing the users with permission to delete their comments. In order to do this, all I have to do is uncomment #@permission_required("comments.delete_comment"), but I want to be able to do this without modifying the... | [
"That line is only commented out because Django 1.1 maintains compatibility with Python 2.3 which doesn't support the decorator (@) syntax. But the view is decorated with permission_required nonetheless (with syntax that is compatible with Python 2.3), as you can see here. Django 1.2 will drop support for Python 2.... | [
0
] | [] | [] | [
"django",
"django_comments",
"python"
] | stackoverflow_0002307219_django_django_comments_python.txt |
Q:
How to Include xml file as .py source file
I am having a xml file and i am reading the data from that xml file.
But the problem is that i am making an exe file from all the available .py files (using py2exe).
i dont want to distribute my xml file along with my exe ( because of securiy reasons) as standalone xml fi... | How to Include xml file as .py source file | I am having a xml file and i am reading the data from that xml file.
But the problem is that i am making an exe file from all the available .py files (using py2exe).
i dont want to distribute my xml file along with my exe ( because of securiy reasons) as standalone xml file.I want my xml file should be part of exe as a... | [
"One thing you can do is include it as a string in a module:\nbigxml = '''<?xml ...\n ....\n ....\n ....\n</topelement>'''\n\nThen just import it:\nfrom xmldoc import bigxml\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002309783_python.txt |
Q:
Downloading Image
I used urllib2.build_opener() to download an image from a corresponding url.But for a particular url I am getting an error. When I checked that url, I saw that there is no image. How can I check whether there is an image or not? This is my code:
opener1 = urllib2.build_opener()
page1=opener1.o... | Downloading Image | I used urllib2.build_opener() to download an image from a corresponding url.But for a particular url I am getting an error. When I checked that url, I saw that there is no image. How can I check whether there is an image or not? This is my code:
opener1 = urllib2.build_opener()
page1=opener1.open(orginal)
my_picture... | [
"I don't understand. Why just not catch the error with the try and except keywords?\n",
"as others have suggested catch the exception and check for code e.g.\nimport urllib2\n\nopener1 = urllib2.build_opener()\ntry:\n page1=opener1.open(\"http://www.google.com/nosuchimage\")\n my_picture=page1.read()\nexcep... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002309829_python.txt |
Q:
Redirect stderr to stdout on exec-ed process from python?
In a bash script, I can write:
exec 2>&1
exec someprog
And the stderr output of someprog would be redirected to stdout.
Is there any way to do a similar thing using python's os.exec* functions?
This doesn't have to be portable, just work on Linux.
A:
os.... | Redirect stderr to stdout on exec-ed process from python? | In a bash script, I can write:
exec 2>&1
exec someprog
And the stderr output of someprog would be redirected to stdout.
Is there any way to do a similar thing using python's os.exec* functions?
This doesn't have to be portable, just work on Linux.
| [
"os.dup2(1, 2)\nIlluminating examples\nLet's execute /bin/ls with a bogus argument so that it complains to stderr.\n\n$ python -c \"import os; os.execl('/bin/ls', '', 'ffweew')\" 1>/dev/null\n: ffweew: No such file or directory\n$ python -c \"import os; os.execl('/bin/ls', '', 'ffweew')\" 2>/dev/null\n$ python -c \... | [
5
] | [] | [] | [
"file_descriptor",
"linux",
"python",
"redirect"
] | stackoverflow_0002309911_file_descriptor_linux_python_redirect.txt |
Q:
Get rid of leading zeros for date strings in Python?
Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?... | Get rid of leading zeros for date strings in Python? | Is there a nimble way to get rid of leading zeros for date strings in Python?
In the example below I'd like to get 12/1/2009 in return instead of 12/01/2009. I guess I could use regular expressions. But to me that seems like overkill. Is there a better solution?
>>> time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '... | [
"A simpler and readable solution is to format it yourself:\n>>> d = datetime.datetime.now()\n>>> \"%d/%d/%d\"%(d.month, d.day, d.year)\n4/8/2012\n\n",
"@OP, it doesn't take much to do a bit of string manipulation.\n>>> t=time.strftime('%m/%d/%Y',time.strptime('12/1/2009', '%m/%d/%Y'))\n>>> '/'.join( map( str, map... | [
22,
8,
3,
2
] | [] | [] | [
"date",
"leading_zero",
"python"
] | stackoverflow_0002309828_date_leading_zero_python.txt |
Q:
file manipulation and find a word and tricky replace
I have file something like this
hostname ser1-xyz
myuser name
passwd secret
group 1234
hostname ser2-xyz
myuser name
passwd secret
group 2345
I need to find the line first appearance of host named "ser1-xyz" and modify it as
"ser1" and incremen... | file manipulation and find a word and tricky replace | I have file something like this
hostname ser1-xyz
myuser name
passwd secret
group 1234
hostname ser2-xyz
myuser name
passwd secret
group 2345
I need to find the line first appearance of host named "ser1-xyz" and modify it as
"ser1" and increment it's the group value by 1
So that final file looks like ... | [
"one way\nimport fileinput\nf=0\nfor line in fileinput.input(\"file\",inplace=0):\n if \"hostname\" in line and \"ser1-xyz\" in line:\n line=line.replace(\"ser1-xyz\",\"ser1\")\n f=1\n if f and \"group\" in line:\n a=line.rstrip().split(\" \")\n a[-1]=str(int(a[-1])+1)\n line=' '... | [
2
] | [] | [] | [
"file",
"python",
"replace"
] | stackoverflow_0002310014_file_python_replace.txt |
Q:
Reading file from concatinated ( tar ) file directly without untarring the tar file
Hi i am having a one xml file and some image files, i am making my one concatenate file (ie as like tar file) from all these file (i am having my own scripts for tarring and untarring).
before i describe what exactly i want you ha... | Reading file from concatinated ( tar ) file directly without untarring the tar file | Hi i am having a one xml file and some image files, i am making my one concatenate file (ie as like tar file) from all these file (i am having my own scripts for tarring and untarring).
before i describe what exactly i want you have to look the current situation.
As of now i have to untar the all files into a director... | [
"The tarfile module gives you access to tarballs. It won't be random access, but you can read out any files you need and put them in a temporary directory, or just store them in strings.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002310100_python.txt |
Q:
running a .py by double-clicking is not working
I'm using Windows XP.
When I double click the Launch_PyDemos.pyw from the book Programming Python, nothing happens. When I try to run Launch_PyDemos.pyw from command-line, I get the error message:
Traceback (most recent call last):
File "PyDemos2.pyw", line 41, in ... | running a .py by double-clicking is not working | I'm using Windows XP.
When I double click the Launch_PyDemos.pyw from the book Programming Python, nothing happens. When I try to run Launch_PyDemos.pyw from command-line, I get the error message:
Traceback (most recent call last):
File "PyDemos2.pyw", line 41, in <module>
from PP3E.Gui.Tools.windows import MainW... | [
"You're missing libraries from the book. Quoting a bytes thread:\n\nPlease follow the instructions on the\n book, or read the README-PP3E.txt\n file; below I copy the most relevant\n parts:\n\"\"\"Copy the entire PP3E directory tree\n to some directory on your computer,\n and add the name of the directory\n c... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0002310189_python.txt |
Q:
How do I print out which arguments a Python function requires/allows?
Suppose I have a function and I want to print out the arguments it accepts. How can I do this?
A:
Use inspect.getargspec() to find out.
A:
I see that someone has already offered the answer i had in mind, so i'll suggest a purely practical on... | How do I print out which arguments a Python function requires/allows? | Suppose I have a function and I want to print out the arguments it accepts. How can I do this?
| [
"Use inspect.getargspec() to find out.\n",
"I see that someone has already offered the answer i had in mind, so i'll suggest a purely practical one. IDLE will give you a function's parameters as a 'tooltip'. \nThis should be enabled by default; the tooltip will appear just after you type the function name and the... | [
6,
2,
0
] | [
"if you use IPython (as you absolutely should), use\nfoo?\n\nto see the documentation, including what the function expects, and:\nfoo??\n\nto see the above documentation plus the source code (if available)\n"
] | [
-1
] | [
"argument_passing",
"arguments",
"function",
"python"
] | stackoverflow_0002309645_argument_passing_arguments_function_python.txt |
Q:
Python Virtualbox API
http://enomalism.com/api/pyvb/pyvb.vm.vbVM-class.html
there is a parameter **kw in init(self, **kw)
what is it?
A:
A dictionary of arbitrary keyword arguments. See http://docs.python.org/tutorial/controlflow.html#keyword-arguments
If it really is a question about that concrete API, t... | Python Virtualbox API | http://enomalism.com/api/pyvb/pyvb.vm.vbVM-class.html
there is a parameter **kw in init(self, **kw)
what is it?
| [
"A dictionary of arbitrary keyword arguments. See http://docs.python.org/tutorial/controlflow.html#keyword-arguments\nIf it really is a question about that concrete API, then please excuse me, I was typing faster than thinking.\n",
"**kw is short for **kwargs. Additional named aguments.\n",
"Looks like it's a d... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002310563_python.txt |
Q:
Printing tuple data in normal text in Python
I have variable r=(u'East london,London,England', u'Mr.Baker in East london (at 2010-02-21 15:25:27.0)') in this format from webservice as a output from small program. How can I print these tuple data as normal string like:
East london,London,England Mr.Baker in East... | Printing tuple data in normal text in Python | I have variable r=(u'East london,London,England', u'Mr.Baker in East london (at 2010-02-21 15:25:27.0)') in this format from webservice as a output from small program. How can I print these tuple data as normal string like:
East london,London,England Mr.Baker in East london (at 2010-02-21 15:25:27.0)
can anybody h... | [
"just join on the separator, if it's space it would be:\n' '.join(r)\n\nedit: re your update code. Your table contains primary key, as can be seen from the table definition, that primary key is an integer. That's why you're getting that TypeError. The question is whether you want to print that primary key or not. I... | [
3,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0002310919_python_tuples.txt |
Q:
How can I get python in the command prompt on Windows?
I have just installed Python on my Windows 7. I thought that after that I will be able to run python on the command prompt but it is not the case. After the installation I also found out that I can run the python command shell. This is nice. But what should I ... | How can I get python in the command prompt on Windows? | I have just installed Python on my Windows 7. I thought that after that I will be able to run python on the command prompt but it is not the case. After the installation I also found out that I can run the python command shell. This is nice. But what should I do if I want to save my program in a file and then I want to... | [
"You need to add the python bin directory to your path. Follow the instructions here and add c:\\python26\\bin to the path (unless you installed python in a non-default location).\n",
"Is python.exe in your windows path? Try to look at the PATH environment variable and see if the installation folder of python is ... | [
2,
0,
0
] | [] | [] | [
"command_line",
"command_prompt",
"python",
"windows"
] | stackoverflow_0002311074_command_line_command_prompt_python_windows.txt |
Q:
Determine if string in input is a single word in Python
a brain dead third party program I'm forced to use determines how to treat paths depending if the input supplied is a single word, or a full path: in the former case, the path is interpreted relative to some obscure root directory.
So, given that the input ca... | Determine if string in input is a single word in Python | a brain dead third party program I'm forced to use determines how to treat paths depending if the input supplied is a single word, or a full path: in the former case, the path is interpreted relative to some obscure root directory.
So, given that the input can be a full or relative path, or a single word (including und... | [
"You could tweak your regex to match the whole input string so that you don't have to count the matches. I.e.\nif re.match(r'\\A[\\w-]+\\Z', word):\n print \"Single word\"\n\n(compile the regex if you feel so inclined)\n\\A and \\Z match the beginning and end of the input string, respectively. So, if your word con... | [
6,
3,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002311044_python_string.txt |
Q:
When using Parallel Python, is there any way to tell on which machine the job has run?
I have written a simple program using parallel python, and all works well. However, mainly for curiosities sake, I would like to know on which machine each task ran, and how long it took.
Is there any way to programmatically get... | When using Parallel Python, is there any way to tell on which machine the job has run? | I have written a simple program using parallel python, and all works well. However, mainly for curiosities sake, I would like to know on which machine each task ran, and how long it took.
Is there any way to programmatically get this information for the job that is returned?
| [
"A uuid1 could help:\n>>> import uuid\n>>> uuid.uuid1()\nUUID('b46fa8cf-1fc1-11df-b891-001641ec3fab')\n>>>\n\nSee pydoc uuid and the RFC 4122 for more details, I think the last 48 bits are unique to the host. Not sure you you call/return that in Parallel python though.\nIn the pp.py I found:\nself.__stats[hostid]... | [
1
] | [] | [] | [
"parallel_python",
"python"
] | stackoverflow_0002307739_parallel_python_python.txt |
Q:
How to handle user mangement in Django for groups that has same access but different rules?
Background information:
I have created an internal site for a company. Most of the work has gone into making calculation tools that their sale persons can use to make offers for clients. Create pdf offers and contracts that... | How to handle user mangement in Django for groups that has same access but different rules? | Background information:
I have created an internal site for a company. Most of the work has gone into making calculation tools that their sale persons can use to make offers for clients. Create pdf offers and contracts that can be downloaded, compare prices etc. All of this is working fine.
Now their sale persons have ... | [
"you could use proxy models on the Group and User models that come packed with django.\nthen write your authorization and calculation methods inside the proxy model. if a new group is added later, you only need to add/change the methods inside of those two proxy models. then make every instance of Group and User (o... | [
1,
0
] | [] | [] | [
"django",
"python",
"user_management"
] | stackoverflow_0002311094_django_python_user_management.txt |
Q:
Using Javascript to change all textareas in an html page
I am creating a project in Django, and I am using the Django Admin pages along with TinyMCE. But I would like to be able to toggle TinyMCE on and off like in this example:
http://tinymce.moxiecode.com/examples/example_01.php
but since the admin page is gener... | Using Javascript to change all textareas in an html page | I am creating a project in Django, and I am using the Django Admin pages along with TinyMCE. But I would like to be able to toggle TinyMCE on and off like in this example:
http://tinymce.moxiecode.com/examples/example_01.php
but since the admin page is generated automatically I imagine I need to overide the base_site.h... | [
"You can use\ndocument.getElementsByTagName(\"textarea\")\n\nto return an array of all the <textarea/> elements. Then iterate over it and do with it as you will.\n"
] | [
4
] | [] | [] | [
"django",
"django_admin",
"javascript",
"python"
] | stackoverflow_0002311718_django_django_admin_javascript_python.txt |
Q:
Slicing at runtime
can someone explain me how to slice a numpy.array at runtime?
I don't know the rank (number of dimensions) at 'coding time'.
A minimal example:
import numpy as np
a = np.arange(16).reshape(4,4) # 2D matrix
targetsize = [2,3] # desired shape
b_correct = dynSlicing(a, targetsize)
b_wrong = np.res... | Slicing at runtime | can someone explain me how to slice a numpy.array at runtime?
I don't know the rank (number of dimensions) at 'coding time'.
A minimal example:
import numpy as np
a = np.arange(16).reshape(4,4) # 2D matrix
targetsize = [2,3] # desired shape
b_correct = dynSlicing(a, targetsize)
b_wrong = np.resize(a, targetsize)
prin... | [
"Passing a tuple of slice objects does the job:\ndef dynSlicing(data, targetsize):\n return data[tuple(slice(x) for x in targetsize)]\n\n",
"Simple solution:\nb = a[tuple(map(slice,targetsize))]\n\n",
"You can directly 'change' it. This is due to the nature of arrays only allowing backdrop.\nInstead you can ... | [
6,
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002311578_numpy_python.txt |
Q:
python twisted stdio multiple connections to a server with a command prompt for interaction
I have written a simple twisted application that connects to a server that listens on 1 or more ports. The twisted app connects to this server and usually connects to a few of the open ports at a time. This server is a ser... | python twisted stdio multiple connections to a server with a command prompt for interaction | I have written a simple twisted application that connects to a server that listens on 1 or more ports. The twisted app connects to this server and usually connects to a few of the open ports at a time. This server is a serial logger that connects to serial devices and provides the serial line information through a raw... | [
"To add an interactive console to your Twisted app, see this article -- it explains how to use twisted.internet.stdio for the purpose.\n"
] | [
2
] | [] | [] | [
"python",
"stdio",
"twisted",
"user_interface"
] | stackoverflow_0002311844_python_stdio_twisted_user_interface.txt |
Q:
Django efficiency question
I am wondering would this make any real efficieny difference (ie computation time, memory etc..)
This is my model:
class FooUser(models.Model):
name = models.CharField(max_length=50)
sirname = models.CharField(max_length=50)
Assume I have 2 different approaches while saving a Fo... | Django efficiency question | I am wondering would this make any real efficieny difference (ie computation time, memory etc..)
This is my model:
class FooUser(models.Model):
name = models.CharField(max_length=50)
sirname = models.CharField(max_length=50)
Assume I have 2 different approaches while saving a FooUser at a view:
First one, assi... | [
"This:\n input_name =request.session['name']\n input_sirname =request.session['sirname']\n\nis not copying strings to variables. It's only assigning pointers to string objects to names in local dictionary (input_name, input_sirname). For better explanation you can take a loot at this: http://effbot.org/zone/python-... | [
4,
1,
0
] | [] | [] | [
"django",
"performance",
"python"
] | stackoverflow_0002311251_django_performance_python.txt |
Q:
Attempting to use gevent library in Python: "ImportError: cannot import name core"
I'm attempting to use the gevent library in a Python app I'm writing. However, both easy_install and installing it manually appears to be failing. Any suggestions?
Python 2.6.2 (r262:71600, Aug 5 2009, 10:31:21)
[GCC 4.1.2 200807... | Attempting to use gevent library in Python: "ImportError: cannot import name core" | I'm attempting to use the gevent library in a Python app I'm writing. However, both easy_install and installing it manually appears to be failing. Any suggestions?
Python 2.6.2 (r262:71600, Aug 5 2009, 10:31:21)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for mo... | [
"The error was caused simply by trying to run a script from the project source directory. Changing to any other directory and doing an \"import\" worked fine. More information here on the gevent mailing list.\n",
"I've answered your question on the mailing list.\nBTW, are you using version 0.10.0 of gevent? It'... | [
1,
0
] | [] | [] | [
"gevent",
"python"
] | stackoverflow_0002303745_gevent_python.txt |
Q:
Scheduling Python Programs
How would you go about a having a function check something every ten minutes?
I would like to check a directory for new files every ten minutes. I know python has a time library but can it be used for this?
A:
The sched module is worth a look.
A:
time.sleep:
time.sleep(10*60)
you mi... | Scheduling Python Programs | How would you go about a having a function check something every ten minutes?
I would like to check a directory for new files every ten minutes. I know python has a time library but can it be used for this?
| [
"The sched module is worth a look.\n",
"time.sleep:\ntime.sleep(10*60)\n\nyou might want to look into cron or Scheduled Tasks services of the OS.\n",
"for checking of files, you may want to try pyinotify\n"
] | [
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"time"
] | stackoverflow_0002312314_python_python_3.x_time.txt |
Q:
python string interpolation
What could generate the following behavior ?
>>> print str(msg)
my message
>>> print unicode(msg)
my message
But:
>>> print '%s' % msg
another message
More info:
my msg object is inherited from unicode.
the methods __str__/__unicode__/__repr__ methods were overridden to return the s... | python string interpolation | What could generate the following behavior ?
>>> print str(msg)
my message
>>> print unicode(msg)
my message
But:
>>> print '%s' % msg
another message
More info:
my msg object is inherited from unicode.
the methods __str__/__unicode__/__repr__ methods were overridden to return the string 'my message'.
the msg objec... | [
"Update 2: Please find the original answer, including a simple example of a class exhibiting the behaviour described by the OP, below the horizontal bar. As for what I was able to surmise in the course of my inquiry into Python's sources (v. 2.6.4):\nThe file Include/unicodeobject.h contains the following to lines ... | [
8,
6,
3
] | [] | [] | [
"python",
"string",
"string_interpolation"
] | stackoverflow_0002311906_python_string_string_interpolation.txt |
Q:
QListWidget on freemantle
I have a problem with QListWidget on freemantle (maemo, n900).
I want to use two QListWidget on same window and allow the user to pick on number in each window.
When the user use the second QListWidget, the "blue" color on it disparear.
How to change the color of a item selected in QListW... | QListWidget on freemantle | I have a problem with QListWidget on freemantle (maemo, n900).
I want to use two QListWidget on same window and allow the user to pick on number in each window.
When the user use the second QListWidget, the "blue" color on it disparear.
How to change the color of a item selected in QListWidget which is not active ?
| [
"Kind of a hack, but you can change the QPallete of both QListWidgets so that the inactive color is the same as the active color.\nhttp://qt.nokia.com/doc/4.6/qpalette.html#ColorGroup-enum\nThere is code sample here: http://www.qtcentre.org/threads/17922-two-qlistwidgets that might be of use to you. I don't have a... | [
2
] | [] | [] | [
"maemo",
"n900",
"python",
"qt"
] | stackoverflow_0002311739_maemo_n900_python_qt.txt |
Q:
Different 404 pages depending on the application in Django
We are developing a project with several applications using Django. It shares the database, but it has several applications targeting different very different users. Roughly, administrators and final users. The UI of each application is very different.
I ... | Different 404 pages depending on the application in Django | We are developing a project with several applications using Django. It shares the database, but it has several applications targeting different very different users. Roughly, administrators and final users. The UI of each application is very different.
I need to create a 404 error page, but seems that I can only creat... | [
"It's not at all true that you can only create a single 404 page for the entire app. The documentation explains how you can create a specific 404 handler view, which of course can look at the value of request.path to see what URL was requested and render the relevant template.\n",
"Write a 404 view by setting han... | [
4,
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002312407_django_python.txt |
Q:
Python ( or general programming ). Why use <> instead of != and are there risks?
I think if I understand correctly, a <> b is the exact same thing functionally as a != b, and in Python not a == b, but is there reason to use <> over the other versions? I know a common mistake for Python newcomers is to think that n... | Python ( or general programming ). Why use <> instead of != and are there risks? | I think if I understand correctly, a <> b is the exact same thing functionally as a != b, and in Python not a == b, but is there reason to use <> over the other versions? I know a common mistake for Python newcomers is to think that not a is b is the same as a != b or not a == b.
Do similar misconceptions occur with <... | [
"<> in Python 2 is an exact synonym for != -- no reason to use it, no disadvantages either except the gratuitous heterogeneity (a style issue). It's been long discouraged, and has now been removed in Python 3.\n",
"Just a pedantic note: the <> operator is in some sense misnamed (misdenoted?). a <> b might natur... | [
15,
8,
0
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0002312169_operators_python.txt |
Q:
How do I store a dict/list in a database?
If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
A:
Options:
1) Pickling
2) XML
3) ... | How do I store a dict/list in a database? | If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
| [
"Options:\n1) Pickling\n2) XML\n3) JSON\nothers I am sure. It has a lot to do on how much portability means to you.\n",
"Why don't you use some serialization/deserialization from pickle module ?\nhttp://docs.python.org/library/pickle.html\n",
"Best, under your stated conditions:\nimport cPickle\n ...\nthestr... | [
4,
3,
2,
2,
1
] | [] | [] | [
"database",
"dictionary",
"list",
"python",
"string"
] | stackoverflow_0002311223_database_dictionary_list_python_string.txt |
Q:
Python: using 4 spaces for indentation. Why?
While coding python I'm using only 2 spaces to indent, sure PEP-8 really recommend to have 4 spaces, but historically for me it's unusual.
So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?
P.S. And finally, what's easy way to convert all exist... | Python: using 4 spaces for indentation. Why? | While coding python I'm using only 2 spaces to indent, sure PEP-8 really recommend to have 4 spaces, but historically for me it's unusual.
So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?
P.S. And finally, what's easy way to convert all existing codebase from 2 spaces to 4 spaces?
P.P.S. PE... | [
"Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be displayed as different widths, that makes no syntactic... | [
145,
86,
64,
17,
16,
7,
6,
5,
4,
2,
1,
1,
0
] | [] | [] | [
"conventions",
"indentation",
"pep8",
"python"
] | stackoverflow_0001125653_conventions_indentation_pep8_python.txt |
Q:
regex for state abbreviations (python)
I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
CA
Ca
The string could be:
Boulder, CO 80303
Boulder, Co
Boulder CO
...
Here is what I have, which obviously doesn't work that well. I'm no... | regex for state abbreviations (python) | I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
CA
Ca
The string could be:
Boulder, CO 80303
Boulder, Co
Boulder CO
...
Here is what I have, which obviously doesn't work that well. I'm not very good with regular expressions and goo... | [
"A simple and reliable way is to have all the states listed:\nstates = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL'... | [
10,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002313032_python_regex.txt |
Q:
Python: How to Access Linux Paths
Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.
Thanks
A:
This
import glob, os
glob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))
will give you a list of all files... | Python: How to Access Linux Paths | Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.
Thanks
| [
"This\nimport glob, os\nglob.glob(os.path.expanduser('~/.mozilla/firefox/*.default'))\n\nwill give you a list of all files ending in \".default\" in the current user's ~/.mozilla/firefox directory using os.path.expanduser to expand the ~ in the path and glob.glob to match the *.default file pattern.\n",
"~ is exp... | [
9,
2,
2,
1
] | [] | [] | [
"linux",
"path",
"python"
] | stackoverflow_0002313053_linux_path_python.txt |
Q:
Default value in a function in Python
I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
A:
Yes, it's correct behavior.
However, from your question, it appears that it's not what you expected.
If ... | Default value in a function in Python | I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
| [
"Yes, it's correct behavior.\nHowever, from your question, it appears that it's not what you expected.\nIf you want it to match your expectations, be aware of the following:\nRule 1. Do not use mutable objects as default values.\ndef anyFunction( arg=[] ):\n\nWill not create a fresh list object. The default list ... | [
12,
4,
1
] | [] | [] | [
"default_value",
"python"
] | stackoverflow_0002313075_default_value_python.txt |
Q:
Programming language decision for C++ legacy project workflow
I have quite a lot of C++ legacy code modules from my colleagues, unfortunately poorly written. Each is doing a different job, but they are all GNU C++ code running under Linux.
I want to write a controller program, to make a singular C++ module for a... | Programming language decision for C++ legacy project workflow | I have quite a lot of C++ legacy code modules from my colleagues, unfortunately poorly written. Each is doing a different job, but they are all GNU C++ code running under Linux.
I want to write a controller program, to make a singular C++ module for a workflow, for a very urgent demo. Also I need to write a front-end... | [
"Noting the \"very urgent demo\" part, assuming that that would take about a month, depending on the complexity, I'd stick to the familiar.\nTrue, maintaining python would be easier in the end, and learning python should be a breeze, if you deem it viable.\nI'd say, have the team learn python and do the basic stuff... | [
3,
2,
0
] | [] | [] | [
"binding",
"java",
"java_native_interface",
"programming_languages",
"python"
] | stackoverflow_0002313017_binding_java_java_native_interface_programming_languages_python.txt |
Q:
Controlling VirtualBox from commandline with python
We are using python virtualbox API for controlling the virtualbox. For that we are using the "pyvb" package(as given in python API documentation).
al=pyvb.vb.VB()
m=pyvb.vm.vbVM()
al.startVM(m)
we have executed using the python interpreter. No error is shown but... | Controlling VirtualBox from commandline with python | We are using python virtualbox API for controlling the virtualbox. For that we are using the "pyvb" package(as given in python API documentation).
al=pyvb.vb.VB()
m=pyvb.vm.vbVM()
al.startVM(m)
we have executed using the python interpreter. No error is shown but the virtualbox doesnt start. Could you please tell us wh... | [
"I found that I can use the following functions to find if a VM is running, restore a VM to a specific snapshot, and start a VM by name.\nfrom subprocess import Popen, PIPE\n\n def running_vms():\n \"\"\"\n Return list of running vms\n \"\"\"\n f = Popen(r'vboxmanage --nologo list run... | [
3,
0
] | [] | [] | [
"python",
"virtualbox"
] | stackoverflow_0002313010_python_virtualbox.txt |
Q:
Django models - how to filter out duplicate values by PK after the fact?
I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable.
Is there a... | Django models - how to filter out duplicate values by PK after the fact? | I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable.
Is there a quick and easy way to do this? I'm considering using a dict instead of a list... | [
"In general it's better to combine all your queries into a single query if possible. Ie.\nq = Model.objects.filter(Q(field1=f1)|Q(field2=f2))\n\ninstead of\nq1 = Models.object.filter(field1=f1)\nq2 = Models.object.filter(field2=f2)\n\nIf the first query is returning duplicated Models then use distinct()\nq = Model.... | [
13,
6,
2,
0,
0,
0
] | [] | [] | [
"data_structures",
"django",
"python",
"set",
"unique"
] | stackoverflow_0000744424_data_structures_django_python_set_unique.txt |
Q:
Segmentation fault when importing pylab in a python script
I have installed Ubuntu 8.10. I am using python 2.6.4. I have installed the following packages
networkx 1.0rc1
matplotlib 0.99.1.2
scipy 0.7.1
numpy 1.3
when I write the following statement in my code
import pylab
Also this statement gives a segmentation... | Segmentation fault when importing pylab in a python script | I have installed Ubuntu 8.10. I am using python 2.6.4. I have installed the following packages
networkx 1.0rc1
matplotlib 0.99.1.2
scipy 0.7.1
numpy 1.3
when I write the following statement in my code
import pylab
Also this statement gives a segmentation fault
import matplotlib.pyplot as plt
I receive a segmentation... | [
"try running python through gdb. The top frame of the stacktrace is the (assumed) origin of the segmentation fault. This should give you a rough idea what to write in a bug report. If all of the above packages are from the ubuntu repositories, there should be a good chance that someone in the ubuntu community has a... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002311941_python.txt |
Q:
Conversion from imperative to functional programming [Python to Standard ML]
I have a function specification that states it that should evaluate a polynomial function of one variable. The coefficient of the function is given as a list. It also accepts the value of the variable as a real.
For example: eval(2, [4... | Conversion from imperative to functional programming [Python to Standard ML] | I have a function specification that states it that should evaluate a polynomial function of one variable. The coefficient of the function is given as a list. It also accepts the value of the variable as a real.
For example: eval(2, [4, 3, 2, 1]) = 26 (1*x^3 + 2*x^2 + 3*x^1 + 4*x^0, where x = 2)
Here's the function ... | [
"The usual way to express sums in functional languages is a fold. You can get rid of the need for an index (and a function to raise an int to the power of another int) by multiplying the sum with r in each iteration:\nfun eval radix lst = let\n fun f (element, sum) = sum * radix + element\nin\n foldr f 0 lst\nend... | [
4,
1
] | [] | [] | [
"functional_programming",
"parameters",
"python",
"recursion",
"sml"
] | stackoverflow_0002313141_functional_programming_parameters_python_recursion_sml.txt |
Q:
Genshi TemplateSyntaxError on python block where it should work
<?python class += 1 ?>
One really simple line of code which definitely should work, but still it gives me this error:
TemplateSyntaxError: invalid syntax (file.html, line 22)
I shorted the filepath for readability, but that's the exact error. I'm de... | Genshi TemplateSyntaxError on python block where it should work | <?python class += 1 ?>
One really simple line of code which definitely should work, but still it gives me this error:
TemplateSyntaxError: invalid syntax (file.html, line 22)
I shorted the filepath for readability, but that's the exact error. I'm definitely sure it should work, as I've used
<?python
i += 1
?>
In... | [
"class is a Python keyword. You can't name a variable that.\n"
] | [
1
] | [] | [] | [
"codeblocks",
"genshi",
"python",
"syntax_error"
] | stackoverflow_0002313590_codeblocks_genshi_python_syntax_error.txt |
Q:
How to improve performance when interpolating on 3d data with SciPy
I have 3d-data representing the atmosphere. Now I want to interpolate this data to a common Z coordinate (what I mean by that should be clear from the function's doctring). The following code works fine, but I was wondering if there were a way to ... | How to improve performance when interpolating on 3d data with SciPy | I have 3d-data representing the atmosphere. Now I want to interpolate this data to a common Z coordinate (what I mean by that should be clear from the function's doctring). The following code works fine, but I was wondering if there were a way to improve the performance ...
def interpLevel(grid,value,data,interp='linea... | [
"Well, this might give a small speed-up just because it uses less memory.\nret = np.zeros_like(data[0,:,:])\nfor latIdx in xrange(grid.shape[1]):\n for lonIdx in xrange(grid.shape[2]):\n # check if we need to flip the column\n if grid[0,latIdx,lonIdx] > grid[-1,latIdx,lonIdx]:\n ind = -1... | [
2
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scipy"
] | stackoverflow_0002312665_interpolation_numpy_python_scipy.txt |
Q:
How can I use the Whirlpool hash with Django authentication?
We have a system written in PHP where account passwords are stored as the first 128 chars of a whirlpool hash of the password.
I'd like to transition to handling the logins with Django without changing the database or asking users to change their passwor... | How can I use the Whirlpool hash with Django authentication? | We have a system written in PHP where account passwords are stored as the first 128 chars of a whirlpool hash of the password.
I'd like to transition to handling the logins with Django without changing the database or asking users to change their passwords. Also, I'd prefer to stick with whirlpool vs. the less secure h... | [
"Basically you want to write your own authentication back-end. Fortunately, this can be done very easily.\nIt's as easy as:\nclass MyBackend:\n def authenticate(self, username=None, password=None):\n # Check the username/password and return a User.\n\nThen all you need to do is specify the back-end class ... | [
2
] | [] | [] | [
"authentication",
"django",
"python",
"sha1"
] | stackoverflow_0002314405_authentication_django_python_sha1.txt |
Q:
How to plot the lines first and points last in matplotlib
I have a simple plot with several sets of points and lines connecting each set. I want the points to be plotted on top of the lines (so that the line doesn't show inside the point). Regardless of order of the plot and scatter calls, this plot comes out th... | How to plot the lines first and points last in matplotlib | I have a simple plot with several sets of points and lines connecting each set. I want the points to be plotted on top of the lines (so that the line doesn't show inside the point). Regardless of order of the plot and scatter calls, this plot comes out the same, and not as I'd like. Is there a simple way to do it?
i... | [
"You need to set the Z-order.\nplt.plot(R,P,color='0.2',lw=1.5, zorder=1)\nplt.scatter(R,P,s=150,color=c, zorder=2)\n\nCheck out this example.\nhttp://matplotlib.sourceforge.net/examples/pylab_examples/zorder_demo.html\n"
] | [
96
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002314379_matplotlib_python.txt |
Q:
In model save() how to get all field starting with 'foo'
I've this django model:
from django.db import models
class MyModel(models.Model):
foo_it = model.CharField(max_length=100)
foo_en = model.CharField(max_length=100)
def save(self):
print_all_field_starting_with('foo_')
super(MyMo... | In model save() how to get all field starting with 'foo' | I've this django model:
from django.db import models
class MyModel(models.Model):
foo_it = model.CharField(max_length=100)
foo_en = model.CharField(max_length=100)
def save(self):
print_all_field_starting_with('foo_')
super(MyModel, self).save()
So I want to get all field starting with fo... | [
"You can do:\nfor field in dir(self):\n if field.startswith('foo_'):\n # getting with getattr(self, field)\n # setting with setattr(self, field, value)\n\nIf you want to get the list of fields you can also so this:\nfoo_fields = [field for field in dir(self) if field.startswith('foo_')]\n\nOr print a l... | [
2,
2,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002314292_django_django_models_python.txt |
Q:
Does PIL create artifacting on the bottom edge of the image when you thumbnail() then crop()? If so, what is your workaround?
When I call PIL to thumbnail() an image, and then crop(), I get artifacting on the last row of pixels -- they're either mostly black with specks of intense color, or what seems to be a not-... | Does PIL create artifacting on the bottom edge of the image when you thumbnail() then crop()? If so, what is your workaround? | When I call PIL to thumbnail() an image, and then crop(), I get artifacting on the last row of pixels -- they're either mostly black with specks of intense color, or what seems to be a not-resized area of the image ( ie, that line of pixels is at the original resolution and did not scale down with the rest )
This does ... | [
"Yes, this happens to me also. This was a learning exercise for me because I have never cropped or created thumbnails using the PIL...\nthumbnail(size,filter=None)\nReplaces the original image, in place, with a new image of the given size (p. 2). The optional\nfilter argument works in the same way as in the .resiz... | [
2
] | [] | [] | [
"imaging",
"python",
"python_imaging_library"
] | stackoverflow_0002312438_imaging_python_python_imaging_library.txt |
Q:
speed-up python function to process files with data segments separated by a blank space
I need to process files with data segments separated by a blank space, for example:
93.18 15.21 36.69 33.85 16.41 16.81 29.17
21.69 23.71 26.38 63.70 66.69 0.89 39.91
86.55 56.34 57.80 98.38 0.24 17.19 75.46
[...]
1.30 73.02... | speed-up python function to process files with data segments separated by a blank space | I need to process files with data segments separated by a blank space, for example:
93.18 15.21 36.69 33.85 16.41 16.81 29.17
21.69 23.71 26.38 63.70 66.69 0.89 39.91
86.55 56.34 57.80 98.38 0.24 17.19 75.46
[...]
1.30 73.02 56.79 39.28 96.39 18.77 55.03
99.95 28.88 90.90 26.70 62.37 86.58 65.05
25.16 32.61 17.47 ... | [
"not to convert floats to floats would be the first step. I would suggest, however, to first profile your code and then try to optimize the bottleneck parts.\nI understand that you've changed your code from the original, but \nvalues = [value for value in line.split()]\n\nis not a good thing either. just write valu... | [
2,
1,
1,
1,
0,
0
] | [] | [] | [
"numpy",
"performance",
"python"
] | stackoverflow_0002311376_numpy_performance_python.txt |
Q:
Efficiently reading a csv file with windows newline on linux in Python
The following is working under windows for reading csv files line by line.
f = open(filename, 'r')
for line in f:
Though when copying the csv file to a linux server, it fails.
It should be mentioned that performance is an issue as the csv fil... | Efficiently reading a csv file with windows newline on linux in Python | The following is working under windows for reading csv files line by line.
f = open(filename, 'r')
for line in f:
Though when copying the csv file to a linux server, it fails.
It should be mentioned that performance is an issue as the csv files are huge. I am therefore concerned about the string copying when using th... | [
"Python has builtin support for Windows, Linux and Mac line endings:\nf = open(filename, 'rtU')\n\nfor line in f:\n ...\n\nIf you really want don't want slow string operations, you should strip the files before processing them. You can either use dos2unix (can be found in the Debian package \"tofrodos\") or (eas... | [
7,
6,
4,
1,
0
] | [] | [] | [
"csv",
"python",
"python_3.x"
] | stackoverflow_0002314501_csv_python_python_3.x.txt |
Q:
Integer comparison in python slows everything down to a crawl
The following code is causing me enormous headaches:
def extract_by_letters(letters, dictionary):
for word in dictionary:
for letter in letters:
if word.count(letter) != letters.count(letter):
if word in dictionary:... | Integer comparison in python slows everything down to a crawl | The following code is causing me enormous headaches:
def extract_by_letters(letters, dictionary):
for word in dictionary:
for letter in letters:
if word.count(letter) != letters.count(letter):
if word in dictionary: #I cant leave this line out
dictionary.remove(w... | [
"The reason you get the exception is that if the letter count matches for more than one letter, you are trying to remove the word more than once\nThe reason it is so slow is that you have loops inside loops inside loops.\nIf you would write a sentence or two about what the function is supposed to do, it would be mu... | [
4,
2,
2,
1,
0
] | [] | [] | [
"integer",
"loops",
"python"
] | stackoverflow_0002309996_integer_loops_python.txt |
Q:
Using Django, why would REMOTE_ADDR return 127.0.0.1 on a web server?
When getting the IP with request.META['REMOTE_ADDR'] code. This works fine on the local system but when hosted on a web server the ip got is 127.0.0.1 - How can this be resolved?
A:
Your web server is probably behind a load balancer. You can t... | Using Django, why would REMOTE_ADDR return 127.0.0.1 on a web server? | When getting the IP with request.META['REMOTE_ADDR'] code. This works fine on the local system but when hosted on a web server the ip got is 127.0.0.1 - How can this be resolved?
| [
"Your web server is probably behind a load balancer. You can try using request.META['HTTP_X_FORWARDED_FOR'].\nOr better, look at the django book, chapter 15 - What’s Middleware? and Reverse Proxy Support (X-Forwarded-For Middleware) sections.\n",
"If you are behind a proxy and running apache as the webserver you ... | [
10,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002144848_django_python.txt |
Q:
Django: request.META['REMOTE_ADDR'] is always '127.0.0.1'
I have an application running with debug=True on a remote host somewhere. Now somehow every time I access REMOTE_ADDR it returns 127.0.0.1 no matter where the request is from.
I'm not sure where to start and why this is happening.
A:
Do you have any kind ... | Django: request.META['REMOTE_ADDR'] is always '127.0.0.1' | I have an application running with debug=True on a remote host somewhere. Now somehow every time I access REMOTE_ADDR it returns 127.0.0.1 no matter where the request is from.
I'm not sure where to start and why this is happening.
| [
"Do you have any kind of proxy, gateway, or load balancer running on that remote host? That's the sort of thing that would cause connections to appear to be from 127.0.0.1 (because that's where the immediate connection is from, as far as the web server is concerned).\n",
"If you are behind a proxy and running apa... | [
7,
0
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0001779464_django_http_python.txt |
Q:
How to generate a module object from a code object in Python
Given that I have the code object for a module, how do I get the corresponding module object?
It looks like moduleNames = {}; exec code in moduleNames does something very close to what I want. It returns the globals declared in the module into a dictiona... | How to generate a module object from a code object in Python | Given that I have the code object for a module, how do I get the corresponding module object?
It looks like moduleNames = {}; exec code in moduleNames does something very close to what I want. It returns the globals declared in the module into a dictionary. But if I want the actual module object, how do I get it?
EDIT:... | [
"As a comment already indicates, in today's Python the preferred way to instantiate types that don't have built-in names is to call the type obtained via the types module from the standard library:\n>>> import types\n>>> m = types.ModuleType('m', 'The m module')\n\nnote that this does not automatically insert the n... | [
25
] | [] | [] | [
"bytecode",
"python"
] | stackoverflow_0002315044_bytecode_python.txt |
Q:
Python daemon to watch a folder and update a database
This is specifically geared towards managing MP3 files, but it should easily work for any directory structure with a lot of files.
I want to find or write a daemon (preferably in Python) that will watch a folder with many subfolders that should all contain X nu... | Python daemon to watch a folder and update a database | This is specifically geared towards managing MP3 files, but it should easily work for any directory structure with a lot of files.
I want to find or write a daemon (preferably in Python) that will watch a folder with many subfolders that should all contain X number of MP3 files. Any time a file is added, updated or del... | [
"Another answer already suggested pyinotify for Linux, let me add watch_directory for Windows (a good discussion of the possibilities in Windows is here, the module's an example) and fsevents on the Mac (unfortunately I don't think there's a single cross-platform module offering a uniform interface to these various... | [
8,
3,
0
] | [] | [] | [
"daemon",
"database",
"filesystems",
"python"
] | stackoverflow_0002314892_daemon_database_filesystems_python.txt |
Q:
UTF-8 and upper()
I want to transform UTF-8 strings using built-in functions such as upper() and capitalize().
For example:
>>> mystring = "işğüı"
>>> print mystring.upper()
Işğüı # should be İŞĞÜI instead.
How can I fix this?
A:
Do not perform actions on encoded strings; decode to unicode first.
>>> mystring ... | UTF-8 and upper() | I want to transform UTF-8 strings using built-in functions such as upper() and capitalize().
For example:
>>> mystring = "işğüı"
>>> print mystring.upper()
Işğüı # should be İŞĞÜI instead.
How can I fix this?
| [
"Do not perform actions on encoded strings; decode to unicode first.\n>>> mystring = \"işğüı\"\n>>> print mystring.decode('utf-8').upper()\nIŞĞÜI\n\n",
"It's actually best, as a general strategy, to always keep your text as Unicode once it's in memory: decode it at the moment it's input, and encode it exactly at ... | [
14,
9
] | [] | [] | [
"case_sensitive",
"python"
] | stackoverflow_0002315451_case_sensitive_python.txt |
Q:
Using python to run other programs
I have a command that works great on the command line. It has lots of arguments like cmd --thing foo --stuff bar -a b input output
I want to run this from python and block waiting for it to complete. As the script prints things to stdout and stderr I want it to be immediately sho... | Using python to run other programs | I have a command that works great on the command line. It has lots of arguments like cmd --thing foo --stuff bar -a b input output
I want to run this from python and block waiting for it to complete. As the script prints things to stdout and stderr I want it to be immediately shown to the user.
What is the right modul... | [
"You have to quote each field separately, ie. split the options from their arguments.\nimport subprocess\noutput = subprocess.call([\"cmd\", \"--thing\", \"foo\", \"--stuff\", \"bar\", \"-a\", \"b\", \"input\", \"output\"])\n\notherwise you are effectively running cmd like this\n$ cmd --thing\\ foo --stuff\\ bar -a... | [
7,
4,
2,
1
] | [] | [] | [
"python",
"subprocess",
"unix"
] | stackoverflow_0002314206_python_subprocess_unix.txt |
Q:
In Django, why does this error say that my column can't be null?
picture_url = models.CharField(max_length=2000)
A:
You'll need to add null=True if the column can be null:
picture_url = models.CharField(max_length=2000, null=True)
A:
By default fields have null set to False try this
picture_url = models.CharFi... | In Django, why does this error say that my column can't be null? | picture_url = models.CharField(max_length=2000)
| [
"You'll need to add null=True if the column can be null:\npicture_url = models.CharField(max_length=2000, null=True)\n\n",
"By default fields have null set to False try this\npicture_url = models.CharField(max_length=2000, blank=True)\n\nhttp://docs.djangoproject.com/en/1.1/ref/models/fields/#null\n"
] | [
3,
0
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002315506_database_django_mysql_python.txt |
Q:
How to sort a collection of objects by an variable they all hold?
I have a class named Individual, which has a variable, self.fitness. I have a collection of these Individual instances and I'd like to sort them by their fitness. How is this done in python?
A:
from operator import attrgetter
sorted(item_list, k... | How to sort a collection of objects by an variable they all hold? | I have a class named Individual, which has a variable, self.fitness. I have a collection of these Individual instances and I'd like to sort them by their fitness. How is this done in python?
| [
"from operator import attrgetter\nsorted(item_list, key=attrgetter('fitness'))\n\nitem_list can be any iterable. Here is an example\n>>> class C(object):\n... def __init__(self, fitness):\n... self.fitness=fitness\n... def __repr__(self):\n... return \"fitness: %s\"%self.fitness\n... \n>>> \... | [
6
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0002315659_python_sorting.txt |
Q:
In Python, how do I loop through the dictionary and change the value if it equals something?
If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
for k, v in mydict.items():
if v is None:
... right?
A:
for k, v in mydict.iteritems():
if v is None:
... | In Python, how do I loop through the dictionary and change the value if it equals something? | If the value is None, I'd like to change it to "" (empty string).
I start off like this, but I forget:
for k, v in mydict.items():
if v is None:
... right?
| [
"for k, v in mydict.iteritems():\n if v is None:\n mydict[k] = ''\n\nIn a more general case, e.g. if you were adding or removing keys, it might not be safe to change the structure of the container you're looping on -- so using items to loop on an independent list copy thereof might be prudent -- but assig... | [
174,
16,
12
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002315520_dictionary_python.txt |
Q:
pyplot.ginput() causes axes to change?
I am encountering some strange behavior with using the matplotlib.pyplot ginput() function to store clicked points. On the first click, the ranges of the axes of the clicked image change to add 200 on each side. The image remains with this border of whitespace until something... | pyplot.ginput() causes axes to change? | I am encountering some strange behavior with using the matplotlib.pyplot ginput() function to store clicked points. On the first click, the ranges of the axes of the clicked image change to add 200 on each side. The image remains with this border of whitespace until something new is plotted.
Example code:
import matplo... | [
"Try \nplt.imshow(im1)\nplt.axis('image')\nx = plt.ginput(4)\n\nI learned this here.\n"
] | [
4
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002315656_matplotlib_python.txt |
Q:
Why does Django's ModelForm validation think that this is invalid?
I have what looks to me to be a pretty simple setup of model, modelform and a view playing with the two. The only hitch is that the model has a user property that can't be POSTed to the form, rather it should be populated by request.user so I have... | Why does Django's ModelForm validation think that this is invalid? | I have what looks to me to be a pretty simple setup of model, modelform and a view playing with the two. The only hitch is that the model has a user property that can't be POSTed to the form, rather it should be populated by request.user so I have this:
# models.py
class Update(models.Model):
user = models... | [
"You should try excluding the user field in the form\nclass UpdateForm(ModelForm):\n name = forms.CharField(\n max_length=140,\n required=False,\n widget=forms.TextInput(attrs={\"class\": \"blankable\"})\n )\n\n class Meta:\n model = Update\n exclude = (\"user\",)\n\nhttp://docs.djangoproject.com/... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002315086_django_python.txt |
Q:
Unescape a string inside a string
I am working with urllib2, and trying to extract the headers in a printable form from a Response object.
Presently I am printing str(response.info()), however what is printed, is itself a Python string (at least to my understanding).
(Pdb) p str(response.info())
'Date: Tue, 23 Feb... | Unescape a string inside a string | I am working with urllib2, and trying to extract the headers in a printable form from a Response object.
Presently I am printing str(response.info()), however what is printed, is itself a Python string (at least to my understanding).
(Pdb) p str(response.info())
'Date: Tue, 23 Feb 2010 03:12:26 GMT\r\nServer: Apache\r\... | [
"str(info()) does give a normal string:\n>>> import urllib2\n>>> f = urllib2.urlopen('http://tejp.de')\n>>> print str(f.info())\nConnection: close\nVary: Accept-Encoding\nContent-Type: text/html\nAccept-Ranges: bytes\nETag: \"-807357257\"\nLast-Modified: Wed, 01 Jul 2009 10:05:34 GMT\nContent-Length: 285\nDate: Tue... | [
2,
0,
0
] | [] | [] | [
"http",
"python",
"string"
] | stackoverflow_0002315889_http_python_string.txt |
Q:
Get number of modified rows after sqlite3 execute in Python
When performing SQL statements such as UPDATE, and INSERT, the usual .fetch*() methods on the Cursor instance obviously don't apply to the number of rows modified.
In the event of executing one of the aforementioned statements, what is the correct way to ... | Get number of modified rows after sqlite3 execute in Python | When performing SQL statements such as UPDATE, and INSERT, the usual .fetch*() methods on the Cursor instance obviously don't apply to the number of rows modified.
In the event of executing one of the aforementioned statements, what is the correct way to obtain the corresponding row count in Python, and the correspondi... | [
"After calling your Cursor.execute*() methods with your UPDATE or INSERT statements you can use Cursor.rowcount to see the # of rows affected by the execute call.\nIf I had to guess I would say the python lib is calling int sqlite3_changes(sqlite3*) from the C API but I have not looked at the code so I can't say fo... | [
41
] | [] | [] | [
"c",
"python",
"sqlite"
] | stackoverflow_0002316003_c_python_sqlite.txt |
Q:
How to create a dictionary of integer pairs from a file in python
If I have a file of pairs of integer IDs, followed by a value, I'd like to create this into a dictionary. Each separate term is separated by a newline. I want to make sure these are all held as ints. How can I do this?
edit: as requested, a sampl... | How to create a dictionary of integer pairs from a file in python | If I have a file of pairs of integer IDs, followed by a value, I'd like to create this into a dictionary. Each separate term is separated by a newline. I want to make sure these are all held as ints. How can I do this?
edit: as requested, a sample.
9 120
10 12
11 4
12 1
13 515
14 32
| [
"d={}\nf=open(\"file\")\nfor line in f:\n a,b=map( int, line.split() ) \n d[a]=b\nf.close()\nprint d\n\noutput\n$ cat file\n9 120\n10 12\n11 4\n12 1\n13 515\n14 32\n\n$ ./python.py\n{9: 120, 10: 12, 11: 4, 12: 1, 13: 515, 14: 32}\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0002316150_python.txt |
Q:
trouble writing to file in "for line in" iterator in Python script
This seems to be an embarrassingly simple question, but, after a day of reading over How-To's and manuals, it must be asked.
I'm writing many lines to a few files using a few nested loops, inserting some static strings and copying lines over from o... | trouble writing to file in "for line in" iterator in Python script | This seems to be an embarrassingly simple question, but, after a day of reading over How-To's and manuals, it must be asked.
I'm writing many lines to a few files using a few nested loops, inserting some static strings and copying lines over from other files over and over again. The output appears to be a single copy o... | [
"It appears that the for loop is only executing once.\nI'm not sure why it would do that - perhaps there is a problem with the line endings so the whole file is being read in as a single line.\nFor example, if the lines of the input script file has \\r line ending and python is expecting \\n line endings.\nTry usin... | [
1,
1,
0,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002316452_file_io_python.txt |
Q:
Numpy masked array modification
Currently I have a code that checks if given element in array is equal = 0 and if so then set the value to 'level' value (temp_board is 2D numpy array, indices_to_watch contains 2D coordinates that should be watched for zeros).
indices_to_watch = [(0,1), (1,2)]
for index in ... | Numpy masked array modification | Currently I have a code that checks if given element in array is equal = 0 and if so then set the value to 'level' value (temp_board is 2D numpy array, indices_to_watch contains 2D coordinates that should be watched for zeros).
indices_to_watch = [(0,1), (1,2)]
for index in indices_to_watch:
if temp_boa... | [
"I'm not sure i follow all of the detail in your question. If i understood it correctly, then it seems like this is straightforward Numpy indexing. The code below checks the array (A) for zeros, and where it finds them, it replaces them with 'level'.\nimport numpy as NP\nA = NP.random.randint(0, 10, 20).reshape(5, ... | [
1,
1,
0
] | [] | [] | [
"masked_array",
"numpy",
"python"
] | stackoverflow_0002306280_masked_array_numpy_python.txt |
Q:
Pipe output of a command to an interactive python session?
What I'd like to do is something like
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
I suppose ipython solution would be best. If this isn't achievable, what would be your ... | Pipe output of a command to an interactive python session? | What I'd like to do is something like
$echo $PATH | python --remain-interactive "x = raw_input().split(':')"
>>>
>>> print x
['/usr/local/bin', '/usr/bin', '/bin']
I suppose ipython solution would be best. If this isn't achievable, what would be your solution for the situation where I want to process output from v... | [
"In IPython you can do this\nx = !echo $$$$PATH\n\nThe double escape of $ is a pain though\nYou could do this I guess\nPATH=\"$PATH\"\nx = !echo $PATH\nx[0].split(\":\")\n\n",
"The --remain-interactive switch you are looking for is -i. You also can use the -c switch to specify the command to execute, such as __im... | [
2,
1,
0
] | [] | [] | [
"interactive",
"ipython",
"pipe",
"python",
"redirect"
] | stackoverflow_0002316730_interactive_ipython_pipe_python_redirect.txt |
Q:
Is there a way to extract a dict in Python into the local namespace?
PHP has a function called extract() which takes an associative array as the argument and creates local variables out of the keys whose values are assigned to the key's values. Is there a way to do this in Python? A quick google search didn't imme... | Is there a way to extract a dict in Python into the local namespace? | PHP has a function called extract() which takes an associative array as the argument and creates local variables out of the keys whose values are assigned to the key's values. Is there a way to do this in Python? A quick google search didn't immediately show me how. I suspect there's a way with exec() but it'd be nice ... | [
"Since it is not safe to modify the dict that locals() returns \n>>> d={'a':6, 'b':\"hello\", 'c':set()}\n>>> exec '\\n'.join(\"%s=%r\"%i for i in d.items())\n>>> a\n6\n>>> b\n'hello'\n>>> c\nset([])\n\nBut using exec like this is ugly. You should redesign so you don't need to dynamically add to your local namespac... | [
5,
4
] | [
"Modifying locals() dict could have been a solution but docs say, http://docs.python.org/library/functions.html#\n\nNote The contents of this dictionary\n should not be modified; changes may\n not affect the values of local and\n free variables used by the\n interpreter.\n\nso the question is why you even need ... | [
-1
] | [
"dictionary",
"php",
"python"
] | stackoverflow_0002316764_dictionary_php_python.txt |
Q:
Pygame and threading: locked when accessing to globals?
I am programming a game using pygame. I intend to control one of the characters using OpenSoundControl (OSC), a udp-based protocol for realtime communication. Basically I am using simpleOSC module to biund some OSC commands to functions on my pygame program.
... | Pygame and threading: locked when accessing to globals? | I am programming a game using pygame. I intend to control one of the characters using OpenSoundControl (OSC), a udp-based protocol for realtime communication. Basically I am using simpleOSC module to biund some OSC commands to functions on my pygame program.
My game structure is something like this (this is a simplific... | [
"I can't verify whether you are in fact having a thread/concurrency issue, although it seems likely. I can suggest a solution that may resolve it.\nThe python multiprocessing module demonstrates how to spawn a new process (not a thread) with a queue. If you create the new process and then init OSC in there, and hav... | [
3
] | [] | [] | [
"multithreading",
"osc",
"pygame",
"python"
] | stackoverflow_0002310728_multithreading_osc_pygame_python.txt |
Q:
Python Virtualbox API
http://enomalism.com/api/pyvb/
here we have def _init_(self,**kw):
what parameter(s) should be passed when we create an instance for pyvb.vm.vbVM ???
A:
What you are seeing is "keyword arguments". You can call the constructor with a dictionary or named arguments. Here is an example of usin... | Python Virtualbox API | http://enomalism.com/api/pyvb/
here we have def _init_(self,**kw):
what parameter(s) should be passed when we create an instance for pyvb.vm.vbVM ???
| [
"What you are seeing is \"keyword arguments\". You can call the constructor with a dictionary or named arguments. Here is an example of using keyword arguments:\n\nclass MyClass(object):\n def __init__(self,**kwargs):\n if 'val' in kwargs:\n self.__value = kwargs['val'];\n elif 'value' in kw... | [
1,
0
] | [] | [] | [
"python",
"virtualbox"
] | stackoverflow_0002312254_python_virtualbox.txt |
Q:
Setting up authentication in Trac
I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.
We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a use... | Setting up authentication in Trac | I am in the works of setting up a Trac server for my (small) company and need a bit of help/guidance with the authentication mechanism.
We have for some time developed our own web application which our users access in their day to day work. It is build in php5.3 and includes a users database stored in a mysql database.... | [
"First off, don't use mod_python, use mod_wsgi.\nSecond, you have several options for how to do authentication. One option might be to just use mod_authn_dbd with a MySQL backend, keeping your authn in the apache2 config.\nThird, look into Trac's AccountManager. It's one of the most useful Trac plugins (we use it a... | [
3,
0,
0
] | [] | [] | [
"apache",
"php",
"python",
"trac"
] | stackoverflow_0002282123_apache_php_python_trac.txt |
Q:
setting windows live messenger nick and status message using win32com.client
is their any way to set windows live messenger using the win32com library ?
A:
This thread at MSDN forum discusses the topic thoroughly.
In short, you can do it with this API
Another possibility is to use a python based web client to d... | setting windows live messenger nick and status message using win32com.client | is their any way to set windows live messenger using the win32com library ?
| [
"This thread at MSDN forum discusses the topic thoroughly.\nIn short, you can do it with this API\nAnother possibility is to use a python based web client to do it over http at home.live.com\n"
] | [
0
] | [] | [] | [
"live",
"python",
"windows",
"windows_live_messenger"
] | stackoverflow_0002317175_live_python_windows_windows_live_messenger.txt |
Q:
Python: Asynchronous http requests sent in order with automatic handling of cookies?
I am coding a python (2.6) interface to a web service. I need to communicate via http so that :
Cookies are handled automatically,
The requests are asynchronous,
The order in which the requests are sent is respected (the order in... | Python: Asynchronous http requests sent in order with automatic handling of cookies? | I am coding a python (2.6) interface to a web service. I need to communicate via http so that :
Cookies are handled automatically,
The requests are asynchronous,
The order in which the requests are sent is respected (the order in which the responses to these requests are received does not matter).
I have tried what c... | [
"\nUsing httplib and urllib2, the\n requests are synchronous unless I use\n thread, in which case the order is not\n guaranteed to be respected\n\nHow would you know that the order has been respected unless you get your response back from the first connection before you send the response to the second connection... | [
2
] | [] | [] | [
"asynchronous",
"cookies",
"http",
"python"
] | stackoverflow_0002315151_asynchronous_cookies_http_python.txt |
Q:
Problem with Twisted and threads
Some of you that are more experienced using Twisted will probably judge me about using it together with threads - but I did it :). And now I am in somehow of a trouble - I am having an application server that listens for client requests and each time a new client connects it spawns... | Problem with Twisted and threads | Some of you that are more experienced using Twisted will probably judge me about using it together with threads - but I did it :). And now I am in somehow of a trouble - I am having an application server that listens for client requests and each time a new client connects it spawns another thread that I probably forget... | [
"\"Twisted way\" to do anything outside reactor loop (aka spawning threads) is twisted.internet.threads.deferToThread.\nFor example:\nfrom twisted.internet import threads\n\ndef sthToDoInSeparateThread():\n return 3\n\nd = threads.deferToThread(sthToDoInSeparateThread)\n\ndeferToThread will execute sthToDoInSepa... | [
4,
0
] | [] | [] | [
"multithreading",
"python",
"twisted"
] | stackoverflow_0001593948_multithreading_python_twisted.txt |
Q:
XML file using Python
I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code?
Also I need to have my output (i.e. element of each attribute come in separate lines in that particular XML file).
A:
Python comes with 2 modules for xml processing mindom which is a ... | XML file using Python | I have made a XML file using python. How can I retrieve an element from it? Will you help me with the code?
Also I need to have my output (i.e. element of each attribute come in separate lines in that particular XML file).
| [
"Python comes with 2 modules for xml processing mindom which is a DOM implemetation and the more 'pythonic' Element Tree which has other information and links to examples etc I use a third party library lxml which is in effect a super set of Element Tree\n",
"There is also the excellent lxml library. You can quer... | [
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0002317626_python_xml.txt |
Q:
JSON serializers not working in Django
Hay, serializers is not returning JSON object
make = Make.objects.filter(slug__exact=make)
models = Model.objects.filter(make=make).values('slug','name')
json_models = serializers.get_serializer("json")()
json_models.serialize(models)
return HttpResponse... | JSON serializers not working in Django | Hay, serializers is not returning JSON object
make = Make.objects.filter(slug__exact=make)
models = Model.objects.filter(make=make).values('slug','name')
json_models = serializers.get_serializer("json")()
json_models.serialize(models)
return HttpResponse(json_models.getvalue())
I'm getting an err... | [
"As the other answer hints, its because .values(...) returns a list and serializers is meant for Querysets. However you can still do this without needing raw SimpleJSON quite simply:\nqueryset = Model.objects.filter(make__slug__exact=make)\nreturn serializers.serialize(\"json\", queryset, fields=('slug', 'name'))\n... | [
4,
2
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0002317818_django_json_python.txt |
Q:
python: dictionary dilemma: how to properly index objects based on an attribute
first, an example:
given a bunch of Person objects with
various attributes (name, ssn, phone,
email address, credit card #, etc.)
now imagine the following simple
website:
uses a person's email address as unique login name
lets... | python: dictionary dilemma: how to properly index objects based on an attribute | first, an example:
given a bunch of Person objects with
various attributes (name, ssn, phone,
email address, credit card #, etc.)
now imagine the following simple
website:
uses a person's email address as unique login name
lets users edit their attributes (including their email address)
if this website had ton... | [
"Consider this.\nclass Person( object ):\n def __init__( self, name, addr, email, etc. ):\n self.observer= []\n ... etc. ...\n @property\n def name( self ): return self._name\n @name.setter\n def name( self, value ): \n self._name= value\n for observer in self.observedBy: ... | [
3,
0
] | [] | [] | [
"data_structures",
"design_patterns",
"dictionary",
"indexing",
"python"
] | stackoverflow_0002305798_data_structures_design_patterns_dictionary_indexing_python.txt |
Q:
Django group / aggregation
I have following structure with example data:
id season_id title
1 1 Intro
2 1 Second part
3 1 Third part
4 4 Other intro
5 4 Other second part
(don't ask why), where season_id is always point to id of first epi... | Django group / aggregation | I have following structure with example data:
id season_id title
1 1 Intro
2 1 Second part
3 1 Third part
4 4 Other intro
5 4 Other second part
(don't ask why), where season_id is always point to id of first episode of season...
What i want, t... | [
"Movie.objects.annotate(category_min_season = models.Min('category__season_id')).filter(season_id=category_min_season)\n\nassuming that your catgory has FK to the Movies model.\nUpdate:\nActually you don't even need annotation; thanks to the denormalised data you have stored in the table.\nYou can just do:\nModel.o... | [
1
] | [] | [] | [
"annotate",
"django",
"group_by",
"orm",
"python"
] | stackoverflow_0002317374_annotate_django_group_by_orm_python.txt |
Q:
Python equivalent for Ruby's ObjectSpace?
I've a name of a class stored in var, which I need to create an object from.
However I do not know in which module it is defined (if I did, I would just call getattr(module,var), but I do know it's imported.
Should I go over every module and test if the class is defined th... | Python equivalent for Ruby's ObjectSpace? | I've a name of a class stored in var, which I need to create an object from.
However I do not know in which module it is defined (if I did, I would just call getattr(module,var), but I do know it's imported.
Should I go over every module and test if the class is defined there ? How do I do it in python ?
What if I have... | [
"globals()[classname] should do it.\nMore code: http://code.activestate.com/recipes/285262/\n",
"Classes are not added to a global registry in Python by default. You'll need to iterate over all imported modules and look for it.\n",
"Rather than storing the classname as a string, why don't you store the class ob... | [
1,
0,
0
] | [] | [] | [
"metaprogramming",
"module",
"python",
"ruby"
] | stackoverflow_0002318044_metaprogramming_module_python_ruby.txt |
Q:
Controlling VirtualBox
Documentation for pyVB is given in http://enomalism.com/api/pyvb/
we are trying to make a commandline interface to virtualbox using pyvb module in python.
>>> import pyvb
>>> n=pyvb.vm.vbVM()
>>> n.setUUID("64e1b2e5-739e-45a6-b8d7-3ab7519c5215}")
>>> m=pyvb.vb.VB()
>>> m.startVM(n)
this is ... | Controlling VirtualBox | Documentation for pyVB is given in http://enomalism.com/api/pyvb/
we are trying to make a commandline interface to virtualbox using pyvb module in python.
>>> import pyvb
>>> n=pyvb.vm.vbVM()
>>> n.setUUID("64e1b2e5-739e-45a6-b8d7-3ab7519c5215}")
>>> m=pyvb.vb.VB()
>>> m.startVM(n)
this is how we tried doing it, but v... | [
"Why reinvent the wheel; VirtualBox already comes with a command line interface?\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002318127_python.txt |
Q:
groovy map coercion in python
I'm a relative newcomer to python and I'm just wondering if there is some equivalent to the map coercion feature available in groovy.
For context, I am writing a unit test and want to mock a class with a simple two method interface, in groovy I would do the following:
mock = [apply:{v... | groovy map coercion in python | I'm a relative newcomer to python and I'm just wondering if there is some equivalent to the map coercion feature available in groovy.
For context, I am writing a unit test and want to mock a class with a simple two method interface, in groovy I would do the following:
mock = [apply:{value -> return value*2 }, isValid:{... | [
"Use the 3-parameter form of type():\nmock = type('mock', (object,), {'apply': (lambda self, value: value * 2),\n 'isValid': lambda self: True})\n\n"
] | [
2
] | [] | [] | [
"closures",
"mocking",
"python"
] | stackoverflow_0002318494_closures_mocking_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.