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 |
|---|---|---|---|---|---|---|---|---|---|
numpy.vectorize returns incorrect values | 26,316,357 | 5 | 2014-10-11T15:43:33Z | 26,316,780 | 10 | 2014-10-11T16:30:02Z | [
"python",
"numpy",
"vectorization"
] | I am having some problems with the `numpy.vectorize` function.
I have defined a function that works well for single element input but the vectorized version returns different results - What am I doing wrong?
**Code:**
```
def c_inf_comp(z):
if z>0:
return np.exp(-1./(z*z))
else:
return 0
>>... | Because you don't specify `otypes` (the output data type) when you vectorize your function, NumPy assumes you want to return an array of `int32` values.
When given `x` the vectorized function `vfunz` first sees `-10.`, returns the integer `0`, and so decides that the `dtype` of the returned array should be `int32`.
T... |
What does 'r' mean before a Regex pattern? | 26,318,287 | 2 | 2014-10-11T19:12:40Z | 26,318,301 | 9 | 2014-10-11T19:14:13Z | [
"python",
"regex",
"string",
"syntax"
] | I found the following regex substitution example from the [documentation](https://docs.python.org/2/library/re.html) for Regex. I'm a little bit confused as to what the prefix `r` does before the string?
```
re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
... r'static PyObject*\npy_\1(void)\n{',
... ... | Placing `r` or `R` before a string literal creates what is known as a [raw-string](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals) literal. Raw strings do not process escape sequences (`\n`, `\b`, etc.) and are thus commonly used for Regex patterns, which often contain a lot of `\` ... |
How to install SciPy stack with pip and homebrew? | 26,319,762 | 5 | 2014-10-11T22:08:30Z | 26,322,102 | 8 | 2014-10-12T05:12:48Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | I'm trying to install the basic scipy stack (numpy, scipy, matplotlib, pandas, sympy, ipython, nose) into a virtualenv; currently, I'm using OSX Mountain Lion. From the installation pages for these packages, as well as various threads here and around the web, it seems that pandas, sympy, and nose can be installed easil... | Answering my own question here, but hopefully this is helpful; feel free to correct if there are any mistakes. The original version is a gigantic wall of text, so I've added a tl;dr to the top with just the steps to hopefully make the process more clear.
**tl;dr:** In terminal/bash, go into a virtualenv (if you want t... |
Converting Pandas DataFrame to Orange Table | 26,320,638 | 6 | 2014-10-12T00:29:38Z | 26,446,366 | 11 | 2014-10-19T01:33:41Z | [
"python",
"pandas",
"dataframe",
"orange"
] | I notice that this is an [issue on GitHub already](https://github.com/biolab/orange3/issues/68). Does anyone have any code that converts a Pandas DataFrame to an Orange Table?
Explicitly, I have the following table.
```
user hotel star_rating user home_continent gender
0 1 39 4.0 ... | The documentation of Orange package didn't cover all the details. `Table._init__(Domain, numpy.ndarray)` works only for `int` and `float` according to `lib_kernel.cpp`.
They really should provide an C-level interface for `pandas.DataFrames`, or at least `numpy.dtype("str")` support.
**Update**: Adding `table2df`, `df... |
many threads to write log file at same time python | 26,325,943 | 2 | 2014-10-12T14:01:51Z | 26,326,440 | 11 | 2014-10-12T14:55:51Z | [
"python",
"multithreading",
"locking"
] | i am writing script to retrieve WMI info from many computers at the same time then write these info in a text file:
the problem is that all threads writing on the same time
```
f = open("results.txt", 'w+') ## to clean the results file before the start
def filesize(asset):
f = open("results.txt", 'a+')
... | You can simply create your own locking mechanism to ensure that only one thread is ever writing to a file.
```
import threading
lock = threading.Lock()
def write_to_file(f, text, file_size):
lock.acquire() # thread blocks at this line until it can obtain lock
# in this section, only one thread can be present... |
numpy subtract every row of matrix by vector | 26,333,005 | 12 | 2014-10-13T04:43:36Z | 26,333,184 | 21 | 2014-10-13T05:03:18Z | [
"python",
"numpy",
"matrix"
] | So I have a **`n x d`** matrix and an **`n x 1`** vector. I'm trying to write a code to subtract every row in the matrix by the vector.
I currently have a **`for`** loop that iterates through and subtracts the **`i`**-th row in the matrix by the vector. **Is there a way to simply subtract an entire matrix by the vecto... | That works in `numpy` but **only if the trailing axes have the same dimension**. Here is an example of successfully subtracting a vector from a matrix:
```
In [27]: print m; m.shape
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
Out[27]: (4, 3)
In [28]: print v; v.shape
[0 1 2]
Out[28]: (3,)
In [29]: m - v
Out[29... |
numpy subtract every row of matrix by vector | 26,333,005 | 12 | 2014-10-13T04:43:36Z | 26,333,395 | 7 | 2014-10-13T05:26:03Z | [
"python",
"numpy",
"matrix"
] | So I have a **`n x d`** matrix and an **`n x 1`** vector. I'm trying to write a code to subtract every row in the matrix by the vector.
I currently have a **`for`** loop that iterates through and subtracts the **`i`**-th row in the matrix by the vector. **Is there a way to simply subtract an entire matrix by the vecto... | In addition to @John1024 answer, "transposing" a one-dimensional vector in numpy can be done like this:
```
In [1]: v = np.arange(3)
In [2]: v
Out[2]: array([0, 1, 2])
In [3]: v = v[:, np.newaxis]
In [4]: v
Out[4]:
array([[0],
[1],
[2]])
```
From here, subtracting `v` from every column of `m` is triv... |
Django + Postfix | 26,333,009 | 8 | 2014-10-13T04:44:09Z | 28,143,166 | 12 | 2015-01-26T00:16:24Z | [
"python",
"django",
"email",
"postfix-mta"
] | How to confiqure django and postfix to send emails for django apps. I am looking for working settings. I am able to do it using gmail server settings but I want to send email from my own server using my own domain. | I banged my head a lot before realizing that it is actually quite simple:
add this to your **settings.py**
```
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'Whatever <what... |
"raise" followed by conditional statement (python) | 26,336,545 | 2 | 2014-10-13T09:17:51Z | 26,336,590 | 7 | 2014-10-13T09:20:33Z | [
"python",
"conditional-statements",
"python-2.5",
"raise"
] | I'm trying to understand some python 2.5 code and I came across this pattern:
```
def __init__(self, matrix, top_buttons, side_buttons, config_button):
raise isinstance(matrix, ButtonMatrixElement) or AssertionError
raise matrix.width() == 8 and matrix.height() == 8 or AssertionError
raise isin... | The code is nonsense, a botched attempt at something that looks like an [`assert` statement](https://docs.python.org/2/reference/simple_stmts.html#the-assert-statement) that fails, as you have discovered.
What they *should* have written is:
```
assert isinstance(matrix, ButtonMatrixElement)
```
etcetera.
It appears... |
MySQLdb returns not all arguments converted with "on duplicate key update" | 26,337,065 | 3 | 2014-10-13T09:48:22Z | 26,372,066 | 12 | 2014-10-14T23:25:40Z | [
"python",
"mysql-python"
] | With MySQLdb package in python, I want to insert records with checking some unique keys. The method I used is executemany. The arguments are sql sentence and a tuple. But when I executed it, it raised an error which said "not all argument converted".
The codes are as following:
```
dData = [[u'Daniel', u'00-50-56-C0-0... | ## What's going wrong
After checking the link in [your comment below](http://stackoverflow.com/questions/26337065/mysqldb-returns-not-all-arguments-converted-with-on-duplicate-key-update#comment41410860_26372066) and doing some more research and testing, I was able to reproduce the error with MySQLdb versions 1.2.4b4 ... |
pyplot combine multiple line labels in legend | 26,337,493 | 10 | 2014-10-13T10:10:53Z | 26,339,101 | 7 | 2014-10-13T11:37:49Z | [
"python",
"matplotlib",
"plot",
"legend"
] | I have data that results in multiple lines being plotted, I want to give these lines a single label in my legend. I think this can be better demonstrated using the example below,
```
In [22]: a = np.array([[ 3.57, 1.76, 7.42, 6.52],
....: [ 1.57, 1.2 , 3.02, 6.88],
....: [ 2.23,... | I'd make a small helper function personally, if i planned on doing it often;
```
from matplotlib import pyplot
import numpy
a = numpy.array([[ 3.57, 1.76, 7.42, 6.52],
[ 1.57, 1.2 , 3.02, 6.88],
[ 2.23, 4.86, 5.12, 2.81],
[ 4.48, 1.38, 2.14, 0.86],
... |
cannot use current_user in jinja2 macro? | 26,339,583 | 7 | 2014-10-13T12:04:00Z | 26,343,624 | 10 | 2014-10-13T15:31:28Z | [
"python",
"flask",
"jinja2"
] | I use Flask-Login which provides the `current_user` object in templates. I want to write a macro to show a comment form or a log in link depending on if the user is logged in. If I use this code directly in the template, it works:
```
{% if current_user.is_authenticated %}
{{ quick_form(form) }}
{% else %}
<a ... | The context a template is rendered in is not passed to imports unless instructed to do so. See the [relevant docs](http://jinja.pocoo.org/docs/dev/templates/#import-context-behavior).
You're right, you don't need to inject context as arguments to macros. You can import the macros `with context` and they will have acce... |
Spark toDebugString not nice in python | 26,342,132 | 6 | 2014-10-13T14:15:22Z | 26,342,920 | 11 | 2014-10-13T14:55:36Z | [
"python",
"scala",
"apache-spark"
] | This is what I get when I use **toDebugString** in **scala**:
```
scala> val a = sc.parallelize(Array(1,2,3)).distinct
a: org.apache.spark.rdd.RDD[Int] = MappedRDD[3] at distinct at <console>:12
scala> a.toDebugString
res0: String =
(4) MappedRDD[3] at distinct at <console>:12
| ShuffledRDD[2] at distinct at <con... | Try adding a `print` statement so that the debug string is actually printed, rather than displaying its `__repr__`:
```
>>> a = sc.parallelize([1,2,3]).distinct()
>>> print a.toDebugString()
(8) PythonRDD[27] at RDD at PythonRDD.scala:44 [Serialized 1x Replicated]
| MappedRDD[26] at values at NativeMethodAccessorImp... |
Test a single variable multiple times in python in a single statement | 26,342,446 | 2 | 2014-10-13T14:30:40Z | 26,342,462 | 7 | 2014-10-13T14:31:47Z | [
"python",
"python-2.7",
"syntax",
"conditional-statements",
"logical-operators"
] | I'm learning Python at uni and have been told how logic operators and conditional statements work. My question is: is there any way of condensing code such as this?
```
if (day != "Sunday" and day != "Saturday" and day != "Friday" and day != "Thursday" and day != "Wednesday" and day != "Tuesday" and day != "Monday"):
... | You could use the `in` keyword.
```
if day not in ("Sunday", "Saturday", "Friday", "Thursday", "Wednesday", "Tuesday", "Monday"):
``` |
How to add a delay to supervised process in supervisor - linux | 26,342,693 | 6 | 2014-10-13T14:43:31Z | 30,178,614 | 11 | 2015-05-11T22:23:44Z | [
"python",
"linux",
"cassandra",
"bottle",
"supervisor"
] | I added a bottle server that uses python's cassandra library, but it exits with this error:
`Bottle FATAL Exited too quickly (process log may have details)`
log shows this:
`File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 1765, in _reconnect_internal
raise NoHostAvailable("Unable to ... | This is what I use:
```
[program:uwsgi]
command=bash -c 'sleep 5 && uwsgi /etc/uwsgi.ini'
``` |
Meaning of "with" statement without "as" keyword | 26,342,769 | 13 | 2014-10-13T14:46:51Z | 26,342,829 | 16 | 2014-10-13T14:50:36Z | [
"python",
"with-statement",
"contextmanager"
] | I'm familiar with using python's `with` statement as a means of ensuring finalization of an object in the event of an exception being thrown. This usually looks like
```
with file.open('myfile.txt') as f:
do stuff...
```
which is short-hand for
```
f = file.open('myfile.txt'):
try:
do stuff...
finally:
f... | The context manager can **optionally** return an object, to be assigned to the identifier named by `as`. And it is the object returned by the `__enter__` method that is assigned by `as`, not necessarily the context manager itself.
Using `as <identifier>` helps when you create a *new* object, like the `open()` call doe... |
I'm having troubles getting pybrain working through anaconda | 26,343,713 | 7 | 2014-10-13T15:35:28Z | 27,549,814 | 8 | 2014-12-18T15:16:40Z | [
"python",
"pybrain"
] | Here is my problem:
After I managed to install anaconda (having python 3.4), I apparently managed to install pybrain too. But when i use 'import pybrain' from anaconda or from the terminal too I get this error:
```
>>> import pybrain
Traceback (most recent call last):
File "<ipython-input-2-0fb7233d2a8c>", line 1, i... | Simply running `sudo pip3 install git+https://github.com/pybrain/pybrain.git` worked for me after having the same issue.
The version up on PyPi isn't Python 3 compatible.
Installing the latest commit directly using `pip3` should take care of your old package (from PyPi) as well. |
Drop multiple columns pandas | 26,347,412 | 24 | 2014-10-13T19:24:44Z | 26,347,456 | 39 | 2014-10-13T19:27:43Z | [
"python",
"pandas"
] | I am trying to drop multiple columns (column 2 and 70 in my data set, indexed as 1 and 69 respectively) by index number in a pandas data frame with the following code:
```
df.drop([df.columns[[1, 69]]], axis=1, inplace=True)
```
I get the following error:
```
TypeError: unhashable type: 'Index'
```
And in my code t... | You don't need to wrap it in a list with `[..]`, just provide the subselection of the columns index:
```
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
```
as the index object is already regarded as list-like. |
ipython notebook is NOT printing until the whole program is finished | 26,348,619 | 5 | 2014-10-13T20:47:23Z | 26,352,157 | 8 | 2014-10-14T03:27:24Z | [
"python",
"printing",
"ipython-notebook",
"progress"
] | ```
import time
print 1
time.sleep(5)
```
I ran the code above in IPython notebook and normal script separately.
In `IPython Notebook`, it doesn't print the number '1' until `time.sleep(5)` is finished, while in normal script it DOES print out number '1' first and go into `time.sleep(5)`. What would that happen?
Th... | It is a buffering issue. Add `sys.stdout.flush()` after the print, to see the output immediately.
python uses line-buffering if it is run interactively (in a terminal) and block buffering (e.g., ~4K bytes buffers) if the output is redirected. Compare:
```
$ python your_script.py
```
And
```
$ python your_script.py ... |
Flask-Admin default filters | 26,349,773 | 9 | 2014-10-13T22:18:39Z | 26,351,005 | 22 | 2014-10-14T00:41:01Z | [
"python",
"flask",
"flask-admin"
] | I would like to display only paid orders in my Flask-Admin model list view.
Here is models.py:
```
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
amount = db.Column(db.Integer)
description = db.Column(db.String)
paid = db.Column(db.Boolean, default=False)
```
Here is ModelView for Fl... | We do this in our app by overriding ModelView.
<https://github.com/mrjoes/flask-admin/blob/master/flask_admin/contrib/sqla/view.py#L654>
I looked through the source code a bit for Flask-Admin, and they've made the API easier to use since we last edited this code, because it looks like you can just do:
```
from flask... |
Python Pandas: Passing Multiple Functions to agg() with Arguments | 26,354,329 | 4 | 2014-10-14T06:49:48Z | 26,354,494 | 7 | 2014-10-14T06:59:57Z | [
"python",
"pandas"
] | I'm struggling to figure out how to combine two different syntaxes for pandas' `dataframe.agg()` function. Take this simple data frame:
```
df = pd.DataFrame({'A': ['group1', 'group1', 'group2', 'group2', 'group3', 'group3'],
'B': [10, 12, 10, 25, 10, 12],
'C': [100, 102, 100, 250... | Well, the [docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html#pandas.core.groupby.GroupBy.aggregate) on aggregate are in fact a bit lacking. There might be a way to handle this with the correct passing of arguments, and you could look into the source code of pandas fo... |
Understanding the diagonal in Pandas' scatter matrix plot | 26,360,759 | 4 | 2014-10-14T12:24:38Z | 26,361,895 | 7 | 2014-10-14T13:19:46Z | [
"python",
"pandas"
] | I'm plotting a scatter plot with `Pandas`. I can understand the plot, except the curves in diagonal plots. Can someone explain to me what they mean?
Image:

Code:
```
import pylab
import numpy as np
from pandas.tools.plotting import scatter_matrix
i... | As you can tell, the scatter matrix is plotting each of the columns specified against each other column.
However, in this format, when you got to a diagonal, you would see a plot of a column against itself. Since this would always be a straight line, Pandas decides it can give you more useful information, and plots th... |
How to find neighbors of a 2D list in python? | 26,363,579 | 2 | 2014-10-14T14:39:03Z | 26,363,975 | 8 | 2014-10-14T14:57:22Z | [
"python",
"arrays",
"list",
"nearest-neighbor"
] | I have a 2D list of only 1's and 0's:
```
Boundaries = [
[0,0,0,0,0],
[0,1,1,1,0],
[0,1,1,1,1],
[0,1,1,1,0],
[0,0,1,0,0]]
```
I need to test this list to check if there are any 1's surrounded by 8 other 1's (such as the middle 1 in this list). If there is a 1 surrounded by 1's as neighbours it should then be changed ... | Using scipy you'd do something like the following
```
import numpy
boundaries = numpy.array([
[0,0,0,0,0],
[0,1,1,1,0],
[0,1,1,1,1],
[0,1,1,1,0],
[0,0,1,0,0]])
counts = scipy.signal.convolve2d... |
Reindexing Elastic search via Bulk API, scan and scroll | 26,371,237 | 7 | 2014-10-14T22:08:58Z | 26,371,327 | 8 | 2014-10-14T22:17:07Z | [
"python",
"elasticsearch",
"indexing",
"reindex",
"elasticsearch-bulk-api"
] | I am trying to re-index my Elastic search setup, currently looking at [the Elastic search documentation](http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/scan-scroll.html) and [an example using the Python API](http://stackoverflow.com/questions/22921629/elasticsearch-py-scan-and-scroll-to-return-all-do... | Hi you can use the scroll api to go through all the documents in the most efficient way. Using the scroll\_id you can find a session that is stored on the server for your specific scroll request. So you need to provide the scroll\_id with each request to obtain more items.
The bulk api is for more efficient indexing d... |
Can't install lxml in python2.7 | 26,372,210 | 4 | 2014-10-14T23:41:54Z | 26,372,327 | 7 | 2014-10-14T23:54:25Z | [
"python",
"python-2.7",
"lxml",
"mint"
] | Im trying to install lxml within a virtualenv with `sudo pip install lxml` and also `sudo pip install --upgrade lxml` but getting the following in both cases:
```
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-z,
relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes ... | `lxml` depends on various C libraries, and you have to have those C libraries installedâincluding their development files (headers, `.so` or `.a` libraries, etc.)âto build `lxml`. The [installation](http://lxml.de/installation.html) docs explain what prerequisites you need to build on your particular platform.
---... |
Use JSONResponse to serialize a QuerySet in Django 1.7? | 26,373,992 | 8 | 2014-10-15T03:26:05Z | 26,833,156 | 11 | 2014-11-09T20:48:40Z | [
"python",
"ajax",
"django",
"jsonresponse"
] | I saw that now in Django 1.7 I can use the `http.JSONResponse` object to send JSON to a client. My View is:
```
#Ajax
def get_chat(request):
usuario = request.GET.get('usuario_consultor', None)
usuario_chat = request.GET.get('usuario_chat', None)
mensajes = list(MensajeDirecto.objects.filter(Q(usuario_rem... | ```
from django.core import serializers
from django.http import JsonResponse
def get_chat(request):
usuario = request.GET.get('usuario_consultor', None)
usuario_chat = request.GET.get('usuario_chat', None)
mensajes = MensajeDirecto.objects.filter(Q(usuario_remitente = usuario, usuario_destinatario = usuar... |
How to know the version of pip itself | 26,378,344 | 14 | 2014-10-15T08:54:01Z | 26,378,395 | 24 | 2014-10-15T08:56:11Z | [
"python",
"pip"
] | which shell command gives me the actual version of `pip` I am using?
pip gives with `pip show` all version of modules that are installed but excludes itself. | You can do this:
`pip -V` or `pip --version` |
using 'or' condition in re.split | 26,383,224 | 2 | 2014-10-15T12:56:40Z | 26,383,293 | 7 | 2014-10-15T13:00:38Z | [
"python",
"split"
] | I have a list of strings each one of those needs to be split when an 'y' or 'm' is found:
```
mylist = ['3m10y','10y20y','18m2y']
```
in the following items:
```
splitlist = [['3m','10y'],['10y','20y'],['18m','2y']]
```
i was thinking of using re.split() but I cannot use the 'or' condition in order to tell the func... | Try `findall` instead of `split`:
```
>>> re.findall(r'\d+[ym]', '3m10y')
['3m', '10y']
```
`[my]` is `m` or `y`. |
better way to invert case of string | 26,385,823 | 2 | 2014-10-15T15:03:24Z | 26,386,127 | 38 | 2014-10-15T15:18:00Z | [
"python"
] | I am learning python and meet an exercise:
> Strings. Create a function that will return another string similar to the input string, but with its case inverted. For example, input of "Mr. Ed" will result in "mR. eD" as the output string.
My Code is:
```
name = 'Mr.Ed'
name_list = []
for i in name:
if i.isupper(... | You can do that with `name.swapcase()`. Lookup the [string methods](https://docs.python.org/2/library/string.html#string.swapcase). |
Recursive pattern in regex | 26,385,984 | 19 | 2014-10-15T15:11:34Z | 26,386,070 | 18 | 2014-10-15T15:15:31Z | [
"python",
"regex",
"recursive-regex"
] | This is very much related to [Regular Expression to match outer brackets](http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets) however, I specifically want to know how or whether it's possible to do this [**regex's recursive pattern**](https://pypi.python.org/pypi/regex)? *I'm yet to fi... | The pattern is:
```
{((?>[^{}]+|(?R))*)}
```
You can see this works for your example:
```
regex.findall("{((?>[^{}]+|(?R))*)}", "{1, {2, 3}} {4, 5}")
# ['1, {2, 3}', '4, 5']
```
### Explanation:
The m part needs to exclude the brackets. The use of an atomic group is needed if you want at the same time to allow a q... |
Recursive pattern in regex | 26,385,984 | 19 | 2014-10-15T15:11:34Z | 26,386,119 | 7 | 2014-10-15T15:17:38Z | [
"python",
"regex",
"recursive-regex"
] | This is very much related to [Regular Expression to match outer brackets](http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets) however, I specifically want to know how or whether it's possible to do this [**regex's recursive pattern**](https://pypi.python.org/pypi/regex)? *I'm yet to fi... | I was able to do this no problem with the `b(?:m|(?R))*e` syntax:
```
{((?:[^{}]|(?R))*)}
```
[***Demo***](http://regex101.com/r/mX2fG5/1)
---
I think the key from what you were attempting is that the repetition doesn't go on `m`, but the entire `(?:m|(?R))` group. This is what allows the recursion with the `(?R)` ... |
Cannot install uWSGI on Mac os X 10.9.5 | 26,386,408 | 2 | 2014-10-15T15:32:00Z | 26,386,519 | 11 | 2014-10-15T15:37:12Z | [
"python",
"osx",
"uwsgi"
] | When I'm trying to install uWSGI in Mac OS X 10.9.5 I get the following error:
```
Installing collected packages: uwsgi
Running setup.py install for uwsgi
plugins/python/pyutils.c:14:22: error: equality comparison with extraneous parentheses [-Werror,-Wparentheses-equality]
if (((exc)->ob_type == &PyClass_T... | Using `export CC=/usr/bin/llvm-gcc` made it work. |
Why isn't pip updating my numpy and scipy? | 26,390,895 | 7 | 2014-10-15T19:50:23Z | 26,393,469 | 9 | 2014-10-15T22:53:45Z | [
"python",
"osx",
"numpy",
"pip",
"package-managers"
] | My problem is that pip won't update my Python Packages, even though there are no errors.
It is similar to [this one](http://stackoverflow.com/questions/21473600/matplotlib-version), but I am still now sure what to do. Basically, ALL my packages for python appear to be ridiculously outdated, even after updating everyth... | In OS X 10.9, Apple's Python comes with a bunch of pre-installed extra packages, in a directory named `/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python`. Including `numpy`.
And the way they're installed (as if by using `easy_install` with an ancient pre-0.7 version of `setuptools`, but not in... |
Using python Requests with javascript pages | 26,393,231 | 9 | 2014-10-15T22:31:11Z | 26,393,257 | 9 | 2014-10-15T22:33:40Z | [
"python",
"web-scraping",
"python-requests"
] | I am trying to use the Requests framework with python (<http://docs.python-requests.org/en/latest/>) but the page I am trying to get to uses javascript to fetch the info that I want.
I have tried to search on the web for a solution but the fact that I am searching with the keyword javascript most of the stuff I am get... | You are going to have to make the same request (using the Requests library) that the javascript is making. You can use any number of tools (including those built into Chrome and Firefox) to inspect the http request that is coming from javascript and simply make this request yourself from Python. |
NLTK python error: "TypeError: 'dict_keys' object is not subscriptable" | 26,394,748 | 8 | 2014-10-16T01:20:27Z | 26,394,855 | 8 | 2014-10-16T01:34:03Z | [
"python",
"nltk"
] | I am following instructions for a class homework assignment and I am supposed to look up the top 200 most frequently used words in a text file.
Here's the last part of the code:
```
fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
vocab[:200]
```
But when I press enter after the vocab 200 line, it returns:
```
Trac... | Looks like you are using Python 3. In Python 3 `dict.keys()` returns an iteratable but not indexable object. The most simple (but not so efective) solution would be:
```
vocab = list(fdist1.keys())
``` |
Pickle File too large to load | 26,394,768 | 10 | 2014-10-16T01:22:56Z | 26,395,638 | 26 | 2014-10-16T03:14:02Z | [
"python",
"sql",
"out-of-memory",
"pickle"
] | The problem that I am having is that I have a very large pickle file (2.6 Gb) that I am trying to open but each time I do so I get a memory error. I realize now that I should have used a database to store all the information but its too late now. The pickle file contains dates and text from the U.S. Congressional recor... | Looks like you're in a bit of a pickle! ;-). Hopefully after this, you'll NEVER USE PICKLE EVER. It's just not a very good data storage format.
Anyways, for this answer I'm assuming your `Document` class looks a bit like this. If not, comment with your actual `Document` class:
```
class Document(object): # <-- object... |
Ansible creating a virtualenv | 26,402,123 | 23 | 2014-10-16T10:30:06Z | 26,402,225 | 11 | 2014-10-16T10:35:04Z | [
"python",
"ansible"
] | How do you create a virtualenv for a specific python version using ansible. Is there a command in the ansible standard library?
I would like something like:
```
- virtualenv: dest=venv python_version:/usr/bin/python3
``` | You can do it with the [`pip`](http://docs.ansible.com/pip_module.html) module and a specific `virtualenv` binary:
```
- pip: virtualenv=/path/to/venv virtualenv_command=/path/to/virtualenv3 ...
``` |
Ansible creating a virtualenv | 26,402,123 | 23 | 2014-10-16T10:30:06Z | 30,777,607 | 20 | 2015-06-11T10:01:25Z | [
"python",
"ansible"
] | How do you create a virtualenv for a specific python version using ansible. Is there a command in the ansible standard library?
I would like something like:
```
- virtualenv: dest=venv python_version:/usr/bin/python3
``` | I have at times experienced some erratic behaviour with specifying `virtualenv_command` (e.g.: getting a python 2.7 executable in my virtualenv even though I specified to run the command with `virtualenv-3.4`.
If you experience that problem, you *can* create the virtualenv manually with the `command` module:
```
- na... |
How do i correctly setup and teardown my pytest class with tests? | 26,405,380 | 10 | 2014-10-16T13:12:42Z | 26,414,138 | 13 | 2014-10-16T21:23:34Z | [
"python",
"class",
"python-2.7",
"object",
"py.test"
] | I am using selenium for end to end testing and i can't get how to use setup\_class and teardown\_class methods.
I need to set up browser in setup\_class method, then perform a bunch of tests defined as class methods and finally quit browser in teardown\_class method.
But logically it seems bad solution, because in fa... | When you write *"tests defined as class methods"*, do you really mean *class methods* (methods which receive its **class** as first parameter) or just regular methods (methods which receive an **instance** as first parameter)?
Since your example uses `self` for the test methods I'm assuming the latter, so you just nee... |
Difficulty with Celery: function object has no property 'delay' | 26,409,871 | 6 | 2014-10-16T16:55:18Z | 26,416,110 | 8 | 2014-10-17T00:34:11Z | [
"python",
"python-2.7",
"flask",
"celery",
"flask-security"
] | I have been churning through the software development recently and have had some success bending celery to my will.
I have used it successfully to send emails, and have just tried to use almost exactly the same code (after restarting all processes etc) to send sms through Twilio.
However I keep getting the following ... | The view name `send_sms` conflicts with the celery task name. The name `send_sms` references the view, not the task, when used in the module that contains the view.
Use different name to avoid the overwriting. |
How to recover matplotlib defaults after setting stylesheet | 26,413,185 | 9 | 2014-10-16T20:19:42Z | 26,413,529 | 17 | 2014-10-16T20:41:05Z | [
"python",
"matplotlib"
] | In an ipython notebook, I used a matplotlib stylesheet to change the look of my plots using
```
from matplotlib.pyplot import *
%matplotlib inline
style.use('ggplot')
```
My version of matplotlib is 1.4.0. How do I go back to the default matplotlib styling? I tried all the available styles in
```
print style.availab... | You should be able to set it back to default by:
```
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
```
In `ipython`, things are a little different, especially with `inline` backend:
```
In [1]:
%matplotlib inline
In [2]:
import matplotlib as mpl
import matplotlib.pyplot as plt
In [3]:
inline_r... |
pdfminer3k has no method named create_pages in PDFPage | 26,413,216 | 3 | 2014-10-16T20:21:33Z | 27,739,391 | 13 | 2015-01-02T08:29:14Z | [
"python",
"pdfminer"
] | Since I want to move from python 2 to 3, I tried to work with pdfmine.3kr in python 3.4. It seems like they have edited everything. Their change logs do not reflect the changes they have done but I had no success in parsing pdf with pdfminer3k. For example:
They have moved PDFDocument into pdfparser (sorry, if I spell... | If you are interested in reading text from a pdf file the following code works with pdfminer3k using python 3.4.
```
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import L... |
How does a python process exit gracefully after receiving SIGTERM while waiting on a semaphore? | 26,414,704 | 7 | 2014-10-16T22:05:42Z | 26,417,304 | 7 | 2014-10-17T03:13:11Z | [
"python",
"python-multiprocessing"
] | I have a Python process which spawns 5 other Python processes using the multiprocessing module. Let's call the parent process P0 and the others P1-P5. The requirement is, if we send a SIGTERM to P0, it should shut down P1 to P5 first and then exit itself.
The catch is P1 and P5 are waiting on semaphores. So when I sen... | You can install a signal handler which throws an exception which is then caught in the subprocess to handle exits gracefully.
Here is an example of a script which waits in a semaphore in a subprocess and terminates gracefully when sent a `SIGTERM`.
```
#!/usr/bin/env python
import signal
import time
import multiproc... |
Normalize columns of pandas data frame | 26,414,913 | 7 | 2014-10-16T22:24:42Z | 26,415,620 | 11 | 2014-10-16T23:34:48Z | [
"python",
"pandas",
"normalize"
] | I have a data frame in pandas in which each column has different value range. For example:
df:
```
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
```
Any idea how I can normalize the columns of this data frame where each value is between 0 and 1?
My desired output is:
```
A B C
1 1 1
0.765 0... | You can use the package sklearn and its associated preprocessing utilities to normalize the data.
```
from sklearn import preprocessing
x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pandas.DataFrame(x_scaled)
```
For more informatio... |
Is there a recommended approach for handling AppConfig when designing an app for Django 1.6 and 1.7? | 26,416,222 | 8 | 2014-10-17T00:50:07Z | 28,334,620 | 9 | 2015-02-05T01:17:13Z | [
"python",
"django",
"version-compatibility"
] | [Django 1.7](https://docs.djangoproject.com/en/1.7/releases/1.7/) has [introduced a new way for handling application configuration](https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.verbose_name) that is independent of `models.py`. However the method for using the new `AppConfig` requires th... | I am not sure about officially django suggested way, but that is how I would do it:
```
# myapp/apps.py
try:
from django.apps import AppConfig
except ImportError:
AppConfig = object
class MyAppConfig(AppConfig):
# put all the necessary stuff for AppConfig
# myapp/__init__.py
default_app_config = 'myapp... |
Extremely slow import of matplotlib afm | 26,421,364 | 10 | 2014-10-17T08:53:54Z | 28,768,078 | 12 | 2015-02-27T15:03:13Z | [
"python",
"performance",
"matplotlib",
"adobe"
] | Import time is unacceptably long:
```
from matplotlib import pylab as plt --> 3.0124739 secs
```
This is the output of cProfile, which clearly shows the problem being afm.py, which is some interface for [Adobe Font Metrics.](http://matplotlib.org/api/afm_api.html). Matplotlib version is 1.4.0 - Ubuntu 14.04
```
... | I had the same problem. I figured out, that this happens when you upgrade `matplotlib` to a newer version. The font cache file is not compatible with the new version, but apparently is not recreated. Instead font list is created each time on the fly. The solution is to delete the matplotlib cache directory (in my case ... |
Python: How to tell Spyder's style analysis PEP8 to read from a setup.cfg or increase max. line length? | 26,426,689 | 5 | 2014-10-17T13:57:46Z | 26,435,067 | 9 | 2014-10-18T00:12:31Z | [
"python",
"spyder",
"pep8"
] | I am using Spyder 2.3.1 and python(x, y).
In the preferences of Spyder you can activate "Style analysis".
This is quite nice, but I want to increase the max. tolerable line length.
The standard setting for PEP8 is 79 characters.
This can be changed through a setup.cfg with the content:
[pep8]
max-line-length = 99
Th... | According to the link cited by @Werner:
<http://pep8.readthedocs.org/en/latest/intro.html#configuration>
what you need to do is to create a file called `~/.config/pep8` (On Linux/Mac) or `~/.pep8` (on Windows), and add these lines to it:
```
[pep8]
max-line-length = 99
```
I tested it in Spyder and it works as expe... |
multiprocessing.dummy in Python | 26,432,411 | 7 | 2014-10-17T19:46:30Z | 26,432,431 | 17 | 2014-10-17T19:47:47Z | [
"python",
"parallel-processing",
"multiprocessing"
] | I do machine learning project in Python, so I have to parallel predict function, that I'm using in my program.
```
from multiprocessing.dummy import Pool
from multiprocessing import cpu_count
def multi_predict(X, predict, *args, **kwargs):
pool = Pool(cpu_count())
results = pool.map(predict, X)
pool.clos... | When you use [`multiprocessing.dummy`](https://docs.python.org/2.7/library/multiprocessing.html#module-multiprocessing.dummy), you're using threads, not processes:
> `multiprocessing.dummy` replicates the API of `multiprocessing` but is no
> more than a wrapper around the `threading` module.
That means you're restric... |
Parsing Flags in Python | 26,432,901 | 3 | 2014-10-17T20:22:44Z | 26,432,918 | 8 | 2014-10-17T20:24:05Z | [
"python"
] | I am trying to manually parse out arguments and flags given a string.
For example, if I have a string
`"--flag1 'this is the argument'"`
I am expecting to get back
`['--flag1', 'this is the argument']`
for any arbitrary number of flags in the string.
The difficulty I am having is determining how to process multi-... | You're in luck; there *is* a simple way to do this. Use [`shlex.split`](https://docs.python.org/2/library/shlex.html#shlex.split). It should split the string as you want.
```
>>> import shlex
>>> shlex.split("--flag1 'this is the argument'")
['--flag1', 'this is the argument']
``` |
What is under the hood of x = 'y' 'z' in Python? | 26,433,138 | 35 | 2014-10-17T20:40:10Z | 26,433,175 | 8 | 2014-10-17T20:43:29Z | [
"python",
"string",
"concatenation",
"python-internals"
] | If you run `x = 'y' 'z'` in Python, you get `x` set to `'yz'`, which means that some kind of string concatenation is occurring when Python sees multiple strings next to each other.
But what kind of concatenation is this?
Is it actually running `'y' + 'z'` or is it running `''.join('y','z')` or something else? | The strings are being concatenated by the python parser before anything is executed, so its not really like `'y' + 'z'` or `''.join('y','z')`, except that it has the same effect. |
What is under the hood of x = 'y' 'z' in Python? | 26,433,138 | 35 | 2014-10-17T20:40:10Z | 26,433,185 | 57 | 2014-10-17T20:44:31Z | [
"python",
"string",
"concatenation",
"python-internals"
] | If you run `x = 'y' 'z'` in Python, you get `x` set to `'yz'`, which means that some kind of string concatenation is occurring when Python sees multiple strings next to each other.
But what kind of concatenation is this?
Is it actually running `'y' + 'z'` or is it running `''.join('y','z')` or something else? | The Python *parser* interprets that as one string. This is well documented in the [Lexical Analysis documentation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation):
> ## String literal concatenation
>
> Multiple adjacent string literals (delimited by whitespace), possibly using d... |
Generating allure report using pytest | 26,434,791 | 4 | 2014-10-17T23:33:47Z | 27,175,962 | 7 | 2014-11-27T17:14:08Z | [
"python",
"allure"
] | I am using py test allure adaptor and trying to generate input data required for allure report.But I am not able to generate any XML's. When I execute the py file using py.test sample.py, it did create **pycache** dir. Then I executed "allure generate -v 1.3.9 C:\allurereports" (This is the dir where I had the sample.p... | Lavanya.
I'll try to explain the sequence you must to perform to generate allure report of autotest.
1. Install **pip**. Download get-pip.py and perform **python get-pip.py**.
2. Install **pytest** and **pytest-allure-adaptor** via pip. Perform **python -m pip install pytest pytest-allure-adaptor**
3. Generate autotes... |
Is there an alternate for the now removed module 'nltk.model.NGramModel'? | 26,443,084 | 8 | 2014-10-18T18:24:13Z | 26,443,165 | 12 | 2014-10-18T18:32:03Z | [
"python",
"nltk",
"n-gram"
] | I've been trying to find out an alternative for two straight days now, and couldn't find anything relevant.
I'm basically trying to get a probabilistic score of a synthesized sentence (synthesized by replacing some words from an original sentence picked from the corpora).
I tried Collocations, but the scores that I'm ... | According to [this open issue on the nltk repo](https://github.com/nltk/nltk/issues/738), `NGramModel` is currently not in master because of some bugs. Their current solution is to install the code from the model branch. This is about 8 months behind master though, so you might miss out on other features and bug fixes.... |
How to delete an object using Django Rest Framework | 26,445,450 | 5 | 2014-10-18T23:05:41Z | 26,445,632 | 11 | 2014-10-18T23:30:55Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I am trying to write an RESTful API for my event planning app using Django Rest Framework but I am having some trouble when using views that do not expect the GET HTTP method. I have read through the tutorial on the DRF site. From what I understand after reading through the tutorial and the class based view documentati... | You're being redundant. The HTTP method is already `DELETE`, so there's no `/events/delete` in the url. Try this:
```
curl -X DELETE "http://127.0.0.1:8000/events/1/"
```
By default, DRF's router creates detailed urls at `/event/<pk>` and you `GET`, `PUT`, `POST` and `DELETE` them to retrieve, update, create and dele... |
Polling a stopping or starting EC2 instance with Boto | 26,446,746 | 7 | 2014-10-19T02:40:15Z | 26,450,961 | 7 | 2014-10-19T13:24:23Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto"
] | I'm using AWS, Python, and the [Boto library](http://boto.readthedocs.org/en/latest/ref/ec2.html).
I'd like to invoke `.start()` or `.stop()` on a Boto EC2 instance, then "poll" it until it has completed either.
```
import boto.ec2
credentials = {
'aws_access_key_id': 'yadayada',
'aws_secret_access_key': 'rigama... | The instance state does not get updated automatically. You have to call the `update` method to tell the object to make another round-trip call to the EC2 service and get the latest state of the object. Something like this should work:
```
while instance.state not in ('running', 'stopped'):
sleep(5)
instance.up... |
How to add trendline in python matplotlib dot (scatter) graphs? | 26,447,191 | 12 | 2014-10-19T04:07:20Z | 26,447,505 | 17 | 2014-10-19T05:06:37Z | [
"python",
"scatter",
"trendline"
] | How could I add trendline to a dot graph drawn using matplotlib.scatter? | as explained [here](http://widu.tumblr.com/post/43624347354/matplotlib-trendline)
With help from numpy one can calculate for example a linear fitting.
```
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print... |
Passing data from Django to D3 | 26,453,916 | 7 | 2014-10-19T18:27:43Z | 26,455,798 | 24 | 2014-10-19T21:50:44Z | [
"javascript",
"python",
"json",
"django",
"d3.js"
] | I'm trying to write a very basic bar graph using Django and D3.js. I have an object called play with a datetime field called date. What I want to do is show number of plays over time grouped by month. Basically I have two questions:
1. How do I get these grouped by month with a count of the number of plays in that mon... | Since D3.js v3 has a nice collection of [methods to load data from external resources](https://github.com/d3/d3-3.x-api-reference/blob/master/API-Reference.md#loading-external-resources)¹, It's better to you not embed data into your page, you just load it.
This will be an answer by example.
Let's start with a model ... |
Renaming a file in PyCharm | 26,454,624 | 11 | 2014-10-19T19:45:28Z | 26,454,706 | 13 | 2014-10-19T19:51:36Z | [
"python",
"pycharm"
] | In PyCharm 3.4, I want to rename a file on the file tree that appears on the left of the IDE. If I right-click on a file, there is an option to delete it, but not to rename it. Similarly, there is no way of renaming it from the File or Edit menus. Is there a fundamental reason why PyCharm does not allow this from withi... | Renaming files in PyCharm is simple. You simply select `Refactor > Rename` when right-clicking on a file in the tree.
This will open a popup where you can type in the new filename. There are additional options when renaming, such as searching for references and in comments, strings, etc. |
Python Pandas: Is Order Preserved When Using groupby() and agg()? | 26,456,125 | 9 | 2014-10-19T22:31:41Z | 26,465,555 | 9 | 2014-10-20T12:19:04Z | [
"python",
"pandas",
"aggregate"
] | I've frequented used pandas' `agg()` function to run summary statistics on every column of a data.frame. For example, here's how you would produce the mean and standard deviation:
```
df = pd.DataFrame({'A': ['group1', 'group1', 'group2', 'group2', 'group3', 'group3'],
'B': [10, 12, 10, 25, 10, 12],... | See this enhancement [issue](https://github.com/pydata/pandas/issues/8588)
The short answer is yes, the groupby will preserve the orderings as passed in. You can prove this by using your example like this:
```
In [20]: df.sort_index(ascending=False).groupby('A').agg([np.mean, lambda x: x.iloc[1] ])
Out[20]:
... |
swift if or/and statement like python | 26,456,587 | 7 | 2014-10-19T23:35:39Z | 26,456,631 | 13 | 2014-10-19T23:41:25Z | [
"python",
"if-statement",
"swift"
] | Is there a way to to do and/or in an if statement in swift. eg/
```
if a > 0 and i == j or f < 3:
//do something
```
can we do that in swift?
Thanks in advance | You can use
```
&&
```
for logical and
and
```
||
```
for logical or
so you can do
```
if a> 0 && i ==j || f<3:
...
```
see here
<https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/BasicOperators.html> |
Convert timedelta64[ns] column to seconds in Python Pandas DataFrame | 26,456,825 | 8 | 2014-10-20T00:09:44Z | 26,457,238 | 15 | 2014-10-20T01:13:49Z | [
"python",
"python-2.7",
"numpy",
"pandas"
] | A pandas DataFrame column `duration` contains `timedelta64[ns]` as shown. How can you convert them to seconds?
```
0 00:20:32
1 00:23:10
2 00:24:55
3 00:13:17
4 00:18:52
Name: duration, dtype: timedelta64[ns]
```
I tried the following
```
print df[:5]['duration'] / np.timedelta64(1, 's')
```
but got the e... | This works properly in the current version of Pandas (version 0.14):
```
In [132]: df[:5]['duration'] / np.timedelta64(1, 's')
Out[132]:
0 1232
1 1390
2 1495
3 797
4 1132
Name: duration, dtype: float64
```
Here is a workaround for older versions of Pandas/NumPy:
```
In [131]: df[:5]['duration'].valu... |
Are Python pure virtual functions possible and/or worth it? | 26,458,618 | 7 | 2014-10-20T04:32:45Z | 26,458,670 | 8 | 2014-10-20T04:39:24Z | [
"python",
"oop",
"pure-virtual"
] | I may be coming from a different mindset, being primarily a C++ programmer. This question has to do with OOP in Python and more specifically pure virtual methods. So taking code I adapted from [this question](http://stackoverflow.com/questions/4714136/python-how-to-implement-virtual-methods) I am looking at this basic ... | Abstract base classes already do what you want. `abstractmethod` has nothing to do with letting you call the method with `super`; you can do that anyway. Instead, any methods decorated with `abstractmethod` must be overridden for a subclass to be instantiable:
```
>>> class Foo(object):
... __metaclass__ = abc.ABC... |
pip doesn't work after upgrading to OS X Yosemite | 26,458,671 | 7 | 2014-10-20T04:39:29Z | 26,461,199 | 15 | 2014-10-20T08:17:35Z | [
"python",
"osx",
"pip",
"osx-yosemite"
] | After upgrading to Yosemite, my `pip` doesn't work anymore. If I issue a `pip` command, it will complain like this:
```
Traceback (most recent call last):
File "/usr/local/bin/pip", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
File "build/bdist.macosx-10.9-x86_64/egg/pkg_resou... | It sounds like you're trying to run pip with a python version installed by homebrew
You may want to try getting your homebrow up and running again.
* Maybe relinking all your installed kegs is enough (s. <http://apple.stackexchange.com/a/125319>)
* Or you can try reinstalling python with `brew reinstall python` |
Nested resources in Django REST Framework | 26,458,767 | 4 | 2014-10-20T04:53:53Z | 28,837,389 | 12 | 2015-03-03T16:51:20Z | [
"python",
"django",
"rest",
"django-rest-framework",
"nested-resources"
] | I wish to implement my new API with a nested resource.
```
Example: /api/users/:user_id/posts/
```
Will evaluate to all of the posts for a specific user. I haven't seen an working example for this use case, maybe this isn't the right way for implementing rest API? | As commented by [Danilo](http://stackoverflow.com/questions/26458767/django-rest-framework-nested-resources#comment45817506_26461156), the `@link` decorator got removed in favor of `@list_route` and `@detail_route` decorators.[2](http://www.django-rest-framework.org/api-guide/routers/#extra-link-and-actions)
Here's th... |
MongoDB aggregate/group/sum query translated to pymongo query | 26,465,846 | 4 | 2014-10-20T12:33:36Z | 26,466,921 | 7 | 2014-10-20T13:32:34Z | [
"python",
"mongodb",
"pymongo"
] | I have a set of entries in the `goals` collection that looks like this:
```
{"user": "adam", "position": "attacker", "goals": 8}
{"user": "bart", "position": "midfielder", "goals": 3}
{"user": "cedric", "position": "goalkeeper", "goals": 1}
```
I want to calculate a sum of all goals. In MongoDB shell I do it like thi... | Just use a **pipe** with **aggregate**.
```
pipe = [{'$group': {'_id': None, 'total': {'$sum': '$goals'}}}]
db.goals.aggregate(pipeline=pipe)
Out[8]: {u'ok': 1.0, u'result': [{u'_id': None, u'total': 12.0}]}
``` |
Python Function to test ping | 26,468,640 | 5 | 2014-10-20T14:53:42Z | 26,468,712 | 7 | 2014-10-20T14:57:09Z | [
"python",
"function",
"variables",
"return"
] | I'm trying to create a function that I can call on a timed basis to check for good ping and return the result so I can update the on-screen display. I am new to python so I don't fully understand how to return a value or set a variable in a function.
Here is my code that works:
```
import os
hostname = "google.com"
r... | It looks like you want the `return` keyword
```
def check_ping():
hostname = "taylor"
response = os.system("ping -c 1 " + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"
return pingstatus
```
You nee... |
Seasonal Decomposition of Time Series by Loess with Python | 26,470,570 | 4 | 2014-10-20T16:35:12Z | 28,289,196 | 7 | 2015-02-03T00:10:42Z | [
"python",
"time-series"
] | I'm trying to do with Python what I the STL function on R.
The R commands are
```
fit <- stl(elecequip, s.window=5)
plot(fit)
```
How do I do this in Python? I investigated that statmodels.tsa has some time series analysis functions but I could specifically found "Seasonal Decomposition of Time Series by Loess" in t... | I've been having a similar issue and am trying to find the best path forward.
[Here is a github repo for an STL decomposition based on the Loess procedure](https://github.com/andreas-h/pyloess/blob/master/mpyloess.py). It is based on the original fortran code that was available with [this paper](http://www.wessa.net/d... |
PIP Install Numpy throws an error "ascii codec can't decode byte 0xe2" | 26,473,681 | 46 | 2014-10-20T19:46:18Z | 26,474,062 | 36 | 2014-10-20T20:11:22Z | [
"python",
"numpy",
"pandas",
"pip"
] | I have a freshly installed Ubuntu on a freshly built computer. I just installed python-pip using apt-get. Now when I try to pip install Numpy and Pandas, it gives the following error.
I've seen this error mentioned in quite a few places on SO and Google, but I haven't been able to find a solution. Some people mention ... | I had this exact problem recently and used
```
apt-get install python-numpy
```
This adds numpy to your system python interpreter. I may have had to do the same for matplotlib. To use in a virtualenv, you have to create your environment using the
```
--system-site-packages
```
option
<http://www.scipy.org/install.... |
PIP Install Numpy throws an error "ascii codec can't decode byte 0xe2" | 26,473,681 | 46 | 2014-10-20T19:46:18Z | 31,573,180 | 22 | 2015-07-22T20:16:57Z | [
"python",
"numpy",
"pandas",
"pip"
] | I have a freshly installed Ubuntu on a freshly built computer. I just installed python-pip using apt-get. Now when I try to pip install Numpy and Pandas, it gives the following error.
I've seen this error mentioned in quite a few places on SO and Google, but I haven't been able to find a solution. Some people mention ... | For me @Charles Duffy comment solved it.
> Use LC\_ALL=C |
Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7 | 26,473,854 | 17 | 2014-10-20T19:58:59Z | 26,513,378 | 20 | 2014-10-22T17:23:04Z | [
"python",
"windows",
"visual-studio-2010",
"64bit",
"pip"
] | I was creating a virtualenv with a clean install of python 3.3, 64-bit version. (Note: I have several installs of python on my computer including WinPython but want to set up clean and small virtualenvs for several projects that I am working on. The WinPython version works just fine.) When I used pip to try to install ... | Ultimately I was able to get pip running. In a nutshell (and redundant from info above) here is what I did to intall 64-bit packages for python 3.3:
1) Installed Microsoft Visual C++ 2010 Express [Download Here](https://app.vssps.visualstudio.com/profile/review?download=true&family=VisualStudioCExpress&release=VisualS... |
Missing Spanish wordnet from NLTK | 26,474,731 | 3 | 2014-10-20T20:53:19Z | 26,494,099 | 7 | 2014-10-21T18:50:44Z | [
"python",
"nlp",
"nltk",
"wordnet"
] | I am trying to use the Spanish Wordnet from the Open Multilingual Wordnet in NLTK 3.0, but it seems that it was not downloaded with the 'omw' package. For example, with a code like the following:
```
from nltk.corpus import wordnet as wn
print [el.lemma_names('spa') for el in wn.synsets('bank')]
```
I get the follow... | Here's the full error traceback if a language is missing from the Open Multilingual WordNet in your `nltk_data` directory:
```
>>> from nltk.corpus import wordnet as wn
>>> wn.synsets('bank')[0].lemma_names('spa')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7... |
Flask + SQLAlchemy adjacency list backref error | 26,475,977 | 3 | 2014-10-20T22:27:50Z | 26,476,115 | 7 | 2014-10-20T22:40:29Z | [
"python",
"orm",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] | I have the following model:
```
class Category(db.Model):
__tablename__ = 'categories'
id = db.Column(db.Integer, primary_key=True)
parent_id = db.Column(db.Integer, db.ForeignKey(id), nullable=True)
level = db.Column(db.SmallInteger)
name = db.Column(db.String(200))
children = db.relationship... | On this line...
```
children = db.relationship('Category', backref=backref('parent', remote_side=id))
```
You are using the attribute `backref`, but have never defined it. You would get a similar error if you had wrote...
```
children = db.relationship('Category', backref=photosynthesis('parent', remote_side=id))
``... |
Converting LinearSVC's decision function to probabilities (Scikit learn python ) | 26,478,000 | 8 | 2014-10-21T02:29:55Z | 26,496,300 | 10 | 2014-10-21T21:05:14Z | [
"python",
"machine-learning",
"scikit-learn",
"svm"
] | I use linear SVM from scikit learn (LinearSVC) for binary classification problem. I understand that LinearSVC can give me the predicted labels, and the decision scores but I wanted probability estimates (confidence in the label). I want to continue using LinearSVC because of speed (as compared to sklearn.svm.SVC with l... | If you want speed, then just *replace* the SVM with `sklearn.linear_model.LogisticRegression`. That uses the exact same training algorithm as `LinearSVC`, but with log-loss instead of hinge loss.
Using [1 / (1 + exp(-x))] will produce probabilities, in a formal sense (numbers between zero and one), but they won't adhe... |
Python regex to extract version from a string | 26,480,935 | 3 | 2014-10-21T07:15:20Z | 26,480,961 | 8 | 2014-10-21T07:17:06Z | [
"python",
"regex"
] | The string looks like this: (`\n` used to break the line)
```
MySQL-vm
Version 1.0.1
WARNING:: NEVER EDIT/DELETE THIS SECTION
```
What I want is only 1.0.1 .
I am trying `re.search(r"Version+'([^']*)'", my_string, re.M).group(1)` but it is not working.
`re.findall(r'\d+', version)` is giving me an array of the num... | Use the below regex and get the version number from group index 1.
```
Version\s*([\d.]+)
```
[DEMO](http://regex101.com/r/aB2vZ7/5)
```
>>> import re
>>> s = """MySQL-vm
... Version 1.0.1
...
... WARNING:: NEVER EDIT/DELETE THIS SECTION"""
>>> re.search(r'Version\s*([\d.]+)', s).group(1)
'1.0.1'
```
**Explanation... |
Could not Import Pandas: TypeError | 26,481,285 | 3 | 2014-10-21T07:38:29Z | 26,504,096 | 7 | 2014-10-22T09:16:27Z | [
"python",
"pandas"
] | I wanted to use the following pandas, but could not import it at all.
<https://github.com/pydata/pandas/releases/download/v0.15.0/pandas-0.15.0.win-amd64-py2.7.exe>
However I could not import it:
```
import pandas as pd
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import pandas a... | This happened to me when upgrading google-api-python-client to a version higher than 1.2.0.
The problem is in Pandas, but it has been fixed: <https://github.com/pydata/pandas/commit/403f38da35ab04d3997f61db3c98134fe02910d3>
The solutions is to either downgrade google-api-python-client, fix the lines in pandas yourself... |
Python pandas insert list into a cell | 26,483,254 | 9 | 2014-10-21T09:26:25Z | 26,510,251 | 11 | 2014-10-22T14:44:05Z | [
"python",
"list",
"pandas",
"insert",
"dataframe"
] | I have a list 'abc' and a dataframe 'df':
```
abc = ['foo', 'bar']
df =
A B
0 12 NaN
1 23 NaN
```
I want to insert the list into cell 1B, so I want this result:
```
A B
0 12 NaN
1 23 ['foo', 'bar']
```
Ho can I do that?
1) If I use this:
```
df.ix[1,'B'] = abc
```
I get the following error mess... | `df3.set_value(1, 'B', abc)` works for any dataframe. Take care of the data type of column 'B'. Eg. a list can not be inserted into a float column, at that case `df['B'] = df['B'].astype(object)` can help. |
Python configparser error after Yosemite install | 26,486,609 | 2 | 2014-10-21T12:21:18Z | 26,887,811 | 9 | 2014-11-12T13:10:38Z | [
"python",
"osx-yosemite",
"configparser"
] | I've upgraded to Yosemite and this seems to have broken my python modules.
`python --version` == `Python 2.7.6`
Then from the Python shell:
```
>>> import pyrax
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pyrax/__init__.py", line 38, in <module>
... | Just move the old six out of the way, and reinstall via pip...
```
mkdir ~/six-old-library/
mkdir ~/six-old-system-library/
sudo mv /Library/Python/2.7/site-packages/six* ~/six-old-library/
sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six* ~/six-old-system-library/
sudo pip instal... |
How to decode url to path in python, django | 26,488,708 | 8 | 2014-10-21T14:05:44Z | 26,488,773 | 9 | 2014-10-21T14:08:24Z | [
"python",
"django",
"python-2.7",
"url",
"path"
] | Hi I need to convert url to path, what i got is this url as bellow:
```
url = u'/static/media/uploads/gallery/Marrakech%2C%20Morocco_be3Ij2N.jpg'
```
and what to be looked something like this:
```
path = u'/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg'
```
thx. | Use [`urllib.unquote`](https://docs.python.org/2/library/urllib.html#urllib.unquote) to decode `%`-encoded string:
```
>>> import urllib
>>> url = u'/static/media/uploads/gallery/Marrakech%2C%20Morocco_be3Ij2N.jpg'
>>> urllib.unquote(url)
u'/static/media/uploads/gallery/Marrakech, Morocco_be3Ij2N.jpg'
```
Using [`url... |
Using Django's m2m_changed to modify what is being saved pre_add | 26,493,254 | 6 | 2014-10-21T18:02:53Z | 26,550,942 | 10 | 2014-10-24T15:15:34Z | [
"python",
"django",
"django-signals",
"django-orm",
"m2m"
] | I am not very familiar with Django's signals and could use some help.
How do I modified the pk\_set before the instance is saved? Do I have to return something to the signal caller (like the `kwargs`)? Or do I save the `instance` myself?
As a simplified example: I wanted to ensure the Category with `pk=1` is included... | Just updating the `pk_set` is sufficient. You don't need to do any extra work. Once the video instance is saved, it will have a category with pk=1.
```
from django.db import models
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
class Category(models.Model):
pass
class Video... |
Extracting text from a PDF file using PDFMiner in python? | 26,494,211 | 18 | 2014-10-21T18:56:50Z | 26,495,057 | 45 | 2014-10-21T19:47:47Z | [
"python",
"text-extraction",
"pdfminer"
] | Python Version 2.7
I am looking for documentation *or* examples on how to extract text from a PDF file using PDFMiner with Python.
It looks like PDFMiner updated their API and all the relevant examples I have found contain outdated code(classes and methods have changed). The libraries I have found that make the task ... | Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)
```
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStrin... |
Pandas - pandas.DataFrame.from_csv vs pandas.read_csv | 26,495,408 | 13 | 2014-10-21T20:10:07Z | 26,495,839 | 13 | 2014-10-21T20:35:43Z | [
"python",
"csv",
"pandas"
] | What's the difference between:
`pandas.DataFrame.from_csv`, doc link: <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_csv.html>
and
`pandas.read_csv`, doc link: <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html> | There is no real difference (both are based on the same underlying function), but as noted in the comments, they have some *different default values* (`index_col` is 0 or None, `parse_dates` is True or False for `read_csv` and `DataFrame.from_csv` respectively) and *`read_csv` supports more arguments* (in `from_csv` th... |
How to convert defaultdict of defaultdicts [of defaultdicts] to dict of dicts [of dicts]? | 26,496,831 | 5 | 2014-10-21T21:38:39Z | 26,496,899 | 9 | 2014-10-21T21:43:51Z | [
"python",
"python-2.7",
"dictionary",
"collections"
] | Using [this answer](http://stackoverflow.com/a/5029958/1547030), I created a `defaultdict` of `defaultdict`s. Now, I'd like to turn that deeply nested dict object back into an ordinary python dict.
```
from collections import defaultdict
factory = lambda: defaultdict(factory)
defdict = factory()
defdict['one']['two']... | You can recurse over the tree, replacing each `defaultdict` instance with a dict produced by a dict comprehension:
```
def default_to_regular(d):
if isinstance(d, defaultdict):
d = {k: default_to_regular(v) for k, v in d.iteritems()}
return d
```
Demo:
```
>>> from collections import defaultdict
>>> ... |
Theano HiddenLayer Activation Function | 26,497,564 | 10 | 2014-10-21T22:38:18Z | 26,498,509 | 15 | 2014-10-22T00:19:43Z | [
"python",
"machine-learning",
"neural-network",
"theano"
] | Is there anyway to use Rectified Linear Unit (ReLU) as the activation function of the hidden layer instead of `tanh()` or `sigmoid()` in Theano? The implementation of the hidden layer is as follows and as far as I have searched on the internet ReLU is not implemented inside the Theano.
```
class HiddenLayer(object):
... | relu is easy to do in Theano:
```
switch(x<0, 0, x)
```
To use it in your case make a python function that will implement relu and pass it to activation:
```
def relu(x):
return theano.tensor.switch(x<0, 0, x)
HiddenLayer(..., activation=relu)
```
Some people use this implementation: `x * (x > 0)`
UPDATE: Newe... |
Theano HiddenLayer Activation Function | 26,497,564 | 10 | 2014-10-21T22:38:18Z | 28,776,557 | 7 | 2015-02-28T00:21:37Z | [
"python",
"machine-learning",
"neural-network",
"theano"
] | Is there anyway to use Rectified Linear Unit (ReLU) as the activation function of the hidden layer instead of `tanh()` or `sigmoid()` in Theano? The implementation of the hidden layer is as follows and as far as I have searched on the internet ReLU is not implemented inside the Theano.
```
class HiddenLayer(object):
... | **UPDATE:** Latest version of theano has native support of ReLU:
[T.nnet.relu](http://deeplearning.net/software/theano/library/tensor/nnet/nnet.html#theano.tensor.nnet.relu), which should be preferred over custom solutions.
I decided to compare the speed of solutions, since it is very important for NNs. Compared speed... |
Scrape multiple pages with BeautifulSoup and Python | 26,497,722 | 7 | 2014-10-21T22:52:17Z | 26,497,825 | 12 | 2014-10-21T23:03:08Z | [
"python",
"html",
"web-scraping",
"page-numbering"
] | My code successfully scrapes the tr align=center tags from [ <http://my.gwu.edu/mod/pws/courses.cfm?campId=1&termId=201501&subjId=ACCY> ] and writes the td elements to a text file.
However, there are multiple pages available at the site above in which I would like to be able to scrape.
For example, with the url above... | The trick here is to check the requests that are coming in and out of the page-change action when you click on the link to view the other pages. The way to check this is to use Chrome's inspection tool (via pressing `F12`) or installing the Firebug extension in Firefox. I will be using Chrome's inspection tool in this ... |
How to remove extra string "Line2D" in matplotlib legend | 26,499,812 | 7 | 2014-10-22T03:20:49Z | 26,499,836 | 13 | 2014-10-22T03:23:33Z | [
"python",
"matplotlib"
] | I have a string "Line2D" appended in the beginning of my matplotlib legend. How to get rid of it? A simple python script that reproduces this problem is as follows:
```
import numpy as np
import matplotlib.pylab as plt
x=np.linspace(0,1,20)
y=np.sin(2*x)
z=np.cos(2*x)
p1, = plt.plot(x,y, label='sin(x)')
p2, = plt.pl... | If you pass just one list to `legend`, it has to be the labels you want to show, not the objects whose labels you want to show. It is converting those line objects to strings, which gives `Line2D(...)`.
Since you gave the lines labels when you created them, you don't need to pass anything to `legend`. Just `plt.legend... |
Why do generator expressions and dict/set comprehensions in Python 2 use a nested function unlike list comprehensions? | 26,500,330 | 8 | 2014-10-22T04:27:40Z | 26,500,410 | 10 | 2014-10-22T04:38:35Z | [
"python",
"bytecode",
"python-internals"
] | List comprehensions have their code placed directly in the function where they are used, like this:
```
>>> dis.dis((lambda: [a for b in c]))
1 0 BUILD_LIST 0
3 LOAD_GLOBAL 0 (c)
6 GET_ITER
>> 7 FOR_ITER 12 (to 22)... | Yes, you are correct. In Python 3.x, this is introduced to fix the variable leakage. Quoting from the post of [History of Python blog](http://python-history.blogspot.in/2010/06/from-list-comprehensions-to-generator.html), supposedly written by the BDFL himself,
> We also made another change in Python 3, to improve equ... |
PyCharm: "Simplify Chained Comparison" | 26,502,775 | 47 | 2014-10-22T08:02:08Z | 26,502,847 | 90 | 2014-10-22T08:07:07Z | [
"python",
"pycharm"
] | I have an integer value `x`, and I need to check if it is between a `start` and `end` values, so I write the following statements:
```
if x >= start and x <= end:
# do stuff
```
This statement gets underlined, and the tooltip tells me that I must
> simplify chained comparison
As far as I can tell, that comparis... | In Python you can "chain" comparison operations which just means they are "and"ed together. In your case, it'd be like this:
```
if start <= x <= end:
```
Reference: <https://docs.python.org/2/reference/expressions.html#not-in> |
Why is there no uuid.uuid2 in Python? | 26,503,686 | 4 | 2014-10-22T08:54:04Z | 26,503,793 | 7 | 2014-10-22T08:59:50Z | [
"python",
"uuid"
] | [There's a `uuid.uuid1`, `uuid.uuid3`, `uuid.uuid4`, and `uuid.uuid5` but no `uuid.uuid2`.](https://docs.python.org/3.4/library/uuid.html)
What happened to `uuid2`? | From [What's new in Python 2.5](https://docs.python.org/3/whatsnew/2.5.html) in which `uuid` module was added for the first time:
> (Version 2 UUIDs are not specified in [RFC 4122](http://tools.ietf.org/html/rfc4122.html) and are not
> supported by this module.) |
Why is there no uuid.uuid2 in Python? | 26,503,686 | 4 | 2014-10-22T08:54:04Z | 26,503,844 | 7 | 2014-10-22T09:02:35Z | [
"python",
"uuid"
] | [There's a `uuid.uuid1`, `uuid.uuid3`, `uuid.uuid4`, and `uuid.uuid5` but no `uuid.uuid2`.](https://docs.python.org/3.4/library/uuid.html)
What happened to `uuid2`? | The UUID2 is a special UUID generated in combination with [DCE Security](http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_2_.28DCE_Security.29) server. It's rarely used nowadays. I guess the effort to implement that was in no relation to the request for such a functionality. |
Error using pelican-quickstart "No module named html_parser" | 26,508,606 | 8 | 2014-10-22T13:29:13Z | 31,671,281 | 8 | 2015-07-28T08:38:18Z | [
"python",
"pelican"
] | I decided to give `pelican` a try, but when I run `pelican-quickstart`, I get the following dialog:
```
$ pelican-quickstart
Traceback (most recent call last):
File "/usr/local/bin/pelican-quickstart", line 9, in <module>
load_entry_point('pelican==3.4.0', 'console_scripts', 'pelican-quickstart')()
File "/Syst... | Reinstall pelican doesn't help me, so i'm make a little fix in pelican Modifications was made in
/Library/Python/2.7/site-packages/pelican/readers.py file
at line 24 place
```
from six.moves import html_parser
```
instead of
```
from six.moves.html_parser import HTMLParser
```
and at line 299
```
class _HTML... |
Why is my object properly removed from a list when __eq__ isn't being called? | 26,509,990 | 17 | 2014-10-22T14:31:46Z | 26,510,056 | 16 | 2014-10-22T14:34:46Z | [
"python",
"list",
"python-3.x"
] | I have the following code, which is making me scratch my head -
```
class Element:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def eq(self, other):
print('comparing {} to {} ({})'.format(self.name,
other.name,
self.name == other.name))... | The fourth element is the exactly same object with the object the code is passing (`elements[3]`).
In other word,
```
>>> elements[3] is elements[3]
True
>>> elements[3] == elements[3]
True
```
So, no need to check the equality because they(?) are identical (same) one.
Equality check will happen if they are not ide... |
Why is my object properly removed from a list when __eq__ isn't being called? | 26,509,990 | 17 | 2014-10-22T14:31:46Z | 26,510,212 | 9 | 2014-10-22T14:42:28Z | [
"python",
"list",
"python-3.x"
] | I have the following code, which is making me scratch my head -
```
class Element:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def eq(self, other):
print('comparing {} to {} ({})'.format(self.name,
other.name,
self.name == other.name))... | Python's [`list.remove()`](https://hg.python.org/cpython/file/17e1af9ad66c/Objects/listobject.c#l2337) method first checks whether the both objects are identical otherwise falls back to regular comparison methods like `__eq__` in this case. So, in this case as both objects are identical it is removed from the list.
``... |
Why does mysql connector break ("Lost connection to MySQL server during query" error) | 26,510,114 | 5 | 2014-10-22T14:37:16Z | 26,747,980 | 7 | 2014-11-05T00:57:25Z | [
"python",
"mysql",
"mamp"
] | When I run large queries (queries returning many rows), I get the `Lost connection to MySQL server during query` error, and I cannot see what I do wrong. I use the "new" mysql driver from mysql.com (not the "old" MySQLdb), and the mysql version that is bundled with MAMP. Python 2.7. Table is not corrupted, `analyze tab... | I also had to switch to PyMySQL. I am running pip 1.5.6, Python 2.7.8, and tried mysql-connector 2.0.1
I was able to run the query from within Sequel Pro with no problems, but my Python query would fail with the error described in the question after returning just a subset of results.
Switched to PyMySQL and things w... |
Numpy: Fastest way of computing diagonal for each row of a 2d array | 26,511,401 | 4 | 2014-10-22T15:36:54Z | 26,511,778 | 8 | 2014-10-22T15:55:46Z | [
"python",
"arrays",
"numpy"
] | Given a 2d Numpy array, I would like to be able to compute the diagonal for each row in the fastest way possible, I'm right now using a list comprehension but I'm wondering if it can be vectorised somehow?
For example using the following *M* array:
```
M = np.random.rand(5, 3)
[[ 0.25891593 0.07299478 0.36586996]... | Here's one way using element-wise multiplication of `np.eye(3)` (the 3x3 identity array) and a slightly re-shaped `M`:
```
>>> M = np.random.rand(5, 3)
>>> np.eye(3) * M[:,np.newaxis,:]
array([[[ 0.42527357, 0. , 0. ],
[ 0. , 0.17557419, 0. ],
[ 0. , 0. , ... |
Ubuntu - How to install a Python module (BeautifulSoup) on Python 3.3 instead of Python 2.7? | 26,511,791 | 10 | 2014-10-22T15:56:21Z | 26,803,508 | 16 | 2014-11-07T14:31:40Z | [
"python",
"python-2.7",
"ubuntu",
"beautifulsoup",
"python-3.3"
] | I have this code (as written in BS4 documentaion):
```
from bs4 import BeautifulSoup
```
When I run the script (using python3) I get the error:
```
ImportError: No module named 'bs4'
```
So installed BeatifulSoup by:
```
sudo pip install BeatifulSoup4
```
But when I try to run the script again I get the sam... | Ubuntu has beautifulsoup packaged. I found it by running apt-cache search
```
$ apt-cache search beautifulsoup
```
I see it has both a 2.7 and 3.3 version in the results. You can get the 3.3 version by installing python3-bs4
```
$ sudo apt-get install python3-bs4
``` |
How does one ignore unexpected keyword arguments passed to a function? | 26,515,595 | 11 | 2014-10-22T19:32:06Z | 26,515,631 | 8 | 2014-10-22T19:33:55Z | [
"python",
"function",
"dictionary"
] | Suppose I have some funciton, `f`
```
def f (a=None):
print a
```
Now, if I have a dictionary such as `dct = {"a":"Foo"}`, I may call `f(**dct)` and get the result `Foo` printed.
However, suppose I have a dictionary `dct2 = {"a":"Foo", "b":"Bar"}`. If I call `f(**dct2)` I get a
```
TypeError: f() got an unexpec... | This can be done by using [`**kwargs`](http://stackoverflow.com/q/1769403/2647279), which allows you to collect all undefined keyword arguments in a dict:
```
def f(**kwargs):
print kwargs['a']
```
Quick test:
```
In [2]: f(a=13, b=55)
13
```
**EDIT** If you still want to use default arguments, you keep the ori... |
How does one ignore unexpected keyword arguments passed to a function? | 26,515,595 | 11 | 2014-10-22T19:32:06Z | 26,515,682 | 9 | 2014-10-22T19:36:53Z | [
"python",
"function",
"dictionary"
] | Suppose I have some funciton, `f`
```
def f (a=None):
print a
```
Now, if I have a dictionary such as `dct = {"a":"Foo"}`, I may call `f(**dct)` and get the result `Foo` printed.
However, suppose I have a dictionary `dct2 = {"a":"Foo", "b":"Bar"}`. If I call `f(**dct2)` I get a
```
TypeError: f() got an unexpec... | As an extension to the answer posted by @Bas, I would suggest to add the kwargs arguments (variable length keyword arguments) as the second parameter to the function
```
>>> def f (a=None, **kwargs):
print a
>>> dct2 = {"a":"Foo", "b":"Bar"}
>>> f(**dct2)
Foo
```
This would necessarily suffice the case of
1. `... |
multiprocessing.Pool: What's the difference between map_async and imap? | 26,520,781 | 42 | 2014-10-23T03:23:30Z | 26,521,507 | 141 | 2014-10-23T04:51:41Z | [
"python",
"multiprocessing",
"python-multiprocessing"
] | I'm trying to learn how to use Python's `multiprocessing` package, but I don't understand the difference between `map_async` and `imap`.
I noticed that both `map_async` and `imap` are executed asynchronously. So when should I use one over the other? And how should I retrieve the result returned by `map_async`?
Should ... | There are two key differences between `imap`/`imap_unordered` and `map`/`map_async`:
1. The way they consume the iterable you pass to them.
2. The way they return the result back to you.
`map` consumes your iterable by converting the iterable to a list (assuming it isn't a list already), breaking it into chunks, and ... |
Using Pandas to pd.read_excel() for multiple worksheets of the same workbook | 26,521,266 | 4 | 2014-10-23T04:21:45Z | 26,521,726 | 8 | 2014-10-23T05:16:38Z | [
"python",
"excel",
"pandas",
"dataframe"
] | I have a large spreadsheet file (.xlsx) that I'm processing using python pandas. It happens that I need data from two tabs in that large file. One of the tabs has a ton of data and the other is just a few square cells.
When I use [pd.read\_excel()](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.excel.... | Try [this](https://github.com/pydata/pandas/blob/master/pandas/io/excel.py#L130):
```
xls = pd.ExcelFile('path_to_file.xls')
df1 = xls.parse('Sheet1')
df2 = xls.parse('Sheet2')
```
Haven't looked closely to see how much is done in the first line and how much is done in subsequent lines, but it's at least a place to s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.