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 |
|---|---|---|---|---|---|---|---|---|---|
Django using locals() | 25,063,328 | 2 | 2014-07-31T15:43:29Z | 25,063,474 | 7 | 2014-07-31T15:49:09Z | [
"python",
"django"
] | I am beginner in web development and after two tutorials I am on my third now. I noticed that this one uses a locals() function instead of the context\_dictionary that I am used to see.From what I see on the internet locals() is pretty useful. So are there any special cases where this is not true and its better to use ... | Using `locals()` in that tutorial is just for convenience, since all the data he needs to pass to the template is stored in local variables. `locals()` returns a dictionary holding the local variables names (as keys) and the current values (as values).
You need to use an explicit context\_dictionary, instead of passin... |
Python - Running Autobahn|Python asyncio websocket server in a separate subprocess or thread | 25,063,403 | 13 | 2014-07-31T15:46:30Z | 25,066,490 | 18 | 2014-07-31T18:36:50Z | [
"python",
"tkinter",
"autobahn",
"python-asyncio"
] | I have a tkinter based GUI program running in Python 3.4.1. I have several threads running in the program to get JSON data from various urls. I am wanting to add some WebSocket functionality to be able to allow program to act as a server and allow several clients to connect to it over a WebSocket and exchange other JSO... | First, you're getting `AssertionError: There is no current event loop in thread 'Thread-1'.` because `asyncio` requires each thread in your program to have its own event loop, but it will only automatically create an event loop for you in the main thread. So if you call `asyncio.get_event_loop` once in the main thread ... |
Sending multiple .CSV files to .ZIP without storing to disk in Python | 25,064,347 | 7 | 2014-07-31T16:31:32Z | 25,194,850 | 9 | 2014-08-08T01:39:10Z | [
"python",
"django",
"csv",
"zipfile"
] | I'm working on a reporting application for my Django powered website. I want to run several reports and have each report generate a .csv file in memory that can be downloaded in batch as a .zip. I would like to do this without storing any files to disk. So far, to generate a single .csv file, I am following the common ... | [zipfile](https://docs.python.org/2/library/zipfile.html) is a standard library module that does exactly what you're looking for. For your use-case, the meat and potatoes is a method called "writestr" that takes a name of a file and the data contained within it that you'd like to zip.
In the code below, I've used a se... |
BLAS/LAPACK not installed: How to install it? | 25,065,113 | 6 | 2014-07-31T17:15:26Z | 25,071,095 | 12 | 2014-08-01T00:29:03Z | [
"python",
"c++",
"bash",
"ubuntu"
] | I am trying to run `pip install tsne`for python2.7 and I keep on getting the same error. I followed the instructions on <http://bickson.blogspot.com/2011/02/installing-blaslapackitpp-on-amaon-ec2.html> and installed LAPACK/BLAS which I thought should have solved the problem. Nothing helped. What am I doing wrong? I am ... | Ubuntu doesn't have a binary distribution of either cblas or openblas, which are required for tsne according to their [github](https://github.com/danielfrg/tsne). However, ATLAS, which is available on Ubuntu, comes with precompiled cblas.
In Ubuntu, that should work with "apt-get install libatlas-base-dev".
<https://l... |
request.args.get('key') gives NULL - Flask | 25,065,900 | 6 | 2014-07-31T18:01:48Z | 25,070,256 | 11 | 2014-07-31T22:55:29Z | [
"python",
"flask"
] | I am trying to pass the variable 'email' from the 'signup' method in my view to the 'character' method. However,
```
request.args.get('email')
```
is saving NULL into the database. I cannot figure out why.
Here is what shows up after passing the 'email' variable to '/character':
```
http://127.0.0.1:5000/character?... | When you submit your signup form, you're using POST. Because you're using POST, your form values are added to `request.form`, not `request.args`.
Your email address will be in:
```
request.form.get('email')
```
If you were hitting the URL `/[email protected]`, and you weren't rendering a template i... |
bbox_to_anchor and loc in matplotlib | 25,068,384 | 9 | 2014-07-31T20:32:48Z | 25,069,717 | 12 | 2014-07-31T22:05:19Z | [
"python",
"matplotlib"
] | I have come across matplotlib code which customizes legend loccation using keywords "loc" and "bbox\_to\_anchor". For example :
fig.legend([line1, line2], ['series1', 'series2'], bbox\_to\_anchor=[0.5, 0.5],
loc='center', ncol=2)
I have seen variation of above where "bbox\_to\_anchor" is used after "loc".
I understa... | When `bbox_to_anchor` and `loc` are used together, the `loc` argument will inform matplotlib which part of the bounding box of the legend should be placed at the arguments of `bbox_to_anchor`. For example (I've simplified the command a bit), the three options below will produce different locations for your legend,
```... |
Python port forwarding | 25,069,005 | 4 | 2014-07-31T21:11:43Z | 25,069,340 | 8 | 2014-07-31T21:36:12Z | [
"python",
"port",
"forwarding"
] | I'm developing a client-server game in python and I want to know more about port forwarding.
What I'm doing for instance is going to my router `(192.168.0.1)` and configure it to allow request for my real IP-adress to be redirected to my local adress `192.168.0.X.` It works really well. But I'm wondering if I can do i... | There are different solutions here, but most are not trivial, and you'll have to do some reading, and you'll need some kind of fallback.
---
[UPnP/IGD](https://en.wikipedia.org/wiki/Internet_Gateway_Device_Protocol) is the simplest. If your router supports it, and is configured to allow it, and you know how to write ... |
Python: why does peek(1) return 8K bytes instead of 1 byte? | 25,070,952 | 4 | 2014-08-01T00:12:31Z | 25,070,988 | 8 | 2014-08-01T00:16:29Z | [
"python",
"file-io",
"peek"
] | I'm using Python 3, and the peek() method for buffered file I/O doesn't seem to work as documented. For example, the following code illustrates the problem -- it prints **8192** as the length of the byte string returned by `f.peek(1)`:
```
jpg_file = 'DRM_1851.JPG'
with open(jpg_file, 'rb') as f:
next_byte = f.pee... | From the [Python docs](https://docs.python.org/3/library/io.html#io.BufferedReader.peek):
> **peek([size])**
>
> Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. **The number of bytes returned may be less or more than requested.**
Emph... |
Box Plot Trellis | 25,072,059 | 5 | 2014-08-01T02:38:21Z | 25,072,227 | 9 | 2014-08-01T03:01:16Z | [
"python",
"matplotlib",
"plot",
"pandas",
"boxplot"
] | Consider I have some data.
Lets say it is weather data, of rainfall and temperature for each month.
For this example, I will randomly generate is like so:
```
def rand_weather(n):
month = n%12+1
temp_ind = np.random.randint(0,4)
temp = ["freezing", "cold", "moderate", "hot", "extreme"][temp_ind]
rain =... | You could use [seaborn](http://stanford.edu/~mwaskom/software/seaborn/), specifically the `factorplot` function:
```
import seaborn as sns
sns.set_style("whitegrid")
sns.factorplot("month", "rainfall", row="temp", data=rain_record,
size=2, aspect=5, kind="box", palette="PuBuGn_d")
sns.despine(left=True... |
why does Python lint want me to use different local variable name, than a global, for the same purpose | 25,072,126 | 6 | 2014-08-01T02:48:25Z | 25,072,186 | 17 | 2014-08-01T02:56:28Z | [
"python",
"pylint"
] | Given Python code such as
```
def func():
for i in range(10):
pass
for i in range(10):
pass
```
pylint complains
```
Redefining name 'i' from outer scope
```
What is the Pythonic way to write the above? Use a different variable locally, say `j`?
But why, when the variable means exactly the same in... | You can avoid global variable conflict by not having any global variables:
```
def func():
for i in range(10):
pass
def _init_func():
for i in range(10):
pass
_init_func()
```
Any code that needs to run at module-init time can be put into a single function. This leaves, as the only executa... |
python 3 print generator | 25,073,064 | 3 | 2014-08-01T04:53:43Z | 25,073,099 | 9 | 2014-08-01T04:57:42Z | [
"python",
"printing",
"generator"
] | There is a problem when i deal with print() function(Python 3).
When I'm looking for sum of a series I may use the following code pattern:
```
>>> sum(i for i in range(101))
```
But when I tend to check the series that I had made: (I choose print() and assume it will print out line by line)
```
>>> print(i for i in... | `sum` takes an iterable of things to add up, while `print` takes separate arguments to print. If you want to feed all the generator's items to `print` separately, use `*` notation:
```
print(*(i for i in range(1, 101)))
```
You don't actually need the generator in either case, though:
```
sum(range(1, 101))
print(*r... |
How to Mask an image using Numpy/OpenCV? | 25,074,488 | 5 | 2014-08-01T06:51:21Z | 25,114,860 | 7 | 2014-08-04T08:50:15Z | [
"python",
"opencv",
"numpy"
] | I have an image I load with:
```
im = cv2.imread(filename)
```
I want to keep data that is in the center of the image. I created a circle as a mask of the area I want to keep.
I created the circle with:
```
height,width,depth = im.shape
circle = np.zeros((height,width))
cv2.circle(circle,(width/2,height/2),280,1,th... | Use `cv2.bitwise_and` and pass the circle as mask.
```
im = cv2.imread(filename)
height,width,depth = im.shape
circle_img = np.zeros((height,width), np.uint8)
cv2.circle(circle_img,(width/2,height/2),280,1,thickness=-1)
masked_data = cv2.bitwise_and(im, im, mask=circle_img)
cv2.imshow("masked", masked_data)
cv2.wait... |
Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3 | 25,076,883 | 7 | 2014-08-01T09:20:17Z | 25,197,877 | 9 | 2014-08-08T07:13:25Z | [
"python",
"python-3.x"
] | First of all, let me say that I read the many threads with similar topics on creating dynamically named variables, but they mostly relate to Python 2 or they assume you are working with classes. And yes, I read [Behaviour of exec function in Python 2 and Python 3](http://stackoverflow.com/questions/15086040/behaviour-o... | When you're not sure why something works the way it does in Python, it often can help to put the behavior that you're confused by in a function and then disassemble it from the Python bytecode with the `dis` module.
Lets start with a simpler version of your code:
```
def foo():
exec("K = 89")
print(K)
```
If... |
Python: "subprocess.Popen" check for success and errors | 25,079,140 | 6 | 2014-08-01T11:20:50Z | 25,079,374 | 10 | 2014-08-01T11:36:27Z | [
"python",
"python-3.x",
"subprocess",
"stdout",
"stderr"
] | I want to check if a subprocess has finished execution successfully or failed. Currently I have come up with a solution but I am not sure if it is correct and reliable. Is it guaranteed that every process outputs its errors only to stderr respectfully to stdout:
Note: I am not interested in just redirecting/printing ou... | Do you need to do anything with the output of the process?
The `check_call` method might be useful here. See the python docs here: <https://docs.python.org/2/library/subprocess.html#subprocess.check_call>
You can then use this as follows:
```
try:
subprocess.check_call(command)
except subprocess.CalledProcessError... |
How to test if an object is a function vs. an unbound method? | 25,083,220 | 3 | 2014-08-01T15:07:18Z | 25,083,260 | 8 | 2014-08-01T15:09:36Z | [
"python",
"introspection"
] | ```
def is_unbound_method(func):
pass
def foo(): pass
class MyClass(object):
def bar(self): pass
```
What can I put in the body of `is_unbound_method` so that
```
is_unbound_method(foo) == False
is_unbound_method(MyClass().bar) == False
is_unbound_method(MyClass.bar) == True
```
?? | An unbound method has `__self__` set to `None`:
```
def is_unbound_method(func):
return getattr(func, '__self__', 'sentinel') is None
```
Demo:
```
>>> foo.__self__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__self__'
>>> is_unboun... |
What do the zeros in python function bytecode mean? | 25,083,861 | 7 | 2014-08-01T15:40:20Z | 25,084,105 | 9 | 2014-08-01T15:54:50Z | [
"python",
"bytecode"
] | I'm trying to teach myself about how python bytecode works so I can do some stuff with manipulating functions' code (just for fun, not for real usage) so I started with some simple examples, such as:
```
def f(x):
return x + 3/x
```
The bytecode is:
```
(124, 0, 0, 100, 1, 0, 124, 0, 0, 20, 23, 83)
```
So it ma... | A large number of bytecodes take arguments (any bytecode with a codepoint at or over [`dis.HAVE_ARGUMENT`](https://docs.python.org/3/library/dis.html#opcode-HAVE_ARGUMENT). Those that do have a 2-byte argument, in little-endian order.
You can see the definition for what bytecodes Python currently uses and what they me... |
How to format text with style | 25,087,291 | 3 | 2014-08-01T19:24:06Z | 25,087,349 | 8 | 2014-08-01T19:27:59Z | [
"python"
] | A code below:
```
info={'Resolution':'640x360', 'DisplayResolution': '640x360', 'Display Channels':'R,G,B,A'}
for key in info:
print (key + str(info[key].rjust(45,'.')))
```
produces a following output:
```
Resolution......................................640x360
DisplayResolution.................................... | Place the periods as a filler for the key, not the value:
```
info = {'Resolution':'640x360', 'DisplayResolution': '640x360',
'Display Channels':'R,G,B,A'}
for key, value in info.items():
print('{k:.<55}{v}'.format(k=key, v=value))
```
yields
```
Resolution.............................................640x3... |
Are python imports guaranteed to be in sequence order? Is relying on this a good idea? | 25,088,217 | 3 | 2014-08-01T20:32:46Z | 25,088,294 | 10 | 2014-08-01T20:38:21Z | [
"python",
"import"
] | If I have the following Python code:
```
import module1
import module2
```
* Does Python guarantee that `module1` is loaded before `module2`, and that they are not, for example, loaded in parallel? This works in CPython, but I would like the code to be portable to other flavours too, including ones that allow multith... | 1. Yes, the import order is guaranteed.
2. No, it's not a good idea. It's very easy to break this by importing another file before importing `module1` that imports `module2`. If you want `module1` to run before `module2`, It's much better to explicitly import `module1` at the top of `module2`. |
python requests get cookies | 25,091,976 | 7 | 2014-08-02T05:27:51Z | 25,092,059 | 14 | 2014-08-02T05:42:14Z | [
"python",
"python-requests"
] | ```
x = requests.post(url, data=data)
print x.cookies
```
I used the requests library to get some cookies from a website, but I can only get the cookies
from the Response, how to get the cookies from the Request? Thanks! | Alternatively, you can use [`requests.Session`](http://docs.python-requests.org/en/latest/user/advanced/#session-objects) and observe `cookies` before and after a request:
```
import requests
session = requests.Session()
session.cookies.get_dict()
{}
response = session.get('http://google.com')
session.cookies.get_dict... |
How to stop PyCharm from populating docstrings? | 25,098,863 | 5 | 2014-08-02T19:58:09Z | 25,101,737 | 8 | 2014-08-03T04:48:29Z | [
"python",
"intellij-idea",
"pycharm",
"docstring"
] | If I add a docstring to a method using the triple-quote, as soon as I type a space after the triple-quote, PyCharm will populate the docstring with the parameters the method takes, and a return value, like so:
```
def fill_blank(self, direction):
"""
:param direction:
:return:
"""
```
I've searched ... | You need to set the docstrings format to "Plain". It defaults to reStructuredText, which is giving you those hints.
The setting is found under Python Integrated Tools in your project settings.
1. File > Settings
2. Python Integrated Tools
3. Docstring format
 |
Python; Convert Scientific Notation to Float | 25,099,626 | 5 | 2014-08-02T21:35:44Z | 25,099,656 | 15 | 2014-08-02T21:39:48Z | [
"python",
"decimal",
"notation"
] | Encountered a problem whereby my JSON data gets printed as a scientific notation instead of a float.
```
import urllib2
import json
import sys
url = 'https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-quid'
json_obj = urllib2.urlopen(url)
QUID_data = json.load(json_obj)
QUID_MarketName_Trex = QUID_data[... | You are looking at the *default `str()` formatting* of floating point numbers, where scientific notation is used for sufficiently small or large numbers.
You don't need to convert this, the *value itself* is a proper float. If you need to display this in a different format, [format it *explicitly*](https://docs.python... |
Docker interactive mode and executing script | 25,101,596 | 9 | 2014-08-03T04:22:29Z | 34,023,343 | 7 | 2015-12-01T14:55:39Z | [
"python",
"containers",
"docker"
] | I have a Python script in my docker container that needs to be executed, but I also need to have interactive access to the container once it has been created ( with /bin/bash ).
I would like to be able to create my container, have my script executed and be inside the container to see the changes/results that have occu... | My way of doing it is slightly different with some advantages.
It is actually multi-session server rather than script but could be even more usable in some scenarios:
```
# Just create interactive container. No start but named for future reference.
# Use your own image.
docker create -it --name new-container <image>
... |
Chaining "is" operators | 25,103,085 | 4 | 2014-08-03T08:53:15Z | 25,103,148 | 9 | 2014-08-03T09:01:25Z | [
"python",
"comparison",
"operator-keyword",
"comparison-operators"
] | Does python support chaining `is` operators, such as the following?
```
a = None
b = None
a is b is None
```
This outputs `True`, some doc references would be nice. | Yes. Any operators classified as comparisons can be chained. From the [language reference](https://docs.python.org/2/reference/expressions.html#not-in):
> Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., *opN*
> are comparison operators, then `a op1 b op2 c ... y opN z` is equivalent
> ... |
pypi see older versions of package | 25,104,154 | 25 | 2014-08-03T11:21:39Z | 29,358,070 | 39 | 2015-03-30T23:25:50Z | [
"python",
"django",
"pypi"
] | This is the package I'm interested in :
<https://pypi.python.org/pypi/django-filebrowser-no-grappelli/>
However the latest version no longer supports Django 1.3. I need to find a version that does.
How do I see list of older versions ? | It's perhaps a little inelegant, but it appears that you can go to the URL
```
https://pypi.python.org/simple/<package>
```
And you will get a bunch of links to tarballs for the package.
Ex:
```
https://pypi.python.org/simple/django-filebrowser-no-grappelli/
``` |
Python Quicksort Runtime Error: Maximum Recursion Depth Exceeded in cmp | 25,105,541 | 5 | 2014-08-03T14:14:59Z | 25,105,705 | 9 | 2014-08-03T14:33:59Z | [
"python",
"recursion",
"runtime-error",
"quicksort"
] | I'm writing a program that will read a text file containing 5,163 names. (text file can be seen [here](http://pastebin.com/BAKTJKy6))
Then I want to store the names into a list called 'names', afterwards, I sort the list based on how many letters the name contains, shorter names are at the start of the list and the lo... | You have simply hit the recursion limits. Your list of names is too large for Python's limited recursion capabilities. Your Quicksort works just fine otherwise.
You *could* raise the recursion limit by setting the limit higher with [`sys.setrecursionlimit()`](https://docs.python.org/2/library/sys.html#sys.setrecursion... |
Compiling Cx-Freeze under Ubuntu | 25,107,697 | 13 | 2014-08-03T18:19:01Z | 25,119,820 | 14 | 2014-08-04T13:27:40Z | [
"python",
"linux",
"ubuntu",
"executable",
"cx-freeze"
] | For the entire day I have been attempting to compile cx-Freeze under Ubuntu 14.04 and had no luck. So I gave up and decided to ask experts here.
**What I have**
1. Ubuntu 14.04
2. Python 3.4
3. python-dev, python3-dev, python3.4-dev installed (I know this common issue)
4. Sources of cx-Freeze 4.3.3
I tried two ways:... | In **setup.py** string
```
if not vars.get("Py_ENABLE_SHARED", 0):
```
replace by
```
if True:
```
---
Thanks to **Thomas K** |
How should I make a big string of floats? | 25,108,932 | 2 | 2014-08-03T20:46:02Z | 25,108,946 | 7 | 2014-08-03T20:47:19Z | [
"python",
"concatenation"
] | I'm creating an arff file with a lot of numeric data. Now since my feature vector is quite large, I ended up with code like this
```
with(file,'w') as myfile:
s = number + ","
s += number + ","
s += number + ","
s += number + ","
...
myfile.write(s)
```
Since I'm quite new to Python I obviousl... | Don't write CSV rows by hand. Use the [`csv` module](https://docs.python.org/2/library/csv.html):
```
with(file, 'wb') as myfile:
writer = csv.writer(myfile)
writer.writerow([number1, number2, number3])
```
Each element in the list is converted to a string for you.
When using `numpy` arrays, you can use [`nu... |
Django makemigrations works, migrate fails with "django.db.utils.IntegrityError: NOT NULL constraint failed" | 25,109,075 | 6 | 2014-08-03T21:02:52Z | 25,109,076 | 13 | 2014-08-03T21:02:52Z | [
"python",
"django",
"sqlite"
] | I'm stuck. Django 1.7, SQLite3.
I've changed my model to add the `thumbnail` column, as in [this tutorial](https://www.youtube.com/watch?v=b43JIn-OGZU). It was this:
```
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date =... | My app name (as created with `python manage.py startapp`) is called `articles`. Here is the new `articles\migrations` folder, after getting the null-constraint error multiple times:
```
__init__.py
0001_initial.py
0002_auto_20140803_1540.py
0003_auto_20140803_1542.py
0004_auto_20140803_1450.py
0005_auto_20140803_1552.... |
How to properly stop phantomjs execution | 25,110,624 | 21 | 2014-08-04T01:20:39Z | 25,117,532 | 9 | 2014-08-04T11:23:50Z | [
"python",
"osx",
"selenium",
"selenium-webdriver",
"phantomjs"
] | I initiated and close `phantomjs` in Python with the following
```
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(url)
html_doc = driver.page_source
driver.close()
```
yet after the script ends execution I still find an instance of `phantomjs` in my Mac Activity Monitor. And actually eve... | The `.close()` method is not guaranteed to release all resources associated with a driver instance. Note that these resources include, but may not be limited to, the driver executable (PhantomJS, in this case). The `.quit()` method is designed to free all resources of a driver, including exiting the executable process. |
How to properly stop phantomjs execution | 25,110,624 | 21 | 2014-08-04T01:20:39Z | 27,704,599 | 12 | 2014-12-30T11:26:52Z | [
"python",
"osx",
"selenium",
"selenium-webdriver",
"phantomjs"
] | I initiated and close `phantomjs` in Python with the following
```
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(url)
html_doc = driver.page_source
driver.close()
```
yet after the script ends execution I still find an instance of `phantomjs` in my Mac Activity Monitor. And actually eve... | I've seen several people struggle with the same issue, but for me, the simplest workaround/hack was to execute the following from the command line through Python AFTER you have invoked `driver.close()` or `driver.quit()`:
```
pgrep phantomjs | xargs kill
```
Please not that this will obviously cause trouble if you ha... |
How to properly stop phantomjs execution | 25,110,624 | 21 | 2014-08-04T01:20:39Z | 38,493,285 | 7 | 2016-07-21T01:10:56Z | [
"python",
"osx",
"selenium",
"selenium-webdriver",
"phantomjs"
] | I initiated and close `phantomjs` in Python with the following
```
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(url)
html_doc = driver.page_source
driver.close()
```
yet after the script ends execution I still find an instance of `phantomjs` in my Mac Activity Monitor. And actually eve... | As of July 2016, `driver.close()` and `driver.quit()` weren't sufficient for me. That killed the `node` process but not the `phantomjs` child process it spawned.
Following the discussion on [this GitHub issue](https://github.com/seleniumhq/selenium/issues/767), the single solution that worked for me was to run:
```
i... |
Python Select Specific Row and Column | 25,110,987 | 2 | 2014-08-04T02:22:59Z | 25,111,028 | 7 | 2014-08-04T02:29:50Z | [
"python",
"csv",
"import-from-csv"
] | I wish to select a specific row and column from a CSV file in python. If the value is blank, I want to perform one action, and if the value is not blank, I want to perform another action.
I think the code should look something like this:
```
inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for row in re... | When you think CSV, think pandas.
```
import pandas as pd
df = pd.read_csv('path/to/csv')
if df.iloc[5, 6]:
# do stuff
else
# do some other stuff
``` |
Does Python's tarfile.open need close()? | 25,113,191 | 4 | 2014-08-04T06:55:40Z | 25,113,252 | 8 | 2014-08-04T06:59:07Z | [
"python",
"tar",
"tarfile"
] | In the official python documentation of [tarfile](https://docs.python.org/2/library/tarfile.html) I don't see wether a tarfile created with
```
tarfile.open('example.tar', 'r:*')
```
should be closed once you don't need it anymore.
In some other examples (e.g. [here](http://pymotw.com/2/tarfile/)) you often see the... | Yes, a [`TarFile` object](https://docs.python.org/2/library/tarfile.html#tarfile-objects) (what `tarfile.open()` returns) can and should be closed.
You can use the object as a context manager, in a `with` statement, to have it closed automatically:
```
with tarfile.open(name, 'r:*') as f:
# do whatever
return... |
Acces all off diagonal elements of boolean numpy matrix | 25,113,682 | 5 | 2014-08-04T07:29:31Z | 25,114,289 | 7 | 2014-08-04T08:14:01Z | [
"python",
"numpy",
"matrix"
] | Suppose there is a diagonal matrix M:
```
#import numpy as np
M = np.matrix(np.eye(5, dtype=bool))
```
Does anybody know a simple way to access all off diagonal elements, meaning all elements that are `False`? In `R` I can simply do this by executing
```
M[!M]
```
Unfortunately this is not valid in Python. | You need the bitwise not operator:
```
M[~M]
``` |
understanding numpy's dstack function | 25,116,595 | 8 | 2014-08-04T10:25:58Z | 25,117,015 | 15 | 2014-08-04T10:52:42Z | [
"python",
"numpy",
"concatenation",
"multidimensional-array"
] | I have some trouble understanding what numpy's `dstack` function is actually doing. The documentation is rather sparse and just says:
> Stack arrays in sequence depth wise (along third axis).
>
> Takes a sequence of arrays and stack them along the third axis
> to make a single array. Rebuilds arrays divided by `dsplit... | It's easier to understand what `np.vstack`, `np.hstack` and `np.dstack`\* do by looking at the `.shape` attribute of the output array.
Using your two example arrays:
```
print(a.shape, b.shape)
# (3, 2) (3, 2)
```
* [`np.vstack`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html) concatenates alo... |
Python: How to escape 'lambda' | 25,118,520 | 3 | 2014-08-04T12:17:52Z | 25,118,622 | 15 | 2014-08-04T12:23:44Z | [
"python",
"lambda",
"argparse"
] | `lambda` has a keyword function in Python:
```
f = lambda x: x**2 + 2*x - 5
```
What if I want to use it as a variable name? Is there an escape sequence or another way?
You may ask why I don't use another name. This is because I'd like to use [`argparse`](https://docs.python.org/2/library/argparse.html):
```
parser... | You can use dynamic attribute access to access that specific attribute still:
```
print getattr(args, 'lambda')
```
Better still, tell `argparse` to use a different attribute name:
```
parser.add_argument("-l", "--lambda",
help="Defines the quantity called lambda",
type=float, dest='lambda_', metavar='LAMBDA... |
Move column by name to front of table in pandas | 25,122,099 | 7 | 2014-08-04T15:21:31Z | 25,122,293 | 14 | 2014-08-04T15:30:09Z | [
"python",
"pandas",
"move",
"dataframe",
"shift"
] | Here is my df:
```
Net Upper Lower Mid Zsore
Answer option
More than once a day 0% 0.22% -0.12% 2 65
Once a day 0% 0.32% -0.19% 3 45
Several times a week 2% 2.45% 1.10% 4 78... | We can use `ix` to reorder by passing a list:
```
In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[27]:
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.ix[:, cols]
df
Out[28... |
json.dump - UnicodeDecodeError: 'utf8' codec can't decode byte 0xbf in position 0: invalid start byte | 25,122,371 | 8 | 2014-08-04T15:34:17Z | 25,122,834 | 9 | 2014-08-04T16:00:04Z | [
"python",
"json",
"unicode",
"encoding",
"utf-8"
] | I have a dictionary `data` where I have stored:
* `key` - ID of an event
* `value` - the name of this event, where `value` is a UTF-8 string
Now, I want to write down this map into a json file. I tried with this:
```
with open('events_map.json', 'w') as out_file:
json.dump(data, out_file, indent = 4)
```
but th... | The exception is caused by the contents of your `data` dictionary, at least *one* of the keys or values is *not* UTF-8 encoded.
You'll have to replace this value; either by substituting a value that *is* UTF-8 encoded, or by decoding it to a `unicode` object by decoding just that value with whatever encoding is the co... |
After OS python upgrade, virtualenv python failing with "undefined symbol: _PyLong_AsInt¨ error on simple tasks | 25,123,437 | 12 | 2014-08-04T16:36:24Z | 32,873,241 | 12 | 2015-09-30T18:29:27Z | [
"python",
"python-2.7",
"virtualenv"
] | I had a long-working virtualenv based on python-2.7.3. After accepting recommended platform OS (Ubuntu) updates which (among many other changes) brought python up to 2.7.6, the python inside the virtualenv has started erroring on essentially all non-trivial tasks, with stacks ending like:
```
ImportError: /home/myuser... | You can simply do
```
cp /usr/bin/python2 /path/to/my-virtualenv/bin/python2
```
or
```
cp /usr/bin/python3 /path/to/my-virtualenv/bin/python3
``` |
array.shape() giving error tuple not callable | 25,125,168 | 7 | 2014-08-04T18:26:23Z | 25,125,173 | 11 | 2014-08-04T18:26:52Z | [
"python",
"arrays",
"numpy",
"tuples"
] | I have a 2D numpy array called `results`, which contains its own array of data, and I want to go into it and use each list:
```
for r in results:
print "r:"
print r
y_pred = np.array(r)
print y_pred.shape()
```
This is the output I get:
```
r:
[ 25. 25. 25. 25. 25. 25. 26. 26. 26. 26. 26. ... | `shape` is just an attribute, not a method. Just use `y_pred.shape` (no parentheses).
(The error message isn't telling you that `y_pred` is a tuple, it's telling you that `y_pred.shape` is a tuple.) |
How to scrape tables in thousands of PDF files? | 25,125,178 | 7 | 2014-08-04T18:27:09Z | 25,125,537 | 9 | 2014-08-04T18:49:42Z | [
"python",
"node.js",
"parsing",
"pdf",
"scraper"
] | I have about 1'500 PDFs consisting of only 1 page each, and exhibiting the same structure (see <http://files.newsnetz.ch/extern/interactive/downloads/BAG_15m_kzh_2012_de.pdf> for an example).
What I am looking for is a way to iterate over all these files (locally, if possible) and extract the actual contents of the ta... | I didn't know this before, but `less` has this magical ability to read pdf files. I was able to extract the table data from your example pdf with this script:
```
import subprocess
import re
output = subprocess.check_output(["less","BAG_15m_kzh_2012_de.pdf"])
re_data_prefix = re.compile("^[0-9]+[.].*$")
re_data_fiel... |
Django REST Framework: Generics or ModelViewSets? | 25,125,959 | 7 | 2014-08-04T19:19:42Z | 25,126,572 | 11 | 2014-08-04T19:59:45Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I use generics and plain urls for my REST API, but now I stuck with problem: I want custom actions, simple views to make some things with my models, like "run", "publish", etc.
`ViewSet` gives `action` decorator to create custom actions, but only in ViewSets, also, there is stepial routers, which gives us ability to s... | The difference is what methods they offer.
For example:
**GenericViewSet** inherits from GenericAPIView but does not provide any implementations of basic actions. Just only get\_object, get\_queryset.
**ModelViewSet** inherits from GenericAPIView and includes implementations for various actions. In other words you d... |
UnicodeEncodeError: 'charmap' codec can't encode character... problems | 25,127,935 | 2 | 2014-08-04T21:34:10Z | 25,128,392 | 13 | 2014-08-04T22:11:44Z | [
"python",
"json",
"python-3.x",
"unicode"
] | Before anyone gives me crap about this being asked a billion times, please note that I've tried several of the answers in many a thread but none of them seemed to work properly for my problem.
```
import json
def parse(fn):
results = []
with open(fn) as f:
json_obj = json.loads(open(fn).read())
... | Everything is fine up until the point where you try to print the string. To print a string it must first be converted from pure Unicode to the byte sequences supported by your output device. This requires an `encode` to the proper character set, which Python has identified as `cp850` - the Windows Console default.
Sta... |
Pandas: Return Hour from Datetime Column Directly | 25,129,144 | 9 | 2014-08-04T23:38:33Z | 30,717,361 | 12 | 2015-06-08T19:20:23Z | [
"python",
"datetime",
"pandas"
] | Assume I have a DataFrame `sales` of timestamp values:
```
timestamp sales_office
2014-01-01 09:01:00 Cincinnati
2014-01-01 09:11:00 San Francisco
2014-01-01 15:22:00 Chicago
2014-01-01 19:01:00 Chicago
```
I would like to create a new column `time_hour`. I can create it by writing a sho... | For posterity: as of [0.15.0](http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#v0-15-0-october-18-2014), there is a handy [.dt accessor](http://pandas.pydata.org/pandas-docs/dev/basics.html#dt-accessor) you can use to pull such values from a datetime/period series (in the above case, just `sales.timestamp.dt.hour... |
Ansible. override single dictionary key | 25,129,728 | 13 | 2014-08-05T00:52:29Z | 25,131,711 | 7 | 2014-08-05T05:26:55Z | [
"python",
"yaml",
"ansible"
] | I am using ansible to manage configuration as for production, as well as for vagrant box.
I have file with default values: **group\_vars/all**.
```
---
env: prod
wwwuser: www-data
db:
root_pwd: root_pwd
pdo_driver: pdo_mysql
host: localhost
name: test
user: test
pwd: test
charset: utf8
do... | By default, Ansible overrides variables at the first level. If you want to be able to merge dictionaries, you have to change your `ansible.cfg` file and set :
```
hash_behaviour=merge
```
(the default value being `replace`).
Note that the Ansible team [does not recommend this](http://docs.ansible.com/intro_configura... |
How do I make pyCharm stop hiding (unfold) my python imports? | 25,135,328 | 14 | 2014-08-05T09:24:33Z | 25,156,495 | 19 | 2014-08-06T09:15:48Z | [
"python",
"import",
"pycharm",
"code-folding"
] | Every time I open a python module file pyCharm will hide all imports and show
```
import ...
```
within the editor.
I have to manually unfold it to see the imports. Where do I find the setting to undo auto-hiding of import statements? Thanks!
EDIT: Added code-folding to the tags. | As this question may be useful for people who also are not looking for the term "code folding", I'll make my comment an answer.
As extracted from [IntelliJ IDEA 13.1.0 Web Help](http://www.jetbrains.com/idea/webhelp/configuring-autofolding-behavior.html), but also worked on PyCharm CE 3.4.1:
1. Open the IDE Settings ... |
How do I make pyCharm stop hiding (unfold) my python imports? | 25,135,328 | 14 | 2014-08-05T09:24:33Z | 36,444,440 | 8 | 2016-04-06T07:37:06Z | [
"python",
"import",
"pycharm",
"code-folding"
] | Every time I open a python module file pyCharm will hide all imports and show
```
import ...
```
within the editor.
I have to manually unfold it to see the imports. Where do I find the setting to undo auto-hiding of import statements? Thanks!
EDIT: Added code-folding to the tags. | 
Actually in pycharm 2016.1 it's Editor -> General -> Code Folding |
OpenCV:src is not a numerical tuple | 25,137,163 | 3 | 2014-08-05T10:59:35Z | 26,647,829 | 7 | 2014-10-30T08:06:11Z | [
"python",
"opencv",
"numerical"
] | I've written a program about color detection by using python. But always there's an error around the 'Erode' sentence. Here's part of my program. Thank you.
```
# Convert the image to a Numpy array since most cv2 functions
# require Numpy arrays.
frame = np.array(frame, dtype=np.uint8)
threshold = 0.05
#blur the imag... | Try:
```
_,h = cv2.threshold(h, 245, 1, cv2.THRESH_BINARY) #245-255 x>245 y=1
_,s = cv2.threshold(h, 15, 1, cv2.THRESH_BINARY_INV) #1-15,x>15 y=0
```
`cv2.threshold` returns two values:
<http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cv2.threshold>
> cv2.threshold(src, thresh, maxval, ... |
Google App Engine and Cloud SQL: Lost connection to MySQL server at 'reading initial communication packet' | 25,139,344 | 4 | 2014-08-05T12:53:12Z | 25,315,098 | 10 | 2014-08-14T18:27:18Z | [
"python",
"mysql",
"django",
"google-app-engine",
"google-cloud-sql"
] | I have a Django app on Google App Engine app which is connected to a Google Cloud SQL, using the [App Engine authentication](https://developers.google.com/appengine/docs/python/cloud-sql/django).
Most of the time everything works fine, but from time to time the following exception is raised:
```
OperationalError: (20... | I had a similar issue and ended up contacting Google for help. They explained it happens when they need to restart or move an instance. If the client instance restarted or was moved to another host server (for various versions) the IPâs wonât match and throw that error. They mentioned that the servers may restart f... |
How to replace non-alphabetic AND numeric characters in a string in python | 25,140,516 | 2 | 2014-08-05T13:51:34Z | 25,140,603 | 8 | 2014-08-05T13:55:15Z | [
"python",
"regex",
"string"
] | I understand that to replace non-alphanumeric characters in a string a code would be as follows:
```
words = re.sub("[^\w]", " ", str).split()
```
However, `^\w` replaces non-alphanumeric characters. I want to replace both non-alphabetic and numeric chars in a string like:
```
"baa!!!!! baa sheep23? baa baa"
```
a... | Use [`str.translate`](https://docs.python.org/2/library/stdtypes.html#str.translate):
```
>>> from string import punctuation, digits
>>> s = "baa!!!!! baa sheep23? baa baa"
>>> s.translate(None, punctuation+digits)
'baa baa sheep baa baa'
``` |
Python "self" is not defined in function arguments list | 25,143,268 | 2 | 2014-08-05T15:56:31Z | 25,143,317 | 8 | 2014-08-05T15:59:23Z | [
"python",
"self"
] | Is there any way to do the following?
```
def getTables(self, db = self._dbName):
//do stuff with db
return func(db)
```
I get a `"self" is not defined`. I could do this...
```
def getTables(self, db = None):
if db is None:
db = self._db
//do stuff with db
return func(db)
```
... but... | Function signatures are evaluated *when the function is defined*, not when the function is called.
When the function is being defined there are no instances yet, there isn't even a *class* yet.
To be precise: the expressions for a class body are executed before the class object is created. The expressions for functio... |
TFIDF for Large Dataset | 25,145,552 | 9 | 2014-08-05T18:09:09Z | 25,168,689 | 10 | 2014-08-06T19:34:26Z | [
"python",
"lucene",
"nlp",
"scikit-learn",
"tf-idf"
] | I have a corpus which has around 8 million news articles, I need to get the TFIDF representation of them as a sparse matrix. I have been able to do that using scikit-learn for relatively lower number of samples, but I believe it can't be used for such a huge dataset as it loads the input matrix into memory first and th... | gensim has an efficient tf-idf model and does not need to have everything in memory at once.
<http://radimrehurek.com/gensim/intro.html>
Your corpus simply needs to be an iterable, so it does not need to have the whole corpus in memory at a time.
The make\_wiki script (<https://github.com/piskvorky/gensim/blob/devel... |
Extracting just Month and Year from Pandas Datetime column (Python) | 25,146,121 | 27 | 2014-08-05T18:44:30Z | 25,146,337 | 22 | 2014-08-05T18:59:43Z | [
"python",
"pandas"
] | I have a Dataframe, df, with the following column:
```
df['ArrivalDate'] =
...
936 2012-12-31
938 2012-12-29
965 2012-12-31
966 2012-12-31
967 2012-12-31
968 2012-12-31
969 2012-12-31
970 2012-12-29
971 2012-12-31
972 2012-12-29
973 2012-12-29
...
```
The elements of the column are pandas.tslib.... | You can directly access the `year` and `month` attributes, or request a `datetime.datetime`:
```
In [15]: t = pandas.tslib.Timestamp.now()
In [16]: t
Out[16]: Timestamp('2014-08-05 14:49:39.643701', tz=None)
In [17]: t.to_datetime()
Out[17]: datetime.datetime(2014, 8, 5, 14, 49, 39, 643701)
In [18]: t.day
Out[18]: ... |
Extracting just Month and Year from Pandas Datetime column (Python) | 25,146,121 | 27 | 2014-08-05T18:44:30Z | 25,149,272 | 47 | 2014-08-05T22:18:11Z | [
"python",
"pandas"
] | I have a Dataframe, df, with the following column:
```
df['ArrivalDate'] =
...
936 2012-12-31
938 2012-12-29
965 2012-12-31
966 2012-12-31
967 2012-12-31
968 2012-12-31
969 2012-12-31
970 2012-12-29
971 2012-12-31
972 2012-12-29
973 2012-12-29
...
```
The elements of the column are pandas.tslib.... | If you want new columns showing year and month separately you can do this:
```
df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year
df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month
```
or...
```
df['year'] = df['ArrivalDate'].dt.year
df['month'] = df['ArrivalDate'].dt.month
```
Then you can combine them or ... |
How do I extract all the values of a specific key from a list of dictionaries? | 25,148,611 | 5 | 2014-08-05T21:25:44Z | 25,148,642 | 10 | 2014-08-05T21:28:24Z | [
"python",
"list",
"dictionary"
] | I have a list of dictionaries that all have the same structure within the list. For example:
```
test_data = [{'id':1, 'value':'one'}, {'id':2, 'value':'two'}, {'id':3, 'value':'three'}]
```
I want to get each of the `value` items from each dictionary in the list:
```
['one', 'two', 'three']
```
I can of course ite... | If you just need to iterate over the values once, use the generator expression:
```
generator = ( item['value'] for item in test_data )
...
for i in generator:
do_something(i)
```
Another (esoteric) option might be to use `map` with `itemgetter` - it could be slightly faster than the generator expression, or no... |
Python loop index of key, value for-loop when using items() | 25,150,502 | 4 | 2014-08-06T00:30:52Z | 25,150,528 | 14 | 2014-08-06T00:33:43Z | [
"python",
"dictionary"
] | Im looping though a dictionary using
```
for key, value in mydict.items():
```
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
```
for key, value, index in mydict.items():
```
its is because I ... | You can use [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate) function, like this
```
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
```
The `enumerate` function gives the current index of the item and the actual item itself. In this case, the second value is... |
Does Python's 'in' operator for lists have an early-out for successful searches | 25,151,927 | 6 | 2014-08-06T03:49:48Z | 25,152,100 | 14 | 2014-08-06T04:10:13Z | [
"python",
"list",
"search",
"containers",
"python-internals"
] | If i have a list then i look up a element in list by:
```
alist=[ele1, ele2, ele3, ele4,ele5,...]
if ele3 in alist:
print "found"
```
Will in stop a search from alist at ele3 ?
Or it will run though all remaining element to the end.
Thanks in advance! | > Will in stop a search from alist at ele3 ?
Yes, the *in* operator on a list does a linear search with an **early exit** if the target is found. Also, it will by-pass the final comparison if the target object is identical to the object in the list.
Here's some tracer code that proves the result by making the compari... |
Can't pickle <type 'instancemethod'> using python's multiprocessing Pool.apply_async() | 25,156,768 | 6 | 2014-08-06T09:29:51Z | 25,161,919 | 19 | 2014-08-06T13:40:03Z | [
"python",
"multiprocessing",
"pool"
] | I want to run something like this:
```
from multiprocessing import Pool
import time
import random
class Controler(object):
def __init__(self):
nProcess = 10
pages = 10
self.__result = []
self.manageWork(nProcess,pages)
def BarcodeSearcher(x):
return x*x
def resultCollector(s... | This works, using `copy_reg`, as suggested by Alex Martelli in the first link you provided:
```
import copy_reg
import types
import multiprocessing
def _pickle_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_n... |
How to allow anonymous uploads to cloud storage | 25,158,266 | 7 | 2014-08-06T10:40:41Z | 25,169,891 | 7 | 2014-08-06T20:46:41Z | [
"java",
"python",
"google-app-engine",
"google-cloud-storage"
] | I need my users to upload files to my Google Cloud Storage without having to authenticate with Google. These are primarily Windows desktop/laptop users running my application. After reading through the different authentication mechanisms, I see that [resumable uploads](https://developers.google.com/storage/docs/json_ap... | You have three major options:
1. Use a signed URL. Basically, you would provide a server that could dispense "signed URLs" to applications using whatever authentication scheme you like. The application would then contact Google Cloud Storage using its XML API and upload the content using the signed URL. This is the mo... |
Export csv file from scrapy (not via command line) | 25,163,023 | 11 | 2014-08-06T14:28:29Z | 25,165,414 | 12 | 2014-08-06T16:24:21Z | [
"python",
"csv",
"scrapy",
"export-to-csv",
"scrapy-spider"
] | I successfully tried to export my items into a csv file from the command line like:
```
scrapy crawl spiderName -o filename.csv
```
My question is:
What is the easiest solution to do the same in the code? I need this as i extract the filename from another file.
End scenario should be, that i call
```
scrapy cra... | Why not use an item pipeline?
WriteToCsv.py
```
import csv
from YOUR_PROJECT_NAME_HERE import settings
def write_to_csv(item):
writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n')
writer.writerow([item[key] for key in item.keys()])
class WriteToCsv(object):
d... |
Matplotlib chart does not display in PyCharm | 25,163,593 | 8 | 2014-08-06T14:53:00Z | 25,163,682 | 13 | 2014-08-06T14:56:54Z | [
"python",
"matplotlib",
"pycharm"
] | I run the following code in PyCharm 3.4.1, and it highlighted `%matplotlib inline` showing syntax error, and I delete the first line, and run, I expect it will prompt me some charts, but it runs normally with `Process finished with exit code 0`ï¼ and no charts is showing.
My question is:
1. What is `%matplotlib inlin... | The `%` notation is for [magic functions](http://ipython.org/ipython-doc/dev/interactive/tutorial.html#magic-functions). The particular magic function and argument you reference, `%matplotlib inline`, is meant for an [IPython notebook](http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%... |
MongoDB return True if document exists | 25,163,658 | 4 | 2014-08-06T14:55:45Z | 25,164,148 | 12 | 2014-08-06T15:18:20Z | [
"python",
"mongodb",
"pymongo",
"tornado-motor"
] | I want to return true if a userID already exists and false otherwise from my collection.I have this function but it always returns `True`.
```
def alreadyExists(newID):
if db.mycollection.find({'UserIDS': { "$in": newID}}):
return True
else:
return False
```
How could I get this function to on... | `find` doesn't return a boolean value, it returns a [cursor](http://api.mongodb.org/python/current/api/pymongo/cursor.html). To check if that cursor contains any documents, use the cursors count-method.
`if db.mycollection.find({'UserIDS': { "$in": newID}}).count() > 0`.
By the way: is newID an array? When it isn't, ... |
How to take the logarithm with base n in numpy? | 25,169,297 | 9 | 2014-08-06T20:09:39Z | 25,169,298 | 28 | 2014-08-06T20:09:39Z | [
"python",
"math",
"numpy",
"logarithm"
] | From the [numpy documentation on logarithms](http://docs.scipy.org/doc/numpy/reference/routines.math.html#exponents-and-logarithms), I have found functions to take the logarithm with base [*e*](http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html#numpy.log), [2](http://docs.scipy.org/doc/numpy/reference/g... | I would suggest to use the built-in python function [`math.log()`](https://docs.python.org/2/library/math.html#math.log), as numpy has no such built-in logarithmic function:
```
import math
math.log(42**3, 42) #3.0
```
However, for people insisting on using numpy (e.g. when using large arrays), there is always the op... |
Running without Python source files in Python 3.4 | 25,172,773 | 8 | 2014-08-07T01:16:13Z | 25,172,892 | 14 | 2014-08-07T01:33:11Z | [
"python",
"python-3.x",
"pyc"
] | I'm trying to run a Python application without keeping the `.py` source files around, and only relying on the `.pyc` compiled files. However, I am getting import errors when I remove the `.py` source files. This functionality is working in Python 2.7, but not in 3.4 (with the new `__pycache__` structure).
Here's a sam... | According to [the PEP](http://www.python.org/dev/peps/pep-3147/#case-3-pycache-foo-magic-pyc-with-no-source):
> It's possible that the foo.py file somehow got removed, while leaving the cached pyc file still on the file system. If the `__pycache__/foo.<magic>.pyc` file exists, but the foo.py file used to create it doe... |
(tornadio2) failed: Error during WebSocket handshake: Unexpected response code: 403 | 25,177,147 | 5 | 2014-08-07T07:59:42Z | 25,190,280 | 16 | 2014-08-07T19:07:18Z | [
"python",
"sockets",
"socket.io",
"tornado"
] | when I run my code on my pc and try to connect socket with my index.html on localhost no problem but when I try to run my code on server and try to connect socket with index.html(it locate on my pc) I get :
```
Router <tornadio2.session.ConnectionInfo object at 0x7f7bfc5fac10>
INFO:tornado.access:200 GET /socket.io/1/... | The html must be loaded from the same server as the websocket unless you override check\_origin to allow cross-origin access: <http://www.tornadoweb.org/en/stable/websocket.html#tornado.websocket.WebSocketHandler.check_origin> |
How to do query with `WHERE value IN list` in the Python Peewee ORM? | 25,179,128 | 6 | 2014-08-07T09:38:51Z | 25,179,183 | 12 | 2014-08-07T09:41:32Z | [
"python",
"orm",
"flask",
"peewee"
] | I'm using the (awesome) Python Peewee ORM for my Flask project, but I now got stuck trying to do a query with a `where value in ['a', 'b', 'c']`. I tried doing it as follows:
```
MyModel.select().where(MyModel.sell_currency in ['BTC', 'LTC'])
```
But unfortunately it returns all records in the DB. Any ideas how I cou... | Have you read the [docs](http://peewee.readthedocs.org/en/latest/peewee/querying.html#column-lookups)?
`MyModel.select().where(MyModel.sell_currency << ['BTC', 'LTC'])` |
Running python script with arguments in microsoft visual studio | 25,179,304 | 5 | 2014-08-07T09:48:16Z | 25,180,719 | 7 | 2014-08-07T10:56:15Z | [
"python",
"visual-studio-2013"
] | I am new to python and work with Microsoft Visual Studio
I have to run this(but it says need more than 1 value):
```
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variab... | You can use the [Python Tools for Visual Studio](http://pytools.codeplex.com/) plugin to configure the python interpreter. Create a new python project and then go to Project Properties | Debug and enter your arguments. You don't need to type `python` or your script name, only the parameters. Specify the script in Gener... |
Using Python pudb debugger with pytest | 25,182,812 | 6 | 2014-08-07T12:39:58Z | 25,183,130 | 7 | 2014-08-07T12:56:07Z | [
"python",
"py.test",
"pudb"
] | Before my testing library of choice was *unittest*. It was working with my favourite debugger - **Pudb**. Not Pdb!!!
To use *Pudb* with *unittest*, I paste `import pudb;pudb.set_trace()` between the lines of code.
I then executed `python -m unittest my_file_test`, where *my\_file\_test* is module representation of *my... | Simply by adding *-s* flag will not replace stdin and stdout and debugging will be accessible, i.e. `py.test -s my_file_test.py` will do the trick.
In documentation provided by ambi it is also said that previously using explicitly *-s* was required for regular *pdb* too, now *-s* flag is implicitly used with *--pdb* f... |
Pylint invalid constant name | 25,184,097 | 23 | 2014-08-07T13:39:49Z | 25,184,336 | 36 | 2014-08-07T13:50:59Z | [
"python",
"coding-style",
"pylint"
] | I'm receiving a Pylint error regarding my constant: `MIN_SOIL_PARTICLE_DENS` (invalid name).
Any ideas why this constant is wrong? Here's my full function:
```
def bulk_density(clay, sand, organic_matter):
MIN_SOIL_PARTICLE_DENS = 2.65
x1 = (0.078 + 0.278 * sand + 0.034 * clay + 0.022 * organic_matter - 0.018
... | When checking names, Pylint differenciates between constants, variables, classes etc. Any name that is not inside a function/class will be considered a constant, anything else is a variable.
See <http://docs.pylint.org/features.html#basic-checker>
> variable-rgx:
> `[a-z_][a-z0-9_]{2,30}$`
>
> const-rgx:
> `(([A-... |
Can't find "six", but it's installed | 25,185,300 | 6 | 2014-08-07T14:36:28Z | 25,200,568 | 13 | 2014-08-08T09:47:29Z | [
"python",
"centos",
"six-python"
] | I have `six` installed (even reinstalled it).
```
$ pip show six
---
Name: six
Version: 1.7.3
Location: /usr/lib/python2.6/site-packages
Requires:
```
But when I try to run `csvcut`, it can't find it.
```
$ csvcut -n monster.csv
Traceback (most recent call last):
File "/usr/bin/csvcut", line 5, in <module>
fro... | Uninstalling and reinstalling `six` using pip *didn't* work
```
sudo pip uninstall six
sudo pip install six
```
However, I was able to solve the problem using `easy_install`:
```
easy_install --upgrade six
``` |
Unable to retrieve gmail messages from any folder other than inbox (Python3 issue) | 25,186,394 | 5 | 2014-08-07T15:27:45Z | 25,961,570 | 12 | 2014-09-21T16:54:11Z | [
"python",
"email",
"python-3.x",
"gmail",
"imaplib"
] | **Update:** my code works under python 2.6.5 but not python 3 (I'm using 3.4.1).
I'm unable to search for messages in the "All Mail" or "Sent Mail" folders - I get an exception:
```
imaplib.error: SELECT command error: BAD [b'Could not parse command']
```
my code:
```
import imaplib
m = imaplib.IMAP4_SSL("imap.gmai... | As it's mentioned in [this answer](http://stackoverflow.com/questions/11736842/imaplib-select-on-big-inbox-too-many-arguments-for-command):
> Try using m.select('"[Gmail]/All Mail"'), so that the double quotes get transmitted.
> I suspect imaplib is not properly quoting the string, so the server gets what looks like t... |
PyQt QListWidget custom items | 25,187,444 | 2 | 2014-08-07T16:17:53Z | 25,188,862 | 10 | 2014-08-07T17:43:06Z | [
"python",
"pyqt",
"qlistwidgetitem"
] | how can i create a QListWidgetItem that has 1 image and 2 labels/strings underneath, that have support for css?
this is the last thing i have tried:
```
class CustomListWidgetItem(QListWidgetItem, QLabel):
def __init__(self, parent=None):
QListWidgetItem.__init__(self, parent)
QLabel.__in... | > how can i create a QListWidgetItem that has 1 image and 2
> labels/strings underneath, that have support for css?
In this case, you can't (it actually has an API for adding icons easily, but two labels/strings is impossible). But, you can create your own custom widget and put it into `QtGui.QListWidget`.
1. Create ... |
python cannot import opencv because it can't find libjpeg.8.dylib | 25,187,742 | 5 | 2014-08-07T16:34:37Z | 25,413,796 | 7 | 2014-08-20T20:24:48Z | [
"python",
"osx",
"opencv",
"jpeg"
] | Trying to get opencv for python working on Mac OSX - Mavericks but keep getting an image not found for libjpeg.8.dylib when doing import cv from python
(Recently updated from Mountain Lion)
This is what I did:
* brew tap homebrew/science
1. brew install opencv
-so far everything is fine
1. > > python
2. >... | The quick and dirty solution for this is to make a symlink inside of the /usr/local/lib folder pointing to the actual location of libjpeg.8.dylib, like this:
```
$ sudo ln -s /usr/local/Cellar/jpeg/8d/lib/libjpeg.8.dylib /usr/local/lib/libjpeg.8.dylib
```
The problem is opencv and python expect libjpeg.8.dylib to be ... |
Reverse complement of DNA strand using Python | 25,188,968 | 2 | 2014-08-07T17:50:45Z | 25,189,373 | 12 | 2014-08-07T18:16:38Z | [
"python",
"list",
"loops",
"dna-sequence",
"complement"
] | I have a DNA sequence and would like to get reverse complement of it using Python. It is in one of the columns of a CSV file and I'd like to write the reverse complement to another column in the same file. The tricky part is, there are a few cells with something other than A, T, G and C. I was able to get reverse compl... | The other answers are perfectly fine, but if you plan to deal with real DNA sequences I suggest you [Biopython](http://www.biopython.org). What if you encounter a character like "-", "\*" or indefinitions? What if you want to do further manipulations of your sequences? Do you want to create a parser for each file forma... |
pandas dataframe select columns in multiindex | 25,189,575 | 7 | 2014-08-07T18:28:15Z | 25,190,070 | 10 | 2014-08-07T18:56:28Z | [
"python",
"pandas",
"hierarchical",
"multi-index"
] | I have the following pd.DataFrame:
```
Name 0 1 ...
Col A B A B ...
0 0.409511 -0.537108 -0.355529 0.212134 ...
1 -0.332276 -1.087013 0.083684 0.529002 ...
2 1.138159 -0.327212 0.570834 ... | There is a `get_level_values` method that you can use in conjunction with boolean indexing to get the the intended result.
```
In [13]:
df = pd.DataFrame(np.random.random((4,4)))
df.columns = pd.MultiIndex.from_product([[1,2],['A','B']])
print df
1 2
A B ... |
SyntaxError: Non-ASCII character '\xe2' | 25,190,659 | 3 | 2014-08-07T19:28:43Z | 25,190,719 | 8 | 2014-08-07T19:32:02Z | [
"python",
"python-2.7"
] | I wrote a program to give me the value of the Mega Doge Coin
```
import time
import urllib2
from datetime import datetime
def get_HTML():
response = urllib.request.urlopen('http://www.dogepay.com')
html = response.read()
return html
def get_Value(rawHTML):
index = rawHTML.find(âCCFF00â)
while... | You should use standard ASCII quotes:
```
index = rawHTML.find("CCFF00")
```
rather than:
```
index = rawHTML.find(âCCFF00â)
``` |
Creating lowpass filter in SciPy - understanding methods and units | 25,191,620 | 20 | 2014-08-07T20:29:12Z | 25,192,640 | 36 | 2014-08-07T21:35:28Z | [
"python",
"scipy",
"filtering",
"signal-processing"
] | I am trying to filter a noisy heart rate signal with python. Because heart rates should never be about 220 beats per minute i want to filter out all noise above 220bpm. I converted 220/minute into 3.66666666 Hertz and then converted that Hertz to rad/s to get 23.0383461 rad/sec.
The sampling frequency of the chip that... | A few comments:
* The [Nyquist frequency](http://en.wikipedia.org/wiki/Nyquist_frequency) is half the sampling rate.
* You are working with regularly sampled data, so you want a digital filter, not an analog filter. This means you should not use `analog=True` in the call to `butter`, and you should use `scipy.signal.f... |
No module named pip.req | 25,192,794 | 5 | 2014-08-07T21:44:08Z | 25,193,001 | 7 | 2014-08-07T22:01:15Z | [
"python",
"pip",
"tweepy"
] | I am installing tweepy, but I am running into an error about pip.req. I have pip installed, but for some reason pip.req still can't be found. I did a bunch of research online and the most I could find was some issue about incompatibilities between zapo (?) and python 2.7 causing the same error for some other user. The ... | It looks like it would work if you had this code:
```
def parse_requirements(filename):
""" load requirements from a pip requirements file """
lineiter = (line.strip() for line in open(filename))
return [line for line in lineiter if line and not line.startswith("#")]
```
Do this:
1. create a directory `p... |
How to turn off INFO logging in PySpark? | 25,193,488 | 59 | 2014-08-07T22:48:58Z | 25,194,212 | 10 | 2014-08-08T00:11:41Z | [
"python",
"apache-spark"
] | I installed Spark using the AWS EC2 guide and I can launch the program fine using the `bin/pyspark` script to get to the spark prompt and can also do the Quick Start quide successfully.
However, I cannot for the life of me figure out how to stop all of the verbose `INFO` logging after each command.
I have tried nearl... | This may be due to how Spark computes its classpath. My hunch is that Hadoop's `log4j.properties` file is appearing ahead of Spark's on the classpath, preventing your changes from taking effect.
If you run
```
SPARK_PRINT_LAUNCH_COMMAND=1 bin/spark-shell
```
then Spark will print the full classpath used to launch th... |
How to turn off INFO logging in PySpark? | 25,193,488 | 59 | 2014-08-07T22:48:58Z | 26,123,496 | 78 | 2014-09-30T14:36:29Z | [
"python",
"apache-spark"
] | I installed Spark using the AWS EC2 guide and I can launch the program fine using the `bin/pyspark` script to get to the spark prompt and can also do the Quick Start quide successfully.
However, I cannot for the life of me figure out how to stop all of the verbose `INFO` logging after each command.
I have tried nearl... | Just execute this command in the spark directory:
```
cp conf/log4j.properties.template conf/log4j.properties
```
Edit log4j.properties:
```
# Set everything to be logged to the console
log4j.rootCategory=INFO, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
l... |
How to turn off INFO logging in PySpark? | 25,193,488 | 59 | 2014-08-07T22:48:58Z | 27,815,462 | 26 | 2015-01-07T08:44:50Z | [
"python",
"apache-spark"
] | I installed Spark using the AWS EC2 guide and I can launch the program fine using the `bin/pyspark` script to get to the spark prompt and can also do the Quick Start quide successfully.
However, I cannot for the life of me figure out how to stop all of the verbose `INFO` logging after each command.
I have tried nearl... | Edit your conf/log4j.properties file and Change the following line:
```
log4j.rootCategory=INFO, console
```
to
```
log4j.rootCategory=ERROR, console
```
Another approach would be to :
Fireup spark-shell and type in the following:
```
import org.apache.log4j.Logger
import org.apache.log4j.Level
Logger.get... |
How to turn off INFO logging in PySpark? | 25,193,488 | 59 | 2014-08-07T22:48:58Z | 32,208,445 | 25 | 2015-08-25T15:46:47Z | [
"python",
"apache-spark"
] | I installed Spark using the AWS EC2 guide and I can launch the program fine using the `bin/pyspark` script to get to the spark prompt and can also do the Quick Start quide successfully.
However, I cannot for the life of me figure out how to stop all of the verbose `INFO` logging after each command.
I have tried nearl... | Inspired by the pyspark/tests.py I did
```
def quiet_logs( sc ):
logger = sc._jvm.org.apache.log4j
logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )
```
Calling this just after creating SparkContext reduced stderr lines logged f... |
How to turn off INFO logging in PySpark? | 25,193,488 | 59 | 2014-08-07T22:48:58Z | 34,487,962 | 15 | 2015-12-28T05:09:40Z | [
"python",
"apache-spark"
] | I installed Spark using the AWS EC2 guide and I can launch the program fine using the `bin/pyspark` script to get to the spark prompt and can also do the Quick Start quide successfully.
However, I cannot for the life of me figure out how to stop all of the verbose `INFO` logging after each command.
I have tried nearl... | ```
>>> log4j = sc._jvm.org.apache.log4j
>>> log4j.LogManager.getRootLogger().setLevel(log4j.Level.ERROR)
``` |
One chart with two different y axis ranges in Bokeh? | 25,199,665 | 12 | 2014-08-08T09:01:32Z | 30,914,348 | 12 | 2015-06-18T11:40:20Z | [
"python",
"bokeh"
] | I would like a Bar chart with Quantity information on the left y-axis, and then overlay a Scatter/Line plot with Yield % on the right. I can create each of these charts separately, but do not know how to combine them into a single plot.
In matplotlib, we would create a second figure using `twinx()`, and then use `yaxi... | Yes, now it is possible to have two y axes in Bokeh plots.
The code below shows script parts significant in setting up the second y axis
to the usual figure plotting script.
```
# Modules needed from Bokeh.
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import LinearAxis, Ra... |
Python function: Optional argument evaluated once? | 25,204,126 | 2 | 2014-08-08T12:59:30Z | 25,204,287 | 8 | 2014-08-08T13:08:07Z | [
"python"
] | Python Tutorial [4.7.1. Default Argument Values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values) states the following:
> **Important warning:** The default value is evaluated only once. This makes a difference
> when the default is a mutable object such as a list, dictionary, or instances ... | In Python, functions are objects too, and the defaults are stored with the function object. Defaults are **not** locals; it is just that when the function is called, the arguments are bound to a default when not given an explicit value.
When Python encounters a `def <functionname>(<arguments>):` statement, it creates ... |
What happens when a function returns its own name in python? | 25,204,896 | 17 | 2014-08-08T13:40:50Z | 25,204,956 | 10 | 2014-08-08T13:43:37Z | [
"python"
] | ```
def traceit(frame, event, trace_arg):
global stepping
if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command... | Since all functions in Python are created as objects, it returns a reference to the function.
It may be passed into another function later in the code or called with parameters as you could with any function.
```
def a(str):
print str
b = a # Assign an instance of a to b
b('hello') # Call b as if it were a
print... |
What happens when a function returns its own name in python? | 25,204,896 | 17 | 2014-08-08T13:40:50Z | 25,205,012 | 17 | 2014-08-08T13:46:52Z | [
"python"
] | ```
def traceit(frame, event, trace_arg):
global stepping
if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command... | A function is an object like anyone else, so there's no problem in returning itself. For example, it allows repeated calling on the same line:
```
traceit("abc", "def", None)("ghi", "jkl", 3)("mno", "pqr", 4.3)
```
---
Edit: `sys.settrace` sets the global tracing function, that is invoked every time a local scope is... |
What happens when a function returns its own name in python? | 25,204,896 | 17 | 2014-08-08T13:40:50Z | 25,207,647 | 7 | 2014-08-08T16:05:56Z | [
"python"
] | ```
def traceit(frame, event, trace_arg):
global stepping
if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command... | <https://docs.python.org/2/library/sys.html#sys.settrace>
settrace allows you to pass a function to use as a debugger.
Every time a new scope is entered, the function you passed is called. It needs to return a function that should be used for debugging inside that scope.
Since the writer of that code, wanted to alway... |
How do I install pyspark for use in standalone scripts? | 25,205,264 | 19 | 2014-08-08T13:59:14Z | 29,498,104 | 16 | 2015-04-07T18:01:01Z | [
"python",
"apache-spark"
] | I'm am trying to use Spark with Python. I installed the Spark 1.0.2 for Hadoop 2 binary distribution from the [downloads](https://spark.apache.org/downloads.html) page. I can run through the quickstart examples in Python interactive mode, but now I'd like to write a standalone Python script that uses Spark. The [quick ... | Add Pyspark lib in Python path in the bashrc
```
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
```
also don't forget to set up the SPARK\_HOME.
PySpark depends the py4j Python package. So install that as follows
```
pip install py4j
```
For more details about stand alone PySpark application refer this [post](ht... |
Python equivalent of the R operator "%in%" | 25,206,376 | 7 | 2014-08-08T14:57:45Z | 25,206,517 | 9 | 2014-08-08T15:04:17Z | [
"python",
"pandas"
] | What is the python equivalent of this in operator? I am trying to filter down a pandas database by having rows only remain if a column in the row has a value found in my list.
I tried using any() and am having immense difficulty with this. | Pandas comparison with R docs are [here](http://pandas.pydata.org/pandas-docs/stable/comparison_with_r.html#match).
```
s <- 0:4
s %in% c(2,4)
```
The isin() method is similar to R %in% operator:
```
In [13]: s = pd.Series(np.arange(5),dtype=np.float32)
In [14]: s.isin([2, 4])
Out[14]:
0 False
1 False
2 ... |
Is the golden ratio defined in Python? | 25,212,181 | 8 | 2014-08-08T21:01:34Z | 25,212,208 | 15 | 2014-08-08T21:03:57Z | [
"python",
"math",
"numpy"
] | Is there a way to get the golden ratio, *`phi`*, in the standard python module? I know of *`e`* and *`pi`* in the `math` module, but I might have missed *`phi`* defined somewhere. | [`scipy.constants`](http://docs.scipy.org/doc/scipy/reference/constants.html) defines the golden ratio as `scipy.constants.golden`. It is nowhere defined in the standard library, presumably because it is easy to define yourself:
```
golden = (1 + 5 ** 0.5) / 2
``` |
How to set some xlim and ylim in Seaborn lmplot facetgrid | 25,212,986 | 21 | 2014-08-08T22:12:00Z | 25,213,438 | 24 | 2014-08-08T23:00:00Z | [
"python",
"pandas",
"seaborn"
] | I'm using Seaborn's lmplot to plot a linear regression, dividing my dataset into two groups with a categorical variable.
For both x and y, I'd like to manually set the *lower bound* on both plots, but leave the *upper bound* at the Seaborn default.
Here's a simple example:
```
import pandas as pd
import seaborn as sn... | You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:
```
lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
```
Then you can get hold of the axes objects (an array of axes):
```
axes = lm.axes
```
After that you can tweak the axes properties
```
axes[0,0].se... |
How to set some xlim and ylim in Seaborn lmplot facetgrid | 25,212,986 | 21 | 2014-08-08T22:12:00Z | 25,213,614 | 32 | 2014-08-08T23:19:53Z | [
"python",
"pandas",
"seaborn"
] | I'm using Seaborn's lmplot to plot a linear regression, dividing my dataset into two groups with a categorical variable.
For both x and y, I'd like to manually set the *lower bound* on both plots, but leave the *upper bound* at the Seaborn default.
Here's a simple example:
```
import pandas as pd
import seaborn as sn... | The `lmplot` function returns a `FacetGrid` instance. This object has a method called `set`, to which you can pass `key=value` pairs and they will be set on each Axes object in the grid.
Secondly, you can set only one side of an Axes limit in matplotlib by passing `None` for the value you want to remain as the default... |
Disable images in Selenium Python | 25,214,473 | 9 | 2014-08-09T01:42:37Z | 25,214,511 | 13 | 2014-08-09T01:49:28Z | [
"javascript",
"python",
"css",
"selenium",
"selenium-webdriver"
] | Because Webdriver waits for the entire page to load before going on to the next line, I think disabling images, css and javascript will speed things up.
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
def disableImages(self):
## get the Firefox profile obje... | *UPDATE*: The answer might not work any longer since [`permissions.default.image` became a frozen setting](http://stackoverflow.com/a/31572457/771848) and cannot be changed. Please try with `quickjava` extension (link to the [answer](http://stackoverflow.com/a/31576684/771848)).
---
You need to pass `firefox_profile`... |
Disable images in Selenium Python | 25,214,473 | 9 | 2014-08-09T01:42:37Z | 31,576,684 | 18 | 2015-07-23T01:23:24Z | [
"javascript",
"python",
"css",
"selenium",
"selenium-webdriver"
] | Because Webdriver waits for the entire page to load before going on to the next line, I think disabling images, css and javascript will speed things up.
```
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
def disableImages(self):
## get the Firefox profile obje... | Unfortunately the option `firefox_profile.set_preference('permissions.default.image', 2)` will no longer work to disable images with the latest version of Firefox - [for reason see Alecxe's answer to my question [Can't turn off images in Selenium / Firefox](http://stackoverflow.com/questions/31571726/cant-turn-off-imag... |
Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv | 25,215,102 | 55 | 2014-08-09T04:01:42Z | 25,215,692 | 8 | 2014-08-09T05:58:52Z | [
"python",
"opencv",
"ubuntu",
"importerror"
] | I have an Ubuntu 14.04 system, on which I want to install OpenCV and use it with Python 2.x.
I installed OpenCV using the instructions here:
<https://help.ubuntu.com/community/OpenCV>
The install seemed to run properly, no errors, the script ended with output
```
OpenCV 2.4.9 ready to be used
```
When I try to run ... | Use pip:
> <https://pypi.python.org/pypi/pip>
```
$ pip install SomePackage
[...]
Successfully installed SomePackage
```
And when you add a path to PYTHONPATH with sys, PYTHONPATH it's always restarted to default values when you close your Python shell. Check this thread:
> [Permanently add a directory to PYTHO... |
Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv | 25,215,102 | 55 | 2014-08-09T04:01:42Z | 29,232,025 | 71 | 2015-03-24T11:54:49Z | [
"python",
"opencv",
"ubuntu",
"importerror"
] | I have an Ubuntu 14.04 system, on which I want to install OpenCV and use it with Python 2.x.
I installed OpenCV using the instructions here:
<https://help.ubuntu.com/community/OpenCV>
The install seemed to run properly, no errors, the script ended with output
```
OpenCV 2.4.9 ready to be used
```
When I try to run ... | I think you don't have the `python-opencv` package.
I had the exact same problem and
```
sudo apt-get install python-opencv
```
solved the issue for me. |
Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv | 25,215,102 | 55 | 2014-08-09T04:01:42Z | 34,120,580 | 15 | 2015-12-06T17:46:01Z | [
"python",
"opencv",
"ubuntu",
"importerror"
] | I have an Ubuntu 14.04 system, on which I want to install OpenCV and use it with Python 2.x.
I installed OpenCV using the instructions here:
<https://help.ubuntu.com/community/OpenCV>
The install seemed to run properly, no errors, the script ended with output
```
OpenCV 2.4.9 ready to be used
```
When I try to run ... | I also had this issue. Tried different things. But finally
```
conda install opencv
```
worked for me. |
Matching characters in two Python strings | 25,215,576 | 3 | 2014-08-09T05:41:56Z | 25,215,624 | 8 | 2014-08-09T05:48:26Z | [
"python",
"regex"
] | I am trying to print the shared characters between 2 sets of strings in Python, I am doing this with the hopes of actually finding how to do this using nothing but python regular expressions (I don't know regex so this might be a good time to learn it).
So if `first_word = "peepa"` and `second_word = "poopa"` I want t... | This sounds like a problem where you want to find the intersection of characters between the two strings. The quickest way would be to do this:
```
>>> set(first_word).intersection(second_word)
set(['a', 'p'])
```
I don't think regular expressions are the right fit for this problem. |
How to see top n entries of term-document matrix after tfidf in scikit-learn | 25,217,510 | 10 | 2014-08-09T10:17:07Z | 25,219,535 | 15 | 2014-08-09T14:24:09Z | [
"python",
"numpy",
"scikit-learn"
] | I am new to scikit-learn, and I was using `TfidfVectorizer` to find the tfidf values of terms in a set of documents. I used the following code to obtain the same.
```
vectorizer = TfidfVectorizer(stop_words=u'english',ngram_range=(1,5),lowercase=True)
X = vectorizer.fit_transform(lectures)
```
Now If I print X, I am ... | Since version 0.15, the global term weighting of the features learnt by a [`TfidfVectorizer`](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html#sklearn.feature_extraction.text.TfidfVectorizer) can be accessed through the attribute `idf_`, which will return an array of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.