title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How can I make cx-oracle bind the results of a query to a dictionary rather than a tuple? | 4,468,071 | 10 | 2010-12-17T05:50:00Z | 4,469,346 | 12 | 2010-12-17T09:54:27Z | [
"python",
"sql",
"database",
"oracle",
"cx-oracle"
] | Here is my code. I would like to find a way to have results from a query returned as a list of dictionaries rather than list of tuples. It seems like cx\_oracle supports this with parts of the documentation talking about 'binding'. Though I can't figure out how it works.
```
def connect():
dsn = cx_Oracle.makeds... | Bindvars are used to execute query such as
* By name(given named parameters)
```
cursor = self.db.cursor()
cursor.execute("SELECT bookName, author from books where Id=:bookId" , bookId="155881")
print cursor.bindnames()
```
will print : ['BOOKID']
* by position given a list of values
```
cursor = sel... |
Python BeautifulSoup equivalent to lxml make_links_absolute | 4,468,410 | 7 | 2010-12-17T07:00:51Z | 4,468,467 | 14 | 2010-12-17T07:11:11Z | [
"python",
"beautifulsoup",
"lxml"
] | So lxml has a very hand feature: make\_links\_absolute:
```
doc = lxml.html.fromstring(some_html_page)
doc.make_links_absolute(url_for_some_html_page)
```
and all the links in doc are absolute now. Is there an easy equivalent in BeautifulSoup or do I simply need to pass it through urlparse and normalize it:
```
soup... | In my answer to [What is a simple way to extract the list of URLs on a webpage using python?](http://stackoverflow.com/questions/4139989/what-is-a-simple-way-to-extract-the-list-of-urls-on-a-webpage-using-python/4140102#4140102) I covered that incidentally as part of the extraction step; you could easily write a method... |
Generating xml in python and lxml | 4,469,983 | 4 | 2010-12-17T11:21:35Z | 4,470,035 | 8 | 2010-12-17T11:29:13Z | [
"python",
"xml",
"lxml"
] | I have this xml from sql, and I want to do the same by python 2.7 and lxml
```
<?xml version="1.0" encoding="utf-16"?>
<results>
<Country name="Germany" Code="DE" Storage="Basic" Status="Fresh" Type="Photo" />
</results>
```
Now I have:
```
from lxml import etree
# create XML
results= etree.Element('results')
c... | ```
from lxml import etree
# Create the root element
page = etree.Element('results')
# Make a new document tree
doc = etree.ElementTree(page)
# Add the subelements
pageElement = etree.SubElement(page, 'Country',
name='Germany',
Code='DE',
... |
Generating xml in python and lxml | 4,469,983 | 4 | 2010-12-17T11:21:35Z | 4,470,210 | 9 | 2010-12-17T11:57:44Z | [
"python",
"xml",
"lxml"
] | I have this xml from sql, and I want to do the same by python 2.7 and lxml
```
<?xml version="1.0" encoding="utf-16"?>
<results>
<Country name="Germany" Code="DE" Storage="Basic" Status="Fresh" Type="Photo" />
</results>
```
Now I have:
```
from lxml import etree
# create XML
results= etree.Element('results')
c... | Note this also prints the BOM
```
>>> from lxml.etree import tostring
>>> from lxml.builder import E
>>> print tostring(
E.results(
E.Country(name='Germany',
Code='DE',
Storage='Basic',
Status='Fresh',
... |
Which is better? Using inbuilt python functions or os.system commands? | 4,470,302 | 2 | 2010-12-17T12:08:25Z | 4,470,327 | 10 | 2010-12-17T12:11:43Z | [
"python"
] | Which is better to use in a python automation script for following simple operations
To create a zip file and copy it or rename it to a new location.
Using python inbuilt functions or terminal commands through os.system modules is better? | The inbuilt Python modules/ stdlib wherever you can, `subprocess` (os.system) where you must.
Reasons: Portability, maintenance, code readability just to name a few. |
Python Enum class (with tostring fromstring) | 4,472,901 | 6 | 2010-12-17T17:01:32Z | 4,472,993 | 9 | 2010-12-17T17:12:14Z | [
"python",
"enums",
"tostring"
] | I've found a simply way to implement(hack) an enum into Python:
```
class MyEnum:
VAL1, VAL2, VAL3 = range(3)
```
I can then call this as such:
```
bob = MyEnum.VAL1
```
Sexy!
Alright, now I want to be able to get both the numerical value if given a string, or a string if given a numerical value. Let's say I wan... | Well, here is what you asked for:
```
class MyEnum:
VAL1, VAL2, VAL3 = range(3)
@classmethod
def tostring(cls, val):
for k,v in vars(cls).iteritems():
if v==val:
return k
@classmethod
def fromstring(cls, str):
return getattr(cls, str.upper(), None)
print MyEnum.fromstring('Val... |
Python Enum class (with tostring fromstring) | 4,472,901 | 6 | 2010-12-17T17:01:32Z | 4,473,031 | 7 | 2010-12-17T17:15:26Z | [
"python",
"enums",
"tostring"
] | I've found a simply way to implement(hack) an enum into Python:
```
class MyEnum:
VAL1, VAL2, VAL3 = range(3)
```
I can then call this as such:
```
bob = MyEnum.VAL1
```
Sexy!
Alright, now I want to be able to get both the numerical value if given a string, or a string if given a numerical value. Let's say I wan... | Use a dict:
```
MyEnum = {'VAL1': 1, 'VAL2':2, 'VAL3':3}
```
No classes necessary. Dicts have your class beat because 1.) they're incredibly efficient, 2.) have a bunch of incredible methods baked in, and 3.) are a universal language construct. They're also extensible:
```
MyEnum['VAL4'] = 4
```
It's not wise to im... |
Python Enum class (with tostring fromstring) | 4,472,901 | 6 | 2010-12-17T17:01:32Z | 19,545,249 | 11 | 2013-10-23T14:56:27Z | [
"python",
"enums",
"tostring"
] | I've found a simply way to implement(hack) an enum into Python:
```
class MyEnum:
VAL1, VAL2, VAL3 = range(3)
```
I can then call this as such:
```
bob = MyEnum.VAL1
```
Sexy!
Alright, now I want to be able to get both the numerical value if given a string, or a string if given a numerical value. Let's say I wan... | [Time passes...]
The new Python Enum has finally landed in 3.4, and [has also been backported](https://pypi.python.org/pypi/enum34). So the answer to your question is now to use that. :) |
unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead) | 4,473,184 | 78 | 2010-12-17T17:31:23Z | 4,473,215 | 7 | 2010-12-17T17:34:55Z | [
"python",
"methods"
] | In Python, I'm trying to run a method in a class and I get an error:
```
Traceback (most recent call last):
File "C:\Users\domenico\Desktop\py\main.py", line 8, in <module>
fibo.f()
TypeError: unbound method f() must be called with fibo instance
as first argument (got nothing instead)
```
Code: (swineflu.p... | `fibo = f.fibo` references the class itself. You probably wanted `fibo = f.fibo()` (note the parentheses) to make *an instance* of the class, after which `fibo.f()` should succeed correctly.
`f.fibo.f()` fails because you are essentially calling `f(self, a=0)` without supplying `self`; `self` is "bound" automatically ... |
unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead) | 4,473,184 | 78 | 2010-12-17T17:31:23Z | 4,473,245 | 108 | 2010-12-17T17:38:36Z | [
"python",
"methods"
] | In Python, I'm trying to run a method in a class and I get an error:
```
Traceback (most recent call last):
File "C:\Users\domenico\Desktop\py\main.py", line 8, in <module>
fibo.f()
TypeError: unbound method f() must be called with fibo instance
as first argument (got nothing instead)
```
Code: (swineflu.p... | OK, first of all, you don't have to get a reference to the module into a different name; you already have a reference (from the `import`) and you can just use it. If you want a different name just use `import swineflu as f`.
Second, you are getting a reference to the class rather than instantiating the class.
So this... |
unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead) | 4,473,184 | 78 | 2010-12-17T17:31:23Z | 26,789,355 | 33 | 2014-11-06T21:04:51Z | [
"python",
"methods"
] | In Python, I'm trying to run a method in a class and I get an error:
```
Traceback (most recent call last):
File "C:\Users\domenico\Desktop\py\main.py", line 8, in <module>
fibo.f()
TypeError: unbound method f() must be called with fibo instance
as first argument (got nothing instead)
```
Code: (swineflu.p... | ## How to reproduce this error with as few lines as possible:
```
>>> class C:
... def f(self):
... print "hi"
...
>>> C.f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as
first argument (got nothing instead)
```
It fails... |
Twitter API: simple status update (Python) | 4,473,320 | 2 | 2010-12-17T17:47:02Z | 4,474,362 | 9 | 2010-12-17T20:05:55Z | [
"python",
"oauth",
"twitter",
"twitter-oauth"
] | I've been looking for a way to update my Twitter status from a Python client. As this client only needs to access one Twitter account, it should be possible to do this with a pre-generated oauth\_token and secret, according to <http://dev.twitter.com/pages/oauth_single_token>
However the sample code does not seem to w... | You might be interested in this <http://code.google.com/p/python-twitter/>
Unfortunately the docs don't exist to be fair and last 'release' was in 2009.
I've used code from the hg:
```
wget http://python-twitter.googlecode.com/hg/get_access_token.py
wget http://python-twitter.googlecode.com/hg/twitter.py
```
After ... |
`staticmethod` and `abc.abstractmethod`: Will it blend? | 4,474,395 | 44 | 2010-12-17T20:11:39Z | 4,474,495 | 19 | 2010-12-17T20:26:25Z | [
"python",
"abstract-class",
"static-methods"
] | In my Python app I want to make a method that is both a `staticmethod` and an [`abc.abstractmethod`](http://docs.python.org/library/abc.html#abc.abstractmethod). How do I do this?
I tried applying both decorators, but it doesn't work. If I do this:
```
import abc
class C(object):
__metaclass__ = abc.ABCMeta
... | ```
class abstractstatic(staticmethod):
__slots__ = ()
def __init__(self, function):
super(abstractstatic, self).__init__(function)
function.__isabstractmethod__ = True
__isabstractmethod__ = True
class A(object):
__metaclass__ = abc.ABCMeta
@abstractstatic
def test():
p... |
`staticmethod` and `abc.abstractmethod`: Will it blend? | 4,474,395 | 44 | 2010-12-17T20:11:39Z | 4,477,235 | 11 | 2010-12-18T08:05:22Z | [
"python",
"abstract-class",
"static-methods"
] | In my Python app I want to make a method that is both a `staticmethod` and an [`abc.abstractmethod`](http://docs.python.org/library/abc.html#abc.abstractmethod). How do I do this?
I tried applying both decorators, but it doesn't work. If I do this:
```
import abc
class C(object):
__metaclass__ = abc.ABCMeta
... | This will do it:
```
>>> import abc
>>> abstractstaticmethod = abc.abstractmethod
>>>
>>> class A(object):
... __metaclass__ = abc.ABCMeta
... @abstractstaticmethod
... def themethod():
... pass
...
>>> a = A()
>>> Traceback (most recent call last):
File "asm.py", line 16,... |
`staticmethod` and `abc.abstractmethod`: Will it blend? | 4,474,395 | 44 | 2010-12-17T20:11:39Z | 31,590,500 | 11 | 2015-07-23T14:36:23Z | [
"python",
"abstract-class",
"static-methods"
] | In my Python app I want to make a method that is both a `staticmethod` and an [`abc.abstractmethod`](http://docs.python.org/library/abc.html#abc.abstractmethod). How do I do this?
I tried applying both decorators, but it doesn't work. If I do this:
```
import abc
class C(object):
__metaclass__ = abc.ABCMeta
... | Starting with **Python 3.3**, it is [possible to combine](https://docs.python.org/3/library/abc.html#abc.abstractmethod) `@staticmethod` and `@abstractmethod`, so none of the other suggestions are necessary anymore:
```
@staticmethod
@abstractmethod
def my_abstract_staticmethod(...):
``` |
C# equivalent to Python's logging library | 4,474,645 | 2 | 2010-12-17T20:49:21Z | 4,474,654 | 8 | 2010-12-17T20:51:22Z | [
"c#",
"python",
"logging"
] | With python, I can use [logging](http://docs.python.org/library/logging.html) library which is pretty handy.
What's the logging library for C#? | You can use [`log4net`](http://logging.apache.org/log4net/index.html) or a [`TraceListener`](http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener.aspx). |
How to keep comments while parsing XML using Python / ElementTree | 4,474,754 | 8 | 2010-12-17T21:07:16Z | 27,333,347 | 10 | 2014-12-06T15:46:47Z | [
"python",
"xml",
"elementtree"
] | **Currently using Python 2.4.3, and not allowed to upgrade**
*I want to change the values of a given attribute in one or more tags, together with XML-comments in the updated file.*
I have managed to create a Python script that takes a XML-file as argument, and for each tag specified changes an attribute, as shown bel... | I know this is old now, but I stumbled across this answer above about how to retain comments. Frederik's [published instructions](http://effbot.org/zone/element-pi.htm) about how to put comments into the tree still works with current versions of ElementTree, but does more than it needs to for my use, at least. It wraps... |
django-south with django-audit-log | 4,475,377 | 5 | 2010-12-17T22:39:05Z | 4,529,034 | 8 | 2010-12-25T02:00:15Z | [
"python",
"django",
"django-south"
] | I'm trying to do a [django-south migration](http://south.aeracode.org/) to an existing application to add [django-audit-log](http://code.google.com/p/django-audit-log/) to it (to track user-initiated changes of a module), but am running into significant errors. Specifically with the action\_user\_id field that is a Las... | Here's finally the answer (and explanation).
When migrating South not only stores the names of the fields in your models, but also the type and the arguments that are passed to it. The result of this is that South has to understand which parameters are given by the field and which should be stored.
So when you create... |
python double loop question | 4,475,704 | 5 | 2010-12-17T23:38:49Z | 4,475,783 | 13 | 2010-12-17T23:55:43Z | [
"python",
"loops"
] | i am wondering if the following code can be written in a somewhat nice way. basically, i want to calculate z = f(x,y) for a (x,y) meshgrid.
```
a = linspace(0,xr,100)
b = linspace(0,yr,100) ... | Yeah. Your code as presented in the question is nice.
Do not ever think that few lines is "nice" or "cool". What counts is clarity, readability and maintainability. Other people should be able to understand your code (and you should understand it in 12 months, when you need to find a bug).
Many programmers, especiall... |
Fast-Responding Command Line Scripts | 4,476,125 | 4 | 2010-12-18T01:38:12Z | 4,476,530 | 7 | 2010-12-18T03:51:35Z | [
"python",
"command-line",
"performance"
] | I have been writing command-line Python scripts for a while, but recently I felt really frustrated with speed.
I'm not necessarily talking about processing speed, dispatching tasks or other command-line tool-specific processes (that is usually a design/implementation problem), but rather I am talking of simply running... | In addition to compiling the Python files, Mercurial modifies importing to be on demand which does indeed reduce the start-up time. It sets `__builtin__.__import__` to its own import function in the demandimport module.
If you look at the hg script in /usr/lib/ (or wherever it is on your machine), you can see this for... |
Python + Mechanize not working with Delicious | 4,476,354 | 4 | 2010-12-18T02:57:08Z | 4,476,709 | 9 | 2010-12-18T04:52:38Z | [
"python",
"web-crawler",
"mechanize",
"scraper"
] | I'm using Mechanize and Beautiful soup to scrape some data off Delicious
```
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
mech = Browser()
url = "http://www.delicious.com/varunsrin"
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
print soup.prettify()
```
This works for ... | Take some of the tips for emulating a browser with python+mechanize from [here](http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/). Adding `addheaders` and `set_handle_robots` appears to be the minimum required. With the code below, I get output:
```
from mechanize import Browser, _http
from Be... |
Simple URL GET/POST function in Python | 4,476,373 | 46 | 2010-12-18T03:02:47Z | 4,476,389 | 59 | 2010-12-18T03:08:44Z | [
"python",
"http"
] | I can't seem to Google it, but I want a function that does this:
Accept 3 arguments (or more, whatever):
* URL
* a dictionary of params
* POST or GET
Return me the results, and the response code.
Is there a snippet that does this? | **requests**
<https://github.com/kennethreitz/requests/>
Here's a few common ways to use it:
```
import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}
# GET
r = requests.get(url)
# GET with params in URL
r = requests.get(url, params=payload)
# POST with form-encoded data
r = requests.... |
Simple URL GET/POST function in Python | 4,476,373 | 46 | 2010-12-18T03:02:47Z | 4,476,392 | 30 | 2010-12-18T03:09:23Z | [
"python",
"http"
] | I can't seem to Google it, but I want a function that does this:
Accept 3 arguments (or more, whatever):
* URL
* a dictionary of params
* POST or GET
Return me the results, and the response code.
Is there a snippet that does this? | You could use this to wrap urllib2:
```
def URLRequest(url, params, method="GET"):
if method == "POST":
return urllib2.Request(url, data=urllib.urlencode(params))
else:
return urllib2.Request(url + "?" + urllib.urlencode(params))
```
That will return a [Request](http://docs.python.org/library/... |
Simple URL GET/POST function in Python | 4,476,373 | 46 | 2010-12-18T03:02:47Z | 4,476,425 | 9 | 2010-12-18T03:18:48Z | [
"python",
"http"
] | I can't seem to Google it, but I want a function that does this:
Accept 3 arguments (or more, whatever):
* URL
* a dictionary of params
* POST or GET
Return me the results, and the response code.
Is there a snippet that does this? | ```
import urllib
def fetch_thing(url, params, method):
params = urllib.urlencode(params)
if method=='POST':
f = urllib.urlopen(url, params)
else:
f = urllib.urlopen(url+'?'+params)
return (f.read(), f.code)
content, response_code = fetch_thing(
'http://g... |
Simple URL GET/POST function in Python | 4,476,373 | 46 | 2010-12-18T03:02:47Z | 10,022,497 | 39 | 2012-04-05T04:01:21Z | [
"python",
"http"
] | I can't seem to Google it, but I want a function that does this:
Accept 3 arguments (or more, whatever):
* URL
* a dictionary of params
* POST or GET
Return me the results, and the response code.
Is there a snippet that does this? | Even easier: via the [requests](http://docs.python-requests.org/en/latest/index.html) module.
```
import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
post_response = requests.post(url='http://some.other.site', data=post_data)
``` |
How to make ON DELETE CASCADE work in sqlite 3.7.4? | 4,477,269 | 8 | 2010-12-18T08:17:06Z | 4,478,470 | 8 | 2010-12-18T14:33:48Z | [
"python",
"sql",
"sqlite"
] | I checked the feature list several times, and it seems that cascading should work.
When I execute this python script:
```
#!/usr/bin/env python3
import sqlite3
print(sqlite3.sqlite_version)
con = sqlite3.connect(':memory:')
a = "create table a (id integer primary key, name text)"
con.execute(a)
b = "create table b... | SQLite foreign keys are disabled for compatibility purposes. You need to enable them manually right after each connection to the database.
`con.execute("PRAGMA foreign_keys = ON")` |
Python try except finally | 4,477,332 | 4 | 2010-12-18T08:38:33Z | 4,477,360 | 9 | 2010-12-18T08:45:53Z | [
"python",
"web2py",
"try-catch-finally"
] | It looks like I don't quite have the hang of Exception handling yet. I'm at a loss :(
The following code sometimes returns this error:
```
File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping
db(table.id==id_).update(status=status)
UnboundLocalError: local variable 'status' referenced befor... | Your code doesn't always assign something to status. I can see a few ways that status might not be assigned and I've highlighted them below:
```
try:
server_url = self._get_pingback_server(target)
except PingbackClientError, e:
# If evaluating `e.message` raises an exception then status is not set.
status ... |
how can i convert a string like 123245wkjsvd :/' to list and sort? | 4,477,504 | 2 | 2010-12-18T09:35:02Z | 4,477,524 | 12 | 2010-12-18T09:41:09Z | [
"python",
"list",
"string"
] | I want to convert it to a list and sort them alphabetically and then turn the result to a string again. Well i want to do this in python. how can i do that? | There are shorter one-liners, but here it is statement-by-statement:
```
# initial string
input_string = "123245wkjsvd :/'"
# Convert string to list of characters
list_of_chars = list(input_string)
# Sort list
list_of_chars.sort()
# Convert to string
output_string = ''.join(list_of_chars)
```
Shortest one-liner:
```... |
python and / or operators return value | 4,477,850 | 8 | 2010-12-18T11:32:37Z | 4,477,856 | 19 | 2010-12-18T11:35:02Z | [
"python",
"operators"
] | I was watching a [2007 video on Advanced Python or Understanding Python](http://video.google.com/videoplay?docid=7760178035196894549#), and at 18'27" the speaker claims "As some may know in Python `and` and `or` return one of the two values, whereas `not` returns always a boolean." When has this been the case?
As far ... | The `and` and `or` operators do return one of their operands, not a pure boolean value like `True` or `False`:
```
>>> 0 or 42
42
>>> 0 and 42
0
```
Whereas `not` always returns a pure boolean value:
```
>>> not 0
True
>>> not 42
False
``` |
python and / or operators return value | 4,477,850 | 8 | 2010-12-18T11:32:37Z | 19,187,401 | 14 | 2013-10-04T17:32:51Z | [
"python",
"operators"
] | I was watching a [2007 video on Advanced Python or Understanding Python](http://video.google.com/videoplay?docid=7760178035196894549#), and at 18'27" the speaker claims "As some may know in Python `and` and `or` return one of the two values, whereas `not` returns always a boolean." When has this been the case?
As far ... | See [this](http://docs.python.org/release/2.7.3/library/stdtypes.html#boolean-operations-and-or-not) table from the standard library reference in the Python docs:
 |
how to draw a heart with pylab | 4,478,078 | 9 | 2010-12-18T12:49:18Z | 4,478,633 | 8 | 2010-12-18T15:21:13Z | [
"python",
"math",
"numpy",
"matplotlib"
] | How to draw a heart with pylab? I searched with google for ways to draw the picture but i want know how to draw it with pylab. Can someone help? The picture should look like [this](http://img3.douban.com/view/note/large/public/p95223116-2.jpg):
 | Using the linked formula in the other solution:
```
import pylab
x = scipy.linspace(-2,2,1000)
y1 = scipy.sqrt(1-(abs(x)-1)**2)
y2 = -3*scipy.sqrt(1-(abs(x)/2)**0.5)
pylab.fill_between(x, y1, color='red')
pylab.fill_between(x, y2, color='red')
pylab.xlim([-2.5, 2.5])
pylab.text(0, -0.4, 'Stack Overflow', fontsize=24, ... |
How does Python handle memory? | 4,478,082 | 4 | 2010-12-18T12:49:59Z | 4,478,112 | 7 | 2010-12-18T12:57:19Z | [
"python",
"performance",
"memory"
] | I've been looking at a [in-memory database](http://en.wikipedia.org/wiki/In-memory_database) -- and it got me thinking, how does Python handle IO that's not tied to a connection (and even data that is); for example, hashes, sets, etc.; is this a config somewhere, or is it dynamically managed based on resources; are the... | Python allocates all memory that the application asks for. There is not much room for policy. The only issue is when to release memory. (C)Python immediately releases all memory that is not referenced anymore (this is also not tunable). Memory that is referenced only from itself (ie. cycles) are released by the garbage... |
Partially transparent scatter plot, but with a solid color bar | 4,478,725 | 15 | 2010-12-18T15:44:49Z | 4,479,996 | 7 | 2010-12-18T20:27:52Z | [
"python",
"matplotlib",
"scatter",
"colorbar"
] | In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1?
Here is what one gets, with `from pylab import *; scatter(range(10), arange(0, 100, 10), c=range(10), alpha=0.2); color_bar = colorbar()`:

fig2 = pylab.figure()
ax1 = fig1.add_subplot(111)
ax2 = fig2.add_subplot(111)
ax1.scatter(range(10), range(10), c=range(10), alpha=0.2)
im = ax2.scatter(range(10), range(10), c=range(10), alpha=1.0)
fig1.c... |
Partially transparent scatter plot, but with a solid color bar | 4,478,725 | 15 | 2010-12-18T15:44:49Z | 4,480,124 | 17 | 2010-12-18T20:55:18Z | [
"python",
"matplotlib",
"scatter",
"colorbar"
] | In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1?
Here is what one gets, with `from pylab import *; scatter(range(10), arange(0, 100, 10), c=range(10), alpha=0.2); color_bar = colorbar()`:

```
color_bar.set_alpha(1)
color_bar.draw_all()
# pylab.draw() or pyplot.draw() might be necessary
```
It would be great to get a confirmation that this is the most robust way to proceed, though! :) |
django, what is related_name for? and how do i create shared columns to use across project? | 4,479,103 | 9 | 2010-12-18T17:11:21Z | 4,479,176 | 7 | 2010-12-18T17:26:55Z | [
"python",
"django"
] | I was trying to design a model in django with some auditing fields. Such as created at, created by, updated at and updated by. Those four columns are going to be repeated across all my models in different applications.
My first question, is there a way to put those columns and can include them in my class each time i ... | Try this:
```
class AbstractClass(models.Model):
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
updated_at=models.DateTimeField("Updated at")
updated_by=models.ForeignKey(User, db_column="updated_by", null=True, ... |
Using fourier analysis for time series prediction | 4,479,463 | 14 | 2010-12-18T18:41:24Z | 4,479,849 | 12 | 2010-12-18T19:52:10Z | [
"python",
"math",
"matlab"
] | For data that is known to have seasonal, or daily patterns I'd like to use fourier analysis be used to make predictions. After running fft on time series data, I obtain coefficients. How can I use these coefficients for prediction?
I believe FFT assumes all data it receives constitute one period, then, if I simply reg... | It sounds like you want a combination of extrapolation *and* denoising.
You say you want to repeat the observed data over multiple periods. Well, then just repeat the observed data. No need for Fourier analysis.
But you also want to find "patterns". I assume that means finding the dominant frequency components in the... |
Using fourier analysis for time series prediction | 4,479,463 | 14 | 2010-12-18T18:41:24Z | 28,163,549 | 11 | 2015-01-27T05:01:06Z | [
"python",
"math",
"matlab"
] | For data that is known to have seasonal, or daily patterns I'd like to use fourier analysis be used to make predictions. After running fft on time series data, I obtain coefficients. How can I use these coefficients for prediction?
I believe FFT assumes all data it receives constitute one period, then, if I simply reg... | I'm aware that this question may be not actual for you anymore, but for others that are looking for answers I wrote a very simple example of fourier extrapolation in Python <https://gist.github.com/tartakynov/83f3cd8f44208a1856ce>
Before you run the script make sure that you have all dependencies installed (numpy, mat... |
Sane way to define default variable values from within a jinja template? | 4,479,710 | 8 | 2010-12-18T19:26:15Z | 4,480,028 | 12 | 2010-12-18T20:34:30Z | [
"python",
"jinja2"
] | I'd like to set default values for variables used in my Jinja template inside of the template itself. Looking at the Jinja2 documentation, I don't see any way to do this. Have I missed something? I see the "default" filter, but I want to set the value template wide instead of a use-by-use basis.
I spent an hour or so ... | The [set control structure](http://jinja.pocoo.org/templates/#assignments) can do what you want.
Here is some code I used to test:
```
from jinja2 import Template
t = '''{% set name=name or "John Doe" %}Hello {{ name }}'''
template = Template(t)
print template.render(name='Jonnie Doe')
print template.render()
```
As... |
Sane way to define default variable values from within a jinja template? | 4,479,710 | 8 | 2010-12-18T19:26:15Z | 19,663,948 | 15 | 2013-10-29T16:27:31Z | [
"python",
"jinja2"
] | I'd like to set default values for variables used in my Jinja template inside of the template itself. Looking at the Jinja2 documentation, I don't see any way to do this. Have I missed something? I see the "default" filter, but I want to set the value template wide instead of a use-by-use basis.
I spent an hour or so ... | What worked for me was to use a filter:
```
t = '''Hello {{name | default('John Doe')}}'''
``` |
How to implement an "undo" feature using Python/Django | 4,479,781 | 11 | 2010-12-18T19:38:18Z | 4,480,105 | 9 | 2010-12-18T20:51:43Z | [
"python",
"django",
"undo",
"undo-redo"
] | I have a Django application where I allow a user to import a CSV file with contact data (membership #, first name, last name, etc).
When they import the file, the application checks the database for a matching record and either: 1) inserts a new record if no match exists, or 2) updates the existing data with the new d... | Take a look at [`django-reversion`](https://github.com/etianen/django-reversion). It provides version control for Django models. Can be easily added to existing project.
It doesn't employ "current" pointer approach. Instead, it serializes object each time it's being saved and stores it in a separate `Version` model wi... |
Python generate dates series | 4,479,800 | 3 | 2010-12-18T19:42:20Z | 4,479,842 | 16 | 2010-12-18T19:50:51Z | [
"python",
"datetime",
"timestamp"
] | How can i generate array with dates like this:
Timestamps in javascript miliseconds format from 2010.12.01 00:00:00 to 2010.12.12.30 23.59.59
with step 5 minutes.
```
['2010.12.01 00:00:00', '2010.12.01 00:05:00','2010.12.01 00:10:00','2010.12.01 00:15:00', ...]
``` | Well, obviously you start at the start time, loop until you reach the end time and increment inbetween.
```
import datetime
dt = datetime.datetime(2010, 12, 01)
end = datetime.datetime(2010, 12, 30, 23, 59, 59)
step = datetime.timedelta(seconds=5)
result = []
while dt < end:
result.append(dt.strftime('%Y-%m-%d ... |
Types and classes in Python | 4,479,819 | 7 | 2010-12-18T19:46:00Z | 4,479,843 | 9 | 2010-12-18T19:51:05Z | [
"python",
"class",
"types"
] | I'm a bit confused about types and classes in Python. For e.g. the following REPL conversation confuses me:
```
>>> class A: pass
...
>>> a = A()
>>> type(a)
<type 'instance'>
>>> a.__class__
<class __main__.A at 0xb770756c>
>>> type([])
<type 'list'>
>>> [].__class__
<type 'list'>
>>> type(list)
<type 'type'>
>>> li... | You're encountering the different behavior for new style classes versus classic classes. For further reading read this: [Python Data Model](http://docs.python.org/reference/datamodel.html). Specifically read the section on classes and the difference between new style and classic classes.
Try typing the following into ... |
django shared library/classes | 4,479,901 | 6 | 2010-12-18T20:06:08Z | 4,482,804 | 9 | 2010-12-19T11:54:49Z | [
"python",
"django"
] | Am new to django and was looking for advice where to place my shared library. Am planning on creating classes that I want to use across all my apps within the project. Where would be the best location to place them?
e.x abstract models
regards, | We usually set our projects up like this:
```
/site/
__init__.py
manage.py
settings.py
urls.py
/apps/
__init__.py
/appA/
__init__.py
/appB/
__init__.py
/lib/
__init__.py
/django-lib/
__init__.py
/shared-lib/
... |
Division by zero: int vs. float | 4,480,020 | 2 | 2010-12-18T20:32:50Z | 4,480,036 | 8 | 2010-12-18T20:35:44Z | [
"c#",
"java",
"python",
"vb.net",
"math"
] | Dividing an int by zero, will throw an exception, but a float won't - at least in Java. Why does a float have additional NaN info, while an int type doesn't? | The representation of a float has been designed such that there are some special combination of bits reserved to store [special values](http://en.wikipedia.org/wiki/Floating_point#Special_values) such as NaN, infinity, etc.
There are no unused representations for an int type - every bit pattern corresponds to an integ... |
Argparse optional positional arguments? | 4,480,075 | 333 | 2010-12-18T20:45:35Z | 4,480,202 | 438 | 2010-12-18T21:15:47Z | [
"python",
"argparse"
] | I have script which is meant to be used like this:
`usage: installer.py dir [-h] [-v]`
`dir` is a positional argument which is defined like this:
```
parser.add_argument('dir', default=os.getcwd())
```
I want dir to be optional: when it's not specified it should just be cwd.
Unfortunately when I don't specify the d... | Try using [`nargs='?'`](http://docs.python.org/2/library/argparse.html#nargs)
```
parser.add_argument('dir', nargs='?', default=os.getcwd())
```
extended example:
```
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v... |
Argparse optional positional arguments? | 4,480,075 | 333 | 2010-12-18T20:45:35Z | 31,243,133 | 26 | 2015-07-06T10:11:40Z | [
"python",
"argparse"
] | I have script which is meant to be used like this:
`usage: installer.py dir [-h] [-v]`
`dir` is a positional argument which is defined like this:
```
parser.add_argument('dir', default=os.getcwd())
```
I want dir to be optional: when it's not specified it should just be cwd.
Unfortunately when I don't specify the d... | As an extension to @VinaySajip answer. [There are additional `nargs` worth mentioning](https://docs.python.org/2/library/argparse.html#nargs).
1. `parser.add_argument('dir', nargs=1, default=os.getcwd())`
N (an integer). N arguments from the command line will be gathered together into a list
2. `parser.add_argument(... |
Python equivalent of Perl file test readable (-r), writeable (-w) and executable (-x) operators | 4,480,316 | 10 | 2010-12-18T21:39:22Z | 4,480,387 | 10 | 2010-12-18T21:56:14Z | [
"python",
"perl",
"operators"
] | I have been Googling to try and find an equivalent in Python to some of Perl's file test operators.
Most of the file test operators are just a direct Pythonification of the underlying os' `stat` call. For example, `os.stat('file').st_ctime` just reads the inode change time as the \*nix `stat` utility or `ls -l` would ... | Looking at the output of `strace`, perl does a `stat()` call followed by `getgroups()` to get the supplementary group IDs of the perl process. So it seems it just checks the results of the `stat()` call against the EUID, EGID and supplementary group IDs.
Python has a `getgroups()` function in `os`, so I'm sure you cou... |
Django and empty formset are valid | 4,481,366 | 8 | 2010-12-19T02:49:27Z | 5,397,721 | 17 | 2011-03-22T20:54:39Z | [
"python",
"django",
"formset"
] | I have a little problem with the formset.
I must display several formsets in a page, and each formset has several forms.
So i did something like that :
```
#GET
for prod in products:
ProductFormSet = modelformset_factory(Product,exclude=('date',),extra=prod.amount)
formsset.append(ProductFormSet(prefix="pro... | I ran into this question while researching another problem. While digging through the Django source in search of a solution for my problem, I found the answer to this question so I'll document it here:
When a form is allowed to have empty values (this applies for empty forms contained within a formset) *and* the submi... |
Django and empty formset are valid | 4,481,366 | 8 | 2010-12-19T02:49:27Z | 14,443,414 | 8 | 2013-01-21T16:50:36Z | [
"python",
"django",
"formset"
] | I have a little problem with the formset.
I must display several formsets in a page, and each formset has several forms.
So i did something like that :
```
#GET
for prod in products:
ProductFormSet = modelformset_factory(Product,exclude=('date',),extra=prod.amount)
formsset.append(ProductFormSet(prefix="pro... | @Jonas, thanks. I used your description to solve my problem. I needed the a form to NOT validate when empty. (Forms added with javascript)
```
class FacilityForm(forms.ModelForm):
class Meta:
model = Facility
def __init__(self, *arg, **kwarg):
super(FacilityForm, self).__init__(*arg, **kwarg)
... |
Failed to get the HTTP POST request body using Twisted | 4,481,644 | 2 | 2010-12-19T04:49:51Z | 4,483,581 | 7 | 2010-12-19T15:17:55Z | [
"python",
"http",
"twisted"
] | I was trying to get the HTTP POST request body by using t.p.basic.LineReceiver but failed. My code is listed below:
```
from twisted.internet import reactor, protocol
from twisted.protocols import basic
class PrintPostBody(basic.LineReceiver):
def __init__(self):
self.line_no = 0
def lineReceived(sel... | I suspect you didn't see the request body printed out because it didn't contain any newlines or end with a newline. So it got into the parse buffer of your PrintPostBody instance and sat there forever, waiting for a newline to indicate that a full line had been received. LineReceiver won't call the lineReceived callbac... |
Python import a module into one class only | 4,481,719 | 5 | 2010-12-19T05:17:15Z | 4,481,741 | 8 | 2010-12-19T05:24:03Z | [
"python",
"import"
] | I am trying to get a module to import, but only if an object of a specific class is called. For example:
```
class One(object):
try:
import OneHelper
except ImportError:
pass
def __init__(self):
# this function doesn't use OneHelper
...
def blah(self):
# this fu... | The `import OneHelper` works fine in the class, making it a class attribute. You can verify this with `dir(One)` after defining your class -- there's your `OneHelper` attribute. `One.OneHelper` is a reference to the module. In an instance, of course, you may access it as `self.OneHelper` from your methods. (You could a... |
Convert a list of characters into a string | 4,481,724 | 235 | 2010-12-19T05:19:06Z | 4,481,731 | 322 | 2010-12-19T05:20:50Z | [
"python",
"string"
] | If I have a list of chars:
```
a = ['a','b','c','d']
```
How do I convert it into a single string?
```
a = 'abcd'
``` | Use the `join` method of the empty string to join all of the strings together with the empty string in between, like so:
```
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'
``` |
Convert a list of characters into a string | 4,481,724 | 235 | 2010-12-19T05:19:06Z | 4,481,737 | 23 | 2010-12-19T05:22:09Z | [
"python",
"string"
] | If I have a list of chars:
```
a = ['a','b','c','d']
```
How do I convert it into a single string?
```
a = 'abcd'
``` | This works in JavaScript or Ruby, why not in Python?
```
>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
```
But in Python the `join` method is on the `str` class:
```
# this is the Python way
"".join(['a','b... |
Convert a list of characters into a string | 4,481,724 | 235 | 2010-12-19T05:19:06Z | 10,055,869 | 7 | 2012-04-07T15:49:06Z | [
"python",
"string"
] | If I have a list of chars:
```
a = ['a','b','c','d']
```
How do I convert it into a single string?
```
a = 'abcd'
``` | This may be the fastest way:
```
>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'
``` |
Watching a property for changes | 4,481,844 | 6 | 2010-12-19T06:09:50Z | 4,481,861 | 16 | 2010-12-19T06:14:46Z | [
"python",
"variables",
"watch"
] | I need a function similar to `gobject.io_add_watch` but for a variable. For example it needs to watch the variable `stop` initialized to `stop = False` and when stop is changed to `True` it must call a function. I can't have a separate thread watching the variable in a loop with a time.sleep.
Is there such a function ... | Use a [property](http://docs.python.org/library/functions.html#property) in a class:
```
class Stopwatch(object):
def __init__(self, callback):
self._stop = False
self.callback = callback
@property
def stop(self): return self._stop
@stop.setter
def stop(self, value):
self.... |
Python: Trying to mock datetime.date.today() but not working | 4,481,954 | 66 | 2010-12-19T06:54:38Z | 4,482,067 | 59 | 2010-12-19T07:49:27Z | [
"python",
"testing",
"datetime",
"mocking"
] | Can anyone tell me why this isn't working?
```
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
```
Perhaps someone could suggest a better way? | There are a few problems.
First of all, the way you're using `mock.patch` isn't quite right. When used as a decorator, it replaces the given function/class (in this case, `datetime.date.today`) with a `Mock` object *only within the decorated function*. So, only within your `today()` will `datetime.date.today` be a dif... |
Python: Trying to mock datetime.date.today() but not working | 4,481,954 | 66 | 2010-12-19T06:54:38Z | 5,437,199 | 27 | 2011-03-25T19:28:12Z | [
"python",
"testing",
"datetime",
"mocking"
] | Can anyone tell me why this isn't working?
```
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
```
Perhaps someone could suggest a better way? | To add to Daniel G's solution:
```
from datetime import date
class FakeDate(date):
"A manipulable date replacement"
def __new__(cls, *args, **kwargs):
return date.__new__(date, *args, **kwargs)
```
This creates a class which, when instantiated, will return a normal datetime.date object, but which is ... |
Python: Trying to mock datetime.date.today() but not working | 4,481,954 | 66 | 2010-12-19T06:54:38Z | 17,644,388 | 62 | 2013-07-14T22:22:04Z | [
"python",
"testing",
"datetime",
"mocking"
] | Can anyone tell me why this isn't working?
```
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
```
Perhaps someone could suggest a better way? | Another option is to use
<https://github.com/spulec/freezegun/>
Install it:
```
pip install freezegun
```
And use it:
```
from freezegun import freeze_time
@freeze_time("2012-01-01")
def test_something():
from datetime import datetime
print(datetime.now()) # 2012-01-01 00:00:00
from datetime import ... |
Python: Trying to mock datetime.date.today() but not working | 4,481,954 | 66 | 2010-12-19T06:54:38Z | 20,034,516 | 10 | 2013-11-17T18:29:22Z | [
"python",
"testing",
"datetime",
"mocking"
] | Can anyone tell me why this isn't working?
```
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
```
Perhaps someone could suggest a better way? | I guess I came a little late for this but I think the main problem here is that you're patching datetime.date.today directly and, according to the documentation, this is wrong.
You should patch the reference imported in the file where the tested function is, for example.
Let's say you have a functions.py file where y... |
Python: Trying to mock datetime.date.today() but not working | 4,481,954 | 66 | 2010-12-19T06:54:38Z | 25,652,721 | 37 | 2014-09-03T20:01:30Z | [
"python",
"testing",
"datetime",
"mocking"
] | Can anyone tell me why this isn't working?
```
>>> import mock
>>> @mock.patch('datetime.date.today')
... def today(cls):
... return date(2010, 1, 1)
...
>>> from datetime import date
>>> date.today()
datetime.date(2010, 12, 19)
```
Perhaps someone could suggest a better way? | For what it's worth, the Mock docs talk about datetime.date.today specifically, and it's possible to do this without having to create a dummy class:
<http://www.voidspace.org.uk/python/mock/examples.html#partial-mocking>
```
>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
... mock_date... |
How do I raise a ValidationError (or do something similar) in views.py of my Django? | 4,482,392 | 9 | 2010-12-19T09:56:05Z | 4,482,474 | 11 | 2010-12-19T10:14:46Z | [
"python",
"django",
"validation",
"forms"
] | I'm using Django forms. I'm validating in the model layer:
```
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError("Headline must be more than 5 characters.")
return title
```
However, there are some things that I need to validate in the `views... | I think gruszczy's answer is a good one, but if you're after generic validation involving variables that you think are only available in the view, here's an alternative: pass in the vars as arguments to the form and deal with them in the form's main clean() method.
The difference/advantage here is that your view stays... |
'module' object has no attribute 'basicConfig' | 4,482,587 | 7 | 2010-12-19T10:50:29Z | 4,482,598 | 17 | 2010-12-19T10:54:29Z | [
"python"
] | I have the following code, copied from the Python manual:
```
import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug('This message should go to the log file')
```
When I try to run the script (via `python.exe script.py`) I get an error of `'module' ob... | You've got another module called `logging` on the python path; probably a file `logging.py` in the same directory. Compare `print logging.__file__`. |
Python - Convert currency code to its sign | 4,483,158 | 12 | 2010-12-19T13:36:48Z | 4,483,705 | 12 | 2010-12-19T15:50:18Z | [
"python",
"currency"
] | In Python, how can I convert currency code to its sign?
For example, `USD` would be converted to `$`, and `JPY` would be converted to `Â¥`.
If there isn't a generic way to do this, is there any simple dictionary of these on the Web?
Thanks. | Using the [locale](http://docs.python.org/library/locale.html#module-locale) module:
```
import locale
locales=('en_AU.utf8', 'en_BW.utf8', 'en_CA.utf8',
'en_DK.utf8', 'en_GB.utf8', 'en_HK.utf8', 'en_IE.utf8', 'en_IN', 'en_NG',
'en_PH.utf8', 'en_US.utf8', 'en_ZA.utf8',
'en_ZW.utf8', 'ja_JP.utf8')
for l in... |
Using Tornado with Pika for Asynchronous Queue Monitoring | 4,483,440 | 8 | 2010-12-19T14:45:58Z | 4,573,259 | 8 | 2011-01-01T05:29:08Z | [
"python",
"asynchronous",
"rabbitmq",
"amqp",
"tornado"
] | I have an AMQP server ([RabbitMQ](http://www.rabbitmq.com/)) that I would like to both publish and read from in a [Tornado web server](http://www.tornadoweb.org/). To do this, I figured I would use an asynchronous amqp python library; in particular [Pika](https://github.com/gmr/pika/) (a variation of it that supposedly... | It would help to see some source code, but I use this same tornado-supporting pika module without issue in more than one production project.
You don't want to create a connection per request. Create a class that wraps all of your AMQP operations, and instantiate it as a singleton at the tornado Application level that ... |
Error when inheriting an abstract class with foreign keys | 4,483,508 | 4 | 2010-12-19T15:01:10Z | 4,483,758 | 8 | 2010-12-19T16:03:21Z | [
"python",
"django"
] | I have the below code written in django
```
from django.db import models
from django.contrib.auth.models import User
class AuditColumns(models.Model):
created_at=models.DateField("Created at")
created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by")
updated_at=models... | Related names are provided by the Django ORM to enable you to easily find all models that key into the current model. So if you have a key from a Foo to a Bar, the instance of Bar will have, by default, an attribute called foo\_set that would give you a list of all Foos that are linked to that specific Bar.
You can sp... |
Writing XML to file corrupts files in python | 4,484,228 | 4 | 2010-12-19T17:37:15Z | 4,484,360 | 8 | 2010-12-19T18:09:13Z | [
"python",
"xml",
"file-io",
"minidom"
] | I'm attempting to write contents from `xml.dom.minidom` object to file. The simple idea is to use 'writexml' method:
```
import codecs
def write_xml_native():
# Building DOM from XML
xmldoc = minidom.parse('semio2.xml')
f = codecs.open('codified.xml', mode='w', encoding='utf-8')
# Using native writexm... | Hmm, though this should work:
```
xml = minidom.parse("test.xml")
with codecs.open("out.xml", "w", "utf-8") as out:
xml.writexml(out)
```
you may alternatively try:
```
with codecs.open("test.xml", "r", "utf-8") as inp:
xml = minidom.parseString(inp.read().encode("utf-8"))
with codecs.open("out.xml", "w", "u... |
How to filter a dictionary in Python? | 4,484,690 | 8 | 2010-12-19T19:29:16Z | 4,484,705 | 12 | 2010-12-19T19:33:00Z | [
"python",
"dictionary"
] | ```
d = {'foo': 'x',
'bar': 'y',
'zoo': 'None',
'foobar': 'None'}
```
I want to filter all the items whose value is `'None'` and update the `foo` and `bar` items with a particular value. I tried:
```
for i in x.items():
....: if i[i] == 'None':
....: x.pop(i[0])
....: else:
...... | it's not clear where you're getting your `'updated'` value from, but in general it would look like this:
```
{i: 'updated' for i, j in d.items() if j != 'None'}
```
in python2.7 or newer. |
How to filter a dictionary in Python? | 4,484,690 | 8 | 2010-12-19T19:29:16Z | 4,484,730 | 17 | 2010-12-19T19:40:23Z | [
"python",
"dictionary"
] | ```
d = {'foo': 'x',
'bar': 'y',
'zoo': 'None',
'foobar': 'None'}
```
I want to filter all the items whose value is `'None'` and update the `foo` and `bar` items with a particular value. I tried:
```
for i in x.items():
....: if i[i] == 'None':
....: x.pop(i[0])
....: else:
...... | It is not clear what is `'None'` in the dictionary you posted. If it is a string, you can use the following:
```
dict((k, 'updated') for k, v in d.iteritems() if v != 'None')
```
If it is `None`, just replace the checking, for example:
```
dict((k, 'updated') for k, v in d.iteritems() if v is None)
``` |
Invalid literal for int with base 10: '' | 4,484,728 | 3 | 2010-12-19T19:39:43Z | 4,484,743 | 7 | 2010-12-19T19:43:47Z | [
"python",
"casting",
"slice"
] | ```
>>> n = ''.join(i for i in x if i.isdigit())
>>> n.isdigit()
True
>>> x.isdigit()
False
>>> previous = 0
>>> next = 100
>>> answer = 0
>>> for i in range(0,100):
... answer += int(n[previous:next])
... previous = next
... next += 100
...
Traceback (most recent call last):
File "<stdin>", line 2, i... | `n` might be numeric, but at some stage you're going past the length of `n` such that `n[previous:next]` contains no characters at all. The empty string `''` cannot be converted to an int, hence the error which tells the full story: `invalid literal for int() with base 10: ''`.
```
>>> int('')
Traceback (most recent c... |
In Python, why doesn't exec work in a function with a subfunction? | 4,484,872 | 42 | 2010-12-19T20:13:00Z | 4,484,946 | 50 | 2010-12-19T20:31:14Z | [
"python",
"exec"
] | It looks like you can't use exec in a function that has a subfunction...
Anyone know why this Python code doesn't work? I get an error at the exec in test2. Also, I know exec's aren't good style, but trust me, I'm using exec for an appropriate reason. I wouldn't use it otherwise.
```
#!/usr/bin/env python
#
def test... | Correct. You can't use exec in a function that has a subfunction, unless you specify a context. From the docs:
> If exec is used in a function and the
> function contains a nested block with
> free variables, the compiler will
> raise a SyntaxError unless the exec
> explicitly specifies the local
> namespace for the e... |
In Python, why doesn't exec work in a function with a subfunction? | 4,484,872 | 42 | 2010-12-19T20:13:00Z | 4,488,826 | 23 | 2010-12-20T10:37:59Z | [
"python",
"exec"
] | It looks like you can't use exec in a function that has a subfunction...
Anyone know why this Python code doesn't work? I get an error at the exec in test2. Also, I know exec's aren't good style, but trust me, I'm using exec for an appropriate reason. I wouldn't use it otherwise.
```
#!/usr/bin/env python
#
def test... | Although in Python it looks kind of like the local variables are stored in a dictionary `locals()`, they usually aren't. Instead they are mostly stored on the stack and accessed by index. This makes local variable lookup faster than if it had to do a dictionary lookup every time. If you use the `locals()` function then... |
How do I download a website using python 3? | 4,485,113 | 4 | 2010-12-19T21:10:28Z | 4,485,121 | 12 | 2010-12-19T21:11:57Z | [
"python",
"python-3.x"
] | Just an http get request like file\_get\_contents in php, or something simple where I enter URL and it get contents to variable. | Use [urllib](http://docs.python.org/py3k/library/urllib.request.html):
```
from urllib.request import urlopen
html = urlopen("http://www.stackoverflow.com/").read().decode('utf-8')
print(html)
``` |
Python: How do you get an XML element's text content using xml.dom.minidom? | 4,485,132 | 9 | 2010-12-19T21:14:24Z | 4,485,159 | 21 | 2010-12-19T21:18:33Z | [
"python",
"xml",
"minidom"
] | I've called `elems = xmldoc.getElementsByTagName('myTagName')` on an XML object that I parsed as `minidom.parse(xmlObj)`. Now I'm trying to get the text content of this element, and although I spent a while looking through the dir() and trying things out, I haven't found the call yet. As an example of what I want to ac... | Try like this:
```
xmldoc.getElementsByTagName('myTagName')[0].firstChild.nodeValue
``` |
python 'is not' operator | 4,485,180 | 27 | 2010-12-19T21:22:51Z | 4,485,205 | 12 | 2010-12-19T21:28:30Z | [
"python"
] | I notice there is a comparison operator `is not`. Should I literally translate it into
```
!=
```
instead of
```
== not
``` | It's not relational comparison, it's identity. And it translates to `not (A is B)`. |
python 'is not' operator | 4,485,180 | 27 | 2010-12-19T21:22:51Z | 4,485,254 | 37 | 2010-12-19T21:37:41Z | [
"python"
] | I notice there is a comparison operator `is not`. Should I literally translate it into
```
!=
```
instead of
```
== not
``` | To expand on what Ignacio said:
`a == b` and `a != b` test whether two objects have the same *value*. You can override an object's `__eq__` and `__ne__` methods to determine what that means.
`a is b` and `a is not b` test whether two objects are the same thing. It's like doing `id(a) == id(b)` |
binary numbers? | 4,485,550 | 3 | 2010-12-19T22:45:48Z | 4,485,590 | 11 | 2010-12-19T22:52:46Z | [
"python",
"binary"
] | I am using the python shell to figure out how the print command works in python.
When I type in
> > > print 01
> > > 1
> > > print 010
> > > 8
> > > print 0100
> > > 64
> > > print 030
> > > 24
What's going on here? Is it just base 2? Why does the "one" in the second position print as 8? Shouldn't it ... | Starting a number with a zero marks it as octal in Python 2. This has been recognized as confusing, surprising and also inconsistent, as starting with 0x will mark it as hexadecimal. Therefore, in Python 3, starting with 0 is invalid, and you get octal by starting with 0o. You can also start with 0b to mark it as binar... |
Python Message Box Without huge library dependancy | 4,485,610 | 17 | 2010-12-19T22:58:36Z | 4,485,736 | 39 | 2010-12-19T23:24:28Z | [
"python",
"windows",
"windows-7"
] | Is there a messagebox class where I can just display a simple message box without a huge GUI library or any library upon program success or failure. (My script only does 1 thing).
Also, I only need it to run on Windows. | You can use the [ctypes](http://docs.python.org/library/ctypes.html) library, which comes installed with Python:
```
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxA
MessageBox(None, 'Hello', 'Window title', 0)
```
Above code is for Python 2.x. For Python 3.x, use `MessageBoxW` instead of `MessageBoxA`: Th... |
Ignoring -Inf values in arrays using numpy/scipy in Python | 4,485,779 | 9 | 2010-12-19T23:37:38Z | 4,485,849 | 8 | 2010-12-19T23:53:19Z | [
"python",
"numpy",
"scipy"
] | I have an NxM array in numpy that I would like to take the log of, and ignore entries that were negative prior to taking the log. When I take the log of negative entries, it returns -Inf, so I will have a matrix with some -Inf values as a result. I then want to sum over the columns of this matrix, but ignoring the -Inf... | Use [masked arrays](http://docs.scipy.org/doc/numpy/reference/maskedarray.html):
```
>>> a = numpy.array([2, 0, 1.5, -3])
>>> b = numpy.ma.log(a)
>>> b
masked_array(data = [0.69314718056 -- 0.405465108108 --],
mask = [False True False True],
fill_value = 1e+20)
>>> b.sum()
1.0986122886681096
``` |
Ignoring -Inf values in arrays using numpy/scipy in Python | 4,485,779 | 9 | 2010-12-19T23:37:38Z | 4,523,280 | 9 | 2010-12-23T23:41:32Z | [
"python",
"numpy",
"scipy"
] | I have an NxM array in numpy that I would like to take the log of, and ignore entries that were negative prior to taking the log. When I take the log of negative entries, it returns -Inf, so I will have a matrix with some -Inf values as a result. I then want to sum over the columns of this matrix, but ignoring the -Inf... | The easiest way to do this is to use [`numpy.ma.masked_invalid()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ma.masked_invalid.html):
```
a = numpy.log(numpy.arange(15))
a.sum()
# -inf
numpy.ma.masked_invalid(a).sum()
# 25.19122118273868
``` |
how to avoid substrings | 4,485,942 | 6 | 2010-12-20T00:21:35Z | 8,350,136 | 8 | 2011-12-02T00:04:04Z | [
"python",
"regex",
"string"
] | I currently process sections of a string like this:
```
for (i, j) in huge_list_of_indices:
process(huge_text_block[i:j])
```
I want to avoid the overhead of generating these temporary substrings. Any ideas? Perhaps a wrapper that somehow uses index offsets? This is currently my bottleneck.
Note that *process()*... | **I think what you are looking for are [buffers](http://docs.python.org/library/functions.html#buffer).**
The characteristic of buffers is that they "slice" an object supporting the buffer interface *without copying its content*, but essentially opening a "window" on the sliced object content. Some more technical expl... |
Running a Python Script using Cron? | 4,486,472 | 5 | 2010-12-20T02:37:16Z | 4,486,483 | 7 | 2010-12-20T02:41:56Z | [
"python",
"linux",
"cron",
"ubuntu-10.04"
] | I have a python script that I'd like to add to cron.
The script has +x permission on it.
How shall I add it to crontab? (say, I want it to run every minute).
Important: when I navigate (using the shell) to the script's folder, I cannot run it using "./script\_name.py"; it doesn't work. Yet, when I run it using "Pyth... | From `cron` you should be running the script as `script_name.py` and your script meets the following criteria:
* Executable bit is set
* The script's hash-bang is set correctly eg. `#!/usr/bin/env python`
* it is accessible from the `PATH`
+ e.g. place it in `/usr/local/bin/` or `/opt/local/bin/` (and they are acces... |
Python decorator with options | 4,486,499 | 6 | 2010-12-20T02:44:55Z | 4,486,616 | 14 | 2010-12-20T03:16:50Z | [
"python",
"arguments",
"decorator"
] | I have a module that has a function whose prototype is similar to that of the thread class.
```
def do(fn, argtuple=(), kwargdict={}, priority=0,
block=False, timeout=0, callback=None, daemon=False)
# do stuff
```
fn is a callable, and argtuple and kwargdict are positional and dictionary arguments th... | What the decorator does is that it takes the function as an argument and also returns a function, typically a new function that is created in the decorator.
That new function needs to take the same parameters as the function you decorate, and it also needs to call the original function.
Now, when you have a decorator... |
Python Script Not Working Via Cron? | 4,487,145 | 2 | 2010-12-20T05:26:27Z | 4,487,291 | 8 | 2010-12-20T06:02:51Z | [
"python",
"linux",
"ubuntu",
"cron"
] | I have a python script that runs another python script. that 'other script' (script being run) takes ~ 45[min] to complete.
When the 'execution' script is run from Ubuntu's shell, it all works perfectly.
I added an entry to cron to run the 'execution' python script. It seems to run at first, but the program is termin... | There are usually a few common misunderstandings made when trying to run things from cron.
* There is no session. If you have code that needs a session you have to do additional setup.
* The PATH and other environment variables are almost always different between your user session and the cron execution environment.
... |
How do I write a "tab" in Python? | 4,488,570 | 40 | 2010-12-20T10:04:11Z | 4,488,585 | 12 | 2010-12-20T10:05:54Z | [
"python"
] | Let's say I have a file. How do I write "hello" TAB "alex"? | You can use \t in a string literal:
`"hello\talex"` |
How do I write a "tab" in Python? | 4,488,570 | 40 | 2010-12-20T10:04:11Z | 4,488,586 | 8 | 2010-12-20T10:06:13Z | [
"python"
] | Let's say I have a file. How do I write "hello" TAB "alex"? | It's usually `\t` in command-line interfaces, which will convert the char `\t` into the whitespace tab character.
For example, `hello\talex` -> `hello--->alex`. |
How do I write a "tab" in Python? | 4,488,570 | 40 | 2010-12-20T10:04:11Z | 4,488,596 | 58 | 2010-12-20T10:07:35Z | [
"python"
] | Let's say I have a file. How do I write "hello" TAB "alex"? | This is the code:
```
f = open(filename, 'w')
f.write("hello\talex")
```
The \t inside the string is the escape sequence for the horizontal tabulation. |
Getting started with Django on Amazon Web Services | 4,488,793 | 21 | 2010-12-20T10:33:41Z | 4,489,468 | 8 | 2010-12-20T12:08:08Z | [
"python",
"django",
"amazon-ec2",
"amazon-web-services",
"amazon-ebs"
] | I'm starting to migrate a few applications to Amazon Web Services. My applications are Python/Django apps, running over MySQL.
I plan on using EC2 and EBS for starters.
I'm looking for a few things:
1. A good step-by-step tutorial explaining how to deploy Django on AWS. I've looked around, but most tutorials are fro... | There is nothing "special" with EC2 here. It just provides bare (or generally preconfigured from custom AMI) system instance - you have access to whole virtualized system, so you can safely break things on your own. Think about it as a specific VPS.
You have to prepare deployment by yourself, which is not so difficult... |
BeautifulSoup: get contents[] as a single string | 4,488,836 | 14 | 2010-12-20T10:39:33Z | 4,488,999 | 19 | 2010-12-20T11:01:45Z | [
"python",
"beautifulsoup"
] | Anyone know an elegant way to get the entire contents of a soup object as a single string?
At the moment I'm getting `contents`, which is of course a list, and then iterating over it:
```
notices = soup.find("div", {"class" : "middlecontent"})
con = ""
for content in notices.contents:
con += str(content)
print co... | What about `contents = str(notices)` ?
Or maybe `contents = notices.renderContents()`, which will hide the div tag. |
How to get an HTML file using Python? | 4,489,550 | 8 | 2010-12-20T12:20:12Z | 4,492,108 | 14 | 2010-12-20T17:21:26Z | [
"python",
"html",
"webclient"
] | I am not very familiar with Python. I am trying to extract the artist names (for a start :)) from the following page: <http://www.infolanka.com/miyuru_gee/art/art.html>.
How do I retrieve the page? My two main concerns are; what functions to use and how to filter out useless links from the page? | Example using urlib and lxml.html:
```
import urllib
from lxml import html
url = "http://www.infolanka.com/miyuru_gee/art/art.html"
page = html.fromstring(urllib.urlopen(url).read())
for link in page.xpath("//a"):
print "Name", link.text, "URL", link.get("href")
output >>
[('Aathma Liyanage', 'athma.html'),... |
Automatic class decoration (or validation) upon derivation | 4,490,053 | 4 | 2010-12-20T13:24:42Z | 4,490,128 | 8 | 2010-12-20T13:36:33Z | [
"python",
"class",
"decorator",
"metaclass"
] | I have a base class from which I derive multiple subclasses.
Each subclass defines class constants, and I wish to enforce certain limitations on them.
For example:
```
class Base(object):
# define these in your sub-class, and make sure (NOM % DENOM == 0)
NOMINATOR = None
DENOMINATOR = None
class Subclas... | Ok, funny. I was thinking about it for a while, but only after posting the question - specifically when choosing tags, and adding "metaclass" there - did I realize I may have an answer myself.
So, submitted for review and future knowledge, here goes:
```
class Base_Metaclass(type):
def __new__(meta, classname, b... |
Django with PyPy | 4,490,366 | 15 | 2010-12-20T14:06:17Z | 4,490,438 | 22 | 2010-12-20T14:17:04Z | [
"python",
"django",
"pypy"
] | Are there some reasons of using Django with PyPy?
I read PyPy increases perfomance. | Unlikely. A Django application is almost always I/O-bound, usually because of the database connection. PyPy wouldn't help with that at all, even if it was purely compatible (which I'm not sure it is). |
Django with PyPy | 4,490,366 | 15 | 2010-12-20T14:06:17Z | 4,490,455 | 10 | 2010-12-20T14:19:28Z | [
"python",
"django",
"pypy"
] | Are there some reasons of using Django with PyPy?
I read PyPy increases perfomance. | Depends.
PyPy does improve performance for all benchmarks that are in the PyPy's benchmark suite. This is only template rendering for now, but noone submitted anything else. It's however safe to assume that performance critical code will be faster (especially after some tuning).
Compatibility-wise databases are a bit... |
Dictionary in python with order I set at start | 4,490,855 | 7 | 2010-12-20T15:05:37Z | 4,490,902 | 15 | 2010-12-20T15:10:58Z | [
"python",
"collections",
"dictionary"
] | I'm making dictionary:
```
d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'
```
But when I display it I saw that this dict is reversed.
```
print(d)
{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}
```
How to reverse it back?
Or if it is true that dictionary is not... | Dictionary are unordered (the order is deterministic, but depends on a handful of factors you don't even think of and shouldn't care about - hash of the keys, order of insertion, collisions, etc). In Python 2.7+, use `collections.OrderedDict`. If you must use an older version, there are various implementations google c... |
Dictionary in python with order I set at start | 4,490,855 | 7 | 2010-12-20T15:05:37Z | 4,490,970 | 12 | 2010-12-20T15:17:26Z | [
"python",
"collections",
"dictionary"
] | I'm making dictionary:
```
d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'
```
But when I display it I saw that this dict is reversed.
```
print(d)
{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}
```
How to reverse it back?
Or if it is true that dictionary is not... | ```
from collections import OrderedDict
d = OrderedDict()
d["server"] = "mpilgrim"
d["database"] = "master"
d['mynewkey'] = 'mynewvalue'
print(d)
OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
``` |
How to convert string to byte arrays? | 4,490,901 | 17 | 2010-12-20T15:10:56Z | 4,491,094 | 28 | 2010-12-20T15:31:52Z | [
"python"
] | How can I convert a string to its byte value? I have a string `"hello"` and I want to change is to something like `"/x68..."`. | Python 2.6 and later have a [bytearray](http://docs.python.org/library/functions.html#bytearray) type which may be what you're looking for. Unlike strings, it is mutable, i.e., you can change individual bytes "in place" rather than having to create a whole new string. It has a nice mix of the features of lists and stri... |
How to convert string to byte arrays? | 4,490,901 | 17 | 2010-12-20T15:10:56Z | 4,491,615 | 8 | 2010-12-20T16:27:28Z | [
"python"
] | How can I convert a string to its byte value? I have a string `"hello"` and I want to change is to something like `"/x68..."`. | If you want to get hexadecimal string representation you could do:
```
"hello".encode("hex") # '68656c6c6f'
```
And to meet your reference representation (don't take it seriously, guess this is ***not what you really want***):
```
"".join(["/x%02x" % ord(c) for c in "hello"]) # '/x68/x65/x6c/x6c/x6f'
``` |
How to convert string to byte arrays? | 4,490,901 | 17 | 2010-12-20T15:10:56Z | 4,492,854 | 23 | 2010-12-20T18:57:29Z | [
"python"
] | How can I convert a string to its byte value? I have a string `"hello"` and I want to change is to something like `"/x68..."`. | Perhaps you want this (Python 2):
```
>>> map(ord,'hello')
[104, 101, 108, 108, 111]
```
For a Unicode string this would return Unicode code points:
```
>>> map(ord,u'Hello, 马å
')
[72, 101, 108, 108, 111, 44, 32, 39532, 20811]
```
But encode it to get byte values for the encoding:
```
>>> map(ord,u'Hello, 马å
... |
Google search with Python | 4,490,983 | 5 | 2010-12-20T15:18:49Z | 4,491,058 | 13 | 2010-12-20T15:27:56Z | [
"python",
"ms-word",
"google-api"
] | How do you perform a search query on Google using Python? How do you store the search results in a Microsoft Word document? | Use the [provided API](http://code.google.com/apis/customsearch/v1/overview.html). First register to get an API key [here](https://code.google.com/apis/console). Then you can use Python's `urllib2` package to fetch the results, e.g.
```
import urllib2
import json
import pprint
data = urllib2.urlopen('https://www.googl... |
in Python, how to separate Local Hard Drives from Network and Floppy in Windows? | 4,491,601 | 7 | 2010-12-20T16:26:22Z | 4,492,037 | 9 | 2010-12-20T17:11:53Z | [
"python",
"winapi"
] | I've been looking for this info for awhile, and I have a number of ways to retrieve a list of local drives under Windows. Here are two examples:
```
print win32api.GetLogicalDriveStrings().split("\x00")
```
and
```
def getDriveLetters(self):
self.drvs = []
n_drives = win32api.GetLogicalDrives()
for i in ... | You can try the win32 [GetDriveType](http://msdn.microsoft.com/en-us/library/aa364939%28v=vs.85%29.aspx) function.
```
import win32file
>>> win32file.GetDriveType("C:/") == win32file.DRIVE_FIXED ##hardrive
True
>>> win32file.GetDriveType("Z:/") == win32file.DRIVE_FIXED ##network
False
>>> win32file.GetDriveType("D:/")... |
Is there a built-in function to sort and filter a python list in one step? | 4,492,254 | 4 | 2010-12-20T17:39:20Z | 4,492,272 | 16 | 2010-12-20T17:41:52Z | [
"python"
] | Given a directory of files all with numeric names, I currently sort and filter the directory list in two steps.
```
#files = os.listdir(path)
files = ["0", "1", "10", "5", "2", "11", "4", "15", "18", "14", "7", "8", "9"]
firstFile = 5
lastFile = 15
#filter out any files that are not in the desired range
files = fi... | Those are orthogonal tasks, I don't think they should be mixed. Besides, it's easy to filter and sort separately in one line with generator expressions
```
files = sorted( (f for f in files if firstFile <= int(f) < lastFile), key=int)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.