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 |
|---|---|---|---|---|---|---|---|---|---|
Constant-time `if-else` in python | 25,218,397 | 8 | 2014-08-09T12:07:10Z | 25,224,029 | 9 | 2014-08-09T23:18:40Z | [
"python",
"security",
"timing"
] | I'd like to know if there is an easy way (maybe a library) to write constant-time programs in Python. In particular, I'd like to be able to specify that an if-else flow must always last the same time either the if condition is `True` or `False`.
For instance:
```
if condition:
foo1()
else:
foo2()
foo3()
```
... | Since your question is about security, I assume we can leave aside performance and very naively introduce a minimal time to spend on all possible branches.One way to achieve this is with [context managers](https://docs.python.org/3.4/reference/datamodel.html#with-statement-context-managers):
Your problem could be the... |
How to use OR in regular expressions | 25,223,038 | 2 | 2014-08-09T21:03:53Z | 25,223,055 | 8 | 2014-08-09T21:06:02Z | [
"python",
"regex"
] | I have some strings like "abc", "def", "xyz" and they may be followed by numbers.
For example:
abc123 or xyz92
If I use:
```
re.findall("abc|def|xyz[0-9]+",text)
```
then it will only return xyz followed by digits, for the rest I only get the strings.
How to match all of them without doing it manually like:
```
re... | Use parenthesis, along with `?:` to create a non-capturing group:
```
(?:abc|def|xyz)[0-9]+
```

[Debuggex Demo](https://www.debuggex.com/r/mC0ygke6rJC0XuYN)
Further, if it is possible that your strings will not be followed by numbe... |
Represent directory tree as JSON | 25,226,208 | 5 | 2014-08-10T06:41:00Z | 25,226,267 | 11 | 2014-08-10T06:52:24Z | [
"python",
"json",
"python-2.7",
"data-structures",
"tree"
] | Is there any easy way to generate such a JSON? I found `os.walk()` and `os.listdir()`, so I may do recursive descending into directories and build a python object, well, but it sounds like reinventing a wheel, maybe someone knows working code for such a task?
```
{
"type": "directory",
"name": "hello",
"children... | I don't think that this task is a "wheel" (so to speak). But it is something which you can easily achieve by means of the tools you mentioned:
```
import os
import json
def path_to_dict(path):
d = {'name': os.path.basename(path)}
if os.path.isdir(path):
d['type'] = "directory"
d['children'] = ... |
Python confusing function reference | 25,226,421 | 6 | 2014-08-10T07:19:22Z | 25,226,438 | 7 | 2014-08-10T07:22:35Z | [
"python",
"list",
"reference"
] | Can anyone explain to me why the two functions below `a` and `b` are behaving differently. Function `a` changes `names` locally and `b` changes the actual object.
Where can I find the correct documentation for this behavior?
```
def a(names):
names = ['Fred', 'George', 'Bill']
def b(names):
names.append('Bil... | Assigning to parameter inside the function does not affect the argument passed. It only makes the local variable to reference new object.
While, `list.append` modify the list in-place.
If you want to change the list inside function, you can use slice assignment:
```
def a(names):
names[:] = ['Fred', 'George', 'B... |
Best way to plot an angle between two lines in Matplotlib | 25,227,100 | 9 | 2014-08-10T09:04:33Z | 25,228,427 | 12 | 2014-08-10T12:05:19Z | [
"python",
"matplotlib"
] | I am fairly new to using matplotlib and cannot find any examples that show two lines with the angle between them plotted.
This is my current image:

And this is an example of what I want to achieve:
 to plot an arc of the corresponding angle measure.
**To draw the angle arc:**
Define a function that could take 2 `matplotlib.lines.Line2D` objects, calculate the angle and return a `matplotlib.patches.Arc` obje... |
How to use MySQL with Anaconda's Python IDE | 25,228,687 | 4 | 2014-08-10T12:38:40Z | 25,236,209 | 8 | 2014-08-11T05:12:54Z | [
"python",
"mysql",
"anaconda"
] | I just want to be able to do a simple "SELECT \* FROM" query.
Need help ... I found a Python MySqlDB Package, but can't get it to install using the Windows installer. It says that Python is not found in the registry.
I then tried briefly to compile it myself but I've debugged about six errors so far during the compil... | The problem is that the binary installers for Python packages are looking for a specific registry key, which does not exist if you are using the Anaconda installer.
To make matters worse, Anaconda doesn't provide database drivers in either their commercial or free repository.
So now you have two options
1. **Recomme... |
Find particular words in a string, Python | 25,235,215 | 2 | 2014-08-11T02:42:57Z | 25,235,252 | 8 | 2014-08-11T02:48:40Z | [
"python",
"regex"
] | Create a function that, Given Two arguments: A text as a string and words as a set of strings, returns the number of words from the set, that are contained in the string.
Eg. count\_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3
My Attempt:
```
import re
def count_words(text, words):
count = ... | ```
def count_words(text, words):
answer = 0
for i in range(len(text)):
if any(text[i:].startswith(word) for word in words):
answer += 1
return answer
```
If you want it to be insensitive to letter cases in the text:
```
def count_words(text, words):
text = text.lower()
answer ... |
Setting plot background colour in Seaborn | 25,238,442 | 5 | 2014-08-11T08:04:25Z | 25,247,866 | 10 | 2014-08-11T16:18:57Z | [
"python",
"matplotlib",
"plot",
"pandas",
"seaborn"
] | I am using Seaborn to plot some data in Pandas.
I am making some very large plots (`factorplot`s).
To see them, I am using some visualisation facilities at my university.
I am using a Compound screen made up of 4 by 4 monitors with small (but nonzero) bevel -- the gap between the screens.
This gap is black.
To minimi... | `seaborn.set` takes and `rc` argument that accepts a dictionary of valid matplotlib `rcparams`. So we need to set two things: the `axes.facecolor`, which is the color of the area where the data are drawn, and the `figure.facecolor`, which is the everything a part of the figure outside of the `axes` object.
## (edited ... |
Python requests speed up using keep-alive | 25,239,650 | 26 | 2014-08-11T09:11:25Z | 25,239,947 | 37 | 2014-08-11T09:26:15Z | [
"python",
"http",
"python-requests",
"python-sockets"
] | In the HTTP protocol you can send many requests in one socket using keep-alive and then receive the response from server at once, so that will significantly speed up whole process. Is there any way to do this in python requests lib? Or are there any other ways to speed this up that well using requests lib? | Yes, there is. Use [`requests.Session`](http://docs.python-requests.org/en/latest/user/advanced/#session-objects) and [it will do keep-alive by default](http://docs.python-requests.org/en/latest/user/advanced/#keep-alive).
I guess I should include a quick example:
```
import logging
import requests
logging.basicConf... |
How to add title to subplots in Matplotlib? | 25,239,933 | 25 | 2014-08-11T09:25:41Z | 25,243,066 | 48 | 2014-08-11T12:15:26Z | [
"python",
"matplotlib",
"plot",
"subtitle"
] | I have one figure which contains many subplots.
```
fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')
# Returns the Axes instance
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
```
How do I add titles to t... | `ax.set_title()` should set the titles for separate subplots:
```
import matplotlib.pyplot as plt
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
fig = plt.figure()
fig.suptitle("Title for whole figure", fontsize=16)
ax = plt.subplot("211")
ax.set_title("Title for first plot")
ax.plot(data)... |
Impute categorical missing values in scikit-learn | 25,239,958 | 10 | 2014-08-11T09:26:41Z | 25,562,948 | 21 | 2014-08-29T06:44:58Z | [
"python",
"pandas",
"scikit-learn"
] | I've got pandas data with some columns of text type. There are some NaN values along with these text columns. What I'm trying to do is to impute those NaN's by sklearn.preprocessing. Imputer (replacing NaN by the most frequent value). The problem is in implementation.
Suppose there is a Pandas dataframe df with 30 colu... | To use mean values for numeric columns and the most frequent value for non-numeric columns you could do something like this. You could further distinguish between integers and floats. I guess it might make sense to use the median for integer columns instead.
```
import pandas as pd
import numpy as np
from sklearn.bas... |
Python: Dump to Json adds additional double quotes and escaping of quotes | 25,242,262 | 8 | 2014-08-11T11:31:25Z | 25,242,376 | 21 | 2014-08-11T11:37:27Z | [
"python",
"json"
] | I am retrieving Twitter-data with a python tool and dump them in the JSon format to my disk. I noticed an unintended escaping of the entire data-string for a tweet being enclosed in double quotes. Furthermore, all double quotes of the actual Json formatting are escaped with a backslash.
They look like this:
> "{\"cre... | You are doubly-encoding JSON strings. `data` is **already** a JSON string, and doesn't need to be encoded *again*:
```
>>> import json
>>> not_encoded = {"created_at":"Fri Aug 08 11:04:40 +0000 2014"}
>>> encoded_data = json.dumps(not_encoded)
>>> print encoded_data
{"created_at": "Fri Aug 08 11:04:40 +0000 2014"}
>>>... |
"Models aren't loaded yet" error while populating in Django 1.8 and Python 2.7.8 | 25,244,631 | 32 | 2014-08-11T13:37:32Z | 25,244,833 | 88 | 2014-08-11T13:47:43Z | [
"python",
"django",
"django-1.8"
] | I am using this code to populate my database:
```
import os
def populate():
python_cat = add_cat('Python')
add_page(cat=python_cat,
title="Official Python Tutorial",
url="http://docs.python.org/2/tutorial/")
add_page(cat=python_cat,
title="How to Think like a Computer Scientist",
url="http://www.greenteapress.com/t... | I had the same exception with Django 1.7rc2. The solution was to add these lines at the beginning of my program:
```
import django
django.setup()
```
Update: [This is now documented for Django 1.8.](https://docs.djangoproject.com/en/1.8/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage) |
numpy.void type - how to use it? | 25,247,190 | 11 | 2014-08-11T15:42:55Z | 25,247,533 | 24 | 2014-08-11T16:01:34Z | [
"python",
"matlab",
"numpy",
"scipy"
] | I loaded a MATLAB `.mat` file via `scipy.io.loadmat` and it gave me a list of `numpy.void` objects.
Can someone tell me what are they, how they can be used and where can I get some reference **documentation** on them? | According to the `numpy` documentation: <http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html>, `numpy.void` types are defined as **flexible** data types. Basically, these are data types where there is no pre-defined type associated to the variable(s) you're looking at. If you look at `numpy`, you have data typ... |
Flag "print" statements in Python code | 25,249,586 | 7 | 2014-08-11T18:02:22Z | 25,249,702 | 11 | 2014-08-11T18:08:40Z | [
"python",
"lint",
"static-code-analysis"
] | I don't want "print" statements in our Python modules, because we will be using a logger.
I'm trying to generate a script to check modules with pylint.
However, pylint currently does not detect this as a warning or error.
I want to detect "print" invocations as an error or a warning in accordance with our internal Py... | [`flake8`](https://pypi.python.org/pypi/flake8) has a [`flake8-print`](https://pypi.python.org/pypi/flake8-print) plugin specifically for the task:
> flake8-print
>
> Check for Print statements in python files.
DEMO:
```
$ cat test.py
s = "test"
print s
$ flake8 test.py
test.py:2:1: T001 print statement found.
``` |
Flag "print" statements in Python code | 25,249,586 | 7 | 2014-08-11T18:02:22Z | 25,249,854 | 7 | 2014-08-11T18:18:58Z | [
"python",
"lint",
"static-code-analysis"
] | I don't want "print" statements in our Python modules, because we will be using a logger.
I'm trying to generate a script to check modules with pylint.
However, pylint currently does not detect this as a warning or error.
I want to detect "print" invocations as an error or a warning in accordance with our internal Py... | If for some reason you don't want to use `flake8-print` as suggested by @alecxe you can roll your own using the `ast` module - which makes use of Python's compiler to parse the file so you can reliably find `print` (instead of lines just starting with `print`):
**Code**:
```
import ast
with open('blah.py') as fin:
... |
How can I use a custom feature selection function in scikit-learn's `pipeline` | 25,250,654 | 4 | 2014-08-11T19:11:54Z | 25,254,187 | 16 | 2014-08-11T23:50:44Z | [
"python",
"scikit-learn"
] | Let's say that I want to compare different dimensionality reduction approaches for a particular (supervised) dataset that consists of n>2 features via cross-validation and by using the `pipeline` class.
For example, if I want to experiment with PCA vs LDA I could do something like:
```
from sklearn.cross_validation i... | I just want to post my solution for completeness, and maybe it is useful to one or the other:
```
class ColumnExtractor(object):
def transform(self, X):
cols = X[:,2:4] # column 3 and 4 are "extracted"
return cols
def fit(self, X, y=None):
return self
```
Then, it can be used in the ... |
How do I run two separate instances of Spyder | 25,250,998 | 12 | 2014-08-11T19:35:22Z | 25,956,248 | 16 | 2014-09-21T05:51:17Z | [
"python",
"multiple-instances",
"spyder"
] | I want to be able to have two instances which are completely independent in the sense that I can be working on two separate unrelated projects in different folders without any interference. | (*Spyder dev here*) This is very easy. You need to go to:
```
Tools > Prefences > General
```
and deactivate the option called
```
[ ] Use a single instance
```
Then every time you start Spyder a new window will be opened. If you want the old behavior back, just activate that option again. |
Downloading file to specified location with Selenium and python | 25,251,583 | 5 | 2014-08-11T20:11:38Z | 25,251,803 | 24 | 2014-08-11T20:25:22Z | [
"python",
"firefox",
"selenium",
"selenium-webdriver"
] | Ok so far i have my programing going to the website i want to download link from and selecting it, then the firefox dialogue box shows up and i don't know what to do. i want to save this file to a folder on my desktop. I am using this for a nightly build so i need this to work. Please help.
Here is my code that grabs ... | You need to make `Firefox` save this particular file type automatically.
This can be achieved by setting `browser.helperApps.neverAsk.saveToDisk` preference:
```
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browse... |
Pandas - Get first row value of a given column | 25,254,016 | 39 | 2014-08-11T23:30:16Z | 25,254,087 | 72 | 2014-08-11T23:39:45Z | [
"python",
"pandas"
] | This seems like a ridiculously easy question... but I'm not seeing the easy answer I was expecting.
So, how do I get the value at an nth row of a given column in Pandas? (I am particularly interested in the first row, but would be interested in a more general practice as well).
For example, let's say I want to pull t... | To select the `ith` row, [use `iloc`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing-loc-iloc-and-ix):
```
In [31]: df_test.iloc[0]
Out[31]:
ATime 1.2
X 2.0
Y 15.0
Z 2.0
Btime 1.2
C 12.0
D 25.0
E 12.0
Name: 0, dtype: float64... |
Using iGraph in python for community detection and writing community number for each node to CSV | 25,254,151 | 8 | 2014-08-11T23:47:20Z | 25,260,234 | 11 | 2014-08-12T09:03:10Z | [
"python",
"igraph",
"hierarchical-clustering"
] | I have an network that I would like to analyze using the `edge_betweenness` community detection algorithm in iGraph. I'm familiar with NetworkX, but am trying to learning iGraph because of it's additional community detection methods over NetworkX.
My ultimate goal is to run `edge_betweenness` community detection and f... | You are on the right track; the optimal number of communities (where "optimal" is defined as "the number of communities that maximizes the modularity score) can be retrieved by `communities.optimal_count` and the community structure can be converted into a flat disjoint clustering using `communities.as_clustering(num_c... |
Pyinstaller - ImportError: No system module 'pywintypes' (pywintypes27.dll) | 25,254,285 | 8 | 2014-08-12T00:03:43Z | 34,123,049 | 7 | 2015-12-06T21:32:54Z | [
"python",
"exe",
"pyinstaller"
] | I am trying to package my python script into an executable. I thought I would be pretty straight forward as I don't have very many imports. First off here are my imports:
```
from __future__ import print_function
from netCDF4 import Dataset
import numpy as np
import os
from progressbar import Percentage,Bar,ETA,Progr... | I just copied the DLL `pywintypes27.dll` in `C:\Python27\Lib\site-packages\pywin32_system32`.
I added it in `win32/lib`.
It's OK! |
Why is numpy.power 60x slower than in-lining? | 25,254,541 | 19 | 2014-08-12T00:40:35Z | 25,254,609 | 17 | 2014-08-12T00:52:23Z | [
"python",
"arrays",
"performance",
"numpy"
] | Maybe I'm doing something odd, but maybe found a surprising performance loss when using numpy, seems consistent regardless of the power used. For instance when x is a random 100x100 array
```
x = numpy.power(x,3)
```
is about 60x slower than
```
x = x*x*x
```
A plot of the speed up for various array sizes reveals a... | It's well known that multiplication of doubles, which your processor can do in a very fancy way, is very, very fast. `pow` is decidedly slower.
[Some performance guides](http://julia.readthedocs.org/en/latest/manual/performance-tips/#tweaks) out there even advise people to plan for this, perhaps even in some way that ... |
Can Python be configured to cache sys.path directory lookups? | 25,255,438 | 12 | 2014-08-12T02:53:15Z | 25,265,904 | 9 | 2014-08-12T13:43:56Z | [
"python",
"python-import"
] | We've been doing a lot of benchmarking of Python running over a remote connection. The program is running offsite but accessing disks on-site. We are running under RHEL6. We watched a simple program with strace. It appears it's spending a lot of time performing stat and open on files to see if they are there. Over a re... | You can avoid this by either moving to Python 3.3, or replacing the standard import system with an alternative. In the `strace` talk that I gave two weeks ago at PyOhio, I discuss the unfortunate *O(nm)* performance (for *n* directories and *m* possible suffixes) of the old import mechanism; start at [this slide](http:... |
What is the difference between running ./file.py and python file.py? | 25,255,985 | 3 | 2014-08-12T04:06:53Z | 25,256,010 | 9 | 2014-08-12T04:10:28Z | [
"python",
"shell",
"command-line"
] | When I run Python script from the command line
```
./file.py
```
it is interpreted differently(fails with a bunch of errors) from when I run it using:
```
python file.py
```
Why are they executed differently? | On Unix-like systems:
* `./file.py` requires `file.py` to be executable (e.g., `chmod a+x file.py`).
* `./file.py` runs the script with whichever interpreter is specified in its shebang line; `python file.py` runs it with whichever interpreter named `python` is highest on your `$PATH`. If you have multiple versions of... |
Python 3.4 :ImportError: no module named win32api | 25,257,274 | 7 | 2014-08-12T06:09:05Z | 26,485,933 | 12 | 2014-10-21T11:47:30Z | [
"python",
"pywin32"
] | I am using python 3.4 on windows 7.In order to open a doc file i am using this code
```
import sys
import win32com.client as win32
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("MyDocument")
doc = word.ActiveDocument
```
M not sure why is this error popping up everytime
ImportError:... | Try to install pywin32 from here :
<http://sourceforge.net/projects/pywin32/files/pywin32/>
depends on you operation system and the python version that you are using. Normally 32bit version should works on both 32 and 64 bit OS. |
Define Custom error messages Flask Restful API | 25,258,138 | 4 | 2014-08-12T07:05:01Z | 25,258,967 | 8 | 2014-08-12T07:55:04Z | [
"python",
"flask",
"flask-restful"
] | I am having problems defining my own error custom messages. I am not exactly sure if I am doing it correctly but I am trying to follow the documentation:
<http://flask-restful.readthedocs.org/en/latest/extending.html#define-custom-error-messages>
This is what my code looks like:
```
from flask import Flask
from flas... | The version of flask-restful you get when you install with pip will be v0.2.12
This version does not have the `errors` keyword argument for `flask_restful.API.__init__` [(github link)](https://github.com/twilio/flask-restful/blob/0.2.12/flask_restful/__init__.py#L71)
To get the errors keyword you will need to install... |
Why manual string reverse is worse than slice reverse in Python 2.7? What is the algorithm being used in Slice? | 25,258,549 | 5 | 2014-08-12T07:29:39Z | 25,259,164 | 8 | 2014-08-12T08:05:40Z | [
"python",
"python-2.7",
"slice",
"timeit"
] | Below the performance difference between Slice and manual reverse operation. If this is the case, What is the reason for that?
```
timeit.timeit("a[::-1]","a=[1,2,3,4,5,6]",number=100)
6.054327968740836e-05
timeit.timeit("[a[i] for i in range(len(a)-1,-1,-1)]","a=[1,2,3,4,5,6]",number=100)
0.0003132152330920235
``` | Here's the bytecode
```
from dis import dis
a = [1,2,3,4,5,6]
def func1():
a[::-1]
def func2():
[a[i] for i in range(len(a)-1,-1,-1)]
def func3():
reversed(a)
```
In the second method, you're finding the length, creating a copy with range and creating the variable i.
 variable-sized binary byte array to an (unsigned) integer/long? As an example, `'\x11\x34'`, which represents 4404
Right now, I'm using
```
def bytes_to_int(bytes):
return int(bytes.encode('hex'), 16)
```
Which is small and somewhat readable, but probably not very efficient. Is the... | Python doesn't traditionally have much use for "numbers in big-endian C layout" that are too big for C. (If you're dealing with 2-byte, 4-byte, or 8-byte numbers, then `struct.unpack` is the answer.)
But enough people got sick of there not being one obvious way to do this that Python 3.2 added a method [`int.from_byte... |
How to 'pip install uwsgi' with alternative build configuration? | 25,260,198 | 3 | 2014-08-12T09:01:27Z | 25,260,588 | 7 | 2014-08-12T09:20:08Z | [
"python",
"pip",
"uwsgi"
] | I'm trying to install [uWSGI](http://uwsgi-docs.readthedocs.org/en/latest/index.html) with pip for deploying a Django project:
```
$ pip install uwsgi
[...]
################# uWSGI configuration #################
pcre = False
kernel = Linux
malloc = libc
execinfo = False
ifaddrs = True
ssl = True
zlib = True
locking ... | The setup process checks an environment variable `UWSGI_PROFILE_OVERRIDE` which can override these configurations. It consists of `key=value` pairs separated by `;` (semicolons). The values `true` and `false` must be lowercase which tripped me up at first.
So you could try `UWSGI_PROFILE_OVERRIDE=ssl=false;routing=tru... |
pytz - Converting UTC and timezone to local time | 25,264,811 | 5 | 2014-08-12T12:52:41Z | 25,265,611 | 11 | 2014-08-12T13:31:03Z | [
"python",
"timezone",
"utc",
"pytz"
] | I have a `datetime` in utc time zone, for example:
```
utc_time = datetime.datetime.utcnow()
```
And a pytz timezone object:
```
tz = timezone('America/St_Johns')
```
What is the proper way to convert `utc_time` to the given timezone? | I think I got it:
```
pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)
```
This line first converts the native `utc_time` `datetime` object to a `datetime` object that contains a timezone (UTC). Then it uses the [`astimezone`](https://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone) functi... |
Python transition matrix | 25,269,476 | 4 | 2014-08-12T16:29:16Z | 25,269,629 | 11 | 2014-08-12T16:38:55Z | [
"python",
"transitions"
] | I have a list looking like this:
[2, 1, 3, 1, 2, 3, 1, 2, 2, 2]
What I want is a transition matrix which shows me the sequence like:
* How often is a 1 followed by a 1
* How often is a 1 followed by a 2
* How often is a 1 followed by a 3
* How often is a 2 followed by a 1
* How often is a 2 followed by a 2
* How oft... | I don't know if there's a module, but I'd go with this code, which is easily generalizeable:
```
import numpy as np
from collections import Counter
a = [2, 1, 3, 1, 2, 3, 1, 2, 2, 2]
b = np.zeros((3,3))
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
b[x-1,y-1] = c
print b
array([[ 0., 2., 1.],
[ 1., ... |
installing cx_Freeze to python at windows | 25,270,885 | 10 | 2014-08-12T17:48:23Z | 25,936,813 | 21 | 2014-09-19T14:56:32Z | [
"python",
"batch-file",
"python-3.x",
"cx-freeze"
] | I am using python 3.4 at win-8. I want to obtain .exe program from python code. I learned that it can be done by cx\_Freeze.
In MS-DOS command line, I wrote pip install cx\_Freeze to set up cx\_Freeze. It is installed but it is not working.
(When I wrote cxfreeze to command line, I get this warning:C:\Users\USER>cxfr... | I faced a similar problem (Python 3.4 32-bit, on Windows 7 64-bit). After installation of cx\_freeze, three files appeared in `c:\Python34\Scripts\`:
* `cxfreeze`
* `cxfreeze-postinstall`
* `cxfreeze-quickstart`
These files have no file extensions, but appear to be Python scripts. When you run `python.exe cxfreeze-po... |
Why is communication via shared memory so much slower than via queues? | 25,271,723 | 5 | 2014-08-12T18:39:08Z | 25,271,803 | 12 | 2014-08-12T18:44:20Z | [
"python",
"performance",
"multiprocessing",
"message-queue",
"shared-memory"
] | I am using Python 2.7.5 on a recent vintage Apple MacBook Pro which has four hardware and eight logical CPUs; i.e., the sysctl utility gives:
```
$ sysctl hw.physicalcpu
hw.physicalcpu: 4
$ sysctl hw.logicalcpu
hw.logicalcpu: 8
```
I need to perform some rather complicated processing on a large 1-D list or array, and... | This is because `multiprocessing.Array` uses a lock by default to prevent multiple processes from accessing it at once:
> **multiprocessing.Array(typecode\_or\_type, size\_or\_initializer, \*,
> lock=True)**
>
> ...
>
> If lock is True (the default) then a new lock object is created to synchronize access to the value.... |
Form the sequence of a union of two sets efficiently | 25,272,113 | 2 | 2014-08-12T19:04:52Z | 25,272,140 | 8 | 2014-08-12T19:06:29Z | [
"python",
"performance",
"set-union"
] | Dear Reader of this post,
do you have an idea how to form the sequence of a union of two lists efficiently in Python? Suppose there are the two following lists:
```
list_a = [['a','b'],['a','c'],['b','c']]
list_b = ['h','i']
```
and I want to calculate:
```
new_list = [['a','b','h'],['a','b','i'],['a','c','h'],[... | You could use [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product):
```
[a+[b] for a, b in itertools.product(list_a, list_b)]
```
However, there's nothing really wrong with the way you did it. Using two loops in a list comprehension is fine if you really need to get every combinat... |
Are Python Empty Immutables Singletons? | 25,273,194 | 7 | 2014-08-12T20:07:43Z | 25,273,422 | 8 | 2014-08-12T20:22:38Z | [
"python",
"types",
"singleton",
"immutability"
] | Are Python Empty Immutables Singletons?
If you review the CPython implementation of builtin types, you'll find comments on all the immutable builtin objects that their empty versions are singletons. This would make a lot of sense as Python could avoid wasting memory on redundant items that would never change in place.... | The [description of standard types](https://docs.python.org/2/reference/datamodel.html) makes no promise that equivalent objects are identical, except for `True`, `False`, `None`, `NotImplemented`, and `Ellipsis`. Some of the promises that it does **not** make are`() is ()`, nor `1 is 1`, nor `'hello' is 'hello'`. (In ... |
TypeError: 'datetime.datetime' object is not callable | 25,275,094 | 4 | 2014-08-12T22:26:17Z | 25,275,120 | 8 | 2014-08-12T22:28:28Z | [
"python",
"time"
] | I have some Python code that iterates through all the days between two start dates. The start date is always November 1st and the end date is always May 31st. However, the code iterates through years. My code is as so:
```
import time
from datetime import datetime
from datetime import date, timedelta as td
list1 = [2... | This is because you are having a variable called `date` that is shadowing imported `datetime.date`. Use a different variable name.
Demo:
```
>>> from datetime import date, datetime
>>> date(01,11,01)
datetime.date(1, 11, 1)
>>> date = datetime(year=2014, month=1, day=2)
>>> date(01,11,01)
Traceback (most recent call ... |
Can't load Python modules installed via pip from site-packages directory | 25,276,329 | 22 | 2014-08-13T00:36:54Z | 25,276,953 | 35 | 2014-08-13T02:04:03Z | [
"python",
"osx",
"bash",
"module",
"evernote"
] | I am trying to install and use the Evernote module (<https://github.com/evernote/evernote-sdk-python>) . I ran `pip install evernote` and it says that the installation worked.
I can confirm that the evernote module exists in `/usr/local/lib/python2.7/site-packages`. However, when I try to run `python -c "import everno... | `/usr/bin/python` is the executable for the python that comes with OS X. `/usr/local/lib` is a location for user-installed programs only, possibly from Python.org or Homebrew. So you're mixing different Python installs, and changing the python path is only a partial workaround for different packages being installed for... |
Can't load Python modules installed via pip from site-packages directory | 25,276,329 | 22 | 2014-08-13T00:36:54Z | 25,276,966 | 17 | 2014-08-13T02:05:51Z | [
"python",
"osx",
"bash",
"module",
"evernote"
] | I am trying to install and use the Evernote module (<https://github.com/evernote/evernote-sdk-python>) . I ran `pip install evernote` and it says that the installation worked.
I can confirm that the evernote module exists in `/usr/local/lib/python2.7/site-packages`. However, when I try to run `python -c "import everno... | I figured it out! I added this line:
`export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages`
to my `.bash_profile` and now I can import modules stored in that directory. Thanks for everyone who answered. |
How to define get_queryset, get_context_data in a django view? | 25,277,099 | 2 | 2014-08-13T02:27:16Z | 25,277,730 | 7 | 2014-08-13T03:49:40Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
] | I want show a tree with `Authors` and `Books` written for each Author in sub item,
like [show in the image](http://i.imgur.com/4Ba0XUt.jpg?1) and... I have two models `Author` and `Book` in a OneToMany relationship.
```
#models.py
from django.db import models
class Author(models.Model):
Name = models.CharField(ma... | First of all you need to establish a `ForeignKey` relationship between your models.
```
#models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length = 250)
author = models.ForeignKey(Author, related_name="books")
def __unicode__(self):
return self.Title
``... |
Parsing non-zero padded timestamps in Python | 25,279,993 | 22 | 2014-08-13T07:01:07Z | 25,280,059 | 37 | 2014-08-13T07:05:05Z | [
"python",
"datetime"
] | I want to get datetimes from timestamps like the following :`3/1/2014 9:55` with `datetime.strptime`, or something equivalent.
The month, day of month, and hour is not zero padded, but there doesn't seem to be a formatting directive listed [here](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavi... | `strptime` is able to parse non-padded values. The fact that they are noted as being padded in the formatting codes table applies to `strftime`'s output. So you can just use
```
datetime.strptime(datestr, "%m/%d/%Y %H:%M")
``` |
How to plot a 3D density map in python with matplotlib | 25,286,811 | 11 | 2014-08-13T12:55:06Z | 25,354,417 | 15 | 2014-08-17T22:57:44Z | [
"python",
"matplotlib",
"scipy",
"mayavi",
"kernel-density"
] | I have a large dataset of (x,y,z) protein positions and would like to plot areas of high occupancy as a heatmap. Ideally the output should look similiar to the volumetric visualisation below, but I'm not sure how to achieve this with matplotlib.
... | Thanks to mwaskon - for suggesting the mayavi library.
I recreated the density scatter plot in mayavi as follows:
```
import numpy as np
from scipy import stats
from mayavi import mlab
mu, sigma = 0, 0.1
x = 10*np.random.normal(mu, sigma, 5000)
y = 10*np.random.normal(mu, sigma, 5000)
z = 10*np.random.normal(mu, si... |
ImportError: cannot import name defaultdict | 25,288,315 | 4 | 2014-08-13T14:05:40Z | 25,288,339 | 11 | 2014-08-13T14:06:35Z | [
"python",
"defaultdict"
] | I'm getting this really strange `ImportError` when running `from collections import defaultdict`:
```
ImportError: cannot import name defaultdict
```
I'm running python 2.7, and the strange part is that in other parts of my application this exact same import line succeeds.
I thought maybe that's a circular import, b... | You probably have a module named 'collections' in your project.
Try renaming this module in your project. |
Capture the result of an IPython magic function | 25,289,437 | 7 | 2014-08-13T14:53:39Z | 25,289,938 | 8 | 2014-08-13T15:15:37Z | [
"python",
"ipython",
"ipython-magic"
] | I'm trying to capture the resulting object of IPython Notebook magic function. Specifically `%timeit`
So the following code...
```
import time
def say_hello(n):
time.sleep(n)
print "hello"
t = %timeit say_hello(5)
```
Prints to stdout:
```
1 loops, best of 3: 5 s per loop
```
However, I'd like to capture ... | In the source file you linked to, the docstring shows the options for running the timeit magic function; one of which is returning an object result:
```
-o: return a TimeitResult that can be stored in a variable to inspect
the result in more details.
```
So, if you run
```
obj = %timeit -o somefunc()
```
`o... |
Why is __len__() called implicitly on a custom iterator | 25,291,590 | 6 | 2014-08-13T16:36:21Z | 25,291,617 | 10 | 2014-08-13T16:37:54Z | [
"python"
] | I'm writing a simple linked list implementation as follows:
```
class Node(object):
def __init__(self, value):
self.value = value
self._next = None
def __iter__(self):
here = self
while here:
yield here
here = here._next
def __len__(self):
p... | You are using `here` in a boolean context:
```
while here:
```
This will use `__len__` to see if it is an empty container (e.g. is false-y), see [*Truth Value Testing*](https://docs.python.org/2/library/stdtypes.html#truth-value-testing):
> Any object can be tested for truth value, for use in an `if` or `while` cond... |
Python 'Functions are objects' | 25,292,239 | 6 | 2014-08-13T17:11:59Z | 25,292,325 | 12 | 2014-08-13T17:17:39Z | [
"python",
"function",
"class",
"methods"
] | I always hear this statement in python (for topics such as decorators, etc. when you are passing functions, etc.) but have never really seen an elaboration on this.
For example is it possible to create a class `c` that has only one abstract method that is called with a set of opened and closed brackets.
```
i.e class... | You are looking for the [`__call__` method](https://docs.python.org/2/reference/datamodel.html#object.__call__). Function objects have that method:
```
>>> def foo(): pass
...
>>> foo.__call__
<method-wrapper '__call__' of function object at 0x106aafd70>
```
Not that the Python interpreter loop actually makes use of... |
Why is converting a list to a set faster than using just list to compute a list difference? | 25,294,897 | 3 | 2014-08-13T19:48:22Z | 25,294,938 | 8 | 2014-08-13T19:51:04Z | [
"python",
"performance",
"list",
"python-2.7",
"set"
] | Say, I wish to compute the difference of two lists `C = A - B`:
```
A = [1,2,3,4,5,6,7,8,9]
B = [1,3,5,8,9]
C = [2,4,6,7] #Result
```
`A` and `B` are both sorted with unique integers *(not sure if there is a way to tell Python about this property of the list)*. I need to preserve the order of the elements. ... | There is overhead to convert a list to a set, but a set is *substantially* faster than a list for those `in` tests.
You can instantly see if item `x` is in set `y` because there's a hash table being used underneath. No matter how large your set is, the lookup time is the same (basically instantaneous) - this is known ... |
View RDD contents in Python Spark? | 25,295,277 | 24 | 2014-08-13T20:13:50Z | 25,296,061 | 21 | 2014-08-13T21:01:53Z | [
"python",
"apache-spark"
] | Running a simple app in pyspark.
```
f = sc.textFile("README.md")
wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add)
```
I want to view RDD contents using foreach action:
```
wc.foreach(print)
```
This throws a syntax error:
```
SyntaxError: invalid syntax
```
What am I missing? | This error is because `print` isn't a function in Python 2.6.
You can either define a helper UDF that performs the print, or use the [\_\_future\_\_](https://docs.python.org/2/library/__future__.html) library to treat `print` as a function:
```
>>> from operator import add
>>> f = sc.textFile("README.md")
>>> def g(x... |
How can I pass a random number generating function into a Python class? | 25,295,377 | 3 | 2014-08-13T20:19:45Z | 25,295,436 | 8 | 2014-08-13T20:22:54Z | [
"python",
"random"
] | I'd like to be able to pass a random number generator into a class in Python. The class represents a research simulation in which a certain set of variables is initialized with draws from a Beta distribution which can be produced with `random.betavariate(2,2)` but I'd like to allow future users to plug in a different t... | Use [`partial`](https://docs.python.org/2/library/functools.html#functools.partial) from [`functools`](https://docs.python.org/2/library/functools.html) to bind the arguments and get a new function-like object back that you can invoke or give as an argument to the class.
```
>>> from functools import partial
>>> impor... |
Iterating over a large dictionary (over 2 billion entries) using python | 25,296,854 | 2 | 2014-08-13T21:55:05Z | 25,296,877 | 7 | 2014-08-13T21:56:45Z | [
"python",
"dictionary"
] | I am very new to python and I want to loop through a dictionary that contains around 2 billion entries. using:
```
for key,value in edge_dict.items():
```
However I am getting out of memory exception because it seems that it tries to load the whole thing and then loop through them. I had this problem with trivial thi... | ```
for key,value in edge_dict.iteritems():
```
I think is what you want
likewise if
```
for i in range (2000000000)
```
causes a memory error you can use a iterator
```
for i in xrange(2000000000)
```
iterators(and/or generators) only load one item at a time and are consumed as they are iterated ... this fixes m... |
how can I package a coroutine as normal function in event loop? | 25,299,887 | 7 | 2014-08-14T04:05:58Z | 25,300,115 | 8 | 2014-08-14T04:28:28Z | [
"python",
"python-3.x",
"coroutine",
"python-asyncio"
] | I am using *asyncio* for a network framework.
In below code(`low_level` is our low level function, `main` block is our program entry, `user_func` is user-defined function):
```
import asyncio
loop = asyncio.get_event_loop()
""":type :asyncio.AbstractEventLoop"""
def low_level():
yield from asyncio.sleep(2)
d... | Because `low_level` is a coroutine, it can *only* be used by running an `asyncio` event loop. If you want to be able to call it from synchronous code that *isn't* running an event loop, you have to provide a wrapper that actually launches an event loop and runs the coroutine until completion:
```
def sync_low_level():... |
Python3 error when running a finite or infinite generator function | 25,305,753 | 2 | 2014-08-14T10:23:42Z | 25,305,781 | 8 | 2014-08-14T10:25:00Z | [
"python",
"python-2.7",
"python-3.x",
"compiler-errors",
"generator"
] | I would like to execute the following finite or infinite generator function (depending on the value of the keyword `terminate`) in Python3.4:
```
def generate_integers(begin, terminate = None):
k = begin
while k<terminate or terminate==None:
yield k
k = k + 1
```
I run this function by the fo... | Change your test to first check if `terminate` is the `None` object:
```
while terminate is None or k < terminate:
```
`or` short-circuits; if `terminate is None` is true, the test for `k < terminate` is not executed.
Your code works in Python 2 because there Python tried to make everything orderable; `None` is sort... |
How to avoid reinstalling packages when building Docker image for Python projects? | 25,305,788 | 25 | 2014-08-14T10:25:20Z | 25,307,587 | 30 | 2014-08-14T12:01:48Z | [
"python",
"docker"
] | My Dockerfile is something like
```
FROM my/base
ADD . /srv
RUN pip install -r requirements.txt
RUN python setup.py install
ENTRYPOINT ["run_server"]
```
Every time I build a new image, dependencies have to be reinstalled, which could be very slow in my region.
One way I think of to `cache` packages that have been... | Try to build with below Dockerfile.
```
FROM my/base
WORKDIR /srv
ADD ./requirements.txt /srv/requirements.txt
RUN pip install -r requirements.txt
ADD . /srv
RUN python setup.py install
ENTRYPOINT ["run_server"]
```
If there are some changes on `.`(your project), docker skip `pip install` line by using cache.
Dock... |
check if the file format is different with the file name extension in Python, Javascript? | 25,306,239 | 2 | 2014-08-14T10:50:06Z | 25,306,334 | 7 | 2014-08-14T10:54:58Z | [
"javascript",
"jquery",
"python",
"django"
] | I have an uploader which has file format validation (only some video formats can be uploaded).
However users can simply change the original file name extension and pass the validation (e.g. rename `file.pdf` to `file.mov` and upload)!
Now I need to check and validate if the file format matches the file extension or n... | In python you can use [`python-magic`](https://github.com/ahupp/python-magic)
Quote from the Readme:
`python-magic is a python interface to the libmagic file type identification library. libmagic identifies file types by checking their headers according to a predefined list of file types.`
It analyses the file heade... |
How to add additional column to Django QuerySet | 25,308,828 | 2 | 2014-08-14T13:08:46Z | 34,755,617 | 7 | 2016-01-12T23:17:28Z | [
"python",
"sql",
"django",
"django-models"
] | I have a QuerySet with Books and I would like to add a `score` field to every Book result.
```
qs = Book.objects.all()
```
In raw SQL I would write:
```
SELECT
*,
(
(SELECT COUNT(*) FROM votes WHERE value=1 AND book=b.id) -
(SELECT COUNT(*) FROM votes WHERE value=-1 AND book=b.id)
) AS s... | Raw SQL is *not* the only way. You can use a `Value()` expression (see docs [here](https://docs.djangoproject.com/en/1.9/ref/models/expressions/#value-expressions)), like so:
```
MyModel.objects.all().annotate(mycolumn=Value('xxx', output_field=CharField())
``` |
Attaching a process with pdb | 25,308,847 | 8 | 2014-08-14T13:09:42Z | 25,329,467 | 12 | 2014-08-15T15:38:20Z | [
"python",
"debugging",
"pdb"
] | I have a python script that I suspect that there is a deadlock. I was trying to debug with `pdb` but if I go step by step it doesn't get the deadlock, and by the output returned I can see that it's not being hanged on the same iteration. I would like to attach my script to a debugger only when it gets locked, is it pos... | At this time, **pdb** does not have the ability to halt and begin debugging on a running program. You have a few other options:
**GDB**
You can use GDB to debug at the C level. This is a bit more abstract because you're poking around Python's C source code rather than your actual Python script, but it can be useful f... |
Issue with a python function returning a generator or a normal object | 25,313,283 | 3 | 2014-08-14T16:41:43Z | 25,313,357 | 10 | 2014-08-14T16:45:57Z | [
"python",
"iteration",
"yield"
] | I defined the function `f` as
```
def f(flag):
n = 10
if flag:
for i in range(n):
yield i
else:
return range(n)
```
But `f` returns a generator no matter what `flag` is:
```
>>> f(True)
<generator object f at 0x0000000003C5EEA0>
>>> f(False)
<generator object f at 0x000000000... | A function containing a `yield` statement **always** returns a generator object.
Only when you iterate over that generator object will the code in the function be executed. Until that time, no code in the function is executed and Python *cannot know* that you'll just return.
Note that using `return` in a generator fu... |
if-else, using the True and False statements on python. skulpt.org | 25,314,003 | 2 | 2014-08-14T17:25:46Z | 25,314,047 | 9 | 2014-08-14T17:28:49Z | [
"python",
"if-statement"
] | This is my code where I had to create it so it allows
1. The user inputs the lengths of three sides of a triangle as Length1, Length2 and Length3
2. If any two sides have the same length the program outputs "Isosceles"
3. Otherwise the program outputs "Not isosceles"
However, the output part doesn't seem like working... | The problem is that Python interprets
```
if Length1 == Length2 is True:
```
like
```
if Length1 == Length2 and Length2 is True:
```
[Comparison operators, like `<`, `==`, or `is` are chained.](http://stackoverflow.com/a/101945/1639625) This is very useful for, e.g. `a < b < c`, but it can also result in some unexp... |
Cell-var-from-loop warning from Pylint | 25,314,547 | 16 | 2014-08-14T17:57:06Z | 25,314,665 | 19 | 2014-08-14T18:04:10Z | [
"python",
"lambda",
"closures"
] | For the following code:
```
for sort_key, order in query_data['sort']:
results.sort(key=lambda k: get_from_dot_path(k, sort_key),
reverse=(order == -1))
```
Pylint reported an error:
> Cell variable sort\_key defined in loop (cell-var-from-loop)
Could anyone give a hint what is happening here? ... | The name `sort_key` in the body of the `lambda` will be looked up when the function is actually called, so it will see what ever value `sort_key` had most recently. Since you are calling `sort` immediately, the value of `sort_key` will not change before the resulting function object is used, so you can safely ignore th... |
Call a Python function from within a C program | 25,316,485 | 2 | 2014-08-14T19:52:02Z | 25,316,487 | 7 | 2014-08-14T19:52:02Z | [
"python",
"c++",
"c",
"python-c-api"
] | I have an application in C and at some point I need to solve a non-linear optimization problem. Unfortunately AFAIK there are very limited resources to do that in C (please let me know otherwise). However it is quite simple to do it in Python, e.g. [scipy.optimize.minimize](http://docs.scipy.org/doc/scipy-0.14.0/refere... | There are some things that you have to make sure are in place in order to make this work:
1. Make sure you have Python installed (you may need the `python-dev` package).
2. Locate your `Python.h` file, e.g. by `locate Python.h`. One of the occurrences should be in a sub(sub)folder in the `include` folder, e.g. the pat... |
Python: Inline if statement else do nothing | 25,319,053 | 4 | 2014-08-14T23:17:19Z | 25,319,292 | 8 | 2014-08-14T23:45:32Z | [
"python",
"django",
"if-statement",
"conditional",
"inline"
] | Assigning a Django Model's field to a value if it matches a condition.
```
g = Car.objects.get(pk=1234)
g.data_version = my_dict['dataVersion'] if my_dict else expression_false # Do nothing??
```
How do I do nothing in that case? We can't do `if conditional else pass`.
I know I can do:
```
if my_dict:
g.data_ve... | No, you can't do exactly what you are describing, as it wouldn't make sense. You are assigning to the variable `g.data_version`... so you must assign something. What you describe would be like writing:
```
g.data_version = # There is nothing else here
```
Which is obviously invalid syntax. And really, there's no rea... |
How to match spaces that are NOT in a multiple of 4? | 25,320,471 | 2 | 2014-08-15T02:33:34Z | 25,320,508 | 7 | 2014-08-15T02:38:30Z | [
"python",
"regex",
"notepad++"
] | I'm re-formatting a Python script using notepad++, but some lines are not indented by 4 (or 8, 12, 16, etc.) spaces.
So I need to **match consecutive leading white-spaces** (i.e. indentation at beginning of each line), which are **NOT in multiple of 4**, i.e. spaces in number of 1, 2, 3, 5, 6, 7, 9, 10, 11, etc.
e.g.... | A character class can only contain .. a set of characters, and thus `[^..]` is not suitable for a general negation. The regular expression `[^( {16}| {12}| {8}| {4})]` is equivalent to `[^( {16}|284]` which would match every *character* not listed.
Now, to match *not* a multiple of 4 spaces is the same as finding `n m... |
Vagrant Installing Anaconda Python? | 25,321,139 | 6 | 2014-08-15T04:10:52Z | 28,035,048 | 10 | 2015-01-19T23:04:09Z | [
"python",
"vagrant",
"puppet",
"vagrantfile"
] | [Anaconda python](http://docs.continuum.io/anaconda/install.html#linux-install) is installed (in linux) via a bash script. I am trying to use Vagrant provisioning to get Anacaonda Python installed.
In the bash script (following the documentation [bootstrap.sh example](https://docs.vagrantup.com/v2/getting-started/prov... | In your bootstrap.sh just include something like:
```
miniconda=Miniconda3-3.7.4-Linux-x86_64.sh
cd /vagrant
if [[ ! -f $miniconda ]]; then
wget --quiet http://repo.continuum.io/miniconda/$miniconda
fi
chmod +x $miniconda
./$miniconda -b -p /opt/anaconda
cat >> /home/vagrant/.bashrc << END
# add for anaconda inst... |
python Shorten the embedded try-except block | 25,321,677 | 2 | 2014-08-15T05:32:18Z | 25,321,723 | 7 | 2014-08-15T05:38:27Z | [
"python",
"python-requests",
"try-except"
] | I've been using `try-except` inside another `try-except`, when I try to open a url which may or may not lack an 'http://' header.
But the code looks messy. I'm wondering if python has some nicer ways to deal with such needs. Actually I've read the 'with' keyword.. Which somehow, I feel, will make the code harder to re... | First assemble a list of potential URLs in order of priority:
```
potential_urls = [link, 'http://' + link, 'http://www.' + link]
```
Also keep a list of errors youâve encountered:
```
errors_encountered = []
```
Then go through the list, `break`ing if it works.
```
res = None
for url in potential_urls:
try:... |
Email Validation from WTForm using Flask | 25,324,113 | 7 | 2014-08-15T09:25:43Z | 25,344,170 | 9 | 2014-08-16T21:29:55Z | [
"python",
"validation",
"email",
"flask-wtforms"
] | I'm following a Flask tutorial from <http://code.tutsplus.com/tutorials/intro-to-flask-adding-a-contact-page--net-28982> and am currently stuck on the validation step:
The old version had the following:
```
from flask.ext.wtf import Form, TextField, TextAreaField, SubmitField, validators, ValidationError
class Conta... | Try this:
```
from flask.ext.wtf import Form
from wtforms import validators
from wtforms.fields.html5 import EmailField
class ContactForm(Form):
email = EmailField('Email address', [validators.DataRequired(), validators.Email()])
``` |
get difference between 3 lists | 25,324,136 | 3 | 2014-08-15T09:27:41Z | 25,324,329 | 8 | 2014-08-15T09:42:13Z | [
"python",
"list",
"set"
] | I am working on differences of lists.
```
>>a = [1, 2, 3]
>>b = [2, 4, 5]
>>c = [3, 2, 6]
```
Symmetric difference between 2 sets can be done using:
```
>>z = set(a).symmetric_difference(set(b))
>>print z
>>set([1, 3, 4, 5])
```
How to get difference between 3 sets?
For difference of 3 sets, expected output is :
`... | Just subtract the intersection from the union:
```
In [1]: a = set([1, 2, 3])
In [2]: b = set([2, 4, 5])
In [3]: c = set([3, 2, 6])
In [4]: (a | b | c) - (a & b & c)
Out[4]: set([1, 3, 4, 5, 6])
```
Or, to generalise to an arbitrary collection of sets:
```
In [10]: l = [a, b, c]
In [11]: reduce(set.union, l) - r... |
What kind of Encoding does a standard midi file use? | 25,324,151 | 2 | 2014-08-15T09:28:42Z | 25,324,208 | 7 | 2014-08-15T09:33:44Z | [
"python",
"encoding",
"midi"
] | What kind of Encoding does a standard midi file use?
Here's what brought this question up:
```
with open(path + "/OneChance1.mid") as f:
for line in f.readline():
print(line)
```
Here I am simply trying to read a midi file to scour its contents. I then receive this error message: | UnicodeDecodeError: 'charmap' code... | MIDI files are **binary content**. By opening the file as a text file however, Python applies the default system encoding in trying to decode the text as Unicode.
Open the file in *binary mode* instead:
```
with open(midifile, 'rb') as mfile:
leader = mfile.read(4)
if leader != b'MThd':
raise ValueErr... |
PIL Clipboard Image to Base64 string | 25,324,816 | 4 | 2014-08-15T10:20:40Z | 25,327,412 | 9 | 2014-08-15T13:36:42Z | [
"python",
"encoding",
"base64",
"python-imaging-library",
"clipboard"
] | I want to get the image in the clipboard and convert its data into a base64 encoded string so that I can put that into a HTML img tag.
I've tried the following:
```
from PIL import ImageGrab
from base64 import encodestring
img = ImageGrab.grabclipboard()
imgStr = encodestring(img.fp.read())
```
Plus some other combi... | `ImageGrab.grabclipboard()` returns an `Image` object. You need to convert it to a known image format, like jpeg or png, then to encode the resulting string in base64 to be able to
use it within an HTML img tag:
```
import cStringIO
jpeg_image_buffer = cStringIO.StringIO()
image.save(jpeg_image_buffer, format="JPEG")... |
Difference between .string and .text BeautifulSoup | 25,327,693 | 14 | 2014-08-15T13:54:05Z | 25,328,374 | 23 | 2014-08-15T14:34:28Z | [
"python",
"beautifulsoup"
] | I noticed something odd about when working with BeautifulSoup and couldn't find any documentation to support this so I wanted to ask over here.
Say we have a tags like these that we have parsed with BS:
```
<td>Some Table Data</td>
<td></td>
```
The [official documented](http://www.crummy.com/software/BeautifulSoup/... | `.string` on a `Tag` type object returns a `NavigableString` type object. On the other hand, `.text` gets all the child strings and return concatenated using the given separator. Return type of .text is `unicode` object.
From the [documentation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring), A... |
How can I change the font size using seaborn FacetGrid? | 25,328,003 | 5 | 2014-08-15T14:12:39Z | 25,394,017 | 11 | 2014-08-19T22:29:59Z | [
"python",
"seaborn"
] | I have plotted my data with `factorplot` in `seaborn` and get `facetgrid` object, but still cannot understand how the following attributes could be set in such a plot:
1. Legend size: when I plot lots of variables, I get very small legends, with small fonts.
2. Font sizes of y and x labels (a similar problem as above) | You can scale up the fonts in your call to `sns.set()`.
```
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='up... |
python 2.7: cannot pip on windows "bash: pip: command not found" | 25,328,818 | 14 | 2014-08-15T14:59:52Z | 25,331,771 | 41 | 2014-08-15T18:09:13Z | [
"python",
"bash",
"numpy",
"matplotlib",
"python-dateutil"
] | I am trying to install the SciPy stack located at scipy(dot)org/stackspec(dot)html [I am only allowed 2 links; trying to use them wisely]. I realize that there are much easier ways to do this, but I think there is a lot to be learned by doing it manually. I am relatively new to a lot of this stuff, so I apologize if I ... | On Windows, `pip` lives in `C:\[pythondir]\scripts`.
So you'll need to add that to your system path in order to run it from the command prompt. You could alternatively `cd` into that directory each time, but that's a hassle.
See the top answer here for info on how to do that:
[Adding Python Path on Windows 7](http://... |
Python local variables in methods | 25,330,864 | 2 | 2014-08-15T17:04:22Z | 25,330,876 | 9 | 2014-08-15T17:05:33Z | [
"python",
"oop",
"python-3.x"
] | I am learning Python 3 and I have very fundamental question regarding object oriented programming in Python. Here is my code.
```
class pet:
number_of_legs = 0
def count_legs(self):
print("I have %s legs" %dog.number_of_legs)
dog = pet()
dog.number_of_legs = 4
dog.count_legs()
```
This code prints:
... | `dog` is looked up as a global *at runtime*; had you named your variable differently the code *would* have thrown an error:
```
>>> class pet:
... number_of_legs = 0
... def count_legs(self):
... print("I have %s legs" %dog.number_of_legs)
...
>>> cat = pet()
>>> cat.number_of_legs = 4
>>> cat.count_l... |
ManagementForm data is missing or has been tampered with | 25,331,500 | 2 | 2014-08-15T17:50:19Z | 25,331,567 | 8 | 2014-08-15T17:54:59Z | [
"python",
"django",
"django-forms",
"django-templates",
"django-views"
] | I am trying to create a formset to save records in a go. But, I keep getting the error when I submit my form. And if possible please as tell me how should I save my batch of records.
My views.py:
```
def weekly_progress(request):
ProgressFormSet = formset_factory(WeeklyProgressReportForm, extra=16)
formset = ... | You have to render the management form in your template. The [docs](https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform) explain why and how; some selected quotes:
> This form is used by the formset to manage the collection of forms contained in the formset. If you donât pro... |
Performance of subprocess.check_output vs subprocess.call | 25,333,537 | 14 | 2014-08-15T20:14:13Z | 25,703,638 | 12 | 2014-09-06T18:50:44Z | [
"python",
"linux",
"subprocess",
"wine"
] | I've been using `subprocess.check_output()` for some time to capture output from subprocesses, but ran into some performance problems under certain circumstances. I'm running this on a RHEL6 machine.
The calling Python environment is linux-compiled and 64-bit. The subprocess I'm executing is a shell script which event... | Reading the docs, both `subprocess.call` and `subprocess.check_output` are use-cases of `subprocess.Popen`. One minor difference is that `check_output` will raise a Python error if the subprocess returns a non-zero exit status. The greater difference is emphasized in the bit about `check_output` (my emphasis):
> The f... |
PIP install "error: package directory 'X' does not exist" | 25,336,150 | 7 | 2014-08-16T01:27:50Z | 25,384,070 | 7 | 2014-08-19T12:58:49Z | [
"python",
"pip",
"packaging",
"easy-install"
] | I am trying to install [this package](https://github.com/TheChymera/RTbatch/tree/e53e419c6a7ea1fc4e3b2de8ffd57478720192ab) via PIP. It gives me the following error:
```
error: package directory 'RTbatch' does not exist
```
I find this weird, because [the relevant `setup.py`](https://github.com/TheChymera/RTbatch/blob... | `py_modules` takes a list of module names, not files. Your call looks for `RTBatch/py.py` and `RTBatch_cli/py.py`. |
Overloading (or alternatives) in Python API design | 25,336,481 | 3 | 2014-08-16T02:46:22Z | 25,336,526 | 7 | 2014-08-16T02:58:19Z | [
"python",
"overloading"
] | I have a large existing program library that currently has a .NET binding, and I'm thinking about writing a Python binding. The existing API makes extensive use of signature-based overloading. So, I have a large collection of static functions like:
```
Circle(p1, p2, p3) -- Creates a circle through three points
Circle... | One option is to exclusively keyword arguments in the constructor, and include logic to figure out what should be used:
```
class Circle(object):
def __init__(self, points=(), radius=None, curves=()):
if radius and len(points) == 1:
center_point = points[0]
# Create from radius/cent... |
Why can't I iterate twice over the same data? | 25,336,726 | 13 | 2014-08-16T03:42:47Z | 25,336,738 | 13 | 2014-08-16T03:45:44Z | [
"python"
] | Honestly I am a little confused here, why can't I iterate twice over the same data?
```
def _view(self,dbName):
db = self.dictDatabases[dbName]
data = db[3]
for row in data:
print("doing this one time")
for row in data:
print("doing this two times")
```
This will print out "doing thi... | It's because `data` is an iterator, an you can consume an iterator only once. For example:
```
lst = [1, 2, 3]
it = iter(lst)
next(it)
=> 1
next(it)
=> 2
next(it)
=> 3
next(it)
=> StopIteration
```
If we are traversing some data using a `for` loop, that last `StopIteration` will cause it to exit the first time. If w... |
Why can't I iterate twice over the same data? | 25,336,726 | 13 | 2014-08-16T03:42:47Z | 25,336,739 | 7 | 2014-08-16T03:45:58Z | [
"python"
] | Honestly I am a little confused here, why can't I iterate twice over the same data?
```
def _view(self,dbName):
db = self.dictDatabases[dbName]
data = db[3]
for row in data:
print("doing this one time")
for row in data:
print("doing this two times")
```
This will print out "doing thi... | Once an iterator is exhausted, it will not yield any more.
```
>>> it = iter([3, 1, 2])
>>> for x in it: print(x)
...
3
1
2
>>> for x in it: print(x)
...
>>>
``` |
Is there an usage `_tuple` in python? | 25,337,530 | 4 | 2014-08-16T06:23:39Z | 25,337,545 | 7 | 2014-08-16T06:25:59Z | [
"python",
"namedtuple",
"python-internals"
] | I read the official documentation for `collections.namedtuple` today and found `_tuple` mentioned in the `__new__` method. I did not find where the `_tuple` defined.
Here is the code, you can try it in Python - it does not raise any error.
```
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
class Point(tupl... | From the generic [source code](http://hg.python.org/cpython/file/e831a98b3f43/Lib/collections/__init__.py#l266) (you can see the source code generated for this specific namedtuple by printing `Point._source`):
```
from builtins import property as _property, tuple as _tuple
```
So `_tuple` here is just an alias for bu... |
setuptools vs. distutils: Why is distutils still a thing? | 25,337,706 | 46 | 2014-08-16T06:49:44Z | 25,372,045 | 24 | 2014-08-18T21:07:46Z | [
"python",
"packaging",
"setuptools",
"distutils"
] | Python has a confusing history of tools that can be used to package and describe projects: These include *distutils* in the Standard Library, *distribute*, *distutils2*, and *setuptools* and maybe more. It appears that *distribute* and *distutils2* were discontinued in favor of *setuptools*, which leaves two competing ... | Have a look at this. It explains all the packaging methods very well, and might help answer your question to some extent: [webpage](http://stackoverflow.com/questions/6344076/differences-between-distribute-distutils-setuptools-and-distutils2)
> **Distutils** is still the standard tool for packaging in Python. It is in... |
Check if string has date, any format | 25,341,945 | 4 | 2014-08-16T17:03:04Z | 25,341,965 | 7 | 2014-08-16T17:05:03Z | [
"python",
"string",
"osx",
"date"
] | How do I check if a string can be parsed to a date?
* Jan 19, 1990
* January 19, 1990
* Jan 19,1990
* 01/19/1990
* 01/19/90
* 1990
* Jan 1990
* January1990
These are all valid dates. If there's any concern regarding the lack of space in between stuff in item #3 and the last item above, that can be easily remedied via... | Have a look at the `parse` function in [`dateutils.parser`](https://pypi.python.org/pypi/python-dateutil). It's capable of parsing almost any string to a `datetime` object.
If you simply want to know whether a particular string *could* represent a date, you could try the following function:
```
from dateutil.parser i... |
Computing and drawing vector fields | 25,342,072 | 6 | 2014-08-16T17:18:43Z | 25,343,170 | 19 | 2014-08-16T19:24:53Z | [
"python",
"numpy"
] | I am trying to draw a potential field for a given object using the following formula:
```
U=-α_goal*e^(-((x-x_goal )^2/a_goal +(y-y_goal^2)/b_goal ) )
```
using the following code
```
# Set limits and number of points in grid
xmax = 10.0
xmin = -xmax
NX = 20
ymax = 10.0
ymin = -ymax
NY =... | First off, let's evaluate it on a regular grid, similar to your example code. (On a side note, you have an error in the code to evaluate your equation. It's missing a negative inside the `exp`.):
```
import numpy as np
import matplotlib.pyplot as plt
# Set limits and number of points in grid
y, x = np.mgrid[10:-10:10... |
Python argparse: default argument stored as string, not list | 25,343,868 | 3 | 2014-08-16T20:51:28Z | 25,344,003 | 7 | 2014-08-16T21:08:22Z | [
"python",
"command-line-arguments",
"argparse"
] | I cannot figure out this behaviour of argparse from the documentation:
```
import argparse
parser.add_argument("--host", metavar="", dest="host", nargs=1, default="localhost", help="Name of host for database. Default is 'localhost'.")
args = parser.parse_args()
print(args)
```
Here is the output with and without an... | Remove the "nargs" keyword argument. Once that argument is defined the argparse assumes your argument will be a list (nargs=1 meaning a list with 1 element) |
Method overloading for different argument type in python | 25,343,981 | 7 | 2014-08-16T21:04:27Z | 25,344,445 | 7 | 2014-08-16T22:07:18Z | [
"python",
"oop",
"design-patterns"
] | I'm writing a preprocessor in python, part of which works with an AST.
There is a `render()` method that takes care of converting various statements to source code.
Now, I have it like this (shortened):
```
def render(self, s):
""" Render a statement by type. """
# code block (used in structures)
if isi... | If you're using Python 3.4 (or are willing to install the [backport](https://pypi.python.org/pypi/singledispatch) for Python 2.6+), you can use [`functools.singledispatch`](https://docs.python.org/3/library/functools.html#functools.singledispatch) for this\*:
```
from functools import singledispatch
class S_Block(obj... |
list comprehension replace for loop in 2D matrix | 25,345,770 | 4 | 2014-08-17T02:22:27Z | 25,345,853 | 9 | 2014-08-17T02:37:01Z | [
"python",
"int",
"output",
"list-comprehension"
] | I try to use list comprehension to replace the for loop.
original file is
```
2 3 4 5 6 3
1 2 2 4 5 5
1 2 2 2 2 4
```
for loop
```
line_number = 0
for line in file:
line_data = line.split()
Cordi[line_number, :5] = line_data
line_number += 1
```
output is
```
[[2 3 4 5 6 3]
[1 2 2 4 5 5]
[1 2 2 2 2... | You have the order of your loops swapped; they should be ordered in the same way they would be nested, from left to right:
```
[int(x) for line in data for x in line.split()]
```
This loops over `data` first, then for each `line` iteration, iterates over `line.split()` to produce `x`. You then produce one *flat* list... |
add excel file attachment when sending python email | 25,346,001 | 3 | 2014-08-17T03:10:09Z | 25,394,911 | 7 | 2014-08-20T00:11:08Z | [
"python",
"email",
"document",
"attachment"
] | How do i add a document attachment when sending an email with python ?
i get the email to send
(please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to send every 30 min, just have to change 5 to 1800)
here is my code so far. how do i attach a document from my computer?
... | This is the code that worked for me- to send an email with an attachment in python
```
#!/usr/bin/python
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
def send_ma... |
Removing list of words from a string | 25,346,058 | 7 | 2014-08-17T03:23:03Z | 25,346,119 | 14 | 2014-08-17T03:36:54Z | [
"python",
"string"
] | I have a list of stopwords. And I have a search string. I want to remove the words from the string.
As an example:
```
stopwords=['what','who','is','a','at','is','he']
query='What is hello'
```
Now the code should strip 'What' and 'is'. However in my case it strips 'a', as well as 'at'. I have given my code below. W... | This is one way to do it:
```
query = 'What is hello'
stopwords = ['what','who','is','a','at','is','he']
querywords = query.split()
resultwords = [word for word in querywords if word.lower() not in stopwords]
result = ' '.join(resultwords)
print result
```
I noticed that you want to also remove a word if its lower... |
How does scrapy use rules? | 25,347,279 | 5 | 2014-08-17T07:48:52Z | 25,352,434 | 8 | 2014-08-17T18:39:08Z | [
"python",
"scrapy",
"response"
] | I'm new to using Scrapy and I wanted to understand how the rules are being used within the CrawlSpider.
If I have a rule where I'm crawling through the yellowpages for cupcake listings in Tucson, AZ, how does yielding a URL request activate the rule - specifically how does it activiate the restrict\_xpath attribute?
... | The rules attribute for a [`CrawlSpider`](http://scrapy.readthedocs.org/en/latest/topics/spiders.html#crawlspider) specify how to extract the links from a page and which callbacks should be called for those links. They are handled by the default `parse()` method implemented in that class -- [look here to read the sourc... |
Can Python pickle lambda functions? | 25,348,532 | 9 | 2014-08-17T10:52:16Z | 25,353,243 | 17 | 2014-08-17T20:14:56Z | [
"python",
"python-2.7",
"lambda",
"pickle"
] | I have read in a number of threads that Python `pickle`/`cPickle` cannot pickle lambda functions. However the following code works, using Python 2.7.6:
```
import cPickle as pickle
if __name__ == "__main__":
s = pickle.dumps(lambda x, y: x+y)
f = pickle.loads(s)
assert f(3,4) == 7
```
So what is going on... | Yes, python can pickle lambda functions⦠but only if you have something that uses `copy_reg` to register **how** to pickle lambda functions -- the package `dill` loads the `copy_reg` you need into the pickle registry for you, when you `import dill`.
```
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compa... |
two Lists to Json Format in python | 25,348,640 | 3 | 2014-08-17T11:07:06Z | 25,348,658 | 7 | 2014-08-17T11:09:12Z | [
"python",
"list",
"dictionary"
] | I have two lists
```
a=["USA","France","Italy"]
b=["10","5","6"]
```
I want the end result to be in json like this.
```
[{"country":"USA","wins":"10"},
{"country":"France","wins":"5"},
{"country":"Italy","wins":"6"},
]
```
I used zip(a,b) to join two but couldn't name it | Using [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions):
```
>>> [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
[{'country': 'USA', 'wins': '10'},
{'country': 'France', 'wins': '5'},
{'country': 'Italy', 'wins': '6'}]
```
Use [`json.dumps`](https:/... |
Email django from using EmailMultiAlternatives | 25,350,849 | 2 | 2014-08-17T15:48:52Z | 25,350,998 | 7 | 2014-08-17T16:05:05Z | [
"python",
"django",
"email",
"html-email",
"mailing"
] | I'm trying to send a mail using Django with **EmailMultiAlternatives**. It works well but in "from" says "info"
Is it posible to say my name for example? How can I do this?
Here is my code:
```
subject, from_email, to = 'Afiliations', 'info@domain.com', 'other@domain.com'
text_content = 'Afiliation is working.'
t = ... | For the `Name` to be displayed instead of the username part of the email, just do
```
from_email = "info@domain.com <info@domain.com>"
```
OR
```
from_email = "Name <info@domain.com>"
``` |
How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html? | 25,351,968 | 8 | 2014-08-17T17:52:52Z | 25,352,191 | 11 | 2014-08-17T18:15:57Z | [
"python",
"html",
"pandas"
] | I converted a pandas dataframe to an html output using the `DataFrame.to_html` function. When I save this to a separate html file, the file shows truncated output.
For example, in my TEXT column,
`df.head(1)` will show
*The film was an excellent effort...*
instead of
*The film was an excellent effort in deconstruc... | Set the `display.max_colwidth` option to `-1`:
```
pd.set_option('display.max_colwidth', -1)
```
[`set_option` docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html#pandas-set-option) |
How to collect error message from stderr using a daemonized uwsgi? | 25,352,357 | 4 | 2014-08-17T18:32:20Z | 27,452,350 | 7 | 2014-12-12T21:25:03Z | [
"python",
"logging",
"flask",
"uwsgi",
"stderr"
] | I run my uwsgi with `--daemonzie=~/uwsgi.log`.
I use flask. In my flask app, if I print some message into `stdin`, it will show on `uwsgi.log`. If I print to `stderr`, `uwsgi.log` won't show these message. How should I enable uwsgi to collect message from `stderr`.
The major problem is that I can not let uwsgi.log co... | Flask is catching your exceptions, make sure, you set `PROPAGATE_EXCEPTIONS` in config.
```
from flask import Flask
application = Flask(__name__)
application.config['PROPAGATE_EXCEPTIONS'] = True
@application.route('/')
def hello_world():
return 'Hello World!'
```
Uwsgi logging can be set with
```
--logto /va... |
llvmpy on Ubuntu 14.04 | 25,353,809 | 5 | 2014-08-17T21:30:41Z | 25,437,446 | 8 | 2014-08-21T23:23:24Z | [
"python",
"llvm"
] | I am trying to install llvmpy on ubuntu 14.04.
```
uname -a
Linux -esktop 3.13.0-30-generic #55-Ubuntu SMP Fri Jul 4 21:40:53 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
lsb_release -a
LSB Version: core-2.0-amd64:core-2.0-noarch:core-3.0-amd64:core-3.0-noarch:core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noa... | llvmpy requires llvm 3.3 at the moment. This is available, but not the default on Ubuntu 14.04 (which defaults to the newer llvm 3.4). First, install llvm3.3:
```
sudo apt-get install llvm-3.3 llvm-3.3-runtime
```
Then, we need to tell pip to use the older llvm.
```
sudo sh -c "LLVM_CONFIG_PATH=/usr/bin/llvm-config-... |
count how many of an object type there are in a list Python | 25,355,705 | 4 | 2014-08-18T02:47:29Z | 25,355,727 | 10 | 2014-08-18T02:50:30Z | [
"python",
"list",
"object-type"
] | If I have a list in python:
```
a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]
```
Is there a very easy way to count the amount of an object type there are in `a`?
Something simpler than the following but produces the same result:
```
l = [i for i in a if type(a[i]) == int]
print(len(l))
```
Hopefully I made myse... | Use `isinstance` to do your type checks, and then `sum` the Boolean values to get the count (`True` is 1, `False` is 0):
```
sum(isinstance(x, int) for x in a)
``` |
Need to dump entire DOM tree with element id from selenium server | 25,356,440 | 5 | 2014-08-18T04:39:06Z | 25,646,401 | 7 | 2014-09-03T14:03:15Z | [
"python",
"selenium",
"ghostdriver"
] | I have been using python selenium for web automation testing. The key part of automation is to find the right element for a user-visible object in a HTML page. The following API will work most of the time, but not all the time.
```
find_element_by_xxx, xxx can be id, name, xpath, tag_name etc.
```
When HTML page is ... | ### The Problem
Ok, so there may be cases where you need to perform some substantial processing of a page on the client (Python) side rather than on the server (browser) side. For instance, if you have some sort of machine learning system already written in Python and it needs to analyze the whole page before performi... |
Save logs - SimpleHTTPServer | 25,360,798 | 2 | 2014-08-18T10:07:47Z | 25,375,077 | 8 | 2014-08-19T02:59:30Z | [
"python",
"logging",
"save",
"simplehttpserver"
] | How can I save the output from the console like
"192.168.1.1 - - [18/Aug/2014 12:05:59] code 404, message File not found"
to a file?
Here is the code:
```
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler... | `BaseHTTPRequestHandler.log_message()` prints all log messages by writing to `sys.stderr`. You have two choices:
1) Continue using `BaseHTTPRequestHandler.log_message()`, but change the value of `sys.stderr`:
```
import sys
sys.stderr = open('logfile.txt', 'w')
httpd.serve_forever()
```
2) Create a new `xxxRequestHa... |
Force use of scientific style for basemap colorbar labels | 25,362,614 | 4 | 2014-08-18T11:48:49Z | 25,370,358 | 8 | 2014-08-18T19:07:37Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] | String formatting can by used to specify scientific notation for matplotlib.basemap colorbar labels:
```
cb = m.colorbar(cs, ax=ax1, format='%.4e')
```
But then each label is scientifically notated with the base.
If numbers are large enough, the colobar automatically reduces them to scientific notation, placing the ... | There's no one-line method, but you can do this by updating the colorbar's `formatter` and then calling `colorbar.update_ticks()`.
```
import numpy as np
import matplotlib.pyplot as plt
z = np.random.random((10,10))
fig, ax = plt.subplots()
im = ax.imshow(z)
cb = fig.colorbar(im)
cb.formatter.set_powerlimits((0, 0)... |
Clarification in the Theano tutorial | 25,366,863 | 4 | 2014-08-18T15:27:52Z | 25,367,188 | 11 | 2014-08-18T15:46:25Z | [
"python",
"numpy",
"theano",
"gradient-descent",
"deep-learning"
] | I am reading [this tutorial](http://nbviewer.ipython.org/github/craffel/theano-tutorial/blob/master/Theano%20Tutorial.ipynb) provided on the [home page of Theano documentation](http://deeplearning.net/software/theano/index.html)
I am not sure about the code given under the gradient descent section.
![enter image desc... | The initialization of 'param\_update' using theano.shared() only tells Theano to reserve a variable that will be used by theano functions. This initialization code is only called once, and will not be used later on to reset the value of 'param\_update' to 0.
The actual value of 'param\_update' will be updated accordin... |
Tuple or list when using 'in' in an 'if' clause? | 25,368,337 | 16 | 2014-08-18T16:58:06Z | 25,368,371 | 26 | 2014-08-18T17:00:12Z | [
"python",
"list",
"optimization",
"tuples",
"python-internals"
] | Which approach is better? Using a tuple, like:
```
if number in (1, 2):
```
or a list, like:
```
if number in [1, 2]:
```
Which one is recommended for such uses and why (both logical and performance wise)? | The CPython interpreter *replaces the second form with the first*.
That's because loading the tuple from a constant is one operation, but the list would be 3 operations; load the two integer contents and build a new list object.
Because you are using a list literal that isn't otherwise reachable, it is substituted fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.