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
Virtual environment in R?
24,283,171
25
2014-06-18T08:35:06Z
25,144,408
15
2014-08-05T17:00:44Z
[ "python" ]
I've found several posts about best practice, reproducibility and workflow in R, for example: * [How to increase longer term reproducibility of research (particularly using R and Sweave)](http://stats.stackexchange.com/questions/4466/how-to-increase-longer-term-reproducibility-of-research-particularly-using-r-an) * [C...
I'm going to use the comment posted by @cboettig in order to resolve this question. ## Packrat Packrat is a dependency management system for R. Gives you three important advantages (all of them focused in your portability needs) * Isolated : Installing a new or updated package for one project won’t break your othe...
Insert a row to pandas dataframe
24,284,342
9
2014-06-18T11:27:35Z
24,284,515
9
2014-06-18T11:36:54Z
[ "python", "pandas" ]
I have a dataframe.. ``` s1 = pd.Series([5, 6, 7]) s2 = pd.Series([7, 8, 9]) df = pd.DataFrame([list(s1), list(s2)], columns = ["A", "B", "C"]) A B C 0 5 6 7 1 7 8 9 [2 rows x 3 columns] ``` and I need to add a first row [2, 3, 4] to get.. ``` A B C 0 2 3 4 1 5 6 7 2 7 8 9 ``` I've tri...
One way to achieve this is ``` >>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True) Out[330]: A B C 0 2 3 4 1 5 6 7 2 7 8 9 ``` Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id),...
How to use pip with python 3.4 on windows?
24,285,508
26
2014-06-18T12:22:15Z
24,285,723
7
2014-06-18T12:32:57Z
[ "python", "python-3.x", "pip" ]
Just installed a fresh copy of python 3.4.1 on windows 7. [Here](https://docs.python.org/3/whatsnew/3.4.html) says that pip is included by default. but i could not find any pip.exe or some pip commands. Do I need to install it separately or it exists somewhere?
"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can sti...
How to use pip with python 3.4 on windows?
24,285,508
26
2014-06-18T12:22:15Z
24,289,829
7
2014-06-18T15:44:26Z
[ "python", "python-3.x", "pip" ]
Just installed a fresh copy of python 3.4.1 on windows 7. [Here](https://docs.python.org/3/whatsnew/3.4.html) says that pip is included by default. but i could not find any pip.exe or some pip commands. Do I need to install it separately or it exists somewhere?
Assuming you don't have any other Python installations, you should be able to do `python -m pip` after a default installation. Something like the following should be in your system path: `C:\Python34\Scripts` This would obviously be different, if you installed Python in a different location.
How to use pip with python 3.4 on windows?
24,285,508
26
2014-06-18T12:22:15Z
26,322,805
28
2014-10-12T07:18:03Z
[ "python", "python-3.x", "pip" ]
Just installed a fresh copy of python 3.4.1 on windows 7. [Here](https://docs.python.org/3/whatsnew/3.4.html) says that pip is included by default. but i could not find any pip.exe or some pip commands. Do I need to install it separately or it exists somewhere?
i have Windows7 Python 3.4.1; following command suggested by Guss worked well ``` C:\Users>py -m pip install requests ``` Output ``` Downloading/unpacking requests Installing collected packages: requests Successfully installed requests Cleaning up... ```
Comparing 3 lists in Python
24,288,780
2
2014-06-18T14:53:56Z
24,288,866
8
2014-06-18T14:58:42Z
[ "python", "list", "compare" ]
The following code compares three lists, `motherList fatherlist` and `sonList`, checking to see if every value in `sonList` is represented in either `motherList` or `fatherList` once. ``` def compareList(motherList, fatherList, sonList): count = 0 for x in sonList: if x in motherList and x in fathe...
Use sets, my friend. ``` In [1]: {0, 1, 2} & {1, 2, 3} & {2, 3, 4} Out[1]: set([2]) ``` So your code will look like: ``` if set(motherList) & set(fatherlist) & set(sonList): ans = "Mendelion" else: ans = "Non-Medelian" ``` First of, it looks really-really good for any developer, secondly it is not so expens...
Searching PyPI by topic
24,289,397
15
2014-06-18T15:22:48Z
24,340,416
12
2014-06-21T09:52:52Z
[ "python", "pip", "package-managers", "pypi" ]
For every python package you can specify a [list of classifiers](https://pypi.python.org/pypi?%3aaction=list_classifiers). Among others there is a `Topic` classifier, that puts the package in the specified categories that can be [browsed on `PyPI`](https://pypi.python.org/pypi?%3aaction=browse). For example, [`numpy`]...
You can search PyPI by classifier via the [XMLRPC API](https://wiki.python.org/moin/PyPIXmlRpc), using the [`browse()`](https://wiki.python.org/moin/PyPIXmlRpc#line-143) method: ``` try: import xmlrpclib # Python 2 except ImportError: import xmlrpc.client as xmlrpclib # Python 3 pypi = xmlrpclib.ServerProxy...
How to suppress warning QPixmap: It is not safe to use pixmaps outside the GUI thread
24,289,418
3
2014-06-18T15:23:31Z
24,292,473
8
2014-06-18T18:17:43Z
[ "python", "qt", "error-handling", "pyqt", "suppress-warnings" ]
I am having this error flood my terminal and make it impossible to debug. Is there a way to silence this warning? This error only generated when I included a scrollToBottom() on my TableWidget.
You **do not want to suppress that warning** because it's not a warning. It's an error. Qt is way too polite here. It should be a hard assertion, since the presence of it indicates that you wrote your code in such a way that it's likely to have corrupted the data of GUI objects and continuing past that point is a fool'...
drop_all() freezes in Flask with SQLAlchemy
24,289,808
6
2014-06-18T15:43:24Z
24,291,231
10
2014-06-18T16:59:32Z
[ "python", "flask" ]
I am writing test cases for a Flask application. I have a setUp method which drops the tables in the db before re-creating them again. It looks like this: ``` def setUp(self): # other stuff... myapp.db.drop_all() myapp.db.create_all() # db creation... ``` This works fine for the first test, but it fr...
Oki, there might be other solutions but for now, after searching the interwebs, I found that the problem disappears if I prepend my code with a `myapp.db.session.commit()`. I guess, somewhere a transaction was waiting to be committed. ``` def setUp(self): # other stuff... myapp.db.session.commit() #<--- solu...
Why is the join built-in having no influence on my code?
24,292,308
3
2014-06-18T18:08:04Z
24,292,319
12
2014-06-18T18:08:49Z
[ "python", "string", "join" ]
I had a bug that I reduced down to this: ``` a = ['a','b','c'] print( "Before", a ) " ".join(a) print( "After", a ) ``` Which outputs this: ``` runfile('C:/program.py', wdir=r'C:/') Before ['a', 'b', 'c'] After ['a', 'b', 'c'] ``` What's going on here?
[`str.join`](https://docs.python.org/2/library/stdtypes.html#str.join) does not operate in-place because string objects are immutable in Python. Instead, it returns an entirely new string object. If you want `a` to reference this new object, you need to explicitly reassign it: ``` a = " ".join(a) ``` Demo: ``` >>> ...
Why can't use semi-colon before for loop in Python?
24,293,128
6
2014-06-18T18:58:00Z
24,293,199
9
2014-06-18T19:02:10Z
[ "python" ]
I can join lines in Python using semi-colon, e.g. ``` a=5; b=10 ``` But why can't I do the same with for ``` x=['a','b']; for i,j in enumerate(x): print(i,":", j) ```
The short (yet valid) answer is simply "because the language [grammar](https://docs.python.org/3/reference/grammar.html) isn't defined to allow it". As for why *that's* the case, it's hard if not impossible to be sure unless you ask whoever came up with that portion of the grammar, but I imagine it's due to readability...
Why can't use semi-colon before for loop in Python?
24,293,128
6
2014-06-18T18:58:00Z
24,293,200
11
2014-06-18T19:02:12Z
[ "python" ]
I can join lines in Python using semi-colon, e.g. ``` a=5; b=10 ``` But why can't I do the same with for ``` x=['a','b']; for i,j in enumerate(x): print(i,":", j) ```
Because the Python grammar disallows it. See [the documentation](https://docs.python.org/2/reference/compound_stmts.html): ``` stmt_list ::= simple_stmt (";" simple_stmt)* [";"] ``` Semicolons can only be used to separate simple statements (not compound statements like `for`). And, really, there's almost no reas...
Hive UDF with Python
24,293,843
3
2014-06-18T19:44:48Z
24,300,006
9
2014-06-19T06:23:48Z
[ "python", "hadoop", "pandas", "hive" ]
I'm new to python, pandas, and hive and would definitely appreciate some tips. I have the python code below, which I would like to turn into a UDF in hive. Only instead of taking a csv as the input, doing the transformations and then exporting another csv, I would like to take a hive table as the input, and then expor...
You can make use of the `TRANSFORM` function to make use of a UDF written in Python. The detailed steps are outlined [here](http://blog.spryinc.com/2013/09/a-guide-to-user-defined-functions-in.html) and [here](http://andreyfradkin.com/posts/2013/06/15/combining-hive-and-python).
uwsgi broken pipe - django, nginx
24,294,319
4
2014-06-18T20:17:19Z
24,297,330
7
2014-06-19T01:14:29Z
[ "python", "django", "nginx", "tastypie", "uwsgi" ]
I'm randomly (and consistently) getting a broken pipe in uwsgi... shown below. Any idea what could be causing this or how I can debug? I'm on django (tastypie), uwsgi, nginx, and am running an m3.medium on aws (ubuntu 14.04). ``` [pid: 1516|app: 0|req: 548/1149] 10.0.0.204 () {42 vars in 1039 bytes} [Wed Jun 18 16:11...
you can safely ignore them, they are triggered by the client (or nginx) disconnecting in the middle of the request. As the response times are really low, it is very probably a client disconnection. Btw, post your nginx and uWSGI configuration for being sure.
How to install pip for python 2.6?
24,294,467
8
2014-06-18T20:27:21Z
24,294,605
20
2014-06-18T20:36:51Z
[ "python", "pip", "easy-install" ]
I tried following the instructions from [this answer](http://stackoverflow.com/a/5538353/1312080) but `easy_install-2.6` could not find `pip`: ``` >sudo easy_install-2.6 pip Processing pip error: Not a recognized archive type: pip ``` How do I install pip for python 2.6? My root need for pip for 2.6 is explained in ...
Just follow the instructions [here](https://pip.pypa.io/en/latest/installing.html#install-pip): 1. Securely download [`get-pip.py`](https://bootstrap.pypa.io/get-pip.py). 2. In the directory you saved `get-pip.py`, run ``` sudo python2.6 get-pip.py ``` and you'll be all set. This will install `pip` for ...
Python Flask Intentional Empty Response
24,295,426
18
2014-06-18T21:38:47Z
24,295,616
37
2014-06-18T21:53:08Z
[ "python", "flask", "response" ]
Is there a way to return a response (from make\_response() object or similar) with certain properties so that it doesn't render the page again and doesn't do anything else either. I am trying to run a code on the server without generating any output A simple 'return None' produces: ``` ValueError: View function did n...
You are responding to a request, your HTTP server *must* return *something*. The HTTP 'empty response' response is `204 No Content`: ``` return ('', 204) ``` Note that returning a file to the browser is *not* an empty response, just different from a HTML response.
Implementing a "Kurtosis filter" using scipys generic_filter
24,296,216
13
2014-06-18T22:49:23Z
24,470,662
9
2014-06-28T20:26:43Z
[ "python", "numpy", "scipy", "filtering", "sliding-window" ]
I have a `5000*5000` numpy array on which I want to calculate the Kurtosis for windows of size 25. I tried putting scipys own kurtosis function in the `generic_filter` found in `ndimage.filters` like so: ``` import numpy as np from scipy.stats import kurtosis from scipy.ndimage.filters import generic_filter mat = np...
Your approach is correct, but as you note, it is way too slow for the task at hand. Consider how large your task is in the numerically best implementation (not bothering about boundary values): ``` def kurt(X, w): n, m = X.shape K = np.zeros_like(X) for i in xrange(w, n-w): # 5000 it...
Is there a way to make matplotlib scatter plot marker or color according to a discrete variable in a different column?
24,297,097
5
2014-06-19T00:41:03Z
24,297,239
9
2014-06-19T01:03:51Z
[ "python", "matplotlib", "pandas", "scatter" ]
I'm making scatterplots out of a DF using matplotlib. In order to get different colors for each data set, I'm making two separate calls to plt.scatter: ``` plt.scatter(zzz['HFmV'], zzz['LFmV'], label = dut_groups[0], color = 'r' ) plt.scatter(qqq['HFmV'], qqq['LFmV'], label = dut_groups[1], color = 'b' ) plt.legend() ...
What you're doing will almost work, but you have to pass `color` a vector of colors, not just a vector of variables. So you could do: ``` color = df.Group.map({dut_groups[0]: "r", dut_groups[1]: "b"}) plt.scatter(x, y, color=color) ``` Same goes for the marker style You could also use [seaborn](http://stanford.edu/~...
take a list of numbers from the command line and print the largest number
24,299,988
2
2014-06-19T06:22:06Z
24,300,085
7
2014-06-19T06:28:24Z
[ "python", "python-3.x" ]
I have to write a program that, when given numbers from the command line, manages to read and print the highest number. ``` import sys numbers = sys.argv[1] def map(f,items): result = [] for i in range(0,len(items),1): result = result + [f(items[i]) return result ``` im trying to find the easiest way to...
``` import sys print(max(float(x) for x in sys.argv[1:])) ``` Alternatively, you can use `print(max(sys.argv[1:], key=float))` (thanks to the nice addition by frostnational). Demo: ``` >> python a.py 12 6 3.14 11 12.0 ``` Explanation: If we add `print(sys.argv)` to the script, the output for the above example will ...
File not found error when launching a subprocess
24,306,205
7
2014-06-19T12:05:47Z
24,306,385
13
2014-06-19T12:14:58Z
[ "python", "shell", "subprocess" ]
I need to run the command `date | grep -o -w '"+tz+"'' | wc -w` using Python on my localhost. I am using `subprocess` module for the same and using the `check_output` method as I need to capture the output for the same. However it is throwing me an error : ``` Traceback (most recent call last): File "test.py", line...
You have to add `shell=True` to execute a shell command. `check_output` is trying to find an executable called: `date | grep -o -w '"+tz+"'' | wc -w` and he cannot find it. (no idea why you removed the essential information from the error message). See the difference between: ``` >>> subprocess.check_output('date | g...
Why is Cython slower than vectorized NumPy?
24,308,236
8
2014-06-19T13:48:58Z
24,308,430
7
2014-06-19T13:58:39Z
[ "python", "arrays", "performance", "numpy", "cython" ]
Consider the following Cython code : ``` cimport cython cimport numpy as np import numpy as np @cython.boundscheck(False) @cython.wraparound(False) def test_memoryview(double[:] a, double[:] b): cdef int i for i in range(a.shape[0]): a[i] += b[i] @cython.boundscheck(False) @cython.wraparound(False) d...
Another option is to use raw pointers (and the global directives to avoid repeating `@cython...`): ``` #cython: wraparound=False #cython: boundscheck=False #cython: nonecheck=False #... cdef ctest_raw_pointers(int n, double *a, double *b): cdef int i for i in range(n): a[i] += b[i] def test_raw_poin...
Celery Result backend. DisabledBackend object has no attribute _get_task_meta_for
24,309,035
3
2014-06-19T14:27:08Z
25,678,229
7
2014-09-05T03:30:27Z
[ "python", "celery" ]
I have configured celery and the backend: ``` cleryapp = Celery( 'tasks_app', brocker='amqp://guest@localhost//', backend='db+postgresql://guest@localhost:5432' ) ``` 'results' appears disabled when i start the worker, but I read on another question here that that's not the issue. The database is getting all...
I found a more convenient way to do that. ``` result = celery.AsyncResult(task_id) ``` `celery` is the Celery instance of your application, not the celery module.
Memory-efficent way to iterate over part of a large file
24,312,123
5
2014-06-19T16:50:46Z
24,312,242
11
2014-06-19T16:58:05Z
[ "python", "iteration", "large-files" ]
I normally avoid reading files like this: ``` with open(file) as f: list_of_lines = f.readlines() ``` and use this type of code instead. ``` f = open(file) for line in file: #do something ``` Unless I only have to iterate over a few lines in a file (and I know which lines those are) then it think it is eas...
If I understand your question correctly, the problem you're encountering is that storing **all** the lines of text in a list and then taking a slice uses too much memory. What you want is to read the file line-by-line, while ignoring all but a certain set of lines (say, lines `[17,34)` for example). Try using `enumera...
Python 2.7 with Bloomberg API import blpapi failure
24,317,469
6
2014-06-19T22:51:46Z
24,331,522
8
2014-06-20T16:12:02Z
[ "python", "eclipse", "python-2.7", "bloomberg", "blpapi" ]
This is my development environment: * Windows 7 on a 64-bit HP Pavilion laptop * Python 2.7, 32-bit in folder C:\python27 * Development environment is Eclipse with PyDev, but this doesn't seem to matter, because I get the same kind of failure whether I use Anaconda or Notepad++. * [Python 2.7 Binary Installer for Wind...
I encountered a similar problem, and spent some time troubleshooting the issue with Bloomberg helpdesk. Here's what I learnt: The ImportError is the result of Bloomberg not being able to find the "blpapi3\_32.dll" DLL file. This DLL file can be located under the \bin or \lib folder of Bloomberg's C/C++ library, which ...
flask make_response with large files
24,318,084
5
2014-06-20T00:03:23Z
24,318,158
7
2014-06-20T00:10:44Z
[ "python", "flask", "download" ]
So I'm real green with file I/O and memory limits and the such, and I'm having a rough time getting my web application to successfully serve large file downloads to a web browser with flask's `make_response`. The following code works on smaller files (<~1GB), but gives me a `MemoryError` Exception when I get into large...
See the docs on [Streaming Content](http://flask.pocoo.org/docs/patterns/streaming/). Basically, you write a function that yields chunks of data, and pass that generator to the response, rather than the whole thing at once. Flask and your web server do the rest. ``` from flask import stream_with_context, Response @ap...
How to use raw input to define a variable
24,330,143
2
2014-06-20T14:54:27Z
24,330,176
8
2014-06-20T14:56:06Z
[ "python", "variables", "raw-input" ]
Here is my code: ``` Adherent = "a person who follows or upholds a leader, cause, etc.; supporter; follower." word=raw_input("Enter a word: ") print word ``` When I run this code and input Adherent, the word Adherent is produced. How can I have the definition of Adherent pop up instead?
You can (should) use a [dictionary](https://docs.python.org/2/library/stdtypes.html#mapping-types-dict) where words are mapped to definitions: ``` >>> word_dct = {"Adherent" : "a person who follows or upholds a leader, cause, etc.; supporter; follower."} >>> word=raw_input("Enter a word: ") Enter a word: Adherent >>> ...
Sending messages with Telegram - APIs or CLI?
24,330,922
23
2014-06-20T15:36:15Z
27,411,553
7
2014-12-10T21:53:33Z
[ "python", "linux", "shell", "python-2.7", "telegram" ]
I would like to be able to send a message to a group chat in Telegram. I want to run a python script (which makes some operations that already works) and then, if some parameters have some values the script should send a message to a group chat through Telegram. I am using Ubuntu, and Python 2.7 I think, if I am not w...
Since version 1.05 you can use the -P option to accept messages from a socket, which is a third option to solve your problem. Sorry that it is not really the answer to your question, but I am not able to comment your question because I do not have enough reputation.
Sending messages with Telegram - APIs or CLI?
24,330,922
23
2014-06-20T15:36:15Z
31,079,913
20
2015-06-26T18:32:19Z
[ "python", "linux", "shell", "python-2.7", "telegram" ]
I would like to be able to send a message to a group chat in Telegram. I want to run a python script (which makes some operations that already works) and then, if some parameters have some values the script should send a message to a group chat through Telegram. I am using Ubuntu, and Python 2.7 I think, if I am not w...
Telegram recently released their new [Bot API](https://core.telegram.org/bots/api) which makes sending/receiving messages trivial. I suggest you also take a look at that and see if it fits your needs, it beats wrapping the client library or integrating with their MTProto API. ``` import urllib import urllib2 # Genera...
Getting error messages from psycopg2 exceptions
24,332,005
2
2014-06-20T16:43:13Z
32,056,764
7
2015-08-17T17:57:14Z
[ "python", "postgresql", "psycopg2" ]
This is my first project using psycopg2 extensively. I'm trying to find a way to extract the psql error message for whenever a connection attempt fails. I've tested the code below will work if all the variables are set correctly, however whenever an error condition occurs (e.g. user chooses a database that doesn't exis...
When I try to catch exceptions, e.pgerror is always None for connection errors. The following code block gets around this by directly printing 'e'. ``` try: conn = psycopg2.connect(conn_string) except psycopg2.OperationalError as e: print('Unable to connect!\n{0}').format(e) sys.exit(1) else: print('Con...
How can I make this repeat forever?
24,335,680
8
2014-06-20T21:09:47Z
24,335,780
9
2014-06-20T21:17:44Z
[ "python", "loops", "random" ]
I have this terrain generator that is, in my opinion pretty efficient. I just can't get it to print forever. Here's the current code I have for it: ``` import random print(' '.join([random.choice(['#','o','~','*']) for i in range(10000)])) ``` I tried to do this, but I got a `SyntaxError`. ``` import random print(' ...
Well, if you want a delay between the characters, you can't use `join()` because that will give you a single string instead of a "character generator". And if you plan on using an "infinite" generator, you can't use `join()` either for that same reason. How about this: ``` import random import sys import time while ...
Overlapping regex
24,336,080
10
2014-06-20T21:41:57Z
24,336,503
10
2014-06-20T22:22:30Z
[ "python", "regex" ]
I want a regex that matches any set of digits, with one possible dot. If there is another dot and more digits after it, do an overlapping match with the previous digits, the dot, and the following digits. example string = `'aa323aa232.02.03.23.99aa87..0.111111.mm'` desired results = `[323, 232.02, 02.03, 03.23, 23....
This uses a lookahead assertion for capturing, and then another expression for gobbling characters following your rules: ``` >>> import re >>> i = 'aa323aa232.02.03.23.99aa87..0.111111.mm' >>> re.findall(r'(?=(\d+(?:\.\d+)?))\d+(?:\.\d+(?!\.?\d))?', i) ``` Output ``` ['323', '232.02', '02.03', '03.23', '23.99', '87'...
Why does a function that returns itself max out recursion in python 3
24,338,139
15
2014-06-21T04:00:06Z
24,338,579
9
2014-06-21T05:22:33Z
[ "python", "python-3.x", "recursion" ]
Why does this code give the error: `RuntimeError: maximum recursion depth exceeded during compilation`? `print_test` never calls itself, hence I would think it isn't a recursive function. ``` def print_test(): print("test") return print_test print_test() #prints 'test' print() #a quick way of writing "print_...
I believe this has to do with [Issue #5765](http://hg.python.org/cpython/rev/ab02cd145f56). > Apply a hard recursion limit in the compiler [as of 3.3] Not 100% sure, but this code [runs on 3.2.3](http://ideone.com/UCG8CH): ``` def f(): return f eval("f" + "()" * 10000) ``` but fails on my 3.4.1 which leaves me...
Installing package dependencies for Scrapy
24,338,840
7
2014-06-21T06:10:40Z
26,704,290
21
2014-11-02T20:55:02Z
[ "python", "windows", "python-2.7", "scrapy", "pyopenssl" ]
So among the many packages users need to install for Scrapy, I think I'm having trouble with pyOpenSSL. When I try to get a tutorial Scrapy project created, I get this following output: ``` Traceback (most recent call last): File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main "__main__", fname, lo...
I got the same error on Mac OS. I solved it by using openssl 0.13 instead of the latest version. ``` easy_install pyOpenSSL==0.13 ``` or ``` pip install pyOpenSSL==0.13 ```
Django tuple checking: TEMPLATE_DIRS should be tuple?
24,340,746
2
2014-06-21T10:34:27Z
24,340,766
8
2014-06-21T10:36:26Z
[ "python", "django", "tuples", "django-1.7" ]
I'm trying Django 1.7. This is my TEMPLATE\_DIRS setting: ``` TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/') ) ``` which is fine for Django 1.6, but doesn't work for Django 1.7. Can someone explains this? Thx!!
You need a trailing `,` for it to be a tuple, see below, the last `,` ``` TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('\\', '/'), ) ``` When there's a single element in the tuple you need to leave a trailing comma at the end, e.g. `(a,)` is a tuple with single element `a`, but `...
Why does this bash call from python not work?
24,340,877
2
2014-06-21T10:55:13Z
24,340,994
7
2014-06-21T11:08:13Z
[ "python", "bash", "subprocess", "bitcoin" ]
I am messing around with Bitcoins a bit. When I want to get some info about the local bitcoin install, I simply run `bitcoin getinfo` and I get something like this: ``` { "version" : 90100, "protocolversion" : 70002, "walletversion" : 60000, "balance" : 0.00767000, "blocks" : 306984, "timeoffse...
Either use a sequence in arguments: ``` process = subprocess.Popen(['bitcoin', 'getinfo'], stdout=subprocess.PIPE) ``` or set the `shell` parameter to `True`: ``` process = subprocess.Popen('bitcoin getinfo', stdout=subprocess.PIPE, shell=True) ``` You can find more information in the [documentation](https://docs.p...
Python equivalent of a given wget command
24,346,872
6
2014-06-21T23:46:48Z
28,313,383
22
2015-02-04T04:15:07Z
[ "python", "wget" ]
I'm trying to create a Python function that does the same thing as this wget command: ``` wget -c --read-timeout=5 --tries=0 "$URL" ``` `-c` - Continue from where you left off if the download is interrupted. `--read-timeout=5` - If there is no new data coming in for over 5 seconds, give up and try again. Given `-c` ...
There is also a nice Python module named `wget` that is pretty easy to use. Found [here](https://pypi.python.org/pypi/wget). This demonstrates the simplicity of the design: ``` >>> import wget >>> url = 'http://www.futurecrew.com/skaven/song_files/mp3/razorback.mp3' >>> filename = wget.download(url) 100% [..............
How do you add additional files to a wheel?
24,347,450
25
2014-06-22T01:48:24Z
25,964,691
10
2014-09-21T22:52:10Z
[ "python", "pip", "python-wheel" ]
How do control what files are included in a wheel? It appears `MANIFEST.in` isn't used by `python setup.py bdist_wheel`. **UPDATE**: I was wrong about the difference between installing from a source tarball vs a wheel. The source distribution includes files specified in `MANIFEST.in`, but the installed package only h...
Have you tried using `package_data` in your `setup.py`? `MANIFEST.in` seems targetted for python versions <= 2.6, I'm not sure if higher versions even look at it. After exploring <https://github.com/pypa/sampleproject>, their `MANIFEST.in` says: ``` # If using Python 2.6 or less, then have to include package data, ev...
When making a call from the browser, how can I tell programmatically when the call has been answered?
24,347,630
5
2014-06-22T02:31:00Z
24,375,662
7
2014-06-23T22:33:51Z
[ "javascript", "python", "twilio" ]
I'm writing a web client with Flask, and integrating Twilio to let me make phone calls from the browser. All well and good, it's mostly working, but I have some status information I want to update when the call is answered. The connection.status() method doesn't seem to help, since "open" seems to mean the call is att...
**For outbound calls** The twilio.js library states: ``` Twilio.Device is your main entry point for creating outbound connections, accepting incoming connections, and setting up your connection event handlers. ``` Within the Device documentation, it goes on to state that the .status() method: ``` Returns the status...
Getting size of pdf without downloading
24,351,677
3
2014-06-22T13:24:11Z
24,351,693
7
2014-06-22T13:25:58Z
[ "python", "http-headers", "request" ]
Is it possible to know the size of a pdf e.g. <http://example.com/ABC.pdf> using requests module in python without actually downloading it. I am writing an application where if the internet speed is slow and if the size of the pdf is large then it will postpone the download for the future
# use a HTTP-HEAD request Response shall provide in headers more details of the file to download without fetching full file. ``` >>> url = "http://www.pdf995.com/samples/pdf.pdf" >>> req = requests.head(url) >>> req.content '' >>> req.headers["content-length"] '433994' ``` # or try streaming read ``` >>> req = requ...
Getting size of pdf without downloading
24,351,677
3
2014-06-22T13:24:11Z
24,351,725
7
2014-06-22T13:29:01Z
[ "python", "http-headers", "request" ]
Is it possible to know the size of a pdf e.g. <http://example.com/ABC.pdf> using requests module in python without actually downloading it. I am writing an application where if the internet speed is slow and if the size of the pdf is large then it will postpone the download for the future
Like this ``` import urllib2 response = urllib2.urlopen('http://example.com/ABC.pdf') size_of_pdf = response.headers['Content-Length'] ``` Before `response.read()` is called, the contents are not downloaded. Take a look at `Response Headers` in [Wikipedia](http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Resp...
Using Celery Chunks with sequences of objects or integers
24,352,065
2
2014-06-22T14:09:08Z
24,357,023
7
2014-06-23T00:28:56Z
[ "python", "celery" ]
When using [`task.chunks`](http://celery.readthedocs.org/en/latest/userguide/canvas.html#chunks) with a sequence of sequences (e.g: list of strings) ``` my_task.chunks(['a', 'b', 'c', 'd'], 2).delay() ``` things work fine. However, passing a sequence of anything else (e.g: integers or objects) ``` my_task.chunks([1,...
Change it to: ``` my_task.chunks([(1,), (2,), (3,), (4,)], 2).delay() ``` As the error trace complains, each argument in your iterable is expected to be a sequence, which can be unpacked into arguments of the function you want to call. How it comes, the `['a', 'b', 'c', 'd']` works? It is just a coincidence resulti...
Build wheel for a package (like scipy) lacking dependency declaration
24,353,267
10
2014-06-22T16:27:26Z
24,353,690
11
2014-06-22T17:17:36Z
[ "python", "scipy", "pip", "virtualenv", "python-wheel" ]
I think it doesn't make a difference here but I'm using Python 2.7. So the general part of my question is the following: I use a separate `virtualenv` for each of my projects. I don't have administrator access and I don't want to mess with system-installed packages anyway. Naturally, I want to use wheels to speed up p...
# Problem description * Have a python package (like `scipy`), which is dependent on other packages (like `numpy`) but `setup.py` is not declaring that requirement/dependency. * Building a wheel for such a package will succeed in case, current environment provides the package(s) which are needed. * In case, required pa...
What happens if you append a list to itself?
24,354,645
4
2014-06-22T18:59:42Z
24,354,667
7
2014-06-22T19:02:00Z
[ "python", "circular-reference" ]
What will happen if I try to append a list to itself? ``` # Let's say empty list is created. some_list = [] # Now, append it with self some_list.append(some_list) # Output shows [[...]] on iPython console. ``` What does this mean? Does `some_list` become recursive list or something ? What will happen to reference cou...
Yes, you created a circular reference; the list object references itself. This means that the reference count goes up by 1 extra reference. The Python garbage collector will handle this case; if nothing else references the list object anymore the garbage collector process is responsible for breaking that circle: ``` ...
Removing \u2018 and \u2019 character
24,358,361
6
2014-06-23T04:25:05Z
24,358,544
13
2014-06-23T04:48:28Z
[ "python" ]
I am using Beautiful Soup to parse webpages and printing the name of the webpages visited on the terminal. However, often the name of the webpage has single right **(\u2018)** and left**(\u2019)** character which the python can't print as it gives charmap encoding error. Is there any way to remove these characters?
These codes are Unicode for the single left and right quote characters. You can replace them with their ASCII equivalent which Python shouldn't have any problem printing on your system: ``` >>> print u"\u2018Hi\u2019" ‘Hi’ >>> print u"\u2018Hi\u2019".replace(u"\u2018", "'").replace(u"\u2019", "'") 'Hi' ``` Altern...
Better to use dict of integer keys or a very long list?
24,359,095
6
2014-06-23T05:45:13Z
24,359,459
8
2014-06-23T06:14:10Z
[ "python", "python-2.7" ]
Basically, I need to make a lookup table with non-consecutive integer IDs. I'm wondering whether, in terms of lookup speed, I'm generally better off using a `dict` with integer keys anyway, or using a very long `list` with a lot of empty indices. It seems to me that a `list` might still be faster, as Python should know...
To answer your question about `dict` vs `list` you'd have to give the *exact* information about the number of elements, the number of missing elements etc, so tha we could estimate exactly the memory usage of the two data structure and try to predict and/or check their performance. In general a `dict` of `N` key-value...
Different calculation result using Python
24,360,328
4
2014-06-23T07:13:48Z
24,360,362
10
2014-06-23T07:15:33Z
[ "python" ]
I've got a weird case using Python to get the result of this calculation: ``` 11.66 * 0.98 * 1.05 + 1.7 + 0.70 * 1.03 ``` in Python the result that I got is **14.41914** but when my customer calculate it using their calculator and iPhone the result that they got is **14.8300842** so which is the correct result ? an...
The correct result is the one Python gave you. Your customer is using a calculator that doesn't account for order of operations, or has used the calculator in such a way that order of operations information was discarded.
Different calculation result using Python
24,360,328
4
2014-06-23T07:13:48Z
24,360,438
7
2014-06-23T07:21:23Z
[ "python" ]
I've got a weird case using Python to get the result of this calculation: ``` 11.66 * 0.98 * 1.05 + 1.7 + 0.70 * 1.03 ``` in Python the result that I got is **14.41914** but when my customer calculate it using their calculator and iPhone the result that they got is **14.8300842** so which is the correct result ? an...
What your customer seems to have done is this: ``` >>> (11.66*0.98*1.05 + (1.7+0.7))*1.03 14.830084200000002 >>> ``` whereas that expression in python: ``` >>> 11.66*0.98*1.05 + 1.7+0.7*1.03 14.419140000000001 ``` Does the multiplies first: ``` >>> (11.66*0.98*1.05) + 1.7+(0.7*1.03) 14.419140000000001 ``` Its a v...
Quick NLTK parse into syntax tree
24,363,145
3
2014-06-23T09:59:49Z
24,376,470
7
2014-06-24T00:08:03Z
[ "python", "nlp", "nltk" ]
I am trying to parse several hundreds of sentences into their syntax trees and i need to do that fast, the problem is that if i use NLTK then i need to define a grammar, and i cant know that i only know its gonna be english. I tried using [this](https://github.com/emilmont/pyStatParser) statistical parser, and it works...
Parsing is a fairly computationally intensive operation. You can probably get much better performance out of a more polished parser, such as [bllip](https://github.com/BLLIP/bllip-parser). It is written in c++ and benefits from a team having worked on it over a prolonged period. There is a python module which interacts...
Naive Bayes: Imbalanced Test Dataset
24,367,141
9
2014-06-23T13:25:26Z
24,528,969
9
2014-07-02T10:36:24Z
[ "python", "machine-learning", "classification", "scikit-learn", "text-classification" ]
I am using scikit-learn Multinomial Naive Bayes classifier for binary text classification (classifier tells me whether the document belongs to the category X or not). I use a balanced dataset to train my model and a balanced test set to test it and the results are very promising. This classifer needs to run in real ti...
You have encountered one of the problems with classification with a highly imbalanced class distribution. I have to disagree with those that state the problem is with the Naive Bayes method, and I'll provide an explanation which should hopefully illustrate what the problem is. Imagine your false positive rate is 0.01,...
Very strange behavior of operator 'is' with methods
24,367,930
47
2014-06-23T14:00:37Z
24,368,034
56
2014-06-23T14:05:16Z
[ "python", "python-2.7", "methods", "python-internals" ]
Why is the first result `False`, should it not be `True`? ``` >>> from collections import OrderedDict >>> OrderedDict.__repr__ is OrderedDict.__repr__ False >>> dict.__repr__ is dict.__repr__ True ```
For user-defined functions, in Python 2 *unbound* and *bound* methods are created on demand, through the [descriptor protocol](https://docs.python.org/2/howto/descriptor.html); `OrderedDict.__repr__` is such a method object, as the wrapped function is implemented as a [pure-Python function](http://hg.python.org/cpython...
TypeError: b'1' is not JSON serializable
24,369,666
9
2014-06-23T15:25:10Z
24,370,008
9
2014-06-23T15:43:22Z
[ "python", "json", "python-3.x", "http-post" ]
I am trying to send a POST request as JSON. \*email variable is of type "bytes" ``` def request_to_SEND(email, index): url = "....." data = { "body": email.decode('utf-8'), "query_id": index, "debug": 1, "client_id": "1", "campaign_id": 1, "meta": {"content_type...
This is happening because you're passing a `bytes` object in the `data` dict (`b'1'`, specifically), probably as the value of `index`. You need to decode it to a `str` object before `json.dumps` can work with it: ``` data = { "body": email.decode('utf-8'), "query_id": index.decode('utf-8'), # decode it here ...
Django image resizing and convert before upload
24,373,341
6
2014-06-23T18:58:08Z
24,373,874
15
2014-06-23T19:31:01Z
[ "python", "django", "django-models" ]
I searched a lot on this subject but couldn't really find what I need. I'll explain my problem : On my website, the user can upload an image. I need to resize this image and convert it to JPEG ***before*** uploading it. I saw some solutions using a method in the Views.py, but I'd like to do it by overriding the save(...
First, it's best to establish the correct language. Django and Python exist only on the server side. Therefore, anything they manipulate, save, or otherwise use, has to be first sent to the server. If Django or Python is to manage the photo, the user MUST upload this photo to the server first. Once the photo is uploade...
where to put freeze_support() in a Python script?
24,374,288
4
2014-06-23T19:58:07Z
24,374,798
11
2014-06-23T20:30:04Z
[ "python", "runtime-error", "multiprocessing", "scikit-learn", "anaconda" ]
I am confused about using `freeze_support()` for `multiprocessing` and I get an `Runtime Error` without it. I am only running a script, not defining a function or a module. Can I still use it? Or the packages I import should have been using it? [Here](https://docs.python.org/2/library/multiprocessing.html#miscellaneou...
On Windows **all** of your `multiprocessing`-using code must be guarded by `if __name__ == "__main__":` So to be safe, I would put all of your the code currently at the top-level of your script in a `main()` function, and then just do this at the top-level: ``` if __name__ == "__main__": main() ``` See the "Safe...
Python loop to run for certain amount of seconds
24,374,620
7
2014-06-23T20:17:35Z
24,374,857
17
2014-06-23T20:34:22Z
[ "python", "time", "timer", "while-loop" ]
I have a while loop, and I want it to keep running through for 15 minutes. it is currently: ``` while True: #blah blah blah ``` (this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop) Thanks!
Try this: ``` import time t_end = time.time() + 60 * 15 while time.time() < t_end: # do whatever you do ``` This will run for 15 min x 60 s = 900 seconds. Function `time.time` returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision...
NetworkX largest component no longer working?
24,374,627
9
2014-06-23T20:18:00Z
24,378,179
12
2014-06-24T04:11:08Z
[ "python", "networkx" ]
according to networkx documentation, connected\_component\_subgraphs(G) returns a sorted list of all components. Thus the very first one should be the largest component. However, when I try to get the largest component of a graph G using the example code on the documentation page ``` G=nx.path_graph(4) G.add_edge(5,6...
The networkx-1.9 documentation is here <http://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.components.connected.connected_components.html#networkx.algorithms.components.connected.connected_components> The interface was changed to return a generator (as you figured out). The ex...
how to print estimated coefficients after a (GridSearchCV) fit a model? (SGDRegressor)
24,375,911
2
2014-06-23T23:00:23Z
24,388,583
8
2014-06-24T13:58:30Z
[ "python", "scikit-learn" ]
I am new to `scikit-learn`, but it did what I was hoping for. Now, maddeningly, the only remaining issue is that I don't find how I could print (or even better, write to a small text file) all the coefficients it estimated, all the features it selected. What is the way to do this? Same with SGDClassifier, but I think ...
The `SGDClassifier` instance fitted with the best hyperparameters is stored in `gs.best_estimator_`. The `coef_` and `intercept_` are the fitted parameters of that best model.
HTTPError 403 (Forbidden) with Django and python-social-auth connecting to Google with OAuth2
24,377,506
50
2014-06-24T02:37:52Z
24,377,507
82
2014-06-24T02:37:52Z
[ "python", "django", "oauth-2.0", "google-api" ]
Using `python-social-auth`, I get a `403: Forbiden` error message after accepting access from google
**You need to add the [`Google+ API`](https://console.developers.google.com/apis/api/plus/overview) to the list of enabled APIs on the Google Developer Console (under `APIs`)** Note: If you want to see the real error message, use the traceback to look at the content of the `response` variable (`response.text`). I use ...
HTTPError 403 (Forbidden) with Django and python-social-auth connecting to Google with OAuth2
24,377,506
50
2014-06-24T02:37:52Z
26,745,731
11
2014-11-04T21:52:23Z
[ "python", "django", "oauth-2.0", "google-api" ]
Using `python-social-auth`, I get a `403: Forbiden` error message after accepting access from google
Thanks also. I was using this [python-social-auth tutorial by art and logic](http://www.artandlogic.com/blog/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-django-application/), but couldn't get past a 403: Forbidden HTTPError at /complete/google-oauth2/ until enabling Google+ API as above **and wait...
Numpy: get values from array where indices are in another array
24,380,791
2
2014-06-24T07:29:59Z
24,381,114
7
2014-06-24T07:47:06Z
[ "python", "numpy", "pandas" ]
I have a mx1 array, a, that contains some values. Moreover, I have a nxk array, say b, that contains indices between 0 and m. Example: ``` a = np.array((0.1, 0.2, 0.3)) b = np.random.randint(0, 3, (4, 4)) ``` For every index value in b I want to get the corresponding value from a. I can do it with a loop: ``` c = n...
``` >>> a array([ 0.1, 0.2, 0.3]) >>> b array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1]]) >>> a[b] array([[ 0.1, 0.1, 0.2, 0.2], [ 0.1, 0.1, 0.2, 0.2], [ 0.1, 0.2, 0.2, 0.1], [ 0.1, 0.2, 0.1, 0.2]]) ``` Tada! It's just `a[b]`. (Also, you probably wa...
Difference between unicode.isdigit() and unicode.isnumeric()
24,384,852
10
2014-06-24T10:57:45Z
24,384,917
17
2014-06-24T11:01:33Z
[ "python", "unicode" ]
What is the difference between methods unicode.isdigit() and unicode.isnumeric()?
The [Python 3 documentation](https://docs.python.org/3/library/stdtypes.html#str.isdigit) is a little clearer than the Python 2 docs: > `str.isdigit()` > [...] Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. Formally, a digit is a character that ...
Adding words to scikit-learn's CountVectorizer's stop list
24,386,489
6
2014-06-24T12:19:49Z
24,386,751
21
2014-06-24T12:33:04Z
[ "python", "scikit-learn", "stop-words" ]
Scikit-learn's [CountVectorizer](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html) class lets you pass a string 'english' to the argument stop\_words. I want to add some things to this predefined list. Can anyone tell me how to do this?
According to the [source code](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py) for `sklearn.feature_extraction.text`, the full list (actually a `frozenset`, from [`stop_words`](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/stop_words.py)...
Does * have side effect in Python regular expression matching?
24,389,803
4
2014-06-24T14:53:15Z
24,389,904
8
2014-06-24T14:57:17Z
[ "python", "regex" ]
I'm learning Python's regular expression, following is working as I expected: ``` >>> import re >>> re.split('\s+|:', 'find a str:s2') ['find', 'a', 'str', 's2'] ``` But when I change `+` to `*`, the output is weird to me: ``` >>> re.split('\s*|:', 'find a str:s2') ['find', 'a', 'str:s2'] ``` How is such pattern...
The 'side effect' you are seeing is that `re.split()` will only split on matches that are longer than 0 characters. The `\s*|:` pattern matches *either* on zero or more spaces, *or* on `:`, **whichever comes first**. But zero spaces *matches everywhere*. In those locations where more than zero spaces matched, the spli...
Many-To-Many Relationship in ndb
24,392,270
5
2014-06-24T16:55:43Z
24,396,938
9
2014-06-24T21:51:09Z
[ "python", "google-app-engine", "many-to-many", "app-engine-ndb" ]
Trying to model a many-to-many relationship with ndb. Can anyone point to a good example of how to do this? At here is an example of what I have at the moment: ``` class Person(ndb.Model): guilds = ndb.KeyProperty(kind="Guild", repeated=True) class Guild(ndb.Model) members = ndb.KeyProperty(kind="Person", ...
No. That is not the correct way to go about it. You can model a many-to-many relationship with only one repeated property: ``` class Person(ndb.Model): guilds = ndb.KeyProperty(kind="Guild", repeated=True) class Guild(ndb.Model): @property def members(self): return Person.query().filter(Person.gu...
Multiple non-flagged arguments with cement
24,395,723
3
2014-06-24T20:30:33Z
25,213,795
9
2014-08-08T23:46:27Z
[ "python", "command-line-interface" ]
I am writing a python command line interface tool on top of [cement](http://builtoncement.org/). Cement is working quite well for standard argument parseing. However, I want to be able to add a specific amount of non-flagged arguments. Let me explain. Typical command line tool: ``` cmd subcmd -flag -stored=flag ``` ...
You can do this using optional positional arguments in ArgParse. There is actually an issue open in GitHub for better documentation on this subject: <https://github.com/datafolklabs/cement/issues/256> Basically, if you want "command1" to handle the operation, then "some/dir some\_string" would be positional arguments...
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?
24,398,302
12
2014-06-25T00:12:08Z
26,856,894
7
2014-11-11T03:16:25Z
[ "python", "python-2.7", "beautifulsoup", "lxml" ]
``` ... soup = BeautifulSoup(html, "lxml") File "/Library/Python/2.7/site-packages/bs4/__init__.py", line 152, in __init__ % ",".join(features)) bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library? ``` The above outputs on my Terminal. I am o...
I have a suspicion that this is related the the parser that BS will use to read the HTML. They [document it here](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser) but if you're like me (on OSX) you might be stuck with something that requires a bit of work: You'll notice that in the BS4 docume...
Expression to remove URL links from Twitter tweet
24,399,820
2
2014-06-25T03:45:05Z
24,399,874
11
2014-06-25T03:51:43Z
[ "python", "regex", "string" ]
I simply would like to find and replace all occurrences of a twitter url in a string (tweet): Input: > This is a tweet with a url: <http://t.co/0DlGChTBIx> Output: > This is a tweet with a url: I've tried this: ``` p=re.compile(r'\<http.+?\>', re.DOTALL) tweet_clean = re.sub(p, '', tweet) ```
Do this: ``` result = re.sub(r"http\S+", "", subject) ``` * `http` matches literal characters * `\S+` matches all non-whitespace characters (the end of the url) * we replace with the empty string
how could we install opencv on anaconda?
24,400,935
4
2014-06-25T05:37:00Z
30,987,824
19
2015-06-22T19:04:28Z
[ "python", "pip", "anaconda" ]
I tried to install OpenCV on Anaconda ``` pip install cv2 pip install opencv conda install opencv conda install -c https://conda.binstar.org/jjhelmus opencv ``` (refered here [Anaconda doesn't find module cv2](http://stackoverflow.com/questions/22589157/anaconda-doesnt-find-module-cv2)) but all failed. Does anybody ...
Run the following command: ``` conda install -c https://conda.binstar.org/menpo opencv ``` I realized that opencv3 is also available now, run the following command: ``` conda install -c https://conda.binstar.org/menpo opencv3 ``` **Edit on Aug 18, 2016**: You may like to add the "menpo" channel permanently by: ```...
Django ChoiceField
24,403,075
10
2014-06-25T07:50:40Z
24,404,791
8
2014-06-25T09:21:07Z
[ "python", "django", "choicefield" ]
I'm trying to solve following issue: I have a web page that can see only moderators. Fields displayed on this page (after user have registered): Username, First name+Last name, Email, Status, Relevance, etc. I need to display table with information of all users stored in db with this fields, but two of fields have ...
First I recommend you as @ChrisHuang-Leaver suggested to define a new file with all the choices you need it there, like `choices.py`: ``` STATUS_CHOICES = ( (1, _("Not relevant")), (2, _("Review")), (3, _("Maybe relevant")), (4, _("Relevant")), (5, _("Leading candidate")) ) RELEVANCE_CHOICES = ( ...
Why is numpy.spacing(0) giving me an impossible number?
24,408,207
2
2014-06-25T12:05:36Z
24,408,933
11
2014-06-25T12:39:31Z
[ "python", "python-2.7", "numpy", "floating-point", "ieee-754" ]
I am working on Python. I have tried numpy.spacing(0) and got 4.9406564584124654e-324, which is significantly smaller than finfo(float).tiny = 2.2250738585072014e-308 How is it possible? I have found no answer on the web, and this number is of course impossible in terms of the floating point standard.
Okay, so let's see what 4.94e-324 actually is: ``` >>> from math import log >>> log(4.94e-324, 2) -1074.0 ``` And just to make sure: ``` >>> 2**-1074 5e-324 ``` That's definitely less than the -1022 which is supposed to be the minimum exponent. In fact, it's **52** less than the minimum, which is the number of bits...
Pandas read_sql with parameters
24,408,557
13
2014-06-25T12:21:42Z
24,418,294
13
2014-06-25T20:49:51Z
[ "python", "sql", "pandas" ]
Are there any examples of how to pass parameters with an SQL query in Pandas? In particular I'm using an SQLAlchemy engine to connect to a PostgreSQL database. So far I've found that the following works: ``` df = psql.read_sql(('select "Timestamp","Value" from "MyTable" ' 'where "Timestamp" BETWE...
The `read_sql` docs say this `params` argument can be a list, tuple or dict (see [docs](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html)). To pass the values in the sql query, there are different syntaxes possible: `?`, `:1`, `:name`, `%s`, `%(name)s` (see [PEP249](http://legacy.python.org/d...
python : can reduce be translated into list comprehensions like map, lambda and filter?
24,410,420
11
2014-06-25T13:43:39Z
24,412,174
10
2014-06-25T14:59:46Z
[ "python", "list", "reduce", "map-function" ]
When programming in python, I now avoid `map`, `lambda` and `filter` by using list comprehensions because it is easier to read and faster in execution. But can `reduce` be replaced as well? E.g. an object has an operator `union()` that works on another object, `a1.union(a2)`, and gives a 3rd object of same type. I ha...
It is no secret that reduce is [not among the favored functions](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) of the Pythonistas. Generically, [reduce](https://docs.python.org/3.0/library/functools.html#functools.reduce) is a [left fold on a list](http://en.wikipedia.org/wiki/Fold_%28higher-order_function%...
Requesting password in IPython notebook
24,410,785
7
2014-06-25T14:00:01Z
24,418,810
15
2014-06-25T21:21:59Z
[ "python", "ssh", "ipython" ]
I have an IPython notebook which accesses data via SSH using encrypted ssh key file. I don't want to store the password in the notebook (nor in a separate file). I can use `input` in order to read the password from user prompt, but in this case the password is visible on the screen. Is there a way to securely obtaining...
You should import the getpass module, then call getpass.getpass. ``` import getpass password = getpass.getpass() ``` **NOTE** the field where you enter the password may not appear in the ipython notebook. It appears in the terminal window on a mac, and I imagine it will appear in a command shell on a PC.
Using custom methods in filter with django-rest-framework
24,414,926
6
2014-06-25T17:24:03Z
24,414,927
9
2014-06-25T17:24:03Z
[ "python", "django", "django-rest-framework", "django-filter" ]
I would like to filter against query params in my REST API - [see django docs on this](http://www.django-rest-framework.org/api-guide/filtering#filtering-against-query-parameters). However, one parameter I wish to filter by is only available via a model @property example models.py: ``` class Listing(models.Model): ...
Use the 'action' parameter to specify a custom method - [see django-filter docs](http://django-filter.readthedocs.org/en/latest/ref/filters.html#action) First define a method that filters a queryset using the value of the category parameter: ``` def filter_category(queryset, value): if not value: ...
Flask-MongoEngine & PyMongo Aggregation Query
24,415,045
9
2014-06-25T17:30:20Z
24,420,848
12
2014-06-26T00:48:36Z
[ "python", "mongodb", "pymongo", "flask-mongoengine" ]
I am trying to make an aggregation query using flask-mongoengine, and from what I have read it does not sound like it is possible. I have looked over several forum threads, e-mail chains and a few questions on Stack Overflow, but I have not found a really good example of how to implement aggregation with flask-mongoen...
The class your define with Mongoengine actually has a `_get_collection()` method which gets the "raw" collection object as implemented in the pymongo driver. I'm just using the name `Model` here as a placeholder for your actual class defined for the connection in this example: ``` Model._get_collection().aggregate([ ...
Python arp sniffing raw socket no reply packets
24,415,294
10
2014-06-25T17:47:07Z
24,416,136
11
2014-06-25T18:39:00Z
[ "python", "arp", "sniffer" ]
to understand the network concepts a bit better and to improve my python skills I am trying to implement a packet sniffer with python. I have just started to learn python, so the code could be optimized of course ;) I have implemented an packet sniffer which unpacks the ethernet frame and the arp header. I want to mak...
I think you need to specify socket protocol number `0x0003` to sniff everything, and then filter out non-ARP packets after the fact. This worked for me: ``` import socket import struct import binascii rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003)) while True: packet = rawSock...
Coordinate of the closest point on a line
24,415,806
9
2014-06-25T18:20:54Z
24,440,122
9
2014-06-26T20:58:23Z
[ "python", "distance", "geos", "shapely" ]
There is a polyline with a list of coordinates of the vertices = [(x1,y1), (x2,y2), (x3,y3),...] and a point(x,y). In Shapely, `geometry1.distance(geometry2)` returns the shortest distance between the two geometries. ``` >>> from shapely.geometry import LineString, Point >>> line = LineString([(0,0),(5,7),(12,6)]) ...
The GIS term you are describing is [linear referencing](https://en.wikipedia.org/wiki/Linear_referencing), and [Shapely has these methods](http://toblerity.org/shapely/manual.html#linear-referencing-methods). ``` # Length along line that is closest to the point print(line.project(p)) # Now combine with interpolated p...
Automating pydrive verification process
24,419,188
17
2014-06-25T21:49:00Z
24,542,604
28
2014-07-02T23:20:14Z
[ "python", "google-api", "cloud", "google-drive-sdk", "pydrive" ]
I am trying to automate the `GoogleAuth` process when using the `pydrive` library (<https://pypi.python.org/pypi/PyDrive>). I've set up the pydrive and the google API such that my `secret_client.json` works but it requires web authentication for gdrive access every time i run my script: ``` from pydrive.auth import G...
First, you're misunderstanding one very important bit of how this works: > when I try to use the above script while I am logged into another > account. It doesn't upload the eng.txt into my gdrive that generated > the secret\_client.json but the account that was logged in when I > authorize the authentication This is...
=> in Google Python Example
24,420,379
3
2014-06-25T23:47:31Z
24,420,397
7
2014-06-25T23:48:52Z
[ "python" ]
So I'm new to Python and trying to work through the Google Python online class [[https://developers.google.com/edu/python/regular-expressions]](https://developers.google.com/edu/python/regular-expressions%5d) I am running Python 2.7.5 and when I try this example it has issues with the =>. I've tried searching google ...
The author is using `=>` to describe the result; it is *not* part of the Python syntax. Consider it written as the following, where the intent may be more clear: ``` match = re.search(r'iii', 'piiig') #=> found, match.group() == "iii" ```
What are Flask Blueprints, exactly?
24,420,857
28
2014-06-26T00:50:32Z
24,420,993
43
2014-06-26T01:11:21Z
[ "python", "flask", "wsgi" ]
I *have* read [the official Flask documentation](http://flask.pocoo.org/docs/blueprints/) on Blueprints and even [one](http://maximebf.com/blog/2012/11/getting-bigger-with-flask/#.U6ttiZSwK7M) or [two](http://charlesleifer.com/blog/dont-sweat-small-stuff-use-flask-blueprints/) blog posts on using them. I've even used ...
A blueprint is a template for generating a "section" of a web application. Think of it like a mold: ![A medallion mold with a gold medallion freshly removed from it](http://i.stack.imgur.com/kd1XW.jpg) You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint ...
Python all() and bool() empty cases?
24,422,510
4
2014-06-26T04:41:32Z
24,422,595
7
2014-06-26T04:51:52Z
[ "python", "built-in" ]
when using help(all), it returns: ``` all(iterable)=>bool return True if bool(x) is True for all values x in the iterable. if the iterable is empty, return True ``` help(bool) returns: ``` bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the ...
``` all(iterable) ``` ...is [documented](https://docs.python.org/2/library/functions.html#all) to be equivalent to; ``` def all(iterable): for element in iterable: if not element: return False return True ``` ...which returns *False if and only if any value in the list converts to False*....
Python all() and bool() empty cases?
24,422,510
4
2014-06-26T04:41:32Z
24,422,637
13
2014-06-26T04:56:02Z
[ "python", "built-in" ]
when using help(all), it returns: ``` all(iterable)=>bool return True if bool(x) is True for all values x in the iterable. if the iterable is empty, return True ``` help(bool) returns: ``` bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the ...
`bool()` is never invoked if `all()`'s argument is empty. That's why the docs point out the behavior of `all()` on an empty input as a special case. The behavior `bool() == False` is irrelevant to what `all()` does in any case. By the way, in Python `bool` is a subclass of `int`, so `bool() == False` is necessary to b...
Does Python's imaplib let you set a timeout?
24,422,724
5
2014-06-26T05:03:10Z
24,422,843
9
2014-06-26T05:15:21Z
[ "python", "imaplib" ]
I'm looking at the API for Python's [imaplib](https://docs.python.org/2/library/imaplib.html). From what I can tell, there is no way to setup a timeout like you can with [smtplib](https://docs.python.org/2/library/smtplib.html). Is that correct? How would you handle a host that's invalid if you don't want it to block...
The `imaplib` module doesn't provide a way to set timeout, but you can set a default timeout for new socket connections via the [`socket.setdefaulttimeout`](https://docs.python.org/2/library/socket.html#socket.setdefaulttimeout): ``` import socket import imaplib socket.setdefaulttimeout(10) imap = imaplib.IMAP4('test....
how to send an array over a socket in python
24,423,162
3
2014-06-26T05:43:31Z
24,424,025
9
2014-06-26T06:45:07Z
[ "python", "arrays", "sockets" ]
I have an array kind of `([1,2,3,4,5,6],[1,2,3,4,5,6])` this. I have to send it over a STREAM/TCP socket in python. Then I have to receive the same array at the receiving end.
Sockets are byte streams, so ideal is to write your protocol (read [this](http://stupidpythonideas.blogspot.ro/2013/05/sockets-are-byte-streams-not-message.html)) This is a basic example without protocol and you should care about buffer -> recv(). If it is too small, your data will be chopped off. That's why you shoul...
What's the difference between numpy.take and numpy.choose?
24,426,452
5
2014-06-26T09:03:47Z
24,450,567
11
2014-06-27T11:19:33Z
[ "python", "arrays", "numpy" ]
It seems that `numpy.take(array, indices)` and `numpy.choose(indices, array)` return the same thing: a subset of `array` indexed by `indices`. Are there only subtle differences between the two, or am I missing something more important? And is there a reason to prefer one over the other?
`numpy.take(array, indices)` and `numpy.choose(indices, array)` behave similarly on 1-D arrays, but this is just coincidence. As pointed out by jonrsharpe, they behave differently on higher-dimensional arrays. ## numpy.take `numpy.take(array, indices)` picks out elements from a flattened version of `array`. (The resu...
Retrieve email/message body in html using Gmail API
24,428,246
10
2014-06-26T10:35:06Z
24,433,196
13
2014-06-26T14:29:02Z
[ "python", "gmail-api" ]
Is there any way to retrieve message body in html form using GMail api ? I have already gone through the [`message.get`](https://developers.google.com/gmail/api/v1/reference/users/messages/get) docs.. Tried changing the `format` params to `full`, `minimal` & `raw`. But id did not help. Its returning the plain text of ...
Email messages that have both HTML and plain text content will have multiple payload parts, and the part with the mimeType "text/html" will contains the HTML content. You can find it with logic like: ``` var part = message.parts.filter(function(part) { return part.mimeType == 'text/html'; }); var html = urlSafeBase6...
Why does this multithreaded python program print from 0 to 99 CORRECTLY?
24,430,008
3
2014-06-26T12:01:37Z
24,430,161
7
2014-06-26T12:09:18Z
[ "python", "multithreading", "python-2.7" ]
This is the code. ``` from Queue import Queue from threading import * threadLock = Lock() def do_stuff(q): while True: threadLock.acquire() print q.get() q.task_done() threadLock.release() q = Queue(maxsize=0) num_threads = 10 for x in range(100): q.put(x) for i in range(num_threads): worker...
Your function doesn't do anything else between retrieving the next number from the queue and printing it. Python holds a lock (the GIL) while executing each bytecode, so only *between* bytecodes can threads switch. Looking at the function (without locks) shows us that there is only *one* spot where a thread switch wou...
Does Theano do automatic unfolding for BPTT?
24,431,621
8
2014-06-26T13:17:00Z
24,437,169
10
2014-06-26T17:57:21Z
[ "python", "gradient", "backpropagation", "theano" ]
I am implementing an RNN in Theano and I have difficulties training it. It doesn't even come near to memorising the training corpus. My mistake is most likely caused by me not understanding exactly how Theano copes with backpropagation through time. Right now, my code is as simple as it gets: ``` grad_params = theano....
I wouldn't say it does automatic "unfolding" - rather, Theano has a notion of what variables are connected, and can pass updates along that chain. If this is what you mean by unfolding, then maybe we are talking about the same thing. I am stepping through this as well, but using [Rasvan Pascanu's rnn.py](https://11350...
How do I parse dates with more than 24 hours in dateutil's parser in Python 3?
24,432,607
2
2014-06-26T14:01:09Z
24,432,718
8
2014-06-26T14:06:23Z
[ "python", "parsing", "datetime", "python-3.x" ]
I currently have a bunch of times in a column written like "27:32:18", meaning someone was waiting for 27 hours, 32 minutes, and 18 seconds. I keep getting "ValueError: hour must be in 0..23" whenever I try to parse these values. How should I go about parsing those values or converting them to a more standard format? ...
You don't *have* a date, you have a time duration. That may be related to dates and timestamps, but only in that the same units of time are involved and are displayed similarly to timestamps. As such, you cannot use `dateutil` for parsing such values. It is easy enough to split out and parse yourself: ``` hours, minu...
Is "syscall-template.S: No such file or directory" a bug of GDB or My Program
24,433,961
3
2014-06-26T15:02:32Z
24,440,711
7
2014-06-26T21:40:28Z
[ "python", "c", "gdb" ]
I used GDB to debug a combined program of Python and C. The GDB gives me an error when segmentation fault of my program occurs. ``` 81 ../sysdeps/unix/syscall-template.S: No such file or directory. ``` Here is several lines more of the trackback information. ``` 0 0x00007ffff6f2b6d7 in kill () at ../sysdeps/unix/s...
If your program passes invalid arguments to a C library function, it can crash in the C library. And, if you don't have the source for the C library installed, then you will get a message like this from gdb. However, this doesn't mean anything is wrong... it is normal to be missing debuginfo and/or source for one or mo...
How to deal with Pylint's "too-many-instance-attributes" message?
24,434,510
16
2014-06-26T15:27:12Z
24,434,901
25
2014-06-26T15:45:23Z
[ "python", "instance-variables", "pylint", "code-readability", "code-structure" ]
I have just tried to lint some code with Pylint, and the last remaining error is ``` R0902: too-many-instance-attributes (8/7) ``` I understand the rationale behind limiting the number of instance attributes, but seven seems a bit low. I also realise that the linter should not have the last word. However, I would lik...
A linter's job is to make you aware of potential issues with your code, and as you say in your question, it should not have the last word. If you've considered what pylint has to say and decided that for this class, the attributes you have are appropriate (which seems reasonable to me), you can both suppress the error...
How does interval comparison work?
24,436,150
7
2014-06-26T16:53:23Z
24,436,175
12
2014-06-26T16:54:51Z
[ "python", "syntax", "comparison" ]
Somehow, this works: ``` def in_range(min, test, max): return min <= test <= max print in_range(0, 5, 10) # True print in_range(0, 15, 10) # False ``` However, I can't quite figure out the order of operations here. Let's test the `False` case: ``` print 0 <= 15 <= 10 # False print (0 <= 15) <= 10 # True pri...
Unlike most languages, Python supports [chained comparison operators](https://docs.python.org/3/reference/expressions.html#grammar-token-comp_operator) and it evaluates them as they would be evaluated in normal mathematics. This line: ``` return min <= test <= max ``` is evaluated by Python like this: ``` return (m...
Unexplainable Flask 404 errors
24,437,248
8
2014-06-26T18:02:10Z
31,945,365
10
2015-08-11T15:01:53Z
[ "python", "flask" ]
I have a website that uses Flask. It used to work well, but since recently, every request returns a 404, and it seems it can't find the right endpoints. However: * Locally, the site still works, only on my VPS it shows this strange behaviour. * `url_for` works and `app.view_functions` contains all the routes as well. ...
I had the same issue. I had it because I changed the parameters `SERVER_NAME`of the config to a name which is not the name of the server. You can solve this bug by removing `SERVER_NAME` from the config if you have it.
Python: Why call '__init__' instead of className()?
24,438,025
4
2014-06-26T18:51:49Z
24,438,048
8
2014-06-26T18:53:09Z
[ "python", "constructor", "initialization" ]
Since calling `className()` will execute the code in `__init__(args)`, why in the code below, is someone explicitly calling `__init__`? ``` class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) ``` Is there any difference in the actual code that is executed between the two method...
`className()` does more than call `__init__`. It also calls `__new__`, which creates a new instance of the class. So calling `Frame()` would not do the superclass initialization on the same `self` object; it would create a new object and initialize that. You call `__init__` when you want to run *just* `__init__` on a ...
Intellij IDEA not display Django in the facet list
24,438,244
5
2014-06-26T19:05:43Z
27,995,660
15
2015-01-17T02:43:01Z
[ "python", "django", "intellij-idea" ]
I am using Fedora 20 with OpenJDK-1.7.0.60 setup. I can setup and run Intellij IDEA 13.1 successfully, then setup Python plugin. Well, when I tried generate a project from Intellij with Python module selectly, I could not find Django facet in the technology part. I searched web but could not find any solution, even any...
Your symptoms are similar to a problem I've also had, which was solved by editing the IDEA module file, which will appear as `{your_project_name}.iml`. This file is either in the root of your project (or module) or in the `.idea` directory of the project. You'll likely see that the module element's type attribute is `...
Python debugging: get filename and line number from which a function is called?
24,438,976
8
2014-06-26T19:47:30Z
24,439,444
14
2014-06-26T20:16:05Z
[ "python", "debugging", "line-numbers", "inspect" ]
I'm currently building quite a complex system in Python, and when I'm debugging I often put simple print statements in several scripts. To keep an overview I often also want to print out the file name and line number where the print statement is located. I can of course do that manually, or with something like this: `...
The function [`inspect.stack()`](https://docs.python.org/2/library/inspect.html#inspect.stack) returns a list of [frame records](https://docs.python.org/2/library/inspect.html#the-interpreter-stack), starting with the caller and moving out, which you can use to get the information you want: ``` from inspect import get...
TypeError: expected a character buffer object
24,439,988
9
2014-06-26T20:50:23Z
24,440,021
19
2014-06-26T20:52:06Z
[ "python" ]
I am running into the following error while writing the value into a file. Can you please help me figure out what is the issue here and how to fix it? ``` row = 649 with open(r'\\loc\dev\Build_ver\build_ver.txt','r+') as f: f.write(row) print row ``` Error: ``` Traceback (most recent call last): File "latest_r...
Assuming you just want to write the string `'649'` to the file, change `row` to `'649'` or issue `f.write(str(row))`.
How can I get affected row count from psycopg2 connection.commit()?
24,441,132
10
2014-06-26T22:17:43Z
24,441,715
15
2014-06-26T23:18:45Z
[ "python", "psycopg2" ]
Currently, I have the following method to execute INSERT/UPDATE/DELETE statements using `psycopg2` in `Python`: ``` def exec_statement(_cxn, _stmt): try: db_crsr = _cxn.cursor() db_crsr.execute(_stmt) _cxn.commit() db_crsr.close() return True except: return False ``` But what I would really l...
`commit()` can't be used to get the row count, but you can use the *cursor* to get that information after each `execute` call. You can use its `rowcount` attribute to get the number of rows affected for *SELECT*, *INSERT*, *UPDATE* and *DELETE*. i.e. ``` db_crsr = _cxn.cursor() db_crsr.execute(_stmt) row...
Trouble embedding bokeh plot
24,444,018
3
2014-06-27T04:35:09Z
24,444,217
8
2014-06-27T04:55:41Z
[ "python", "flask", "anaconda", "bokeh" ]
In working on a flask website that will allow users to plot certain data, I decided to use bokeh instead of matplotlib as it seems to be built for embedding, with the ability to use dynamic data. I've scoured online examples, and the bokeh documentation. In the examples I see the command 'create\_html\_snippet', which ...
`create_html_snippet` is indeed deprecated. We will be releasing Bokeh 0.5 on July 7, there is a much improved, simplified, and documented `bokeh.embed` module now that supersedes that function. If you'd like to try it out sooner, there are dev builds available now, the instructions are on the mailing list: <https://g...
Python string splitlines() removes certain Unicode control characters
24,453,713
5
2014-06-27T14:00:41Z
24,453,934
8
2014-06-27T14:10:51Z
[ "python", "unicode" ]
I noticed that Python's standard string method splitlines() actually removes some crucial Unicode control characters as well. Example ``` >>> s1 = u'asdf \n fdsa \x1d asdf' >>> s1.splitlines() [u'asdf ', u' fdsa ', u' asdf'] ``` Notice how the "\x1d" character quietly disappears. It doesn't happen if the string s1 i...
This is indeed under-documented; I had to dig through the source code somewhat to find it. The [`unicodetype_db.h` file](http://hg.python.org/cpython/file/94f7cdab9f71/Objects/unicodetype_db.h#l3316) defines linebreaks as: ``` case 0x000A: case 0x000B: case 0x000C: case 0x000D: case 0x001C: case 0x001D: case 0x001E: ...
lxml installation error ubuntu 14.04 (internal compiler error)
24,455,238
48
2014-06-27T15:14:22Z
25,239,912
15
2014-08-11T09:24:56Z
[ "python", "install", "pip", "lxml", "ubuntu-14.04" ]
I am having problems with installing `lxml`. I have tried the solutions of the relative questions in this site and other sites but could not fix the problem. Need some suggestions/solution on this. I am providing the full log after executing `pip install lxml`, ``` Downloading/unpacking lxml Downloading lxml-3.3.5....
Refer to <http://stackoverflow.com/a/6504860/261718> Go install some dev packages before *pip install lxml* ``` apt-get install libxml2-dev libxslt1-dev python-dev ```