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 |
|---|---|---|---|---|---|---|---|---|---|
ImportError: cannot import name HTTPSHandler using PIP | 20,688,034 | 49 | 2013-12-19T17:29:26Z | 26,982,802 | 42 | 2014-11-17T22:00:34Z | [
"python",
"ssl",
"openssl",
"pip"
] | Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env... | # OSX + homebrew users:
You can get the latest updates to the recipe:
```
brew reinstall python
```
but if you still get the issue, e.g. maybe you upgraded your OS, then you may need to get the latest openssl first.
```
brew install openssl
brew link --overwrite --dry-run openssl # safety first.
brew link openssl ... |
ImportError: cannot import name HTTPSHandler using PIP | 20,688,034 | 49 | 2013-12-19T17:29:26Z | 30,355,543 | 18 | 2015-05-20T16:34:31Z | [
"python",
"ssl",
"openssl",
"pip"
] | Facing an HTTPSHandler error while installing python packages using pip, following is the stack trace,
```
--------desktop:~$ pip install Django==1.3
Traceback (most recent call last):
File "/home/env/.genv/bin/pip", line 9, in <module>
load_entry_point('pip==1.4.1', 'console_scripts', 'pip')()
File "/home/env... | # Homebrew
This was probably caused by an upgrade to Mavericks. Here's how I fixed it.
## Update OpenSSL
```
#make a copy of the existing library, just in case
sudo cp /usr/bin/openssl /usr/bin/openssl.apple
# update openssl
brew update
brew install openssl
brew link --force openssl
# reload terminal paths
hash -... |
Numpy: Assignment and Indexing as Matlab | 20,688,881 | 4 | 2013-12-19T18:18:58Z | 20,689,082 | 8 | 2013-12-19T18:31:00Z | [
"python",
"numpy",
"indexing"
] | Sometimes is useful to assign arrays with one index only. In Matlab this is straightforward:
```
M = zeros(4);
M(1:5:end) = 1
M =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
```
Is there a way to do this in Numpy? First I thought to flatten the array, but that operation doesn't preserve the r... | You could try [numpy.ndarray.flat](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flat), which represents an iterator that you can use for reading and writing into the array.
```
>>> M = zeros((4,4))
>>> M.flat[::5] = 1
>>> print(M)
array([[ 1., 0., 0., 0.],
[ 0., ... |
Flask Error: "Method Not Allowed The method is not allowed for the requested URL" | 20,689,195 | 7 | 2013-12-19T18:37:11Z | 20,689,328 | 12 | 2013-12-19T18:43:58Z | [
"python",
"flask"
] | I'm getting the following error whenever I try to submit data to my Flask form:
```
Method Not Allowed The method is not allowed for the requested URL.
```
I think the issue is in the `return redirect(url_for('database'))` I'm doing. I've also tried `return render_template('database.html)` too. I'm trying to call the... | What is happening here is that database route does not accept any url methods.
I would try putting the url methods in the app route just like you have in the entry\_page function:
```
@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
if request.method == 'POST':
date = request.form['date']
... |
(Python) Gaussian Bernoulli RBM on computing P(v|h) | 20,690,163 | 5 | 2013-12-19T19:31:44Z | 20,693,716 | 8 | 2013-12-19T23:29:56Z | [
"python",
"numpy",
"machine-learning",
"neural-network",
"rbm"
] | **Context:**
I am implementing Gaussian Bernoulli RBM, it is like the popular RBM but with real-valued visible units.
True that the procedure of sampling hidden values `p(h=1|v)` are the same for both, i.e.

**Problem:**
My problem is in coding (us... | The notation *X* ~ *N*(μ, ϲ) means that *X* is normally distributed with mean μ and variance ϲ, so in the RBM training routine, *v* should be **sampled** from such a distribution. In NumPy terms, that's
```
v = sigma * np.random.randn(v_size) + b + sigma * W.dot(h)
```
Or use `scipy.stats.norm` for better rea... |
brew install python, but then: "python-2.7.6 already installed, it's just not linked" | 20,691,181 | 30 | 2013-12-19T20:35:27Z | 20,691,578 | 48 | 2013-12-19T20:59:56Z | [
"python",
"bash",
"homebrew"
] | disclaimer: noob
OSX 10.8.5
When I installed python in bash I got [this warning and error](http://i.imgur.com/EZddNcX.png):
```
Warning: Could not link python. Unlinking...
Error: The 'brew link' step did not complete successfully
The formula built, but is not symlinked into /usr/local
You can try again using 'brew ... | It looks like you have installed Python using another method before. Don't be scared. Homebrew is engineered so it won't mess up your system like Mac Ports et al.
You can always do `brew link --overwrite --dry-run python` to see first what exactly will be overwritten, without actually doing it.
If once you do this it... |
Why does pandas use (&, |) instead of the normal, pythonic (and, or)? | 20,691,508 | 7 | 2013-12-19T20:55:46Z | 20,691,565 | 14 | 2013-12-19T20:58:54Z | [
"python",
"pandas"
] | I understand the [pandas docs](http://pandas.pydata.org/pandas-docs/dev/indexing.html#boolean-indexing) explain that this is the convention, but I was wondering why?
For example:
```
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,4), index=list('abcdef'), columns=list('ABCD'))
print(df[(df... | Because `&` and `|` are overridable (customizable). You can write the code that drives the operators for any `class`.
The logic operators `and` and `or`, on the other hand, have standard behavior that cannot be modified.
See [here](http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types) for the rel... |
Comparing strings with Python: X in ['item1', 'item2', ...] vs. X == 'item1', X == 'item2', ...? | 20,691,829 | 3 | 2013-12-19T21:15:36Z | 20,691,877 | 8 | 2013-12-19T21:18:29Z | [
"python",
"string",
"performance",
"list",
"comparison"
] | I am fairly new to Python and I have a question regarding performance when comparing strings. Both codes below seem to achieve what I want but is there any reason to use one of them instead of the other?
Option1:
```
if first_column_header == 'author name' or first_column_header == 'author' or first_column_header == ... | Option 2 is definitely shorter and more pythonic. It's also possible that it adds a little more of overhead to your code because it creates a list and then iterates through it.
This is a trade off you'll have to accept by making programs more readable but, IMHO, **this is too little overhead to worry** so I'll go with... |
Edit pandas dataframe row-by-row | 20,692,122 | 5 | 2013-12-19T21:33:50Z | 20,692,226 | 13 | 2013-12-19T21:41:03Z | [
"python",
"pandas",
"trial"
] | pandas for python is neat. I'm trying to replace a list-of-dictionaries with a pandas-dataframe. However, I'm wondering of there's a way to change values row-by-row in a for-loop just as easy?
Here's the non-pandas dict-version:
```
trialList = [
{'no':1, 'condition':2, 'response':''},
{'no':2, 'condition':1,... | If you really want row-by-row ops, you could use `iterrows` and `loc`:
```
>>> for i, trial in dfTrials.iterrows():
... dfTrials.loc[i, "response"] = "answer {}".format(trial["no"])
...
>>> dfTrials
condition no response
0 2 1 answer 1
1 1 2 answer 2
2 1 3 answer 3
[3... |
Pythonic Improvement Of Function In List Comprehension? | 20,692,637 | 2 | 2013-12-19T22:08:15Z | 20,692,720 | 8 | 2013-12-19T22:13:50Z | [
"python",
"list-comprehension"
] | Is there a more pythonic way to do the following code? I would like to do it in one line
parsed\_rows is a function that can return a tuple of size 3, or None.
```
parsed_rows = [ parse_row(tr) for tr in tr_els ]
data = [ x for x in parsed_rows if x is not None ]
``` | Doing this in one line won't make it more Pythonic; it will make it less readable. If you really want to, you can always translate it directly by substitution like this:
```
data = [x for x in [parse_row(tr) for tr in tr_els] if x is not None]
```
⦠which can obviously be flattened as Doorknob of Snow shows, but it... |
How to add logging to a file with timestamps to a Python TCP Server for Raspberry Pi | 20,695,241 | 2 | 2013-12-20T02:19:42Z | 20,758,170 | 18 | 2013-12-24T09:22:11Z | [
"python",
"raspberry-pi",
"tcpserver"
] | I am kinda stuck for my project & I desperately need help. I need a simple TCP server python code that has features like logging & time stamp which I could use for my Raspberry Pi. Its for my Final Year Project.
I've looked at some examples, but as I don't have much experience in writing my own scripts/codes, I'm not ... | To add logging to a file with timestamps, you could use `logging` module:
```
import logging
logging.basicConfig(level=logging.INFO,
filename='myserver.log', # log to this file
format='%(asctime)s %(message)s') # include timestamp
logging.info("some message")
```
If you run t... |
How to indicate that a function expects a function as a parameter, or returns a function, via function annotations? | 20,695,516 | 7 | 2013-12-20T02:51:24Z | 20,695,543 | 7 | 2013-12-20T02:54:44Z | [
"python",
"function",
"python-3.x",
"annotations"
] | You can use [function annotations](http://www.python.org/dev/peps/pep-3107/) in python 3 to indicate the types of the parameters and return value, like so:
```
def myfunction(name: str, age: int) -> str:
return name + str(age) #usefulfunction
```
But what if you were writing a function that expects a function as ... | There's no style defined for annotations. Either use `callable`, `types.FunctionType` or a string.
PS: `callable` was not available in Python 3.0 and 3.1 |
Efficiently partition a string at arbitrary index | 20,696,084 | 4 | 2013-12-20T04:04:40Z | 20,696,173 | 8 | 2013-12-20T04:16:47Z | [
"python",
"string",
"python-3.x",
"idioms"
] | Given an arbitrary string (i.e., not based on a pattern), say:
```
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
```
I am trying to partition a string based a list of indexes.
Here is what I tried, which does work:
```
import string
def split_at_idx(txt, idx):
new_li=[None]*2*... | I have a feeling someone asked this question very recently, but I can't find it now. Assuming that the dropped letters were an accident, couldn't you just do:
```
def split_at_idx(s, idx):
return [s[i:j] for i,j in zip([0]+idx, idx+[None])]
```
after which we have
```
>>> split_at_idx(string.ascii_letters, [3, 1... |
PRAW: How to get a reddit comment object with just the comment ID? | 20,696,674 | 5 | 2013-12-20T05:07:05Z | 20,711,464 | 7 | 2013-12-20T20:28:13Z | [
"python",
"reddit",
"praw"
] | I'm working on a bot where I only have the comment IDs, e.g., t1\_asdasd. I don't have access to the parent thread or anything. Can I pull the corresponding comment object with just the comment ID? | This reddit thread shows how to accomplish this through the normal API: <http://www.reddit.com/r/redditdev/comments/1si9m0/fetching_comments_by_id/>
Here's the code to do this with PRAW:
```
import praw
r = praw.Reddit(user_agent="bot by /u/{0}".format("YOUR-USERNAME"))
submission = r.get_info(thing_id="t1_asdasd")
... |
When does using swapcase twice not return an identical answer? | 20,696,923 | 15 | 2013-12-20T05:32:20Z | 20,697,163 | 10 | 2013-12-20T05:50:34Z | [
"python"
] | The Python docs for [`str.swapcase()`](http://docs.python.org/3/library/stdtypes.html#str.swapcase) say:
> Note that it is not necessarily true that `s.swapcase().swapcase() == s`.
I'm guessing that this has something to do with Unicode; however, I wasn't able to produce a string that changed after exactly two applic... | This is the case when multiple letters are lower cases of the same letter.
For example, the micro character `µ` [(U+00B5)](http://www.fileformat.info/info/unicode/char/00b5/index.htm) and the mu character `μ` [(U+03BC)](http://www.fileformat.info/info/unicode/char/03BC/index.htm):
```
>>> u'\xb5'.swapcase()
u'\u039... |
Find and draw regression plane to a set of points | 20,699,821 | 7 | 2013-12-20T09:02:47Z | 20,700,063 | 7 | 2013-12-20T09:15:28Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"regression"
] | I want to fit a plane to some data points and draw it. My current code is this:
```
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
points = [(1.1,2.1,8.1),
(3.2,4.2,8.0),
(5.3,1.3,8.2),
(3.4,2.4,8.3),
(1.5,4.5,8.0)]
xs, ys, zs = zip(... | Oh, the idea just came to my mind. It's quite easy. :-)
```
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import scipy.optimize
import functools
def plane(x, y, params):
a = params[0]
b = params[1]
c = params[2]
z = a*x + b*y + c
return z
def error(par... |
Why do I get only one parameter from a statsmodels OLS fit | 20,701,484 | 13 | 2013-12-20T10:27:10Z | 20,701,559 | 19 | 2013-12-20T10:30:29Z | [
"python",
"pandas",
"linear-regression",
"statsmodels"
] | Here is what I am doing:
```
$ python
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
>>> import statsmodels.api as sm
>>> statsmodels.__version__
'0.5.0'
>>> import numpy
>>> y = numpy.array([1,2,3,4,5,6,7,8,9])
>>> X = numpy.array([1,1,2,2,3,3,4,4,5])... | try this:
```
X = sm.add_constant(X)
sm.OLS(y,X)
```
as in the [documentations](http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html):
> An interecept is not included by default and should be added by the user
[`statsmodels.tools.tools.add_constant`](http://statsmodels.sou... |
Is there a sessionInfo() equivalent in Python? | 20,703,975 | 12 | 2013-12-20T12:47:31Z | 20,704,624 | 9 | 2013-12-20T13:22:41Z | [
"python",
"ipython"
] | Normally I use R, and often when wanting to make things reproduicible I use `sessionInfo()`. The reason for this is that I like to let people know what version of everything I am using and what packages I have installed/loaded and what OS I am on etc, so that its quite clear.
`sessionInfo` returns the version of R, th... | The following will make you part there :
```
In [1]: import IPython
In [2]: print IPython.sys_info()
{'codename': 'Work in Progress',
'commit_hash': '4dd36bf',
'commit_source': 'repository',
'default_encoding': 'UTF-8',
'ipython_path': '/Users/matthiasbussonnier/ipython/IPython',
'ipython_version': '2.0.0-dev',
... |
Pipe Ipython magic output to a variable? | 20,704,063 | 7 | 2013-12-20T12:53:45Z | 20,704,242 | 8 | 2013-12-20T13:04:02Z | [
"python",
"python-2.7",
"ipython",
"ipython-notebook",
"ipython-magic"
] | I want to run a bash script in my ipython Notebook and save the output as a string in a python variable for further manipulation. Basically I want to pipe the output of the bash magic to a variable,
For example the output of something like this:
```
%%bash
some_command [options] foo bar
``` | What about using this:
```
myvar = !some_command --option1 --option2 foo bar
```
instead of the `%%bash` magic? Using the `!` symbol runs the following command as a shell command, and the results are all stored in `myvar`. For running multiple commands and collecting the output of all of them, just put together a qui... |
Pipe Ipython magic output to a variable? | 20,704,063 | 7 | 2013-12-20T12:53:45Z | 24,776,049 | 8 | 2014-07-16T08:38:54Z | [
"python",
"python-2.7",
"ipython",
"ipython-notebook",
"ipython-magic"
] | I want to run a bash script in my ipython Notebook and save the output as a string in a python variable for further manipulation. Basically I want to pipe the output of the bash magic to a variable,
For example the output of something like this:
```
%%bash
some_command [options] foo bar
``` | For completeness, if you would still like to use the `%%bash` cell magic, you can pass the `--out` and `--err` flags to redirect the outputs from the stdout and stderr to a variable of your choice.
From the [doucumentation](http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ip... |
Selenium Webdriver + PhantomJS remains at about:blank for a specific site | 20,705,027 | 13 | 2013-12-20T13:46:47Z | 21,045,736 | 16 | 2014-01-10T13:35:31Z | [
"c#",
"python",
"selenium",
"phantomjs"
] | I am trying to use PhantomJS with Selenium Webdriver and got success but for a specific website I see that it does not navigate to the URL. I have tried it with both Python and C#.
Python Code:
```
dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = ("Mozilla/5.0 (Windows... | Following is a complete code solution for c# -
```
PhantomJSDriverService service = PhantomJSDriverService.CreateDefaultService();
service.IgnoreSslErrors = true;
service.LoadImages = false;
service.ProxyType = "none";
driver = new PhantomJSDriver(service);
``` |
How can I get int value from url | 20,705,035 | 2 | 2013-12-20T13:47:11Z | 20,705,068 | 8 | 2013-12-20T13:48:45Z | [
"python",
"regex",
"python-2.7"
] | If I have a `url` like `examle/def/5/`, I tried to find `int` value from `url` by using
```
re.findall([0-9],'examle/def/5/')
```
but I get an error.
> Traceback (most recent call last): File "", line 1, in
> File "/usr/lib/python2.7/re.py", line 177, in findall return
> \_compile(pattern, flags).findall(string) Fil... | Make sure to import `re`.
```
>>> import re
```
Pass the first argument as string object. (Without quotes `[0-9]` a list literal equivalent to `[-9]`.)
```
>>> re.findall('[0-9]','examle/def/5/')
['5']
```
BTW, you can use `\d` instead of `[0-9]` to match digit (Using `r'raw string'` you don't need to escape `\`):
... |
Why non existing URL containing the sharp ("#") sign in Python/Flask aren't handled by the errorhandler | 20,705,285 | 2 | 2013-12-20T14:00:03Z | 20,705,345 | 7 | 2013-12-20T14:03:14Z | [
"python",
"url",
"routing",
"flask"
] | I'm building a Python/Flask (fully ajax, without full page reloading) web application and I change the content of my master page when the sharp ("#") sign on the url change [(Ben Alman, HashChange event)](http://benalman.com/projects/jquery-hashchange-plugin/)
I would like to catch all Error-404 to append an error pag... | Everything after the `#` forms the [fragment identifier](http://en.wikipedia.org/wiki/Fragment_identifier) of a resource and is handled **client side**. In the normal course of operation, the fragment identifier is never sent to the server:
> The fragment identifier functions differently than the rest of the URI: name... |
scipy.misc.derivative for mutiple argument function | 20,708,038 | 9 | 2013-12-20T16:34:49Z | 20,708,578 | 11 | 2013-12-20T17:05:30Z | [
"python",
"numpy",
"scipy",
"derivative"
] | It is straightforward to compute the partial derivatives of a function at a point with respect to the first argument using the SciPy function `scipy.misc.derivative`. Here is an example:
```
def foo(x, y):
return(x**2 + y**3)
from scipy.misc import derivative
derivative(foo, 1, dx = 1e-6, args = (3, ))
```
But how... | I would write a simple wrapper, something along the lines of
```
def partial_derivative(func, var=0, point=[]):
args = point[:]
def wraps(x):
args[var] = x
return func(*args)
return derivative(wraps, point[var], dx = 1e-6)
```
Demo:
```
>>> partial_derivative(foo, 0, [3,1])
6.000000000838... |
Ignore matplotlib cursor widget when toolbar widget selected? | 20,711,148 | 4 | 2013-12-20T20:05:13Z | 20,712,813 | 7 | 2013-12-20T22:18:51Z | [
"python",
"matplotlib",
"interactive"
] | I am using a cursor widget in an interactive Matplotlib plot like so:
```
cursor = Cursor(ax1, useblit=True, color='red', linewidth=1)
cid = fig.canvas.mpl_connect('button_press_event', on_click)
```
Works well. The `on_click` function takes the x,y click locations and does some supplemental plotting. Basic stuff.
W... | That isn't public state, but you can check
```
fig.canvas.manager.toolbar._active is None
```
which will be `True` if the toolbar is not trying to grab clicks (either through pan or zoom).
You are reaching in and touching internal state which can change at any time, so use this at your own risk. The developers have ... |
pandas retrieve the frequency of a time series | 20,711,180 | 4 | 2013-12-20T20:07:36Z | 20,711,306 | 7 | 2013-12-20T20:17:27Z | [
"python",
"pandas"
] | Is there a way to retrieve the frequency of a time series in pandas?
```
rng = date_range('1/1/2011', periods=72, freq='H')
ts =pd.Series(np.random.randn(len(rng)), index=rng)
```
ts.frequency or ts.period are not methods available.
Thanks
**Edit:**
Can we infer the frequency from time series that do not specify fr... | For `DatetimeIndex`
```
>>> rng
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00, ..., 2011-01-03 23:00:00]
Length: 72, Freq: H, Timezone: None
>>> len(rng)
72
>>> rng.freq
<1 Hour>
>>> rng.freqstr
'H'
```
Similary for series indexed with this index
```
>>> ts.index.freq
<1 Hour>
``` |
Python - str() function completely alters list | 20,711,321 | 2 | 2013-12-20T20:18:42Z | 20,711,386 | 8 | 2013-12-20T20:23:11Z | [
"python",
"string",
"list"
] | Below is a code to generate the products of any two 3-digits numbers
```
integers_list = [(i * x) for i in range(100,1000) for x in range(100,1000)]
string_list = (map(str, integers_list))
integers_list.sort()
string_list.sort()
print integers_list[-10:-1]
print string_list[-10:-1]
```
gives:
```
[995004, 995... | Strings sort in a different order than integers. 9800 is greater than 990, but '9800' is less than '990'. |
XML to CSV in Python | 20,714,038 | 5 | 2013-12-21T00:27:24Z | 20,714,466 | 16 | 2013-12-21T01:32:08Z | [
"python",
"xml",
"csv",
"gps",
"garmin"
] | I'm having a lot of trouble converting an XML file to a CSV in Python. I've looked at many forums, tried both lxml and xmlutils.xml2csv, but I can't get it to work. It's GPS data from a Garmin GPS device.
Here's what my XML file looks like, shortened of course:
```
<?xml version="1.0" encoding="utf-8"?>
<gpx xmlns:tc... | This is a **namespaced** XML document. Therefore you need to address the nodes using their respective namespaces.
The namespaces used in the document are defined at the top:
```
xmlns:tc2="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tp1="http... |
Python Django Encoding Error, Non-ASCII character '\xe5' | 20,714,517 | 3 | 2013-12-21T01:41:36Z | 20,714,620 | 7 | 2013-12-21T01:58:41Z | [
"python",
"django",
"view",
"encoding"
] | **Hi,
I ran into an encoding error with Python Django.
In my views.py, I have the following:**
```
from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
# Create your views here.
def hello(request):
name = 'Mike... | Well, here you are:
Put `# -*- coding: utf-8 -*-` at top of file, it define de encoding.
The [docs](http://www.python.org/dev/peps/pep-0263/) says:
> Python will default to ASCII as standard encoding if no other
> encoding hints are given.
>
> ```
> To define a source code encoding, a magic comment must
> be placed ... |
Flask RESTful API multiple and complex endpoints | 20,715,238 | 17 | 2013-12-21T03:57:41Z | 20,722,760 | 33 | 2013-12-21T19:32:47Z | [
"python",
"api",
"rest",
"flask",
"flask-extensions"
] | In my Flask-RESTful API, imagine I have two objects, users and cities. It is a 1-to-many relationship. Now when I create my API and add resources to it, all I can seem to do is map very easy and general URLs to them. Here is the code (with useless stuff not included):
```
class UserAPI(Resource): #The API class that ... | Your are making two mistakes.
First, Flask-RESTful leads you to think that a resource is implemented with a single URL. In reality, you can have many different URLs that return resources of the same type. In Flask-RESTful you will need to create a different `Resource` subclass for each URL, but conceptually those URLs... |
Saving and loading multiple objects in python pickle file | 20,716,812 | 18 | 2013-12-21T07:47:45Z | 20,725,705 | 23 | 2013-12-22T02:38:01Z | [
"python",
"class",
"object",
"python-3.x",
"pickle"
] | I have class that serves players in a game, creates them and other things.
I need to save these player objects in a file to use it later. I've tried pickle module but I don't know how to save multiple objects and again loading them? Is there a way to do that or should I use other classes such as lists and save and loa... | Using a list, tuple, or dict is by far the most common way to do this:
```
import pickle
PIK = "pickle.dat"
data = ["A", "b", "C", "d"]
with open(PIK, "wb") as f:
pickle.dump(data, f)
with open(PIK, "rb") as f:
print pickle.load(f)
```
That prints:
```
['A', 'b', 'C', 'd']
```
However, a pickle file *can* ... |
Saving and loading multiple objects in python pickle file | 20,716,812 | 18 | 2013-12-21T07:47:45Z | 28,745,948 | 23 | 2015-02-26T15:09:39Z | [
"python",
"class",
"object",
"python-3.x",
"pickle"
] | I have class that serves players in a game, creates them and other things.
I need to save these player objects in a file to use it later. I've tried pickle module but I don't know how to save multiple objects and again loading them? Is there a way to do that or should I use other classes such as lists and save and loa... | Two additions to [Tim Peters' accepted answer](http://stackoverflow.com/a/20725705/2810305).
**First**, you need not store the number of items you pickled separately if you use the following idiom for loading:
```
def load(filename):
with open(filename, "rb") as f:
while True:
try:
... |
Python - Download Images from google Image search? | 20,716,842 | 11 | 2013-12-21T07:52:07Z | 20,717,030 | 16 | 2013-12-21T08:20:24Z | [
"python",
"web-scraping"
] | I want to download all Images of google image search using python . The code I am using seems to have some problem some times .My code is
```
import os
import sys
import time
from urllib import FancyURLopener
import urllib2
import simplejson
# Define search term
searchTerm = "parrot"
# Replace spaces ' ' in search t... | The [Google Image Search API is deprecated](https://developers.google.com/image-search/), you need to use the [Google Custom Search](https://developers.google.com/custom-search/) for what you want to achieve. To fetch the images you need to do this:
```
import urllib2
import simplejson
import cStringIO
fetcher = urll... |
Python - Download Images from google Image search? | 20,716,842 | 11 | 2013-12-21T07:52:07Z | 28,487,500 | 12 | 2015-02-12T20:49:59Z | [
"python",
"web-scraping"
] | I want to download all Images of google image search using python . The code I am using seems to have some problem some times .My code is
```
import os
import sys
import time
from urllib import FancyURLopener
import urllib2
import simplejson
# Define search term
searchTerm = "parrot"
# Replace spaces ' ' in search t... | I have modified my code. Now the code can download 100 images for a given query, and images are full high resolution that is original images are being downloaded.
I am downloading the images using urllib2 & Beautiful soup
from bs4 import BeautifulSoup
import requests
import re
import urllib2
import os
import cookielib... |
How to find a missing number from a list | 20,718,315 | 8 | 2013-12-21T11:05:44Z | 20,718,334 | 10 | 2013-12-21T11:07:45Z | [
"python"
] | How to find the missing number from a sorted list the pythonic way
```
a=[1,2,3,4,5,7,8,9,10]
```
I have come across this [post](http://codereview.stackexchange.com/questions/24520/finding-missing-items-in-an-int-list/) but is there a more easier and efficient way to do this? | ```
>>> a=[1,2,3,4,5,7,8,9,10]
>>> sum(xrange(a[0],a[-1]+1)) - sum(a)
6
```
alternatively (using the sum of AP series formula)
```
>>> a[-1]*(a[-1] + a[0]) / 2 - sum(a)
6
```
For generic cases when multiple numbers may be missing, you can formulate an O(n) approach.
```
>>> a=[1,2,3,4,7,8,10]
>>> from itertools imp... |
MultinomialNB error: "Unknown Label Type" | 20,722,986 | 5 | 2013-12-21T19:59:27Z | 20,724,284 | 10 | 2013-12-21T22:38:38Z | [
"python",
"numpy",
"scikit-learn"
] | I have two numpy arrays, X\_train and Y\_train, where the first of dimensions (700,1000) is populated by the values 0, 1, 2, 3, 4, and 10. The second of dimensions (700,) is populated by the values 'fresh' or 'rotten', since I'm working with Rotten Tomatoes's API. For some reason, when I execute:
```
nb = MultinomialN... | The problems seems to be the dtype of y. looks like numpy didnt manage to figure out it was a string. so it was set to a generic object. If you change:
`Y = np.asarray(critics['fresh'])` to `Y = np.asarray(critics['fresh'], dtype="|S6")` i think it should work. |
Switching to ipython for python3? | 20,723,086 | 6 | 2013-12-21T20:10:15Z | 20,723,126 | 9 | 2013-12-21T20:15:09Z | [
"python",
"ipython"
] | I have python 2.7 and python3 installed on my machine along with ipython. I wanna use Ipython with python3 by default its taking python 2.7. Whats the Process to use ipython with python 3. | Why don't you try this:
```
ipython3
``` |
py.test import error "- 'config' not found." | 20,723,713 | 4 | 2013-12-21T21:24:39Z | 20,731,114 | 7 | 2013-12-22T15:46:23Z | [
"python",
"flask",
"py.test"
] | While trying to add py.test functionality to a Flask API I ran into the following error message when calling py.test on my source directory
```
E ImportStringError: import_string() failed for 'config'. Possible reasons are:
E
E - missing __init__.py in a package;
E ... | I suppose these ones are the most probable
```
E - package or module path not included in sys.path;
E - duplicated package or module name taking precedence in sys.path;
```
So the first thing I'd try is to rename config file to something like `config_default.py`.
Then you can try to use the real ... |
Confusion over time.sleep in Python "while True" loop | 20,723,881 | 4 | 2013-12-21T21:46:05Z | 20,723,928 | 7 | 2013-12-21T21:52:02Z | [
"python",
"signals"
] | Level beginner
I am using python 2.7 version on ubuntu.
I have a confusion regarding a small code snippet in python. I know that `while True` in python means to loop infinitely. I have the following code:
```
#!/usr/bin/env python
import signal
import time
def ctrlc_catcher(signum, frm):
print "Process can't be ... | In the first example you're constantly resetting the alarm. You set an alarm for 1 second from now, then 0.00001 seconds later you set an alarm for 1 second from now, then 0.00001 seconds later you set an alarm for 1 second from now... so the alarm is always 1 second in the future! In the second example, by sleeping, y... |
Ways to invoke python and Spyder on OSX | 20,723,977 | 6 | 2013-12-21T21:57:36Z | 30,033,903 | 18 | 2015-05-04T15:27:54Z | [
"python",
"osx",
"finder",
"spyder",
"anaconda"
] | I recently bought a MacBook and install Python on it via Anaconda. Here's the version information:
```
Python 2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Nov 11 2013, 10:49:09)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
```
I'd like to be able do all of the following:
1. Launch Spyder without having to go through ... | To make spyder callable from Spotlight or Finder:
1. Locate where your spyder executable is by running in Terminal:
```
which spyder
```
This should yield `~/anaconda/bin/spyder` if you installed spyder via Anaconda, `/opt/local/bin/spyder` if you used MacPorts or something similar.
2. Create a file call... |
Pandas Dataframe AttributeError: 'DataFrame' object has no attribute 'design_info' | 20,724,919 | 7 | 2013-12-22T00:18:54Z | 20,726,340 | 10 | 2013-12-22T04:44:12Z | [
"python",
"pandas",
"scipy",
"pickle",
"statsmodels"
] | I am trying to use the `predict()` function of the `statsmodels.formula.api` OLS implementation. When I pass a new data frame to the function to get predicted values for an out-of-sample dataset `result.predict(newdf)` returns the following error: `'DataFrame' object has no attribute 'design_info'`. What does this mean... | Pickling and unpickling of a pandas DataFrame doesn't save and restore attributes that have been attached by a user, as far as I know.
Since the formula information is currently stored together with the DataFrame of the original design matrix, this information is lost after unpickling a Results and Model instance.
If... |
How to check if a string contains only characters from a given set in python | 20,726,010 | 2 | 2013-12-22T03:40:14Z | 20,726,022 | 7 | 2013-12-22T03:42:45Z | [
"python",
"string",
"python-2.5"
] | I have a a user-inputted polynomial and I only want to use it if it only has characters in the string `1234567890^-+x`.
How can I check if it does or not without using external packages? I only want to use built-in Python 2.5 functions.
I am writing a program that runs on any Mac without needing external packages. | Use a regular expression:
```
import re
if re.match('^[-0-9^+x]*$', text):
# Valid input
```
The `re` module comes with Python 2.5, and is your fastest option.
Demo:
```
>>> re.match('^[-0-9^+x]*$', '1x2^4-2')
<_sre.SRE_Match object at 0x10f0b6780>
``` |
How to check if a string contains only characters from a given set in python | 20,726,010 | 2 | 2013-12-22T03:40:14Z | 20,726,077 | 9 | 2013-12-22T03:51:14Z | [
"python",
"string",
"python-2.5"
] | I have a a user-inputted polynomial and I only want to use it if it only has characters in the string `1234567890^-+x`.
How can I check if it does or not without using external packages? I only want to use built-in Python 2.5 functions.
I am writing a program that runs on any Mac without needing external packages. | Here are some odd ;-) ways to do it:
```
good = set('1234567890^-+x')
if set(input_string) <= good:
# it's good
else:
# it's bad
```
or
```
if input_string.strip('1234567890^-+x'):
# it's bad!
else:
# it's good
``` |
Function is_prime - Error | 20,728,274 | 11 | 2013-12-22T10:10:22Z | 20,728,299 | 11 | 2013-12-22T10:13:14Z | [
"python",
"math",
"numbers",
"primes"
] | This is a question from codeacademy.com, where I am learning Python.
So what I want is to define a function that checks if a number is prime.
If it is, return True.
If it isn't, return False.
Here is my code:
```
def is_prime(x):
lst = [] # empty list to put strings 'False' and 'True'
for i in range(2,... | Let's see what happens when you enter `-2`:
* `range(2,-2)` is empty, so the `for` loop never runs.
* Therefore, `lst` is still `[]` after the loop.
* Therefore, `'False' in lst` is `False`
* Therefore, `return True` is executed. |
How the tuple unpacking differ from normal assignment? | 20,729,366 | 8 | 2013-12-22T12:26:06Z | 20,729,637 | 7 | 2013-12-22T12:55:14Z | [
"python",
"python-2.7",
"cpython"
] | From [this link](http://docs.python.org/2/c-api/int.html) i learnt that
> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object
But when I tried to give some example for my se... | Because int is immutable, Python may or may not use exists object, if you save the following code in to a script file, and run it, it will output two True.
```
a, b = 300, 300
print a is b
c = 300
d = 300
print c is d
```
When Python compile the code, it may reuse all the constants. Becasue you input your code in a ... |
NumPy resize method | 20,730,366 | 9 | 2013-12-22T14:21:03Z | 20,730,503 | 9 | 2013-12-22T14:34:50Z | [
"python",
"exception",
"numpy",
"resize"
] | Can anyone explain this to me? (Python 3.3.2, numpy 1.7.1):
```
>>> a = np.array([[1,2],[3,4]])
>>> a # just a peek
array([[1, 2],
[3, 4]])
>>> a.resize(3,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot resize an array references or is referenced
by another arra... | From the [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html) (emphasis mine):
> The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in o... |
Ubuntu 13.10 : No Module Named appindicator | 20,730,487 | 6 | 2013-12-22T14:33:01Z | 20,730,531 | 15 | 2013-12-22T14:38:23Z | [
"python",
"ubuntu",
"appindicator"
] | Appindicator is not available on Ubuntu 13.10?
```
jason@jz:~$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import appindicator
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError... | ```
sudo apt-get install python-appindicator
``` |
Unwrapping a list or map as function arguments in Scala | 20,731,069 | 8 | 2013-12-22T15:42:05Z | 20,731,711 | 9 | 2013-12-22T16:52:25Z | [
"python",
"scala"
] | Is it possible to dynamically unwrap a list/tuple/map items as arguments to a function in Scala? I am looking for a Scala equivalent of Python's `args`/`kwargs`.
For instance, in Python if a function is defined as `def foo(bar1, bar2, bar3=None, bar4=1)` then given a list `x=[1,7]` and a dictionary `y={'bar3':True, 'b... | Just to be clear, the following is valid Python code:
```
def foo(bar1, bar2, bar3=None, bar4=1): print("bar1="+str(bar1)+" bar2="+str(bar2)+" bar3="+str(bar3)+" bar4="+str(bar4))
x=[1,7]
y={'bar3':True, 'bar4':9}
foo(*x,**y)
```
However, there is no analogous Scala syntax. There are some similar things, but the main... |
function not being overridden in child class | 20,732,325 | 2 | 2013-12-22T17:56:48Z | 20,732,345 | 7 | 2013-12-22T17:59:19Z | [
"python",
"inheritance"
] | I have these two classes:
```
class Shape(object):
def __init__(self, start_point, *args):
self.vertices = []
self.__make_vertices(start_point, *args)
def __make_vertices(self, start_point, *args):
print "Not Implemented: __make_vertices"
def __getitem__(self, *args):
retu... | You are missing [name mangling](http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references):
> Any identifier of the form `__spam` (at least two leading underscores, at most one trailing underscore) is textually replaced with `_classname__spam`, where classname is the current class nam... |
Slice indices must be integers or None or have __index__ method | 20,733,156 | 7 | 2013-12-22T19:26:41Z | 20,733,180 | 8 | 2013-12-22T19:28:37Z | [
"python",
"slice"
] | I'm trying something with Python. I want to slice a list (plateau) in several list (L[i]) but I have the following error message:
```
File "C:\Users\adescamp\Skycraper\skycraper.py", line 20, in <module>
item = plateau[debut:fin]
TypeError: slice indices must be integers or None or have an __index__ method
```
... | Your `debut` and `fin` values are floating point values, not integers, because `taille` is a float.
Make those values integers instead:
```
item = plateau[int(debut):int(fin)]
```
Alternatively, make `taille` an integer:
```
taille = int(sqrt(len(plateau)))
``` |
Lock windows workstation using Python | 20,733,441 | 3 | 2013-12-22T19:55:18Z | 20,733,443 | 10 | 2013-12-22T19:55:18Z | [
"python",
"windows"
] | Is there a way to lock the PC from a Python script on Windows?
I do not want to implement some kind of locking on my own - I'd like to use the same lock screen that's also used when the user presses `WIN`+`L` or locks the machine via the start menu. | This can be done with the [`LockWorkStation()`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa376875%28v=vs.85%29.aspx) function from *user32.dll*:
> This function has the same result as pressing Ctrl+Alt+Del and clicking Lock Workstation.
In Python it can be called using using the ctypes/windll FFI from ... |
creating list of random numbers in python | 20,733,827 | 4 | 2013-12-22T20:37:51Z | 20,733,853 | 7 | 2013-12-22T20:40:36Z | [
"python",
"list",
"random"
] | I have initiated a list of known length with zeros. I am trying to go back through the list and put random floating point numbers from 0-1 at each index. I am using a while loop to do this. However, the code is not putting the random numbers in. The list is still full of zeros and I do not understand why. I've inserted... | List is random:
```
>>> randomList
[0.46044625854330556, 0.7259964854084655, 0.23337439854506958, 0.4510862027107614, 0.5306153865653811, 0.8419679084235715, 0.8742117729328253, 0.7634456118593921, 0.5953545552492302, 0.7763910850561638]
```
But you print it's elements as itegers with `"%d" % randomList[index]`, so a... |
Python regular expressions to filter list of strings | 20,734,011 | 10 | 2013-12-22T21:02:18Z | 20,734,025 | 12 | 2013-12-22T21:03:28Z | [
"python",
"regex"
] | I am trying to filter a list of strings with regular expressions, as shown in [this answer](http://stackoverflow.com/questions/3640359/regular-expressions-search-in-list). However the code gives an unexpected result:
```
In [123]: r = re.compile('[0-9]*')
In [124]: string_list = ['123', 'a', '467','a2_2','322','21']
I... | The problem is that your pattern contains the `*`, quantifier, will match *zero* or more digits. So even if the string doesn't contain a digit at all, it will match the pattern. Furthermore, your pattern will match digits wherever they occur in the input string, meaning, `a2` is still a valid match because it *contains... |
Regex Python adding characters after a certain word | 20,735,384 | 7 | 2013-12-22T23:56:00Z | 20,735,396 | 11 | 2013-12-22T23:57:22Z | [
"python",
"regex"
] | I have a text file and every time that the word "get" occurs I need to insert an `@` sign after it.
In Python how do I add a character after a specific word using regex? Right now I am parsing the line word by word and I don't understand regex enough to write the code. | Use `re.sub()` to provide replacements, using a backreference to re-use matched text:
```
import re
text = re.sub(r'(get)', r'\1@', text)
```
The `(..)` parenthesis mark a group, which `\1` refers to when specifying a replacement. So `get` is replaced by `get@`.
Demo:
```
>>> import re
>>> text = 'Do you get it ye... |
Making a function that will identify an infinite loop in existing code | 20,735,680 | 2 | 2013-12-23T00:49:19Z | 20,735,690 | 8 | 2013-12-23T00:51:32Z | [
"python",
"infinite-loop",
"halting-problem"
] | I'm trying to create a function that will identify if the code in a python file will go through and infinite loop or not. This is what I have so far:
```
def reader(filename):
myfile = open(filename)
counter = 0
#counters the number of lines in the file
for line in myfile:
counter +=1
... | This is impossible. Read up on the [halting problem](https://en.wikipedia.org/wiki/Halting_problem).
Also, even if it were possible in theory, or even if you just want to do some sort of heuristic guess, you obviously can't do it by just running the file. If the program has an infinite loop, you will run the infinite ... |
Python: How to read a text file containing co-ordinates in row-column format into x-y co-ordinate arrays? | 20,735,922 | 5 | 2013-12-23T01:32:01Z | 20,735,946 | 7 | 2013-12-23T01:36:58Z | [
"python",
"coordinates"
] | I have a text file with numbers stored in the following format:
```
1.2378 4.5645
6.789 9.01234
123.43434 -121.0212
```
... and so on.
I wish to read these values into two arrays, one for x co-ordinates and the other for y co-ordinates. Like, so
```
x[0] = 1.2378
y[0] = 4.5645
x[1] = 6.789
y[1] = 9.01234
```
... | One method:
```
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
```
where f is the file object (from open() for instance)
You could also use the csv library
```
import csv
with open('filename','r') as f:
reader = csv.reader(f,delimeter=' ')
for row in reader:
x... |
How to iterate over two dictionaries at once and get a result using values and keys from both | 20,736,709 | 3 | 2013-12-23T03:47:27Z | 20,736,773 | 10 | 2013-12-23T03:57:21Z | [
"python",
"loops"
] | ```
def GetSale():#calculates expected sale value and returns info on the stock with highest expected sale value
global Prices
global Exposure
global cprice
global bprice
global risk
global shares
global current_highest_sale
best_stock=' '
for value in ... | The question is a bit vague, but answering the title, you can get both keys and values at the same time like this:
```
>>> d = {'a':5, 'b':6, 'c': 3}
>>> d2 = {'a':6, 'b':7, 'c': 3}
>>> for (k,v), (k2,v2) in zip(d.items(), d2.items()):
print k, v
print k2, v2
a 5
a 6
c 3
c 3
b 6
b 7
``` |
Reading a cell value that contains a formula returns 0.0 when using xlrd | 20,736,814 | 7 | 2013-12-23T04:03:39Z | 24,126,789 | 7 | 2014-06-09T18:44:21Z | [
"python",
"xlrd"
] | I try to read a cell value, say E5 and E5 in the excel sheet contains a formula '**=(A29 - A2)**'. I use the following code and it returns me 0.00 instead of the actual value **1.440408**
. Is there a way to solve this? I want to print the correct value. Please help me with this. Thank you.
```
book = xlrd.open_workbo... | **Excel files store formulas and values independently.** If the files are saved directly by Excel, then Excel will write both. However, files generated by other software, such as xlwt, OpenPyXL, and XlsxWriter, *only write the formula*. This is because there is no guarantee that a third-party package will be able to ev... |
Concatenate elements of a tuple in a list in python | 20,736,917 | 13 | 2013-12-23T04:18:56Z | 20,736,978 | 15 | 2013-12-23T04:26:52Z | [
"python",
"string",
"list",
"tuples",
"concatenation"
] | I have a list of tuples that has strings in it
For instance:
```
[('this', 'is', 'a', 'foo', 'bar', 'sentences')
('is', 'a', 'foo', 'bar', 'sentences', 'and')
('a', 'foo', 'bar', 'sentences', 'and', 'i')
('foo', 'bar', 'sentences', 'and', 'i', 'want')
('bar', 'sentences', 'and', 'i', 'want', 'to')
('sentences', 'and',... | For a lot of data, you should consider whether you *need* to keep it all in a list. If you are processing each one at a time, you can create a generator that will yield each joined string, but won't keep them all around taking up memory:
```
new_data = (' '.join(w) for w in sixgrams)
```
if you can get the original t... |
Attach a calculated column to an existing dataframe | 20,737,811 | 5 | 2013-12-23T06:03:23Z | 20,740,973 | 10 | 2013-12-23T09:53:58Z | [
"python",
"pandas"
] | I am starting to learn Pandas, and I was following the question [here](http://stackoverflow.com/questions/20724455/new-cumulative-value-col-derived-from-existing-col-in-a-pandas-dataframe) and could not get the solution proposed to work for me and I get an indexing error. This is what I have
```
from pandas import *
i... | The problem is, as the Error message says, that the index of the calculated column you want to insert is incompatible with the index of `df`.
The index of `df` is a simple index:
```
In [8]: df.index
Out[8]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype='int64')
```
while the index of the calculated column is a Mult... |
getting seconds from numpy timedelta64 | 20,738,357 | 11 | 2013-12-23T06:49:39Z | 20,739,897 | 13 | 2013-12-23T08:46:22Z | [
"python",
"numpy",
"pandas"
] | I have a datetime index in pandas
```
index = np.array(['2013-11-11T12:36:00.078757888-0800',
'2013-11-11T12:36:03.692692992-0800',
'2013-11-11T12:36:07.085489920-0800',
'2013-11-11T12:36:08.957488128-0800'], dtype='datetime64[ns]')
```
I want to calculate the tim... | Your own answer is correct and good. Slightly different way is to specify scale constants with `timedelta` expression.
For example, to scale to seconds:
```
>>> np.diff(index)/np.timedelta64(1, 's')
array([ 3.6139351 , 3.39279693, 1.87199821])
```
To minutes:
```
>>> np.diff(index)/np.timedelta64(1, 'm')
array([ ... |
While testing python max recursion depth, why am I hitting RuntimeError multiple times? | 20,740,283 | 6 | 2013-12-23T09:11:35Z | 20,740,589 | 7 | 2013-12-23T09:30:40Z | [
"python",
"cpython"
] | I was trying to experimentally determine Python's maximum recursion depth with the following code:
```
def recursive(i):
i = i + 1
try:
recursive(i)
except RuntimeError:
print 'max depth == %d' % i
exit(0)
recursive(0)
```
But when I ran it, this happened:
```
[ hive ~ ]$ python ... | You are using the [`exit()` function the Python `site` module sets](http://docs.python.org/2/library/constants.html#constants-added-by-the-site-module) for use in the interactive interpreter.
This is **Python code** you are calling, not C code. This triggers the recursion depth exception handler a few more times until... |
Understanding Multiprocessing: Shared Memory Management, Locks and Queues in Python | 20,742,637 | 28 | 2013-12-23T11:30:34Z | 24,787,346 | 24 | 2014-07-16T17:44:44Z | [
"python",
"locking",
"multiprocessing",
"python-multiprocessing"
] | [Multiprocessing](https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing) is a powerful tool in python, and I want to understand it more in depth.
I want to know when to use *regular* [Locks](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Lock) and [Queues](https://docs.py... | `multiprocessing.Lock` is implemented using a Semaphore object provided by the OS. On Linux, the child just inherits a handle to the Semaphore from the parent via `os.fork`. This isn't a copy of the semaphore; it's actually inheriting the same handle the parent has, the same way file descriptors can be inherited. Windo... |
SQLAlchemy create_all() does not create tables | 20,744,277 | 16 | 2013-12-23T13:09:19Z | 20,749,534 | 27 | 2013-12-23T18:55:48Z | [
"python",
"postgresql",
"sqlalchemy"
] | I'm trying to integrate PostgreSQL and SQLAlchemy but SQLAlchemy.create\_all() is not creating any tables from my models.
My code:
```
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_ap... | You should put your model class before `create_all()` call, like this:
```
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.Stri... |
Looping through and appending a list of names | 20,744,989 | 3 | 2013-12-23T13:53:40Z | 20,745,004 | 10 | 2013-12-23T13:55:00Z | [
"python",
"for-loop",
"python-3.x"
] | I'm writing a program that keeps asking the user to enter names until the word END is entered,
at which point it prints out the list of names.
The code:
```
import getpass
import time
import sys
print("Welcome " + getpass.getuser() + "...")
time.sleep(0.25)
print("This program, powered by Python, it will ask you to e... | It occurs because the variable `names` is empty *thus there's nothing to iterate over*
So use a while loop instead:
```
while True:
name = input("Please enter a name: ")
if name == "END":
print(names)
break
names.append(name)
```
Note: To exit a loop use `break` instead of `sys.exit()`... |
ValueError: malformed string when using ast.literal_eval | 20,748,202 | 13 | 2013-12-23T17:22:19Z | 20,748,308 | 16 | 2013-12-23T17:29:46Z | [
"python",
"python-2.7",
"python-3.x"
] | It is widely known that using `eval()` is a potential security risk so the use of [`ast.literal_eval(node_or_string)`](http://docs.python.org/2/library/ast.html#ast.literal_eval) is promoted
However In python 2.7 it returns `ValueError: malformed string` when running this example:
```
>>> ast.literal_eval("4 + 9")
``... | The reason this doesnât work on Python 2 lies in its implementation of `literal_eval`. For some odd reasons, the only actual number evaluation `literal_eval` supports is addition and subtraction where the right operand is a complex number.
This was changed in Python 3 so that it supports any kind of valid number exp... |
PyQt5 failing import of QtGui | 20,749,819 | 6 | 2013-12-23T19:19:36Z | 20,752,155 | 11 | 2013-12-23T22:31:05Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5"
] | I've just moved from PyQt4 to 5 and I'm having an issue with QtGui. I installed using the 32bit windows installer, not my own build.
when I do:
```
from PyQt5 import QtGui
```
I get
```
class MainWindow(QtGui.QMainWindow, UI.MainUI.Ui_MainWindow):
AttributeError: 'module' object has no attribute 'QMainWindow'
```
... | Assuming everything was installed correctly, you need to adjust your imports slightly to port from PyQt4 to PyQt5.
The main GUI elements are in the QtWidgets module, whilst the more basic GUI elements are in QtGui. See the [Qt modules page](https://qt-project.org/doc/qt-5/qtmodules.html) for more details.
The example... |
filling gaps on an image using numpy and scipy | 20,753,288 | 8 | 2013-12-24T00:36:34Z | 20,755,876 | 7 | 2013-12-24T06:17:58Z | [
"python",
"image-processing",
"numpy",
"scipy"
] | The image (test.tif) is attached.
The np.nan values are the whitest region.
How to fill those whitest region using some gap filling algorithms that uses values from the neighbours?
> 
```
import scipy.ndimage
data = ndimage.imread('test.tif')
``` | If you want values from the nearest neighbors, you could use the [NearestNDInterpolator](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.NearestNDInterpolator.html#scipy.interpolate.NearestNDInterpolator) from scipy.interpolate. There are also [other interpolators](http://docs.scipy.org/doc/scipy/... |
filling gaps on an image using numpy and scipy | 20,753,288 | 8 | 2013-12-24T00:36:34Z | 20,943,818 | 17 | 2014-01-06T05:50:30Z | [
"python",
"image-processing",
"numpy",
"scipy"
] | The image (test.tif) is attached.
The np.nan values are the whitest region.
How to fill those whitest region using some gap filling algorithms that uses values from the neighbours?
> 
```
import scipy.ndimage
data = ndimage.imread('test.tif')
``` | As others have suggested, scipy.interpolate can be used. However, it requires fairly extensive index manipulation to get this to work.
Complete example:
```
from pylab import *
import numpy
import scipy.ndimage
import scipy.interpolate
import pdb
data = scipy.ndimage.imread('data.png')
# a boolean array of (width, ... |
How can I use the fields_to_export attribute in BaseItemExporter to order my Scrapy CSV data? | 20,753,358 | 11 | 2013-12-24T00:47:38Z | 20,758,558 | 16 | 2013-12-24T09:47:01Z | [
"python",
"csv",
"scrapy"
] | I have made a simple [Scrapy](http://doc.scrapy.org/en/latest/index.html) spider that I use from the command line to export my data into the CSV format, but the order of the data seem random. How can I order the CSV fields in my output?
I use the following command line to get CSV data:
```
scrapy crawl somwehere -o i... | To use such exporter you need to create your own Item pipeline that will process your spider output. Assuming that you have simple case and you want to have all spider output in one file this is pipeline you should use (`pipelines.py`):
```
from scrapy import signals
from scrapy.contrib.exporter import CsvItemExporter... |
Why is the id of a Python class not unique when called quickly? | 20,753,364 | 23 | 2013-12-24T00:48:30Z | 20,753,425 | 23 | 2013-12-24T00:57:32Z | [
"python",
"class",
"python-3.x"
] | I'm doing some things in python (Using python 3.3.3), and I came across something that is confusing me since to my understanding class's get a new id each time they are called.
Lets say you have this in some .py file:
```
class someClass: pass
print(someClass())
print(someClass())
```
The above returns the same ... | The `id` of an object is only guaranteed to be unique *during that object's lifetime*, not over the entire lifetime of a program. The two `someClass` objects you create only exist for the duration of the call to `print` - after that, they are available for garbage collection (and, in CPython, deallocated immediately). ... |
Why is the id of a Python class not unique when called quickly? | 20,753,364 | 23 | 2013-12-24T00:48:30Z | 20,753,450 | 11 | 2013-12-24T01:00:59Z | [
"python",
"class",
"python-3.x"
] | I'm doing some things in python (Using python 3.3.3), and I came across something that is confusing me since to my understanding class's get a new id each time they are called.
Lets say you have this in some .py file:
```
class someClass: pass
print(someClass())
print(someClass())
```
The above returns the same ... | If you read the documentation for [`id`](http://docs.python.org/3/library/functions.html#id), it says:
> Return the âidentityâ of an object. **This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same `id()` va... |
Default fonts in Seaborn statistical data visualization in iPython | 20,753,782 | 8 | 2013-12-24T01:49:47Z | 20,768,282 | 12 | 2013-12-25T01:17:33Z | [
"python",
"fonts",
"matplotlib",
"seaborn"
] | After multiple problems trying to run [stanford.edu/~mwaskom/software/seaborn/](http://stanford.edu/~mwaskom/software/seaborn/) in Anaconda and Enthought for Mac (many problems with dependencies and versions), I was able to run it from an Enthought virtual environment in Ubuntu (running on VirtualBox).
Following some ... | As Joe notes, Arial isn't installed on Ubuntu by default, but it's easy to install. This is what I do for testing on Travis, which is an Ubuntu environment:
```
sudo apt-get install msttcorefonts -qq
```
Seaborn also exposes the font option at the top level of the style control, so you could also easily use one that'... |
Separating a String | 20,754,857 | 22 | 2013-12-24T04:27:01Z | 20,754,984 | 15 | 2013-12-24T04:42:42Z | [
"python",
"permutation",
"itertools"
] | Given a string, I want to generate all possible combinations. In other words, all possible ways of putting a comma somewhere in the string.
For example:
```
input: ["abcd"]
output: ["abcd"]
["abc","d"]
["ab","cd"]
["ab","c","d"]
["a","bc","d"]
["a","b","cd"]
["a","bcd"... | How about something like:
```
from itertools import combinations
def all_splits(s):
for numsplits in range(len(s)):
for c in combinations(range(1,len(s)), numsplits):
split = [s[i:j] for i,j in zip((0,)+c, c+(None,))]
yield split
```
after which:
```
>>> for x in all_splits("abcd... |
Separating a String | 20,754,857 | 22 | 2013-12-24T04:27:01Z | 20,755,019 | 15 | 2013-12-24T04:48:03Z | [
"python",
"permutation",
"itertools"
] | Given a string, I want to generate all possible combinations. In other words, all possible ways of putting a comma somewhere in the string.
For example:
```
input: ["abcd"]
output: ["abcd"]
["abc","d"]
["ab","cd"]
["ab","c","d"]
["a","bc","d"]
["a","b","cd"]
["a","bcd"... | You can certainly use `itertools` for this, but I think it's easier to write a recursive generator directly:
```
def gen_commas(s):
yield s
for prefix_len in range(1, len(s)):
prefix = s[:prefix_len]
for tail in gen_commas(s[prefix_len:]):
yield prefix + "," + tail
```
Then
```
pr... |
python not strict type check for bool | 20,756,199 | 2 | 2013-12-24T06:45:58Z | 20,756,275 | 7 | 2013-12-24T06:51:38Z | [
"python"
] | I have always read that python has strict type checks -
```
>>> 1 + 'hello'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
```
This is fine since we cannot add int to a string
But why is the following allowed ?
```
>>> True + Fa... | ```
>>> issubclass(bool, int)
True
```
That explains everything. That is, `bool` is a subclass of `int`. That's why you can use a `bool` anywhere an `int` is allowed.
For a lot of detail, [see the PEP that introduced the type](http://www.python.org/dev/peps/pep-0285/).
**EDIT: gloss**
Note that Python didn't have a... |
Python : Trying to POST form using requests | 20,759,981 | 8 | 2013-12-24T11:18:56Z | 20,760,055 | 20 | 2013-12-24T11:24:59Z | [
"python",
"python-requests"
] | I'm trying to login a website for some scraping using Python and requests library, i am trying the following (which doesn't work):
```
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
In [12]: r = requests.post('https://admin.example.com/login.php',head... | You can use the [Session](http://docs.python-requests.org/en/latest/user/advanced/#session-objects) object
```
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
session = requests.Session()
session.post('https://admin.example.com/login.php',headers=heade... |
How can I save a variable inside a definition in python? | 20,760,595 | 3 | 2013-12-24T12:02:37Z | 20,760,717 | 8 | 2013-12-24T12:10:36Z | [
"python"
] | I have the following code:
```
def thingy(res)
if res=="food":
res=0
if res=="wood":
res=1
if res=="metal":
res=2
if res=="gold":
res=3
if res=="oil":
res=3
res="food"
thingy(res)
print(res)
```
When I run this it comes up with "food" when i want it to s... | You need to return the value, and why not to use `dictionary` instead of all the `if` statements, They are the best for this kind of problems:
**Example:**
```
def thingy(res):
myOptions = {'food':0, 'wood':1, 'metal': 2, 'gold': 3, 'oil': 3}
return myOptions[res]
res = "food"
res = thingy(res)
print(res)
``... |
convert only non-empty list to tuple in a list of lists | 20,761,132 | 3 | 2013-12-24T12:40:19Z | 20,761,248 | 10 | 2013-12-24T12:47:58Z | [
"python",
"list",
"python-3.x",
"tuples"
] | how do i convert this:
```
[[], [], [('ef', 1)], [], [('cd', 3)], [('ab', 2)]]
```
into this:
```
[[], [], ['ef', 1], [], ['cd', 3], ['ab', 2]]
```
i understand that to convert a tuple into a list, we would simply use list(tuple), or if it is a list like [(1,2),(3,4)] we can use map. How would i do this with the tu... | ```
>>> my_list = [[], [], [('ef', 1)], [], [('cd', 3)], [('ab', 2)]]
>>> [list(*el) for el in my_list]
[[], [], ['ef', 1], [], ['cd', 3], ['ab', 2]]
``` |
What's the correct way to sort Python `import x` and `from x import y` statements? | 20,762,662 | 66 | 2013-12-24T14:37:57Z | 20,762,915 | 7 | 2013-12-24T15:01:11Z | [
"python",
"coding-style",
"python-import",
"pep8"
] | The [python style guide](http://www.python.org/dev/peps/pep-0008/#imports) suggests to group imports like this:
> Imports should be grouped in the following order:
>
> 1. standard library imports
> 2. related third party imports
> 3. local application/library specific imports
However, it does not mention anything how... | The PEP 8 says nothing about it indeed. There's no convention for this point, and it doesn't mean the Python community need to define one absolutely. A choice can be better for a project but the worst for another... It's a question of preferences for this, since each solutions has pro and cons. But if you want to follo... |
What's the correct way to sort Python `import x` and `from x import y` statements? | 20,762,662 | 66 | 2013-12-24T14:37:57Z | 20,763,446 | 37 | 2013-12-24T15:48:50Z | [
"python",
"coding-style",
"python-import",
"pep8"
] | The [python style guide](http://www.python.org/dev/peps/pep-0008/#imports) suggests to group imports like this:
> Imports should be grouped in the following order:
>
> 1. standard library imports
> 2. related third party imports
> 3. local application/library specific imports
However, it does not mention anything how... | Imports are generally sorted alphabetically and described in various places beside PEP 8.
**Alphabetically sorted modules are quicker to read and searchable**. After all python is all about readability.
Also It is easier to verify that something is imported, and avoids duplicated imports
There is nothing available in... |
Creating raw socket in Python without root privileges | 20,763,039 | 6 | 2013-12-24T15:10:55Z | 20,763,318 | 7 | 2013-12-24T15:37:55Z | [
"python",
"sockets",
"raw-sockets"
] | Is it possible to create a raw socket without root privileges? If not, can a script elevate its privileges itself?
I wrote a Python script using a raw socket:
```
#!/usr/bin/env python
import socket
rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
print "Worked!"
```
Running it wit... | As you noted raw sockets require higher privilege than a regular user have.
You can circumvent this issue in two ways:
1. Activating the SUID bit for the file with a command like `chmod +s file` and set its owner to `root` with `chown root.root file`. This will run your script as root, regardless of the effective user... |
Writing gimp plugins in python on windows- how do i debug? where is the output? | 20,763,448 | 12 | 2013-12-24T15:48:58Z | 20,906,193 | 13 | 2014-01-03T14:46:09Z | [
"python",
"gimp",
"gimpfu"
] | EDITED HEAVILY with some new information (and a bounty)
I am trying to create a plug in in python for gimp. (on windows)
this page <http://gimpbook.com/scripting/notes.html> suggests running it from the shell, or looking at ~/.xsession-errors
neither work.
I am able to run it from the cmd shell, as
> gimp-2.8.exe -c... | > 1- can i refresh a plugin without restarting gimp ? (so at least my
> slow-morph will be faster )
You must restart GIMP when you add a script or change register().
No need to restart when changing other parts of the script -- it runs as a separate process and will be re-read from disk each time.
helpful source:
<ht... |
flask Set Cookie for every response | 20,764,566 | 2 | 2013-12-24T17:20:00Z | 20,765,853 | 10 | 2013-12-24T19:23:35Z | [
"python",
"session",
"cookies",
"flask"
] | I use flask session in my app. In one of my handler I set session value and no session set in other handlers. But I found that in every response there is a http header: `Set Cookie` exists. Why does that happen?
```
app = Flask(__name__)
app.secret_key = r"A0Zr98j/3yX R~XHH!jmN'LWX/,?RT"
@app.route('/auth/login', met... | # The Short Answer:
This is by design, but a recent change in Flask allows you to change this behavior through use of the `SESSION_REFRESH_EACH_REQUEST` option. As of the posting of this answer, that option is not yet in a stable release of Flask.
# The Long Answer
Let's back up and discuss how cookies are supposed ... |
Python re.sub back reference not back referencing | 20,765,265 | 11 | 2013-12-24T18:24:07Z | 20,765,286 | 27 | 2013-12-24T18:26:54Z | [
"python",
"regex"
] | I have the following:
```
<text top="52" left="20" width="383" height="15" font="0"><b>test</b></text>
```
and I have the following:
```
fileText = re.sub("<b>(.*?)</b>", "\1", fileText, flags=re.DOTALL)
```
In which fileText is the string I posted above. When I print out `fileText` after I run the regex replacemen... | You need to use a [raw-string](http://docs.python.org/2/reference/lexical_analysis.html#string-literals) here so that the backslash isn't processed as an escape character:
```
>>> import re
>>> fileText = '<text top="52" left="20" width="383" height="15" font="0"><b>test</b></text>'
>>> fileText = re.sub("<b>(.*?)</b>... |
Flask-login not redirecting to previous page | 20,766,291 | 5 | 2013-12-24T20:09:54Z | 20,766,483 | 11 | 2013-12-24T20:34:47Z | [
"python",
"redirect",
"login",
"flask",
"flask-login"
] | I have seen quite a few questions with this in mind, but haven't been able to address my issue. I have a Flask app with flask-login for session management. And, when I try to view a page without logging in, I get redirected to a link in form of `/login/?next=%2Fsettings%2F`
The issue is, as far as I could have it unde... | [`request.path`](http://flask.pocoo.org/docs/api/?highlight=request.path#flask.Request.path) is not what you're looking for. It returns the actual path of the URL. So, if your URL is `/a/?b=c`, then `request.path` returns `/a`, not `c` as you are expecting.
The `next` parameter is after the `?` in the URL, thus it is ... |
What benefit is added by using Gunicorn + Nginx + Flask? | 20,766,684 | 8 | 2013-12-24T21:00:26Z | 20,766,961 | 9 | 2013-12-24T21:31:56Z | [
"python",
"nginx",
"flask",
"gunicorn"
] | I see people are running setups like Nginx + Gunicorn + Flask.
Can someone explain what is the benefit of having Gunicorn in front of Flask? Why not just have Flask running? Doesn't it consume more resources having Gunicorn + Flask running? Is it able to reboot the flask instance when it fails to respond?
What's also... | I think you may be confused, Flask is not a **web server**, it is a framework and needs some sort of web server, such as Gunicorn, Nginx or Apache, to accept HTTP requests which it will then operate on. The reason why people run Nginx and Gunicorn together is that in addition to being a web server, Nginx can also proxy... |
How to convert signed to unsigned integer in python | 20,766,813 | 27 | 2013-12-24T21:14:54Z | 20,766,849 | 7 | 2013-12-24T21:19:14Z | [
"python",
"integer",
"unsigned",
"signed"
] | Let's say I have this number `i = -6884376`.
How do I refer to it as to an unsigned variable?
Something like `(unsigned long)i` in C. | Python doesn't have builtin unsigned types. You can use mathematical operations to compute a *new* int representing the value you would get in C, but there is no "unsigned value" of a Python int. The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer. |
How to convert signed to unsigned integer in python | 20,766,813 | 27 | 2013-12-24T21:14:54Z | 20,766,900 | 25 | 2013-12-24T21:24:20Z | [
"python",
"integer",
"unsigned",
"signed"
] | Let's say I have this number `i = -6884376`.
How do I refer to it as to an unsigned variable?
Something like `(unsigned long)i` in C. | To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if `unsigned long` is 32 bit:
```
>>> i = -6884376
>>> i & 0xffffffff
4288082920
```
or if it is 64 bit:
```
>>> i & 0xffffffffffffffff
18446744073702667240
```
Do be aware though that although that gives you the value you ... |
How to convert signed to unsigned integer in python | 20,766,813 | 27 | 2013-12-24T21:14:54Z | 20,768,199 | 39 | 2013-12-25T00:59:16Z | [
"python",
"integer",
"unsigned",
"signed"
] | Let's say I have this number `i = -6884376`.
How do I refer to it as to an unsigned variable?
Something like `(unsigned long)i` in C. | **Assuming**:
1. You have 2's-complement representations in mind; and,
2. By `(unsigned long)` you *mean* unsigned 32-bit integer,
then you just need to add `2**32 (or 1 << 32)` to the negative value.
For example, apply this to -1:
```
>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b111111111111111111111111111111... |
Why can't I assign python's print to a variable? | 20,767,402 | 7 | 2013-12-24T22:31:15Z | 20,767,411 | 18 | 2013-12-24T22:32:29Z | [
"python",
"python-2.7",
"function-pointers",
"variable-assignment"
] | I'm learning to program and I am using Python to start. In there, I see that I can do something like this:
```
>>>> def myFunction(): return 1
>>>> test = myFunction
>>>> test()
1
```
However, if I try and do the same with `print` it fails:
```
>>>> test2 = print
File "<stdin>", line 1
test2 = print
... | [`print` is a statement](http://docs.python.org/2/reference/simple_stmts.html#the-print-statement), not a function. This was [changed in Python 3](http://www.python.org/dev/peps/pep-3105/) partly to allow you to do things like this. In Python 2.7 you can get print as a function by doing `from __future__ import print_fu... |
Django Query sort case-insensitive using Model method with PostgreSQL | 20,768,955 | 2 | 2013-12-25T04:06:43Z | 29,636,097 | 14 | 2015-04-14T19:45:36Z | [
"python",
"django",
"python-2.7",
"django-1.5",
"postgresql-9.3"
] | I'm really new to django, python and postgres... I can't seem to find the answer on how to order\_by being case insensitive while using Model as the query method, only if you use direct SQL queries.
```
Model
@classmethod
def get_channel_list(cls, account):
return cls.objects.filter(accountid=account).order_by('-n... | With django 1.8, there is a built-in solution:
```
from django.db.models.functions import Lower
...
ret = ret.order_by(Lower('name_lower'))
ret = ret.order_by(Lower('name_lower').asc())
ret = ret.order_by(Lower('name_lower').desc())
``` |
fitting multivariate curve_fit in python | 20,769,340 | 9 | 2013-12-25T05:26:34Z | 20,775,121 | 11 | 2013-12-25T17:15:47Z | [
"python",
"scipy",
"curve-fitting"
] | I'm trying to fit a simple function to two arrays of independent data in python. I understand that I need to bunch the data for my independent variables into one array, but something still seems to be wrong with the way I'm passing variables when I try to do the fit. (There are a couple previous posts related to this o... | N and M are defined in [the help](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) for the function. N is the number of data points and M is the number of parameters. Your error therefore basically means you need at least as many data points as you have parameters, which makes perfect ... |
How to detect a Christmas Tree? | 20,772,893 | 295 | 2013-12-25T12:40:55Z | 20,779,498 | 134 | 2013-12-26T05:15:19Z | [
"c++",
"python",
"opencv",
"image-processing",
"computer-vision"
] | Which image processing techniques could be used to implement an application that detects the christmas trees displayed in the following images?




 process each tree image individually, as requested in the requirements, (ii) to consider both object brightness and shape in order to improve the quality of the result.
---
Below is presented an approach that takes in consideration the object brightness and shape. In other wor... |
How to detect a Christmas Tree? | 20,772,893 | 295 | 2013-12-25T12:40:55Z | 20,788,323 | 70 | 2013-12-26T16:59:41Z | [
"c++",
"python",
"opencv",
"image-processing",
"computer-vision"
] | Which image processing techniques could be used to implement an application that detects the christmas trees displayed in the following images?








. The **lighted tree area is more "energetic" and has higher intensity**.
The process is as follows:
1. Convert to gra... |
How to detect a Christmas Tree? | 20,772,893 | 295 | 2013-12-25T12:40:55Z | 20,794,680 | 55 | 2013-12-27T04:21:33Z | [
"c++",
"python",
"opencv",
"image-processing",
"computer-vision"
] | Which image processing techniques could be used to implement an application that detects the christmas trees displayed in the following images?









3. Apply morphological dilation to the mask to connect disconnected areas
4. Discard small areas and horizontal blocks (remember trees are verti... |
How to detect a Christmas Tree? | 20,772,893 | 295 | 2013-12-25T12:40:55Z | 20,805,935 | 54 | 2013-12-27T18:33:58Z | [
"c++",
"python",
"opencv",
"image-processing",
"computer-vision"
] | Which image processing techniques could be used to implement an application that detects the christmas trees displayed in the following images?




.
At the heart of the ... |
How to detect a Christmas Tree? | 20,772,893 | 295 | 2013-12-25T12:40:55Z | 20,850,922 | 124 | 2013-12-31T02:40:10Z | [
"c++",
"python",
"opencv",
"image-processing",
"computer-vision"
] | Which image processing techniques could be used to implement an application that detects the christmas trees displayed in the following images?




![](https:... | I have an approach which I think is interesting and a bit different from the rest. The main difference in my approach, compared to some of the others, is in how the image segmentation step is performed--I used the [DBSCAN](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSC... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.