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 |
|---|---|---|---|---|---|---|---|---|---|
Calling list() empties my iterable object? | 34,732,641 | 13 | 2016-01-11T22:54:53Z | 34,732,710 | 25 | 2016-01-11T22:59:04Z | [
"python",
"list"
] | ```
a = range(1, 3)
a = iter(a)
list(a)
a = list(a)
```
`a` evaluates to `[ ]`.
```
a = range(1, 3)
a = iter(a)
a = list(a)
```
`a` evaluates to `[1, 2]`.
The first result is unexpected to me. What semantics are going on here? | The issue is not `list()` but [`iter()`](https://docs.python.org/3.5/library/functions.html#iter) which as documented returns a single-use [`iterator`](https://docs.python.org/3.5/glossary.html#term-iterator). Once something has accessed the `iterator`'s elements, the iterator is permanently empty. The more commonly us... |
why is list[-1:1] empty in python? | 34,737,719 | 3 | 2016-01-12T07:24:29Z | 34,737,763 | 11 | 2016-01-12T07:26:52Z | [
"python",
"list"
] | ```
>>>list=[1,2,3]
>>>list[1:2]
2
>>>list[-1:1]
[]
```
In python, `list[first:last]` is `return list[first,first+1,...last-1]`
but `list[-1:1]` is return empty, why not include `list[-1]`? | What are you expecting to return? Your `-1` position in that list is `2`, so your `list[-1:1]` is the same as `list[2:1]` which is empty list. You could do it with `step=-1`:
```
list[-1:1:-1]
3
```
*Note*: Usually it's not a good idea to reassign built-in variables such as `list`. It's better to use some othe name, ... |
How to remove final character in a number of strings? | 34,739,993 | 3 | 2016-01-12T09:36:38Z | 34,740,092 | 10 | 2016-01-12T09:41:21Z | [
"python",
"string",
"trailing"
] | I have a number of strings that I would like to remove the last character of each string. When I try out the code below it removes my second line of string instead of removing the last element. Below is my code:
**Code**
```
with open('test.txt') as file:
seqs=file.read().splitlines()
seqs=seqs[:-1]
```
**te... | Change this `seqs=seqs[:-1]`
to a [`list comprehension`](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions):
```
seqs=[val[:-1] for val in seqs]
```
**Note:**
* The problem in your old method is that `seq` is a list of strings`i.e)["ABCABC","XYZXYZ"]`. You are just getting the before last i... |
How to specify test timeout for python unittest? | 34,743,448 | 4 | 2016-01-12T12:15:40Z | 34,743,601 | 7 | 2016-01-12T12:23:06Z | [
"python",
"unit-testing",
"timeout"
] | I'm using `python` framework `unittest`. Is it possible to specify by framework's abilities a timeout for test? If no, is it possible to specify gracefully a `timeout` for all tests and for some separated tests a private value for each one?
I want to define a `global timeout` for all tests (they will use it by defaul... | As far as I know [`unittest`](https://docs.python.org/2.7/library/unittest.html) does not contain any support for tests timeout.
You can try [`timeout-decorator`](https://pypi.python.org/pypi/timeout-decorator) library from PyPI. Apply the decorator on individual tests to make them terminate if they take too long:
``... |
Tuples and Dictionaries contained within a List | 34,748,017 | 6 | 2016-01-12T15:48:27Z | 34,748,108 | 7 | 2016-01-12T15:52:10Z | [
"python",
"list",
"dictionary",
"tuples"
] | I am trying to a obtain a specific dictionary from within a list that contains both tuples and dictionaries. How would I go about returning the dictionary with key 'k' from the list below?
```
lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}]
``` | For your
```
lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}]
```
using
```
next(elem for elem in lst if isinstance(elem, dict) and 'k' in elem)
```
returns
```
{'k': [1, 2, 3]}
```
i.e. the first object of your list which is a dictionary and contains key 'k'.
This raises `StopIteration` if no... |
Using moviepy, scipy and numpy in amazon lambda | 34,749,806 | 21 | 2016-01-12T17:12:06Z | 34,882,192 | 12 | 2016-01-19T16:39:57Z | [
"python",
"amazon-web-services",
"numpy",
"aws-lambda"
] | I'd like to generate video using `AWS Lambda` feature.
I've followed instructions found [here](http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-deployment-pkg.html#with-s3-example-deployment-pkg-python) and [here](http://www.perrygeo.com/running-python-with-compiled-code-on-aws-lambda.html).
And I now have... | I was also following your first link and managed to import **numpy** and **pandas** in a Lambda function this way (on Windows):
1. Started a (free-tier) **t2.micro** [EC2 instance](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#ec2-launch-instance_linux) with 64-bit Amazon Linux AMI 2015.09.1 a... |
Python with...as for custom context manager | 34,749,943 | 20 | 2016-01-12T17:19:11Z | 34,749,982 | 7 | 2016-01-12T17:21:10Z | [
"python"
] | I wrote a simple context manager in Python for handling unit tests (and to try to learn context managers):
```
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test_count += 1
def __enter__(self):
pass
def __exit... | ```
def __enter__(self):
return self
```
will make it work. The value returned from this method will be assigned to the `as` variable.
See also [the Python doc](https://docs.python.org/2/reference/compound_stmts.html#grammar-token-with_stmt):
> If a target was included in the `with` statement, the return value f... |
Python with...as for custom context manager | 34,749,943 | 20 | 2016-01-12T17:19:11Z | 34,749,985 | 22 | 2016-01-12T17:21:18Z | [
"python"
] | I wrote a simple context manager in Python for handling unit tests (and to try to learn context managers):
```
class TestContext(object):
test_count=1
def __init__(self):
self.test_number = TestContext.test_count
TestContext.test_count += 1
def __enter__(self):
pass
def __exit... | [`__enter__` needs to return `self`](https://docs.python.org/2/reference/datamodel.html#object.__enter__).
> The with statement will bind this methodâs return value to the target(s) specified in the as clause of the statement, if any.
This will work.
```
class TestContext(object):
test_count=1
def __init__... |
Read a python variable in a shell script? | 34,751,930 | 5 | 2016-01-12T19:12:16Z | 34,752,001 | 7 | 2016-01-12T19:17:02Z | [
"python",
"bash",
"shell"
] | my python file has these 2 variables:
```
week_date = "01/03/16-01/09/16"
cust_id = "12345"
```
how can i read this into a shell script that takes in these 2 variables?
my current shell script requires manual editing of "dt" and "id". I want to read the python variables into the shell script so i can just edit my py... | Consider something akin to the following:
```
#!/bin/bash
# ^^^^ NOT /bin/sh, which doesn't have process substitution available.
python_script='
import sys
d = {} # create a context for variables
exec(open(sys.argv[1], "r").read()) in d # execute the Python code in that contex... |
Difference between coroutine and future/task in Python 3.5? | 34,753,401 | 21 | 2016-01-12T20:43:00Z | 34,753,649 | 16 | 2016-01-12T20:57:17Z | [
"python",
"python-asyncio",
"python-3.5"
] | Let's say we have a dummy function:
```
async def foo(arg):
result = await some_remote_call(arg)
return result.upper()
```
What's the difference between:
```
coros = []
for i in range(5):
coros.append(foo(i))
loop = get_event_loop()
loop.run_until_complete(wait(coros))
```
And:
```
from asyncio import... | A coroutine is a generator function that can both yield values and accept values from the outside. The benefit of using a coroutine is that we can pause the execution of a function and resume it later. In case of a network operation, it makes sense to pause the execution of a function while we're waiting for the respon... |
Most pythonic way to interleave two strings | 34,756,145 | 96 | 2016-01-13T00:06:53Z | 34,756,161 | 43 | 2016-01-13T00:08:35Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] | What's the most pythonic way to mesh two strings together?
For example:
Input:
```
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` | With `join()` and `zip()`.
```
>>> ''.join(''.join(item) for item in zip(u,l))
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` |
Most pythonic way to interleave two strings | 34,756,145 | 96 | 2016-01-13T00:06:53Z | 34,756,226 | 118 | 2016-01-13T00:13:42Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] | What's the most pythonic way to mesh two strings together?
For example:
Input:
```
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` | For me, the most pythonic\* way is the following which *pretty much does the same thing* but uses the `+` operator for concatenating the individual characters in each string:
```
res = "".join(i + j for i, j in zip(u, l))
print(res)
# 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
```
It is also faster than u... |
Most pythonic way to interleave two strings | 34,756,145 | 96 | 2016-01-13T00:06:53Z | 34,756,604 | 15 | 2016-01-13T00:53:27Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] | What's the most pythonic way to mesh two strings together?
For example:
Input:
```
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` | If you want the fastest way, you can combine [itertools](https://docs.python.org/2/library/itertools.html) with `operator.add`:
```
In [36]: from operator import add
In [37]: from itertools import starmap, izip
In [38]: timeit "".join([i + j for i, j in uzip(l1, l2)])
1 loops, best of 3: 142 ms per loop
In [39]: t... |
Most pythonic way to interleave two strings | 34,756,145 | 96 | 2016-01-13T00:06:53Z | 34,756,930 | 53 | 2016-01-13T01:30:36Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] | What's the most pythonic way to mesh two strings together?
For example:
Input:
```
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` | ## Faster Alternative
Another way:
```
res = [''] * len(u) * 2
res[::2] = u
res[1::2] = l
print(''.join(res))
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
```
## Speed
Looks like it is faster:
```
%%timeit
res = [''] * len(u) * 2
res[::2] = u
res[1::2] = l
''.join(res)
100000 loops, be... |
Most pythonic way to interleave two strings | 34,756,145 | 96 | 2016-01-13T00:06:53Z | 34,761,165 | 13 | 2016-01-13T07:55:50Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] | What's the most pythonic way to mesh two strings together?
For example:
Input:
```
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` | On Python 2, by *far* the faster way to do things, at ~3x the speed of list slicing for small strings and ~30x for long ones, is
```
res = bytearray(len(u) * 2)
res[::2] = u
res[1::2] = l
str(res)
```
This wouldn't work on Python 3, though. You could implement something like
```
res = bytearray(len(u) * 2)
res[::2] ... |
Most pythonic way to interleave two strings | 34,756,145 | 96 | 2016-01-13T00:06:53Z | 34,784,700 | 9 | 2016-01-14T08:23:24Z | [
"python",
"string",
"python-2.7",
"python-3.x"
] | What's the most pythonic way to mesh two strings together?
For example:
Input:
```
u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
l = 'abcdefghijklmnopqrstuvwxyz'
```
Output:
```
'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
``` | You could also do this using [`map`](https://docs.python.org/3/library/functions.html#map) and [`operator.add`](https://docs.python.org/3/library/operator.html#operator.add):
```
from operator import add
u = 'AAAAA'
l = 'aaaaa'
s = "".join(map(add, u, l))
```
**Output**:
```
'AaAaAaAaAa'
```
What map does is it t... |
Any reason to use "while 1, do something, break" in Python? | 34,756,466 | 4 | 2016-01-13T00:38:18Z | 34,756,566 | 7 | 2016-01-13T00:50:00Z | [
"python",
"while-loop",
"sympy"
] | In the Python library [SymPy](http://www.sympy.org/en/index.html) I try to understand the function `partitions()` in [`sympy.utilities.iterables`](https://github.com/sympy/sympy/blob/master/sympy%2Futilities%2Fiterables.py):
It starts like this:
```
def partitions(n, m=None, k=None, size=False):
"""Generate all p... | This is a dirty hack to bring [goto](https://en.wikipedia.org/wiki/Goto) to Python. The `while 1:` line is the label and the `continue` statement is the goto.
Please do not write code like that if you can avoid it. If you *must* do this, at least make it `while True:` since the argument to `while` is ordinarily a bool... |
Delete multiple dictionaries in a list | 34,763,208 | 5 | 2016-01-13T09:45:42Z | 34,763,252 | 11 | 2016-01-13T09:47:24Z | [
"python",
"list",
"dictionary"
] | I have been trying to delete multiple dictionaries in a list but I can only delete one at a time.
Below is the main code I am working on. Records is the list of dictionaries. I want to delete dictionaries that have 0 in them.
```
Records = [{'Name':'Kelvin','Price': 0},{'Name': 'Michael','Price':10}]
```
I want to d... | Use a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) with an `if` condition
```
>>> Records = [{'Name':'Kelvin','Price': 0},{'Name': 'Michael','Price':10}]
>>> [i for i in Records if i['Price'] != 0]
[{'Price': 10, 'Name': 'Michael'}]
```
Check out [Python: if/else in... |
create list by -5 and + 5 from given number | 34,765,433 | 3 | 2016-01-13T11:26:02Z | 34,765,470 | 13 | 2016-01-13T11:27:21Z | [
"python",
"list",
"python-2.7",
"range"
] | Suppose `num = 10`
want output like `[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]`
Tried : `range(num-5, num) + range(num, num+5)`
Is there an other way to achieve this ? | Use `range`'s start and stop parameters, like this
```
>>> range(num - 5, num + 5)
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
``` |
Python: Splat/unpack operator * in python cannot be used in an expression? | 34,766,677 | 19 | 2016-01-13T12:24:51Z | 34,767,282 | 25 | 2016-01-13T12:53:07Z | [
"python",
"python-2.7"
] | Does anybody know the reasoning as to why the unary (`*`) operator cannot be used in an expression involving iterators/lists/tuples?
Why is it only limited to function unpacking? or am I wrong in thinking that?
For example:
```
>>> [1,2,3, *[4,5,6]]
File "<stdin>", line 1
[1,2,3, *[4,5,6]]
^
SyntaxError: inv... | Not allowing unpacking in Python `2.x` has noted and fixed in Python `3.5` which now has this feature as described in **[PEP 448](https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-448)**:
```
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) on Windows (64 bits).
>>> [1, 2, 3, *[4, 5, 6]]
[1, 2, 3, 4, ... |
What is the Matlab equivalent to Python's `not in`? | 34,768,388 | 5 | 2016-01-13T13:48:25Z | 34,768,427 | 12 | 2016-01-13T13:49:50Z | [
"python",
"matlab"
] | In Python, one could get elements that are exclusive to `lst1` using:
```
lst1=['a','b','c']
lst2=['c','d','e']
lst3=[]
for i in lst1:
if i not in lst2:
lst3.append(i)
```
What would be the Matlab equivalent? | You are looking for MATLAB's [`setdiff`](http://www.mathworks.com/help/matlab/ref/setdiff.html) -
```
setdiff(lst1,lst2)
```
Sample run -
```
>> lst1={'a','b','c'};
>> lst2={'c','d','e'};
>> setdiff(lst1,lst2)
ans =
'a' 'b'
```
Verify with Python run -
```
In [161]: lst1=['a','b','c']
...: lst2=['c','... |
how to pick random items from a list while avoiding picking the same item in a row | 34,769,801 | 3 | 2016-01-13T14:54:41Z | 34,769,912 | 8 | 2016-01-13T14:59:27Z | [
"python",
"list",
"random"
] | I want to iterate through list with random values. However, I want the item that has been picked to be removed from the list for the next trial, so that I can avoid picking the same item in a row; but it should be added back again after.
please help me on showing that on this simple example.
Thank you
```
import rand... | Both work for list of non-unique elements as well:
```
def choice_without_repetition(lst):
prev = None
while True:
i = random.randrange(len(lst))
if i != prev:
yield lst[i]
prev = i
```
or
```
def choice_without_repetition(lst):
i = 0
while True:
i = (i... |
matplotlib taking time when being imported | 34,771,191 | 52 | 2016-01-13T15:54:39Z | 34,999,763 | 57 | 2016-01-25T18:33:26Z | [
"python",
"matplotlib"
] | I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message:
```
/usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is ... | As tom suggested in the comment above, deleting the files: fontList.cache, fontList.py3k.cache and tex.cache solve the problem. In my case the files were under ~/.matplotlib. |
How to config Django using pymysql as driver? | 34,777,755 | 3 | 2016-01-13T21:50:38Z | 34,778,155 | 9 | 2016-01-13T22:18:23Z | [
"python",
"mysql",
"django",
"pymysql"
] | I'm new to Django. It wasted me whole afternoon to config the MySQL engine. I am very confused about the database engine and the database driver. Is the **engine** also the **driver**? All the tutorial said that the ENGINE should be 'django.db.backends.mysql', but how the ENGINE decide which driver is used to connect M... | [You can import `pymsql` so it presents as MySQLdb](http://www.codes9.com/programing-language/python/python3-5-django1-8-5-the-solution-of-the-import-pymysql-pymysql-install_as_mysqldb-installation-2/). You'll need to do this *before* any django code is run, so put this in your `manage.py` file
```
import pymysql
pymy... |
Anaconda Python installation error | 34,780,267 | 16 | 2016-01-14T01:37:32Z | 34,796,239 | 44 | 2016-01-14T17:42:08Z | [
"python",
"python-2.7",
"installation",
"anaconda"
] | I get the following error during Python 2.7 64-bit windows installation. I previously installed python 3.5 64-bit and it worked fine. But during python 2.7 installation i get this error:
```
Traceback (most recent call last):
File "C:\Anaconda2\Lib\_nsis.py", line 164, in <module> main()
File "C:\Anaconda2\Lib\_nsis.p... | I had the same problem today. I did the following to get this fixed:
First, open a DOS prompt and admin rights.
Then, go to your Anaconda2\Scripts folder.
Then, type in:
```
conda update conda
```
and allow all updates. One of the updates should be menuinst.
Then, change to the Anaconda2\Lib directory, and type in ... |
Sort at various levels in Python | 34,784,220 | 9 | 2016-01-14T07:53:11Z | 34,784,358 | 13 | 2016-01-14T08:01:42Z | [
"python",
"list",
"sorting"
] | I am trying to sort a list of tuples like these:
```
[('Pineapple', 1), ('Orange', 3), ('Banana', 1), ('Apple', 1), ('Cherry', 2)]
```
The sorted list should be:
```
[('Orange', 3), ('Cherry', 2), ('Apple', 1), ('Banana', 1), ('Pineapple', 1)]
```
So, here 1st the list should be sorted based on `tuple[1]` in descen... | Have your key return a tuple of the numeric value *negated*, and then the string. By negating, your numbers will be sorted in descending order, while the strings are sorted in ascending order:
```
top_n.sort(key=lambda t: (-t[1], t[0]))
```
Yes, this is a bit of a hack, but works anywhere you need to sort by two crit... |
Updating a sliced list | 34,784,558 | 15 | 2016-01-14T08:15:11Z | 34,784,590 | 19 | 2016-01-14T08:16:50Z | [
"python",
"list"
] | I thought I understood Python slicing operations, but when I tried to update a sliced list, I got confused:
```
>>> foo = [1, 2, 3, 4]
>>> foo[:1] = ['one'] # OK, foo updated
>>> foo
['one', 2, 3, 4]
>>> foo[:][1] = 'two' # why foo not updated?
>>> foo
['one', 2, 3, 4]
>>> foo[:][2:] = ['three', 'four'] # Again, foo... | `foo[:]` is a copy of `foo`. You mutated the copy. |
Updating a sliced list | 34,784,558 | 15 | 2016-01-14T08:15:11Z | 34,784,864 | 13 | 2016-01-14T08:34:58Z | [
"python",
"list"
] | I thought I understood Python slicing operations, but when I tried to update a sliced list, I got confused:
```
>>> foo = [1, 2, 3, 4]
>>> foo[:1] = ['one'] # OK, foo updated
>>> foo
['one', 2, 3, 4]
>>> foo[:][1] = 'two' # why foo not updated?
>>> foo
['one', 2, 3, 4]
>>> foo[:][2:] = ['three', 'four'] # Again, foo... | The main thing to notice here is that `foo[:]` will return a copy of itself and then the indexing `[1]` will be applied *on the copied list that was returned*
```
# indexing is applied on copied list
(foo[:])[1] = 'two'
^
copied list
```
You can view this if you retain a reference to the copied list. So, the `foo... |
Updating a sliced list | 34,784,558 | 15 | 2016-01-14T08:15:11Z | 34,790,007 | 16 | 2016-01-14T12:46:34Z | [
"python",
"list"
] | I thought I understood Python slicing operations, but when I tried to update a sliced list, I got confused:
```
>>> foo = [1, 2, 3, 4]
>>> foo[:1] = ['one'] # OK, foo updated
>>> foo
['one', 2, 3, 4]
>>> foo[:][1] = 'two' # why foo not updated?
>>> foo
['one', 2, 3, 4]
>>> foo[:][2:] = ['three', 'four'] # Again, foo... | This is because python does **not** have *l*-values that could be assigned. Instead, some expressions have an assignment form, which is different.
A `foo[something]` is a syntactic sugar for:
```
foo.__getitem__(something)
```
but a `foo[something] = bar` is a syntactic sugar for rather different:
```
foo.__setitem... |
PyODBC : can't open the driver even if it exists | 34,785,653 | 7 | 2016-01-14T09:18:36Z | 34,934,901 | 7 | 2016-01-21T21:43:28Z | [
"python",
"sql-server",
"linux",
"pyodbc",
"unixodbc"
] | I'm new to the linux world and I want to query a Microsoft SQL Server from Python. I used it on Windows and it was perfectly fine but in Linux it's quite painful.
After some hours, I finally succeed to install the Microsoft ODBC driver on Linux Mint with unixODBC.
Then, I set up an anaconda with python 3 environment.... | I also had the same problem on Ubuntu 14 after following the microsoft tutorial for SQL Server Linux ODBC Driver (<https://msdn.microsoft.com/en-us/library/hh568454%28v=sql.110%29.aspx?f=255&MSPPError=-2147217396>).
The file exists and after running an ldd, it showed there were dependencies missing:
/opt/microsoft/ms... |
Advanced custom sort | 34,788,757 | 6 | 2016-01-14T11:42:07Z | 34,789,228 | 7 | 2016-01-14T12:06:05Z | [
"python",
"list",
"python-2.7",
"sorting"
] | I have a list of items that I would like to sort on multiple criterion.
Given input list:
```
cols = [
'Aw H',
'Hm I1',
'Aw I2',
'Hm R',
'Aw R',
'Aw I1',
'Aw E',
'Hm I2',
'Hm H',
'Hm E',
]
```
Criterions:
* Hm > Aw
* I > R > H > E
The output should be:
```
cols = [
'Hm I... | You could write a function for the key, returning a `tuple` with each portion of interest sorted by priority.
```
def k(s):
m = {'I':0, 'R':1, 'H':2, 'E':3}
return m[s[3]], int(s[4:] or 0), -ord(s[0])
cols = [
'Aw H',
'Hm I1',
'Aw I2',
'Hm R',
'Aw R',
'Aw I1',
'Aw E',
'Hm I2',
... |
ImportError: No module named 'ipdb' | 34,804,121 | 6 | 2016-01-15T03:51:38Z | 34,804,150 | 8 | 2016-01-15T03:54:51Z | [
"python",
"ipdb"
] | I'm new to python and I'm trying to use the interactive python debugger in the standard python package. Whenever I run "import ipdb" in my text editor (atom) or in the command line through iPython then I get the error:
ImportError: No module named 'ipdb'
Where is my ipdb module? It's still missing after I reinstalled ... | `pdb` is built-in. `ipdb` you will have to install.
```
pip install ipdb
``` |
cx_freeze converted GUI-app (tkinter) crashes after presssing plot-Button | 34,806,650 | 2 | 2016-01-15T08:06:12Z | 34,893,933 | 9 | 2016-01-20T07:28:56Z | [
"python",
"python-3.x",
"matplotlib",
"tkinter",
"cx-freeze"
] | I've been dealing with this for days now and hope to finde some help. I developed a GUI-application with imported modules tkinter, numpy, scipy, matplotlib, which runs fine in python itself. After having converted to an \*.exe everything works as expected, but NOT the matplotlib section. When I press my defined plot-Bu... | I found a potential solution (or at least an explanation) for this problem while testing PyInstaller with the same **test.py**. I received error message about a dll file being missing, that file being **mkl\_intel\_thread.dll**.
I searched for that file and it was found inside **numpy** folder.
I copied files matching... |
Python .get() in Java | 34,811,106 | 3 | 2016-01-15T12:28:44Z | 34,811,204 | 10 | 2016-01-15T12:34:26Z | [
"java",
"python"
] | So if we have a dictionary in python we have the amazing `Dictionary.get(x ,y)`
if x exists, return whatever x value is, else return y. Does java have this method? I've looked around and can't find anything | In Java 8, `Map` provides a [`getOrDefault`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-) method.
In earlier versions, you are probably stuck with either getting the value for the key with [`get`](https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#get%28java.... |
Is it possible to know the maximum number accepted by chr using Python? | 34,813,535 | 3 | 2016-01-15T14:42:48Z | 34,813,568 | 9 | 2016-01-15T14:43:57Z | [
"python",
"python-3.x",
"unicode"
] | From the Python's documentation of the [`chr`](https://docs.python.org/3.5/library/functions.html#chr) built-in function, the maximum value that `chr` accepts is 1114111 (in decimal) or 0x10FFFF (in base 16). And in fact
```
>>> chr(1114112)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>... | Use [`sys.maxunicode`](https://docs.python.org/3/library/sys.html#sys.maxunicode):
> An integer giving the value of the largest Unicode code point, i.e. `1114111` (`0x10FFFF` in hexadecimal).
On my Python 2.7 UCS-2 build the maximum Unicode character supported by `unichr()` is 0xFFFF:
```
>>> import sys
>>> sys.maxu... |
Anaconda prompt loading error: The input line is too long | 34,818,282 | 4 | 2016-01-15T19:21:36Z | 35,138,036 | 11 | 2016-02-01T18:50:22Z | [
"python",
"batch-file",
"windows-7-x64",
"anaconda",
"prompt"
] | I installed Anaconda 64 python 2.7 on Windows 7 64-bit version.
After installation, the anaconda prompt can start with no problem. But whenever I restart/shutdown and restart the laptop, the anaconda prompt will display the following error message, and some python packages have problems to load in the jupyter notebook.... | I found that if you change from using single quotes for the CALL SET on the following:
```
REM Make sure that root's Scripts dir is on PATH, for sake of keeping activate/deactivate available.
CALL SET "PATH_NO_SCRIPTS=%%PATH:%SCRIPT_PATH%=%%"
IF "%PATH_NO_SCRIPTS%"=="%PATH%" SET "PATH=%PATH%;%SCRIPT_PATH%"
```
to:
`... |
How to measure Python's asyncio code performance? | 34,826,533 | 6 | 2016-01-16T11:41:39Z | 34,827,291 | 8 | 2016-01-16T13:04:48Z | [
"python",
"performance-testing",
"trace",
"python-asyncio"
] | I can't use normal tools and technics to measure the performance of a coroutine because the time it takes at `await` should not be taken in consideration (or it should just consider the overhead of reading from the awaitable but not the IO latency).
So how do measure the time a coroutine takes ? How do I compare 2 imp... | One way is to patch `loop._selector.select` in order to time and save all the IO operations. This can be done using a context manager:
```
@contextlib.contextmanager
def patch_select(*, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
old_select = loop._selector.select
# Define the new ... |
Running TensorFlow on a Slurm Cluster? | 34,826,736 | 4 | 2016-01-16T12:03:59Z | 36,803,148 | 7 | 2016-04-22T20:53:30Z | [
"python",
"python-2.7",
"cluster-computing",
"tensorflow",
"slurm"
] | I could get access to a computing cluster, specifically one node with two 12-Core CPUs, which is running with [Slurm Workload Manager](https://en.wikipedia.org/wiki/Slurm_Workload_Manager).
I would like to run [TensorFlow](https://en.wikipedia.org/wiki/TensorFlow) on that system but unfortunately I were not able to fi... | It's relatively simple.
Under the simplifying assumptions that you request one process per host, slurm will provide you with all the information you need in environment variables, specifically SLURM\_PROCID, SLURM\_NPROCS and SLURM\_NODELIST.
For example, you can initialize your task index, the number of tasks and th... |
AttributeError: module 'html.parser' has no attribute 'HTMLParseError' | 34,827,566 | 12 | 2016-01-16T13:33:09Z | 36,000,103 | 7 | 2016-03-14T23:38:40Z | [
"python",
"django",
"python-3.x"
] | 1. This is the hints,how can I resolve it?
2. I use Python 3.5.1 created a virtual envirement by virtualenv
3. The source code works well on my friend's computer machine
Error:
```
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "A:\Python3.5\... | As you can read [here](http://www.thefourtheye.in/2015/02/python-35-and-django-17s-htmlparseerror.html) this error is raised...
> because `HTMLParseError` is deprecated from Python 3.3 onwards and removed in Python 3.5.
What you can do is downgrade your Python version or upgrade your Django version. |
Using map in Python | 34,831,050 | 3 | 2016-01-16T19:17:04Z | 34,831,115 | 7 | 2016-01-16T19:22:58Z | [
"python"
] | I'm trying to use the `map` Python function (I know I can use list comprehension but I was instructed to use map in this example) to take the row average of a two row matrix.
Here is what I think the answer should look like:
```
def average_rows2(mat):
print( map( float(sum) / len , [mat[0],mat[1]] ) )
average_ro... | The first argument has to be evaluated before it can be passed to `map`. This:
```
float(sum) / len
```
is causing you various errors as it doesn't make any sense to evaluate it on its own (unless you'd shadowed `sum` and `len`, which would be a different problem). You are trying to sum over one built-in function the... |
Comprehensions in Python to sample tuples from a list | 34,832,058 | 13 | 2016-01-16T20:58:34Z | 34,832,108 | 19 | 2016-01-16T21:03:11Z | [
"python",
"list",
"tuples",
"list-comprehension"
] | I am trying to get the list of three-element tuples from the list `[-4, -2, 1, 2, 5, 0]` using comprehensions, and checking whether they fulfil the condition `sum([] == 0)`. The following code works. However, there is no question that there ought to be an easier, much more elegant way of expressing these comprehensions... | You can use [`itertools.product`](https://docs.python.org/3/library/itertools.html#itertools.product) to hide the nested loops in your list comprehension. Use the `repeat` parameter to set the number of loops over the list (i.e. the number of elements in the tuple):
```
>>> import itertools
>>> lst = [-4, -2, 1, 2, 5,... |
Combine if conditions in Python | 34,834,814 | 3 | 2016-01-17T03:31:27Z | 34,834,820 | 10 | 2016-01-17T03:32:18Z | [
"python"
] | Does this exist in Python? I want to combine an If statement that is very repetitive.
```
# ORIGINAL IF STATEMENT
if a < 100 and b < 100 and c < 100:
#pass
# I KNOW THIS IS WRONG, I JUST WANT TO KNOW IF THERE IS A WAY TO MAKE THE IF CONDITION SHORTER
if [a,b,c] < 100:
#pass
``` | You can use the built-in [`all()`](https://docs.python.org/2/library/functions.html#all):
```
if all(item < 100 for item in [a, b, c]):
``` |
Tensorflow: Where is tf.nn.conv2d Actually Executed? | 34,835,503 | 9 | 2016-01-17T05:42:09Z | 34,843,397 | 10 | 2016-01-17T20:40:12Z | [
"python",
"machine-learning",
"tensorflow"
] | I am curious about the Tensorflow implementation of `tf.nn.conv2d(...)`. To call it, one simply runs `tf.nn.conv2d(...)`. However, I'm going down the rabbit hole trying to see where it is executed. The code is as follows (where the arrow indicates the function it ultimately calls):
```
tf.nn.conv2d(...) -> tf.nn_ops.c... | **TL;DR:** The implementation of [`tf.nn.conv2d()`](https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d) is written in C++, which invokes optimized code using either Eigen (on CPU) or the cuDNN library (on GPU). You can find the implementation [here](https://github.com/tensorflow/tensorflow/blob/8... |
What does "list comprehension" in Python mean? How does it work and how can I use it? | 34,835,951 | 26 | 2016-01-17T06:55:55Z | 34,835,952 | 47 | 2016-01-17T06:55:55Z | [
"python",
"list",
"list-comprehension"
] | I have the following code:
```
[x**2 for x in range(10)]
```
When I run it in the Python Shell, it returns:
```
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
```
I've searched and it seems this is called a *list comprehension*, but how does it work? | [From **the documentation**:](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)
> List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or... |
a pythonic way to write a constrain() function | 34,837,677 | 5 | 2016-01-17T11:13:13Z | 34,837,691 | 10 | 2016-01-17T11:14:30Z | [
"python"
] | What's the best way of writing a constrain function? or is there already a builtin python function that does this?
**Option 1:**
```
def constrain(val, min_val, max_val):
if val < min_val: return min_val
if val > max_val: return max_val
return val
```
**Option 2:**
```
def constrain(val, min_val, max_v... | I do not know if this is the more "pythonic", but you can use built-in [`min()`](https://docs.python.org/3/library/functions.html#min) and [`max()`](https://docs.python.org/3/library/functions.html#max) like this:
```
def constrain(val, min_val, max_val):
return min(max_val, max(min_val, val))
``` |
Can't accurately calculate pi on Python | 34,840,741 | 7 | 2016-01-17T16:38:24Z | 34,840,868 | 7 | 2016-01-17T16:50:36Z | [
"python",
"python-2.7",
"numeric",
"montecarlo",
"pi"
] | I am new member here and I'm gonna drive straight into this as I've spent my whole Sunday trying to get my head around it.
I'm new to Python, having previously learned coding on C++ to a basic-intermediate level (it was a 10-week university module).
I'm trying a couple of iterative techniques to calculate Pi but both... | The algorithm for your first version should look more like this:
```
from __future__ import division, print_function
import sys
if sys.version_info.major < 3:
range = xrange
import random
incircle = 0
n = 100000
for n in range(n):
x = random.random()
y = random.random()
if (x*x + y*y <= 1):
... |
Import error with spacy: "No module named en" | 34,842,052 | 3 | 2016-01-17T18:32:53Z | 34,842,085 | 7 | 2016-01-17T18:36:05Z | [
"python",
"spacy"
] | I'm having trouble using the Python [spaCy library](https://spacy.io/). It seems to be installed correctly but at
```
from spacy.en import English
```
I get the following import error:
```
Traceback (most recent call last):
File "spacy.py", line 1, in <module>
from spacy.en import English
File "/home/user/Cm... | You are facing this error because you named your own file `spacy.py`. Rename your file, and everything should work. |
Merge multiple backups of the same table schema into 1 master table | 34,844,602 | 6 | 2016-01-17T22:36:24Z | 34,885,447 | 7 | 2016-01-19T19:33:16Z | [
"python",
"sql",
"sqlite"
] | I have about 200 copies of a SQLite database. All taken at different times with different data in them. Some rows are deleted and some are added. They are all in a single directory.
I want to merge all the rows in the table `my_table`, using all the `.db` files in the directory. I want duplicate rows to be deleted, sh... | To be able to access both the master database and a snapshot at the same time, use [ATTACH](http://www.sqlite.org/lang_attach.html).
To delete and old version of a row, use [INSERT OR REPLACE](http://www.sqlite.org/lang_insert.html):
```
ATTACH 'snapshot123.db' AS snapshot;
INSERT OR REPLACE INTO main.my_table SELECT ... |
convert entire pandas dataframe to integers in pandas (0.17.0) | 34,844,711 | 2 | 2016-01-17T22:48:58Z | 34,844,867 | 7 | 2016-01-17T23:05:50Z | [
"python",
"pandas"
] | My question is very similar to [this one](http://stackoverflow.com/questions/33126477/pandas-convert-objectsconvert-numeric-true-deprecated), but I need to convert my entire dataframe instead of just a series. The `to_numeric` function only works on one series at a time and is not a good replacement for the deprecated ... | ## All columns convertible
You can apply the function to all columns:
```
df.apply(pd.to_numeric)
```
Example:
```
>>> df = pd.DataFrame({'a': ['1', '2'], 'b': ['45.8', '73.9'], 'c': [10.5, 3.7]})
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 0 to 1
Data columns (total 3 columns):
a ... |
Remove arrays from nested arrays based on first element of each array | 34,848,584 | 2 | 2016-01-18T06:37:39Z | 34,848,641 | 8 | 2016-01-18T06:41:10Z | [
"python",
"list"
] | I have two nested arrays say
```
a=[[1,2,3],[2,4,7],[4,2,8],[3,5,7],[6,1,2]]
b=[[1,6,7],[2,4,9],[4,3,5],[3,10,2],[5,3,2],[7,2,1]]
```
I want to only keep those arrays in `b` whose first element is not common to the first elements of the arrays in `a`, so for these two we should get
```
c=[[5,3,2],[7,2,1]]
```
Is th... | You may do like this,
```
>>> a=[[1,2,3],[2,4,7],[4,2,8],[3,5,7],[6,1,2]]
>>> b=[[1,6,7],[2,4,9],[4,3,5],[3,10,2],[5,3,2],[7,2,1]]
>>> [i for i in b if i[0] not in [j[0] for j in a]]
[[5, 3, 2], [7, 2, 1]]
>>>
```
or
```
>>> k = [j[0] for j in a]
>>> [i for i in b if i[0] not in k]
[[5, 3, 2], [7, 2, 1]]
``` |
Jupyter: can't create new notebook? | 34,851,801 | 7 | 2016-01-18T09:56:33Z | 35,518,674 | 12 | 2016-02-20T03:13:33Z | [
"python",
"ipython-notebook",
"jupyter",
"jupyter-notebook"
] | I have some existing Python code that I want to convert to a Jupyter notebook. I have run:
```
jupyter notebook
```
Now I can see this in my browser:
[](http://i.stack.imgur.com/Qsz65.png)
But how do I create a new notebook? The `Notebook` link in t... | None of the other answers worked for me on Ubuntu 14.04. After 2 days of struggling, I finally realized that I needed to install the latest version of IPython (not the one in pip). First, I uninstalled ipython from my system with:
```
sudo apt-get --purge remove ipython
sudo pip uninstall ipython
```
I don't know if ... |
Cannot import cv2 in python in OSX | 34,853,220 | 6 | 2016-01-18T11:07:33Z | 34,853,347 | 15 | 2016-01-18T11:13:12Z | [
"python",
"opencv"
] | I have installed OpenCV 3.1 in my Mac, cv2 is also installed through `pip install cv2`.
```
vinllen@ $ pip install cv2
You are using pip version 7.1.0, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Requirement already satisfied (use --upgrade to upgrade)... | **I do not know what `pip install cv2` actually installs... but is surely *not* OpenCV.** `pip install cv2` actually installs [this](https://pypi.python.org/pypi/cv2/1.0), which are some *blog distribution utilities*, not sure what it is, but it is **not** OpenCV.
---
To properly install OpenCV, check any of the link... |
Enumerating three variables in python list comprehension | 34,853,508 | 12 | 2016-01-18T11:21:19Z | 34,853,551 | 14 | 2016-01-18T11:23:28Z | [
"python",
"list-comprehension"
] | I am trying to print all the possible enumerations of a list for three variables. For example if my input is:
```
x = 1
y = 1
z = 1
```
I want the output to be like:
```
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
```
If any of the x,y,z variables are higher than 1, it w... | You could use the `product()` function from `itertools` as follows:
```
from itertools import product
answer = list(list(x) for x in product([0, 1], repeat=3))
print(answer)
```
**Output**
```
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
``` |
Enumerating three variables in python list comprehension | 34,853,508 | 12 | 2016-01-18T11:21:19Z | 34,853,772 | 8 | 2016-01-18T11:35:49Z | [
"python",
"list-comprehension"
] | I am trying to print all the possible enumerations of a list for three variables. For example if my input is:
```
x = 1
y = 1
z = 1
```
I want the output to be like:
```
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
```
If any of the x,y,z variables are higher than 1, it w... | Complementary to the solutions using `product`, you could also use a triple list comprehension.
```
>>> x, y, z = 1, 2, 3
>>> [(a, b, c) for a in range(x+1) for b in range(y+1) for c in range(z+1)]
[(0, 0, 0),
(0, 0, 1),
(0, 0, 2),
(some more),
(1, 2, 2),
(1, 2, 3)]
```
The `+1` is necessary since `range` does n... |
AttributeError: 'str' object has no attribute 'regex' django 1.9 | 34,853,531 | 8 | 2016-01-18T11:22:17Z | 34,854,283 | 10 | 2016-01-18T11:59:57Z | [
"python",
"django",
"windows",
"django-1.9"
] | I am working with django 1.9 and I am currently coding - in Windows Command Prompt - `python manage.py makemigrations` and the error:
***AttributeError: 'str' object has no attribute 'regex'***
I have tried coding:
```
url(r'^$', 'firstsite.module.views.start', name="home"),
url(r'^admin/', include(admin.site.urls))... | Firstly, remove the `django.conf.urls.handler400` from the middle of the urlpatterns. It doesn't belong there, and is the cause of the error.
Once the error has been fixed, you can make a couple of changes to update your code for Django 1.8+
1. Change `urlpatterns` to a list, instead of using `patterns()`
2. Import t... |
Is unsetting a single bit in flags safe with Python variable-length integers? | 34,855,777 | 28 | 2016-01-18T13:20:59Z | 34,856,274 | 10 | 2016-01-18T13:46:51Z | [
"python",
"bit-manipulation"
] | In my program (written in Python 3.4) I have a variable which contains various flags, so for example:
```
FLAG_ONE = 0b1
FLAG_TWO = 0b10
FLAG_THREE = 0b100
status = FLAG_ONE | FLAG_TWO | FLAG_THREE
```
Setting another flag can easily be done with
```
status |= FLAG_FOUR
```
But what if I explicitly want to clear a ... | Clearing a flag works with
```
status &= ~FLAG_THREE
```
because Python treats those negated values as negative:
```
>>> ~1L
-2L
>>> ~1
-2
>>> ~2
-3
```
Thus the `&` operator can act appropriately and yield the wanted result irrespective of the length of the operands, so `0b11111111111111111111111111111111111111111... |
Is unsetting a single bit in flags safe with Python variable-length integers? | 34,855,777 | 28 | 2016-01-18T13:20:59Z | 34,856,371 | 13 | 2016-01-18T13:51:37Z | [
"python",
"bit-manipulation"
] | In my program (written in Python 3.4) I have a variable which contains various flags, so for example:
```
FLAG_ONE = 0b1
FLAG_TWO = 0b10
FLAG_THREE = 0b100
status = FLAG_ONE | FLAG_TWO | FLAG_THREE
```
Setting another flag can easily be done with
```
status |= FLAG_FOUR
```
But what if I explicitly want to clear a ... | You should be safe using that approach, yes.
`~` in Python is simply implemented as `-(x+1)` (cf. the [CPython source](https://hg.python.org/cpython/file/d8f48717b74e/Objects/longobject.c#l3985)) and negative numbers are treated as if they have any required number of 1s padding the start. From the [Python Wiki](https:... |
How can I pass union/intersection methods as a parameter in Python? | 34,856,650 | 2 | 2016-01-18T14:05:38Z | 34,856,705 | 7 | 2016-01-18T14:08:19Z | [
"python",
"parameter-passing"
] | Can I pass the union and intersection methods of the [Set](https://docs.python.org/2/library/sets.html) Python class as an argument?
I am searching for direct way to do this, without using additional lambda or regular functions. | Methods are first-class objects, just like other functions. You can pass it bound:
```
x = set([1,2,3])
my_function(x.union)
```
or unbound
```
my_function(set.union)
```
as necessary.
Example:
```
def test(s1, s2, op):
return op(s1,s2)
test(set([1]), set([2]), set.union) # set([1, 2])
``` |
Unexpected behavior of python builtin str function | 34,859,471 | 6 | 2016-01-18T16:25:43Z | 34,860,001 | 7 | 2016-01-18T16:51:41Z | [
"python"
] | I am running into an issue with subtyping the str class because of the `str.__call__` behavior I apparently do not understand.
This is best illustrated by the simplified code below.
```
class S(str):
def __init__(self, s: str):
assert isinstance(s, str)
print(s)
class C:
def __init__(self, s:... | Strictly speaking, `str` isn't a function. It's a type. When you call `str(c)`, Python goes through the normal procedure for generating an instance of a type, calling `str.__new__(str, c)` to create the object (or reuse an existing object), **and then calling the `__init__` method of the result to initialize it**.
[`s... |
What causes the '' in ['h', 'e', 'l', 'l', 'o', ''] when you do re.findall('[\w]?', 'hello') | 34,860,722 | 25 | 2016-01-18T17:33:00Z | 34,860,788 | 40 | 2016-01-18T17:36:50Z | [
"python",
"regex"
] | What causes the `''` in `['h', 'e', 'l', 'l', 'o', '']` when you do `re.findall('[\w]?', 'hello')`. I thought the result would be `['h', 'e', 'l', 'l', 'o']`, without the last empty string. | The question mark in your regex (`'[\w]?'`) is responsible for the empty string being one of the returned results.
A question mark is a quantifier meaning "zero-or-one matches." You are asking for all occurrences of either zero-or-one "word characters". The letters satisfy the "-or-one word characters" match. The empt... |
Build a dictionary with a regular expression | 34,864,409 | 2 | 2016-01-18T21:29:19Z | 34,864,444 | 8 | 2016-01-18T21:31:40Z | [
"python",
"python-2.7"
] | I am getting some data through a serial connection which I'd like to process so I can do more with it.
---
My Python script gets the variable which looks like:
```
data = "P600F600"
```
and my goal is to get this:
```
finaldata = {
'P': 600,
'F': 600
}
```
---
I like regular expressions and my input format i... | In this case, `re.findall` seems to be really helpful:
```
>>> import re
>>> re.findall('([A-Z])(\d+)', 'P600F600')
[('P', '600'), ('F', '600')]
```
It just so happens that a dict can be built from this directly:
```
>>> dict(re.findall('([A-Z])(\d+)', 'P600F600'))
{'P': '600', 'F': '600'}
```
Of course, this leave... |
use conda environment in sublime text 3 | 34,865,717 | 4 | 2016-01-18T23:03:30Z | 34,866,051 | 8 | 2016-01-18T23:32:08Z | [
"python",
"sublimetext3",
"anaconda"
] | Using Sublime Text 3, how can I build a python file using a conda environment that I've created as in <http://conda.pydata.org/docs/using/envs.html> | A standard Python [`.sublime-build`](http://docs.sublimetext.info/en/latest/file_processing/build_systems.html) file looks like this:
```
{
"cmd": ["/path/to/python", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
```
All you need to do to use a particu... |
What is the proper way to determine if an object is a bytes-like object in Python? | 34,869,889 | 15 | 2016-01-19T06:28:09Z | 34,870,210 | 7 | 2016-01-19T06:49:25Z | [
"python",
"python-3.x"
] | I have code that expects `str` but will handle the case of being passed `bytes` in the following way:
```
if isinstance(data, bytes):
data = data.decode()
```
Unfortunately, this does not work in the case of `bytearray`. Is there a more generic way to test whether an object is either `bytes` or `bytearray`, or sh... | There are a few approaches you could use here.
# Duck typing
Since Python is [duck typed](http://en.wikipedia.org/wiki/Duck_typing), you could simply do as follows (which seems to be the way usually suggested):
```
try:
data = data.decode()
except AttributeError:
pass
```
You could use `hasattr` as you desc... |
What does tf.nn.embedding_lookup function do? | 34,870,614 | 18 | 2016-01-19T07:14:40Z | 34,877,590 | 31 | 2016-01-19T13:05:06Z | [
"python",
"embedding",
"tensorflow"
] | ```
tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None)
```
I cannot understand the duty of this function. Is it like a lookup table? which means return the param corresponding for each id (in ids)?
For instance, in the `skip-gram` model if we use `tf.nn.embedding_lookup(embeddings, train_inputs)... | `embedding_lookup` function retrieves rows of the `params` tensor. The behavior is similar to using indexing with arrays in numpy. E.g.
```
matrix = np.random.random([1024, 64]) # 64-dimensional embeddings
ids = np.array([0, 5, 17, 33])
print matrix[ids] # prints a matrix of shape [4, 64]
```
`params` argument can ... |
Trace Bug which happends only sometimes in CI | 34,872,918 | 7 | 2016-01-19T09:25:01Z | 34,948,768 | 8 | 2016-01-22T14:13:41Z | [
"python",
"debugging",
"trace"
] | I have a strange bug in python code which only happens sometimes in CI.
We can't reproduce it.
Where is the test code:
```
response=self.admin_client.post(url, post)
self.assertEqual(200, response.status_code, response)
```
Sometimes we get a 302 which happens since the form gets saved.
My idea to debug this:
```... | The [trace](https://docs.python.org/3.5/library/trace.html#module-trace) module gives you a very simple solution (different from what you are asking for, but simple enough to have a try.)
```
from trace import Trace
tracer = Trace()
response = tracer.runfunc(self.admin_client.post, url, post)
self.assertEqual(200, re... |
Find the coordinates of a cuboid using list comprehension in Python | 34,873,322 | 4 | 2016-01-19T09:43:19Z | 34,873,400 | 8 | 2016-01-19T09:46:57Z | [
"python",
"list",
"list-comprehension"
] | `X`, `Y` and `Z` are the three coordinates of a cuboid.
Now X=1,Y=1, Z=1 and N=2.
I have to generate a list of all possible coordinates on a 3D grid where the sum of Xi + Yi + Zi is not equal to N. If X=2, the possible values of Xi can be 0, 1 and 2. The same applies to Y and Z.
I have written this below code so far... | `range` is actually a half-closed function. So, the ending value will not be included in the resulting range.
> If X=2, the possible values of Xi can be 0, 1 and 2
In your code, `range(X)` will give only `0` and `1`, if `X` is 2. You should have used `range(X + 1)`.
```
>>> X, Y, Z, N = 1, 1, 1, 2
>>> [[x,y,z] for x... |
Pythonic way to "round()" like Javascript "Math.round()"? | 34,876,585 | 2 | 2016-01-19T12:15:45Z | 34,876,996 | 7 | 2016-01-19T12:35:51Z | [
"javascript",
"python",
"python-3.x",
"math"
] | I want the most Pythonic way to round numbers just like Javascript does (through `Math.round()`). They're actually slightly different, but this difference can make huge difference for my application.
**Using `round()` method from Python 3:**
```
// Returns the value 20
x = round(20.49)
// Returns the value 20
x = ro... | ```
import math
def roundthemnumbers(value):
x = math.floor(value)
if (value - x) < .50:
return x
else:
return math.ceil(value)
```
Haven't had my coffee yet, but that function should do what you need. Maybe with some minor revisions. |
Seeking Elegant Python Dice Iteration | 34,876,784 | 15 | 2016-01-19T12:25:25Z | 34,877,016 | 28 | 2016-01-19T12:36:40Z | [
"python"
] | Is there an elegant way to iterate through possible dice rolls with up to five dice?
I want to replace this hacky Python:
```
self.rolls[0] = [str(a) for a in range(1,7)]
self.rolls[1] = [''.join([str(a), str(b)])
for a in range(1, 7)
for b in range(1, 7)
if a <= b]
... | You can use [**`itertools`**](https://docs.python.org/2/library/itertools.html)' [**`combinations_with_replacement`**](https://docs.python.org/2/library/itertools.html#itertools.combinations_with_replacement).
For example with 3 4-sided dice (just because the output isn't *too* large):
```
>>> from itertools import c... |
Unexpected behaviour when indexing a 2D np.array with two boolean arrays | 34,877,314 | 10 | 2016-01-19T12:51:08Z | 34,877,540 | 8 | 2016-01-19T13:02:54Z | [
"python",
"arrays",
"numpy",
"indexing",
"slice"
] | ```
two_d = np.array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
first = np.array((True, True, False, False, False))
second = np.array((False, False, False, True, True))
```
Now,... | When given multiple boolean arrays to index with, NumPy pairs up the indices of the True values. The first true value in `first` in paired with the first true value in `second`, and so on. NumPy then fetches the elements at each of these (x, y) indices.
This means that `two_d[first, second]` is equivalent to:
```
two... |
Determining if I need quotes in HTML with django template | 34,878,869 | 3 | 2016-01-19T14:05:21Z | 34,879,016 | 7 | 2016-01-19T14:11:46Z | [
"python",
"django",
"django-templates"
] | I have a `dict` in python that is something like the following:
```
d = {'key1': .98, 'key2': 'some_str',
#...
}
```
In this dictionary some keys will be mapped to `float` and others will be mapped to `str`
In my HTML I am doing something like the following:
```
html_dict = {
{% for k, v in my_dict.items ... | Don't do this. You are manually trying to replicate a JS data structure, when there already exists a well-defined structure that both Python and JS know about, namely JSON. Use that instead. Convert the dict to JSON in your view, and pass it to the template where it can be output directly. |
What happens in degenerate case of multiple assignment? | 34,882,417 | 15 | 2016-01-19T16:49:40Z | 34,882,802 | 11 | 2016-01-19T17:06:40Z | [
"python"
] | I'm [teaching myself algorithms](http://rosalind.info/problems/list-view/?location=algorithmic-heights). I needed to swap two items in a list. Python makes all things easy:
```
def swap(A, i, j):
A[i], A[j] = A[j], A[i]
```
This works a treat:
```
>>> A = list(range(5))
>>> A
[0, 1, 2, 3, 4]
>>> swap(A, 0, 1)
>>... | Well it seems *you are re-assigning to the same target* `A[1]`, to get a visualization of the call:
```
A[1], A[0], A[1] = A[0], A[1], A[1]
```
Remember, from the documentation on **[assignment statements](https://docs.python.org/3.5/reference/simple_stmts.html#assignment-statements)**:
> An assignment statement *ev... |
What happens in degenerate case of multiple assignment? | 34,882,417 | 15 | 2016-01-19T16:49:40Z | 34,882,874 | 23 | 2016-01-19T17:09:44Z | [
"python"
] | I'm [teaching myself algorithms](http://rosalind.info/problems/list-view/?location=algorithmic-heights). I needed to swap two items in a list. Python makes all things easy:
```
def swap(A, i, j):
A[i], A[j] = A[j], A[i]
```
This works a treat:
```
>>> A = list(range(5))
>>> A
[0, 1, 2, 3, 4]
>>> swap(A, 0, 1)
>>... | `cycle` is doing exactly what you ask it to: assigning to the left hand values the right hand values.
```
def cycle(A, i, j, k):
A[i], A[j], A[k] = A[j], A[k], A[i]
```
is functionally equivalent to
```
def cycle(A, i, j, k):
new_values = A[j], A[k], A[i]
A[i], A[j], A[k] = new_values
```
So when you do... |
What is the point of views in pandas if it is undefined whether an indexing operation returns a view or a copy? | 34,884,536 | 7 | 2016-01-19T18:40:49Z | 34,908,742 | 9 | 2016-01-20T19:24:42Z | [
"python",
"pandas",
"views",
"slice"
] | I have switched from R to pandas. I routinely get SettingWithCopyWarnings, when I do something like
```
df_a = pd.DataFrame({'col1': [1,2,3,4]})
# Filtering step, which may or may not return a view
df_b = df_a[df_a['col1'] > 1]
# Add a new column to df_b
df_b['new_col'] = 2 * df_b['col1']
# SettingWithCopyWarni... | Great question!
The short answer is: this is a flaw in pandas that's being remedied.
You can find a longer discussion of the nature of [the problem here](https://github.com/pydata/pandas/issues/10954), but the main take-away is that we're now moving to a "copy-on-write" behavior in which any time you slice, you get a... |
How to avoid slack command timeout error? | 34,896,954 | 3 | 2016-01-20T10:04:29Z | 34,944,331 | 9 | 2016-01-22T10:23:44Z | [
"python",
"slack-api",
"slack"
] | I am working with slack command (python code is running behind this), it works fine, but this gives error
`This slash command experienced a problem: 'Timeout was reached' (error detail provided only to team owning command).`
How to avoid this ? | According to the Slack [slash command documentation](https://api.slack.com/slash-commands#responding_to_a_command), you need to respond within 3000ms (three seconds). If your command takes longer then you get the `Timeout was reached` error. Your code obviously won't stop running, but the user won't get any response to... |
Generate list of months between interval in python | 34,898,525 | 3 | 2016-01-20T11:16:02Z | 34,898,764 | 7 | 2016-01-20T11:27:50Z | [
"python",
"python-2.7"
] | I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows:
```
date1 = "2014-10-10" # input start date
date2 = "2016-01-07" # input end date
month_list = ['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15',... | ```
>>> from datetime import datetime, timedelta
>>> from collections import OrderedDict
>>> dates = ["2014-10-10", "2016-01-07"]
>>> start, end = [datetime.strptime(_, "%Y-%m-%d") for _ in dates]
>>> OrderedDict(((start + timedelta(_)).strftime(r"%b-%y"), None) for _ in xrange((end - start).days)).keys()
['Oct-14', 'N... |
Why would I add python to PATH | 34,900,042 | 5 | 2016-01-20T12:25:58Z | 34,900,138 | 10 | 2016-01-20T12:30:30Z | [
"python",
"python-3.x",
"path",
"install"
] | I am beginning to look at python, so when I found a tutorial it said that the first thing to do would be to download python from www.python.org/downloads/
Now when I downloaded python 3, I then started the installation and got to
[](http://i.stack.img... | PATH is an environment variable in Windows. It basically tells the commandline what folders to look in when attempting to find a file. If you didn't add Python to PATH then you would call it from the commandline like this:
```
C:/Python27/Python some_python_script.py
```
Whereas if you add it to PATH, you can do this... |
Confused about a variable assignment (Python) | 34,901,867 | 4 | 2016-01-20T13:49:48Z | 34,901,947 | 7 | 2016-01-20T13:53:49Z | [
"python",
"algorithm"
] | For a task on ProjectEuler I've written code that uses brute force to find the longest chain of primes below 100 that add up to a prime, and the code does give the correct results. So for numbers below 100 the answer is 2 + 3 + 5 + 7 + 11 + 13 = 41
```
import math
def prime(n):
for x in xrange(2,int(math.sqrt(n)+... | `seq = chain` creates another *reference* to the same `chain` list. You then print that list, but *the loop doesn't stop*.
You continue to expand `chain`, and since `seq` is just a reference to that list, you'll see those changes once the loop has ended. During the remaining `for` loop iterations `chain` / `seq` conti... |
Why is my list not sorted as expected? | 34,907,849 | 3 | 2016-01-20T18:35:30Z | 34,907,913 | 10 | 2016-01-20T18:39:40Z | [
"python",
"sorting"
] | I have a `dict()` called `twitter_users` which holds `TwitterUser` objects as values. I want those objects to be sorted by the field `mentioned`. However, using `sorted()` does not work as I expect. I provide a `lambda` function that is supposed to determine if user `a` or user `b` was mentioned more often.
```
srt = ... | A `cmp` function should return an integer, `0` when equal, `1` or higher when `a` should come after `b` and `-1` or lower if they should come in the opposite order.
You instead return `False` and `True`. Because the Python boolean type is a subclass of `int`, these objects have the values `0` and `1` when interpreted ... |
Cannot gather gradients for GradientDescentOptimizer in TensorFlow | 34,911,276 | 2 | 2016-01-20T21:49:08Z | 34,911,503 | 7 | 2016-01-20T22:03:03Z | [
"python",
"tensorflow"
] | I've been trying to gather the gradient steps for each step of the GradientDescentOptimizer within TensorFlow, however I keep running into a TypeError when I try to pass the result of `apply_gradients()` to `sess.run()`. The code I'm trying to run is:
```
import tensorflow as tf
from tensorflow.examples.tutorials.mnis... | The [`Optimizer.compute_gradients()`](https://www.tensorflow.org/versions/master/api_docs/python/train.html#Optimizer.compute_gradients) method returns a list of (`Tensor`, `Variable`) pairs, where each tensor is the gradient with respect to the corresponding variable.
`Session.run()` expects a list of `Tensor` object... |
Combining lists of tuples based on a common tuple element | 34,919,028 | 2 | 2016-01-21T08:46:42Z | 34,919,125 | 7 | 2016-01-21T08:52:57Z | [
"python",
"list"
] | Consider two lists of tuples:
```
data1 = [([X1], 'a'), ([X2], 'b'), ([X3], 'c')]
data2 = [([Y1], 'a'), ([Y2], 'b'), ([Y3], 'c')]
```
Where `len(data1) == len(data2)`
Each tuple contains two elements:
1. list of some strings (i.e `[X1]`)
2. A **common** element for `data1` and `data2`: strings `'a'`, `'b'`, and so ... | You can use `zip` function and a list comprehension:
```
[(s1,l1,l2) for (l1,s1),(l2,s2) in zip(data1,data2)]
``` |
Create a simple number pattern in python? | 34,929,895 | 2 | 2016-01-21T17:04:40Z | 34,929,933 | 11 | 2016-01-21T17:06:21Z | [
"python",
"python-3.x"
] | I'm trying to get this number pattern
```
0
01
012
0123
01234
012345
0123456
01234567
012345670
0123456701
```
But I can't figure out how to reset the digits when I reach over 8 in my function. There is my code:
```
def afficherPatron(n):
triangle = ''
for i in range(0, n):
triangle = triangle + (str(i))
pr... | Use `i` mod 8 (`i%8`) because it is cyclic 0 to 7 :
```
for i in range(0, n):
triangle = triangle + str(i%8)
print(triangle)
``` |
Iterate over lists with a particular sum | 34,930,745 | 4 | 2016-01-21T17:45:40Z | 34,930,908 | 7 | 2016-01-21T17:54:40Z | [
"python",
"math",
"optimization"
] | I would like to iterate over all lists of length `n` whose elements sum to 2. How can you do this efficiently? Here is a very inefficient method for `n = 10`. Ultimately I would like to do this for `n > 25'.
```
n = 10
for L in itertools.product([-1,1], repeat = n):
if (sum(L) == 2):
print L #Do something ... | you only can have a solution of 2 if you have 2 more +1 than -1 so for n==24
```
a_solution = [-1,]*11 + [1,]*13
```
now you can just use itertools.permutations to get every permutation of this
```
for L in itertools.permutations(a_solution): print L
```
it would probably be faster to use itertools.combinations to ... |
Python - Delete all files EXCEPT for | 34,931,192 | 2 | 2016-01-21T18:11:26Z | 34,931,241 | 7 | 2016-01-21T18:13:45Z | [
"python",
"csv"
] | I have a Python script and I'm trying to delete all files in this directory EXCEPT for the .csv file. Getting syntax error on the "not" in this line:
```
for CleanUp not in glob.glob("c:\python\AIO*.*"):
```
If I remove the "not", it will delete the AIO.csv file, but I need to preserve that file and ONLY that file. N... | Try this instead
```
import os
import glob
import time
file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
time.sleep(10)
if os.path.isfile(file_path):
#Verifies CSV file was created, then deletes unneeded files.
for CleanUp in glob.glob('C:/python/*.*'):
print CleanUp
if not... |
How can I convert an absolutely massive number to a string in a reasonable amount of time? | 34,936,226 | 25 | 2016-01-21T23:16:28Z | 34,936,584 | 16 | 2016-01-21T23:47:20Z | [
"python",
"string",
"primes",
"biginteger"
] | This is quite an odd problem I know, but I'm trying to get a copy of the current largest prime number in a file. Getting the number in integer form is fairly easy. I just run this.
```
prime = 2**74207281 - 1
```
It takes about half a second and it works just fine. Operations are fairly quick as well. Dividing it by ... | Repeated string concatenation is notoriously inefficient since Python strings are immutable. I would go for
```
strprime = str(prime)
```
In my benchmarks, this is consistently the fastest solution. Here's my little benchmark program:
```
import decimal
def f1(x):
''' Definition by OP '''
strprime = ""
... |
How can I convert an absolutely massive number to a string in a reasonable amount of time? | 34,936,226 | 25 | 2016-01-21T23:16:28Z | 34,937,258 | 9 | 2016-01-22T01:02:19Z | [
"python",
"string",
"primes",
"biginteger"
] | This is quite an odd problem I know, but I'm trying to get a copy of the current largest prime number in a file. Getting the number in integer form is fairly easy. I just run this.
```
prime = 2**74207281 - 1
```
It takes about half a second and it works just fine. Operations are fairly quick as well. Dividing it by ... | Took about 32 seconds to output the file using WinGhci (Haskell language):
```
import System.IO
main = writeFile "prime.txt" (show (2^74207281 - 1))
```
The file was 21 megabytes; the last four digits, 6351. |
How can I convert an absolutely massive number to a string in a reasonable amount of time? | 34,936,226 | 25 | 2016-01-21T23:16:28Z | 34,939,701 | 13 | 2016-01-22T05:36:31Z | [
"python",
"string",
"primes",
"biginteger"
] | This is quite an odd problem I know, but I'm trying to get a copy of the current largest prime number in a file. Getting the number in integer form is fairly easy. I just run this.
```
prime = 2**74207281 - 1
```
It takes about half a second and it works just fine. Operations are fairly quick as well. Dividing it by ... | Python's integer to string conversion algorithm uses a simplistic algorithm with a running of O(n\*\*2). As the length of the number doubles, the conversion time quadruples.
Some simple tests on my computer show the increase in running time:
```
$ time py35 -c "n=str(2**1000000)"
user 0m1.808s
$ time py35 -c "n=st... |
Preprocess a Tensorflow tensor in Numpy | 34,942,745 | 4 | 2016-01-22T09:05:07Z | 34,951,694 | 7 | 2016-01-22T16:40:05Z | [
"python",
"numpy",
"tensorflow"
] | I have set up a CNN in Tensorflow where I read my data with a TFRecordReader. It works well but I would like to do some more preprocessing and data augmentation than offered by the `tf.image` functions. I would specifically like to do some randomized scaling.
Is it possible to process a Tensorflow tensor in Numpy? Or ... | If you could create a custom I/O pipeline that fetches intermediate results back from TensorFlow using one or more threads, applies arbitrary Python logic, and then feeds them into a queue for subsequent processing. The resulting program would be somewhat more complicated, but I suggest you look at the [threading and q... |
How to set layer-wise learning rate in Tensorflow? | 34,945,554 | 6 | 2016-01-22T11:22:10Z | 34,948,185 | 14 | 2016-01-22T13:45:45Z | [
"python",
"deep-learning",
"tensorflow"
] | I am wondering if there is a way that I can use different learning rate for different layers like what is in Caffe. I am trying to modify a pre-trained model and use it for other tasks. What I want is to speed up the training for new added layers and keep the trained layers at low learning rate in order to prevent them... | It can be achieved quite easily with 2 optimizers:
```
var_list1 = [variables from first 5 layers]
var_list2 = [the rest of variables]
train_op1 = GradientDescentOptimizer(0.00001).minimize(loss, var_list=var_list1)
train_op2 = GradientDescentOptimizer(0.0001).minimize(loss, var_list=var_list2)
train_op = tf.group(tra... |
Is there a sunset/sunrise function built into Astropy yet? | 34,952,552 | 3 | 2016-01-22T17:23:51Z | 34,955,251 | 9 | 2016-01-22T20:19:56Z | [
"python",
"coordinates",
"pyephem",
"astropy"
] | I have seen a couple of answers referring to PyEphem on here and how that can produce sunset/sunrise times, however it would be more useful to me if I could find a solution using solely Astropy packages. At the moment the closest I have found is the *(get\_sun)* function in the **astropy.coordinates** package. Is this ... | The [Astroplan](http://astroplan.readthedocs.org) package has an [Observer](http://astroplan.readthedocs.org/en/latest/api/astroplan.Observer.html) class with a [Observer.sun\_rise\_time](http://astroplan.readthedocs.org/en/latest/api/astroplan.Observer.html#astroplan.Observer.sun_rise_time) and a [Observer.sun\_set\_t... |
Pandas: Compress Column Names to Cell Values where True | 34,955,321 | 4 | 2016-01-22T20:23:59Z | 34,955,500 | 8 | 2016-01-22T20:34:44Z | [
"python",
"pandas",
"dataframe"
] | I have a dataframe that looks like
```
ID Cat1 Cat2 Cat3 Cat4
3432432 True False True False
1242323 False True False False
3423883 False False False True
```
How can I convert that to a dataframe that chooses the first column that is True?
```
ID Status
3432432 Cat1
... | You could take advantage of the fact that `idxmax` will return the first True:
```
>>> df.set_index("ID").idxmax(axis=1).reset_index(name="Status")
ID Status
0 3432432 Cat1
1 1242323 Cat2
2 3423883 Cat4
```
which works because we have
```
>>> df.iloc[:,1:]
Cat1 Cat2 Cat3 Cat4
0 True Fal... |
What is the difference between namedtuple return and its typename argument? | 34,962,181 | 4 | 2016-01-23T10:14:18Z | 34,962,236 | 7 | 2016-01-23T10:19:53Z | [
"python"
] | Python documentation says:
```
collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
Returns a new tuple subclass named typename.
```
and it gives an example
`>>>Point = namedtuple('Point',`...
In all the examples I could find, the return from `namedtuple` and argument `typename` are spelle... | When you execute the following code:
```
Bar = collections.namedtuple('Foo', 'field')
```
you are:
1. creating a new type named `Foo`;
2. assigning that type to a variable named `Bar`.
That code is equivalent to this:
```
class Foo:
...
Bar = Foo
del Foo
```
Even if you assign your class to a variable with a... |
Softmax function - python | 34,968,722 | 38 | 2016-01-23T20:52:50Z | 34,969,389 | 21 | 2016-01-23T22:00:06Z | [
"python",
"numpy",
"machine-learning",
"logistic-regression",
"softmax"
] | From the [Udacity's deep learning class](https://www.udacity.com/course/viewer#!/c-ud730/l-6370362152/m-6379811820), the softmax of y\_i is simply the exponential divided by the sum of exponential of the whole Y vector:
[](http://i.stack.imgur.com/iP8D... | They're both correct but yours has an unnecessary term.
You start with
e ^ (x - max(x)) / sum(e^(x - max(x))
By using the fact that a^(b - c) = (a^b)/(a^c) we have
= e ^ x / e ^ max(x) \* sum(e ^ x / e ^ max(x))
= e ^ x / sum(e ^ x)
Which is what the other answer says. You could replace max(x) with any variable a... |
Softmax function - python | 34,968,722 | 38 | 2016-01-23T20:52:50Z | 35,276,415 | 13 | 2016-02-08T18:13:54Z | [
"python",
"numpy",
"machine-learning",
"logistic-regression",
"softmax"
] | From the [Udacity's deep learning class](https://www.udacity.com/course/viewer#!/c-ud730/l-6370362152/m-6379811820), the softmax of y\_i is simply the exponential divided by the sum of exponential of the whole Y vector:
[](http://i.stack.imgur.com/iP8D... | I would say that while both are correct mathematically, implementation-wise, first one is better. When computing softmax, the intermediate values may become very large. Dividing two large numbers can be numerically unstable. [These notes](http://cs231n.github.io/linear-classify/#softmax) (from Stanford) mention a norma... |
Python 3 doesn't need __init__.py in this situation? | 34,969,646 | 5 | 2016-01-23T22:23:28Z | 34,969,715 | 7 | 2016-01-23T22:30:51Z | [
"python",
"python-2.7",
"python-3.x",
"import"
] | Suppose I have:
```
src/
__init__.py
a.py
b.py
```
Suppose `__init__.py` is an empty file, and `a.py` is just one line:
```
TESTVALUE = 5
```
Suppose `b.py` is:
```
from src import a
print(a.TESTVALUE)
```
Now in both Python 2.7 and Python 3.x, running `b.py` gives the result (`5`).
However, if I delete... | Python 3 supports [namespace packages](https://www.python.org/dev/peps/pep-0420/) that work without an `__init__.py` file.
Furthermore, these packages can be distribute over several directories. This means all directories on your `sys.path` that contain `*.py` files will be recognized as packages.
This breaks backward... |
Need to embed `-` character into arguments in python argparse | 34,970,533 | 3 | 2016-01-23T23:59:54Z | 34,970,609 | 7 | 2016-01-24T00:08:14Z | [
"python",
"python-2.7",
"shell",
"command-line-interface",
"argparse"
] | I am designing a tool to meet some spec. I have a scenario where I want the argument to contain `-` its string. Pay attention to `arg-1` in the below line.
```
python test.py --arg-1 arg1Data
```
I am using the `argparse` library on `python27`. For some reason the argparse gets confused with the above trial.
My ques... | Python argparse module replace dashes by underscores, thus:
```
if args.arg_1:
print "verbosity turned on"
```
Python doc (second paragraph of section [15.4.3.11. dest](https://docs.python.org/2.7/library/argparse.html#dest)) states:
> Any internal `-` characters will be converted to `_` characters to make
> s... |
Django many-to-many | 34,972,012 | 3 | 2016-01-24T03:52:21Z | 34,972,055 | 7 | 2016-01-24T03:58:42Z | [
"python",
"django",
"many-to-many"
] | ```
class Actor(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Movie(models.Model):
title = models.CharField(max_length=50)
actors = models.ManyToManyField(Actor)
def __str__(self):
return self.title
```
how can I access to the movie... | just put `related_name` into `actors` field
```
actors = models.ManyToManyField(Actor, related_name="actor_movies")
```
and then in template:
```
{{ actor.actor_movies.all }}
```
or if you dont want `related_name`:
template:
```
{{ actor.movie_set.all }}
``` |
403 Forbidden using Urllib2 [Python] | 34,974,117 | 3 | 2016-01-24T09:29:01Z | 35,028,627 | 7 | 2016-01-27T03:58:10Z | [
"python",
"instagram-api"
] | ```
url = 'https://www.instagram.com/accounts/login/ajax/'
values = {'username' : 'User',
'password' : 'Pass'}
#'User-agent', ''
data = urllib.urlencode(values)
req = urllib2.Request(url, data,headers={'User-Agent' : "Mozilla/5.0"})
con = urllib2.urlopen( req )
the_page = response.read()
```
Does anyone ha... | Two important things, for starters:
* make sure you stay on the *legal side*. According to the Instagram's [Terms of Use](https://help.instagram.com/478745558852511):
> We prohibit crawling, scraping, caching or otherwise accessing any content on the Service via automated means, including but not limited to, user pro... |
Split text lines in scanned document | 34,981,144 | 5 | 2016-01-24T20:36:46Z | 35,014,061 | 7 | 2016-01-26T12:38:42Z | [
"python",
"opencv",
"ocr",
"skimage"
] | I am trying to find a way to break the split the lines of text in a scanned document that has been adaptive thresholded. Right now, I am storing the pixel values of the document as unsigned ints from 0 to 255, and I am taking the average of the pixels in each line, and I split the lines into ranges based on whether the... | From your input image, you need to make text as white, and background as black
[](http://i.stack.imgur.com/DmbZx.png)
You need then to compute the rotation angle of your bill. A simple approach is to find the `minAreaRect` of all white points (`findNo... |
TensorFlow: Max of a tensor along an axis | 34,987,509 | 5 | 2016-01-25T07:49:27Z | 34,988,069 | 8 | 2016-01-25T08:30:27Z | [
"python",
"deep-learning",
"tensorflow"
] | My question is in two connected parts:
1. How do I calculate the max along a certain axis of a tensor? For example if I have
```
x = tf.constant([[1,220,55],[4,3,-1]])
```
I want something like
```
x_max = tf.max(x, axis=1)
print sess.run(x_max)
output: [220,4]
```
I know there is a tf.... | The [`tf.reduce_max()`](https://www.tensorflow.org/versions/0.6.0/api_docs/python/math_ops.html#reduce_max) operator provides exactly this functionality. By default it computes the global maximum of the given tensor, but you can specify a list of `reduction_indices`, which has the same meaning as `axis` in NumPy. To co... |
Python import error: 'module' object has no attribute 'x' | 34,992,019 | 6 | 2016-01-25T11:56:39Z | 34,992,394 | 7 | 2016-01-25T12:15:01Z | [
"python",
"python-3.x",
"import"
] | I am trying to do a python script that it is divided in multiple files, so I can maintain it more easily instead of making a very-long single file script.
Here is the directory structure:
```
wmlxgettext.py
<pywmlx>
|- __init__.py
|- (some other .py files)
|- <state>
|- __init__.py
|- state.py
... | Python does several things when importing packages:
* Create an object in `sys.modules` for the package, with the name as key: `'pywmlx'`, `'pywmlx.state'`, `'pywmlx.state.machine'`, etc.
* Run the bytecode loaded for that module; this may create more modules.
* Once a module is fully loaded and it is located inside a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.