title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to calculate the sum of all columns of a 2D numpy array (efficiently)
13,567,345
17
2012-11-26T14:55:05Z
13,567,388
30
2012-11-26T14:58:17Z
[ "python", "numpy" ]
Let's say I have the following 2D numpy array consisting of four rows and three columns: ``` >>> a = numpy.arange(12).reshape(4,3) >>> print(a) [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] ``` What would be an efficient way to generate a 1D array that contains the sum of all columns (like `[18, 22, 26]`)? Can thi...
Check out the documentation for [`numpy.sum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html), paying particular attention to the `axis` parameter. To sum over columns: ``` >>> import numpy as np >>> a = np.arange(12).reshape(4,3) >>> a.sum(axis=0) array([18, 22, 26]) ``` Or, to sum over rows: ``...
Passing csrftoken with python Requests
13,567,507
23
2012-11-26T15:04:28Z
13,569,789
34
2012-11-26T17:15:40Z
[ "python", "csrf", "python-requests" ]
How do you pass a csrftoken with the python module Requests? This is what I have but it's not working, and I'm not sure which parameter to pass it into (data, headers, auth...) ``` import requests from bs4 import BeautifulSoup URL = 'https://portal.bitcasa.com/login' client = requests.session(config={'verbose': sys....
You need to set the referrer to the same URL as the login page: ``` import sys import requests URL = 'https://portal.bitcasa.com/login' client = requests.session() # Retrieve the CSRF token first client.get(URL) # sets cookie csrftoken = client.cookies['csrf'] login_data = dict(username=EMAIL, password=PASSWORD, ...
Image overlay in 3d plot using python
13,570,287
6
2012-11-26T17:46:02Z
15,592,168
17
2013-03-23T21:17:10Z
[ "python", "3d", "matplotlib" ]
I have a 3d plot of lines generated by matplotlib. I want to overlay an image at a specific xy (or yz, xz) slice. How do I do that using python? Thanks. I have a simple 3d plot code as: ``` fig = plt.figure(1),<br> ax = Axes3D(fig)<br> ax.plot(f[:,0], f[:,1], f[:,2], color='r') ``` I also have an image "Im" (a 2d ar...
I did a 3d surface plot overlay on top of a background image once: ![3d surface plot on top of background image](http://i.stack.imgur.com/oyl6c.jpg) If this is similar to what you want, I could try to make a working example out of it. Alternatively, if you just want to display an image in 3d space, you can use a sur...
Using scipy fft and ifft to solve ordinary differential equation numerically
13,570,828
6
2012-11-26T18:22:25Z
13,635,867
11
2012-11-29T22:23:07Z
[ "python", "scipy", "fft", "ode", "ifft" ]
I have an `ordinary differential equation` in time domain as follows: ``` C*du/dt = -g*u + I ``` where `I = A*t/tau*exp^(1-t/tau)` in the freq domain: ``` u(w) = I(w)/(g*(1+C/g*j*w)) ``` `j` being the complex number `sqrt(-1)` hence i can get `u(t)` by going into the freq domain using [fast Fourier transform](htt...
The derivative of a sinusoid, or complex exponential, is directly proportional to its frequency, and phase shifted by `π/2`. For a complex exponential the phase shift is equivalent to multiplying by `j`. For example, `d/dt exp(j*Ω*t)` `== j*Ω * exp(j*Ω*t)` `== Ω * exp(j*π/2) * exp(j*Ω*t)` `== Ω * exp(j*(Ω*t + ...
How to recursively go through all subdirectories and read files?
13,571,134
19
2012-11-26T18:45:55Z
13,571,166
38
2012-11-26T18:48:15Z
[ "python", "file" ]
I have a root-ish directory containing multiple subdirectories, all of which contain a file name data.txt. What I would like to do is write a script that takes in the "root" directory, and then reads through all of the subdirectories and reads every "data.txt" in the subdirectories, and then writes stuff from every dat...
You need to use absolute paths, your `file` variable is just a local filename without a directory path. The `root` variable is that path: ``` with open('output.txt','w') as fout: for root, subFolders, files in os.walk(rootdir): if 'data.txt' in files: with open(os.path.join(root, 'data.txt'), '...
Why is my Kurtosis function not producing the same output as scipy.stats.kurtosis?
13,571,198
3
2012-11-26T18:50:16Z
13,571,278
8
2012-11-26T18:56:08Z
[ "python", "numpy", "statistics", "scipy" ]
I have a homework problem in which I'm supposed to write a function for Kurtosis as descirbed here: ![Kurtosis, where theta is the standard deviation](http://i.stack.imgur.com/ENQEN.png) The theta in the denominator is the standard deviation (square-root of the variance) and the x-with-the-bar in the numerator is the...
By default, [`scipy.stats.kurtosis()`](http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.kurtosis.html): 1. Computes *excess* kurtosis (i.e. subtracts 3 from the result). 2. Corrects for statistical biases (this affects some of the denominators). Both behaviours are configurable through optional a...
I need Selenium to open it's web browser in a larger resolution ( preferably maximized)
13,571,349
14
2012-11-26T19:02:07Z
15,417,185
22
2013-03-14T18:19:55Z
[ "python", "selenium", "selenium-webdriver" ]
I am using Selenium WebDriver and coding in Python I have looked all over the place and the best I could find were things written in different languages. I also tried to use the export tool on Selenium IDE but when I look at the data says that the function is not supported for export. EDIT: The reason I need the brow...
Selenium 2.31.0 ``` driver = webdriver.Firefox() # Resize the window to the screen width/height driver.set_window_size(300, 500) # Move the window to position x/y driver.set_window_position(200, 200) ```
I need Selenium to open it's web browser in a larger resolution ( preferably maximized)
13,571,349
14
2012-11-26T19:02:07Z
16,051,907
13
2013-04-17T05:04:20Z
[ "python", "selenium", "selenium-webdriver" ]
I am using Selenium WebDriver and coding in Python I have looked all over the place and the best I could find were things written in different languages. I also tried to use the export tool on Selenium IDE but when I look at the data says that the function is not supported for export. EDIT: The reason I need the brow...
``` browser = webdriver.Firefox() url= 'http://www.google.com/' browser.get(url) driver.maximize_window() ```
Python: For loop with files, how to grab the next line within forloop?
13,572,062
4
2012-11-26T19:52:17Z
13,572,081
7
2012-11-26T19:53:21Z
[ "python", "file", "for-loop" ]
I have a file that I want to get each line at a time, but once it gets to a specific line, I need to get the next few lines information. Here is a code sample: ``` rofile = open('foo.txt', 'r') for line in rofile: print line if(line.strip() == 'foo'): line = line.next() print line line...
You can use `iter` to convert your object into an iterable which supports `next`. ``` irofile = iter(rofile) for line in irofile: print line if(line == 'foo'): line = next(irofile) #BEWARE, This could raise StopIteration! print line ``` As pointed out in the comments, if your object is alread...
Change values in a numpy array
13,572,448
4
2012-11-26T20:17:17Z
13,572,485
21
2012-11-26T20:19:31Z
[ "python", "numpy" ]
Suppose you have a numpy array and a list: ``` >>> a = np.array([1,2,2,1]).reshape(2,2) >>> a array([[1, 2], [2, 1]]) >>> b = [0, 10] ``` I'd like to replace values in an array, so that 1 is replaced by 0, and 2 by 10. I found a similar problem here - <http://mail.python.org/pipermail//tutor/2011-September/08...
Well, I suppose what you need is ``` a[a==2] = 10 #replace all 2's with 10's ```
Change values in a numpy array
13,572,448
4
2012-11-26T20:17:17Z
13,572,640
8
2012-11-26T20:29:01Z
[ "python", "numpy" ]
Suppose you have a numpy array and a list: ``` >>> a = np.array([1,2,2,1]).reshape(2,2) >>> a array([[1, 2], [2, 1]]) >>> b = [0, 10] ``` I'd like to replace values in an array, so that 1 is replaced by 0, and 2 by 10. I found a similar problem here - <http://mail.python.org/pipermail//tutor/2011-September/08...
Instead of replacing the values one by one, it is possible to remap the entire array like this: ``` import numpy as np a = np.array([1,2,2,1]).reshape(2,2) # palette must be given in sorted order palette = [1, 2] # key gives the new values you wish palette to be mapped to. key = np.array([0, 10]) index = np.digitize(a...
Change values in a numpy array
13,572,448
4
2012-11-26T20:17:17Z
33,411,211
9
2015-10-29T10:05:51Z
[ "python", "numpy" ]
Suppose you have a numpy array and a list: ``` >>> a = np.array([1,2,2,1]).reshape(2,2) >>> a array([[1, 2], [2, 1]]) >>> b = [0, 10] ``` I'd like to replace values in an array, so that 1 is replaced by 0, and 2 by 10. I found a similar problem here - <http://mail.python.org/pipermail//tutor/2011-September/08...
Read-only array in numpy can be made writable: ``` nArray.flags.writeable = True ``` This will then allow assignment operations like this one: ``` nArray[nArray == 10] = 9999 # replace all 10's with 9999's ``` The real problem was not assignment itself but the writable flag.
How to get multiple class in one query using Beautiful Soup
13,572,676
2
2012-11-26T20:32:21Z
13,572,767
7
2012-11-26T20:39:38Z
[ "python", "html-parsing", "beautifulsoup" ]
I want to find td with class="s" or class="sb" in the following html ``` <tr bgcolor="#e5e5f3"><td class="sb" width="200" align="left">test1</td><td class="sb" align="right">5,774.0</td><td class="sb" align="right">4,481.0</td><td class="sb" align="right">5,444.0</td><td class="sb" align="right">6,615.0</td><td class=...
You can do this using beautiful soup's support for regular expressions. ``` import re soup = BeautifulSoup(urllib2.urlopen(url).read(),"lxml"); for item in soup.find_all("td", { "class" : re.compile(r"^(s|sb)$") }) ``` This regular expression matches: * `^` - the start of the string * `(s|sb)` - either the string `'...
Sort dictionary of dictionaries by value
13,573,123
9
2012-11-26T21:03:17Z
13,573,197
13
2012-11-26T21:09:10Z
[ "python", "dictionary", "pyqt" ]
I have this dictionary: ``` statuses = { 'pending' : {'status_for':'all', 'position':1}, 'cancelled' : {'status_for':'all','position':2}, 'approved' : {'status_for':'owner', 'position':1}, 'rejected - owner' : {'status_for':'owner', 'position':2}, 'accepted' ...
Would something like this work? Similar to the post you linked, this uses the `key` function of `sorted` to provide a custom sort order. `iteritems()` returns a `(key, value)` tuple, so that gets passed into `lambda (x, y): y['position']`, where `y['position']` is the value (your nested dictionary, keyed by the status)...
Sort dictionary of dictionaries by value
13,573,123
9
2012-11-26T21:03:17Z
13,573,231
7
2012-11-26T21:11:53Z
[ "python", "dictionary", "pyqt" ]
I have this dictionary: ``` statuses = { 'pending' : {'status_for':'all', 'position':1}, 'cancelled' : {'status_for':'all','position':2}, 'approved' : {'status_for':'owner', 'position':1}, 'rejected - owner' : {'status_for':'owner', 'position':2}, 'accepted' ...
``` In [232]: statuses = { 'pending' : {'status_for':'all', 'position':1}, 'cancelled' : {'status_for':'all','position':2}, 'approved' : {'status_for':'owner', 'position':1}, 'rejected - owner' : {'status_f...
create new list without changing the original list
13,573,507
4
2012-11-26T21:33:25Z
13,573,520
10
2012-11-26T21:34:34Z
[ "python", "list", "sorting" ]
I have a list : ``` L=[2,0,4,5] ``` and I want to create a new list without changing L itself: ``` K= [0,2,4,5] ``` but when I try: ``` K=L.sort() print(K) ``` it prints nothing, and if I try: ``` print(L) ``` it comes out : [0,2,4,5] why K is not =[0,2,4,5]? and how can I...
The following will make a sorted copy of `L` and assign it to `K`: ``` K = sorted(L) ``` [`sorted()`](http://docs.python.org/2/library/functions.html#sorted) is a builtin function. The reason `K = L.sort()` doesn't work is that `sort()` sorts the list *in place*, and returns `None`. This is why `L` ends up being mod...
How do Django forms sanitize text input to prevent SQL injection, XSS, etc?
13,574,043
2
2012-11-26T22:12:25Z
13,574,089
9
2012-11-26T22:15:58Z
[ "python", "django", "xss", "sql-injection" ]
I don't see any form input sanitization in Django's form code w/r/t handling raw text. How does Django ensure that user input is sanitized when going into the database? Does it do this at all to prevent SQL injection, etc?
User input is sanitized by the database driver automatically. Explicit user input sanitization is only ever required when you are trying to assemble a single string that contains both the SQL commands and also the data that you are trying to include; proper use of the Python DBAPI fully separates the commands and the ...
Construct pandas DataFrame from items in nested dictionary
13,575,090
22
2012-11-26T23:41:31Z
13,581,730
27
2012-11-27T10:05:17Z
[ "python", "dataframe", "pandas" ]
Suppose I have a nested dictionary 'user\_dict' with structure: **Level 1:** UserId (Long Integer) **Level 2:** Category (String) **Level 3:** Assorted Attributes (floats, ints, etc..) For example, an entry of this dictionary would be: ``` user_dict[12] = { "Category 1": {"att_1": 1, "att_2...
Up to two level nesting you can use `pd.DataFrame.from_dict()`, for three level nesting i used two steps. ``` In [57]: user_dict Out[57]: {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'}, 'Category 2': {'att_1': 23, 'att_2': 'another'}}, 15: {'Category 1': {'att_1': 10, 'att_2': 'foo'}, 'Category 2': {'att_1...
Recursive generators
13,575,168
4
2012-11-26T23:48:14Z
13,575,200
8
2012-11-26T23:51:20Z
[ "python", "recursion", "generator" ]
From time to time I find myself writing recursive generators in Python. Here is a [recent example](http://stackoverflow.com/a/13573935/367273): ``` def comb(input, lst = [], lset = set()): if lst: yield lst for i, el in enumerate(input): if lset.isdisjoint(el): for out in comb(input[i+1:], l...
> Every time I have to spell out the for: yield loop, it makes me cringe. Is this really the way to write recursive generators in Python, or are there superior (more idiomatic, more performant, etc) alternatives? There is a superior alternative: ``` yield from comb(...) ``` This does effectively the same thing as: ...
Django Application: Foreign Key pointing to an abstract class
13,575,754
3
2012-11-27T00:50:16Z
13,575,835
7
2012-11-27T00:58:12Z
[ "python", "django", "django-models" ]
I am trying to design a framework to help implement complex web flows. The framework would provide with abstract classes which could inherited and implemented by the sub-apps. Now, as you can see my abstract class Action has a Foreign Key with Stage. Since, it has a foreignkey it could not be made abstract due to which...
An abstract class is a class that doesn't exist. It is used as a basis for other classes. It is never never ever initialized. Something that does not exist cannot have a foreign key pointing at it! Something to look at, if you want to have a way to point at several different kinds of classes: [generic relations](http...
protoRPC: returning dict
13,576,140
2
2012-11-27T01:36:30Z
13,576,562
7
2012-11-27T02:34:47Z
[ "python", "google-app-engine", "protorpc" ]
How does one return a `dict` like object through `protoRPC` ? I tried using the `FieldList` to no avail. I only see the following field definitions: ``` 'IntegerField', 'FloatField', 'BooleanField', 'BytesField', 'StringField', 'MessageField', 'EnumField', ```
There are two scenarios: **1) Your `dict` has a well-defined schema:** This is the best use case for ProtoRPC and if possible you should try to fit it into a schema. In this case, you would use a `MessageField` with some `Message` class that matches the schema in your dictionary. For example, instead of ``` {'amount...
convert openCV image into PIL Image in Python (for use with Zbar library)
13,576,161
14
2012-11-27T01:39:55Z
13,576,190
7
2012-11-27T01:44:16Z
[ "python", "opencv", "python-imaging-library", "zbar" ]
I'm trying to use the Zbar library's QR code detection methods on images I extract with OpenCV's camera methods. Normally the QR code detection methods work with images (jpg, png, etc.) on my computer, but I guess the captured frames of OpenCV are different. Is there a way of making the captured frame into a PIL Imag...
I think I may have found the answer. I'll edit later with results. **OpenCV to PIL Image** ``` import Image, cv cv_im = cv.CreateImage((320,200), cv.IPL_DEPTH_8U, 1) pi = Image.fromstring("L", cv.GetSize(cv_im), cv_im.tostring()) ``` Source: <http://opencv.willowgarage.com/documentation/python/cookbook.html>
convert openCV image into PIL Image in Python (for use with Zbar library)
13,576,161
14
2012-11-27T01:39:55Z
18,158,998
24
2013-08-10T05:37:41Z
[ "python", "opencv", "python-imaging-library", "zbar" ]
I'm trying to use the Zbar library's QR code detection methods on images I extract with OpenCV's camera methods. Normally the QR code detection methods work with images (jpg, png, etc.) on my computer, but I guess the captured frames of OpenCV are different. Is there a way of making the captured frame into a PIL Imag...
With the python CV2, you can also do this: ``` import Image, cv2 cap = cv2.VideoCapture(0) # says we capture an image from a webcam _,cv2_im = cap.read() cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB) pil_im = Image.fromarray(cv2_im) pil_im.show() ```
Matplotlib - hiding specific ticks on x-axis
13,576,805
9
2012-11-27T03:09:00Z
13,583,251
15
2012-11-27T11:29:56Z
[ "python", "matplotlib", "plot", "axis-labels" ]
I am trying to hide the first and last x-axis tick text of my bar plot, which is '2004' and '2013'. Matplotlib automatically adds these in by default, even though my dataset is for 2005 to 2012, hence I'd prefer not to have 2004 and 2013 in my bar plot. I'm looking for some lines of code to select and hide these ticks....
Please, tell me if it's not what you want. ``` import sys, os import matplotlib.pyplot as plt path = sys.path[0] sizes = [(12,3,), (4,3,)] x = range(20) for i, size in enumerate(sizes): fig = plt.figure(figsize = size, dpi = 80, facecolor='white',edgecolor=None,linewidth=0.0, frameon=True, subplotpars=None) ...
Do Python regular expressions have an equivalent to Ruby's atomic grouping?
13,577,372
24
2012-11-27T04:23:50Z
13,577,411
37
2012-11-27T04:29:24Z
[ "python", "ruby", "regex" ]
Ruby's regular expressions have a feature called atomic grouping `(?>regexp)`, described [here](http://www.ruby-doc.org/core-1.9.3/Regexp.html#label-Atomic+Grouping), is there any equivalent in Python's `re` module?
Python does not directly support this feature, but you can emulate it by using a zero-width lookahead assert (`(?=RE)`), which matches from the current point with the same semantics you want, putting a named group (`(?P<name>RE)`) inside the lookahead, and then using a named backreference (`(?P=name)`) to match exactly...
Do Python regular expressions have an equivalent to Ruby's atomic grouping?
13,577,372
24
2012-11-27T04:23:50Z
13,577,428
7
2012-11-27T04:31:56Z
[ "python", "ruby", "regex" ]
Ruby's regular expressions have a feature called atomic grouping `(?>regexp)`, described [here](http://www.ruby-doc.org/core-1.9.3/Regexp.html#label-Atomic+Grouping), is there any equivalent in Python's `re` module?
According to [this table](http://www.regular-expressions.info/refflavors.html), the answer is no. A [RFE](http://bugs.python.org/issue433030) was created to add it to Python 3, but was declined in favor of the new [`regex`](http://pypi.python.org/pypi/regex) module, which supports it: ``` >>> import regex >>> regex.ma...
how to create virtualenv with pypy?
13,578,593
24
2012-11-27T06:32:28Z
13,578,892
20
2012-11-27T06:54:59Z
[ "python", "virtualenv", "pypy" ]
running the following command ``` virtualenv -p /usr/local/bin/pypy pypy ``` exits with error like ``` Running virtualenv with interpreter /usr/local/bin/pypy New pypy executable in pypy/bin/pypy debug: WARNING: Library path not found, using compiled-in sys.path. debug: WARNING: 'sys.prefix' will not be set. debug: ...
This appears to be a regression in 1.8.4. While trying this out on my system everything worked fine with virtualenv 1.8.2, then I upgraded and now I get the same error as you.
Case-insensitive string startswith in Python
13,578,916
24
2012-11-27T06:57:02Z
13,578,943
23
2012-11-27T06:59:08Z
[ "python", "string", "performance", "case-insensitive", "startswith" ]
Here is how I check whether `mystring` begins with some string: ``` >>> mystring.lower().startswith("he") True ``` The problem is that `mystring` is very long (thousands of characters), so the `lower()` operation takes a lot of time. **QUESTION:** Is there a more efficient way? My unsuccessful attempt: ``` >>> imp...
You could use a regular expression as follows: ``` In [33]: bool(re.match('he', 'Hello', re.I)) Out[33]: True In [34]: bool(re.match('el', 'Hello', re.I)) Out[34]: False ``` On a 2000-character string this is about 20x times faster than `lower()`: ``` In [38]: s = 'A' * 2000 In [39]: %timeit s.lower().startswith(...
Case-insensitive string startswith in Python
13,578,916
24
2012-11-27T06:57:02Z
13,578,990
13
2012-11-27T07:02:10Z
[ "python", "string", "performance", "case-insensitive", "startswith" ]
Here is how I check whether `mystring` begins with some string: ``` >>> mystring.lower().startswith("he") True ``` The problem is that `mystring` is very long (thousands of characters), so the `lower()` operation takes a lot of time. **QUESTION:** Is there a more efficient way? My unsuccessful attempt: ``` >>> imp...
How about this: ``` prefix = 'he' if myVeryLongStr[:len(prefix)].lower() == prefix.lower() ```
amazon s3 The specified key does not exist after get_key success
13,580,335
7
2012-11-27T08:46:07Z
13,602,018
7
2012-11-28T09:39:55Z
[ "python", "web-services", "amazon-s3", "amazon-web-services", "boto" ]
I am using python and boto this is my code: ``` key = bucket.get_key(key_name) if not key: print 'error, key does not exist' return data = key.get_contents_as_string() ``` sometimes (appears randomly) i get this exception: > S3ResponseError: S3ResponseError: 404 Not Found NOTE: the file is uploaded by one ...
This is expected behaviour, according to [Amazon S3 developer guide](http://docs.amazonwebservices.com/AmazonS3/latest/dev/Introduction.html#ConsistencyMode): > ... However, information about the changes might not immediately replicate across Amazon S3 and you might observe the following behaviors: A process writes a ...
AttributeError: 'module' object (scipy) has no attribute 'misc'
13,581,593
20
2012-11-27T09:58:31Z
13,581,936
32
2012-11-27T10:15:51Z
[ "python", "scipy" ]
I updated from ubuntu 12.04 to ubuntu 12.10 and the python module I have written suddenly no longer works with the error message that the module scipy does not have the attribute 'misc'. This worked previously. I am still using python 2.7 after the update. Here is where the code crashes ``` import scipy scipy.misc.ims...
``` >>> import scipy >>> scipy.misc Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'misc' >>> >>> >>> import scipy.misc >>> scipy.misc.imsave <function imsave at 0x19cfa28> >>> ``` Which seems to be quite common with `scipy`.
Deduce the type of data in a string
13,582,142
2
2012-11-27T10:26:05Z
13,582,201
8
2012-11-27T10:29:32Z
[ "python", "data-type-conversion" ]
I would like to try to deduce the type of data in a string. **Scenario:** I have a CSV file which contains rows of data, and I would like to store this data in a database. I do not want to store all the fields as strings. Since the fields in the CSV might change, I cannot assume anything about their types. **Ex...
Use [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval) on the value; it'll interpret it as a python literal. If that fails, you have a string instead. ``` >>> import ast >>> ast.literal_eval("45.5") 45.5 >>> ast.literal_eval("3") 3 >>> ast.literal_eval("John") Traceback (most recent cal...
Convert DataFrameGroupBy object to DataFrame pandas
13,582,449
18
2012-11-27T10:43:07Z
13,583,024
11
2012-11-27T11:16:51Z
[ "python", "pandas" ]
I had a dataframe and did a groupby in FIPS and summed the groups that worked fine. ``` kl = ks.groupby('FIPS') kl.aggregate(np.sum) ``` I just want a normal Dataframe back but I have a `pandas.core.groupby.DataFrameGroupBy` object. There is a question that sounds like this one but it is not the same.
The **result** of `kl.aggregate(np.sum)` is a normal DataFrame, you just have to assign it to a variable to further use it. With some random data: ``` >>> df = DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', >>> 'foo', 'bar', 'foo', 'foo'], ... 'B' : ['one', 'one', 'two', 'three'...
How to zoomed a portion of image and insert in the same plot in matplotlib
13,583,153
22
2012-11-27T11:24:35Z
13,586,069
15
2012-11-27T14:11:26Z
[ "python", "image", "matplotlib" ]
I would like to zoom a portion of data/image and plot it inside the same figure. It looks something like this figure. ![zoomed plot](http://i.stack.imgur.com/ph8Tk.png) Is it possible to insert a portion of zoomed image inside the same plot. I think it is possible to draw another figure with subplot but it draws two ...
Playing with runnable code is one of the fastest ways to learn Python. So let's start with the [code from the matplotlib example gallery](http://matplotlib.org/examples/pylab_examples/axes_demo.html). Given the comments in the code, it appears the code is broken up into 4 main stanzas. The first stanza generates some...
How to zoomed a portion of image and insert in the same plot in matplotlib
13,583,153
22
2012-11-27T11:24:35Z
22,989,034
10
2014-04-10T13:09:12Z
[ "python", "image", "matplotlib" ]
I would like to zoom a portion of data/image and plot it inside the same figure. It looks something like this figure. ![zoomed plot](http://i.stack.imgur.com/ph8Tk.png) Is it possible to insert a portion of zoomed image inside the same plot. I think it is possible to draw another figure with subplot but it draws two ...
The nicest way I know of to do this is to use mpl\_toolkits.axes\_grid1.inset\_locator (part of matplotlib). There is a great example with source code here: ![enter image description here](http://i.stack.imgur.com/RTBu5.png)<http://nellev.github.io/tmp/jhepc/2013/entry10/index.html>.
How to zoomed a portion of image and insert in the same plot in matplotlib
13,583,153
22
2012-11-27T11:24:35Z
23,762,295
15
2014-05-20T14:16:51Z
[ "python", "image", "matplotlib" ]
I would like to zoom a portion of data/image and plot it inside the same figure. It looks something like this figure. ![zoomed plot](http://i.stack.imgur.com/ph8Tk.png) Is it possible to insert a portion of zoomed image inside the same plot. I think it is possible to draw another figure with subplot but it draws two ...
The simplest way is to combine "zoomed\_inset\_axes" and "mark\_inset", whose description and related examples could be found here: [Overview of AxesGrid toolkit](http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html) ![enter image description here](http://i.stack.imgur.com/bMlhM.png)
How would you install a python module with chef?
13,583,649
4
2012-11-27T11:50:45Z
24,829,453
12
2014-07-18T16:07:22Z
[ "python", "chef", "engineyard" ]
We're using EngineYard which has Python installed by default. But when we enabled SSL we received the following error message from our logentries chef recipe. "WARNING: The "ssl" module is not present. Using unreliable workaround, host identity cannot be verified. Please install "ssl" module or newer version of Python...
There now appears to be a solution with better community support (based on the fact that it is documented on the [opscode website](http://docs.opscode.com/lwrp_python.html)). You might try: ``` include_recipe 'python' python_pip 'ssl' ``` As documented: [here](https://supermarket.getchef.com/cookbooks/python) or [he...
How to use symbolic group name using re.findall()
13,585,336
7
2012-11-27T13:30:49Z
13,585,419
9
2012-11-27T13:34:37Z
[ "python", "regex", "match", "findall" ]
Is it possible to access the symbolic group name defined in a regular expression with `(?P<toto>...)` with the equivalent of `re.findall()`? Using `re.match()`, re returns a `MatchObject` on which the function `.group('toto')` can be used... I would like to do something close. Here is an example : ``` import re my_s...
You can't do that with `.findall()`. However, you *can* achieve the same effect with [`.finditer()`](http://docs.python.org/2/library/re.html#re.finditer) and some list comprehension magic: ``` print [m.groupdict() for m in re.finditer('toto=(?P<toto>\d+)\,\sbip=(?P<bip>\w+)', my_str)] ``` This prints: ``` [{'toto':...
Flask-WTFform: Flash does not display errors
13,585,663
6
2012-11-27T13:48:10Z
13,587,339
10
2012-11-27T15:20:20Z
[ "python", "flask", "wtforms" ]
I'm trying to flash WTForm validation errors. I found [this snippet](http://flask.pocoo.org/snippets/12/) and slightly modified it: ``` def flash_errors(form): """Flashes form errors""" for field, errors in form.errors.items(): for error in errors: flash(u"Error in the %s field - %s" % ( ...
**There are no errors yet because you haven't processed the form yet** Try putting the `flash_errors` on the `else` of the `validate_on_submit` method ``` @app.route("/contact/", methods=("GET", "POST")) def contact(): """Contact view""" form = ContactForm() if form.validate_on_submit(): sender = ...
How to launch EC2 instance with Boto, specifying size of EBS?
13,585,857
21
2012-11-27T13:59:36Z
13,604,274
33
2012-11-28T11:43:04Z
[ "python", "amazon-web-services", "amazon-ec2", "boto" ]
I'm using boto/python to launch a new EC2 instance that boots from an EBS volume. At the time I launch the instance, I'd like to override the default size of the booting EBS volume. I found no boto methods or parameters that might fit into my launch code: ``` ec2 = boto.connect_ec2( ACCESS_KEY, SECRET_KEY, region=reg...
You have to create a block device mapping first: ``` dev_sda1 = boto.ec2.blockdevicemapping.EBSBlockDeviceType() dev_sda1.size = 50 # size in Gigabytes bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping() bdm['/dev/sda1'] = dev_sda1 ``` After this you can give the block device map in your `run_instances` call: ```...
Extract external contour or silhouette of image in Python
13,586,686
4
2012-11-27T14:44:13Z
13,587,497
10
2012-11-27T15:29:13Z
[ "python", "image-processing", "matplotlib" ]
I want to extract the silhouette of an image, and I'm trying to do it using the contour function of MatplotLib. This is my code: ``` from PIL import Image from pylab import * # read image to array im = array(Image.open('HOJA.jpg').convert('L')) # create a new figure figure() # show contours with origin upper left c...
If you want to stick with your contour approach you can simply add a levels argument with a value 'thresholding' the image between the white background and the leaf. You could use the histogram to find an appropriate value. But in this case any value slightly lower than 255 will do. So: ``` contour(im, levels=[245],...
Minify HTML output from Flask application with Jinja2 templates
13,587,531
11
2012-11-27T15:31:00Z
13,588,062
7
2012-11-27T15:57:39Z
[ "python", "web-applications", "flask", "wsgi", "jinja2" ]
Is there a Flask or Jinja2 configuration flag / extension to automatically minify the HTML output after rendering the template?
Have a look here <https://github.com/cobrateam/django-htmlmin#using-the-html_minify-function> I realise it is mainly used for django but the example shows how to use this projects code to do what you want with a flask view, i think.
Minify HTML output from Flask application with Jinja2 templates
13,587,531
11
2012-11-27T15:31:00Z
26,139,704
13
2014-10-01T10:53:07Z
[ "python", "web-applications", "flask", "wsgi", "jinja2" ]
Is there a Flask or Jinja2 configuration flag / extension to automatically minify the HTML output after rendering the template?
Found a better way to do this. You can minify all your pages with this method: ``` from flask import Flask from htmlmin.main import minify app = Flask(__name__) @app.after_request def response_minify(response): """ minify html response to decrease site traffic """ if response.content_type == u'text/...
Invoking python under CygWin on Windows hangs
13,588,454
21
2012-11-27T16:17:28Z
13,588,963
20
2012-11-27T16:45:06Z
[ "python", "cygwin" ]
Installing a new Windows system, I've installed CygWin and 64 bit Python (2.7.3) in their default locations (`c:\cygwin` and `c:\Python27\python`), and added both the CygWin bin and the Python directory to my path (in the user variable PATH). From the normal command window, Python starts up perfectly, but when I invoke...
The problem is that due to the way that the Cygwin terminal (MinTTY) behaves, the native Windows build of Python doesn't realize that stdout is a terminal device -- it thinks it's a pipe, so it runs in non-interactive mode instead of interactive mode, and it fully buffers its output instead of line-buffering it. The r...
Invoking python under CygWin on Windows hangs
13,588,454
21
2012-11-27T16:17:28Z
18,675,890
26
2013-09-07T17:17:29Z
[ "python", "cygwin" ]
Installing a new Windows system, I've installed CygWin and 64 bit Python (2.7.3) in their default locations (`c:\cygwin` and `c:\Python27\python`), and added both the CygWin bin and the Python directory to my path (in the user variable PATH). From the normal command window, Python starts up perfectly, but when I invoke...
Try this ``` python -i ``` and yes you will find some glitches here and there !!!
Invoking python under CygWin on Windows hangs
13,588,454
21
2012-11-27T16:17:28Z
23,164,293
7
2014-04-19T00:18:09Z
[ "python", "cygwin" ]
Installing a new Windows system, I've installed CygWin and 64 bit Python (2.7.3) in their default locations (`c:\cygwin` and `c:\Python27\python`), and added both the CygWin bin and the Python directory to my path (in the user variable PATH). From the normal command window, Python starts up perfectly, but when I invoke...
I had a similar issue with Mercurial (hg)+OpenSSH, Python and MinTTY, but under MSYS instead of CygWin. Nonetheless, as far as I can tell, both this and my issue were caused by MinTTY not being to handle applications that uses the native Windows console functions (in an answer here by Adam, he explained it in detail fo...
How to use numpy.where with logical operators
13,589,390
17
2012-11-27T17:10:18Z
13,589,551
30
2012-11-27T17:19:36Z
[ "python", "numpy", "where", "logical-operators" ]
I'm trying to find the indices of all elements in an array that are greater than a but less than b. It's probably just a problem with my syntax but this doesn't work: ``` numpy.where((my_array > a) and (my_array < b)) ``` How should I fix this? Or is there a better way to do it? Thanks!
Here are two ways: ``` In [1]: my_array = arange(10) In [2]: where((my_array > 3) & (my_array < 7)) Out[2]: (array([4, 5, 6]),) In [3]: where(logical_and(my_array > 3, my_array < 7)) Out[3]: (array([4, 5, 6]),) ``` For the first (replacing `and` with `&`), be careful to add parentheses appropriately: `&` has higher...
Is there a better way to write this "if" boolean evaluation?
13,589,811
12
2012-11-27T17:31:55Z
13,589,849
30
2012-11-27T17:34:11Z
[ "python", "if-statement" ]
I have this small snippet of python code that I wrote. It works, but I think there should be a more streamlined method to achieve the same results. I'm just not seeing it. Any ideas? ``` if tx_avt >= 100: tx = 1 elif tx_avt < 100 and tx_avt >= 50: tx = 2 elif tx_avt < 50 and tx_avt >= 25: tx = 3 elif tx_avt < 25 and...
You can change it to: ``` if tx_avt >= 100: tx = 1 elif tx_avt >= 50: tx = 2 elif tx_avt >= 25: tx = 3 elif tx_avt >= 12.5: tx = 4 else: tx = 5 ``` **Explanation:** * If `if tx_avt >= 100` is not true, then you can deduce that `tx_avt < 100` **must** be true. * This eliminates the need to do the "`tx_avt < 100`" ...
Is there a better way to write this "if" boolean evaluation?
13,589,811
12
2012-11-27T17:31:55Z
13,589,858
11
2012-11-27T17:34:45Z
[ "python", "if-statement" ]
I have this small snippet of python code that I wrote. It works, but I think there should be a more streamlined method to achieve the same results. I'm just not seeing it. Any ideas? ``` if tx_avt >= 100: tx = 1 elif tx_avt < 100 and tx_avt >= 50: tx = 2 elif tx_avt < 50 and tx_avt >= 25: tx = 3 elif tx_avt < 25 and...
you dont need the upper bounds on the elifs since these are resolved by the clause above them ... ``` elif tx_avt >= 50 : #do something elif tx_avt >= 25 : #somthing else ``` on a side note in python you can do ``` if 3 < ab < 10 : #check if ab is between 3 and 10 ```
Is there a better way to write this "if" boolean evaluation?
13,589,811
12
2012-11-27T17:31:55Z
13,589,876
8
2012-11-27T17:36:07Z
[ "python", "if-statement" ]
I have this small snippet of python code that I wrote. It works, but I think there should be a more streamlined method to achieve the same results. I'm just not seeing it. Any ideas? ``` if tx_avt >= 100: tx = 1 elif tx_avt < 100 and tx_avt >= 50: tx = 2 elif tx_avt < 50 and tx_avt >= 25: tx = 3 elif tx_avt < 25 and...
If your if-elif-else chain gets really long you can use this method: ``` for amt, tx in [(100, 1), (50, 2), (25, 3), (12.5, 4)]: if tx_avt >= amt: break else: tx = 5 ``` **note:** The `else` clause of a `for` loop is executed when `break` has not been encountered. In this case it is used to provide th...
Reading Unicode file data with BOM chars in Python
13,590,749
16
2012-11-27T18:32:28Z
13,591,421
27
2012-11-27T19:16:19Z
[ "python", "unicode" ]
I'm reading a series of source code files using Python and running into a unicode BOM error. Here's my code: ``` bytes = min(32, os.path.getsize(filename)) raw = open(filename, 'rb').read(bytes) result = chardet.detect(raw) encoding = result['encoding'] infile = open(filename, mode, encoding=encoding) data = infile.r...
BOM characters should be automatically stripped when decoding UTF-16, but not UTF-8, unless you explicitly use the `utf-8-sig` encoding. You could try something like this: ``` import io import chardet import codecs bytes = min(32, os.path.getsize(filename)) raw = open(filename, 'rb').read(bytes) if raw.startswith(co...
Reading Unicode file data with BOM chars in Python
13,590,749
16
2012-11-27T18:32:28Z
24,370,596
8
2014-06-23T16:14:18Z
[ "python", "unicode" ]
I'm reading a series of source code files using Python and running into a unicode BOM error. Here's my code: ``` bytes = min(32, os.path.getsize(filename)) raw = open(filename, 'rb').read(bytes) result = chardet.detect(raw) encoding = result['encoding'] infile = open(filename, mode, encoding=encoding) data = infile.r...
I've composed a nifty BOM-based detector based on Chewie's answer. It's sufficient in the common use case where data can be either in a known local encoding or Unicode with BOM. (that's what text editors typically produce): ``` def detect_by_bom(path,default): with open(path, 'rb') as f: raw = f.read(4) ...
Does Python optimize tail recursion?
13,591,970
84
2012-11-27T19:53:41Z
13,592,002
95
2012-11-27T19:55:43Z
[ "python", "recursion", "stack", "stack-overflow", "tail-recursion" ]
I have the following piece of code which fails with the following error: > RuntimeError: maximum recursion depth exceeded I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been successful if a TCO had taken place. ``` def trisum(n, csum): if n == 0: ...
No, and it never will since Guido prefers to be able to have proper tracebacks <http://neopythonic.blogspot.com.au/2009/04/tail-recursion-elimination.html> <http://neopythonic.blogspot.com.au/2009/04/final-words-on-tail-calls.html> You can manually eliminate the recursion with a transformation like this ``` >>> def...
Does Python optimize tail recursion?
13,591,970
84
2012-11-27T19:53:41Z
13,592,014
17
2012-11-27T19:56:53Z
[ "python", "recursion", "stack", "stack-overflow", "tail-recursion" ]
I have the following piece of code which fails with the following error: > RuntimeError: maximum recursion depth exceeded I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been successful if a TCO had taken place. ``` def trisum(n, csum): if n == 0: ...
The word of Guido is at <http://neopythonic.blogspot.co.uk/2009/04/tail-recursion-elimination.html> > I recently posted an entry in my Python History blog on the origins of > Python's functional features. A side remark about not supporting tail > recursion elimination (TRE) immediately sparked several comments about >...
Does Python optimize tail recursion?
13,591,970
84
2012-11-27T19:53:41Z
18,506,625
50
2013-08-29T09:08:18Z
[ "python", "recursion", "stack", "stack-overflow", "tail-recursion" ]
I have the following piece of code which fails with the following error: > RuntimeError: maximum recursion depth exceeded I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been successful if a TCO had taken place. ``` def trisum(n, csum): if n == 0: ...
**Edit (2015-07-02):** *With the time, my answer has became quite popular and since it was initially more a link than anything else, I decided to take some time and re-write it fully (however, the initial answer can be found at the end).* **Edit (2015-07-12):** I finally published a module performing tail-call optimiz...
Compiling pygraphviz: Unrecognized command line option '-mno-cygwin'
13,592,192
15
2012-11-27T20:08:37Z
13,843,945
17
2012-12-12T16:14:34Z
[ "python", "mingw32", "pygraphviz" ]
On Windows 7, when trying to compile pygraphviz, I run ``` python setup.py build -c mingw32 ``` I get > C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall "-IC:\Program Files (x86)\Graphv > iz 2.28\include\graphviz" -Ic:\Python27\include -Ic:\Python27\PC -c pygraphviz/g > raphviz\_wrap.c -o build\temp.win-amd64-2.7...
See this answer: <http://stackoverflow.com/a/6035864/1516291> In short, you may need to modify `distutils\cygwinccompiler.py` in your python installation dir to remove traces of `-mno-cygwin`.
Launch a totally independent process from Python
13,592,219
21
2012-11-27T20:10:19Z
13,593,715
18
2012-11-27T21:46:54Z
[ "python", "windows-installer", "popen" ]
I'm trying to launch a completely independent process from python. I can't use something simple like os.startfile since I need to pass arguments. Currently I'm using subprocess.popen which gets me 90% of the way there. ``` args = ["some_exe.exe", "some_arg", "another_arg"] subprocess.Popen(args, creationflags=DETACHED...
I think I found the answer. By using `Popen` with `close_fds = True` I was able to start up a process that was independent and without handles to the parent. For docs look [here](http://docs.python.org/2/library/subprocess.html) and search for `close_fds`. > Or, on Windows, if close\_fds is true then no handles will ...
python pandas dataframe thread safe?
13,592,618
4
2012-11-27T20:38:31Z
13,593,942
8
2012-11-27T22:01:48Z
[ "python", "thread-safety", "pandas" ]
I am using multiple threads to access and delete data in my pandas dataframe. Because of this, I am wondering is pandas dataframe threadsafe? Thanks! Andrew
The data in the underlying ndarrays can be accessed in a threadsafe manner, and modified at your own risk. Deleting data would be difficult as changing the size of a DataFrame usually requires creating a new object. I'd like to change this at some point in the future.
Making sure a Python script with subprocesses dies on SIGINT
13,593,223
24
2012-11-27T21:17:04Z
13,737,455
17
2012-12-06T05:23:30Z
[ "python", "signals" ]
I've got a command that I'm wrapping in `script` and spawning from a Python script using `subprocess.Popen`. I'm trying to make sure it dies if the user issues a `SIGINT`. I could figure out if the process was interrupted in a least two ways: A. Die if the wrapped command has a non-zero exit status (doesn't work, bec...
The subprocess is by default part of the same process group, and only one can control and receive signals from the terminal, so there are a couple of different solutions. **Setting stdin as a PIPE** (in contrast to inheriting from the parent process), this will prevent the child process from receiving signals associat...
getting dynamic attribute in python
13,595,690
9
2012-11-28T00:23:49Z
13,595,755
16
2012-11-28T00:30:28Z
[ "python", "getattr" ]
I have and object with an *pseudo* or *special* attribute that can be named in three different ways (Note: I don't control the code which generates the object) The value in the attributes (depending which one is set) is exactly the same, and I need to get that for further processing, so depending of the source of data...
How about: ``` for name in 'a', 'b', 'c': try: thing = getattr(obj, name) except AttributeError: pass else: break ```
Errors while building/installing C module for Python 2.7
13,596,407
10
2012-11-28T01:41:40Z
19,915,585
18
2013-11-11T20:45:56Z
[ "python", "visual-studio-2008" ]
I'm trying getting the following errors while trying to install/compile [ctools](http://deap.gel.ulaval.ca/doc/default/tutorials/speedup.html#using-the-c-version-of-the-nsga-ii-algorithm) for python (version info) ``` ActivePython 2.7.2.5 (ActiveState Software Inc.) based on Python 2.7.2 (default, Jun 24 2011, 12:22:1...
Since you're using the 64 bit version of Python, once you have installed [Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1](http://www.microsoft.com/en-us/download/details.aspx?id=3138) (which installs the 64bit compiler that isn't installed when installing [Visual Studio 2008 SP1 Express Edition](http://...
Errors while building/installing C module for Python 2.7
13,596,407
10
2012-11-28T01:41:40Z
21,898,585
17
2014-02-20T05:03:47Z
[ "python", "visual-studio-2008" ]
I'm trying getting the following errors while trying to install/compile [ctools](http://deap.gel.ulaval.ca/doc/default/tutorials/speedup.html#using-the-c-version-of-the-nsga-ii-algorithm) for python (version info) ``` ActivePython 2.7.2.5 (ActiveState Software Inc.) based on Python 2.7.2 (default, Jun 24 2011, 12:22:1...
I summarized above in my blog. <http://springflex.blogspot.com/2014/02/how-to-fix-valueerror-when-trying-to.html> To install Visual Studio 2008 Express Edition with all required components: 1. Install Microsoft Visual Studio 2008 Express Edition. The main Visual Studio 2008 Express installer is available from (the C+...
how to combine two columns with an if/else in python pandas?
13,596,419
6
2012-11-28T01:42:21Z
13,597,189
7
2012-11-28T03:13:49Z
[ "python", "pandas" ]
I am very new to Pandas (i.e., less than 2 days). However, I can't seem to figure out the right syntax for combining two columns with an if/else condition. Actually, I did figure out one way to do it using 'zip'. This is what I want to accomplish, but it seems there might be a more efficient way to do this in pandas. ...
Perhaps try [np.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html#numpy-where): ``` import numpy as np df['year'] = np.where(source_years,source_years,df['year']) ```
how to combine two columns with an if/else in python pandas?
13,596,419
6
2012-11-28T01:42:21Z
13,637,005
11
2012-11-30T00:01:17Z
[ "python", "pandas" ]
I am very new to Pandas (i.e., less than 2 days). However, I can't seem to figure out the right syntax for combining two columns with an if/else condition. Actually, I did figure out one way to do it using 'zip'. This is what I want to accomplish, but it seems there might be a more efficient way to do this in pandas. ...
In pandas >= 0.10.0 try ``` df['year'] = df['year'].where(source_years!=0,df['year']) ``` and see: <http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-where-method-and-masking> As noted in the comments, this DOES use np.where under the hood - the difference is that pandas aligns the series with the outpu...
Why can't I add <some list>.append to a python set?
13,596,430
5
2012-11-28T01:43:52Z
13,596,469
7
2012-11-28T01:48:31Z
[ "python", "set" ]
Why is it that I can add normal callables and methods to a set, but not `<some list>.append` (for instance)? For Example: ``` >>> l = [] >>> s = set() >>> s.add(l.append) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> type(l.append) <type 'builtin_funct...
You cannot add `list`s to a set because lists are mutable. Only immutable objects can be added to sets. `l.append` is an instance method. You can think of it as if it were the tuple `(l, list.append)` — that is, it's the list.append() method tied to the particular list `l`. The list.append() method is immutable but `l...
Python not working in command prompt?
13,596,505
11
2012-11-28T01:53:17Z
13,596,981
14
2012-11-28T02:51:30Z
[ "python", "windows", "windows-8", "command" ]
I type python into the command line, but the command prompt says that python is not recognized as an internal or external command, operable program, or batch file. What should I do Note: I have installed Python 2.7 and Python 3.2 onto my computer.
It finally worked!!! I needed to do things to get it to work 1. Add C:\Python27\ to the end of the PATH system variable 2. Add C:\Python27\ to the end of the PYTHONPATH system variable I had to add these to both for it to work. If I added any subdirectories, it did not work for some reason. Thank you all for your ...
Pythonic way to read file line by line?
13,597,088
2
2012-11-28T03:02:49Z
13,597,113
10
2012-11-28T03:05:21Z
[ "python" ]
What's the Pythonic way to go about reading files line by line of the two methods below? ``` with open('file', 'r') as f: for line in f: print line ``` or ``` with open('file', 'r') as f: for line in f.readlines(): print line ``` Or is there something I'm missing?
File handles are their own iterators (specifically, they implement the iterator protocol) so ``` with open('file', 'r') as f: for line in f: # code ``` Is the preferred usage. `f.readlines()` returns a list of lines, which means absorbing the entire file into memory -> generally ill advised, especially for larg...
How can redirect to form invalid from the form_valid function in django
13,597,856
3
2012-11-28T04:30:23Z
13,597,865
7
2012-11-28T04:32:09Z
[ "python", "django" ]
I am performing some more validation fater the main form has been validated. I am using class based views ``` def form_valid(self, request, *args, **kwargs): some custom logic if(false) Here i want to return to form invalid page with my custom message ``` I am processing the file in form\_valid and thats ...
You shouldn't be doing validation in `form_valid`. Do it in the form, either in `Form.clean` or `Form.clean_FOO`. Refer to the [Django documentation on form validation](https://docs.djangoproject.com/en/1.4/ref/forms/validation/). If you insist on mutilating your code-base, then try the following: ``` def form_valid(...
How to dynamically select template directory to be used in flask?
13,598,363
26
2012-11-28T05:22:30Z
13,598,612
39
2012-11-28T05:46:33Z
[ "python", "flask", "jinja" ]
By default flask uses template files stored in "template" directory : ``` /flaskapp /application.py /templates /hello.html ``` Is there any way to dynamically choose template directory according to user logged in? This is how I want the directory structure to be : ``` /flaskapp /application.py ...
You can pass the Flask constructor a "template\_folder" argument. Like so... ``` Flask(__name__, template_folder="wherever") ``` Here's the documentation: <http://flask.pocoo.org/docs/api/>
How to dynamically select template directory to be used in flask?
13,598,363
26
2012-11-28T05:22:30Z
13,598,839
25
2012-11-28T06:06:53Z
[ "python", "flask", "jinja" ]
By default flask uses template files stored in "template" directory : ``` /flaskapp /application.py /templates /hello.html ``` Is there any way to dynamically choose template directory according to user logged in? This is how I want the directory structure to be : ``` /flaskapp /application.py ...
There is also the possibility to overwrite Jinja loader and set the paths where Jinja will look for the templates. Like: ``` my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader(['/flaskapp/userdata', \ '/flaskapp/templates']), ]) app.jinja_lo...
Import modules from different folders
13,598,958
7
2012-11-28T06:15:59Z
13,599,005
10
2012-11-28T06:20:13Z
[ "python" ]
I have following arrangement of files: ``` python |--main.py |files |-----folder1 |-----a.py,a1.py..... |-----folder2 |-----b.py,b1.py.... ``` I wanted to import my modules a and b.py to main.py. For this I used the following commands in main.py: ``` ...
When I do this in Python 2.7 I use: ``` import sys sys.path.append('C:/python/files/folder1') import a import a1 ``` **UPDATE** Here's a hack I built to import all modules in a directory into a dictionary: ``` import os import sys dir_of_interest = 'C:/python/files/folder1' modules = {} sys.path.append(dir_of_in...
Import modules from different folders
13,598,958
7
2012-11-28T06:15:59Z
13,599,116
11
2012-11-28T06:29:17Z
[ "python" ]
I have following arrangement of files: ``` python |--main.py |files |-----folder1 |-----a.py,a1.py..... |-----folder2 |-----b.py,b1.py.... ``` I wanted to import my modules a and b.py to main.py. For this I used the following commands in main.py: ``` ...
**Quick Answer:** Add a file `__init__.py` (can be blank) to folders *files*, *folder1* and *folder2*. Then you got a package *files* with sub-packages *folder1* and *folder2*. After this you can import from the main.py like this: ``` from files.folder1 import * ```
How to return a number as a binary string with a set number of bits in python
13,599,638
2
2012-11-28T07:08:14Z
13,599,710
10
2012-11-28T07:12:12Z
[ "python", "binary" ]
Probably a silly question, but in python is there a simple way to automatically pad a number with zeros to a fixed length? I wasn't able to find this in the python docs, but I may not have been looking hard enough? e.i. I want bin(4) to return 00100, rather than just 100. Is there a simple way to ensure the output will...
Strings have a `.zfill()` method to pad it with zeros: ``` >>> '100'.zfill(5) '00100' ``` For binary numbers however, I'd use string formatting: ``` >>> '{0:05b}'.format(4) '00100' ``` The `:05b` formatting specification formats the number passed in as binary, with 5 digits, zero padded. See the [Python format stri...
python tilde unary operator as negation numpy bool array
13,600,988
21
2012-11-28T08:41:29Z
13,602,395
21
2012-11-28T09:59:32Z
[ "python", "numpy", "boolean", "multidimensional-array" ]
Should be a simple question, but I'm unable to find an answer anywhere. The `~` operator in python is a documented as a bitwise inversion operator. Fine. I have noticed seemingly schizophrenic behavior though, to wit: ``` ~True -> -2 ~1 -> -2 ~False -> -1 ~0 -> -1 ~numpy.array([True,False],dtype=int) -> array([-2,-1])...
`not` is implemented through the `__nonzero__` special method, which is required to return either `True` or `False`, so it can't give the required result. Instead the `~` operator is used, which is implemented through the `__not__` special method. For the same reason, `&` and `|` are used in place of `and` and `or`. [...
How do I find the difference between two values without knowing which is larger?
13,602,170
11
2012-11-28T09:47:48Z
13,602,196
24
2012-11-28T09:49:13Z
[ "python", "function", "numbers", "distance" ]
I was wondering if there was a function built into Python that can determine the distance o between to rational numbers but without me telling it which number is larger. i.e. ``` >>>distance(6,3) 3 >>>distance(3,6) 3 ``` Obviously I could write a simple definition to calculate which is larger and then just do a simp...
`abs(x-y)` will do exactly what you're looking for: ``` In [1]: abs(1-2) Out[1]: 1 In [2]: abs(2-1) Out[2]: 1 ```
Fastest way to get sorted unique list in python?
13,603,042
9
2012-11-28T10:36:04Z
13,605,607
12
2012-11-28T12:58:01Z
[ "python", "sorting", "optimization" ]
What is the fasted way to get a sorted, unique list in python? (I have a list of hashable things, and want to have something I can iterate over - doesn't matter whether the list is modified in place, or I get a new list, or an iterable. In my concrete use case, I'm doing this with a throwaway list, so in place would be...
I believe `sorted(set(sequence))` is the fastest way of doing it. Yes, `set` iterates over the sequence but that's a C-level loop, which is **a lot** faster than any looping you would do at python level. Note that even with `groupby` you still have `O(n) + O(nlogn) = O(nlogn)` and what's worst is that `groupby` will r...
Using a loop in Python to name variables
13,603,215
7
2012-11-28T10:45:53Z
13,603,268
20
2012-11-28T10:49:08Z
[ "python", "variables", "for-loop" ]
How do I use a loop to name variables? For example, if I wanted to have a variable **double\_1 = 2**, **double\_2 = 4** all the way to **double\_12 = 24**, how would I write it? I get the feeling it would be something like this: ``` for x in range(1, 13): double_x = x * 2 #I want the x in double_x to count up...
Use a dictionary instead. E.g: ``` doubles = dict() for x in range(1, 13): doubles[x] = x * 2 ``` Or if you *absolutely* **must** do this **[AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING](http://docs.python.org/2/library/functions.html?highlight=locals#locals)**, you can assign to `locals()` as to a dictio...
Python reduce explanation
13,603,361
2
2012-11-28T10:54:47Z
13,603,510
8
2012-11-28T11:01:22Z
[ "python", "functional-programming", "reduce" ]
I'm not able to understand the following code segment: ``` >>> lot = ((1, 2), (3, 4), (5,)) >>> reduce(lambda t1, t2: t1 + t2, lot) (1, 2, 3, 4, 5) ``` How does the reduce function produce a tuple of (1,2,3,4,5) ?
It's easier if you break out the `lambda` into a function, so it's clearer to what's going on: ``` >>> def do_and_print(t1, t2): print 't1 is', t1 print 't2 is', t2 return t1+t2 >>> reduce(do_and_print, ((1,2), (3,4), (5,))) t1 is (1, 2) t2 is (3, 4) t1 is (1, 2, 3, 4) t2 is (5,) (1, 2, 3, 4, 5) ```
ImportError when trying to import python module in SublimeText2
13,605,646
4
2012-11-28T13:00:01Z
13,610,112
9
2012-11-28T16:45:00Z
[ "python", "sublimetext2", "sublimetext" ]
I'm new to SublimeText2. So far I have found it excellent, but I just came across a problem I did not manage to solve. I'm trying to import a Python module, *mechanize*, into my script. However, whenever a run it (just the *import mechanize* line), I get: ``` Traceback (most recent call last): File "/Users/gabrielbi...
I managed to solve this problem. ST2 was not using the same python as the Terminal. For anyone having the same mistake, you can solve this by selecting: Sublime Text 2 > Preferences > Browser Packages... Then go into 'Python' folder and open 'Python.sublime\_build'. Now edit the 'cmd' parameter to match your desired Py...
Django old issue: Get current user in model
13,606,227
2
2012-11-28T13:30:52Z
13,606,939
7
2012-11-28T14:06:10Z
[ "python", "django", "model" ]
First i am sorry for asking this question, i am a new user for django. And i set up my project only by the models.Model ``` ##models.py class Task(models.Model): Name = models.CharField('Title', max_length=200) Notes = models.TextField('Description',max_length=2000, null=True) Creator = ...
You need to override the `save_model` in the Admin Class. ``` class TaskAdmin(admin.ModelAdmin): list_display = ['Name', 'Owner','EstEndTime','LastModifiedTime','Statu'] def save_model(self, request, task, form, change): task.Creator = request.user task.save() ``` ...
What is the difference between multiprocessing and subprocess?
13,606,867
21
2012-11-28T14:02:29Z
13,606,946
13
2012-11-28T14:06:26Z
[ "python", "subprocess", "multiprocessing" ]
My work should use parallel techniques, and I a new user of python. So I wonder if you could share some material about the python `multiprocessing` and `subprocess` modules. What is the difference between these two?
If you want to call an external program (especially one not written in Python) use `subprocess`. If you want to call a Python function in a subprocess, use `multiprocessing`. (If the program is written in Python, but is also importable, then I would try to call its functions using `multiprocessing`, rather than calli...
What is the difference between multiprocessing and subprocess?
13,606,867
21
2012-11-28T14:02:29Z
13,607,111
32
2012-11-28T14:15:17Z
[ "python", "subprocess", "multiprocessing" ]
My work should use parallel techniques, and I a new user of python. So I wonder if you could share some material about the python `multiprocessing` and `subprocess` modules. What is the difference between these two?
The `subprocess` module lets you run and control other programs. Anything you can start with the command line on the computer, can be run and controlled with this module. Use this to integrate external programs into your Python code. The `multiprocessing` module lets you divide tasks written in python over multiple pr...
format python output to json
13,607,765
2
2012-11-28T14:45:47Z
13,607,810
7
2012-11-28T14:48:11Z
[ "python", "json", "dictionary" ]
I have written a Python script that outputs a long data structure (dictionary i called "celldict") in Json format. Here's a small part of it : ``` { "1224": { "OUT3FA_5": 12, "IN1": 37, "Total_IN1": 37 }, "1225": { "OUT3FA_5": 24, "IN1": 59, "Total_IN1": 22 ...
Just put `celldict` *inside* another dict: ``` json.dumps({'success': True, 'data': celldict.values()}) ``` You'll have to add the `Week` key to the `celldict` dictionaries first: ``` for d in celldict.itervalues(): celldict['Week'] = '1238' ``` or use create a copy of each dict on-the-fly: ``` json.dumps({'su...
Python: How do I pass a string by reference?
13,608,919
7
2012-11-28T15:45:25Z
13,608,959
13
2012-11-28T15:46:49Z
[ "python", "string" ]
From this link: [Python: How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference), we know, Python will copy a string (an immutable type variable) when it is passed to a function as a parameter, but I think it will waste memory if the string is huge...
Python does not make copies of objects (this includes strings) passed to functions: ``` >>> def foo(s): ... return id(s) ... >>> x = 'blah' >>> id(x) == foo(x) True ``` If you need to "modify" a string in a function, return the new string and assign it back to the original name: ``` >>> def bar(s): ... retur...
How to make built-in containers (sets, dicts, lists) thread safe?
13,610,654
14
2012-11-28T17:11:27Z
13,618,333
34
2012-11-29T03:26:48Z
[ "python", "multithreading", "thread-safety" ]
I understand [from this question](http://stackoverflow.com/questions/2227169/are-python-built-in-containers-thread-safe) that if I want to have a `set` which is thread-safe I have to implement the thread-safety part on my own. Therefore I could come up with: ``` from threading import Lock class LockedSet(set): "...
You can use Python's metaprogramming facilities to accomplish this. (Note: written quickly and not thoroughly tested.) I prefer to use a class decorator. I also think you *may* need to lock more than `add` and `remove` to make a set thread-safe, but I'm not sure. I'll ignore that problem and just concentrate on your q...
Django get_or_create, how to say commit=False
13,610,896
6
2012-11-28T17:24:37Z
13,611,749
9
2012-11-28T18:14:54Z
[ "python", "django" ]
Suppose I have this model: ``` class SocialGroupMembers(models.Model): social_group = models.ForeignKey(SocialGroup, related_name="members") profile = models.ForeignKey(Profile) date_joined = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User) approved = models.BooleanField(d...
There is a `defaults` argument you can pass to `get_or_create` to populate this data for newly created objects which are not used in the filtering: ``` defaults = {'added_by': request.user} obj, created = SocialGroupMembers.objects.get_or_create( social_group=social_group, profile=profile, defaults=defaults) `...
Efficient way to apply multiple filters to pandas DataFrame or Series
13,611,065
26
2012-11-28T17:34:35Z
13,616,382
52
2012-11-28T23:38:41Z
[ "python", "algorithm", "pandas" ]
I have a scenario where a user wants to apply several filters to a Pandas DataFrame or Series object. Essentially, I want to efficiently chain a bunch of filtering (comparison operations) together that are specified at run-time by the user. The filters should be additive (aka each one applied should narrow results). ...
Pandas (and numpy) allow for [boolean indexing](http://pandas.pydata.org/pandas-docs/dev/indexing.html#boolean-indexing), which will be much more efficient: ``` In [11]: df.loc[df['col1'] >= 1, 'col1'] Out[11]: 1 1 2 2 Name: col1 In [12]: df[df['col1'] >= 1] Out[12]: col1 col2 1 1 11 2 2 12 ...
Efficient way to apply multiple filters to pandas DataFrame or Series
13,611,065
26
2012-11-28T17:34:35Z
30,778,300
7
2015-06-11T10:28:54Z
[ "python", "algorithm", "pandas" ]
I have a scenario where a user wants to apply several filters to a Pandas DataFrame or Series object. Essentially, I want to efficiently chain a bunch of filtering (comparison operations) together that are specified at run-time by the user. The filters should be additive (aka each one applied should narrow results). ...
Chaining conditions creates long lines, which are discouraged by pep8. Using the .query method forces to use strings, which is powerful but unpythonic and not very dynamic. Once each of the filters is in place, one approach is ``` import numpy as np import functools def conjunction(*conditions): return functools....
Vim neocomplcache: disable usage prompt
13,611,198
2
2012-11-28T17:42:23Z
13,612,128
10
2012-11-28T18:39:08Z
[ "python", "vim", "vim-plugin", "neocomplcache" ]
I am using Vim with neocomplcache plugin, its feature of usage prompt while completion confused me so much. It behaved like this: I typed `<C-X><C-U>` when the cursor was at the end of `os.path.`, then not only completion candidates was listed under the line, but also a horizontal split which contained docstring of th...
It's all because `preview` is in `completeopt` by default, you can see its value by type command `:set completeopt` and the result should be `completeopt=menu,preview`. What we need is just `menu`, so cut the `preview`, add this line in your vimrc: ``` set completeopt-=preview ``` vim help reference: ``` ...
Read tabbed files in python
13,611,291
2
2012-11-28T17:47:32Z
13,611,343
7
2012-11-28T17:50:30Z
[ "python", "file-io" ]
I have integer data as follows in a .txt file. ``` 600 17 3488541 601 21 6523232 602 18 6565444 603 23 6655656 ``` It goes on like that. The file is pretty huge. In a specific program I need to get each of the values in a line into an integer variable and use it and then the values in the next line and so on....
``` with open('file.txt') as f: for line in f: a, b, c = map(int, line.split()) ... ```
Migrating from Python to Racket (regular expression libraries and the "Racket Way")
13,611,591
7
2012-11-28T18:04:54Z
13,611,710
8
2012-11-28T18:12:03Z
[ "python", "regex", "racket", "porting" ]
I'm attempting to learn Racket, and in the process am attempting to rewrite a Python filter. I have the following pair of functions in my code: ``` def dlv(text): """ Returns True if the given text corresponds to the output of DLV and False otherwise. """ return text.startswith("DLV") or \ ...
You are very close. You simply need to add `#:match-select cadr` to your `regexp-match` call: ``` (regexp-match* #rx"{(.*?)}" text #:match-select cadr) ``` By default, `#:match-select` has value of `car`, which returns the whole matched string. `cadr` selects the first group, `caddr` selects the second group, etc. Se...
Repeated single or multiple tests with Nose
13,611,658
7
2012-11-28T18:08:38Z
13,611,804
10
2012-11-28T18:18:40Z
[ "python", "nose" ]
Similar to [this question](http://stackoverflow.com/questions/4088354/is-it-possible-to-use-nose-to-run-one-test-multiple-times-concurrently), I'd like to have Nose run a test (or all tests) `n` times -- but *not* in parallel. I have a few hundred tests in a project; some are some simple unit tests. Others are integra...
You can [write a nose test as a generator](https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators), and nose will then run each function yielded: ``` def check_something(arg): # some test ... def test_something(): for arg in some_sequence: yield (check_something, arg) ``` Using [no...
Django Tables - Column Filtering
13,611,741
7
2012-11-28T18:14:15Z
15,129,259
16
2013-02-28T06:48:45Z
[ "python", "django", "django-tables2" ]
I started using [django-tables2](https://github.com/bradleyayers/django-tables2) (which I can highly recommend from the first impression) and I m asking myself how to implement column filtering. I do not find the appropriate documentation for it, but I m sure it is somewhere out there.
A little late answer but anyway ... I also couldn't find any appropriate documentation for column filtering. There are many methods to do it: **A. By hand**: I add a form containing the fields I'd like to filter with and then I do something like this in my view: ``` data = models.MyClass.all() form = forms.MyFilt...
Why are the methods sys.exit(), exit(), raise SystemExit not working?
13,612,434
5
2012-11-28T18:59:43Z
13,612,490
7
2012-11-28T19:03:19Z
[ "python", "multithreading", "sockets", "exit", "sys" ]
I need an alternative to kill the python script while inside a thread function. My intention is killing the server when the client enters a 0... Is this not working because the threads haven't been terminated? Here is my code: ``` socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); print 'Socket created' try:...
The problem is that all `sys.exit()` does is raise `SystemExit`. Since this happens in a worker thread, the effect is to stop that thread (exceptions don't propagate across threads). You could trying signalling to the main thread that the script needs to terminate, either though some mechanism of your own, or by calli...
Using the tornado RequestHandler is it possible to get POST data without specifying a argument?
13,612,697
5
2012-11-28T19:16:13Z
13,615,044
9
2012-11-28T21:51:39Z
[ "python", "tornado" ]
I am trying to get the POST data from this CURL statement: ``` curl -d 'DATA HERE' http://localhost:8888/ ``` I cannot find a method to do this, at the moment I am using an argument in the POST request: ``` curl -d 'data=test' http://localhost:8888/ ``` and this to retrieve the data: ``` postData = self.get_argume...
The raw body from a post request is in `self.request.body`
Is this Python code vulnerable to SQL injection? (SQLite3)
13,613,037
8
2012-11-28T19:37:33Z
13,613,104
18
2012-11-28T19:41:28Z
[ "python", "sql", "security", "sqlite", "sqlite3" ]
As the title suggests, I would like to know if this code is vulnerable to SQL Injection? And if so, is there a better, more secure, way of achieving the same thing? ``` def add(table,*args): statement="INSERT INTO %s VALUES %s" % (table,args) cursor.execute(statement) ```
Yes, it is. Use something like this to prevent it: ``` cursor.execute("INSERT INTO table VALUES ?", args) ``` Note that you cannot enter the table in like this. Ideally the table should be hard coded, in no circumstance should it come from a user input of any kind. You can use a string similar to what you did for the...
Python: how do I know if my list has all 1s?
13,613,044
40
2012-11-28T19:37:41Z
13,613,065
79
2012-11-28T19:39:18Z
[ "python" ]
I am looking for a better way, may be using list comprehensions? ``` >>> x = [1, 1, 1, 1, 1, 1] >>> x [1, 1, 1, 1, 1, 1] >>> for i in x: ... if i!=1: ... print "fail" ... >>> >>> x = [1, 1, 1, 1, 1, 0] >>> for i in x: ... if i!=1: ... print "fail" ... fail >>> ```
``` >>> x = [1, 1, 1, 1, 1, 1] >>> all(el==1 for el in x) True ``` This uses the function [**`all`**](http://docs.python.org/dev/library/functions.html#all) with a [generator expression](http://docs.python.org/dev/tutorial/classes.html#generator-expressions). --- If you always have only zeroes and ones in the list (...
Python: how do I know if my list has all 1s?
13,613,044
40
2012-11-28T19:37:41Z
13,613,174
16
2012-11-28T19:45:50Z
[ "python" ]
I am looking for a better way, may be using list comprehensions? ``` >>> x = [1, 1, 1, 1, 1, 1] >>> x [1, 1, 1, 1, 1, 1] >>> for i in x: ... if i!=1: ... print "fail" ... >>> >>> x = [1, 1, 1, 1, 1, 0] >>> for i in x: ... if i!=1: ... print "fail" ... fail >>> ```
In addition to the `all()` answer already provided, you can also do it with `set()`: ``` >>> x = [1, 1, 1, 1, 1, 1] >>> y = set(x) >>> len(y) == 1 and y.pop() == 1 True >>> a = [1, 1, 1, 1, 0] >>> b = set(a) >>> len(b) == 1 and b.pop() == 1 False ``` **Caveat; (and Redeeming Factor)**: * As some have pointed out, t...
Python: how do I know if my list has all 1s?
13,613,044
40
2012-11-28T19:37:41Z
13,614,080
10
2012-11-28T20:46:19Z
[ "python" ]
I am looking for a better way, may be using list comprehensions? ``` >>> x = [1, 1, 1, 1, 1, 1] >>> x [1, 1, 1, 1, 1, 1] >>> for i in x: ... if i!=1: ... print "fail" ... >>> >>> x = [1, 1, 1, 1, 1, 0] >>> for i in x: ... if i!=1: ... print "fail" ... fail >>> ```
@sampson-chen had a good idea that could use some help. Consider up voting his answer and look at this this as an extended comment. (I don't know how to make code look good in a comment). Here's my rewrite: ``` >>> setone = set([1]) >>> x = [1, 1, 1, 1, 1, 1] >>> set(x) == setone True ``` This code does not *exactly*...
Python: how do I know if my list has all 1s?
13,613,044
40
2012-11-28T19:37:41Z
13,615,438
42
2012-11-28T22:20:22Z
[ "python" ]
I am looking for a better way, may be using list comprehensions? ``` >>> x = [1, 1, 1, 1, 1, 1] >>> x [1, 1, 1, 1, 1, 1] >>> for i in x: ... if i!=1: ... print "fail" ... >>> >>> x = [1, 1, 1, 1, 1, 0] >>> for i in x: ... if i!=1: ... print "fail" ... fail >>> ```
Yet more possible methods: ``` x == [1] * len(x) list(set(x)) == [1] tuple(set(x)) == (1,) ``` Some timing results: ``` all(el==1 for el in x) [1.184262990951538, 1.1856739521026611, 1.1883699893951416] y = set(x);len(y) == 1 and y.pop() == 1 [0.6140780448913574, 0.6152529716491699, 0.6156158447...