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 |
|---|---|---|---|---|---|---|---|---|---|
fibonacci works in python but fails in Java | 21,585,932 | 20 | 2014-02-05T18:50:56Z | 21,589,234 | 9 | 2014-02-05T21:47:57Z | [
"java",
"python",
"fibonacci"
] | I have this code for calculating `fibonacci` number in `python`. It works and gives the expected result. but when I translated the same to `Java`, it fails. Any idea of what is going wrong here?
In `python`:
```
def fib3(n):
a,b=0,1
while n>0:
a,b=b,a+b
n-=1
return a
```
`fib3(12) --> 144`
In `Ja... | The issue is that you've got to one value from `b` to `a` ***at the same time*** as assigning to `b` the sum of `a` and `b`. Get that simultaneous swap wrong and you get the wrong answer.
In the spirit of the Python code, I present:
```
public static int fib(int n) {
int a = 0, b = 1;
while (n-->0)
b ... |
Simple guestbook django: __init__() takes 1 positional argument but 2 were given | 21,586,883 | 9 | 2014-02-05T19:39:57Z | 21,587,097 | 22 | 2014-02-05T19:51:38Z | [
"python",
"django"
] | I'm new to Django and trying to make a simple guestbook application to get used to the environment. I get the following mistake, but I can't locate the error:
**Exception Value: \_*init*\_() takes 1 positional argument but 2 were given.**
```
from django.db import models
from django.contrib.auth.models import User
fr... | In your urls.py:
You are missing .as\_view()
change it to:
```
(r"^(\d+)/$", Gastenboek.views.BerichtListView.as_view()),
(r"", Gastenboek.views.BerichtListView.as_view()),
``` |
passing a variable with colon in function python | 21,587,675 | 4 | 2014-02-05T20:22:09Z | 21,587,800 | 8 | 2014-02-05T20:28:10Z | [
"python",
"bulbs"
] | I am using this api.. whose function call looks like:
```
g.vertices.index.lookup(identifier="value")
```
Now note that idenitifier is a variable which I have not defined but is resoluted by api and value is a string.
Something similar happens in pymongo api:
<http://api.mongodb.org/python/current/tutorial.html>
``... | ```
g.vertices.index.lookup(**{"bad:identifier":"value"})
```
may work ... this is known as unpacking keyword arguments |
pandas join DataFrame force suffix? | 21,588,811 | 6 | 2014-02-05T21:22:46Z | 21,589,330 | 10 | 2014-02-05T21:52:35Z | [
"python",
"pandas"
] | How can I force a suffix on a merge or join. I understand it's possible to provide one if there is a collision but in my case I'm merging df1 with df2 which doesn't cause any collision but then merging again on df2 which uses the suffixes but I would prefer for each merge to have a suffix because it gets confusing if I... | You could force a suffix on the actual DataFrame:
```
In [11]: df_a = pd.DataFrame([[1], [2]], columns=['A'])
In [12]: df_b = pd.DataFrame([[3], [4]], columns=['B'])
In [13]: df_a.join(df_b)
Out[13]:
A B
0 1 3
1 2 4
```
By appending to it's column's names:
```
In [14]: df_a.columns = df_a.columns.map(lamb... |
Possible to have ``a < b and not(a - b < 0)`` with floats | 21,590,883 | 6 | 2014-02-05T23:28:42Z | 21,591,038 | 8 | 2014-02-05T23:38:56Z | [
"python",
"floating-point"
] | Is
`a < b and not(a - b < 0)`
possible for floating points due to floating point round of error?
Is there an example? | It depends on the floating point format, and specifically whether it has [gradual underflow](http://en.wikipedia.org/wiki/Arithmetic_underflow). IEEE 754 binary floating point does. That means the gap between two distinct floats is always non-zero, even if it can only be represented with one significant bit in the extr... |
Possible to have ``a < b and not(a - b < 0)`` with floats | 21,590,883 | 6 | 2014-02-05T23:28:42Z | 21,637,817 | 9 | 2014-02-07T21:10:27Z | [
"python",
"floating-point"
] | Is
`a < b and not(a - b < 0)`
possible for floating points due to floating point round of error?
Is there an example? | [This answer is intended as a pedant's supplement to the fine answer already given by Patricia Shanahan. That answer covers the normal case; here we're worrying about edge cases that you're unlikely to encounter in practice.]
Yes, it is perfectly possible. Here's a Python session from my very ordinary, Intel-based Mac... |
How do I get logger to delete existing log file before writing to it again? | 21,591,748 | 13 | 2014-02-06T00:40:41Z | 21,591,806 | 14 | 2014-02-06T00:46:37Z | [
"python",
"logging",
"filehandler"
] | Using the configuration below, my logfile will be called 'test-debug.log' and it will grow infinitely for everytime I run the script. I just want this logfile to contain the log records from the most recent run of the script. The log should be deleted before starting again.
How do I do that?
```
logger = logging.getL... | Try this:
```
filehandler_dbg = logging.FileHandler(logger.name + '-debug.log', mode='w')
```
to open the filename in `write` mode instead of `append` mode, clobbering `logger.name`
More information: [logging.FileHandler](http://docs.python.org/2/library/logging.handlers.html#logging.FileHandler) docs |
How to use continuation line over-indented for visual indent? | 21,592,569 | 7 | 2014-02-06T01:59:40Z | 21,592,649 | 12 | 2014-02-06T02:07:23Z | [
"python",
"pep8"
] | I'm having a hard time trying to fix this piece of code in order for it to fit PEP8's guidelines. I have tried breaking the line with a backslash and then enclosing it with a set of brackets. Furthermore, I made sure that the second line came right after the position first right bracket.
```
if (len(self._stools[o... | I'm guessing you are getting a "Continuation line does not distinguish itself from next logical line". The solution is to move the second line another indent -
```
if (len(self._stools[origin]) > 0 and len(self._stools[dest]) and
self.top_cheese(origin).size > self.top_cheese(dest).size):
raise IllegalMove... |
How does one convert a grayscale image to RGB in OpenCV (Python) for visualizing contours after processing an image in binary? | 21,596,281 | 7 | 2014-02-06T07:08:41Z | 21,709,613 | 20 | 2014-02-11T18:04:22Z | [
"python",
"opencv",
"image-processing"
] | I am learning image processing using OpenCV for a realtime application. I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
Early in the program I used gray = cv2.cvtColor(frame, cv2.COLOR\_BGR2GRAY) to convert from RG... | I am promoting my comment to an answer:
The easy way is:
> You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
`backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)` is the correct syntax. |
Pybluez installation in Linux | 21,597,536 | 9 | 2014-02-06T08:25:58Z | 21,597,642 | 19 | 2014-02-06T08:32:17Z | [
"python",
"linux",
"failed-installation"
] | I am trying to install PyBluez-0.18 on my Linux Mint 15 machine, but got an error message during the installation process. I tried searching online to see if others might have encountered this problem, but I could not find any.
I list the command I tried to execute, along with the error message I received. Could someo... | You need to install libbluetooth-dev package for compiling your code
```
sudo apt-get install libbluetooth-dev
```
That should install the bluetooth header files. |
How to create multiple class objects with a loop in python? | 21,598,872 | 3 | 2014-02-06T09:34:47Z | 21,598,969 | 9 | 2014-02-06T09:39:17Z | [
"python",
"class",
"object"
] | Suppose you have to create 10 class objects in python, and do something with them, like:
```
obj_1 = MyClass()
other_object.add(obj_1)
obj_2 = MyClass()
other_object.add(obj_2)
.
.
.
obj_10 = MyClass()
other_object.add(obj_10)
```
How would you do it with a loop, and assign a variable to each object (like `obj_1`), s... | This question is asked every day in some variation. The answer is: keep your data out of your variable names, and [this is the obligatory blog post](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html).
In this case, why not make a list of objs?
```
objs = [MyClass() for i in range(10)]
for... |
python XlsxWriter set border around multiple cells | 21,599,809 | 11 | 2014-02-06T10:13:23Z | 26,429,246 | 7 | 2014-10-17T16:16:32Z | [
"python",
"excel",
"xlsxwriter"
] | I need an easy way to set border around multiple cells, like so:

All I found was border of 1 cell, and merge cells, which is not what I need.
I was expecting for something like:
```
worksheet.range_border(first_row, first_col, last_row, last_col)
```
Is the... | XlsxWriter is an awesome module that made my old job 1,000x easier (thanks John!), but formatting cells with it can be time-consuming. I've got a couple helper functions I use to do stuff like this.
First, you need to be able to create a new format by adding properties to an existing format:
```
def add_to_format(exi... |
Can a simple MD5 hash converted to a django password? | 21,600,088 | 2 | 2014-02-06T10:23:32Z | 21,600,444 | 7 | 2014-02-06T10:38:02Z | [
"python",
"django",
"encryption",
"cryptography",
"password-encryption"
] | I have a legacy users database which I would like to integrate into a new Django project.
The users passwords are saved in the old database with a plain and simple MD5 encryption(PHP md5() function), without any salting whatsoever.
Overriding the check\_password and set\_password of django.contrib.auth is not an opti... | The Django [`contrib.auth.hashers` module](https://github.com/django/django/blob/master/django/contrib/auth/hashers.py) *already* supports plain, unsalted MD5 passwords:
```
# Ancient versions of Django created plain MD5 passwords and accepted
# MD5 passwords with an empty salt.
if ((len(encoded) == 32 and '$' not in ... |
How do I use sklearn CountVectorizer with both 'word' and 'char' analyzer? - python | 21,600,196 | 4 | 2014-02-06T10:27:27Z | 21,600,406 | 9 | 2014-02-06T10:36:23Z | [
"python",
"machine-learning",
"scikit-learn",
"analyzer",
"text-analysis"
] | How do I use sklearn CountVectorizer with both 'word' and 'char' analyzer?
<http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html>
I could extract the text features by word or char separately but how do i create a `charword_vectorizer`? Is there a way to combine the vect... | You can pass a callable as the `analyzer` argument to get full control over the tokenization, e.g.
```
>>> from pprint import pprint
>>> import re
>>> x = ['this is a foo bar', 'you are a foo bar black sheep']
>>> def words_and_char_bigrams(text):
... words = re.findall(r'\w{3,}', text)
... for w in words:
...... |
Write-once dictionary? | 21,601,593 | 2 | 2014-02-06T11:26:03Z | 21,601,690 | 9 | 2014-02-06T11:29:47Z | [
"python"
] | I'd quite like to have a write-once dictionary object in Python, so that:
```
my_dict[1] = 'foo'
my_dict[2] = 'bar'
my_dict[1] = 'baz' # Raises KeyError
```
I can imagine making a straightforward one, but I wonder if a better-thought-out recipe exists? I couldn't find one. | It's easy enough to implement a subclass:
```
class WriteOnceDict(dict):
def __setitem__(self, key, value):
if key in self:
raise KeyError('{} has already been set'.format(key))
super(WriteOnceDict, self).__setitem__(key, value)
```
You could also provide a custom `update()` method, an... |
Python @property decorator not working | 21,604,388 | 5 | 2014-02-06T13:29:42Z | 21,604,419 | 13 | 2014-02-06T13:31:08Z | [
"python",
"properties",
"decorator",
"getter-setter"
] | Could anyone find a problem with this @property decorator? I cannot seem to get it to assert correctly. I'm sure I'm doing some really simple thing wrong, but can anyone point my tired eyes in the right direction please?
```
class A:
def __init__(self):
self.a = 0
self._b = 0
@property
def... | The `@property` decorator only works on *new style classes*. Inherit from `object`:
```
class A(object):
```
With that change your test function passes. |
Numpy Cholesky decomposition LinAlgError | 21,604,498 | 4 | 2014-02-06T13:34:16Z | 21,605,863 | 8 | 2014-02-06T14:39:06Z | [
"python",
"numpy",
"scipy",
"linear-algebra",
"covariance"
] | In my attempt to perform cholesky decomposition on a variance-covariance matrix for a 2D array of periodic boundary condition, under certain parameter combinations, I always get `LinAlgError: Matrix is not positive definite - Cholesky decomposition cannot be computed`. Not sure if it's a `numpy.linalg` or implementatio... | Digging a bit deeper in problem, I tried printing the Eigenvalues of the Cov matrix.
```
print np.linalg.eigvalsh(Cov)
```
And the answer turns out to be this
```
[-0.0801339 -0.0801339 0.12653595 0.12653595 0.12653595 0.12653595 0.14847999 0.36269785 0.36269785 0.36269785 0.36269785 1.09439988 1.09439988... |
python requests on Google App Engine not working for HTTPS | 21,605,328 | 12 | 2014-02-06T14:15:10Z | 21,610,822 | 16 | 2014-02-06T18:17:00Z | [
"python",
"google-app-engine",
"python-2.7",
"python-requests"
] | I'm using python-request on Google App Engine and it's not working as expected for HTTPS. Let's see an example:
```
import requests
requests.get('https://www.digitalocean.com')
```
That line works perfectly if I execute it in a terminal. Response is 200 OK (without redirects).
However, if I execute it on GAE a TooMa... | Downgrading to requests==2.1.0 worked for me.
Having an up-to-date urllib3 is important for resolving an unrelated bug (`import pwd`, as I recall).
Hopefully App Engine fixes this soon, as requests [won't](https://github.com/kennethreitz/requests/issues/1905).
EDIT:
I think you can also patch this in the latest req... |
StructuredProperty inside another StructuredProperty. How to? | 21,605,892 | 3 | 2014-02-06T14:40:06Z | 21,609,082 | 7 | 2014-02-06T16:53:22Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I have an Entity which has a variable amount of another Entity in it (so I'm usingStructured Property, repeated=True), but that one property can hold variable amount of single entity kind as well. So my code looks like this:
```
class Property(ndb.Model):
name = ndb.StringProperty()
cost = ndb.FloatPrope... | > Although a StructuredProperty can be repeated and a StructuredProperty
> can contain another StructuredProperty, beware: if one structured
> property contains another, only one of them can be repeated. A
> work-around is to use LocalStructuredProperty, which does not have
> this constraint (but does not allow queries... |
Conditional Replace Pandas | 21,608,228 | 5 | 2014-02-06T16:16:54Z | 21,608,417 | 20 | 2014-02-06T16:24:57Z | [
"python",
"replace",
"pandas",
"conditional"
] | I'm probably doing something very stupid, but I'm stumped.
I have a dataframe and I want to replace the values in a particular column that exceed a value with zero. I had thought this was a way of achieving this:
```
df[df.my_channel > 20000].my_channel = 0
```
If I copy the channel into a new data frame it's simple... | Try
```
df.ix[df.my_channel > 20000, 'my_channel'] = 0
``` |
Pure virtual methods in Python | 21,610,836 | 7 | 2014-02-06T18:17:41Z | 21,611,047 | 11 | 2014-02-06T18:28:07Z | [
"python",
"oop",
"inheritance",
"virtual-method"
] | What is the ideologically correct way of implementing *pure virtual methods* in Python?
Just raising `NotImplementedError` in the methods?
Or is there a better way?
Thank you! | While it's not uncommon to see [people using `NotImplementedError`](http://www.java2s.com/Tutorial/Python/0220__Class/Creatingaclasshierarchywithanabstractbaseclass.htm), some will argue that the "proper" way to do it (since python 2.6) is using a **Abstract Base Class**, through the [`abc` module](http://docs.python.o... |
Assert that a method was called with one argument out of several | 21,611,559 | 6 | 2014-02-06T18:55:47Z | 21,611,963 | 11 | 2014-02-06T19:16:41Z | [
"python",
"unit-testing"
] | I'm mocking out a call to `requests.post` using the `Mock` library:
```
requests.post = Mock()
```
The the call involves multiple arguments: the URL, a payload, some auth stuff, etc. I want to assert that `requests.post` is called with a particular URL, but I don't care about the other arguments. When I try this:
``... | As far as I know `Mock` doesn't provide a way to achieve what you want via `assert_called_with`. You could access the [`call_args`](http://docs.python.org/3.3/library/unittest.mock.html#unittest.mock.Mock.call_args) and [`call_args_list`](http://docs.python.org/3.3/library/unittest.mock.html#unittest.mock.Mock.call_arg... |
Assert that a method was called with one argument out of several | 21,611,559 | 6 | 2014-02-06T18:55:47Z | 27,152,023 | 14 | 2014-11-26T14:46:24Z | [
"python",
"unit-testing"
] | I'm mocking out a call to `requests.post` using the `Mock` library:
```
requests.post = Mock()
```
The the call involves multiple arguments: the URL, a payload, some auth stuff, etc. I want to assert that `requests.post` is called with a particular URL, but I don't care about the other arguments. When I try this:
``... | You can also use the `ANY` helper to always match arguments you don't know or aren't checking for.
More in the ANY helper:
<https://docs.python.org/3/library/unittest.mock.html#any>
So for instance you could match the argument 'session' to anything like so:
```
from mock import ANY
requests_arguments = {'slug': 'foo... |
Zbar + python, crashes on import (OSX 10.9.1) | 21,612,908 | 9 | 2014-02-06T20:06:37Z | 21,885,499 | 21 | 2014-02-19T15:48:16Z | [
"python",
"osx-mavericks",
"zbar"
] | I've attempted to install Zbar for use with python 2.7.6 with Homebrew and pip (brew install zbar, then pip install zbar) but every time I import it, python crashes. Simply running:
```
#!/usr/bin/python
import zbar
```
lands me with this from the terminal:
```
:~ aj$ cd '/Users/aj/Documents/nlcc/check in/python/' ... | I found the answer, but I wanted to post it here anyway in case anyone has the same trouble I did. You can use the brew installation of zbar, but you have to install to python via: pypi.python.org/pypi/zbar using this patch: <https://github.com/npinchot/zbar/commit/d3c1611ad2411fbdc3e79eb96ca704a63d30ae69>. Also, be su... |
'Finally' equivalent for If/Elif statements in Python | 21,612,910 | 8 | 2014-02-06T20:06:39Z | 21,613,218 | 7 | 2014-02-06T20:21:03Z | [
"python",
"finally"
] | Does Python have a `finally` equivalent for its `if/else` statements, similar to its `try/except/finally` statements? Something that would allow us to simplify this:
```
if condition1:
do stuff
clean up
elif condition2:
do stuff
clean up
elif condition3:
do stuff
clean up
...
.... | It can be done totally non-hackily like this:
```
def function(x,y,z):
if condition1:
blah
elif condition2:
blah2
else:
return False
#finally!
clean up stuff.
```
In some ways, not as convenient, as you have to use a separate function. However, good practice to not make to... |
A function-like variable | 21,614,236 | 4 | 2014-02-06T21:18:18Z | 21,614,306 | 8 | 2014-02-06T21:21:30Z | [
"python",
"function",
"variables",
"representation"
] | [Inspired by [this question](http://stackoverflow.com/q/21613967/198633)]
Suppose I have two lists:
```
list1 = ['tom', 'mary', 'frank', 'joe', 'john', 'barry']
list2 = [1, 2, 3, 4]
```
I want to match each name in `list1` with a number in `list2`. Since there are four numbers in `list2`, I would like to pair each o... | Seems the simplest approach here would be to create a generator that yields all the filler values for eternity, then chain this with yielding the values in list2:
```
def inf_gen(f):
while True:
yield f()
```
Note that `inf_gen(f)` is actually equivalent to `iter(f, None)`, given that `f` never returns. `... |
Reverse string: string[::-1] works, but string[0::-1] and others don't | 21,617,586 | 7 | 2014-02-07T01:22:05Z | 21,617,607 | 10 | 2014-02-07T01:24:42Z | [
"python",
"string",
"reverse",
"slice"
] | I am somewhat of a python/programming newbie, and I have just been playing around with string slicing. So the simple string reverse method of `string[::-1]` works just fine as we know, but there are other instances in my code below that yields unexpected results:
```
In [1]: string = "Howdy doody"
In [2]: string[::]
... | In all of your cases which aren't working, you're **starting** at the **beginning** and then moving **backwards**. There is no further backwards than the beginning, so you don't get any more characters.
This would be the solution:
```
>>> string[len(string)::-1]
'ydood ydwoH'
```
The slice notation is `start`, `end`... |
Python-3.2 coroutine: AttributeError: 'generator' object has no attribute 'next' | 21,622,193 | 12 | 2014-02-07T07:54:13Z | 21,622,696 | 23 | 2014-02-07T08:25:11Z | [
"python",
"python-3.x"
] | ```
#!/usr/bin/python3.2
import sys
def match_text(pattern):
line = (yield)
if pattern in line:
print(line)
x = match_text('apple')
x.next()
for line in input('>>>> '):
if x.send(line):
print(line)
x.close()
```
This is a coroutine but Python3.2 sees it as a generator - why? What is goi... | You're getting thrown off by the error message; type-wise, Python doesn't make a distinction - you can `.send` to anything that uses `yield`, even if it doesn't do anything with the sent value internally.
In 3.x, there is no longer a `.next` method attached to these; instead, use the built-in free function `next`. |
What does y, _ assignment do in python / sklearn? | 21,625,655 | 5 | 2014-02-07T10:45:11Z | 21,625,742 | 8 | 2014-02-07T10:49:30Z | [
"python",
"scikit-learn"
] | As a relative new-comer to Python I am trying to use the sklearn RandomForestClassifier. One example from a how-to guide by yhat is the following:
```
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
iris = load_iris()
df = pd.DataFrame(... | You decompose the returned tuple into two distinct values, `y` and `_`.
`_` is convention for "I don't need that value anymore".
It's basically the same as:
```
y = pd.factorize(train['species'])[0]
```
with the exception that this code would work for any indexable return value with at least 1 element, while yours ... |
Unable to pass jinja2 variables into javascript snippet | 21,626,048 | 15 | 2014-02-07T11:02:30Z | 21,627,350 | 32 | 2014-02-07T12:05:18Z | [
"javascript",
"python",
"flask",
"jinja2"
] | How do i pass jinja2 data into javascript.
I have a Flask REST url as `/logs/<test_case_name>`
I am trying use `.getJSON()` to query the above URL and hence would want to pass the jinja2 data which has the testcasename to `.getJSON` function.
sample code:
```
<script type="text/javascript">
alert({{name}});
</scrip... | Try with quotes:
```
alert("{{name}}");
``` |
Unable to pass jinja2 variables into javascript snippet | 21,626,048 | 15 | 2014-02-07T11:02:30Z | 21,628,553 | 21 | 2014-02-07T13:04:29Z | [
"javascript",
"python",
"flask",
"jinja2"
] | How do i pass jinja2 data into javascript.
I have a Flask REST url as `/logs/<test_case_name>`
I am trying use `.getJSON()` to query the above URL and hence would want to pass the jinja2 data which has the testcasename to `.getJSON` function.
sample code:
```
<script type="text/javascript">
alert({{name}});
</scrip... | other than encapsulating the variable in a string, an alternate is jquery for profit:
its generally a bad idea to mix template language with javascript. An alternative would be to use html as a proxy - store the name in an element like so
```
<meta id="my-data" data-name="{{name}}" data-other="{{other}}">
```
then i... |
Changing hostname in a url | 21,628,852 | 18 | 2014-02-07T13:20:43Z | 21,629,125 | 27 | 2014-02-07T13:34:16Z | [
"python",
"url"
] | I am trying to use python to change the hostname in a url, and have been playing around with the urlparse module for a while now without finding a satisfactory solution. As an example, consider the url:
<https://www.google.dk:80/barbaz>
I would like to replace "www.google.dk" with e.g. "www.foo.dk", so I get the foll... | You can use [`urlparse.urlparse`](http://docs.python.org/2/library/urlparse.html#urlparse.urlparse) function and `ParseResult._replace` method:
```
>>> import urlparse
>>> parsed = urlparse.urlparse("https://www.google.dk:80/barbaz")
>>> replaced = parsed._replace(netloc="www.foo.dk:80")
>>> print replaced
ParseResult... |
Changing hostname in a url | 21,628,852 | 18 | 2014-02-07T13:20:43Z | 21,629,155 | 9 | 2014-02-07T13:36:06Z | [
"python",
"url"
] | I am trying to use python to change the hostname in a url, and have been playing around with the urlparse module for a while now without finding a satisfactory solution. As an example, consider the url:
<https://www.google.dk:80/barbaz>
I would like to replace "www.google.dk" with e.g. "www.foo.dk", so I get the foll... | You can take advantage of [`urlsplit`](http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit) and [`urlunsplit`](http://docs.python.org/2/library/urlparse.html#urlparse.urlunsplit) from Python's [`urlparse`](http://docs.python.org/2/library/urlparse.html#module-urlparse):
```
>>> from urlparse import urlspl... |
Neat way to get descriptor object | 21,629,397 | 4 | 2014-02-07T13:46:38Z | 21,629,637 | 8 | 2014-02-07T13:56:46Z | [
"python",
"python-3.x",
"descriptor"
] | In Python 3
```
class A(object):
attr = SomeDescriptor()
...
def somewhere(self):
# need to check is type of self.attr is SomeDescriptor()
desc = self.__class__.__dict__[attr_name]
return isinstance(desc, SomeDescriptor)
```
Is there better way to do it? I don't like this `self.__c... | Yes, to access descriptors on a class, the only way to prevent [`descriptor.__get__`](http://docs.python.org/2/reference/datamodel.html#implementing-descriptors) from being invoked is to go through the class `__dict__`.
You could use [`type(self)`](http://docs.python.org/2/library/functions.html#type) to access the cu... |
Reading from a file with sys.stdin in Pycharm | 21,630,403 | 9 | 2014-02-07T14:36:45Z | 23,942,485 | 7 | 2014-05-29T20:35:29Z | [
"python",
"stdin",
"pycharm"
] | I am trying to test a simple code that reads a file line-by-line with Pycharm.
```
for line in sys.stdin:
name, _ = line.strip().split("\t")
print name
```
I have the file I want to input in the same directory: lib.txt
How can I debug my code in Pycharm with the input file? | You can work around this issue if you use the fileinput module rather than trying to read stdin directly.
With fileinput, if the script receives a filename(s) in the arguments, it will read from the arguments in order. In your case, replace your code above with:
```
import fileinput
for line in fileinput.input():
... |
Python xlwt create faulty excel book | 21,631,544 | 3 | 2014-02-07T15:26:33Z | 21,635,803 | 7 | 2014-02-07T19:05:06Z | [
"python",
"excel",
"xlwt"
] | I am trying to use `xlwt` to create a output file (in .xlsx format) with multiple tabs. The version number of my Python is 2.7, and I am using Aptana Studio 3 as IDE.
I've used the `xlwt` package before, with the same environment, to carry out the same task. It worked well. But this time, it works well at first, then ... | The `xlwt` module cannot create `.xlsx` files. It is a writer for `.xls` files.
The warning is due to a feature in newer versions of Excel called ["extension hardening"](http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx) which means that the file extension has to match the ... |
How can I pass parameters to a RequestHandler? | 21,631,799 | 6 | 2014-02-07T15:37:29Z | 21,631,948 | 7 | 2014-02-07T15:43:53Z | [
"python"
] | The Python documentation includes [an example of creating an HTTP server](http://docs.python.org/3.3/library/http.server.html):
```
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
`... | Use a class factory:
```
def MakeHandlerClassFromArgv(init_args):
class CustomHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super(CustomHandler, self).__init__(*args, **kwargs)
do_stuff_with(self, init_args)
return CustomHandler
if __name__ == "__main_... |
Celery: is there a way to write custom JSON Encoder/Decoder? | 21,631,878 | 16 | 2014-02-07T15:41:12Z | 22,520,957 | 26 | 2014-03-20T00:19:11Z | [
"python",
"json",
"celery"
] | I have some objects I want to send to celery tasks on my application. Those objects are obviously not json serializable using the default json library. Is there a way to make celery serialize/de-serialize those objects with custom JSON `Encoder`/`Decoder`? | A bit late here, but you should be able to define a custom encoder and decoder by registering them in the kombu serializer registry, as in the docs: <http://docs.celeryproject.org/en/latest/userguide/calling.html#serializers>.
For example, the following is a custom datetime serializer/deserializer (subclassing [python... |
Find matching key-value pairs of two dictionaries | 21,631,951 | 2 | 2014-02-07T15:44:00Z | 21,632,049 | 7 | 2014-02-07T15:47:56Z | [
"python"
] | What will be the most efficient way to check if key-value pair of one dictionary is present in other dictionary as well.
Suppose if I have two dictionaries as **dict1** and **dict2** and these two dictionaries have some of the key-value pairs in common. I want to find those and print them. What would be the most eff... | one way would be:
```
d_inter = dict([k, v for k, v in dict1.iteritems() if k in dict2 and dict2[k] == v])
```
the other:
```
d_inter = dict(set(d1.iteritems()).intersection(d2.iteritems()))
```
I'm not sure which one would be more efficient, so let's compare both of them:
## 1. Solution with iteration through dic... |
Proper way for user authentication with angularjs and flask | 21,634,682 | 11 | 2014-02-07T18:01:31Z | 21,635,756 | 41 | 2014-02-07T19:01:53Z | [
"python",
"angularjs",
"flask",
"authentication",
"flask-security"
] | I'm currently working my way through Web development with flask. I want to build a webapp with flask as backend and angular.js at the frontend. The Json part is straight forward, and my first steps work out well. But now I got stuck with User Authentication. I read a lot but found out, that WTFForms works not as well w... | I have written several tutorials on RESTful APIs with Flask, all with examples that are ready to use:
<http://blog.miguelgrinberg.com/category/REST>
The tutorials are:
* [Designing a RESTful API with Python and Flask](http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask)
This is a sim... |
pip executes the wrong python library versions inside virtual env | 21,635,107 | 10 | 2014-02-07T18:26:03Z | 23,419,548 | 7 | 2014-05-02T01:47:52Z | [
"python",
"virtualenv",
"osx-mavericks",
"virtualenvwrapper"
] | I create a virtual enviroment with `virtualenvwrapper` and then I try to install django in it with `pip`. However I keep getting an error due to a conflict in python versions.
```
$ mkvirtualenv env
$ workon env
$ pip install django
Downloading/unpacking django
Cleaning up...
Exception:
Traceback (most recent call las... | I ran into the same issue on a Mac with Anaconda installed. The way I fixed it was searching for platform.py, then modifying the following (commenting out a line):
**ORIGINAL**
```
_sys_version_parser = re.compile(
r'([\w.+]+)\s*'
'\|[^|]*\|\s*' # version extra
'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
... |
Why you shouldn't use os.linesep when editing on text mode? | 21,636,213 | 8 | 2014-02-07T19:29:40Z | 21,636,284 | 11 | 2014-02-07T19:33:02Z | [
"python"
] | [Python 2.7 documentation](http://docs.python.org/2/library/os.html?highlight=linesep#os.linesep) (and [Python 3 documentation](http://docs.python.org/3/library/os.html?highlight=linesep#os.linesep) as well) contain the following line about the `os.linepath` function:
> Do not use os.linesep as a line terminator when ... | When you open a file in text mode any `\n` that you write to the file is converted to the appropriate line ending for the platform you are using.
So, for example if you were on Windows where `os.linesep` is `'\r\n'`, when you write that to a file the `\n` will get automatically converted to `\r\n` and you will end up ... |
Tutorial for scipy.cluster.hierarchy | 21,638,130 | 23 | 2014-02-07T21:32:26Z | 21,723,473 | 43 | 2014-02-12T09:19:03Z | [
"python",
"scipy",
"hierarchical-clustering"
] | I'm trying to understand how to manipulate a hierarchy cluster but the documentation is too ... technical?... and I can't understand how it works.
Is there any tutorial that can help me to start with, explaining step by step some simple tasks?
Let's say I have the following data set:
```
a = np.array([[0, 0 ],
... | There are three steps in hierarchical agglomerative clustering (HAC):
1. Quantify Data (`metric` argument)
2. Cluster Data (`method` argument)
3. Choose the number of clusters
Doing
```
z = linkage(a)
```
will accomplish the first two steps. Since you did not specify any parameters it uses the standard values
1. `... |
error: command 'cc' failed with exit status 1 - MySQLdb installation on MAC | 21,638,444 | 6 | 2014-02-07T21:51:53Z | 22,633,553 | 10 | 2014-03-25T11:43:31Z | [
"python",
"mysql-python"
] | I am new to Mac and i am trying to install MySQLdb for Python on MAC but after following the steps mentioned on <http://www.tutorialspoint.com/python/python_database_access.htm>, i received an error after running
```
$ python setup.py build
```
Error:
```
clang: warning: argument unused during compilation: '-mno-fus... | The problem is unused arguments passed to compiler. Try this before running your build code:
```
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
``` |
Inverse of a matrix using numpy | 21,638,895 | 7 | 2014-02-07T22:24:38Z | 21,638,984 | 10 | 2014-02-07T22:32:06Z | [
"python",
"numpy",
"matrix"
] | I'd like to use numpy to calculate the inverse. But I'm getting an error:
```
'numpy.ndarry' object has no attribute I
```
To calculate inverse of a matrix in numpy, say matrix M, it should be simply:
`print M.I`
Here's the code:
```
x = numpy.empty((3,3), dtype=int)
for comb in combinations_with_replacement(range(... | The `I` attribute only exists on `matrix` objects, not `ndarray`s. You can use [`numpy.linalg.inv`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html#numpy.linalg.inv) to invert arrays:
```
inverse = numpy.linalg.inv(x)
```
Note that the way you're generating matrices, not all of them will be ... |
How to determine the name of an egg for a Python package on Github? | 21,638,929 | 3 | 2014-02-07T22:26:53Z | 21,639,005 | 7 | 2014-02-07T22:33:26Z | [
"python",
"pip",
"egg",
"distribute"
] | I know [I can install](http://www.pip-installer.org/en/latest/logic.html#git) with
```
$ pip install -e git+https://git.repo/some_pkg#egg=SomePackage
```
but -- when I'm trying to use somebody else's package -- how do I determine what the name of the egg is? | Look at the git repo, find the `setup.py` file in the root and find what is passed to the `name` keyword in the `setup()` function call.
For example, the [Pyramid `setup.py`](https://github.com/Pylons/pyramid/blob/master/setup.py#L71) has:
```
setup(name='pyramid',
```
so you'd use:
```
$ pip install -e git+https:/... |
Python "SyntaxError: Non-ASCII character '\xe2' in file" | 21,639,275 | 53 | 2014-02-07T22:55:16Z | 21,639,459 | 54 | 2014-02-07T23:11:12Z | [
"python"
] | I am writing some python code and I am receiving the error message as in the title, from searching this has to do with the character set.
Here is the line that causes the error
```
hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
```
I cannot figure out what character is not in the ... | You've got a stray byte floating around. You can find it by running
```
with open("x.py") as fp:
for i, line in enumerate(fp):
if "\xe2" in line:
print i, repr(line)
```
where you should replace `"x.py"` by the name of your program. You'll see the line number and the offending line(s). For exa... |
Python "SyntaxError: Non-ASCII character '\xe2' in file" | 21,639,275 | 53 | 2014-02-07T22:55:16Z | 24,221,963 | 84 | 2014-06-14T16:28:18Z | [
"python"
] | I am writing some python code and I am receiving the error message as in the title, from searching this has to do with the character set.
Here is the line that causes the error
```
hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
```
I cannot figure out what character is not in the ... | If you are just trying to use UTF-8 characters or don't care if they are in your code, add this line to the top of your `.py` file
```
# -*- coding: utf-8 -*-
``` |
Python "SyntaxError: Non-ASCII character '\xe2' in file" | 21,639,275 | 53 | 2014-02-07T22:55:16Z | 28,063,209 | 9 | 2015-01-21T09:04:42Z | [
"python"
] | I am writing some python code and I am receiving the error message as in the title, from searching this has to do with the character set.
Here is the line that causes the error
```
hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
```
I cannot figure out what character is not in the ... | Change the file character encoding,
put below line to top of your code always
```
# -*- coding: utf-8 -*-
``` |
Difference between super() and calling directly | 21,639,788 | 3 | 2014-02-07T23:44:38Z | 21,639,994 | 8 | 2014-02-08T00:05:21Z | [
"python",
"oop",
"python-2.7",
"python-3.x",
"superclass"
] | In Python 2.7 and 3, I use the following method to call a super-class's function:
```
class C(B):
def __init__(self):
B.__init__(self)
```
I see it's also possible to replace `B.__init__(self)` with `super(B, self).__init__()` and in python3 `super().__init__()`.
Are there any advantages or disadvantages... | For single inheritance, `super()` is just a fancier way to refer to the base type. That way, you make the code more maintainable, for example in case you want to change the base typeâs name. When you are using `super` everywhere, you just need to change it in the `class` line.
The real benefit comes with multiple in... |
Is it possible to convert list to queue in python? | 21,639,888 | 3 | 2014-02-07T23:54:03Z | 21,639,920 | 7 | 2014-02-07T23:57:17Z | [
"python"
] | How to convert a list to queue? So that operations like enqueue or dequeue an be carried out. I want to use to the list to remove the top most values and i believe it can be done using queues. | pop from the front of a list is not very efficient as all the references in the list need to be updated.
[deque](http://docs.python.org/2/library/collections.html#collections.deque) will allow you do queue like operations efficiently
```
>>> from collections import deque
>>> deque([1,2,3,4])
deque([1, 2, 3, 4])
``` |
Python DNS module import error | 21,641,696 | 5 | 2014-02-08T03:57:13Z | 21,642,297 | 7 | 2014-02-08T05:21:23Z | [
"python",
"python-2.7",
"module",
"resolver"
] | I have been using python dns module.I was trying to use it on a new Linux installation but the module is not getting loaded.
I have tried to clean up and install but the installation does not seem to be working.
```
$ python --version
Python 2.7.3
$ sudo pip install dnspython
Downloading/unpacking dnsp... | I ran into the same issue with dnspython.
My solution was to build the source from their official GitHub project.
So my steps were:
```
git clone https://github.com/rthalley/dnspython
cd dnspython/
python setup.py install
```
After doing this, I was able to import the `dns` module.
**EDIT**
It seems the pip insta... |
Python struct.calcsize length | 21,641,735 | 3 | 2014-02-08T04:04:03Z | 21,642,181 | 7 | 2014-02-08T05:06:41Z | [
"python"
] | ```
>>>import struct
>>>size_a = struct.calcsize('10s')
size_a = 10
>>>size_b = struct.calcsize('iii')
size_b = 12
>>>size_c = struct.calcsize('10siii')
size_c = 24
```
Could someone tell me why size\_c is `24` rather than `22`(10 + 12) ? | This has to do with [alignment](http://docs.python.org/library/struct.html#struct-alignment). Any particular type (byte, integer,
etc.) can only begin at an offset that is a multiple of its standard size.
* A byte string `s` can begin at any offset because its standard size is 1.
* But a 32-bit integer `i` can only be... |
python multiprocessing - process hangs on join for large queue | 21,641,887 | 8 | 2014-02-08T04:27:19Z | 21,644,038 | 12 | 2014-02-08T09:00:26Z | [
"python",
"process",
"queue",
"multiprocessing"
] | I'm running python 2.7.3 and I noticed the following strange behavior. Consider this minimal example:
```
from multiprocessing import Process, Queue
def foo(qin, qout):
while True:
bar = qin.get()
if bar is None:
break
qout.put({'bar': bar})
if __name__ == '__main__':
impo... | The `qout` queue in the subprocess gets full. The data you put in it from `foo()` doesn't fit in the buffer of the OS's pipes used internally, so the subprocess blocks trying to fit more data. But the parent process is not reading this data: it is simply blocked too, waiting for the subprocess to finish. This is a typi... |
Linear regression implementation always performs worse than sklearn | 21,642,387 | 4 | 2014-02-08T05:33:35Z | 21,642,954 | 7 | 2014-02-08T06:44:35Z | [
"python",
"machine-learning",
"scikit-learn",
"linear-regression"
] | I implemented linear regression with gradient descent in python. To see how well it is doing I compared it with scikit-learn's LinearRegression() class. For some reason, sklearn always outperforms my program by a MSE of 3 on average (I am using the Boston Housing dataset for testing). I understand that I am currently n... | First, make sure that you are computing the correct objective function value. The linear regression objective should be `.5*np.mean((pred-y)**2)`, rather than `np.mean(abs(pred - y))`.
You are actually running a stochastic gradient descent (SGD) algorithm (running a gradient iteration on individual examples), which sh... |
Python floating point determinism | 21,642,779 | 4 | 2014-02-08T06:25:37Z | 21,642,797 | 10 | 2014-02-08T06:27:44Z | [
"python",
"floating-point",
"deterministic",
"non-deterministic"
] | The code below (to compute cosine similarity), when run repeatedly on my computer, will output 1.0, 0.9999999999999998, or 1.0000000000000002. When I take out the normalize function, it will only return 1.0. I thought floating point operations were supposed to be deterministic. What would be causing this in my program ... | Floating-point math may be deterministic, but the ordering of dictionary keys is not.
When you call `.keys()`, the order of the resulting list is potentially random.
Thus the order of your math operations inside the loops are also potentially random, and thus the result is not going to be deterministic because while ... |
Find smallest eigenvalue exactly | 21,644,262 | 3 | 2014-02-08T09:23:34Z | 21,646,022 | 7 | 2014-02-08T12:34:46Z | [
"python",
"math",
"numpy",
"scipy",
"sympy"
] | I would like to find the smallest (in absolute value) non-zero eigenvalue of a matrix exactly. I can do this using floating point arithmetic using numpy but
* is there a way to get an exact answer?
* Do you have to use sympy for this or is there another way?
The matrices will be small (say less than 20 by 20) with in... | Eigenvalues are [algebraic numbers](http://en.wikipedia.org/wiki/Algebraic_number), that is roots of some polynomial. The degree of that polynomial would be the matrix dimension. For polynomials up to degree 4 you are in principle able to write those numbers down as nested roots, but beyond that there is in general no ... |
Flask - ImportError: No module named migrate.versioning | 21,646,689 | 6 | 2014-02-08T13:39:44Z | 24,152,007 | 13 | 2014-06-10T22:40:06Z | [
"python",
"flask",
"importerror",
"flask-sqlalchemy",
"flask-migrate"
] | I'm working through a flask tutorial and am trying to run a script that creates a database instead of doing it through the command line. It uses the SQLAlchemy-migrate package, but when I try to run the script, it gives an ImportError.
This is the terminal output:
```
Sean:app seanpatterson$ python ./db_create.py
Tr... | ```
pip install sqlalchemy==0.7.9
```
and
```
pip install sqlalchemy-migrate==0.7.2
```
and
optionally this flask-whooshalchemy==0.55a should solve the problem |
Creating a Pandas DataFrame with a numpy array containing multiple types | 21,647,054 | 5 | 2014-02-08T14:12:59Z | 21,647,198 | 16 | 2014-02-08T14:25:37Z | [
"python",
"numpy",
"pandas"
] | I want to create a pandas dataframe with default values of zero, but one column of integers and the other of floats. I am able to create a numpy array with the correct types, see the `values` variable below. However, when I pass that into the dataframe constructor, it only returns NaN values (see `df` below). I have in... | Here are a few options you could choose from:
```
import numpy as np
import pandas as pd
index = ['x', 'y']
columns = ['a','b','c']
# Option 1: Set the column names in the structured array's dtype
dtype = [('a','int32'), ('b','float32'), ('c','float32')]
values = np.zeros(2, dtype=dtype)
df = pd.DataFrame(values, i... |
OAuth Access Token request (Twitter API) and oauth_verifier field | 21,651,846 | 4 | 2014-02-08T21:08:40Z | 21,653,087 | 7 | 2014-02-08T23:28:09Z | [
"python",
"twitter",
"oauth",
"twitter-oauth"
] | So, after ~~years~~ days of struggling to get a request\_token from `https://api.twitter.com/oauth/request_token` working, I finally successfully generated a Base Signature String and HMAC-SHA1 signature, and received an `oauth_token` from `https://api.twitter.com/oauth/request_token`.
Now, I'm a bit confused about th... | What you are looking for is [application-only authentication](https://dev.twitter.com/docs/auth/application-only-auth).
Here's an example in **Python 3.3**, of how to obtain the bearer token you can use for application only requests using the [requests](http://docs.python-requests.org) package and assuming the values ... |
AMQP: acknowledgement and prefetching | 21,652,517 | 4 | 2014-02-08T22:22:18Z | 21,662,129 | 16 | 2014-02-09T17:05:06Z | [
"python",
"rabbitmq",
"amqp",
"pika"
] | I try to understand some aspects of AMQP protocol. Currently I have project with RabbitMQ and use python pika library. So question is about acknowledgement and message prefetching.
1. Consider we have queue with only consumer (for sure this queue was declared as exclusive). So do I understand correctly: no matter if I... | With `autoack` flag unset, if your application failed during message processing all received messages will be lost. If such situation is quite rare and message lose is appropriate option in your application (for example, but no limited to, logs processing) you may turn autoack off.
And yes, having `autoack` unset requ... |
How to rotate a simple matplotlib Axes | 21,652,631 | 3 | 2014-02-08T22:33:12Z | 21,654,433 | 8 | 2014-02-09T02:20:50Z | [
"python",
"matplotlib"
] | is it possible to rotate matplotlib.axes.Axes as it is for matplotlib.text.Text
```
# text and Axes instance
t = figure.text(0.5,0.5,"some text")
a = figure.add_axes([0.1,0.1,0.8,0.8])
# rotation
t.set_rotation(angle)
a.set_rotation()???
```
a simple set\_rotation on a text instance will rotate the text by the angle ... | Are you asking how to rotate the entire axes (and not just the text)?
If so, yes, it's possible, but you have to know the extents of the plot beforehand.
You'll have to use `axisartist`, which allows more complex relationships like this, but is a bit more complex and not meant for interactive visualization. If you tr... |
Matplotlib drag overlapping points interactively | 21,654,008 | 4 | 2014-02-09T01:20:50Z | 21,688,791 | 7 | 2014-02-10T21:58:12Z | [
"python",
"matplotlib"
] | In my case, I only want to drag one point each time. However, since the two points are heavily overlapping, dragging one point would cause another point to be dragged. How can I only drag the point that is on the above? Thank you!
```
from pylab import *
from scipy import *
import matplotlib.pyplot as plt
import matpl... | Joe's method works fine, but it makes a set of draggablepoints as a class instead of a single draggablepoint class. I just came across an alternative method to solve the above problem using [animation blit techniques](http://matplotlib.org/users/event_handling.html). It not only makes the dragging faster and smoother, ... |
Scatter plots in Pandas/Pyplot: How to plot by category | 21,654,635 | 23 | 2014-02-09T02:51:57Z | 21,655,221 | 9 | 2014-02-09T04:19:30Z | [
"python",
"matplotlib",
"pandas"
] | I am trying to make a simple scatter plot in pyplot using a Pandas DataFrame object, but want an efficient way of plotting two variables but have the symbols dictated by a third column (key). I have tried various ways using df.groupby, but not successfully. A sample df script is below. This colours the markers accordin... | With `plt.scatter`, I can only think of one: to use a proxy artist:
```
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.... |
Scatter plots in Pandas/Pyplot: How to plot by category | 21,654,635 | 23 | 2014-02-09T02:51:57Z | 21,655,256 | 34 | 2014-02-09T04:23:06Z | [
"python",
"matplotlib",
"pandas"
] | I am trying to make a simple scatter plot in pyplot using a Pandas DataFrame object, but want an efficient way of plotting two variables but have the symbols dictated by a third column (key). I have tried various ways using df.groupby, but not successfully. A sample df script is below. This colours the markers accordin... | You can use `scatter` for this, but that requires having numerical values for your `key1`, and you won't have a legend, as you noticed.
It's better to just use `plot` for discrete categories like this. For example:
```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
np.random.seed(1974)
# Gene... |
Simple explanation of Google App Engine NDB Datastore | 21,655,862 | 11 | 2014-02-09T05:53:29Z | 21,656,687 | 7 | 2014-02-09T07:54:19Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I'm creating a Google App Engine application (python) and I'm learning about the general framework. I've been looking at the tutorial and documentation for the NDB datastore, and I'm having some difficulty wrapping my head around the concepts. I have a large background with SQL databases and I've never worked with any ... | Datastore [keys](https://developers.google.com/appengine/docs/python/ndb/keyclass) are a little more analogous to internal SQL row identifiers, but of course not entirely. Identifiers in Appengine are a bit like SQL primary keys. To support decentralised concurrent creation of new keys by many application instances in ... |
Simple explanation of Google App Engine NDB Datastore | 21,655,862 | 11 | 2014-02-09T05:53:29Z | 21,658,988 | 9 | 2014-02-09T12:24:34Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I'm creating a Google App Engine application (python) and I'm learning about the general framework. I've been looking at the tutorial and documentation for the NDB datastore, and I'm having some difficulty wrapping my head around the concepts. I have a large background with SQL databases and I've never worked with any ... | I think you've overcomplicating things in your mind. When you create an entity, you can either give it a named key that you've chosen yourself, or leave that out and let the datastore choose a numeric ID. Either way, when you call `put`, the datastore will return the key, which is stored in the form `[<entity_kind>, <i... |
How to show related objects in Django/Admin? | 21,657,225 | 6 | 2014-02-09T09:07:58Z | 21,657,286 | 8 | 2014-02-09T09:15:51Z | [
"python",
"django"
] | I have 2 models:
```
from django.db import models
class Category(models.Model):
icon = models.ImageField(upload_to = 'thing/icon/')
image = models.ImageField(upload_to = 'thing/image/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
title = mo... | You can use "Inlines" to visualize and edit Things of a certain Category in the admin detail for that category:
In the admin.py file, create an Inline object for Thing (ThingInline) and modify your CategoryAdmin class to have an inline of type ThingInline like this:
```
...
class ThingInline(admin.TabularInline):
... |
Python ImportError: cannot import name itemgetter | 21,657,685 | 2 | 2014-02-09T09:59:36Z | 21,658,399 | 7 | 2014-02-09T11:20:07Z | [
"python",
"urllib"
] | ```
Python 2.7.5 (default, Sep 12 2013, 12:43:04)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/urllib.py", line 33, in <modu... | You have a file called operator.py in the current directory, so `import operator` is picking up your module and not the Python standard library module `operator`.
You should rename your file to not conflict with Python's standard library. |
Cython Numpy code not faster than pure python | 21,658,356 | 8 | 2014-02-09T11:15:26Z | 21,658,808 | 18 | 2014-02-09T12:03:41Z | [
"python",
"optimization",
"numpy",
"cython"
] | First I know that there are many similarly themed question on SO, but I can't find a solution after a day of searching, reading, and testing.
I have a python function which calculates the pairwise correlations of a numpy ndarray (m x n). I was orginally doing this purely in numpy but the function also computed the rec... | Profiling with [`kernprof`](http://pythonhosted.org/line_profiler/) shows the bottleneck is the last line of the loop:
```
Line # Hits Time Per Hit % Time Line Contents
==============================================================
<snip>
16 5000 6145280 1229.1 86.6 runnin... |
How to sharex when using subplot2grid | 21,661,526 | 12 | 2014-02-09T16:15:26Z | 21,661,696 | 14 | 2014-02-09T16:30:33Z | [
"python",
"matplotlib"
] | I'm a Matlab user recently converted to Python. Most of the Python skills I manage on my own, but with plotting I have hit the wall and need some help.
This is what I'm trying to do...
I need to make a figure that consists of 3 subplots with following properties:
* subplot layout is 311, 312, 313
* the height of 312... | Just specify `sharex=ax1` when creating your second and third subplots.
```
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = s1*s2
fig = plt.figure()
ax1 = plt.subplot2grid((4,3), (0,0), colspan=3, rowspan=2)
ax2 = plt.subplot2grid((4,3), (... |
Splitting a string with brackets using regular expression in python | 21,662,474 | 2 | 2014-02-09T17:35:29Z | 21,662,493 | 8 | 2014-02-09T17:37:04Z | [
"python",
"regex"
] | Suppose I have a string like `str = "[Hi all], [this is] [an example] "`. I want to split it into several pieces, each of which consists content inside a pair bracket. In another word, i want to grab the phrases inside each pair of bracket. The result should be like:
```
['Hi all', 'this is', 'an example']
```
How ca... | ```
data = "[Hi all], [this is] [an example] "
import re
print re.findall("\[(.*?)\]", data) # ['Hi all', 'this is', 'an example']
```

[Debuggex Demo](https://www.debuggex.com/r/qiG6j-36Tv9nyv4G) |
Python 'list indices must be integers, not tuple" | 21,662,532 | 17 | 2014-02-09T17:40:49Z | 21,662,549 | 9 | 2014-02-09T17:42:03Z | [
"python",
"list"
] | I have been banging my head against this for two days now. I am new to python and programming so the other examples of this type of error have not helped me to much. I am reading through the documentation for lists and tuples, but haven't found anything that helps. Any pointer would be much appreciated. Not looking for... | To create list of lists, you need to separate them with commas, like this
```
coin_args = [
["pennies", '2.5', '50.0', '.01'],
["nickles", '5.0', '40.0', '.05'],
["dimes", '2.268', '50.0', '.1'],
["quarters", '5.67', '40.0', '.25']
]
``` |
Python 'list indices must be integers, not tuple" | 21,662,532 | 17 | 2014-02-09T17:40:49Z | 21,662,608 | 30 | 2014-02-09T17:46:11Z | [
"python",
"list"
] | I have been banging my head against this for two days now. I am new to python and programming so the other examples of this type of error have not helped me to much. I am reading through the documentation for lists and tuples, but haven't found anything that helps. Any pointer would be much appreciated. Not looking for... | The problem is that `[...]` in python has two distinct meanings
1. `expr [ index ]` means accessing an element of a list
2. `[ expr1, expr2, expr3 ]` means building a list of three elements from three expressions
In your code you forgot the comma between the expressions for the items in the outer list:
```
[ [a, b, ... |
linux tee is not working with python? | 21,662,783 | 29 | 2014-02-09T18:01:36Z | 21,663,010 | 46 | 2014-02-09T18:21:24Z | [
"python",
"linux",
"tee"
] | I made a python script which communicates with a web server using an infinite loop.
I want to log every communication data to a file and also monitor them from terminal at same time. so I used tee command like this.
```
python client.py | tee logfile
```
however, I got nothing from terminal nor logfile.
the python sc... | From `man python`:
```
-u Force stdin, stdout and stderr to be totally unbuffered. On systems
where it matters, also put stdin, stdout and stderr in binary mode. Note
that there is internal buffering in xreadlines(), readlines() and file-
object iterators ("for line in... |
Python: make a list generator JSON serializable | 21,663,800 | 9 | 2014-02-09T19:25:57Z | 24,033,219 | 9 | 2014-06-04T09:04:24Z | [
"python",
"json",
"out-of-memory",
"generator"
] | How can I concat a list of JSON files into a huge JSON array? I've 5000 files and 550 000 list items.
My fist try was to use [jq](http://stedolan.github.io/jq/), but it looks like jq -s is not optimized for a large input.
```
jq -s -r '[.[][]]' *.js
```
This command works, but takes way too long to complete and I re... | You should derive from `list` and override `__iter__` method.
```
import json
def gen():
yield 20
yield 30
yield 40
class StreamArray(list):
def __iter__(self):
return gen()
# according to the comment below
def __len__(self):
return 1
a = [1,2,3]
b = StreamArray()
print(jso... |
Python: make a list generator JSON serializable | 21,663,800 | 9 | 2014-02-09T19:25:57Z | 31,517,812 | 8 | 2015-07-20T13:28:31Z | [
"python",
"json",
"out-of-memory",
"generator"
] | How can I concat a list of JSON files into a huge JSON array? I've 5000 files and 550 000 list items.
My fist try was to use [jq](http://stedolan.github.io/jq/), but it looks like jq -s is not optimized for a large input.
```
jq -s -r '[.[][]]' *.js
```
This command works, but takes way too long to complete and I re... | As of simplejson 3.8.0, you can use the `iterable_as_array` option to make any iterable serializable into an array
```
# Since simplejson is backwards compatible, you should feel free to import
# it as `json`
import simplejson as json
json.dumps((i*i for i in range(10)), iterable_as_array=True)
```
result is `[0, 1, ... |
Why doesn't \b\w+\b match a word? | 21,664,290 | 3 | 2014-02-09T20:03:16Z | 21,664,309 | 8 | 2014-02-09T20:04:32Z | [
"python",
"regex"
] | Why does the following Python statement return `None`?
```
>>> re.match('\b\w+\b', 'foo')
>>>
```
As far as I understand, that should match the word `foo`. The first `\b` should match the beginning of the word `foo`, `\w+` should match the word `foo`, and the final `\b` should match the end of the word `foo`. What is... | If you don't escape backslash in `\b`, `\b` matches backspace, not word boundary.
```
>>> '\b' # BACKSPACE, not \ + b
'\x08'
>>> '\\b' # \ + b
'\\b'
>>> r'\b' # raw string literal (r'\b' == '\\b')
'\\b'
>>> re.match('\b\w+\b', 'foo')
>>> re.match(r'\b\w+\b', 'foo')
<_sre.SRE_Match object at 0x0000000002C18100>... |
Python multiprocessing and independence of children processes | 21,665,341 | 6 | 2014-02-09T21:33:08Z | 21,666,430 | 8 | 2014-02-09T23:14:49Z | [
"python",
"subprocess",
"multiprocessing",
"children",
"orphan"
] | From the python terminal, I run some command like the following, to spawn a long-running child process:
```
from multiprocessing.process import Process
Process(target=LONG_RUNNING_FUNCTION).start()
```
This command returns, and I can do other things in the python terminal, but anything printed by the child is still p... | This isn't a matter of how you're invoking python; it's a feature of the `multiprocessing` module. When you import that module an exit handler is added to the parent process that calls `join()` on the `Process` objects of all children created via `multiprocessing.Process` before allowing the parent to exit. If you're g... |
Celery auto reload on ANY changes | 21,666,229 | 10 | 2014-02-09T22:53:56Z | 28,309,657 | 9 | 2015-02-03T22:05:27Z | [
"python",
"celery",
"django-celery"
] | I could make celery reload itself automatically when there is changes on modules in `CELERY_IMPORTS` in `settings.py`.
I tried to give mother modules to detect changes even on child modules but it did not detect changes in child modules. That make me understand that detecting is not done recursively by celery. I searc... | You can manually include additional modules with `-I|--include`. Combine this with GNU tools like `find` and `awk` and you'll be able to find all `.py` files and include them.
```
$ celery -A app worker --autoreload --include=$(find . -name "*.py" -type f | awk '{sub("\./",""); gsub("/", "."); sub(".py",""); print}' O... |
convert string to hex in python | 21,669,374 | 9 | 2014-02-10T04:56:55Z | 21,669,474 | 9 | 2014-02-10T05:05:41Z | [
"python",
"converter",
"hex"
] | I have a script that calls a function that takes a hexadecimal number for an argument. The argument needs to the 0x prefix. The data source is a database table and is stored as a string, so it is returned '0x77'. I am looking for a way to take the string from the database and use it as an argument in hex form with the ... | Your `class.function` expects an *integer* which can be represented either by a decimal or a hexadecimal *literal*, so that these two calls are completely equivalent:
```
class.function(0x77)
class.function(119) # 0x77 == 119
```
Even `print(0x77)` will show `119` (because decimal is the default representation).
So... |
Getting "cannot write mode P as JPEG" while operating on JPG image | 21,669,657 | 24 | 2014-02-10T05:22:52Z | 21,669,827 | 56 | 2014-02-10T05:37:35Z | [
"python",
"osx",
"python-imaging-library",
"pillow"
] | I am trying to resize some images, most of which are JPG. But in a few images, I am getting the error:
```
Traceback (most recent call last):
File "image_operation_new.py", line 168, in modifyImage
tempImage.save(finalName);
File "/Users/kshitiz/.virtualenvs/django_project/lib/python2.7/site- packages/PIL/... | You need to convert the image to RGB mode.
```
Image.open('old.jpeg').convert('RGB').save('new.jpeg')
``` |
how to find global minimum in python optimization with bounds? | 21,670,080 | 7 | 2014-02-10T06:00:41Z | 21,967,888 | 14 | 2014-02-23T11:59:17Z | [
"python",
"optimization",
"scipy",
"numeric",
"mathematical-optimization"
] | I have a Python function with 64 variables, and I tried to optimise it using L-BFGS-B method in the minimise function, however this method have quite a strong dependence on the initial guess, and failed to find the global minimum.
But I liked its ability to set bounds for the variables. Is there a way/function to find... | This can be done with `scipy.optimize.basinhopping`. Basinhopping is a function designed to find the *global* minimum of an objective function. It does repeated minimizations using the function `scipy.optimize.minimize` and takes a random step in coordinate space after each minimization. Basinhopping can still respect ... |
Extract data from JSON API using Python | 21,670,239 | 2 | 2014-02-10T06:14:23Z | 21,670,407 | 8 | 2014-02-10T06:27:07Z | [
"python",
"json",
"api",
"openurl"
] | I go through this part:
How do I extract the data from that URL? I only want to print out the `"networkdiff": 58954.60268219`.
```
from urllib import urlopen
url = urlopen('http://21.luckyminers.com/index.php?page=api&action=getpoolstatus&api_key=8dba7050f9fea1e6a554bbcf4c3de5096795b253b45525c53562b72938771c41').rea... | You can use the `json` module to parse out a Python dictionary and get right to the value like so:
```
import json
result = json.loads(url) # result is now a dict
print '"networkdiff":', result['getpoolstatus']['data']['networkdiff']
```
To do this multiple times (to answer your question in the comments section):
`... |
What user will Ansible run my commands as? | 21,670,747 | 31 | 2014-02-10T06:51:45Z | 21,680,256 | 31 | 2014-02-10T14:47:27Z | [
"python",
"linux",
"node.js",
"git",
"ansible"
] | ## Background
My question seems simple, but it gets more complex really fast.
Basically, I got really tired of maintaining my servers manually *(screams in background)* and I decided it was time to find a way to make being a server admin much more livable. That's when I found Ansible. Great huh? Sure beats making bas... | You may find it useful to read the Hosts and Users section on Ansible's documentation site:
<http://docs.ansible.com/playbooks_intro.html#hosts-and-users>
In summary, ansible will run all commands in a playbook as the user specified in the `remote_user` variable (assuming you're using ansible >= 1.4, `user` before th... |
Link ATLAS/MKL to an installed Numpy | 21,671,040 | 17 | 2014-02-10T07:12:11Z | 21,673,585 | 19 | 2014-02-10T09:41:29Z | [
"python",
"performance",
"numpy",
"linear-algebra",
"blas"
] | **TL;DR** how to link ATLAS/MKL to existing Numpy without rebuilding.
I have used Numpy to calculate with the large matrix and I found that it is very slow because Numpy only use 1 core to do calculation. After doing a lot of search I figure that my Numpy does not link to some optimized library like ATLAS/MKL. Here is... | Assuming you're running some flavour of linux, here's one way you could do it:
1. Find out what BLAS library numpy is currently linked against using `ldd`.
* **For versions of numpy older than v1.10:**
```
$ ldd /<path_to_site-packages>/numpy/core/_dotblas.so
```
For example, if I install num... |
Flask-SQLAlchemy filters and operators | 21,674,303 | 2 | 2014-02-10T10:14:27Z | 21,676,774 | 10 | 2014-02-10T12:05:52Z | [
"python",
"sqlalchemy",
"flask",
"operators",
"flask-sqlalchemy"
] | Flask-SQLAlchemy gives the option to filter a query. There are a wide number of ways you can filter a query - the examples the Flask-SQLAlchemy docs give:
```
User.query.filter_by(username='peter') # Returns all users named 'peter'
User.query.filter(User.email.endswith('@example.com')) # Returns all users with emails ... | For a list of filters check [SQLAlchemy documentation](http://docs.sqlalchemy.org/en/rel_0_9/orm/query.html)
> > what filter would I use to check if a user's email is contained within a particular set of email addresses?
Columns have a `.in_()` method to use in query. So something like:
```
res = User.query.filter(U... |
Group by multiple keys and summarize/average values of a list of dictionaries | 21,674,331 | 7 | 2014-02-10T10:15:38Z | 21,674,471 | 14 | 2014-02-10T10:22:32Z | [
"python",
"list",
"dictionary"
] | What is the most pythonic way to group by multiple keys and summarize/average values of a list of dictionaries in Python please? Say I have a list of dictionaries as below:
```
input = [
{'dept': '001', 'sku': 'foo', 'transId': 'uniqueId1', 'qty': 100},
{'dept': '001', 'sku': 'bar', 'transId': 'uniqueId2', 'qty': 200}... | To get the aggregated results
```
from itertools import groupby
from operator import itemgetter
grouper = itemgetter("dept", "sku")
result = []
for key, grp in groupby(sorted(input_data, key = grouper), grouper):
temp_dict = dict(zip(["dept", "sku"], key))
temp_dict["qty"] = sum(item["qty"] for item in grp)
... |
Python: Concatenate list of lists in the algebraic way | 21,682,129 | 4 | 2014-02-10T16:08:11Z | 21,682,222 | 7 | 2014-02-10T16:12:23Z | [
"python",
"list",
"itertools"
] | In maths, when you have two sets of words *A={foo,bar}* and *B={x,y}*, then the algebraic (or each-to-each) product is *AB={foox,fooy,barx,bary}*. I would like a similar thing in Python. Given two sets of words (= list of lists):
```
A = [ [0,1], [2,3] ]
B = [ [4,5], [6,7] ]
```
I would like to concatenate them each-... | ```
ABC = [ sum(z, []) for z in itertools.product(*SETS) ]
```
`product(*SETS)` basically does `product(A, B, C)`. The technical term is [argument unpacking](http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists).
`sum(z, [])` basically does `a + b + c + []`.
**EDIT**:
As smart people said in ... |
Pass command line parameters to uwsgi script | 21,685,577 | 10 | 2014-02-10T18:56:56Z | 21,692,823 | 17 | 2014-02-11T03:59:26Z | [
"python",
"wsgi",
"uwsgi"
] | I'm trying to pass arguments to an example wsgi application, :
```
config_file = sys.argv[1]
def application(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World %s" % config_file]
```
And run:
```
uwsgi --http :9090 --wsgi-file test_uwsgi.py -???? config_fil... | python args:
--pyargv "foo bar"
```
sys.argv
['uwsgi', 'foo', 'bar']
```
uwsgi options:
--set foo=bar
```
uwsgi.opt['foo']
'bar'
``` |
Multi-language syntax highlighting in Emacs | 21,685,612 | 6 | 2014-02-10T18:58:37Z | 21,686,480 | 11 | 2014-02-10T19:45:02Z | [
"python",
"sql",
"emacs"
] | Say I have code from multiple languages in a single buffer, can I have emacs syntax highlight each snippet according to its corresponding language?
For example, the following code is part of a python script, but it contains SQL code:
```
import psycopg2 as pg
import pandas.io.sql as psql
# Some SQL code:
my_query ='... | When I'm using some SQL in C, I have a system using MMM-Mode; wrapping the required statement in a set of comments,
```
/* SQL */
```
and
```
/* #SQL */
```
the following will give me SQL syntax highlighting:
```
(require 'mmm-mode)
(set-face-background 'mmm-default-submode-face nil)
(mmm-add-classes
'((embe... |
Using Python and lxml to strip only the tags that have certain attributes/values | 21,685,795 | 6 | 2014-02-10T19:08:58Z | 21,686,786 | 7 | 2014-02-10T20:02:01Z | [
"python",
"lxml"
] | I'm familiar with etree's `strip_tags` and `strip_elements` methods, but I'm looking for a straightforward way of stripping tags (and leaving their contents) that only contain particular attributes/values.
For instance: I'd like to strip all `span` or `div` tags (or other elements) from a tree (`xhtm`l) that have a `c... | # HTML
`lxml`s HTML elements have a method [`drop_tag()`](http://lxml.de/lxmlhtml.html#html-element-methods) which you can call on any element in a tree parsed by `lxml.html`.
It acts similar to `strip_tags` in that it removes the element, but retains the text, and it can be called *on* the element - which means you ... |
TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data | 21,687,581 | 18 | 2014-02-10T20:48:10Z | 21,697,288 | 41 | 2014-02-11T09:03:45Z | [
"python",
"arrays",
"logging",
"scalar"
] | ```
f=np.loadtxt('Single Small Angle 1.txt',unpack=True,skiprows=2)
g=np.loadtxt('Single Small Angle 5.txt',unpack=True,skiprows=2)
x = f-g[:,:11944]
t=range(len(x))
m=math.log10(abs(x))
np.polyfit(t,m)
plt.plot(t,abs(x))
plt.show()
```
I'm just not sure on how to fix my issue. It keeps saying:
```
m=math.log10(ab... | Non-numpy functions like `math.abs()` or `math.log10()` don't play nicely with numpy arrays. Just replace the line raising an error with:
```
m = np.log10(np.abs(x))
```
Apart from that the `np.polyfit()` call will not work because it is missing a parameter (and you are not assigning the result for further use an... |
TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data | 21,687,581 | 18 | 2014-02-10T20:48:10Z | 36,242,627 | 11 | 2016-03-27T00:46:23Z | [
"python",
"arrays",
"logging",
"scalar"
] | ```
f=np.loadtxt('Single Small Angle 1.txt',unpack=True,skiprows=2)
g=np.loadtxt('Single Small Angle 5.txt',unpack=True,skiprows=2)
x = f-g[:,:11944]
t=range(len(x))
m=math.log10(abs(x))
np.polyfit(t,m)
plt.plot(t,abs(x))
plt.show()
```
I'm just not sure on how to fix my issue. It keeps saying:
```
m=math.log10(ab... | **Here is another way to reproduce this error in Python2.7 with numpy:**
```
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b)
print(c)
```
The `np.concatenate` method produces an error:
```
TypeError: only length-1 arrays can be converted to Python scalars
```
If you read the d... |
specifying fixture argument for py.test from command line | 21,688,111 | 4 | 2014-02-10T21:17:52Z | 21,697,558 | 8 | 2014-02-11T09:16:21Z | [
"python",
"command-line-arguments",
"py.test"
] | I'd like to pass a command line argument to py.test for fixture creation. For example, I'd like to pass a database hostname to the fixture creation below, so it won't be hard-coded:
```
import pytest
def pytest_addoption(parser):
parser.addoption("--hostname", action="store", default='127.0.0.1', help="specify IP... | What is the layout of your files? It seems you are trying to put all this code in the test\_opt.py module. However the `pytest_addoption()` hook will only get read from a conftest.py file. So you should try moving the `pytest_addoption()` function to a conftest.py file in the same directory as test\_opt.py.
In general... |
Method Not Allowed flask error 405 | 21,689,364 | 8 | 2014-02-10T22:38:03Z | 21,689,599 | 15 | 2014-02-10T22:54:06Z | [
"python",
"forms",
"flask"
] | I am developing a flask registration form, and I receive an error:
```
error 405 method not found.
```
Code:
```
import os
# Flask
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, Markup, send_from_directory, escape
from werkzeug import secure_filename
from cult... | This is because you only allow POST requests when defining your route.
When you visit `/registrazione` in your browser, it will do a GET request first. Only once you submit the form your browser will do a POST. So for a self-submitting form like yours, you need to handle both.
Using
```
@app.route('/registrazione', ... |
Python 3 TypeError: must be str, not bytes with sys.stdout.write() | 21,689,365 | 16 | 2014-02-10T22:38:05Z | 21,689,447 | 27 | 2014-02-10T22:43:58Z | [
"python"
] | I was looking for a way to run an external process from python script and print its stdout messages during the execution.
The code below works, but prints no stdout output during runtime. When it exits I am getting the following error:
> sys.stdout.write(nextline) TypeError:must be str,not bytes
```
p = subprocess.... | Python 3 handles strings a bit different. Originally there was just one type for
strings: `str`. When unicode gained traction in the '90s the new `unicode` type
was added to handle Unicode without breaking pre-existing code1. This is
effectively the same as `str` but with multibyte support.
In Python 3 there are two d... |
pandas attribute error : no attribute 'Factor' found | 21,689,423 | 11 | 2014-02-10T22:42:27Z | 21,689,542 | 35 | 2014-02-10T22:50:31Z | [
"python",
"python-2.7",
"pandas"
] | I'm trying to run code provided by yhat [in their article about random forests in Python](http://blog.yhathq.com/posts/random-forests-in-python.html), but I keep getting following error message:
```
File "test_iris_with_rf.py", line 11, in <module>
df['species'] = pd.Factor(iris.target, iris.target_names)
Attribut... | In newer versions of pandas, the `Factor` is called `Categorical` instead. Change your line to:
```
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
``` |
pandas attribute error : no attribute 'Factor' found | 21,689,423 | 11 | 2014-02-10T22:42:27Z | 27,769,102 | 7 | 2015-01-04T18:51:27Z | [
"python",
"python-2.7",
"pandas"
] | I'm trying to run code provided by yhat [in their article about random forests in Python](http://blog.yhathq.com/posts/random-forests-in-python.html), but I keep getting following error message:
```
File "test_iris_with_rf.py", line 11, in <module>
df['species'] = pd.Factor(iris.target, iris.target_names)
Attribut... | Categorical variables seems to be one of the more active areas of development in pandas, so I believe it's changed yet again in pandas 0.15.0 :
```
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
```
(I lacked sufficient reputation to add this as a comment on David Robinson's answer) |
Jinja2 Exception Handling | 21,692,387 | 5 | 2014-02-11T03:20:31Z | 21,763,226 | 9 | 2014-02-13T19:02:34Z | [
"python",
"templates",
"exception",
"django-templates",
"jinja2"
] | Is there a way to handle exceptions within a template in jinja2?
```
{% for item in items %}
{{ item|urlencode }} <-- item contains a unicode string that contains a character causes urlencode to throw KeyError
{% endfor %}
```
How do I handle that exception so that I can just skip that item or handle it without f... | ```
{% for item in items %}
{{ item | custom_urlencode_filter }}
{% endfor %}
```
Then in whatever file you have setting up your jinja2 environment
```
def custom_urlencode_filter(value):
try:
return urlencode(value)
except:
# handle the exception
environment.filters['custom_urlencode_fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.