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 |
|---|---|---|---|---|---|---|---|---|---|
Using headers with the Python requests library's get method | 6,260,457 | 30 | 2011-06-07T04:03:15Z | 6,260,521 | 18 | 2011-06-07T04:12:49Z | [
"python",
"http-request",
"python-requests"
] | So I recently stumbled upon this great library for handling HTTP requests in Python; found here <http://docs.python-requests.org/en/latest/index.html>.
I love working with it, but I can't figure out how to add headers to my get requests. Help? | Seems pretty straightforward, according to the [docs](http://docs.python-requests.org/en/latest/api/) on the page you linked (emphasis mine).
> requests.get(url, params=None, headers=None, cookies=None, auth=None,
> timeout=None)
>
> Sends a GET request.
> Returns `Response` object.
>
> Parameters:
>
> * url â URL f... |
Using headers with the Python requests library's get method | 6,260,457 | 30 | 2011-06-07T04:03:15Z | 6,260,526 | 55 | 2011-06-07T04:13:21Z | [
"python",
"http-request",
"python-requests"
] | So I recently stumbled upon this great library for handling HTTP requests in Python; found here <http://docs.python-requests.org/en/latest/index.html>.
I love working with it, but I can't figure out how to add headers to my get requests. Help? | According to the [api](http://docs.python-requests.org/en/latest/api/), the headers can all be passed in using requests.get:
```
r=requests.get("http://www.example.com/", headers={"content-type":"text"});
``` |
Python Regex to Parse String and Return Tuple | 6,260,777 | 4 | 2011-06-07T05:02:48Z | 6,260,945 | 8 | 2011-06-07T05:28:24Z | [
"python",
"regex",
"string",
"numbers",
"return"
] | I've been given some strings to work with. Each one represents a data set and consists of the data set's name and the associated statistics. They all have the following form:
```
s= "| 'TOMATOES_PICKED' | 914 | 1397 |"
```
I'm trying to implement a function that will parse... | I would use a single regular expression to match the entire line, with the parts I want in named groups (`(?P<name>exampl*e)`).
```
import re
def extract_data2(s):
pattern = re.compile(r"""\|\s* # opening bar and whitespace
'(?P<name>.*?)' # quoted name
... |
SQLAlchemy - How to make "django choices" using SQLAlchemy? | 6,262,943 | 16 | 2011-06-07T09:03:20Z | 6,264,027 | 17 | 2011-06-07T10:40:19Z | [
"python",
"sqlalchemy"
] | In Django we can use very simple "choices" e.g.:
```
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Foo(models.Model):
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
```
How to make something like this using SQLAlchemy? | Use [custom types](http://www.sqlalchemy.org/docs/core/types.html#custom-types).
Example:
```
import sqlalchemy.types as types
class ChoiceType(types.TypeDecorator):
impl = types.String
def __init__(self, choices, **kw):
self.choices = dict(choices)
super(ChoiceType, self).__init__(**kw)
... |
Odd behavior of stacked filter() calls | 6,263,017 | 5 | 2011-06-07T09:10:04Z | 6,263,087 | 7 | 2011-06-07T09:16:26Z | [
"python",
"filter"
] | So I'm getting some interesting behaviour from some filters stacked within a for loop.
I'll start with a demonstration:
```
>>> x = range(100)
>>> x = filter(lambda n: n % 2 == 0, x)
>>> x = filter(lambda n: n % 3 == 0, x)
>>> list(x)
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]
```
Here we get ... | In Python 3.x, `filter()` returns a generator instead of a list. As such, only the final value of `factor` gets used since all three filters use the same `factor`. You will need to modify your lambda slightly in order to make it work.
```
result = filter(lambda n, factor=factor: n % factor != 0, result)
``` |
How to adapt the Singleton pattern? (Deprecation warning) | 6,264,025 | 14 | 2011-06-07T10:40:06Z | 6,264,202 | 8 | 2011-06-07T10:59:34Z | [
"python",
"design-patterns",
"singleton",
"deprecated"
] | Few years ago I found an implementation of the Singleton pattern in Python by [Duncan Booth](http://web.archive.org/web/20090619190842/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html):
```
class Singleton(object):
"""
Singleton class by Duncan Booth.
Multiple object variables refers to th... | You need to drop any additional arguments you are passing when you construct the object. Change the offending line to:
```
cls._instance = object.__new__(cls)
```
or
```
cls._instance = super(Singleton, cls).__new__(cls)
```
though I think you'll be fine with the first (diamond inheritance and singl... |
Querying MongoDB (via pymongo) in case insensitive efficiently | 6,266,555 | 15 | 2011-06-07T14:14:54Z | 6,269,152 | 27 | 2011-06-07T17:24:01Z | [
"python",
"mongodb",
"case-insensitive",
"pymongo"
] | I'm currently creating a website in python (pyramid) which requires users to sign up and log in. The system allows for users to choose a username which can be a mixture of capital letters, lowercase letters, and numbers.
The problem arises when making sure that two users don't accidentally share the same username, i.e... | PyMongo uses native python regular expressions, in the same way as the mongo shell uses native javascript regular expressions. To write the equivalent query of what you had written in the shell above, you would use:
```
db.stuff.find_one({'name': re.compile(username, re.IGNORECASE)})
```
Note that this will avoid usi... |
How to write Python generator function that never yields anything | 6,266,561 | 16 | 2011-06-07T14:15:23Z | 6,266,586 | 18 | 2011-06-07T14:17:03Z | [
"python",
"generator",
"yield"
] | I want to write a Python generator function that never actually yields anything. Basically it's a "do-nothing" drop-in that can be used by other code which expects to call a generator (but doesn't always need results from it). So far I have this:
```
def empty_generator():
# ... do some stuff, but don't yield anyt... | Another way is
```
def empty_generator():
return
yield
```
Not really "more expressive", but shorter. :)
Note that `iter([])` or simply `[]` will do as well. |
Python: Cut off the last word of a sentence? | 6,266,727 | 25 | 2011-06-07T14:26:36Z | 6,266,839 | 77 | 2011-06-07T14:32:41Z | [
"python",
"split",
"concatenation",
"word",
"text-segmentation"
] | What's the best way to slice the last word from a block of text?
I can think of
1. Split it to a list (by spaces) and removing the last item, then reconcatenating the list.
2. Use a regular expression to replace the last word.
I'm currently taking approach #1, but I don't know how to concatenate the list...
```
con... | Actually you don't need to split all words. You can split you text by last space symbol into two parts using [rsplit](http://docs.python.org/library/stdtypes.html#str.rsplit).
Some example:
```
>>> text = 'Python: Cut of the last word of a sentence?'
>>> text.rsplit(' ', 1)[0]
'Python: Cut of the last word of a'
``` |
Modifying axes on matplotlib colorbar plot of 2D array | 6,267,008 | 6 | 2011-06-07T14:44:08Z | 6,267,559 | 8 | 2011-06-07T15:23:12Z | [
"python",
"numpy",
"matplotlib",
"colorbar"
] | I have a 2D numpy array that I want to plot in a colorbar. I am having trouble changing the axis so that they display my dataset. The vertical axis goes 'down' from 0 to 100, whereas I want it to go 'up' from 0.0 to 0.1. So I need to do two things:
* Flip the array using np.flipud() and then 'flip' the axis as well
* ... | You want to look at the imshow options "origin" and "extent", I think.
```
import matplotlib.pyplot as plt
import numpy as np
x,y = np.mgrid[-2:2:0.1, -2:2:0.1]
data = np.sin(x)*(y+1.05**(x*np.floor(y))) + 1/(abs(x-y)+0.01)*0.03
fig = plt.figure()
ax = fig.add_subplot(111)
ticks_at = [-abs(data).max(), 0, abs(data).... |
pointer in python? | 6,267,505 | 2 | 2011-06-07T15:19:58Z | 6,267,538 | 7 | 2011-06-07T15:21:45Z | [
"python",
"pointers"
] | When I was trying to figure out the use of [imp.load\_module](http://docs.python.org/library/imp.html?highlight=imp#imp.load_module) in Python, I got the following code ([origin page](http://nullege.com/codes/search/imp.load_module/all/-1/0/python/page:2)). It's my first time seeing the use of \* in Python, is that som... | The `*` on front if `info` causes the list / tuple to be unwrapped into individual arguments to the function. You can read more about unpacking [here](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) in the python documentation. this can also be done with dictionaries for named arguments, see ... |
Modifying global variables in Python unittest framework | 6,268,278 | 15 | 2011-06-07T16:10:18Z | 6,278,113 | 23 | 2011-06-08T11:37:17Z | [
"python",
"unit-testing",
"global-variables"
] | I am working on a series of unit tests in Python, some of which depend on the value of a configuration variable. These variables are stored in a global Python config file and are used in other modules. I would like to write unit tests for different values of the configuration variables but have not yet found a way to d... | Don't do this:
```
from my_module import my_function_with_global_var
```
But this:
```
import my_module
```
And then you can inject `MY_CONFIG_VARIABLE` into the imported `my_module`, without changing the system under test like so:
```
class TestSomething(unittest.TestCase): # Fixed that for you!
def test_fir... |
Modifying global variables in Python unittest framework | 6,268,278 | 15 | 2011-06-07T16:10:18Z | 34,631,010 | 8 | 2016-01-06T10:37:47Z | [
"python",
"unit-testing",
"global-variables"
] | I am working on a series of unit tests in Python, some of which depend on the value of a configuration variable. These variables are stored in a global Python config file and are used in other modules. I would like to write unit tests for different values of the configuration variables but have not yet found a way to d... | You probably want to mock those global variables instead. The advantage of this is that the globals get reset once you're done. Python ships with a mocking module that lets you do this.
[`unittest.mock.patch`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch) be used as a decorator:
```
class ... |
numpy.savetxt Problems with 1D array writing | 6,268,657 | 7 | 2011-06-07T16:43:12Z | 6,268,761 | 8 | 2011-06-07T16:50:57Z | [
"python",
"numpy"
] | I'm trying to use numpy's `savetxt` function to generate a bunch of files as inputs for another piece of software.
I'm trying to write an array of the form:
```
a=np.array([1,2,3,4,...])
a.shape=>(1,n)
```
to a text file with the formatting
1,2,3,4,...
when I enter the command
```
np.savetxt('test.csv',a,fmt='%d',... | There are different ways to fix this. The one closest to your current approach is:
```
np.savetxt('test.csv', a[None], fmt='%d', delimiter=',')
```
i.e. add the slicing `[None]` to your array to make it two-dimensional with only a single line. |
How to show the default beautiful popup message in ubuntu using python? | 6,268,675 | 2 | 2011-06-07T16:44:52Z | 6,268,841 | 9 | 2011-06-07T16:56:18Z | [
"python",
"user-interface",
"ubuntu",
"popup",
"gnome"
] | <http://tinypic.com/r/5dv7kj/7>
How can i show the message like in the picture(top right)?
I'm new to linux and now tring to use pygtk to make a client application to show/popup some random hint/mems.
Using traditional winodw is OK,but this one is much more friendly to me.I have tried scanning through the pygtk guide... | It's an Ubuntu specific thing called [NotifyOSD](https://wiki.ubuntu.com/NotifyOSD). There are examples of programming for it [here](https://wiki.ubuntu.com/NotificationDevelopmentGuidelines#Layout%20cases%20%28with%20examples%20in%20C,%20Python%20and%20C#%29). |
Submitting a post request to an aspx page | 6,269,064 | 9 | 2011-06-07T17:16:34Z | 6,269,418 | 7 | 2011-06-07T17:43:09Z | [
"asp.net",
"python",
"httpwebrequest"
] | I have an ASPX page at <https://searchlight.cluen.com/E5/CandidateSearch.aspx> with a form on it, that I'd like to submit and parse for information.
Using Python's urllib and urllib2 I created a post request with the proper headers and user agent. But the resulting html response does not contain the expected table of ... | ASP.Net uses a security feature that protects against tampering with the ViewState by [embedding specific information in it.](http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enableviewstatemac.aspx)
More than likely, the server is rejecting your request because the ViewState is being trea... |
What does the 'b' character do in front of a string literal? | 6,269,765 | 187 | 2011-06-07T18:14:52Z | 6,269,785 | 110 | 2011-06-07T18:16:22Z | [
"python",
"string",
"unicode",
"binary"
] | Apparently, the following is valid syntax...
```
my_string = b'The string'
```
I would like to know...
1. What does this `b` character infront of the string mean?
2. What are the effects of using it?
3. What are appropriate situations to use it.
I found a [related question](http://stackoverflow.com/q/4749442/346561... | To quote [the Python 2.x documentation](https://docs.python.org/2/reference/lexical_analysis.html#string-literals):
> A prefix of 'b' or 'B' is ignored in
> Python 2; it indicates that the
> literal should become a bytes literal
> in Python 3 (e.g. when code is
> automatically converted with 2to3). A
> 'u' or 'b' pref... |
What does the 'b' character do in front of a string literal? | 6,269,765 | 187 | 2011-06-07T18:14:52Z | 6,273,618 | 177 | 2011-06-08T02:34:37Z | [
"python",
"string",
"unicode",
"binary"
] | Apparently, the following is valid syntax...
```
my_string = b'The string'
```
I would like to know...
1. What does this `b` character infront of the string mean?
2. What are the effects of using it?
3. What are appropriate situations to use it.
I found a [related question](http://stackoverflow.com/q/4749442/346561... | [Python 3.x](http://diveintopython3.org/strings.html) makes a clear distinction between the types:
* `str` = `'...'` literals = a sequence of Unicode characters (UTF-16 or UTF-32, depending on how Python was compiled)
* `bytes` = `b'...'` literals = a sequence of octets (integers between 0 and 255)
If you're familiar... |
Detect if a python module changes and then reload | 6,270,395 | 21 | 2011-06-07T19:13:58Z | 6,270,494 | 8 | 2011-06-07T19:23:07Z | [
"python",
"import",
"runtime"
] | So I'm developing a rather large python project with a number of modules. The "main" (runnable) module is a daemon (a Thrift daemon, actually) which calls off to other modules for its actual functionality. Starting up the daemon takes a long time because some of the modules have a rather lengthy and involved initializa... | [Detect File Change Without Polling](http://stackoverflow.com/questions/5738442/detect-file-change-without-polling)
Coupled with you already knowing how to reload your module this answer pretty much fills it out. It uses Inotify to "notify" (see what they did there) the program when the file is modified. |
How to run sudo with paramiko? (Python) | 6,270,677 | 10 | 2011-06-07T19:39:50Z | 6,271,562 | 12 | 2011-06-07T20:57:24Z | [
"python",
"ssh",
"sudo",
"paramiko"
] | What I've tried:
1. invoke\_shell() then channel.send su then send the password resulted in not being root
2. invoke\_shell() then channel.exec\_command resulted in Channel Closed error
3. \_transport.open\_session() then channel.exec\_command resulted in not being in root
4. invoke\_shell() then write to the stdin an... | check this example out:
```
ssh.connect('127.0.0.1', username='jesse',
password='lol')
stdin, stdout, stderr = ssh.exec_command(
"sudo dmesg")
stdin.write('lol\n')
stdin.flush()
data = stdout.read.splitlines()
for line in data:
if line.split(':')[0] == 'AirPort':
print line
```
Example found here... |
How to send an email with Python? | 6,270,782 | 66 | 2011-06-07T19:48:05Z | 6,270,987 | 95 | 2011-06-07T20:07:33Z | [
"python",
"email",
"function",
"smtplib"
] | This code works and sends me an email just fine:
```
import smtplib
#SERVER = "localhost"
FROM = 'monty@python.com'
TO = ["jon@mycompany.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (F... | I recommend that you use the standard packages `email` and `smtplib` together to send Email. Please look at the following example (reproduced from the [Python documentation](http://docs.python.org/library/email-examples.html)). Notice that if you follow this approach, the "simple" task is indeed simple, and the more co... |
How to send an email with Python? | 6,270,782 | 66 | 2011-06-07T19:48:05Z | 31,957,430 | 8 | 2015-08-12T06:21:41Z | [
"python",
"email",
"function",
"smtplib"
] | This code works and sends me an email just fine:
```
import smtplib
#SERVER = "localhost"
FROM = 'monty@python.com'
TO = ["jon@mycompany.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (F... | There is indentation problem. The code below will work:
```
import textwrap
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = textwrap.dedent("""\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ... |
How to send an email with Python? | 6,270,782 | 66 | 2011-06-07T19:48:05Z | 34,139,884 | 11 | 2015-12-07T17:44:36Z | [
"python",
"email",
"function",
"smtplib"
] | This code works and sends me an email just fine:
```
import smtplib
#SERVER = "localhost"
FROM = 'monty@python.com'
TO = ["jon@mycompany.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (F... | I'd like to help you with sending emails by advising the yagmail package (I'm the maintainer, sorry for the advertising, but I feel it can really help!).
The whole code for you would be:
```
import yagmail
yag = yagmail.SMTP(FROM, 'pass')
yag.send(TO, SUBJECT, TEXT)
```
Note that I provide defaults for all arguments... |
How to send an email with Python? | 6,270,782 | 66 | 2011-06-07T19:48:05Z | 35,296,862 | 18 | 2016-02-09T16:16:14Z | [
"python",
"email",
"function",
"smtplib"
] | This code works and sends me an email just fine:
```
import smtplib
#SERVER = "localhost"
FROM = 'monty@python.com'
TO = ["jon@mycompany.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (F... | Well, you want to have an answer that is up-to-date and modern.
Here is my answer:
When I need to mail in python, I use the [mailgun](http://www.mailgun.com) API wich get's a lot of the headaches with sending mails sorted out. They have a wonderfull app/api that allows you to send 10,000 emails per month for free.
S... |
How to "comma" format the output of a django variable? | 6,270,904 | 5 | 2011-06-07T19:58:59Z | 6,270,984 | 12 | 2011-06-07T20:07:20Z | [
"python",
"django"
] | I have this variable:
```
{{ object.article.rating.get_percent|floatformat }}
```
that outputs this:
```
540787
```
Is there a way to format it so it shows as:
```
540,787
``` | this should help you out:
<http://twigstechtips.blogspot.com/2010/02/django-formatting-numbers-with-commas.html>
details:
add "django.contrib.humanize" to your INSTALLED\_APPS setting.
then in the template:
```
{% load humanize %}
{{ price|intcomma }}
``` |
How can I simulate input to stdin for pyunit? | 6,271,947 | 13 | 2011-06-07T21:40:38Z | 6,271,995 | 18 | 2011-06-07T21:47:49Z | [
"python",
"linux",
"pyunit"
] | I'm trying to test a function that takes input from `stdin`, which I'm currently testing with something like this:
```
cat /usr/share/dict/words | ./spellchecker.py
```
In the name of test automation, is there any way that `pyunit` can fake input to `raw_input()`? | The short answer is to [monkey patch](http://en.wikipedia.org/wiki/Monkey_patch) `raw_input()`.
There are some good examples in the answer to [How to display the redirected stdin in Python?](http://stackoverflow.com/questions/5812333/how-to-display-the-redirected-stdin-in-python)
Here is a simple, trivial example usi... |
How can I simulate input to stdin for pyunit? | 6,271,947 | 13 | 2011-06-07T21:40:38Z | 6,272,100 | 8 | 2011-06-07T21:59:05Z | [
"python",
"linux",
"pyunit"
] | I'm trying to test a function that takes input from `stdin`, which I'm currently testing with something like this:
```
cat /usr/share/dict/words | ./spellchecker.py
```
In the name of test automation, is there any way that `pyunit` can fake input to `raw_input()`? | ### Update -- using unittest.mock.patch
Since python 3.3 there is new submodule for `unittest` called mock that does exactly what you need to do. For those using python 2.6 or above there is a backport of `mock` found [here](https://pypi.python.org/pypi/mock).
```
import unittest
from unittest.mock import patch
impo... |
Access array contents from a .mat file loaded using Scipy.io.loadmat - python | 6,273,634 | 9 | 2011-06-08T02:38:14Z | 12,591,639 | 9 | 2012-09-25T21:53:15Z | [
"python",
"matlab",
"numpy",
"scipy",
"mat-file"
] | **UPDATE: This is a long question that boils down to, can someone explain the numpy array class to me? I answered my own question below.**
I am working on a project to import data from matlab into a mysql database whose contents will be made available through a django website. I want to use Scipy.io.loadmat to get the... | I've run into a similar issue with a fairly complex mat file at our company. I'm still getting my head wrapped around the scipy IO module, but here is what we found.
When you access matfile['sensors'] it returns a scipy.io.matlab.mio5\_params.mat\_struct object, which we can use to access the contents below. When you ... |
python replace backslashes to slashes | 6,275,695 | 4 | 2011-06-08T07:46:32Z | 6,275,710 | 9 | 2011-06-08T07:48:26Z | [
"python",
"string",
"filepath",
"backslash"
] | How can I escape backslashe in string: 'pictures\12761\_1.jpg'?
I know about raw string.
But how can I convert str to raw if I take 'pictures\12761\_1.jpg' value from xml file for example? | You can use the string `.replace()` method.
```
>>> print r'pictures\12761_1.jpg'.replace("\\", "/")
pictures/12761_1.jpg
``` |
Escaping quotes in string | 6,275,762 | 6 | 2011-06-08T07:53:24Z | 6,275,812 | 14 | 2011-06-08T07:58:54Z | [
"python",
"regex",
"escaping"
] | I have a python dictionary e.g.:
```
[{"pk":"1","name":"John","size":"1/4" "},{},{},etc]
```
That size is 1/4 inch,how would I "escape" that quote? So it still would display it as 1/4",
Its a list of things, so I cant just manually code it like `1/4\"`,
I tried `replace('"','\"')`
EDIT:
The orginal list is a textfi... | You need to escape your backslash in the replace in order to get it printed. Try
```
replace('"','\\"')
``` |
Suds over https with cert | 6,277,027 | 28 | 2011-06-08T09:57:32Z | 6,532,645 | 31 | 2011-06-30T09:22:21Z | [
"python",
"ssl",
"https",
"suds"
] | I have soap service under Apache with ssl, suds works greate without ssl.
I have client certificate (my.crt and user.p12 files).
How I need to configure suds client ot make it work with service over https?
without certs i see
```
urllib2.URLError: <urlopen error [Errno 1] _ssl.c:499: error:14094410:SSL routines:S... | It sounds like you want to authenticate using a *client* certificate, not a *server* certificate as was stated in some of the comments. I had the same issue and was able to write a custom transport for SUDS. Here's the code that works for me.
You'll need your certificates in PEM format for this to work; OpenSSL can ea... |
Suds over https with cert | 6,277,027 | 28 | 2011-06-08T09:57:32Z | 17,356,449 | 11 | 2013-06-28T02:47:48Z | [
"python",
"ssl",
"https",
"suds"
] | I have soap service under Apache with ssl, suds works greate without ssl.
I have client certificate (my.crt and user.p12 files).
How I need to configure suds client ot make it work with service over https?
without certs i see
```
urllib2.URLError: <urlopen error [Errno 1] _ssl.c:499: error:14094410:SSL routines:S... | Another workaround is to use requests library as transport which has better support for ssl. This is what I'm using now to access SOAP services through https using suds:-
```
import requests
from suds.transport.http import HttpAuthenticated
from suds.transport import Reply, TransportError
class RequestsTransport(Http... |
are generators supported in RPython? | 6,277,174 | 8 | 2011-06-08T10:09:35Z | 6,278,734 | 20 | 2011-06-08T12:32:33Z | [
"python",
"generator",
"pypy",
"rpython"
] | Are generators supported in RPython, because I just read something in PyPy's documentation that says they are not
[PyPy Doc - Coding Guide](http://doc.pypy.org/en/latest/coding-guide.html)
They seem easy to be translated to a statically typed language like C because every generation step is generated in function call... | Generators are not supported simply because they were not needed at the time. The problem is not really having a roughly equivalent functionality in C, but needing to keep a frame of generator alive. Since RPython frames are translated to C frames, to support full python generators you would need some support for getti... |
Raising exceptions when an exception is already present in Python 3 | 6,278,426 | 13 | 2011-06-08T12:06:35Z | 6,279,664 | 8 | 2011-06-08T13:43:13Z | [
"python",
"exception",
"exception-handling",
"python-3.x"
] | What happens to my first exception (`A`) when the second (`B`) is raised in the following code?
```
class A(Exception): pass
class B(Exception): pass
try:
try:
raise A('first')
finally:
raise B('second')
except X as c:
print(c)
```
If run with `X = A` I get:
```
Traceback (most recent ca... | Pythons exception handling will only deal with one exception at a time. However, exception objects are subject to the same variable rules and garbage collection as everything else. Hence, if you save the exception object in a variable somewhere you can deal with it later, even if another exception is raised.
In your c... |
How to solve Python TypeError? | 6,278,531 | 4 | 2011-06-08T12:14:43Z | 6,278,617 | 8 | 2011-06-08T12:22:30Z | [
"python",
"psycopg2",
"typeerror"
] | This is my code below and I try to load data from one database to another. I believe everything works fine but an error occurs and I don't know what this means.
```
import pymssql, psycopg2
class Datenbankabfrage:
def __init__(self):
self.conn1 = pymssql.connect(host='***', user='***', password='***', database='... | According to [the documentation](http://initd.org/psycopg/docs/cursor.html#cursor.executemany), `executemany()` takes two parameters. You have provided but one (`query`).
> `executemany(operation, seq_of_parameters)`
>
> Prepare a database operation (query or
> command) and then execute it against
> all parameter tupl... |
Is it possible to kill a process on Windows from within Python? | 6,278,847 | 18 | 2011-06-08T12:42:24Z | 6,278,951 | 29 | 2011-06-08T12:50:37Z | [
"python",
"windows",
"windows-xp"
] | I'm using *Python 2.6*. Sometimes there become several instances of a certain process open, and that process causes some problems in itself. I want to be able to programatically detect that there are multiple instances of that process and to kill them.
For example, maybe in some cases there are 50 instances of make.ex... | I would think you could just use [taskkill](http://technet.microsoft.com/en-us/library/bb491009.aspx) and the Python [os.system()](http://docs.python.org/library/os.html#os.system)
```
import os
os.system("taskkill /im make.exe")
```
---
Note: I would just note you might have to fully qualify the taskkill path. I am... |
Scheduling a regular event: Cron/Cron alternatives (including Celery) | 6,278,940 | 7 | 2011-06-08T12:50:01Z | 6,284,483 | 11 | 2011-06-08T19:59:28Z | [
"python",
"windows",
"django",
"linux",
"cron"
] | Something I've had interest in is regularly running a certain set of actions at regular time intervals. Obviously, this is a task for [cron](http://en.wikipedia.org/wiki/Cron), right?
Unfortunately, the Internet seems to be in a bit of disagreement there.
Let me elaborate a little about my setup. First, my developmen... | A simple, non-Celery way to approach things would be to create [Django custom management commands](https://docs.djangoproject.com/en/1.3/howto/custom-management-commands/) to perform your asynchronous or scheduled tasks.
Then, on Windows, you use the `at` command to schedule these tasks. On Linux, you use `cron`.
I'd... |
Scheduling a regular event: Cron/Cron alternatives (including Celery) | 6,278,940 | 7 | 2011-06-08T12:50:01Z | 8,867,017 | 11 | 2012-01-15T02:03:35Z | [
"python",
"windows",
"django",
"linux",
"cron"
] | Something I've had interest in is regularly running a certain set of actions at regular time intervals. Obviously, this is a task for [cron](http://en.wikipedia.org/wiki/Cron), right?
Unfortunately, the Internet seems to be in a bit of disagreement there.
Let me elaborate a little about my setup. First, my developmen... | I had the same problem, and held off trying to solve it with celery (too complicated) or cron (external to application) and ended up finding [Advanced Python Scheduler](http://packages.python.org/APScheduler/index.html). Only just started using it but it seems reasonably mature and stable, has decent documentation and ... |
Is it possible to do bitwise operations on a string in Python? | 6,279,134 | 5 | 2011-06-08T13:04:34Z | 6,279,339 | 7 | 2011-06-08T13:19:52Z | [
"python",
"string",
"bit-manipulation"
] | This fails, not surprisingly:
```
>>> 'abc' << 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'str' and 'int'
>>>
```
With ascii `abc` being equal to `011000010110001001100011` or `6382179`, is there a way to shift it some arbitrary amount so ... | It doesn't make any sense to do bitwise operations on strings. You probably want to use the `struct` module to convert your strings to numbers:
```
>>> import struct
>>> x = 'abc'
>>> x = '\x00' * (4-len(x)) + x
>>> number = struct.unpack('!i', x)[0]
>>> number
6382179
```
You can then do all your operations on `numb... |
Is it possible to do bitwise operations on a string in Python? | 6,279,134 | 5 | 2011-06-08T13:04:34Z | 6,279,380 | 7 | 2011-06-08T13:22:03Z | [
"python",
"string",
"bit-manipulation"
] | This fails, not surprisingly:
```
>>> 'abc' << 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'str' and 'int'
>>>
```
With ascii `abc` being equal to `011000010110001001100011` or `6382179`, is there a way to shift it some arbitrary amount so ... | What you probably want is the bitstring module (see <http://code.google.com/p/python-bitstring/>). It seems to support bitwise operations as well as a bunch of other manipulations of bit arrays. But you should be careful to feed bytes into it (e.g. `b'abc'` or `bytes('abc')`), not characters - characters can contain Un... |
TypeError: cannot deepcopy this pattern object | 6,279,305 | 10 | 2011-06-08T13:17:54Z | 6,279,439 | 7 | 2011-06-08T13:26:13Z | [
"python",
"regex",
"deep-copy"
] | Trying to understand this error in my "Variable" class.
I was hoping to store a sre.SRE\_Pattern in my "Variable" class. I just started copying the Variable class and noticed that it was causing all my Variable class instances to change. I now understand that I need to deepcopy this class, but now I run into "TypeErro... | `deepcopy` doesn't know anything about your classes and doesn't know how to copy them.
You can tell `deepcopy` how to copy your objects by implementing a `__deepcopy__()` method:
```
class VariableWithoutRE(object):
# ...
def __deepcopy__(self):
return VariableWithoutRE(self.name, self.regexTarget, self.t... |
New To Python (Programming) and Data Storage | 6,280,727 | 2 | 2011-06-08T14:50:07Z | 6,281,407 | 8 | 2011-06-08T15:35:15Z | [
"python",
"python-3.x"
] | I have a question about data storage. I have a program that is creating a list of objects. What is the best way to store these on file so that the program can reload them later? I've tried to use Pickle, but I think I might be heading down the wrong alley and I keep getting this error when I try to read back the data:
... | I think the problem is that the line
```
knowledge = pickle.load(open("data.txt"))
```
doesn't open the file in binary mode. Python 3.2:
```
>>> import pickle
>>>
>>> knowledge = {1:2, "fred": 19.3}
>>>
>>> with open("data.txt", 'wb') as FILE:
... pickle.dump(knowledge, FILE)
...
>>> knowledge2 = pickle.load(... |
how to uniqify a list of dict in python | 6,280,978 | 6 | 2011-06-08T15:04:29Z | 6,281,063 | 13 | 2011-06-08T15:09:43Z | [
"python"
] | I have a list:
```
d = [{'x':1, 'y':2}, {'x':3, 'y':4}, {'x':1, 'y':2}]
```
`{'x':1, 'y':2}` comes more than once I want to remove it from the list.My result should be:
```
d = [{'x':1, 'y':2}, {'x':3, 'y':4} ]
```
**Note:**
`list(set(d))` is not working here throwing an error. | If your value is hashable this will work:
```
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]
```
EDIT:
I tried it with no duplicates and it seemed to work fine
```
>>> d = [{'x':1, 'y':2}, {'x':3, 'y':4}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4,... |
How to apply multiple filters on a Django template variable? | 6,281,404 | 19 | 2011-06-08T15:34:48Z | 21,390,239 | 20 | 2014-01-27T19:48:48Z | [
"python",
"django"
] | For me this works:
> {{ game.description|safe }}
But this fails:
```
{{ game.description|safe|slice:"65" }}
```
Is there a way to apply two or more filters on a variable in Django templates? | Although it's quite past when the OP posted the question, but for other people that may need the info, this seems to work well for me:
You can rewrite
```
{{ game.description|safe|slice:"65" }}
```
as
```
{% with description=game.description|safe %}
{{description|slice:"65"}}
{% endwith %}
``` |
Assignment inside lambda expression in Python | 6,282,042 | 53 | 2011-06-08T16:23:36Z | 6,282,109 | 16 | 2011-06-08T16:29:16Z | [
"python",
"lambda",
"expression",
"variable-assignment"
] | I have a list of objects and I want to remove all objects that are empty except for one, using `filter` and a `lambda` expression.
For example if the input is:
```
[Object(name=""), Object(name="fake_name"), Object(name="")]
```
...then the output should be:
```
[Object(name=""), Object(name="fake_name")]
```
Is t... | There's no need to use a lambda, when you can remove *all* the null ones, and put one back if the input size changes:
```
input = [Object(name=""), Object(name="fake_name"), Object(name="")]
output = [x for x in input if x.name]
if(len(input) != len(output)):
output.append(Object(name=""))
``` |
Assignment inside lambda expression in Python | 6,282,042 | 53 | 2011-06-08T16:23:36Z | 14,617,232 | 134 | 2013-01-31T01:58:29Z | [
"python",
"lambda",
"expression",
"variable-assignment"
] | I have a list of objects and I want to remove all objects that are empty except for one, using `filter` and a `lambda` expression.
For example if the input is:
```
[Object(name=""), Object(name="fake_name"), Object(name="")]
```
...then the output should be:
```
[Object(name=""), Object(name="fake_name")]
```
Is t... | You can perform local assignments as a side effect of list comprehensions in Python 2.
```
import sys
say_hello = lambda: [
[None for message in ["Hello world"]],
sys.stdout.write(message + "\n")
][-1]
say_hello()
```
However, it's not possible to use this in your example because your variable `flag` is in an... |
Assignment inside lambda expression in Python | 6,282,042 | 53 | 2011-06-08T16:23:36Z | 14,624,285 | 21 | 2013-01-31T11:09:08Z | [
"python",
"lambda",
"expression",
"variable-assignment"
] | I have a list of objects and I want to remove all objects that are empty except for one, using `filter` and a `lambda` expression.
For example if the input is:
```
[Object(name=""), Object(name="fake_name"), Object(name="")]
```
...then the output should be:
```
[Object(name=""), Object(name="fake_name")]
```
Is t... | You cannot really maintain state in a `filter`/`lambda` expression (unless abusing the global namespace). You can however achieve something similar using the accumulated result being passed around in a `reduce()` expression:
```
>>> f = lambda a, b: (a.append(b) or a) if (b not in a) else a
>>> input = ["foo", u"", "b... |
Writing numerical values on the plot with Matplotlib | 6,282,058 | 17 | 2011-06-08T16:24:42Z | 6,282,664 | 19 | 2011-06-08T17:19:19Z | [
"python",
"matplotlib"
] | Is it possible, with Matplotlib, to print the values of each point on the graph?
For example, if I have:
```
x = numpy.range(0,10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
pyplot.plot(x,y)
```
How can I display y values on the plot (e.g. print a 5 near the (0,5) point, print a 3 near the (1,3) point, etc.)? | You can use the [annotate](http://matplotlib.sourceforge.net/users/annotations.html) command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this
```
import numpy
from matplotlib import pyplot
x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
... |
Opening the Excel application from Python | 6,282,230 | 3 | 2011-06-08T16:39:52Z | 6,282,392 | 7 | 2011-06-08T16:54:03Z | [
"python",
"excel",
"browser"
] | I am using 'xlwt' to write into Excel files as part of my project in Python. I also need to actually open the Excel spreadsheet for display and also close it. I found a function:
```
import webbrowser
webbrowser.open('C:/Users/300231823/Desktop/GUI/simplenew4.xls')
```
This seems to open the .xls file. How do I close... | ```
from win32com.client import Dispatch
xl = Dispatch("Excel.Application")
xl.Visible = True # otherwise excel is hidden
# newest excel does not accept forward slash in path
wb = xl.Workbooks.Open(r'C:\Users\300231823\Desktop\GUI\simplenew4.xls')
wb.Close()
xl.Quit()
```
The win32com module is part of [pywin32](htt... |
Load sparse array from npy file | 6,282,432 | 9 | 2011-06-08T16:57:01Z | 6,283,729 | 13 | 2011-06-08T18:53:12Z | [
"python",
"scipy",
"sparse-array"
] | I am trying load a sparse array that I have previously saved. Saving the sparse array was easy enough. Trying to read it though is a pain. scipy.load returns a 0d array around my sparse array.
```
import scipy as sp
A = sp.load("my_array"); A
array(<325729x325729 sparse matrix of type '<type 'numpy.int8'>'
with 149713... | The [mmwrite](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmwrite.html#scipy.io.mmwrite)/[mmread](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.mmread.html#scipy.io.mmread) functions in scipy.io can save/load sparse matrices in the Matrix Market format.
```
scipy.io.mmwrite('/tmp/my_arr... |
Python and Exceptions | 6,283,757 | 4 | 2011-06-08T18:55:20Z | 6,283,926 | 13 | 2011-06-08T19:12:02Z | [
"python",
"exception"
] | Coming from a Java background, I like it when I was warned that I was not catching an exception, without having to read the documentation. And if I did read the documentation about a method, the exception thrown was shown right in the documentation's method signature.
With Python I have to often read through a paragra... | We **love** exceptions. They're a pretty important language feature. Good documentation will generally state what exceptions will be thrown in which cases, and personally I found most documentation to be good in this regard. Of course there's always some percentage of documentation that isn't good. Either way, if you'r... |
permutations with unique values | 6,284,396 | 34 | 2011-06-08T19:51:59Z | 6,284,454 | 13 | 2011-06-08T19:57:16Z | [
"python",
"permutation",
"itertools"
] | itertools.permutations generates where its elements are treated as unique based on their position, not on their value. So basically I want to avoid duplicates like this:
```
>>> list(itertools.permutations([1, 1, 1]))
[(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]
```
Filtering afterwards is not p... | You could try using set:
```
>>> list(itertools.permutations(set([1,1,2,2])))
[(1, 2), (2, 1)]
```
The call to set removed duplicates |
permutations with unique values | 6,284,396 | 34 | 2011-06-08T19:51:59Z | 6,285,203 | 32 | 2011-06-08T20:59:58Z | [
"python",
"permutation",
"itertools"
] | itertools.permutations generates where its elements are treated as unique based on their position, not on their value. So basically I want to avoid duplicates like this:
```
>>> list(itertools.permutations([1, 1, 1]))
[(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]
```
Filtering afterwards is not p... | ```
class unique_element:
def __init__(self,value,occurrences):
self.value = value
self.occurrences = occurrences
def perm_unique(elements):
eset=set(elements)
listunique = [unique_element(i,elements.count(i)) for i in eset]
u=len(elements)
return perm_unique_helper(listunique,[0]*u... |
permutations with unique values | 6,284,396 | 34 | 2011-06-08T19:51:59Z | 6,285,330 | 8 | 2011-06-08T21:11:33Z | [
"python",
"permutation",
"itertools"
] | itertools.permutations generates where its elements are treated as unique based on their position, not on their value. So basically I want to avoid duplicates like this:
```
>>> list(itertools.permutations([1, 1, 1]))
[(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]
```
Filtering afterwards is not p... | This relies on the implementation detail that any permutation of a sorted iterable are in sorted order unless they are duplicates of prior permutations.
```
from itertools import permutations
def unique_permutations(iterable, r=None):
previous = tuple()
for p in permutations(sorted(iterable), r):
if p... |
PyCharm auto add import with autocomplete | 6,284,482 | 8 | 2011-06-08T19:59:23Z | 6,284,667 | 12 | 2011-06-08T20:13:05Z | [
"python",
"ide",
"pycharm"
] | I am giving PyCharm a try for the first time. Coming from an Eclipse/PyDev environment I have to say so far things have been going well.
There is one feature I am missing that I can't seem to find though and that is as follows:
In the auto-complete list in PyDev, when typing a symbol that doesn't exist in the file's ... | See **Settings** | **Editor** | **General** | [Auto Import](http://www.jetbrains.com/pycharm/webhelp/editor-auto-import.html). |
AVAudioRecorder doesn't write out proper WAV File Header | 6,284,651 | 6 | 2011-06-08T20:12:01Z | 6,618,826 | 23 | 2011-07-08T00:52:34Z | [
"python",
"ios",
"avaudiorecorder",
"wave"
] | I'm working on a project on the iPhone where I'm recording audio from the device mic using AVAudioRecorder, and then will be manipulating the recording.
To ensure that I'm reading in the samples from the file correctly, I'm using python's wave module to see if it returns the same samples.
However, python's wave modul... | Apple software often creates WAVE files with a non-standard (but "spec" conformant) `"FLLR"` subchunk after the `"fmt "` subchunk and before the `"data"` subchunk. I assume "FLLR" stands for "filler", and I assume the purpose of the subchunk is to enable some sort of data alignment optimization. The subchunk is usually... |
How to generate an URL with Pyramid and Akhet? | 6,285,071 | 2 | 2011-06-08T20:48:52Z | 6,286,595 | 7 | 2011-06-08T23:48:56Z | [
"python",
"url",
"pylons",
"pyramid",
"akhet"
] | I'm creating an [Akhet](http://docs.pylonsproject.org/projects/akhet/dev/index.html) (Pyramid) web application.
How can one generate in a mako template the URL for a given Handler/view ?
I'm looking for the equivalent of Pylons' `${url(controller="users", view="list")` | You need to use route\_url. It's available in the templates in request.route\_url.
```
<a href="${request.route_url('import')}">Import</a>
```
for example |
How to do math in a Django template? | 6,285,327 | 62 | 2011-06-08T21:10:51Z | 6,285,425 | 8 | 2011-06-08T21:19:32Z | [
"python",
"django"
] | I want to do this:
```
100 - {{object.article.rating_score}}
```
so for example, the output would be "20" if {{object.article.rating\_score}} equaled "80". How to do this at the template level? I don't have access to the python code. | Generally it is recommended you do this calculation in your view. Otherwise, you could use the add filter. |
How to do math in a Django template? | 6,285,327 | 62 | 2011-06-08T21:10:51Z | 6,285,428 | 92 | 2011-06-08T21:19:43Z | [
"python",
"django"
] | I want to do this:
```
100 - {{object.article.rating_score}}
```
so for example, the output would be "20" if {{object.article.rating\_score}} equaled "80". How to do this at the template level? I don't have access to the python code. | You can use the [`add`](https://docs.djangoproject.com/en/1.7/ref/templates/builtins/#add) filter:
```
{{ object.article.rating_score|add:"-100" }}
``` |
How to do math in a Django template? | 6,285,327 | 62 | 2011-06-08T21:10:51Z | 21,423,514 | 19 | 2014-01-29T06:17:39Z | [
"python",
"django"
] | I want to do this:
```
100 - {{object.article.rating_score}}
```
so for example, the output would be "20" if {{object.article.rating\_score}} equaled "80". How to do this at the template level? I don't have access to the python code. | Use [django-mathfilters](http://pypi.python.org/pypi/django-mathfilters). In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value.
For the specific example above, you would use `{{ 100|sub:object.article.rating_score }}`. |
How does extending classes (Monkey Patching) work in Python? | 6,286,006 | 12 | 2011-06-08T22:23:39Z | 6,286,119 | 11 | 2011-06-08T22:37:49Z | [
"python",
"oop",
"object",
"monkeypatching"
] | ```
class Foo(object):
pass
foo = Foo()
def bar(self):
print 'bar'
Foo.bar = bar
foo.bar() #bar
```
Coming from JavaScript, if a "class" prototype was augmented with a certain attribute. It is known that all instances of that "class" would have that attribute in its prototype chain, hence no modifications has to... | The real question is, how can it not? In Python, classes are first-class objects in their own right. Attribute access on instances of a class is resolved by looking up attributes on the instance, and then the class, and then the parent classes (in the method resolution order.) These lookups are all done at runtime (as ... |
How does extending classes (Monkey Patching) work in Python? | 6,286,006 | 12 | 2011-06-08T22:23:39Z | 6,286,634 | 10 | 2011-06-08T23:54:34Z | [
"python",
"oop",
"object",
"monkeypatching"
] | ```
class Foo(object):
pass
foo = Foo()
def bar(self):
print 'bar'
Foo.bar = bar
foo.bar() #bar
```
Coming from JavaScript, if a "class" prototype was augmented with a certain attribute. It is known that all instances of that "class" would have that attribute in its prototype chain, hence no modifications has to... | I just read through a bunch of documentation, and as far as I can tell, the *whole story* of how `foo.bar` is resolved, is as follows:
* Can we find `foo.__getattribute__` by the following process? If so, use the result of `foo.__getattribute__('bar')`.
+ (Looking up `__getattribute__` will not cause infinite recurs... |
Reading 32 bit signed ieee 754 floating points from a binary file with python? | 6,286,033 | 12 | 2011-06-08T22:25:59Z | 6,286,078 | 19 | 2011-06-08T22:30:46Z | [
"python",
"parsing",
"floating-point",
"binaryfiles",
"ieee-754"
] | I have a binary file which is simple a list of signed 32 bit ieee754 floating point numbers. They are not separated by anything, and simply appear one after another until EOF.
How would I read from this file and interpret them correctly as floating point numbers?
I tried using `read(4)`, but it automatically converts... | ```
struct.unpack('f', file.read(4))
```
You can also unpack several at once, which will be faster:
```
struct.unpack('f'*n, file.read(4*n))
``` |
Terminate multiple threads when any thread completes a task | 6,286,235 | 32 | 2011-06-08T22:53:44Z | 6,286,343 | 52 | 2011-06-08T23:07:58Z | [
"python",
"multithreading"
] | I am new to both python, and to threads. I have written python code which acts as a web crawler and searches sites for a specific keyword. My question is, how can I use threads to run three different instances of my class at the same time. When one of the instances finds the keyword, all three must close and stop crawl... | There doesn't seem to be a (simple) way to terminate a thread in Python.
Here is a simple example of running multiple HTTP requests in parallel:
```
import threading
def crawl():
import urllib2
data = urllib2.urlopen("http://www.google.com/").read()
print "Read google.com"
threads = []
for n in range(... |
Python mmap 'Permission denied' on Linux | 6,286,592 | 15 | 2011-06-08T23:48:13Z | 6,286,646 | 24 | 2011-06-08T23:56:54Z | [
"python",
"mmap",
"permission-denied"
] | I have a really large file I'm trying to open with mmap and its giving me permission denied. I've tried different flags and modes to the `os.open` but its just not working for me.
What am I doing wrong?
```
>>> import os,mmap
>>> mfd = os.open('BigFile', 0)
>>> mfile = mmap.mmap(mfd, 0)
Traceback (most recent call la... | I think its a flags issue, try opening as read only:
```
mfd = os.open('BigFile', os.O_RDONLY)
```
and mmap.mmap by default tries to map read/write, so just map read only:
```
mfile = mmap.mmap(mfd, 0, prot=mmap.PROT_READ)
``` |
Django: class views, generic views, etc | 6,286,826 | 3 | 2011-06-09T00:30:43Z | 6,287,132 | 7 | 2011-06-09T01:28:30Z | [
"python",
"django"
] | I'm coming back to Django after a brief encounter with version 1.2, and now in version 1.3 the favored approach to views seems to be using classes.
Keeping in mind code style, maintainability and modularity: when should I use classes, and when functions? Should I always extend from generic class views (there seems to ... | I find that class-based views help keep my code readable and streamlined.
Take, for example, the sample (function-based) view from the form documentation:
```
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST ... |
How well does your language support unicode in practice? | 6,286,922 | 7 | 2011-06-09T00:44:07Z | 6,286,969 | 8 | 2011-06-09T00:53:24Z | [
"python",
"ruby",
"node.js",
"lisp"
] | I'm looking into new languages, kind of craving for one where I no longer need to worry about charset problems amongst inordinate amounts of other niggles I have with PHP for a new project.
I tend to find Java too verbose and messy, and my not wanting to touch Windows with a 6-foot pole tends to rule out .Net. That le... | Python's unicode support did not really change in 3.x. The unicode *support* in Python has been pretty much the same since Python 2.x, which introduced the separate `unicode` type and the encoding handling. What Python 3.x changes is that unicode becomes the only string type (and is renamed to `str`), whereas 2.x has b... |
Python: Programmatically resize .jpgs | 6,286,964 | 2 | 2011-06-09T00:52:55Z | 6,287,104 | 7 | 2011-06-09T01:21:23Z | [
"java",
"c++",
"python",
"resize",
"jpeg"
] | I have a folder of .jpgs files that are all over 2MB in size. I need to upload them to a website but they are WAY too large to show on a website.
Is there a way to resize the actual images in Python &/or to reduce the file size of the jpgs in python.
**Maybe there is a native python library to work with bitmaps &/or ... | Can't get much easier than with [PIL](http://www.pythonware.com/library/pil/handbook/introduction.htm):
```
from PIL import Image
size = 300, 300
im = Image.open('image.jpg')
im.thumbnail(size, Image.ANTIALIAS) # thumbnail maintains aspect ratio
im.save('image_resized.jpg')
``` |
Parse JSON with Python | 6,287,092 | 2 | 2011-06-09T01:17:40Z | 6,287,099 | 13 | 2011-06-09T01:19:59Z | [
"python",
"json",
"parsing"
] | I'd like to parse
```
{"ticker":{"high":31.9099,"low":22.5,"vol":108468,"buy":29.61,"sell":30,"last":29.61}}
```
and end up with:
```
last = 29.61
```
but I don't know where to start parsing python :( | ```
>>> text = '''{"ticker":{"high":31.9099,"low":22.5,"vol":108468,"buy":29.61,"sell":30,"last":29.61}}'''
>>> json.loads(text)
{u'ticker': {u'sell': 30, u'buy': 29.609999999999999, u'last': 29.609999999999999, u'vol': 108468, u'high': 31.9099, u'low': 22.5}}
>>> json.loads(text)[u'ticker'][u'last']
29.609999999999999... |
Populating a Django DateTimeField with feedparser | 6,287,268 | 4 | 2011-06-09T01:57:58Z | 6,287,319 | 7 | 2011-06-09T02:05:37Z | [
"python",
"django",
"rss",
"date",
"feedparser"
] | I'm attempting to read my school's athletics/activities calendar, available in iCal or RSS format, into a Django Events model using feedparser.
Everything works, except the dates. Feedparser populates item.updated\_parsed with a "9-tuple" but I can't figure out how to make this into something Django will accept in a D... | Covert the `time.struct_time` object into a `datetime.datetime` object:
```
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(item['updated_parsed']))
``` |
python function of a default argument | 6,287,459 | 4 | 2011-06-09T02:30:49Z | 6,287,487 | 7 | 2011-06-09T02:34:09Z | [
"python",
"function",
"lambda",
"arguments"
] | How can I access `qux` inside methods? Do I really have to define it again inside the body of `foo()`, or is there a way to import it from `self`?
```
class Baz(object):
qux = lambda x : x + '_quux'
def foo(self, bar=qux('fred')):
print bar
print qux('waldo')
# NameError: global name... | If you want to be able to access a method off the class then you must use [`classmethod`](http://docs.python.org/library/functions.html#classmethod) or [`staticmethod`](http://docs.python.org/library/functions.html#staticmethod).
```
class Baz(object):
qux = staticmethod(lambda x : x + '_quux')
```
But [don't do th... |
How to find children of nodes using Beautiful Soup | 6,287,529 | 38 | 2011-06-09T02:40:37Z | 6,287,601 | 28 | 2011-06-09T02:51:50Z | [
"python",
"html",
"beautifulsoup"
] | I want to get all the `<a>` tags which are children of `<li>`
```
<div>
<li class="test">
<a>link1</a>
<ul>
<li>
<a>link2</a>
</li>
</ul>
</li>
</div>
```
I know how to find element with particular class like this
```
soup.find("li", { "class" : "test" })
```
But i don't know... | Try this
```
li = soup.find('li', {'class': 'text'})
children = li.findChildren()
for child in children:
print child
``` |
How to find children of nodes using Beautiful Soup | 6,287,529 | 38 | 2011-06-09T02:40:37Z | 15,892,793 | 45 | 2013-04-09T03:30:39Z | [
"python",
"html",
"beautifulsoup"
] | I want to get all the `<a>` tags which are children of `<li>`
```
<div>
<li class="test">
<a>link1</a>
<ul>
<li>
<a>link2</a>
</li>
</ul>
</li>
</div>
```
I know how to find element with particular class like this
```
soup.find("li", { "class" : "test" })
```
But i don't know... | Theres a super small section in the DOCs that shows how to find/find\_all **direct** children.
<http://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument>
in your case:
```
soup.find("li", { "class" : "test" },recursive=False)
soup.find_all("li", { "class" : "test" },recursive=False)
``` |
How to decompile an exe file compiled by py2exe? | 6,287,918 | 18 | 2011-06-09T03:55:36Z | 20,018,517 | 14 | 2013-11-16T12:35:01Z | [
"python",
"py2exe",
"decompiler"
] | How to decompile an exe file compiled by py2exe?
just one exe file, didn'n have any zip file.
how to decompile to pyc or pyo file? | You can use [unpy2exe](https://github.com/matiasb/unpy2exe) to extract the .pyc and then use [pyREtic](https://github.com/MyNameIsMeerkat/pyREtic/blob/master/docs/HOWTO.md) to get the source code. I guess you can read the HOWTO and understand how to use these programs, but basically you go to the location of unpy2exe.p... |
"'generator' object is not subscriptable" error | 6,288,016 | 10 | 2011-06-09T04:15:12Z | 6,288,032 | 12 | 2011-06-09T04:17:56Z | [
"python",
"generator"
] | I am getting this error when attempting to solve Project Euler Problem 11 for part of my code here.
```
for x in matrix:
p = 0
for y in x:
if p < 17:
currentProduct = int(y) * int(x[p + 1]) * int(x[p + 2]) * int(x[p + 3])
if currentProduct > highestProduct:
print... | Whatever `x` is is a `generator` object, but you are trying to access an element as though it were a list (`x[p + 1]`). If you put `x = list(x)` on a line before `for y in x`, this should fix it. |
What does the symbol "#!" mean in Python? | 6,288,855 | 9 | 2011-06-09T06:23:52Z | 6,288,867 | 17 | 2011-06-09T06:25:17Z | [
"python",
"shebang"
] | What does this line of code mean? Without it, my python3 http server can't understand and let the browser download an empty .py file (depend on the link to the .py file)
```
#! /usr/local/bin/python3
``` | It's not a Python thing, it a [hashbang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) (or shebang) line which indicates which interpreter should process the file.
The rules vary but, in its simplest form, a file with the name `xyz` (containing that as the first line), when run from the command line with `xyz`, wil... |
What does the symbol "#!" mean in Python? | 6,288,855 | 9 | 2011-06-09T06:23:52Z | 6,288,870 | 8 | 2011-06-09T06:25:26Z | [
"python",
"shebang"
] | What does this line of code mean? Without it, my python3 http server can't understand and let the browser download an empty .py file (depend on the link to the .py file)
```
#! /usr/local/bin/python3
``` | This is not a python specific notion, see <http://en.wikipedia.org/wiki/Shebang_(Unix>) |
What does the symbol "#!" mean in Python? | 6,288,855 | 9 | 2011-06-09T06:23:52Z | 6,288,873 | 7 | 2011-06-09T06:25:37Z | [
"python",
"shebang"
] | What does this line of code mean? Without it, my python3 http server can't understand and let the browser download an empty .py file (depend on the link to the .py file)
```
#! /usr/local/bin/python3
``` | It's the shebang/hashbang line and a Linux/UNIX thing, not Python-related at all.
When executing the file, the kernel will see the `#!` magic and use whatever comes after it to execute the script. The actual program that gets launched by the kernel will be `program-from-shebang script-file-path [script-args]`
Note th... |
python function as a function argument? | 6,289,646 | 42 | 2011-06-09T07:47:28Z | 6,289,656 | 43 | 2011-06-09T07:48:57Z | [
"python",
"function",
"arguments"
] | Can a python function be an argument of another function?
say:
```
def myfunc(anotherfunc, extraArgs):
# run anotherfunc and also pass the values from extraArgs to it
pass
```
So this is basically two questions:
1) is it allowed at all?
2) and if it is, how to use the function inside the other function? Would... | > Can a python function be an argument
> of another function?
Yes.
```
def myfunc(anotherfunc, extraArgs):
anotherfunc(*extraArgs)
```
To be more specific ... with various arguments ...
```
>>> def x(a,b):
... print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
... z(*t)
...
>>> y(x,("hello","manu... |
python function as a function argument? | 6,289,646 | 42 | 2011-06-09T07:47:28Z | 6,289,675 | 10 | 2011-06-09T07:50:29Z | [
"python",
"function",
"arguments"
] | Can a python function be an argument of another function?
say:
```
def myfunc(anotherfunc, extraArgs):
# run anotherfunc and also pass the values from extraArgs to it
pass
```
So this is basically two questions:
1) is it allowed at all?
2) and if it is, how to use the function inside the other function? Would... | Functions in Python are first-class objects. But your function definition [is a bit off](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).
```
def myfunc(anotherfunc, extraArgs, extraKwArgs):
return anotherfunc(*extraArgs, **extraKwArgs)
``` |
How to automatically reflect database to sqlalchemy declarative? | 6,290,162 | 25 | 2011-06-09T08:40:43Z | 6,307,733 | 51 | 2011-06-10T14:26:27Z | [
"python",
"sqlalchemy",
"declarative",
"auto-generate"
] | sqlautocode - has issues with many-to-many relations
sqlsoup - doesn't support relations
elixir - it's note auto-generate
Is there something else I could try? | In theory reflection in sqlalchemy should work for you. In this case I'm using an mssql database with two tables which have a simple Many-to-one relation:
"Tests" with fields:
* id
* testname
* author\_id (foreign key to the Users table, Users.id field)
"Users" with fields:
* id
* fullname
So the following should ... |
How to automatically reflect database to sqlalchemy declarative? | 6,290,162 | 25 | 2011-06-09T08:40:43Z | 6,438,598 | 17 | 2011-06-22T10:48:00Z | [
"python",
"sqlalchemy",
"declarative",
"auto-generate"
] | sqlautocode - has issues with many-to-many relations
sqlsoup - doesn't support relations
elixir - it's note auto-generate
Is there something else I could try? | Well I went through that, tried on Northwind database and it looks promising. Although, I had to add relationship field to be able to follow database relations.
Let's consider that I don't know relations between tables at the moment of starting the application so I need is a way to generate automatically.
```
import ... |
How to automatically reflect database to sqlalchemy declarative? | 6,290,162 | 25 | 2011-06-09T08:40:43Z | 17,651,301 | 16 | 2013-07-15T09:49:09Z | [
"python",
"sqlalchemy",
"declarative",
"auto-generate"
] | sqlautocode - has issues with many-to-many relations
sqlsoup - doesn't support relations
elixir - it's note auto-generate
Is there something else I could try? | You could use [sqlacodegen](https://pypi.python.org/pypi/sqlacodegen) to generate all the models from the database. However you need to take care of the foreign key manually. |
Numpy - square root of -1 leaves a small real part | 6,290,222 | 13 | 2011-06-09T08:46:47Z | 6,290,283 | 9 | 2011-06-09T08:51:26Z | [
"python",
"numpy",
"floating-point",
"square-root"
] | Perhaps this is an algorithmic issue, but the following piece of code
`numpy.power((-1+0j),0.5)`
produces the following output
`(6.1230317691118863e-17+1j)`
Analogous expressions e.g. `numpy.power(complex(-1),.5)` yield the same result, however - `numpy.sqrt(complex(-1))` yields the expected result of `1j`. Clearly... | It's a side effect of the implementation of `numpy.power()` for complex numbers. The stdlib exhibits the same issue.
```
>>> numpy.power(-1+0j, 0.5)
(6.123233995736766e-17+1j)
>>> cmath.exp(cmath.log(-1)/2)
(6.123233995736766e-17+1j)
``` |
Numpy - square root of -1 leaves a small real part | 6,290,222 | 13 | 2011-06-09T08:46:47Z | 6,293,302 | 15 | 2011-06-09T13:11:05Z | [
"python",
"numpy",
"floating-point",
"square-root"
] | Perhaps this is an algorithmic issue, but the following piece of code
`numpy.power((-1+0j),0.5)`
produces the following output
`(6.1230317691118863e-17+1j)`
Analogous expressions e.g. `numpy.power(complex(-1),.5)` yield the same result, however - `numpy.sqrt(complex(-1))` yields the expected result of `1j`. Clearly... | What happens is that the square root of -1 is calculated as exp(i phase/2), where the phase (of -1) is *approximately* Ï. In fact,
```
>>> import cmath, math
>>> z = -1+0j
>>> cmath.phase(z)
3.141592653589793
>>> math.cos(_/2)
6.123233995736766e-17
```
This shows that the phase of -1 is Ï only up to a few 1e-17; th... |
Python logging: use milliseconds in time format | 6,290,739 | 65 | 2011-06-09T09:30:08Z | 6,290,946 | 33 | 2011-06-09T09:47:58Z | [
"python",
"logging",
"time"
] | By default `logging.Formatter('%(asctime)s')` prints with the following format:
```
2011-06-09 10:54:40,638
```
where 638 is the millisecond. I need to change the comma to a dot:
```
2011-06-09 10:54:40.638
```
To format the time I can use:
```
logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)
```
howe... | **Please note [Craig McDaniel's solution](http://stackoverflow.com/a/7517430/190597) is clearly better.**
---
logging.Formatter's `formatTime` method looks like this:
```
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
els... |
Python logging: use milliseconds in time format | 6,290,739 | 65 | 2011-06-09T09:30:08Z | 7,517,430 | 144 | 2011-09-22T15:33:48Z | [
"python",
"logging",
"time"
] | By default `logging.Formatter('%(asctime)s')` prints with the following format:
```
2011-06-09 10:54:40,638
```
where 638 is the millisecond. I need to change the comma to a dot:
```
2011-06-09 10:54:40.638
```
To format the time I can use:
```
logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)
```
howe... | This should work too:
```
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
``` |
Change the default domain of Client() in unittest of Django | 6,291,120 | 9 | 2011-06-09T10:05:22Z | 6,291,428 | 16 | 2011-06-09T10:32:14Z | [
"python",
"django",
"unit-testing",
"django-views",
"django-unittest"
] | I am writing a unit test for Django views.
```
class TestLog(unittest.TestCase):
"""Test for Contact"""
def setUp(self):
self.c = Client()
try:
self.bob = User.objects.create_user("mojo","b@example.com", "bmojo")
except :
print ''
def test_get_emails(self):
... | Django's `Client` [extends `RequestFactory`](https://code.djangoproject.com/browser/django/trunk/django/test/client.py#L326) so you should be able to pass in extra params as keyword arguments.
Try:
```
response = self.c.get('/emails/html/upload', SERVER_NAME="mydomain.com")
``` |
What is the difference between an 'sdist' .tar.gz distribution and an python egg? | 6,292,652 | 10 | 2011-06-09T12:17:12Z | 6,292,860 | 10 | 2011-06-09T12:35:16Z | [
"python",
"egg",
"sdist"
] | I am a bit confused. There seem to be two different kind of Python packages, source distributions (setup.py sdist) and egg distributions (setup.py bdist\_egg).
Both seem to be just archives with the same data, the python source files. One difference is that `pip`, the most recommended package manager, is not able to i... | `setup.py sdist` creates a **source distribution**: it contains setup.py, the source files of your module/script (.py files or .c/.cpp for binary modules), your data files, etc. The result is an archive that can then be used to recompile everything on any platform.
`setup.py bdist` (and `bdist_*`) creates a **built di... |
Python, Printing multiple times, | 6,293,421 | 3 | 2011-06-09T13:20:56Z | 6,293,665 | 12 | 2011-06-09T13:38:15Z | [
"python"
] | How can I repeat a string multiple times, multiple times? I know I can use a for loop, but I would like to repeat a string `x` times per row, over `n` rows.
For example, if the user enters `2`, the output would be:
```
@@
@@
@@
@@
```
Where `x` equals 2, and `n` equals 4. | E.g. if you want to print something 10 times you can write this:
```
print "-"*10
```
or use a foor loop like suggested above:
```
for i in range(1,10):
print "-"
``` |
Can I use K-means algorithm on a string? | 6,293,637 | 9 | 2011-06-09T13:36:24Z | 6,293,942 | 7 | 2011-06-09T13:58:14Z | [
"python",
"algorithm",
"cluster-analysis",
"bioinformatics",
"k-means"
] | I am working on a python project where I study RNA structure evolution (represented as a string for example: "(((...)))" where the parenthesis represent basepairs). The point being is that I have an ideal structure and a population that evolves towards the ideal structure. I have implemented everything however I would ... | K-means only works with euclidean distance. Edit distances such as Levenshtein don't even obey the triangle inequality may obey the triangle inequality, but are not euclidian. For the sorts of metrics you're interested in, you're better off using a different sort of algorithm, such as Hierarchical clustering: <http://e... |
a text file circular buffer in python | 6,293,868 | 5 | 2011-06-09T13:53:10Z | 6,293,895 | 8 | 2011-06-09T13:54:51Z | [
"python",
"file",
"fifo",
"circular-buffer"
] | I need a python script implementing a circular buffer for rows in a text file limited to N rows like this:
```
row 1 -> pop
row 2
row 3
|
|
push -> row N
```
What's the best solution?
EDIT:
This script should create and maintain the text file which only contains the latest N... | Use [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque). It supports a `maxlen` parameter.
```
d = collections.deque(maxlen=10)
for line in f:
d.append(line)
# ...
``` |
How to find all occurrences of an element in a list? | 6,294,179 | 119 | 2011-06-09T14:12:36Z | 6,294,205 | 181 | 2011-06-09T14:13:57Z | [
"python",
"list"
] | [`index()`](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list? | You can use a list comprehension:
```
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
``` |
How to find all occurrences of an element in a list? | 6,294,179 | 119 | 2011-06-09T14:12:36Z | 6,294,221 | 7 | 2011-06-09T14:14:57Z | [
"python",
"list"
] | [`index()`](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list? | How about:
```
In [1]: l=[1,2,3,4,3,2,5,6,7]
In [2]: [i for i,val in enumerate(l) if val==3]
Out[2]: [2, 4]
``` |
How to find all occurrences of an element in a list? | 6,294,179 | 119 | 2011-06-09T14:12:36Z | 6,294,744 | 43 | 2011-06-09T14:47:02Z | [
"python",
"list"
] | [`index()`](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list? | While not a solution for lists directly, `numpy` really shines for this sort of thing:
```
import numpy as np
values = np.array([1,2,3,1,2,4,5,6,3,2,1])
searchval = 3
ii = np.where(values == searchval)[0]
```
returns:
```
ii ==>array([2, 8])
```
This can be significantly faster for lists (arrays) with a large numbe... |
How to find all occurrences of an element in a list? | 6,294,179 | 119 | 2011-06-09T14:12:36Z | 18,669,080 | 17 | 2013-09-07T02:29:52Z | [
"python",
"list"
] | [`index()`](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list? | A solution using `list.index`:
```
def indices(lst, element):
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset)
```
It's much faster than the list comprehension with `enumera... |
Python is converting double quotes to single quotes in new variable | 6,294,501 | 6 | 2011-06-09T14:32:11Z | 6,294,528 | 20 | 2011-06-09T14:34:16Z | [
"python"
] | I'm trying to save a variable with double quotes in python, because I need to pass the double quoted JSON to a template and single quotes wont work with what I'm doing. So I set the variable in python to:
```
json = {
"auth": {
"key": "auth-code-here"
},
"template_id": "id-here",
"redirect_url": "url-here"... | You should use a JSON module to do that. To Python, double- and single-quotes are interchangeable.
[Python has JSON abilities built in](http://docs.python.org/release/3.1.3/library/json.html). |
Mixins, multi-inheritance, constructors, and data | 6,294,867 | 4 | 2011-06-09T14:55:54Z | 6,295,095 | 7 | 2011-06-09T15:11:24Z | [
"python",
"multiple-inheritance",
"mixins"
] | I have a class:
```
class A(object):
def __init__(self, *args):
# impl
```
Also a "mixin", basically another class with some data and methods:
```
class Mixin(object):
def __init__(self):
self.data = []
def a_method(self):
# do something
```
Now I create a subclass of A with the... | I'm fairly new to OOP too, but what is the problem on this code:
```
class AWithMixin(A, Mixin):
def __init__(self, *args):
A.__init__(self, *args)
Mixin.__init__(self)
``` |
Mixins, multi-inheritance, constructors, and data | 6,294,867 | 4 | 2011-06-09T14:55:54Z | 8,329,377 | 9 | 2011-11-30T16:29:46Z | [
"python",
"multiple-inheritance",
"mixins"
] | I have a class:
```
class A(object):
def __init__(self, *args):
# impl
```
Also a "mixin", basically another class with some data and methods:
```
class Mixin(object):
def __init__(self):
self.data = []
def a_method(self):
# do something
```
Now I create a subclass of A with the... | ```
class A_1(object):
def __init__(self, *args, **kwargs):
print 'A_1 constructor'
super(A_1, self).__init__(*args, **kwargs)
class A_2(object):
def __init__(self, *args, **kwargs):
print 'A_2 constructor'
super(A_2, self).__init__(*args, **kwargs)
class B(A_1, A_2):
def _... |
Looping through a list from a specific key to the end of the list | 6,295,185 | 10 | 2011-06-09T15:17:49Z | 6,295,209 | 26 | 2011-06-09T15:19:16Z | [
"python"
] | in Python how do i loop through list starting at a key and not the beginning.
e.g.
```
l = ['a','b','c','d']
```
loop through `l` but starting at b e.g. `l[1]` | Just use [slicing](http://docs.python.org/tutorial/introduction.html#lists):
```
>>> l = ['a','b','c','d']
>>> for i in l[1:]:
... print i
...
b
c
d
```
It will generate a new list with the items before `1` removed:
```
>>> l[1:]
['b', 'c', 'd']
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.