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 |
|---|---|---|---|---|---|---|---|---|---|
Can python distutils compile CUDA code? | 10,034,325 | 6 | 2012-04-05T18:54:12Z | 13,300,714 | 9 | 2012-11-09T01:13:26Z | [
"python",
"cuda"
] | I have CUDA code which I want to build a dynamic library to Python using distutils. But it seems distutils doesn't recognize ".cu" file even if the "nvcc" compiler is installed. Not sure how to get it done. | Distutils is not able to compile CUDA by default, because it doesn't support using multiple compilers simultaneously. By default, it sets to compiler just based on your platform, not on the type of source code you have.
I have an example project on github that contains some monkey patches into distutils to hack in sup... |
Truncating a string in python | 10,034,377 | 10 | 2012-04-05T18:57:48Z | 10,034,414 | 14 | 2012-04-05T19:00:20Z | [
"python",
"truncate"
] | Someone gave me a syntax to truncate a string as follows:
```
string = "My Text String"
print string [0:3] # This is just an example
```
I'm not sure what this is called (the string[0:3] syntax), so I've had a hard time trying to look it up on the internet and understand how it works. So far I think it works like th... | It's called a slice:
> **s[i:j:k]**
>
> The slice of s from i to j is defined as the sequence of items with
> index k such that i <= k < j. If i or j is greater than len(s), use
> len(s). If i is omitted or None, use 0. If j is omitted or None, use
> len(s). If i is greater than or equal to j, the slice is empty.
[so... |
Truncating a string in python | 10,034,377 | 10 | 2012-04-05T18:57:48Z | 10,034,876 | 7 | 2012-04-05T19:34:35Z | [
"python",
"truncate"
] | Someone gave me a syntax to truncate a string as follows:
```
string = "My Text String"
print string [0:3] # This is just an example
```
I'm not sure what this is called (the string[0:3] syntax), so I've had a hard time trying to look it up on the internet and understand how it works. So far I think it works like th... | As @Uku and @thebjorn said its called [Slicing](http://docs.python.org/tutorial/introduction.html#strings)
But one easier way to think is to consider a String like a list, for example you can do:
```
text = 'Any String'
for letter in text:
print letter
```
And the same if you want to get a specific letter inside... |
removing trailing empty elements in Python | 10,034,917 | 6 | 2012-04-05T19:38:50Z | 10,034,949 | 9 | 2012-04-05T19:41:48Z | [
"python",
"list"
] | Is there an elegant pythonian way of removing trailing empty elements from a list. A sort of list.rstrip(None). So
```
[1, 2, 3, None, 4, None, None]
```
should result in
```
[1, 2, 3, None, 4]
```
I guess this could be generalized to removing trailing elements of any particular value.
---
**UPDATE**: I should ha... | **Edited**: To use pop() instead of slicing the list, as commenters have correctly suggested.
I don't know if there's a more pythonic way, but this works:
```
my_list = [1, 2, 3, None, 4, None, None]
while not my_list[-1]:
my_list.pop()
print my_list
>>>[1, 2, 3, None, 4]
```
**Edit**: As @DSM points out, if you... |
removing trailing empty elements in Python | 10,034,917 | 6 | 2012-04-05T19:38:50Z | 10,034,995 | 7 | 2012-04-05T19:45:02Z | [
"python",
"list"
] | Is there an elegant pythonian way of removing trailing empty elements from a list. A sort of list.rstrip(None). So
```
[1, 2, 3, None, 4, None, None]
```
should result in
```
[1, 2, 3, None, 4]
```
I guess this could be generalized to removing trailing elements of any particular value.
---
**UPDATE**: I should ha... | The following explicitly checks for `None` elements:
```
while l and l[-1] is None:
l.pop()
```
It can be generalized as follows:
```
f = lambda x: x is None
while l and f(l[-1]):
l.pop()
```
You can now define different functions for `f` to check for other conditions. |
How can I make a blank subplot in matplotlib? | 10,035,446 | 25 | 2012-04-05T20:22:18Z | 10,035,974 | 40 | 2012-04-05T21:03:32Z | [
"python",
"matplotlib",
"axes",
"subplot"
] | I am making a group of subplot (say, 3 x 2) in matplotlib, but I have fewer than 6 datasets. How can I make the remaining subplot blank?
The arrangement looks like this:
```
+----+----+
| 0,0| 0,1|
+----+----+
| 1,0| 1,1|
+----+----+
| 2,0| 2,1|
+----+----+
```
This may go on for several pages, but on the final page... | You could always hide the axes which you do not need. For example, the following code turns of the 6-th axes completely:
```
import matplotlib.pyplot as plt
hf, ha = plt.subplots(3,2)
ha[-1, -1].axis('off')
plt.show()
```
and results in the following figure:
 in matplotlib, but I have fewer than 6 datasets. How can I make the remaining subplot blank?
The arrangement looks like this:
```
+----+----+
| 0,0| 0,1|
+----+----+
| 1,0| 1,1|
+----+----+
| 2,0| 2,1|
+----+----+
```
This may go on for several pages, but on the final page... | A *much* improved [subplot interface](http://matplotlib.org/users/gridspec.html) has been added to matplotlib since this question was first asked. Here you can create exactly the subplots you need without hiding the extras. In addition, the subplots can span additional rows or columns.
```
import pylab as plt
ax1 = p... |
What causes a Python segmentation fault? | 10,035,541 | 32 | 2012-04-05T20:28:56Z | 10,035,594 | 36 | 2012-04-05T20:32:53Z | [
"python",
"segmentation-fault",
"large-data"
] | I am implementing Kosaraju's Strong Connected Component(SCC) graph search algorithm in Python.
The program runs great on small data set, but when I run it on a super-large graph (more than 800,000 nodes), it says "Segmentation Fault".
What might be the cause of it? Thank you!
---
Additional Info:
First I got this E... | This happens when a python *extension* (written in C) tries to access a memory beyond reach.
You can trace it in following ways.
* Add [`sys.settrace`](http://docs.python.org/py3k/library/sys.html#sys.settrace) at the very first line of the code.
* Use `gdb` as described by *Mark* in [this answer](http://stackoverflo... |
What causes a Python segmentation fault? | 10,035,541 | 32 | 2012-04-05T20:28:56Z | 11,368,425 | 23 | 2012-07-06T19:19:45Z | [
"python",
"segmentation-fault",
"large-data"
] | I am implementing Kosaraju's Strong Connected Component(SCC) graph search algorithm in Python.
The program runs great on small data set, but when I run it on a super-large graph (more than 800,000 nodes), it says "Segmentation Fault".
What might be the cause of it? Thank you!
---
Additional Info:
First I got this E... | I understand you've solved your issue, but for others reading this thread, here is the answer: you have to increase the stack that your operating system allocates for the python process.
The way to do it, is operating system dependant. In linux, you can check with the command `ulimit -s` your current value and you can... |
Elegant Python code for Integer Partitioning | 10,035,752 | 11 | 2012-04-05T20:45:38Z | 10,036,764 | 23 | 2012-04-05T22:16:12Z | [
"python",
"algorithm"
] | I tried to write code to solve the standard Integer Partition problem ([Wikipedia](http://en.wikipedia.org/wiki/Partition_%28number_theory%29)). The code I wrote was a mess. I need an elegant solution to solve the problem, because I want to improve my coding style. This is not a homework question. | ```
>>> def partition(number):
... answer = set()
... answer.add((number, ))
... for x in range(1, number):
... for y in partition(number - x):
... answer.add(tuple(sorted((x, ) + y)))
... return answer
...
>>> partition(4)
set([(1, 3), (2, 2), (1, 1, 2), (1, 1, 1, 1), (4,)])
```
I... |
Extracting a number from a 1-word string | 10,037,279 | 5 | 2012-04-05T23:11:12Z | 10,037,368 | 11 | 2012-04-05T23:19:52Z | [
"python",
"python-3.x"
] | In this program I am trying to make, I have an expression (such as "I=23mm", or "H=4V") and I am trying to extract the 23 (or the 4) out of it, so that I can turn it into an integer.
The problem I keep running into is that since the expression I am trying to take the numbers out of is 1 word, I cannot use split() or a... | ```
>>> import re
>>> I = "I=2.7A"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'2.7'
>>> I = "A=3V"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'3'
>>> I = "I=2.723A"
>>> s = re.search(r"\d+(\.\d+)?", I)
>>> s.group(0)
'2.723'
``` |
Remove class attribute from HTML using Python and lxml | 10,037,289 | 10 | 2012-04-05T23:12:12Z | 10,037,426 | 11 | 2012-04-05T23:27:48Z | [
"python",
"html",
"lxml"
] | # Question
How do I remove class attributes from html using python and lxml?
## Example
I have:
```
<p class="DumbClass">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
```
I want:
```
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
```
## What I've tried so far
I've checked out [lx... | I can't test this at the moment but this appears to be the general idea
```
for tag in node.xpath('//*[@class]'):
tag.attrib.pop('class')
``` |
Python introspection: access function name and docstring inside function definition | 10,037,825 | 13 | 2012-04-06T00:31:22Z | 10,037,861 | 12 | 2012-04-06T00:36:21Z | [
"python",
"introspection"
] | Consider the following python code:
```
def function():
"Docstring"
name = ???
doc = ???
return name, doc
>>> function()
"function", "Docstring"
```
What do I need to replace the question marks with so that I get the name and the docstring of the function from inside the same function?
EDIT:
Most ... | This is not possible to do cleanly in a consistent way because names can be changed and reassigned.
However, you can use this so long as the function isn't renamed or decorated.
```
>>> def test():
... """test"""
... doc = test.__doc__
... name = test.__name__
... return doc, name
...
>>> test()
('te... |
Python/iptables: Capturing all UDP packets and their original destination | 10,038,727 | 9 | 2012-04-06T03:16:49Z | 10,084,749 | 8 | 2012-04-10T07:25:40Z | [
"python",
"sockets",
"udp",
"iptables",
"packet-capture"
] | I am trying to write an `iptables` rule that will redirect all outgoing UDP packets to a local socket, but I also need the destination information. I started out with
```
sudo iptables -t nat -A sshuttle-12300 -j RETURN --dest 127.0.0.0/8 -p udp
sudo iptables -t nat -A sshuttle-12300 -j REDIRECT --dest 0.0.0.0/0 -... | I found your question interesting.
The following solution is based on marking the UDP traffic generated by the host and re-routing it back to the local host application. At the application, a UDP socket should be used to read the data, even one that is not destined for the host itself (see below how).
# Networking se... |
Easiest way to initialize a large number of variables | 10,039,306 | 3 | 2012-04-06T04:58:10Z | 10,039,323 | 12 | 2012-04-06T05:00:33Z | [
"python",
"initialization",
"iterable-unpacking"
] | Assume you are given a large number of variables that need to be initialized to None. A naive way to do this would be to count the number of variables on the left, and create a list of the same size on the right:
```
a, b, c, d, e, f, g, h, i, j = [None]*10
```
Is there a way to do this without having to count the va... | ```
a = b = c = d = e = f = g = h = i = j = None
```
Note: don't use this for mutable types. If you're curious why, this demonstrates:
```
>>> a = b = []
>>> a.append(1)
>>> a
[1]
>>> b
[1]
``` |
Refer to class variable in another class variable definition | 10,039,422 | 3 | 2012-04-06T05:15:15Z | 10,039,459 | 8 | 2012-04-06T05:21:06Z | [
"python"
] | ```
class SomeClass:
SOME_CONST = "hello"
SOME_OTHER_CONST = SomeClass.SOME_CONST + " world"
```
This doesn't work.
> NameError: name 'SomeClass' is not defined
Is there any way to refer to the class within the class? | You don't need the class name
```
class SomeClass:
SOME_CONST = "hello"
SOME_OTHER_CONST = SOME_CONST + " world"
``` |
Tkinter - RuntimeError: maximum recursion depth exceeded | 10,039,485 | 3 | 2012-04-06T05:24:01Z | 10,039,671 | 7 | 2012-04-06T05:51:21Z | [
"python",
"tkinter"
] | I started programming in Python on Monday. I have enjoyed learning it. But I am stuck trying to understand how to avoid recursion when switching between tkinter menus! I am sure this is a very basic question, and I appreciate you tolerating my ignorance on this subject, but I have been unable to find an answer elsewher... | Only one `mainloop()` is needed to handle a tkinter GUI.
With that said, I think you just need an example of the class structure:
```
from tkinter import Tk,Button
class Application(Tk):
def say_hi(self):
print('Hello world?!')
def close_app(self):
self.destroy()
def create_Widgets(sel... |
How to do a less than or equal to filter in Django queryset? | 10,040,143 | 62 | 2012-04-06T06:49:32Z | 10,040,165 | 119 | 2012-04-06T06:52:03Z | [
"python",
"django",
"django-queryset"
] | I am attempting to filter users by a custom field in each users profile called profile. This field is called level and is an integer between 0-3.
If I filter using equals, I get a list of users with the chosen level as expected:
```
user_list = User.objects.filter(userprofile__level = 0)
```
When I try to filter usi... | Less than or equal:
```
User.objects.filter(userprofile__level__lte=0)
```
Greater than or equal:
```
User.objects.filter(userprofile__level__gte=0)
```
Likewise, `lt` for less than and `gt` for greater than. You can find them all [in the documentation](https://docs.djangoproject.com/en/dev/ref/models/querysets/). |
Override a form in Django admin | 10,040,442 | 17 | 2012-04-06T07:23:19Z | 10,041,463 | 29 | 2012-04-06T09:16:10Z | [
"python",
"django",
"django-models",
"django-admin",
"django-views"
] | In Django admin I want to override an implement my own form for a model (e.g. Invoice model).
I want the invoice form to have autofill fields for customer name, product name and want to do custom validation (such as credit limit for a customer). How can i override the default form provided by Django admin and implemen... | You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form> and <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin>
It'... |
Override a form in Django admin | 10,040,442 | 17 | 2012-04-06T07:23:19Z | 19,014,382 | 11 | 2013-09-25T20:14:21Z | [
"python",
"django",
"django-models",
"django-admin",
"django-views"
] | In Django admin I want to override an implement my own form for a model (e.g. Invoice model).
I want the invoice form to have autofill fields for customer name, product name and want to do custom validation (such as credit limit for a customer). How can i override the default form provided by Django admin and implemen... | How to override a form in the django admin according to the [docs](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form):
```
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
m... |
Iteratively parse a large XML file without using the DOM approach | 10,040,444 | 2 | 2012-04-06T07:23:35Z | 10,040,590 | 7 | 2012-04-06T07:39:58Z | [
"python",
"xml",
"xml-parsing",
"lxml"
] | I have an xml file
```
<temp>
<email id="1" Body="abc"/>
<email id="2" Body="fre"/>
.
.
<email id="998349883487454359203" Body="hi"/>
</temp>
```
I want to read the xml file for each email tag. That is, at a time I want to read email id=1..extract body from it, the read email id=2...and extract body from it... | An example for iterparse:
```
import cStringIO
from xml.etree.ElementTree import iterparse
fakefile = cStringIO.StringIO("""<temp>
<email id="1" Body="abc"/>
<email id="2" Body="fre"/>
<email id="998349883487454359203" Body="hi"/>
</temp>
""")
for _, elem in iterparse(fakefile):
if elem.tag == 'email':
... |
How to profile Google App Engine python27 runtime (not python) | 10,040,783 | 7 | 2012-04-06T08:02:24Z | 10,043,813 | 14 | 2012-04-06T12:59:22Z | [
"python",
"google-app-engine",
"profile",
"python-2.7"
] | How to **profile** python code under **Google App Engine** runtime **python27**?
In runtime **python** it was done by this code - [python runtime](https://developers.google.com/appengine/kb/commontasks#profiling):
```
from google.appengine.ext import webapp
class PageHandler(webapp.RequestHandler):
def get(self):
... | You can profile a WSGI app using WSGI middleware by inserting in your appengine\_config.py:
```
import cProfile
import cStringIO
import logging
import pstats
def webapp_add_wsgi_middleware(app):
def profiling_wrapper(environ, start_response):
profile = cProfile.Profile()
response = profile.runcall(app, env... |
How to clear cache for specific model in NDB | 10,041,248 | 2 | 2012-04-06T08:55:55Z | 10,051,668 | 10 | 2012-04-07T04:10:51Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I am in the process of transitioning to the NDB, and I am using two model sets: one based in plain old `google.appengine.ext.db` and one based on new fancy `google.appengine.ext.ndb`.
I would like to use NDB-based models for read-only and retain the caching that's built into NDB, while being able to store changes usin... | I would recommend just disabling the cache for those model classes that you have in duplicate; better be safe than sorry. This is easily done by putting
```
_use_memcache = False
_use_cache = False
```
inside each ndb.Model subclass (i.e. before or after the property declarations). Docs for this are here: <http... |
How to make pylab.savefig() save image for 'maximized' window instead of default size | 10,041,627 | 24 | 2012-04-06T09:31:53Z | 10,041,681 | 11 | 2012-04-06T09:36:52Z | [
"python",
"matplotlib"
] | I am using pylab in matplotlib to create a plot and save the plot to an image file. However, when I save the image using `pylab.savefig( image_name )`, I find that the **SIZE** image saved is the same as the image that is shown when I use `pylab.show()`.
As it happens, I have a lot of data in the plot and when I am us... | You set the size on initialization:
```
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!
```
**Edit**:
If the problem is with x-axis ticks - You can set them "manually":
```
fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here
```
... |
How to make pylab.savefig() save image for 'maximized' window instead of default size | 10,041,627 | 24 | 2012-04-06T09:31:53Z | 10,262,161 | 24 | 2012-04-21T19:16:04Z | [
"python",
"matplotlib"
] | I am using pylab in matplotlib to create a plot and save the plot to an image file. However, when I save the image using `pylab.savefig( image_name )`, I find that the **SIZE** image saved is the same as the image that is shown when I use `pylab.show()`.
As it happens, I have a lot of data in the plot and when I am us... | There are two major options in matplotlib (pylab) to control the image size:
1. You can set the size of the resulting image in inches
2. You can define the DPI (dots per inch) for output file (basically, it is a resolution)
Normally, you would like to do both, because this way you will have **full control** over the ... |
Python -subtraction of value within a list | 10,042,851 | 6 | 2012-04-06T11:31:51Z | 10,042,916 | 7 | 2012-04-06T11:37:14Z | [
"python",
"list",
"nested-lists"
] | I'm new to Python and I'm having difficulties with lists. I wish to subtract 1 from all the values within the list except for values 10.5. The code below gives an error that the x3 list assignment index is out of range. The code so far:
```
x2=[10.5, -6.36, 11.56, 19.06, -4.37, 26.56, 9.38, -33.12, -8.44, 0.31, -13.44... | Try the following:
```
x3 = [((x - 1) if x != 10.5 else x) for x in x2]
``` |
Any reason not to use '+' to concatenate two strings? | 10,043,636 | 64 | 2012-04-06T12:42:33Z | 10,043,677 | 33 | 2012-04-06T12:46:04Z | [
"python",
"string-concatenation",
"anti-patterns"
] | A common antipattern in Python is to concatenate a sequence of strings using `+` in a loop. This is bad because the Python interpreter has to create a new string object for each iteration, and it ends up taking quadratic time. (Recent versions of CPython can apparently optimize this in some cases, but other implementat... | Plus operator is perfectly fine solution to concatenate **two** Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.
`''.join([a, b, c])` trick is a performance optimization. |
Any reason not to use '+' to concatenate two strings? | 10,043,636 | 64 | 2012-04-06T12:42:33Z | 10,043,957 | 51 | 2012-04-06T13:11:17Z | [
"python",
"string-concatenation",
"anti-patterns"
] | A common antipattern in Python is to concatenate a sequence of strings using `+` in a loop. This is bad because the Python interpreter has to create a new string object for each iteration, and it ends up taking quadratic time. (Recent versions of CPython can apparently optimize this in some cases, but other implementat... | There is nothing wrong in concatenating *two* strings with `+`. Indeed it's easier to read than `''.join([a, b])`.
You are right though that concatenating more than 2 strings with `+` is an O(n^2) operation (compared to O(n) for `join`) and thus becomes inefficient. However this has not to do with using a loop. Even `... |
class Classname versus class Classname(object) | 10,043,963 | 3 | 2012-04-06T13:12:10Z | 10,044,136 | 8 | 2012-04-06T13:27:31Z | [
"python",
"class",
"object"
] | What is the difference between:
```
class ClassName(object):
pass
```
and
```
class ClassName:
pass
```
When I call the help function of the module of those class you can read `____builtin____.object` for the first case just under the CLASS title of help. For the second case it just shows the class name. Is... | When you inherit from "object" you class is a "new style" class - that was implemented back in Python 2.2 (around 2001) - The non inheriting from "object" case creates an "old style" class, that was actually maintained only for backwards compatibility.
The great benefit of "new style" classes is the unification of typ... |
How to generate a temporary url to upload file to Amazon S3 with boto library? | 10,044,151 | 17 | 2012-04-06T13:28:31Z | 10,046,634 | 37 | 2012-04-06T17:00:34Z | [
"python",
"amazon-s3",
"amazon-web-services",
"boto"
] | I knew how to download file in this way - key.generate\_url(3600).
But when I tried to upload : key.generate\_url(3600, method='PUT'), the url didn't work. I was told:
"The request signature we calculated does not match the signature you provided. Check your key and signing method."
I cannot found example code in bot... | I found some time to experiment with this and here's what I found.
```
>>> import boto
>>> c =boto.connect_s3()
>>> fp = open('myfiletoupload.txt')
>>> content_length = len(fp.read())
>>> c.generate_url(300, 'PUT', 'test-1332789015', 'foobar', headers={'Content-Length': str(content_length)}, force_http=True)
'http://t... |
How to generate a temporary url to upload file to Amazon S3 with boto library? | 10,044,151 | 17 | 2012-04-06T13:28:31Z | 24,830,602 | 9 | 2014-07-18T17:23:47Z | [
"python",
"amazon-s3",
"amazon-web-services",
"boto"
] | I knew how to download file in this way - key.generate\_url(3600).
But when I tried to upload : key.generate\_url(3600, method='PUT'), the url didn't work. I was told:
"The request signature we calculated does not match the signature you provided. Check your key and signing method."
I cannot found example code in bot... | This is a follow up to garnaat's answer from Apr 6 '12.
I am generating a signed URL server side, where I have credentials, and I pass it to a client such that a client can directly upload content. I trust the client far enough to allow it to upload arbitrary sized files, but not enough to give it security tokens. I w... |
_func() , any functional use of underscore? (Python) | 10,044,918 | 3 | 2012-04-06T14:31:29Z | 10,044,992 | 11 | 2012-04-06T14:38:04Z | [
"python",
"function"
] | I created two modules, one with
```
def _func():
print "hi"
```
and another
```
def func():
print "hi"
```
When I use the help function on the module including the first function, the help module doesn't display this function. As opposed the second example where this function shows in the help output. Is th... | Yes, there *is* an (admittedly subtle) difference functionality-wise. Let's assume you have a module **A.py**:
```
foo = 1
_bar = 2
```
Observe:
```
>>> from A import *
>>> foo
1
>>> _bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_bar' is not defined
```
The default b... |
Pickling cv2.KeyPoint causes PicklingError | 10,045,363 | 12 | 2012-04-06T15:07:10Z | 11,985,056 | 11 | 2012-08-16T10:15:11Z | [
"python",
"opencv"
] | I want to search surfs in all images in a given directory and save their keypoints and descriptors for future use. I decided to use pickle as shown below:
```
#!/usr/bin/env python
import os
import pickle
import cv2
class Frame:
def __init__(self, filename):
surf = cv2.SURF(500, 4, 2, True)
self.filename = ... | The problem is that you cannot dump cv2.KeyPoint to a pickle file. I had the same issue, and managed to work around it by essentially serializing and deserializing the keypoints myself before dumping them with Pickle.
So represent every keypoint and its descriptor with a tuple:
```
temp = (point.pt, point.size, point... |
Hashing an immutable dictionary in Python | 10,045,562 | 13 | 2012-04-06T15:25:18Z | 10,045,717 | 11 | 2012-04-06T15:37:47Z | [
"python",
"dictionary",
"hash",
"immutability",
"python-3.2"
] | **Short version:** What's the best hashing algorithm for a multiset implemented as a dictionary of unordered items?
I'm trying to hash an immutable multiset (which is a bag or multiset in other languages: like a mathematical set except that it can hold more than one of each element) implemented as a dictionary. I've c... | Since the dictionary is immutable, you can create the hash when the dictionary is created and return it directly. My suggestion would be to create a [`frozenset`](http://docs.python.org/library/stdtypes.html#frozenset) from `items` (in 3+; `iteritems` in 2.7), hash it, and store the hash.
To provide an explicit exampl... |
How to shade region under the curve in matplotlib | 10,046,262 | 15 | 2012-04-06T16:25:52Z | 10,046,303 | 13 | 2012-04-06T16:29:07Z | [
"python",
"numpy",
"matplotlib"
] | I want to use matplotlib to illustrate the definite integral between two regions: x\_0, and x\_1.
How can I shade a region under a curve in matplotlib from x=-1, to x=1 given the following plot
```
import numpy as np
from matplotlib import pyplot as plt
def f(t):
return t * t
t = np.arange(-4,4,1/40.)
plt.plot(t... | Check out [`fill`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill). Here's an [example](http://scipy-cookbook.readthedocs.org/items/Matplotlib_SigmoidalFunctions.html) on filling a constrained region. |
Write xml utf-8 file with utf-8 data with ElementTree | 10,046,755 | 8 | 2012-04-06T17:12:12Z | 10,048,713 | 13 | 2012-04-06T20:09:16Z | [
"python",
"elementtree"
] | I'm trying to write an xml file with utf-8 encoded data using ElementTree like this:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import codecs
... | `codecs.open` expects Unicode strings to be written to the file object and it will handle encoding to UTF-8. ElementTree's `write` encodes the Unicode strings to UTF-8 byte strings before sending them to the file object. Since the file object wants Unicode strings, it is coercing the byte string back to Unicode using t... |
Is it possible to use the GPU to accelerate hashing in Python? | 10,047,601 | 5 | 2012-04-06T18:26:58Z | 10,048,545 | 12 | 2012-04-06T19:52:39Z | [
"python",
"hash",
"gpu"
] | I recently read Jeff's blog post entitled [Speed Hashing](http://www.codinghorror.com/blog/2012/04/speed-hashing.html), where amongst other things he mentions that you can hash things really fast by harnessing the power of your GPU.
I was wondering whether or not it was possible to harness the power of the GPU to hash... | There are two obstacles:
1. Writing a program to execute on the GPU. AFAIK, there is no mechanism currently available to convert an Python program to the code executed by a GPU. So unless you can find what you need (which might be possible, as it looks like a reasonably common use case), then you are going to have to ... |
How to pickle a python function with its dependencies? | 10,048,061 | 7 | 2012-04-06T19:07:50Z | 16,891,169 | 16 | 2013-06-03T06:35:41Z | [
"python",
"function",
"pickle"
] | As a follow up to this question:
[Is there an easy way to pickle a python function (or otherwise serialize its code)?](http://stackoverflow.com/questions/1253528/is-there-an-easy-way-to-pickle-a-python-function-or-otherwise-serialize-its-cod)
I would like to see an example of this bullet from the above post:
"If the ... | The cloud package does this -- just 'pip install cloud' and then:
```
import cloud, pickle
def foo(x):
return x*3
def bar(z):
return foo(z)+1
x = cloud.serialization.cloudpickle.dumps(bar)
del foo
del bar
f = pickle.loads(x)
print f(3) # displays "10"
```
In other words, just call cloudpickle.dump() or cl... |
What is the most pythonic way to pop a random element from a list? | 10,048,069 | 30 | 2012-04-06T19:08:55Z | 10,048,122 | 21 | 2012-04-06T19:13:22Z | [
"python",
"list",
"random",
"pop"
] | Say I have a list `x` with unkown length from which I want to randomly pop one element so that the list does not contain the element afterwards. What is the most pythonic way to do this?
I can do it using a rather unhandy combincation of `pop`, `random.randint`, and `len` and would like to see shorter or nicer solutio... | You won't get much better than that, but here is a slight improvement:
```
x.pop(random.randrange(len(x)))
```
Documentation on [`random.randrange()`](http://docs.python.org/library/random.html#random.randrange):
> random.randrange([start], stop[, step])
> Return a randomly selected element from `range(start, stop... |
What is the most pythonic way to pop a random element from a list? | 10,048,069 | 30 | 2012-04-06T19:08:55Z | 10,048,168 | 35 | 2012-04-06T19:17:22Z | [
"python",
"list",
"random",
"pop"
] | Say I have a list `x` with unkown length from which I want to randomly pop one element so that the list does not contain the element afterwards. What is the most pythonic way to do this?
I can do it using a rather unhandy combincation of `pop`, `random.randint`, and `len` and would like to see shorter or nicer solutio... | What you seem to be up to doesn't look very Pythonic in the first place. You shouldn't remove stuff from the middle of a list, because lists are implemented as arrays in all Python implementations I know of, so this is an `O(n)` operation.
So what you can do if you don't need access to the remaining elements is just s... |
What is the most pythonic way to pop a random element from a list? | 10,048,069 | 30 | 2012-04-06T19:08:55Z | 10,048,313 | 7 | 2012-04-06T19:30:20Z | [
"python",
"list",
"random",
"pop"
] | Say I have a list `x` with unkown length from which I want to randomly pop one element so that the list does not contain the element afterwards. What is the most pythonic way to do this?
I can do it using a rather unhandy combincation of `pop`, `random.randint`, and `len` and would like to see shorter or nicer solutio... | Here's another alternative: why don't you shuffle the list *first*, and then start popping elements of it until no more elements remain? like this:
```
import random
x = [1,2,3,4,5,6]
random.shuffle(x)
while x:
p = x.pop()
# do your stuff with p
``` |
Compare date and datetime in Django | 10,048,216 | 7 | 2012-04-06T19:21:20Z | 10,048,320 | 9 | 2012-04-06T19:30:57Z | [
"python",
"django",
"django-models"
] | I have a model with a datetime field:
```
class MyModel(models.Model):
created = models.DateTimeField(auto_now = True)
```
I want to get all the records created today.
I tried:
```
MyModel.objects.all().filter(created = timezone.now())
```
and
```
MyModel.objects.all().filter(created = timezone.now().date())
... | There may be a more proper solution, but a quick workup suggests that this would work:
```
from datetime import timedelta
start_date = timezone.now().date()
end_date = start_date + timedelta( days=1 )
Entry.objects.filter(created__range=(start_date, end_date))
```
I'm assuming timezone is a datetime-like object.
T... |
How do I determine if current time is within a specified range using Python's datetime module? | 10,048,249 | 9 | 2012-04-06T19:24:21Z | 10,048,290 | 21 | 2012-04-06T19:28:23Z | [
"python",
"python-datetime"
] | What would be the best way to see if the current time lies between say `10:30 AM` and `4:30 PM`.
I could think of the following, not sure how correct:
```
from datetime import datetime
nw = datetime.now()
hrs = nw.hour;mins = nw.minute;secs = nw.second;
zero = timedelta(seconds = secs+mins*60+hrs*3600)
st = nw - zero... | ```
from datetime import datetime, time
now = datetime.now()
now_time = now.time()
if now_time >= time(10,30) and now_time <= time(16,30):
print "yes, within the interval"
```
An alternative check as suggested by Rik:
```
if time(10,30) <= now.time() <= time(16,30):
print "yes, within the interval"
``... |
Python: Finding a trend in a set of numbers | 10,048,571 | 15 | 2012-04-06T19:56:04Z | 10,048,844 | 14 | 2012-04-06T20:23:54Z | [
"python",
"math"
] | I have a list of numbers in Python, like this:
```
x = [12, 34, 29, 38, 34, 51, 29, 34, 47, 34, 55, 94, 68, 81]
```
What's the best way to find the trend in these numbers? I'm not interested in predicting what the next number will be, I just want to output the trend for many sets of numbers so that I can compare the ... | Possibly you mean you want to plot these numbers on a graph and find a straight line through them where the overall distance between the line and the numbers is minimized? This is called a linear regression
```
def linreg(X, Y):
"""
return a,b in solution to y = ax + b such that root mean square distance betwe... |
Python: Finding a trend in a set of numbers | 10,048,571 | 15 | 2012-04-06T19:56:04Z | 10,048,928 | 7 | 2012-04-06T20:33:10Z | [
"python",
"math"
] | I have a list of numbers in Python, like this:
```
x = [12, 34, 29, 38, 34, 51, 29, 34, 47, 34, 55, 94, 68, 81]
```
What's the best way to find the trend in these numbers? I'm not interested in predicting what the next number will be, I just want to output the trend for many sets of numbers so that I can compare the ... | The Link provided by Keith or probably the answer from Riaz might help you to get the poly fit, but it is always recommended to use libraries if available, and for the problem in your hand, [numpy](http://docs.scipy.org/doc/numpy-1.3.x/contents.html) provides a wonderful polynomial fit function called [polyfit](http://... |
How to keep selections highlighted in a tkinter Listbox? | 10,048,609 | 9 | 2012-04-06T19:59:11Z | 10,050,053 | 15 | 2012-04-06T22:39:21Z | [
"python",
"tkinter"
] | I have 2 separated List-boxes set on single selection mode. When I select an item from `listboxA`, it gets highlighted, but when I select an item from `listboxB`, it gets highlighted, and the item from `listboxA` remains active, but isn't highlighted. How can I keep both highlighted? | Set the `exportselection` attribute of each Listbox widget to `False` |
.gitignore style fnmatch() | 10,048,667 | 4 | 2012-04-06T20:04:41Z | 22,090,594 | 7 | 2014-02-28T09:05:46Z | [
"python",
"regex",
"filenames",
"gitignore"
] | What would be the simplest way to have .gitignore style fnmatch() with Python. Looks like that stdlib does not provide a match() function which would match a path spec against an UNIX style path regex.
* fnmatch() matches only pure filenames, no paths <http://docs.python.org/library/fnmatch.html?highlight=fnmatch#fnma... | There's now a library called [pathspec](https://pypi.python.org/pypi/pathspec) which implements the full `.gitignore` specification, including things like `**/*.py`; the documentation doesn't currently mention them but the [code](https://github.com/cpburnz/python-path-specification/blob/master/pathspec/gitignore.py) ha... |
Function for calling a function repeatedly? | 10,048,916 | 5 | 2012-04-06T20:32:06Z | 10,049,021 | 10 | 2012-04-06T20:42:49Z | [
"python",
"iterator",
"iteration"
] | Consider the hypothetical function `repeatcall`, that takes as arguments a no-args callable `func` and a positive integer `n`, and returns a list whose members are obtained by executing `func()` `n` times. It supports an infinite stream of silly hijinks like:
```
>>> repeatcall(lambda: id(dict()), 5)
[45789920, 457880... | You've seen this in the standard library docs, not the standard library itself.
It's `repeatfunc` from the [`itertools` recipes](http://docs.python.org/library/itertools.html#recipes):
```
def repeatfunc(func, times=None, *args):
"""Repeat calls to func with specified arguments.
Example: repeatfunc(random.r... |
How to flatten axes of a multidimensional array without making copies in NumPy? | 10,051,935 | 10 | 2012-04-07T05:02:10Z | 10,052,011 | 12 | 2012-04-07T05:17:16Z | [
"python",
"multidimensional-array",
"numpy",
"indexing"
] | I am wondering if there is a way to flatten a multidimensional array (i.e., of type `ndarray`) along given axes without making copies in NumPy. For example, I have an array of 2D images and I wish to flatten each to a vector. So, one easy way to do it is `numpy.array([im.flatten() for im in images])`, but that creates ... | `ravel` it:
```
>>> a = numpy.arange(25).reshape((5, 5))
>>> b = a.ravel()
>>> b[0] = 55
>>> a
array([[55, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
```
Or `reshape` it:
```
>>> a = numpy.arange(27).reshape((3, 3, 3))
>>> b =... |
Scraping javascript-generated data using Python | 10,052,465 | 7 | 2012-04-07T06:56:36Z | 10,053,618 | 8 | 2012-04-07T10:20:31Z | [
"javascript",
"python",
"screen-scraping",
"web-scraping"
] | I want to scrape some data of following url using Python.
<http://www.hankyung.com/stockplus/main.php?module=stock&mode=stock_analysis_infomation&itemcode=078340>
It's about a summary of company information.
What I want to scrape is not shown on the first page.
By clicking tab named "ì¬ë¬´ì í", you can access fin... | There's also [dryscape](https://github.com/niklasb/dryscrape) (a library written by me, so the recommendation is a bit biased, obviously :) which uses a fast Webkit-based in-memory browser to navigate around. It understands Javascript, too, but is a lot more lightweight than Selenium. |
How to sort dictionaries of objects by attribute value in python? | 10,052,912 | 8 | 2012-04-07T08:15:58Z | 10,052,956 | 7 | 2012-04-07T08:23:39Z | [
"python",
"dictionary",
"attributes",
"operator-keyword",
"sorted"
] | I would like to iterate over a dictionary of objects in an atribute sorted way
```
import operator
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
studi1=Student('john', 'A', 15)
studi2=Student('dave', 'B... | ```
for student in (sorted(student_Dict.values(), key=operator.attrgetter('age'))):
print(student.name)
``` |
Python Importing object that originates in one module from a different module into a third module | 10,053,886 | 4 | 2012-04-07T10:59:55Z | 10,053,917 | 12 | 2012-04-07T11:04:54Z | [
"python",
"import"
] | I was reading the sourcode for a python project and came across the following line:
```
from couchexport.export import Format
```
(source: <https://github.com/wbnigeria/couchexport/blob/master/couchexport/views.py#L1> )
I went over to `couchexport/export.py` to see what `Format` was (Class? Dict? something else?). U... | If module `a` does a `from b import Foo`, then `Foo` is a member of `a` afterwards and accessible as `a.Foo`. It's only consequent that you can now import it too using `from a import Foo`.
This is commonly used if you have a large library distributed across multiple files and you want them to be accessible from a sing... |
How can I create custom page for django admin? | 10,053,981 | 17 | 2012-04-07T11:16:47Z | 10,054,139 | 12 | 2012-04-07T11:41:06Z | [
"python",
"django",
"django-admin"
] | I want to create custom page for admin panel without model. For first i copy index.html to project folder:
```
mysite/
templates/
admin/
index.html
```
Then add to apps block my code:
```
<div class="module">
<table summary="{% blocktrans with name="preferences" %}Models available in the ... | You need to add your admin URL *before* the URL patterns of the admin itself:
```
urlpatterns = patterns('',
url(r'^admin/preferences/$', TemplateView.as_view(template_name='admin/preferences/preferences.html')),
url(r'^admin/', include('django.contrib.admin.urls')),
)
```
This way the URL won't be processed by... |
How can I create custom page for django admin? | 10,053,981 | 17 | 2012-04-07T11:16:47Z | 13,336,424 | 10 | 2012-11-11T23:04:51Z | [
"python",
"django",
"django-admin"
] | I want to create custom page for admin panel without model. For first i copy index.html to project folder:
```
mysite/
templates/
admin/
index.html
```
Then add to apps block my code:
```
<div class="module">
<table summary="{% blocktrans with name="preferences" %}Models available in the ... | You should be using admin's [get\_urls](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls). |
Iterating in Python lists - does it copy or use iterator? | 10,054,928 | 4 | 2012-04-07T13:33:42Z | 10,054,952 | 9 | 2012-04-07T13:37:07Z | [
"python",
"list",
"iteration",
"name-binding"
] | I have a list like this
```
a = [ [ 1,2,3 ], [ 4,5,6] ]
```
If I write
```
for x in a:
do something with x
```
Is the first list from `a` copied into `x`? Or does python do that with an iterator without doing any extra copying? | Python does not copy an item from a into x. It simply refers to the first element of a as x. That means: when you modify x, you also modify the element of a.
Here's an example:
```
>>> a = [ [ 1,2,3 ], [ 4,5,6] ]
>>> for x in a:
... x.append(5)
...
>>> a
[[1, 2, 3, 5], [4, 5, 6, 5]]
``` |
Python good programming practice for enumerating lists | 10,055,045 | 17 | 2012-04-07T13:51:56Z | 10,055,062 | 34 | 2012-04-07T13:54:53Z | [
"python",
"list"
] | I'm pretty new to Python and programming in general, and I was wondering if it is a good programming practice to write long statements with many logic operators - for example, in a for loop.
For example, here's a function I made that gets all the vowels from a word and returns a list containing those vowels.
```
def ... | No it is not considered good practice, there are always better ways :D
```
if i.upper() in "AEIOU"
```
Here is a much shorter version of your function using list comprehensions:
```
def get_vowels(word):
vowels = "AEIOU"
return [c for c in word if c.upper() in vowels]
``` |
how do i insert spaces into a string using the range function? | 10,055,631 | 6 | 2012-04-07T15:15:16Z | 10,055,656 | 11 | 2012-04-07T15:18:30Z | [
"python"
] | If I have a string, for example which reads: 'Hello how are you today Joe' How am I able to insert spaces into it at regular intervals? So for example I want to insert spaces into it using the range function in these steps: range(0,27,2). So it will look like this:
```
"He ll o ho w ar e yo u to da y Jo e"
```
I... | The most straight-forward approach for this particular case is
```
s = 'Hello how are you today Joe'
s = " ".join(s[i:i+2] for i in range(0, len(s), 2))
```
This splits the string into chunks of two characters each first, and then joins these chunks with spaces. |
g++ with python.h, how to compile | 10,056,393 | 6 | 2012-04-07T16:50:34Z | 18,447,561 | 9 | 2013-08-26T15:22:56Z | [
"c++",
"python",
"makefile"
] | I compile one test code with g++ without any issue.
```
#include "Python.h"
int main(int argc, char** argv)
{
Py_Initialize();
PyRun_SimpleString("import pylab");
PyRun_SimpleString("pylab.plot(range(5))");
PyRun_SimpleString("pylab.show()");
Py_Exit(0);
}
```
`g++ -o test test.cp... | Take a look at Lucas's comment for the answer:
"To get rid of the \_POSIX\_C\_SOURCE warning, make sure to include Python.h before all other header files."
I had the same problem. I use Boost Python, so for me I moved the include of boost/python.hpp to the first line in my .cpp file.
(Lukas, post your comment as an ... |
Python: Calculate factorial of a non-integral number | 10,056,797 | 5 | 2012-04-07T17:45:41Z | 10,056,808 | 11 | 2012-04-07T17:46:58Z | [
"python",
"floating-point",
"factorial"
] | I'm wondering if there's a speedy, Pythonic way to calculate factorials of non-integral numbers (e.g., 3.4)? Of course, the bult-in `factorial()` function in the `Math` module is available, but it only works for integrals (I don't care about negative numbers here).
Best,
j | You'd want to use [`math.gamma(x)`.](http://docs.python.org/dev/library/math.html#math.gamma)
The [gamma function](http://en.wikipedia.org/wiki/Gamma_function) is an extension of the factorial function to real numbers.
Note that the function is shifted by 1 when compared to the factorial function. So `math.factorial(... |
Cannot run a simple helloworld in gae (python 2.7) | 10,056,861 | 6 | 2012-04-07T17:52:51Z | 10,158,891 | 36 | 2012-04-15T01:34:37Z | [
"python",
"google-app-engine"
] | I am trying to run the [official helloworld](https://shadyabhi@github.com/shadyabhi/helloworld.git) program in google-appengine 1.6.4 for python 2.7.
It's so frustrating to be not able to run a simple helloworld. I would appreciate any kind of help here.
Error I encounter:-
```
shadyabhi@MBP-archlinux ~/codes/gae $ ... | If you're using python2.7 libraries there's an error with the tutorial
This line is incorrect:
```
application = webapp2.WSGIApplication([('/', MainPage)], debug=True)
```
The correct line should be:
```
app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
```
The WSGI handler is complaining because it is ... |
Installing numpy Lion with Python 2.7? | 10,057,095 | 9 | 2012-04-07T18:21:17Z | 10,057,263 | 12 | 2012-04-07T18:42:44Z | [
"python",
"numpy",
"osx-lion"
] | I am working on a OS X 10.7 with Python 2.7 from python.org and XCode 4.2.
1. Following these [instructions](http://www.scipy.org/Installing_SciPy/Mac_OS_X#head-9ec15aabd402675e5139a8c9c727e6a23513d56a), I tried changing the `CC`, `CXX`,
and `FFLAGS` variables and install with `sudo pip install numpy`.
However, ... | If I recall correctly the precompiled binary on source forge is 32-bit. It took me ages to get Numpy, Scipy, and Matplotlib set up on my macbook, it's definitely much harder than it should be.
I believe that your best option is [the Scipy superpack](http://fonnesbeck.github.com/ScipySuperpack/). Before using the super... |
Dots and boxes solving algorithm | 10,057,357 | 7 | 2012-04-07T18:53:57Z | 10,129,797 | 15 | 2012-04-12T18:43:45Z | [
"python",
"algorithm"
] | I'm currently working on a "[dots and boxes](http://en.wikipedia.org/wiki/Dots_and_Boxes)" program where the input is automatically generated by a computer, and our output is what move we'll make. I'll be competing against another player (their algorithm).
I'm representing the dots and boxes board as a matrix in Pytho... | I think that minimax is not the best choice of algorithm for dots-and-boxes. For the full story about this game you really need to read the book [*The Dots and Boxes Game: Sophisticated Child's Play* by Elwyn R. Berlekamp](http://math.berkeley.edu/~berlek/cgt/dots.html), but I'll give you a brief summary here.
Berleka... |
Correct way to implement a custom popup tkinter dialog box | 10,057,672 | 10 | 2012-04-07T19:34:05Z | 10,065,345 | 19 | 2012-04-08T18:40:35Z | [
"python",
"dialog",
"tkinter"
] | I just started learning how to create a custom pop up dialog box; and as it turns out, the `tkinter messagebox` is really easy to use, but it also does not do too much. Here is my attempt to create a dialog box that will take input and then store that in the username.
My question is what is the recommended style to im... | Using the [global statement](http://docs.python.org/2/reference/simple_stmts.html#the-global-statement) is unnecessary in the two scenarios that come to mind.
1. you want to code a dialog box that can be imported to use **with** a main GUI
2. you want to code a dialog box that can be imported to use **without** a main... |
Inverse of Tan in python (tan-1) | 10,057,854 | 4 | 2012-04-07T19:56:22Z | 10,057,866 | 20 | 2012-04-07T19:57:51Z | [
"python",
"math",
"trigonometry"
] | I am trying to calculate the inverse of tan in python, but it does not give me the correct value, for example, if I were to do the inverse tan of 1.18, `math.atan(1.18)`
```
>>>math.atan(1.18)
0.8677
```
However, the correct answer is 49.720136931. What is the correct way to do than? | [`math.atan(x)`](http://docs.python.org/library/math.html#math.atan) returned in radian, if you want degree, convert it using [`math.degrees(x)`](http://docs.python.org/library/math.html#math.degrees)
```
Converts angle x from radians to degrees.
>>> import math
>>> math.degrees(math.atan(1.18))
49.720136931043555
``... |
Accessing Items In a ordereddict | 10,058,140 | 41 | 2012-04-07T20:34:19Z | 10,058,239 | 56 | 2012-04-07T20:46:29Z | [
"python",
"collections",
"dictionary",
"python-3.x",
"ordereddictionary"
] | Lets say I have the following code:
```
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'
```
Is there a way I can access the items in a numbered manner, like:
```
d(0) #foo's Output
d(1) #bar's Output
``` | If its an `OrderedDict()` you can easily access the elements by indexing by getting the tuples of (key,value) pairs as follows
```
>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')... |
Accessing Items In a ordereddict | 10,058,140 | 41 | 2012-04-07T20:34:19Z | 22,927,576 | 11 | 2014-04-08T04:29:40Z | [
"python",
"collections",
"dictionary",
"python-3.x",
"ordereddictionary"
] | Lets say I have the following code:
```
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'
```
Is there a way I can access the items in a numbered manner, like:
```
d(0) #foo's Output
d(1) #bar's Output
``` | Do you have to use an OrderedDict or do you specifically want a map-like type that's ordered in some way with fast positional indexing? If the latter, then consider one of Python's many sorted dict types (which orders key-value pairs based on key sort order). Some implementations also support fast indexing. For example... |
Accessing Items In a ordereddict | 10,058,140 | 41 | 2012-04-07T20:34:19Z | 24,479,563 | 7 | 2014-06-29T19:38:10Z | [
"python",
"collections",
"dictionary",
"python-3.x",
"ordereddictionary"
] | Lets say I have the following code:
```
import collections
d = collections.OrderedDict()
d['foo'] = 'python'
d['bar'] = 'spam'
```
Is there a way I can access the items in a numbered manner, like:
```
d(0) #foo's Output
d(1) #bar's Output
``` | Here is a special case if you want the *first* entry (or close to it) in an OrderedDict, without creating a list:
```
>>> from collections import OrderedDict
>>>
>>> d = OrderedDict()
>>> d["foo"] = "one"
>>> d["bar"] = "two"
>>> d["baz"] = "three"
>>>
>>> d.iteritems().next()
('foo', 'one')
```
(The first time you... |
Background Process subprocess.Popen with Pipe | 10,058,368 | 7 | 2012-04-07T21:04:42Z | 10,058,398 | 9 | 2012-04-07T21:07:52Z | [
"python",
"background",
"subprocess",
"audio-recording"
] | I'm trying to record and convert a stream with python using arecord.
In the shell this is a command more or less like:
```
arecord -B 5000 -f dat | lame -m j -q 5 -V 2 - test.mp3 &
```
In Python I tried this with subprocess.Popen:
```
reccmd = ["arecord", "-B", "5000", "-f", "dat"]
mp3cmd = ["lame", "-m", "j", "-q"... | If you don't want the main Python process to block while executing the subprocesses, simply don't call `p2.communicate()`. The calls to `subprocess.Popen()` don't block. |
Get max length of multi-dimension tuple | 10,058,421 | 11 | 2012-04-07T21:11:12Z | 10,058,448 | 8 | 2012-04-07T21:14:18Z | [
"python",
"tuples",
"variable-length"
] | My tuple looks something like this(for a particular set of generated value)
```
tTrains = [ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
```
Now, what I need to find is the length of longest tuple inside this tuple/list. I can always use a for loop, iterate over all the sub-tuples and do it. But I want to ask if the... | You shouldn't use `max` as a variable name, since this will shadow the built-in of the same name. This built-in `max()` can be used to compute the maximum of an iterable.
You currently have a list of tuples, but you want the maximum of the list of their lengths. To get this list, you can use a list comprehension:
```... |
Get max length of multi-dimension tuple | 10,058,421 | 11 | 2012-04-07T21:11:12Z | 10,058,468 | 11 | 2012-04-07T21:17:12Z | [
"python",
"tuples",
"variable-length"
] | My tuple looks something like this(for a particular set of generated value)
```
tTrains = [ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
```
Now, what I need to find is the length of longest tuple inside this tuple/list. I can always use a for loop, iterate over all the sub-tuples and do it. But I want to ask if the... | ```
tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
max(map(len,tup))
```
result:
```
4
``` |
Get max length of multi-dimension tuple | 10,058,421 | 11 | 2012-04-07T21:11:12Z | 10,058,837 | 8 | 2012-04-07T22:16:54Z | [
"python",
"tuples",
"variable-length"
] | My tuple looks something like this(for a particular set of generated value)
```
tTrains = [ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
```
Now, what I need to find is the length of longest tuple inside this tuple/list. I can always use a for loop, iterate over all the sub-tuples and do it. But I want to ask if the... | Another solution:
```
>>> tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
>>> len(max(tup, key=len))
4
```
which translates to 'give me the length of the largest element of `tup`, with "largest" defined by the length of the element'. |
oauth flow in github api v3 not working | 10,058,522 | 3 | 2012-04-07T21:24:51Z | 10,058,722 | 11 | 2012-04-07T21:58:50Z | [
"python",
"api",
"oauth",
"github"
] | So this should be pretty simple, but I can't seem to find my fail point. Hopefully someone else can point it out to me.
First I go to `https://github.com/login/oauth/authorize?client_id=CLIENT_ID&scope=gist` and this returns a code to me. Then I do this:
```
import requests, json
client_id = XXXX
client_secret = XXX... | Well I was right this was a really simple problem, but I'll leave this here incase others run into the same error.
When in doubt manually define your header. So you need:
```
header = {'content-type':'application/json'}
```
And then pass in the header:
```
r = requests.post(
'https://github.com/login/oauth/acce... |
How can I open UTF-16 files on Python 2.x? | 10,058,591 | 11 | 2012-04-07T21:36:26Z | 10,058,718 | 18 | 2012-04-07T21:57:46Z | [
"python",
"unicode"
] | I'm working on a Python tool that must be able to open files of UTF-8 and UTF-16 encoding. In Python 3.2, I use the following code to try opening the file using UTF-8, then try it with UTF-16 if there's a unicode error:
```
def readGridFromPath(self, filepath):
try:
self.readGridFromFile(open(filepath,'r',... | `io.open` is drop-in replacement for your needs, so code sample you've provided will look as follows in Python 2.x:
```
import io
def readGridFromPath(self, filepath):
try:
self.readGridFromFile(io.open(filepath, 'r', encoding='utf-8'))
except UnicodeDecodeError:
self.readGridFromFile(io.open(... |
combining maybe and seq monads: confused at the output | 10,059,163 | 10 | 2012-04-07T23:20:16Z | 10,059,297 | 8 | 2012-04-07T23:48:01Z | [
"python",
"haskell",
"clojure",
"monads",
"monad-transformers"
] | I'm trying to compose seq-m and error-m to do list comprehensions on things that can return errors. My output has unexpected types, though other than that it does actually seem to be sensible. i've exploded my code below, but here is a [working gist](https://github.com/dustingetz/sandbox/blob/master/etc/monads/loan.py)... | I am not a Python expert, but this definition:
```
def bind(mval, mf):
return error_bind(mval, lambda mval: seq_bind(mval, mf))
```
...makes me very suspicious. Presumably, `mf` is supposed to return something that's wrapped in both the `error` and `seq` monad types, with the `error`-ness outermost; however, you'... |
combining maybe and seq monads: confused at the output | 10,059,163 | 10 | 2012-04-07T23:20:16Z | 10,061,083 | 8 | 2012-04-08T07:15:07Z | [
"python",
"haskell",
"clojure",
"monads",
"monad-transformers"
] | I'm trying to compose seq-m and error-m to do list comprehensions on things that can return errors. My output has unexpected types, though other than that it does actually seem to be sensible. i've exploded my code below, but here is a [working gist](https://github.com/dustingetz/sandbox/blob/master/etc/monads/loan.py)... | Combining monads by stacking like this is, in Haskell, using [Monad Transformers](http://book.realworldhaskell.org/read/monad-transformers.html). Set aside Daniel Wagner's point that ListT is not a monad for moment. You have two monads with types:
1. `List a` which looks like `[x,y,z]`
2. `(Error e) a` which looks `x,... |
sqlalchemy unique across multiple columns | 10,059,345 | 71 | 2012-04-07T23:55:16Z | 10,061,143 | 124 | 2012-04-08T07:26:01Z | [
"python",
"sqlalchemy"
] | Let's say that I have a class that represents locations. Locations "belong" to customers. Locations are identified by a unicode 10 character code. The "location code" should be unique among the locations for a specific customer.
```
The two below fields in combination should be unique
customer_id = Column(Integer,Fore... | Extract from the [documentation](http://docs.sqlalchemy.org/en/latest/core/schema.html?highlight=uniqueconstraint#sqlalchemy.schema.Column) of the `Column`:
> **unique** â When True, indicates that this column contains a unique
> constraint, or if *index* is True as well, indicates that the Index
> should be created... |
inserting characters at the start and end of a string | 10,059,554 | 31 | 2012-04-08T00:45:49Z | 10,059,562 | 54 | 2012-04-08T00:47:09Z | [
"python"
] | I am new and trying to find a way to insert a number of L's at the beginning and end of a string. So if I have a string which says
"where did I put my cupcake this morning"
And I want to insert 1 L at the start and 2 L's at the end, so it looks like: "Lwhere did I put my cupcake this morningLL" How do I do this. than... | Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:
```
yourstring = "L" + yourstring + "LL"
```
Note that you can also create a string with n `L`s by using multiplication:
```
m = 1
n = 2
yourstring = ("... |
inserting characters at the start and end of a string | 10,059,554 | 31 | 2012-04-08T00:45:49Z | 10,059,605 | 7 | 2012-04-08T01:00:20Z | [
"python"
] | I am new and trying to find a way to insert a number of L's at the beginning and end of a string. So if I have a string which says
"where did I put my cupcake this morning"
And I want to insert 1 L at the start and 2 L's at the end, so it looks like: "Lwhere did I put my cupcake this morningLL" How do I do this. than... | You can also use join:
```
yourstring = ''.join(('L','yourstring','LL'))
```
Result:
```
>>> yourstring
'LyourstringLL'
``` |
inserting characters at the start and end of a string | 10,059,554 | 31 | 2012-04-08T00:45:49Z | 10,059,623 | 12 | 2012-04-08T01:06:46Z | [
"python"
] | I am new and trying to find a way to insert a number of L's at the beginning and end of a string. So if I have a string which says
"where did I put my cupcake this morning"
And I want to insert 1 L at the start and 2 L's at the end, so it looks like: "Lwhere did I put my cupcake this morningLL" How do I do this. than... | For completeness along with the other answers:
```
yourstring = "L%sLL" % yourstring
```
Or, more forward compatible with Python 3.x:
```
yourstring = "L{0}LL".format(yourstring)
``` |
Named regular expression group "(?P<group_name>regexp)": what does "P" stand for? | 10,059,673 | 63 | 2012-04-08T01:18:00Z | 10,059,707 | 11 | 2012-04-08T01:26:59Z | [
"python",
"regex",
"group"
] | In Python, the `(?P<group_name>â¦)` [syntax](http://docs.python.org/library/re.html#regular-expression-syntax) allows one to refer to the matched string through its name:
```
>>> import re
>>> match = re.search('(?P<name>.*) (?P<phone>.*)', 'John 123456')
>>> match.group('name')
'John'
```
What does "P" stand for? I... | Pattern! The group names a (sub)pattern for later use in the regex. See [the documentation here](http://docs.python.org/library/re.html) for details about how such groups are used. |
Named regular expression group "(?P<group_name>regexp)": what does "P" stand for? | 10,059,673 | 63 | 2012-04-08T01:18:00Z | 10,060,065 | 93 | 2012-04-08T03:05:34Z | [
"python",
"regex",
"group"
] | In Python, the `(?P<group_name>â¦)` [syntax](http://docs.python.org/library/re.html#regular-expression-syntax) allows one to refer to the matched string through its name:
```
>>> import re
>>> match = re.search('(?P<name>.*) (?P<phone>.*)', 'John 123456')
>>> match.group('name')
'John'
```
What does "P" stand for? I... | Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered [this thread](http://markmail.org/message/oyezhwvefvotacc3) [emphasis mine]:
> Subject: Claiming (?P...) regex syntax extensions
... |
Safely extract zip or tar using Python | 10,060,069 | 21 | 2012-04-08T03:07:46Z | 10,077,309 | 35 | 2012-04-09T17:44:16Z | [
"python",
"zip",
"tar",
"zipfile",
"tarfile"
] | I'm trying to extract user-submitted zip and tar files to a directory. The documentation for zipfile's [extractall](http://docs.python.org/library/zipfile.html#zipfile.ZipFile.extractall) method (similarly with tarfile's [extractall](http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall)) states that i... | **Note:** Starting with python 2.7.4, this is a non-issue for ZIP archives. Details at the bottom of the answer. This answer focuses on tar archives.
To figure out where a path really points to, use `os.path.abspath()` (but note the caveat about symlinks as path components). If you normalize a path from your zipfile w... |
byte string vs. unicode string. Python | 10,060,411 | 21 | 2012-04-08T04:37:09Z | 10,060,471 | 22 | 2012-04-08T04:52:04Z | [
"python",
"string",
"unicode"
] | Could you explain in detail what the difference is between byte string and Unicode string in Python. I have read [this](http://www.coolinterview.com/interview/5512/):
> Byte code is simply the converted source code into arrays of bytes
Does it mean that Python has its own coding/encoding format? Or does it use the op... | No python does not use its own encoding. It will use any encoding that it has access to and that you specify. A character in a `str` represents one unicode character. However to represent more than 256 characters, individual unicode encodings use more than one byte per character to represent many characters. `bytearray... |
byte string vs. unicode string. Python | 10,060,411 | 21 | 2012-04-08T04:37:09Z | 34,695,423 | 8 | 2016-01-09T15:37:41Z | [
"python",
"string",
"unicode"
] | Could you explain in detail what the difference is between byte string and Unicode string in Python. I have read [this](http://www.coolinterview.com/interview/5512/):
> Byte code is simply the converted source code into arrays of bytes
Does it mean that Python has its own coding/encoding format? Or does it use the op... | Here's an attempt at a simple explanation that applies to Python 3 only. I hope that coming from a lay person, it would help to clear some confusion for the completely uninitiated. If there are any technical inaccuracies, pls forgive me and feel free to point it out.
Suppose you create a string using Python 3 in the u... |
Python - Firefox Headless | 10,060,417 | 14 | 2012-04-08T04:38:29Z | 10,060,574 | 8 | 2012-04-08T05:16:53Z | [
"python",
"firefox",
"selenium",
"headless",
"tor"
] | I've spent the last few days messing around with Selenium, Tor, and Firefox as a combination for multiple tasks. I've managed to write a simple script in Python that takes control of Firefox through Selenium, while Firefox is connected to Tor for privacy.
Now, I'm looking for a way to save resources, so I thought of r... | xvfb is a common way of doing this. Searching for "selenium xvfb" should find lots, such as:
* [Is it possible to run Selenium scripts without having an X server running, too?](http://stackoverflow.com/questions/9207320/is-it-possible-to-run-selenium-scripts-without-having-an-x-server-running-too)
* [How do I run Sele... |
Does Python respect symlinks? | 10,060,759 | 3 | 2012-04-08T06:01:16Z | 10,060,782 | 10 | 2012-04-08T06:09:10Z | [
"python",
"symlink",
"moinmoin",
"openshift"
] | I'm have difficulty finding any docs describing Python's expected symlink behavior.
I've tried testing it myself but I'm getting weird results - sometimes it appears to work for a while then stops working.
Anyway, I have a situation where MoinMoin keeps it's data files and plugin modules in the same directory but I n... | Should work just fine - symlinks are handled on the OS level, meaning as long as python isn't trying to determine if something is a symlink or not, calling an `open` on it should just open the file it's pointing to.
Is there anything in particular that isn't working? What are you seeing when it stops working? |
Create Python EXE without MSVCP90.dll | 10,060,765 | 8 | 2012-04-08T06:03:07Z | 10,060,842 | 10 | 2012-04-08T06:24:23Z | [
"python",
"py2exe"
] | I'm trying to use Py2Exe to take a python program (using wxPython) to a Windows exe but there is an error regarding MSVCP90.dll . After reading [py2exe fails to generate an executable](http://stackoverflow.com/questions/323424/py2exe-fails-to-generate-an-executable) on StackOverflow, it says I need to download this fil... | ## What is MSVCP90.dll
MSVCP90.dll is Multithreaded, dynamic Visual Studio 2008 C Runtime Library. Generally your application should package MSVCP90.dll unless you are sure that the target machine have the matching CRT. You can use any of the packaging software to package the necessary DLLs and your software and distr... |
reading some content from a web page read in python | 10,061,544 | 3 | 2012-04-08T08:43:32Z | 10,061,848 | 7 | 2012-04-08T09:39:12Z | [
"python"
] | I am trying to read some data from a python module from a web.
I manage to read, however having some difficulty in parsing this data and getting the required information.
My code is below. Any help is appreciated.
```
#!/usr/bin/python2.7 -tt
import urllib
import urllib2
def Connect2Web():
aResp = urllib2.urlope... | It's not recommended to use RE to match XML/HTML. It can sometimes work, however. It's better to use an HTML parser and a DOM API. Here's an example:
```
import html5lib
import urllib2
aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp")
t = aResp.read()
dom = ht... |
Which classes cannot be subclassed? | 10,061,752 | 67 | 2012-04-08T09:19:02Z | 10,114,382 | 20 | 2012-04-11T21:39:15Z | [
"python",
"class",
"inheritance",
"python-3.x",
"language-design"
] | Is there any rule about which built-in and standard library classes are not subclassable ("final")?
As of Python 3.3, here are a few examples:
* `bool`
* `function`
* `operator.itemgetter`
* `slice`
I found a [question](http://stackoverflow.com/questions/2825364/final-classes-in-python-3-x-something-guido-isnt-telli... | There seems to be two reasons for a class to be "final" in Python.
*1. Violation of Class Invariant*
Classes that follow Singleton pattern have an invariant that there's a limited (pre-determined) number of instances. Any violation of this invariant in a subclass will be inconsistent with the class' intent, and would... |
MySQLdb for Python 2.7 (Ubuntu) | 10,062,002 | 11 | 2012-04-08T10:07:29Z | 10,062,032 | 21 | 2012-04-08T10:15:19Z | [
"python",
"mysql",
"ubuntu",
"mysql-python"
] | After I installed MySQLdb by
```
sudo apt-get install python-mysqldb
```
I can import and use it when I use Python 2.6, but not 2.7. (ImportError: No module named MySQLdb)
I think that apt-get install MySQLdb in version 2.6, but I don't know how to make python 2.7 work with it. Please help me. Thanks a lot! | If you want system-wide installation for python2.7 you should use easy\_install-2.7. Install [setuptools](http://pypi.python.org/pypi/setuptools) (or [distribute](http://pypi.python.org/pypi/distribute)) for python 2.7, then type:
> easy\_install-2.7 mysql-python
**Update:**
Or just
> sudo apt-get install python2.7... |
Smallest way to expand a list by n | 10,062,408 | 10 | 2012-04-08T11:20:38Z | 10,062,448 | 13 | 2012-04-08T11:25:45Z | [
"python",
"list"
] | i want to expand a list
```
[1,2,3,4]
```
by *n*
e.g. for n = 2:
```
[1,1,2,2,3,3,4,4]
```
I'm searching for the smallest possible way to achieve this without any additional librarys.
Its easy to do a loop and append each item n times to a new list... but is there a other way? | ```
>>> l = [1,2,3,4]
>>> [it for it in l for _ in range(2)]
[1, 1, 2, 2, 3, 3, 4, 4]
``` |
Python convert Tuple to Integer | 10,062,673 | 9 | 2012-04-08T12:09:14Z | 10,062,684 | 12 | 2012-04-08T12:10:40Z | [
"python",
"integer",
"tuples"
] | Is there any function that can convert a tuple into an integer?
Example:
```
input = (1, 3, 7)
output = 137
``` | ```
>>> x = (1,3,7)
>>> int(''.join(map(str,x)))
137
``` |
Python convert Tuple to Integer | 10,062,673 | 9 | 2012-04-08T12:09:14Z | 10,062,711 | 23 | 2012-04-08T12:15:42Z | [
"python",
"integer",
"tuples"
] | Is there any function that can convert a tuple into an integer?
Example:
```
input = (1, 3, 7)
output = 137
``` | ```
>>> reduce(lambda rst, d: rst * 10 + d, (1, 2, 3))
123
``` |
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() | 10,062,954 | 53 | 2012-04-08T12:56:07Z | 10,063,039 | 52 | 2012-04-08T13:08:01Z | [
"python",
"matplotlib"
] | I just discovered a logical bug in my code which was causing all sorts of problems. I was inadvertently doing a **bitwise AND** instead of a **logical AND**.
I changed the code from:
```
r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[ma... | `r` is a numpy (rec)array. So `r["dt"] >= startdate` is also a (boolean)
array. For numpy arrays the `&` operation returns the bitwise-and of the two
boolean arrays.
The NumPy developers felt there was no one commonly understood way to evaluate
an array in boolean context: it could mean `True` if *any* element is
`Tru... |
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() | 10,062,954 | 53 | 2012-04-08T12:56:07Z | 13,903,284 | 19 | 2012-12-16T16:36:56Z | [
"python",
"matplotlib"
] | I just discovered a logical bug in my code which was causing all sorts of problems. I was inadvertently doing a **bitwise AND** instead of a **logical AND**.
I changed the code from:
```
r = mlab.csv2rec(datafile, delimiter=',', names=COL_HEADERS)
mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[ma... | I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The `(a-b).any()` or `(a-b).all()` seem not working, at least for me.
Alternatively I found another solution which works perfectly for my desired functionality [(http://stackoverflow.com/questions/12647471/the... |
python, how to incrementally create Threads | 10,063,353 | 5 | 2012-04-08T13:59:08Z | 10,063,386 | 7 | 2012-04-08T14:04:04Z | [
"python",
"multithreading"
] | I have a list of items aprox 60,000 items - i would like to send queries to the database to check if they exist and if they do return some computed results. I run an ordinary query, while iterating through the list one-by-one, the query has been running for the last 4 days. I thought i could use the threading module to... | You could try using a process pool, which is available in the multiprocessing module. Here is the example from the python docs:
```
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes
result = pool.apply_async(f... |
how to check if 3 characters are in consecutive alpha order | 10,063,962 | 6 | 2012-04-08T15:26:44Z | 10,064,227 | 11 | 2012-04-08T16:05:59Z | [
"python",
"sequence",
"alphabetical"
] | Just curious, what's the most pythonic/efficient way to determine if
sequence of 3 characters are in consecutive alpha order?
Below a quick&dirty way that seems to work, other, nicer implementations?
I suppose one alternative approach might be to sort a copy the
sequence and compare it with the original. Nope, that w... | Easy:
```
>>> letters = "Cde"
>>> from string import ascii_lowercase
>>> letters.lower() in ascii_lowercase
True
>>> letters = "Abg"
>>> letters.lower() in ascii_lowercase
False
```
Alternatively, one could use `string.find()`.
```
>>> letters = "lmn"
>>> ascii_lowercase.find(letters) != -1
True
```
I guess a funct... |
Can't access parent member variable in Python | 10,064,688 | 11 | 2012-04-08T17:12:58Z | 10,064,703 | 20 | 2012-04-08T17:15:00Z | [
"python",
"inheritance",
"scope"
] | I'm trying to access a parent member variable from an extended class. But running the following code...
```
class Mother(object):
def __init__(self):
self._haircolor = "Brown"
class Child(Mother):
def __init__(self):
Mother.__init__(self)
def print_haircolor(self):
print Mother... | You're mixing up class and instance attributes.
```
print self._haircolor
``` |
Can't access parent member variable in Python | 10,064,688 | 11 | 2012-04-08T17:12:58Z | 10,064,719 | 15 | 2012-04-08T17:17:20Z | [
"python",
"inheritance",
"scope"
] | I'm trying to access a parent member variable from an extended class. But running the following code...
```
class Mother(object):
def __init__(self):
self._haircolor = "Brown"
class Child(Mother):
def __init__(self):
Mother.__init__(self)
def print_haircolor(self):
print Mother... | You want the instance attribute, not the class attribute, so you should use `self._haircolor`.
Also, you really should use `super` in the `__init__` in case you decide to change your inheritance to `Father` or something.
```
class Child(Mother):
def __init__(self):
super(Child, self).__init__()
def p... |
Can you make a python script behave differently when imported than when run directly? | 10,064,796 | 2 | 2012-04-08T17:27:23Z | 10,064,812 | 13 | 2012-04-08T17:28:47Z | [
"python"
] | I often have to write data parsing scripts, and I'd like to be able to run them in two different ways: as a module and as a standalone script. So, for example:
```
def parseData(filename):
# data parsing code here
return data
def HypotheticalCommandLineOnlyHappyMagicFunction():
print json.dumps(parseData(... | The standard way to do this is to guard the code that should be only run when the script is called stand-alone by
```
if __name__ == "__main__":
# Your main script code
```
The code after this `if` won't be run if the module is imported.
The `__name__` special variable contains the name of the current module as ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.