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 |
|---|---|---|---|---|---|---|---|---|---|
What does a star * alone mean in a function declaration? | 32,727,198 | 7 | 2015-09-22T21:23:58Z | 32,727,253 | 9 | 2015-09-22T21:28:19Z | [
"python",
"syntax",
"parameter-passing"
] | What does the `*` mean in the following code (found in the `pprint` library)?
```
def pformat(object, indent=1, width=80, depth=None, *, compact=False):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth,
comp... | It separates positional arguments from [keyword-only arguments](https://www.python.org/dev/peps/pep-3102/) when there are no variable arguments. This is a Python-3-only feature. |
Combine set values into single set | 32,728,394 | 8 | 2015-09-22T23:00:50Z | 32,728,467 | 7 | 2015-09-22T23:07:58Z | [
"python"
] | I have the following dict object:
```
obj = {
'US': set(...),
'FR': set(...),
'BE': set(...)
}
```
How would I combine it into a single set? Currently I'm doing it the verbose way of:
```
items = set(list(obj['US']) + list(obj['FR']) + list(obj['BE']))
``` | An efficient way is with set.union(\*obj.values())
For example:
```
obj = {
'US': set([1,2,3]),
'FR': set([3,4,5]),
'BE': set([5,6,7])
}
set.union(*obj.values())
Out[35]: {1, 2, 3, 4, 5, 6, 7}
``` |
Python's equivalent of Ruby's ||= | 32,729,970 | 14 | 2015-09-23T02:20:44Z | 32,730,327 | 21 | 2015-09-23T03:09:55Z | [
"python",
"ruby"
] | To check if a variable exist, and if exits, use the original value, other wise, use the new value assigned.
In ruby, it's
`var ||= var_new`
How to write it in python?
PS:
I don't know the `name` of `||=`, I simply can't search it in Bing. | I think there is some confusion from the people who aren't really sure what the conditional assignment operator (`||=`) does, and also some misunderstanding about how variables are spawned in Ruby.
Everyone should read [this article](http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html) on ... |
Create Spark DataFrame. Can not infer schema for type: <type 'float'> | 32,742,004 | 11 | 2015-09-23T14:13:33Z | 32,742,294 | 26 | 2015-09-23T14:26:20Z | [
"python",
"python-2.7",
"apache-spark",
"apache-spark-sql",
"pyspark"
] | Could someone help me solve this problem I have with spark DataFrame?
When I do myFloatRDD.toDF() i get an error:
> TypeError: Can not infer schema for type: type 'float'
I don't understand why...
example:
```
myFloatRdd = sc.parallelize([1.0,2.0,3.0])
df = myFloatRdd.toDF()
```
Thanks | `SqlContext.createDataFrame`, which is used under the hood, requires an `RDD` of `Row`/`tuple`/`list`/~~`dict`~~\* or `pandas.DataFrame`. Try something like this:
```
myFloatRdd.map(lambda x: (x, )).toDF()
```
or even better:
```
from pyspark.sql import Row
row = Row("val") # Or some other column name
myFloatRdd.ma... |
How do I convert an RDD with a SparseVector Column to a DataFrame with a column as Vector | 32,745,119 | 7 | 2015-09-23T16:47:51Z | 32,745,924 | 9 | 2015-09-23T17:33:04Z | [
"python",
"apache-spark",
"pyspark",
"rdd",
"spark-dataframe"
] | I have an **RDD** with a tuple of values (String, SparseVector) and I want to create a **DataFrame** using the **RDD**. To get a (label:string, features:vector) **DataFrame** which is the Schema required by most of the ml algorithm's libraries.
I know it can be done because [HashingTF](https://spark.apache.org/docs/lat... | You have to use `VectorUDT` here:
```
from pyspark.mllib.linalg import SparseVector, VectorUDT
temp_rdd = sc.parallelize([
(0.0, SparseVector(4, {1: 1.0, 3: 5.5})),
(1.0, SparseVector(4, {0: -1.0, 2: 0.5}))])
schema = StructType([
StructField("label", DoubleType(), True),
StructField("features", Vect... |
Flask-Login raises TypeError: 'bool' object is not callable when trying to override is_active property | 32,750,526 | 6 | 2015-09-23T22:26:30Z | 32,750,951 | 11 | 2015-09-23T23:11:35Z | [
"python",
"flask",
"flask-login"
] | I want to modify `is_active` in Flask-Login so that users are not always active.
The default always returns `True`, but I changed it to return the value of the `banned` column.
Based on the docs, `is_active` should be a property. However, the internal Flask-Login code raises:
```
TypeError: 'bool' object is not call... | `is_active`, `is_anonymous`, and `is_authenticated` are all properties as of Flask-Login 0.3. If you want to use them, treat them as attributes, don't call them. If you want to override them, remember to decorate them with `@property`.
```
# change from
current_user.is_authenticated()
# to
current_user.is_authenticate... |
Pandas: How to create a data frame of random integers? | 32,752,292 | 7 | 2015-09-24T02:17:00Z | 32,752,318 | 10 | 2015-09-24T02:20:46Z | [
"python",
"pandas",
"dataframe"
] | I know that if I use`randn`,
```
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD')
```
gives me what I am looking for, but with elements from a normal distribution. But what if I just wanted random integers?
`randint` works by providing a range, but not an array like `randn` does. So how do I do this w... | [`numpy.random.randint`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html) accepts a third argument (`size`) , in which you can specify the size of the output array. You can use this to create your `DataFrame` -
```
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('AB... |
Python conditional one or the other but not both | 32,753,157 | 3 | 2015-09-24T04:05:00Z | 32,753,184 | 8 | 2015-09-24T04:08:21Z | [
"python",
"if-statement",
"conditional"
] | I am trying to compile an if statement in python where it checks two variables to see if they are <= .05. Now if both variables are True, I just want the code to pass/continue, but if only one of the variables are True, then I want the code to do something. eg:
```
ht1 = 0.04
ht2 = 0.03
if (ht1 <= 0.05) or (ht2 <= 0.... | What you want is called an "exclusive-OR", which in this case can be expressed as a 'not-equal' or 'is not' relation:
```
if (ht <= 0.05) is not (ht2 <= 0.05):
```
The way this works is that the `if` will only succeed if one of them is `True` and the other one is `False`. If they're both `True` or both `False` then i... |
How to know a generated sequence is at most a certain length | 32,757,073 | 8 | 2015-09-24T08:46:09Z | 32,757,187 | 7 | 2015-09-24T08:52:57Z | [
"python",
"generator"
] | I want to know whether a generated sequence has fewer than 2 entries.
```
>>> def sequence():
... for i in xrange(secret):
... yield i
```
My inefficient method is to create a list, and measure its length:
```
>>> secret = 5
>>> len(list(sequence())) < 2
True
```
Obviously, this consumes the whole gener... | As of Python 3.4, generators can implement a [length hint](http://www.python.org/dev/peps/pep-0424/). If a generator implements this it'll be exposed through the [`object.__length_hint__()` method](https://docs.python.org/3/reference/datamodel.html#object.__length_hint__).
You can test for it with the [`operator.lengt... |
How to write metaclass which would prevent creating new attributes after __init__()? | 32,760,802 | 7 | 2015-09-24T12:01:41Z | 32,760,880 | 10 | 2015-09-24T12:05:46Z | [
"python",
"python-2.7",
"metaclass"
] | Currently I override the class' `__setattr__`() towards the end of the class' `__init__`() method to prevent new attribute creation -
```
class Point(object):
def __init__(self):
self.x = 0
self.y = 0
Point.__setattr__ = self._setattr
def _setattr(self, name, value):
if not has... | Don't reinvent the wheel.
Two simple ways to achieve that (without directly using a metaclass) are using:
1. [`namedtuple`](https://docs.python.org/dev/library/collections.html#collections.namedtuple)s
2. [`__slots__`](https://stackoverflow.com/questions/472000/python-slots)
For example, using `namedtuple` (based on... |
PySpark DataFrames - way to enumerate without converting to Pandas? | 32,760,888 | 9 | 2015-09-24T12:06:15Z | 32,761,138 | 8 | 2015-09-24T12:18:20Z | [
"python",
"apache-spark",
"bigdata",
"pyspark",
"rdd"
] | I have a very big **pyspark.sql.dataframe.DataFrame** named df.
I need some way of enumerating records- thus, being able to access record with certain index. (or select group of records with indexes range)
In pandas, I could make just
```
indexes=[2,3,6,7]
df[indexes]
```
Here I want something similar, *(and withou... | It doesn't work because:
1. the second argument for `withColumn` should be a `Column` not a collection. `np.array` won't work here
2. when you pass `"index in indexes"` as a SQL expression to `where` `indexes` is out of scope and it is not resolved as a valid identifier
**PySpark >= 1.4.0**
~~You can add row numbers... |
Django 1.9 ImportError for import_module | 32,761,566 | 17 | 2015-09-24T12:38:50Z | 32,761,567 | 12 | 2015-09-24T12:38:50Z | [
"python",
"django",
"django-1.9"
] | When trying to run either `runserver` or `shell` using `manage.py` I get an `ImportError` exception. I'm using Django 1.9.
```
ImportError: No module named 'django.utils.importlib'
``` | I solved this with the following:
```
try:
# Django versions >= 1.9
from django.utils.module_loading import import_module
except ImportError:
# Django versions < 1.9
from django.utils.importlib import import_module
``` |
Django 1.9 ImportError for import_module | 32,761,566 | 17 | 2015-09-24T12:38:50Z | 32,763,639 | 29 | 2015-09-24T14:12:40Z | [
"python",
"django",
"django-1.9"
] | When trying to run either `runserver` or `shell` using `manage.py` I get an `ImportError` exception. I'm using Django 1.9.
```
ImportError: No module named 'django.utils.importlib'
``` | `django.utils.importlib` is a compatibility library for when Python 2.6 was still supported. It has been obsolete since Django 1.7, which dropped support for Python 2.6, and is removed in 1.9 per the deprecation cycle.
Use Python's `import_module` function instead:
```
from importlib import import_module
```
The rea... |
how to decode an ascii string with backslash x \x codes | 32,761,954 | 3 | 2015-09-24T12:57:31Z | 32,761,989 | 7 | 2015-09-24T12:59:08Z | [
"python",
"string",
"unicode",
"python-2.x"
] | I am trying to decode from a Brazilian Portogese text:
> 'Demais Subfun\xc3\xa7\xc3\xb5es 12'
It should be
> 'Demais Subfunções 12'
```
>> a.decode('unicode_escape')
>> a.encode('unicode_escape')
>> a.decode('ascii')
>> a.encode('ascii')
```
all give:
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3... | You have binary data that is **not** ASCII encoded. The `\xhh` codepoints indicate your data is encoded with a different codec, and you are seeing Python produce a *representation* of the data [using the `repr()` function](https://docs.python.org/2/library/functions.html#repr) that can be re-used as a Python literal th... |
python: API token generation with itsdangerous | 32,763,177 | 2 | 2015-09-24T13:52:42Z | 32,763,443 | 8 | 2015-09-24T14:03:35Z | [
"python",
"security",
"authentication",
"flask"
] | I'm following the "Flask Web Development" book to implement token based authentication. Basically, user authenticate his/herself with HTTP basic auth and a token is generated for it:
```
s = Serializer(app.config['SECRET_KEY'], expires_in = 3600)
token = s.dumps({ 'id': user.id })
```
But it looks like this doesn't c... | If you need a token that is time sensitive, use the [`TimedSerializer` class](http://pythonhosted.org/itsdangerous/#itsdangerous.TimedSerializer) instead.
Not only does it used a timestamp to form the signature (thus producing a new signature each time you use it), but you can also *limit the token lifetime* using tha... |
My boolean is outputing none? | 32,768,165 | 2 | 2015-09-24T18:11:41Z | 32,768,186 | 8 | 2015-09-24T18:12:47Z | [
"python"
] | ```
sunny = (input('Is it sunny outside? '))
def isItSunny(sunny):
if sunny == True:
return 'Its sunny outside, you may need sunsreen'
elif sunny == False:
return 'Its cloudy, rain might be forcasted!'
print (str(isItSunny(sunny)))
```
When I run this short program and enter "True" or "False" I get an out... | The string `'True'` is not equal to the literal `True`
```
>>> 'True' == True
False
```
You should be doing string comparisons
```
if sunny == 'True':
``` |
Modify each element in a list | 32,769,070 | 3 | 2015-09-24T19:08:00Z | 32,769,113 | 7 | 2015-09-24T19:10:50Z | [
"python",
"list"
] | I thought this question was easy enough but couldn't find an answer.
I have a list of tuples of length 2.
I want to get a list of tuples of length 3 in which the third element is the result of some operation over the other two.
Example:
```
for val_1, val_2 in list_of_tuples
#...
#some multi line operati... | Use a list comprehension.
```
>>> list_of_tups = [(1,2),(2,3),(3,4)]
>>> [(i,j,i+j) for i,j in list_of_tups]
[(1, 2, 3), (2, 3, 5), (3, 4, 7)]
```
Now re-assign it back
```
>>> list_of_tups = [(i,j,i+j) for i,j in list_of_tups]
```
Do not modify lists while iterating as it can have some bad effects. |
Summation of only consecutive values in a python array | 32,770,620 | 5 | 2015-09-24T20:46:32Z | 32,770,770 | 7 | 2015-09-24T20:57:02Z | [
"python",
"arrays",
"numpy"
] | I am new on python (and even programing!), so I will try to be as clear as I can to explain my question. For you guys it could be easy, but I have not found a satisfactory result on this yet.
Here is the problem:
I have an array with both negative and positive values, say:
```
x = numpy.array([1, 4, 2, 3, -1, -6, -6... | You can use [`itertools`](https://docs.python.org/3/library/itertools.html) module, here with using `groupby` you can grouping your items based on those sign then check if it meet the condition in `key` function so it is contains negative numbers then yield the sum else yield it and at last you can use `chain.from_iter... |
Optimization Break-even Point: iterate many times over set or convert to list first? | 32,770,762 | 13 | 2015-09-18T21:15:45Z | 32,770,763 | 30 | 2015-09-20T13:45:48Z | [
"python",
"optimization",
"hash",
"list",
"iterator"
] | Here's something I've always wondered about. I'll pose the question for Python, but I would also welcome answers which address the standard libraries in Java and C++.
Let's say you have a Python list called "my\_list", and you would like to iterate over its **unique** elements. There are two natural approaches:
```
#... | > # I'm looking for a rule of thumb...
## Rule of thumb
Here's the best rule of thumb for writing optimal Python: use as few intermediary steps as possible and avoid materializing unnecessary data structures.
Applied to this question: sets are iterable. Don't convert them to another data structure just to iterate ov... |
pip install PIL fails | 32,772,596 | 6 | 2015-09-24T23:36:26Z | 32,800,456 | 9 | 2015-09-26T18:18:13Z | [
"python",
"django",
"pip",
"python-imaging-library"
] | I am trying to install the pip package PIL. However the install doesn't work throwing the following error.
```
Could not find a version that satisfies the requirement pil (from xhtml2pdf==0.0.4->-r virtualenv-reqs.txt (line 16)) (from versions: )
Some externally hosted files were ignored as access to them may be unr... | Pillow is a maintained fork of PIL, so I recommend using Pillow. But you can't have both installed at the same time.
1. First, remove both PIL and Pillow.
2. Then install Pillow with `pip install pillow` (although, depending on platform, you may need some [prerequisites](https://pillow.readthedocs.org/installation.htm... |
Print a line in python up to a space | 32,774,634 | 2 | 2015-09-25T04:06:03Z | 32,774,650 | 7 | 2015-09-25T04:07:54Z | [
"python"
] | If I have two separate values in a line like this:
```
1234556 1234567
```
How would I go about printing out both numbers in two separate variables?
The digits lengths will change per line so i cant simply search index the line.
Thanks | ```
s = "1234556 1234567"
a, b = map(int, s.split(' '))
print a, b
``` |
How to compare wrapped functions with functools.partial? | 32,786,078 | 4 | 2015-09-25T15:52:33Z | 32,786,109 | 7 | 2015-09-25T15:54:30Z | [
"python",
"functools"
] | If I define my function as below:
```
def myfunc(arg1, arg2):
pass
```
then `myfunc == myfunc` will return `True`
But `functools.partial(myfunc, arg2=1) == functools.partial(myfunc, arg2=1)` will return `False`.
For unittest purpose, is there an easy way to test if the partial function is the one I expect? | Test if the `func`, `args` and `keywords` attributes are the same:
```
p1.func == p2.func and p1.args == p2.args and p1.keywords == p2.keywords
```
where `p1` and `p2` are both `partial()` objects:
```
>>> from functools import partial
>>> def myfunc(arg1, arg2):
... pass
...
>>> partial(myfunc, arg2=1).func ==... |
How to add a constant column in a Spark DataFrame? | 32,788,322 | 16 | 2015-09-25T18:17:14Z | 32,788,650 | 33 | 2015-09-25T18:40:15Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] | I want to add a column in a `DataFrame` with some arbitrary value (that is the same for each row). I get an error when I use `withColumn` as follows:
```
dt.withColumn('new_column', 10).head(5)
---------------------------------------------------------------------------
AttributeError Traceb... | The second argument for `DataFrame.withColumn` should be a `Column` so you have to use a literal:
```
from pyspark.sql.functions import lit
df.withColumn('new_column', lit(10))
```
If you need complex columns you can build these using blocks like `array`:
```
from pyspark.sql.functions import array, struct
df.with... |
'PipelinedRDD' object has no attribute 'toDF' in PySpark | 32,788,387 | 13 | 2015-09-25T18:21:06Z | 32,788,832 | 23 | 2015-09-25T18:52:37Z | [
"python",
"apache-spark",
"apache-spark-sql",
"pyspark",
"apache-spark-ml"
] | I'm trying to load an SVM file and convert it to a DataFrame so I can use the ML module (Pipeline ML) from Spark.
I've just installed a fresh Spark 1.5.0 on an Ubuntu 14.04 (no spark-env.sh configured).
My `my_script.py` is:
```
from pyspark.mllib.util import MLUtils
from pyspark import SparkContext
sc = SparkContext... | `toDF` method is a monkey patch executed inside `SQLContext` (`SparkSession` constructor in 2.0+) constructor so to be able to use it you have to create a `SQLContext` (or `SparkSession`) first:
```
from pyspark.sql import SQLContext # or from pyspark.sql import HiveContext
rdd = sc.parallelize([("a", 1)])
hasattr(rd... |
Selenium unexpectedly having issues | 32,792,739 | 21 | 2015-09-26T01:31:04Z | 32,792,757 | 37 | 2015-09-26T01:34:49Z | [
"python",
"google-chrome",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] | I have been using selenium now for a while on a number of projects.
With code that was running I am now receiving the following error:
```
C:\Users\%USER%\Miniconda\python.exe C:/Users/%USER%/PycharmProjects/c_r/quick_debug.py
Traceback (most recent call last):
File "C:/Users/%USER%/PycharmProjects/c_r/... | After having a quick look at the [source code](https://chromium.googlesource.com/chromium/src/+/31b6a93e15c029f5ccba9b4a9af47366ad5205f0/chrome/test/chromedriver/chrome/browser_info.cc#103), I think this is a compatibility issue between ChromeDriver and Chrome itself - I suspect your Chrome auto-updated and now is too ... |
What is the runtime complexity (big O) of the following pseudocode? | 32,793,881 | 5 | 2015-09-26T05:11:27Z | 32,793,921 | 11 | 2015-09-26T05:19:22Z | [
"python",
"algorithm",
"big-o",
"time-complexity"
] | I recently had a very, very intense debate about the runtime complexity of a super simple algorithm with a colleague of mine. In the end we both agreed to disagree but as I've been thinking about this, it's challenged my basic understanding of computer science fundamentals and so I therefore must get additional insight... | Applying Big-O notation to a single scenario in which all the inputs are known is ludicrous. There *is* no Big-O for a single case.
The whole point is to get a worst-case estimate for arbitrarily large, ***unknown* values of *n***. If you already know the exact answer, why on Earth would you waste time trying to estim... |
Checking if a variable belongs to a class in python | 32,796,536 | 8 | 2015-09-26T11:11:45Z | 32,796,572 | 7 | 2015-09-26T11:16:06Z | [
"python",
"class",
"instance"
] | I have a small class which is as follows :
```
class Gender(object):
MALE = 'M'
FEMALE = 'F'
```
I have a parameter variable which can be only **M** or **F**.To ensure it is only that, I do the following :
```
>>> parameter = 'M'
>>> if parameter not in (Gender.MALE, Gender.FEMALE)
... print "Invalid par... | You could use the `__dict__` property which composes a class, for example:
```
In [1]: class Foo(object):
...: bar = "b"
...: zulu = "z"
...:
In [2]: "bar" in Foo.__dict__
Out[2]: True
```
Or as you're searching for the values use `__dict__.values()`:
```
In [3]: "b" in Foo.__dict__.values()
O... |
NumPy sum along disjoint indices | 32,798,519 | 3 | 2015-09-26T14:59:50Z | 32,798,907 | 7 | 2015-09-26T15:43:46Z | [
"python",
"arrays",
"numpy",
"sum"
] | I have an application where I need to sum across arbitrary groups of indices in a 3D NumPy array. The built-in NumPy array sum routine sums up all indices along one of the dimensions of an ndarray. Instead, I need to sum up ranges of indices along one of the dimensions in my array and return a new array.
For example, ... | You can use `np.add.reduceat` as a general approach to this problem. This works even if the ranges are not all the same length.
To sum the slices `0:25`, `25:50` and `50:75` along axis 0, pass in indices `[0, 25, 50]`:
```
np.add.reduceat(a, [0, 25, 50], axis=0)
```
This method can also be used to sum non-contiguous... |
PyCrypto on python 3.5 | 32,800,336 | 18 | 2015-09-26T18:07:07Z | 33,338,523 | 24 | 2015-10-26T04:33:51Z | [
"python",
"pycrypto"
] | i found some exes of PyCrypto for python 3.3 and 3.4, but nothing for python 3.5.
When i try to install PyCrypton using pip install, it says:
warning: GMP or MPIR library not found; Not building Crypto.PublicKey.\_fastmath.
Is there any way how to install PyCrypto on python 3.5 in Windows 10? Thanks! | That warning shouldn't stop the build, more likely you are lacking the Visual Studio 2015 compiler which is necessary to build binary extensions (which PyCrypto has). See the [Python Packaging User Guide](https://packaging.python.org/en/latest/extensions/#building-binary-extensions) for which compiler you need for your... |
How to get the FFT of a numpy array to work? | 32,800,623 | 4 | 2015-09-26T18:34:55Z | 32,800,723 | 8 | 2015-09-26T18:44:09Z | [
"python",
"arrays",
"csv",
"numpy",
"fft"
] | I'm reading a specific column of a csv file as a numpy array. When I try to do the fft of this array I get an array of NaNs. How do I get the fft to work? Here's what I have so far:
```
#!/usr/bin/env python
from __future__ import division
import numpy as np
from numpy import fft
import matplotlib.pyplot as plt
fi... | Presumably there are some missing values in your csv file. By default, `np.genfromtxt` will replace the missing values with `NaN`.
If there are any `NaN`s or `Inf`s in an array, the `fft` will be all `NaN`s or `Inf`s.
For example:
```
import numpy as np
x = [0.1, 0.2, np.nan, 0.4, 0.5]
print np.fft.fft(x)
```
And ... |
pandas concat ignore_index doesn't work | 32,801,806 | 6 | 2015-09-26T20:38:35Z | 32,802,014 | 8 | 2015-09-26T21:05:10Z | [
"python",
"pandas",
"append",
"concat"
] | I am trying to column bind dataframes and having issue with pandas concat, ignore\_index = True doesn't seem to work:
```
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 2, 3,4])
df2... | If I understood you correctly, this is what you would like to do.
```
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 2, 3,4])
df2 = pd.DataFrame({'A1': ['A4', '... |
Is there a possibility to override a unary operator with a binary one in Python? | 32,806,796 | 6 | 2015-09-27T10:08:06Z | 32,806,818 | 11 | 2015-09-27T10:10:43Z | [
"python",
"operator-overloading",
"unary-operator"
] | I tried to define a class and override the tilde operator:
```
class foo:
def __invert__(self, other)
return 1232 # a random number , just as test
```
Then calling it like:
```
>>> f = foo()
>>> g = foo()
>>> f ~ g
File "<input>", line 1
f ~ g
^
SyntaxError: invalid syntax
```
Can we replace... | No, you can't do that, not without radically altering how Python compiles bytecode. All expressions are first *parsed* into a Abstract Syntax Tree, then compiled into bytecode from that, and it is at the parsing stage that operands and operators are grouped.
By the time the bytecode runs you can no longer decide to ac... |
How to use async/await in Python 3.5? | 32,808,893 | 21 | 2015-09-27T14:19:35Z | 32,808,937 | 27 | 2015-09-27T14:25:00Z | [
"python",
"python-3.x",
"async-await",
"coroutine",
"python-3.5"
] | ```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
async def foo():
await time.sleep(1)
foo()
```
I couldn't make this dead simple example to run:
```
RuntimeWarning: coroutine 'foo' was never awaited foo()
``` | Running coroutines requires an *event loop*. Use the [`asyncio()` library](https://docs.python.org/3/library/asyncio.html) to create one:
```
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(foo())
loop.close()
```
Also see the [*Tasks and Coroutines* chapter of the `asyncio` documentation](htt... |
What is causing this Python syntax error? | 32,811,007 | 4 | 2015-09-27T17:52:19Z | 32,811,036 | 7 | 2015-09-27T17:54:47Z | [
"python",
"django"
] | I'm totally new to Python, and I'm trying to run my server but I'm getting this syntax error from the project I'm working on.
```
def find_shortest_path(start: GraphNode, end, path=[]):
^
SyntaxError: invalid syntax
```
To be clear, I didn't write the code, I'm just supposed to sty... | This code appears to be using [function annotations](https://docs.python.org/3/tutorial/controlflow.html#function-annotations) which are only available in Python 3.X.
What [version](http://stackoverflow.com/questions/8917885/which-version-of-python-do-i-have-installed) of Python are you using? |
Python: Assertion error, "not called" | 32,813,455 | 7 | 2015-09-27T22:21:06Z | 32,872,455 | 8 | 2015-09-30T17:38:34Z | [
"python",
"multithreading",
"smtp"
] | I am finding it difficult to tackle the following bugs with the program, I would greatly appreciate some input.
The goal of the program is to perform a SMTP scan. The user inputs the target IP address, usernames, passwords and numbers of threads to allocate to the scanning process.
```
Traceback (most recent call las... | Your constructor of myThread class must be:
```
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self, name=name)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("[+] Starting ... |
Are global variables thread safe in flask? | 32,815,451 | 11 | 2015-09-28T03:52:36Z | 32,825,482 | 10 | 2015-09-28T14:26:28Z | [
"python",
"flask",
"thread-safety"
] | In my app the state of a common object is changed by making requests, and the response depends on the state.
```
class SomeObj():
def __init__(self, param):
self.param = param
def query(self):
self.param += 1
return self.param
global_obj = SomeObj(0)
@app.route('/')
def home():
fl... | You can't use global variables to hold this sort of data. Not only is it not thread safe, it's not *process* safe, and WSGI servers in production spawn multiple processes. So not only would your counts be wrong if you were using threads to handle requests, they would also vary depending on which process handled the req... |
Convert every character in a String to a Dictionary Key | 32,816,104 | 6 | 2015-09-28T05:18:27Z | 32,816,131 | 9 | 2015-09-28T05:20:50Z | [
"python",
"string",
"dictionary"
] | Suppose i have a string `"abcdefghijklmnopqrstuvwxyz"`and i want to initialize dictionary keys with those values.
```
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabetDict = dict()
for char in alphabet:
alphabetDict[char] = 0
```
Is there a better way of doing that? | You can use [`dict.fromkeys()`](https://docs.python.org/2/library/stdtypes.html#dict.fromkeys) method -
```
>>> s = 'abcdefghijklmnopqrstuvwxyz'
>>> alphaDict = dict.fromkeys(s,0)
>>> alphaDict
{'m': 0, 'p': 0, 'i': 0, 'n': 0, 'd': 0, 'w': 0, 'k': 0, 'y': 0, 's': 0, 'b': 0, 'h': 0, 't': 0, 'u': 0, 'q': 0, 'g': 0, 'l':... |
Getting "django.core.exceptions.ImproperlyConfigured: GEOS is required and has not been detected." although GEOS is installed | 32,818,523 | 9 | 2015-09-28T08:20:02Z | 32,821,948 | 22 | 2015-09-28T11:32:11Z | [
"python",
"django",
"ubuntu-14.04",
"geodjango",
"geos"
] | I'm running *Django 1.8* and *Python 3.4* on *Ubuntu 14.04 LTS*. Just recently, my Django app has been reporting that **GEOS** is not present. **GEOS** is installed and **libgeos\_c.so** is where it's supposed to be (*/usr/lib/*). My code seems fine. It is the source of a docker image which still works. This seems to i... | I had the same problem today, though in an unrelated python project. This is is the line I also encountered and which led me here:
```
ImportError: /usr/lib/python3.4/lib-dynload/_ctypes.cpython-34m-x86_64-linux-gnu.so: undefined symbol: _PyTraceback_Add
```
It looks like Ubunut has pushed a Python 3.4 update which i... |
How to override default python functions like round()? | 32,822,046 | 4 | 2015-09-28T11:37:29Z | 32,822,094 | 13 | 2015-09-28T11:39:55Z | [
"python",
"python-3.x",
"python-2.x"
] | I Want to override default round() function of python because I have to convert the result of round() function into integer. By default round() returns value in float.
The code given below is returning error message.
**RuntimeError: maximum recursion depth exceeded while calling a Python object.**
```
def round(numbe... | The issue with your current code is that after you have overwritten the built-in `round()` method, when you call `round()` inside your own `round()` , you are recursively calling your own function, not the built-in `round` function.
For Python 3.x, you can use [`builtins`](https://docs.python.org/3/library/builtins.ht... |
Django: "No module named context_processors" error after reboot | 32,828,536 | 4 | 2015-09-28T17:23:00Z | 38,907,086 | 8 | 2016-08-11T22:30:05Z | [
"python",
"django"
] | I have a Django site that works on my PC, and was working briefly on my server after loading it on. I noticed my server had Django 1.6 and I upgraded to 1.8.
After rebooting, none of the pages on my site load and I get the error:
ImportError No module named context\_processors
I read through the docs on Django and a... | I encountered the same problem but I am upgrading from 1.9.1 to 1.10. I found there's a little difference in the setttings.
This is the code form 1.9.1
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OP... |
Why does open(True, 'w') print the text like sys.stdout.write? | 32,841,090 | 11 | 2015-09-29T09:59:38Z | 32,841,230 | 10 | 2015-09-29T10:06:25Z | [
"python",
"python-3.x"
] | I have the following code:
```
with open(True, 'w') as f:
f.write('Hello')
```
Why does this code print the text `Hello` instead of raise an error? | From the [built-in function documentation on `open()`](https://docs.python.org/3/library/functions.html#open):
> `open(file, mode='r', buffering=-1...`
> *file* is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file des... |
python for loop increasing or decreasing | 32,843,354 | 5 | 2015-09-29T11:55:16Z | 32,843,706 | 7 | 2015-09-29T12:11:03Z | [
"python",
"python-2.7",
"python-3.x",
"for-loop"
] | I have to loop between two values where sometimes the first value is lesser that the second and some other times the first is greater than the second (I'm working on two cells inside a grid and the first cell can be on the left of the second or viceversa).
With python I can specify if a for loop has to decrease or to ... | Note that using `step=-1` is *not* the same as a range from the smaller to the larger value!
```
>>> range(3, 7, 1)
[3, 4, 5, 6]
>>> range(7, 3, -1)
[7, 6, 5, 4]
```
The first one is from 3 to 6, the latter one from 4 to 7.
If that's still what you want, another way would be to use `or`:
```
>>> x, y = 7, 3
>>> ran... |
Quick way to upsample numpy array by nearest neighbor tiling | 32,846,846 | 4 | 2015-09-29T14:37:15Z | 32,848,377 | 7 | 2015-09-29T15:45:13Z | [
"python",
"arrays",
"numpy"
] | I have a 2D array of integers that is *MxN*, and I would like to expand the array to *(BM)x(BN)* where *B* is the length of a square tile side thus each element of the input array is repeated as a *BxB* block in the final array. Below is an example with a nested for loop. Is there a quicker/builtin way?
```
import num... | Here's a potentially fast way using stride tricks and reshaping:
```
from numpy.lib.stride_tricks import as_strided
def tile_array(a, b1, b2):
r, c = a.shape
rs, cs = a.strides
x = as_strided(a, (r, b1, c, b2), (rs, 0, cs, 0))
return x.reshape(r*b1, c*b2)
```
(Note: data needs to be copied for the `r... |
filter mystery output | 32,847,796 | 4 | 2015-09-29T15:18:18Z | 32,847,844 | 7 | 2015-09-29T15:20:34Z | [
"python",
"list",
"filter",
"lambda"
] | I was reading about `filter`, `lambda` and `map`. When I tried using them, I found this peculiarity :
```
def returnAsIs(element):
return element
print range(10)
print filter(returnAsIs, range(10))
print map(lambda x : x, range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6,... | **Why the element `0` gets skipped in `filter()`?**
This is happening because value `0` evaluates to `False`.
As per the [`.filter()` docs:](https://docs.python.org/2/library/functions.html#filter)
> Construct a list from those elements of iterable for which **function
> returns true.**
So, when we apply `filter(fu... |
How does __call__ actually work? | 32,855,927 | 9 | 2015-09-30T00:34:59Z | 32,856,533 | 8 | 2015-09-30T01:56:14Z | [
"python"
] | Python's magic method `__call__` is called whenever you attempt to call an object. `Cls()()` is thus equal to `Cls.__call__(Cls())`.
Functions are first class objects in Python, meaning they're just callable objects (using `__call__`). However, `__call__` itself is a function, thus it too has `__call__`, which again h... | Under the hood, all calls in Python use the same mechanism, and almost all arrive at the same C function in the CPython implementation. Whether an object is an instance of a class with a `__call__` method, a function (itself an object), or a builtin object, all calls (except for optimized special cases) arrive at the f... |
In Odoo 8 ORM api , how to get results in reverse order using search()? | 32,860,626 | 3 | 2015-09-30T07:46:33Z | 32,864,423 | 7 | 2015-09-30T11:00:49Z | [
"python",
"python-2.7",
"python-3.x",
"odoo",
"odoo-8"
] | I try to use [search()](https://www.odoo.com/documentation/8.0/reference/orm.html#openerp.models.Model.search) to fetch data from a table in a http controller.
```
x = obj.search(cr, uid, criteria, offset=0,limit=36,order=sortBy)
```
It returns an array containing the ids of the top 36 items ordered by `sortBy` but ... | **Search**
Takes a search [domain](https://www.odoo.com/documentation/8.0/reference/orm.html#reference-orm-domains), returns a recordset of matching records. Can return a subset of matching records (offset and limit parameters) and be ordered (order parameter):
Syntax:
```
search(args[, offset=0][, limit=None][, ord... |
infinite type error in haskell when trying to translate python function into haskell. Why? | 32,861,367 | 4 | 2015-09-30T08:27:34Z | 32,862,899 | 8 | 2015-09-30T09:44:11Z | [
"python",
"algorithm",
"haskell"
] | ```
def get_N_Partition_Permutations(xs, n):
if n == 1:
return [[xs]]
acc = []
for i in xrange(1,len(xs)):
acc += [[xs[:i]] + j for j in get_N_Partition_Permutations(xs[i:], n-1)]
return acc
```
I'm trying to implement the function above (which is in Python) in haskell below.
```
getNP... | First of all, I've made your Haskell code a little bit more comprehensible:
```
getNPartitionPermutations :: [a] -> Int -> [[[a]]]
getNPartitionPermutations xs 1 = [[xs]]
getNPartitionPermutations xs n = iter xs 1 []
where iter ys n acc
| length xs == n = acc
| otherwise =
... |
How to create an ec2 instance using boto3 | 32,863,768 | 6 | 2015-09-30T10:27:31Z | 32,863,919 | 11 | 2015-09-30T10:34:48Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto",
"boto3"
] | Is it possible to create an ec2 instance using boto3 in python?
Boto3 document is not helping here, and I couldn't find any helping documents online. please provide some sample codes/links. | The API has changed but it's right there in the documentation
```
# Boto 3
ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)
```
Link to the documentation:
<http://boto3.readthedocs.org/en/latest/guide/migrationec2.html#launching-new-instances> |
What would be a compact way to return 1 if a variable is 0 and to return 0 if it is 1? | 32,866,760 | 3 | 2015-09-30T12:58:52Z | 32,866,793 | 7 | 2015-09-30T13:00:31Z | [
"python",
"boolean",
"invert"
] | How could the following be made more compact (perhaps using Booleans), given that I am supplied with an integer variable?
```
indexTag = 0 # or 1
1 if indexTag == 0 else 0
``` | You could use `not`:
```
not indexTag
```
which gives you a *boolean* (`True` or `False`), but Python booleans are a subclass of `int` and do have an integer value (`False` is `0`, `True` is `1`). You could turn that back into an integer with `int(not indexTag)` but if this is just a boolean, why bother?
Or you coul... |
Test if two numpy arrays are (close to) equal, including shape | 32,874,840 | 6 | 2015-09-30T20:16:56Z | 32,875,374 | 7 | 2015-09-30T20:49:13Z | [
"python",
"numpy"
] | I want to test if two numpy arrays are (close to) equal, so I've been using the `np.allclose` function. The only problem is, it returns `True` if given a two-dimensional matrix and a three-dimensional matrix of equal elements.
```
import numpy as np
x = np.array([[3.14159265, -0.1], [-0.1, 0.1]])
y = np.array([[math... | What's happening is that `allclose` broadcasts its input. This allows comparisons with similarly shaped arrays (e.g. `3` and `[3, 3, 3]`) following the [broadcasting rules](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).
---
For your purposes, have a look at the `numpy.testing` functions, specifically... |
Is there a way to use asyncio.Queue in multiple threads? | 32,889,527 | 5 | 2015-10-01T13:58:54Z | 32,894,169 | 10 | 2015-10-01T18:11:45Z | [
"python",
"python-3.x",
"python-asyncio"
] | Let's assume I have the following code:
```
import asyncio
import threading
queue = asyncio.Queue()
def threaded():
import time
while True:
time.sleep(2)
queue.put_nowait(time.time())
print(queue.qsize())
@asyncio.coroutine
def async():
while True:
time = yield from queue... | `asyncio.Queue` [is not thread-safe](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue), so you can't use it directly from more than one thread. Instead, you can use [`janus`](https://github.com/aio-libs/janus), which is a third-party library that provides a thread-aware `asyncio` queue:
```
import as... |
Taking Apart A List Python | 32,890,089 | 3 | 2015-10-01T14:26:22Z | 32,890,303 | 7 | 2015-10-01T14:37:00Z | [
"python",
"list",
"stacked"
] | If I have a list like:
```
X = [0, 2, 3, 4.0, 1, 0, 3, 0, 0, 0, 2, 1, 5, 2, 6, 0, 2.2, 1]
```
How would I write code in python that takes this list and finds the number of consecutive positive numbers and then makes a list that has lists of each of those consecutive numbers in it.
for example this example of x would... | There is no need to fine the zeros. You can simply loop over your list and put the positive numbers in a temporary list until you encounter with a zero, but as a more pythonic approach for such tasks you can use [*itertools.groupby*](https://docs.python.org/3/library/itertools.html#itertools.groupby) :
```
>>> from it... |
Pandas dataframe - running sum with reset | 32,890,124 | 6 | 2015-10-01T14:28:08Z | 32,891,081 | 7 | 2015-10-01T15:13:06Z | [
"python",
"pandas",
"dataframe",
"cumsum"
] | I want to calculate the running sum in a given column(without using loops, of course). The caveat is that I have this other column that specifies when to reset the running sum to the value present in that row. Best explained by the following example:
```
reset val desired_col
0 0 1 1
1 0 5 6
... | You can use 2 times `cumsum()`:
```
# reset val desired_col
#0 0 1 1
#1 0 5 6
#2 0 4 10
#3 1 2 2
#4 1 -1 -1
#5 0 6 5
#6 0 4 9
#7 1 2 2
df['cumsum'] = df['reset'].cums... |
Is there an OrderedDict comprehension? | 32,895,660 | 2 | 2015-10-01T19:45:31Z | 32,895,702 | 12 | 2015-10-01T19:48:25Z | [
"python",
"beautifulsoup"
] | I don't know if there is such a thing - but I'm trying to do an ordered dict comprehension. However it doesn't seem to work?
```
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
t_data = OrderedDict()
rows = ta... | You can't directly do a comprehension with an `OrderedDict`. You can, however, use a generator in the constructor for `OrderedDict`.
Try this on for size:
```
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
r... |
Unable to install nltk on Mac OS El Capitan | 32,898,583 | 23 | 2015-10-01T23:57:39Z | 32,930,419 | 31 | 2015-10-04T05:42:12Z | [
"python",
"python-2.7",
"nltk"
] | I did `sudo pip install -U nltk` as suggested by the nltk documentation.
However, I am getting the following output:
```
Collecting nltk
Downloading nltk-3.0.5.tar.gz (1.0MB)
100% |ââââââââââââââââââââââââââââââââ| 1.0MB 516kB/s
Collecting six>=1.9... | Here is the way how I fixed the issues:
First, install `Xcode CLI`:
```
xcode-select --install
```
Then reinstall `Python`:
```
sudo brew reinstall python
```
Finally, install `nltk`:
```
sudo pip install -U nltk
```
Hope it helps :) |
Unable to install nltk on Mac OS El Capitan | 32,898,583 | 23 | 2015-10-01T23:57:39Z | 33,024,464 | 16 | 2015-10-08T19:33:12Z | [
"python",
"python-2.7",
"nltk"
] | I did `sudo pip install -U nltk` as suggested by the nltk documentation.
However, I am getting the following output:
```
Collecting nltk
Downloading nltk-3.0.5.tar.gz (1.0MB)
100% |ââââââââââââââââââââââââââââââââ| 1.0MB 516kB/s
Collecting six>=1.9... | I know there's plenty of 'brew boosters' out there, but you shouldn't need to use another python for something so basic. If a dependency is found by `pip` in /System, as they said on South Park 'you're going to have a bad time'. If you don't need to make this change system-wide, you can just `pip install --user <packag... |
One object two foreign keys to the same table | 32,898,831 | 6 | 2015-10-02T00:32:18Z | 32,899,385 | 9 | 2015-10-02T01:50:22Z | [
"python",
"postgresql",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] | I need to have a post associated to two users. The author and the moderator. I am trying without success this code
```
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
...
post = db.relationship('Post', foreign_keys=['posts.id'], backref='post_user',... | One of the issues here is that you are currently trying to use table columns in the relationship `foreign_keys`, rather than class attributes.
That is, instead of using `posts.id`, you should be using `Post.id`. (In fact, to refer to a table column, you would need to use `posts.c.id`).
So, it is possible that your or... |
Need interpretation for this code | 32,904,707 | 2 | 2015-10-02T09:52:28Z | 32,904,754 | 7 | 2015-10-02T09:54:42Z | [
"python"
] | ```
n1, n2, n3 = (n + [None]*2)[:3]
```
I just very briefly want to know what this does, how this works.
Is this like a list comprehension, as long as I offer a list or iterable with enough variables will it assign the n1 = iterable[0]?
Also why does having [:3] on the end of the brackets limit the length?
I underst... | This takes the first three elements of `n`, padding with `None` if it has fewer than three elements.
`(n + [None]*2)` concatenates a list of `[None, None]` to the list `n`, and as you say, `[:3]` takes the first three items of the resulting list. These three items are then unpacked to the variables `n1`, `n2` and `n3`... |
OSError: dlopen(libSystem.dylib, 6): image not found | 32,905,322 | 7 | 2015-10-02T10:33:44Z | 32,906,318 | 9 | 2015-10-02T11:35:49Z | [
"python",
"django",
"celery"
] | Just updated my Mac to El Capitan 10.11.
I am trying to run Django 1.6 with Celery 3.1 and I'm getting this error now:
```
Unhandled exception in thread started by <function wrapper at 0x10f861050>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 93, in wra... | I suspect (but can't confirm) the [System Integrity Protection (SIP)](https://en.wikipedia.org/wiki/System_Integrity_Protection) of OSX El Capitan is preventing access to your `/usr/lib` folder.
It would be extreme and defeating the purpose of the security feature, but you could try disabling SIP by booting into the O... |
OSError: dlopen(libSystem.dylib, 6): image not found | 32,905,322 | 7 | 2015-10-02T10:33:44Z | 33,794,703 | 8 | 2015-11-19T03:22:54Z | [
"python",
"django",
"celery"
] | Just updated my Mac to El Capitan 10.11.
I am trying to run Django 1.6 with Celery 3.1 and I'm getting this error now:
```
Unhandled exception in thread started by <function wrapper at 0x10f861050>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 93, in wra... | ```
pip install --upgrade billiard
pip install --upgrade celery
pip install --upgrade kombu
pip install --upgrade amqp
```
This should work. |
Why Python splits read function into multiple syscalls? | 32,906,360 | 5 | 2015-10-02T11:38:06Z | 33,840,585 | 8 | 2015-11-21T06:50:28Z | [
"python",
"system-calls",
"dd"
] | I tested this:
```
strace python -c "fp = open('/dev/urandom', 'rb'); ans = fp.read(65600); fp.close()"
```
With the following partial output:
```
read(3, "\211^\250\202P\32\344\262\373\332\241y\226\340\16\16!<\354\250\221\261\331\242\304\375\24\36\253!\345\311"..., 65536) = 65536
read(3, "\7\220-\344\365\245\240\34... | I did some research on exactly why this happens.
Note: I did my tests with Python 3.5. Python 2 has a different I/O system with the same quirk for a similar reason, but this was easier to understand with the new IO system in Python 3.
As it turns out, this is due to Python's BufferedReader, not anything about the act... |
Getting rotation of a list in python | 32,908,010 | 3 | 2015-10-02T13:13:43Z | 32,908,135 | 7 | 2015-10-02T13:21:41Z | [
"python",
"list"
] | I want all possible single right shift arrays:
```
def gen(total):
rot = []
init = [0]*total
init[0] = 1
print init
rot.append(init)
for i in range(total-1):
init[i] = init[i] - init[i+1]
init[i+1] = init[i] + init[i+1]
init[i] = init[i+1] - init[i]
print init
... | Existing answers cover pretty well the problem with the existing code, so here's a different approach entirely:
```
>>> [[int(a==b) for b in range(8)] for a in range(8)]
[[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, ... |
Zlib error when installing Pillow on Mac | 32,909,426 | 9 | 2015-10-02T14:25:48Z | 33,003,406 | 13 | 2015-10-07T22:21:27Z | [
"python",
"osx",
"pillow"
] | I've been trying to install the module Pillow on my Mac (running a fresh install of El Capitan and python 3.5) for some time now. Using pip3 install Pillow, I get an error saying that zlib is not found, which then causes the install to abort. I've installed Xcode, so theoretically zlib is already installed, and when I ... | Running
```
$ xcode-select --install
```
seems to have solved the problem for me. |
Flask: 'session' vs. 'g'? | 32,909,851 | 19 | 2015-10-02T14:47:13Z | 32,910,056 | 23 | 2015-10-02T14:57:18Z | [
"python",
"session",
"flask"
] | I'm trying to understand the differences in functionality and purpose between `g` and `session`. Both are objects to 'hang' session data on, am I right? If so, what exactly are the differences and which one should I use in what cases? | No, `g` is *not* an object to hang session data on. `g` data is not persisted between requests.
`session` gives you a place to store data *per specific browser*. As a user of your Flask app, using a specific browser, returns for more requests, the session data is carried over across those requests.
`g` on the other h... |
Is there a way to auto generate a __str__() implementation in python? | 32,910,096 | 4 | 2015-10-02T14:58:59Z | 33,800,620 | 9 | 2015-11-19T10:01:33Z | [
"python",
"boilerplate"
] | Being tired manually implementing a string representation for my classes, I was wondering if there is a pythonic way to do that automatically.
I would like to have an output that covers all the attributes of the class and the class name. Here is an example:
```
class Foo(object):
attribute_1 = None
attribute_... | You can iterate instnace attributes using [`vars`](https://docs.python.org/2/library/functions.html#vars), [`dir`](https://docs.python.org/2/library/functions.html#dir), ...:
```
>>> def auto_str(cls):
... def __str__(self):
... return '%s(%s)' % (
... type(self).__name__,
... ', '.... |
A simple looping command In Python | 32,910,848 | 10 | 2015-10-02T15:39:31Z | 32,910,955 | 13 | 2015-10-02T15:44:43Z | [
"python",
"loops",
"while-loop",
"boolean"
] | So, I recently got into programming in python and decided to make a simple code which ran some simple maths e.g calculating the missing angle in a triangle and other simple things like that. After I made the program and a few others, I thought that maybe other people I know could use this so I decided to try and make t... | ```
while True:
a = int(input("What's one of the angles?" + '\n'))
b = int(input("What's the other angle in the triangle?"+ '\n'))
c = (a + b)
f = int(180 - c)
print(f)
if input("Would you like to do another? 'y' or 'n'"+ '\n').lower() == 'y':
pass
else:
break
```
You can ju... |
Pass !, !=, ~, <, > as parameters | 32,934,064 | 7 | 2015-10-04T13:35:35Z | 32,934,078 | 8 | 2015-10-04T13:37:14Z | [
"python",
"arguments",
"params",
"args",
"kwargs"
] | I want to be able to pass arguments like this:
```
fn(a>=b) or fn(a!=b)
```
I saw this behavior in DjangoORM and SQLAlchemy but I don't know how to achieve it. | ORMs use [*special methods*](https://docs.python.org/2/reference/datamodel.html#specialnames) on classes for `a` and `b` to hook into operators and customise what is produced.
`>=` for is handled by the [`object.__ge__()` method](https://docs.python.org/2/reference/datamodel.html#object.__ge__), while `!=` calls [`obj... |
Python: Apply function to values in nested dictionary | 32,935,232 | 3 | 2015-10-04T15:38:57Z | 32,935,278 | 9 | 2015-10-04T15:44:00Z | [
"python",
"python-2.7",
"loops",
"dictionary"
] | I have an arbitrarily deep set of nested dictionary:
```
x = {'a': 1, 'b': {'c': 6, 'd': 7, 'g': {'h': 3, 'i': 9}}, 'e': {'f': 3}}
```
and I'd like to basically apply a function to all the integers in the dictionaries, so like `map`, I guess, but for nested dictionaries.
So: `map_nested_dicts(x, lambda v: v + 7)` wo... | Visit all nested values recursively:
```
import collections
def map_nested_dicts(ob, func):
if isinstance(ob, collections.Mapping):
return {k: map_nested_dicts(v, func) for k, v in ob.iteritems()}
else:
return func(ob)
map_nested_dicts(x, lambda v: v + 7)
# Creates a new dict object:
# {'a... |
Cannot upgrade Pip. Permission denied. Why? | 32,936,215 | 4 | 2015-10-04T17:23:13Z | 32,936,225 | 11 | 2015-10-04T17:24:32Z | [
"python",
"pip"
] | I'm trying to upgrade pip on my iMac, but I keep getting a permission denied error. I'm the admin, so I don't know what I've done wrong.
```
iMac:~ me$ pip install --upgrade pip
You are using pip version 6.0.8, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip... | `pip` installations require elevation
```
sudo pip install --upgrade pip
```
Just because you are currently using an admin account doesn't mean the command will run with elevation, unless you specify `sudo` |
Python ASCII codec can't encode character error during write to CSV | 32,939,771 | 2 | 2015-10-05T00:25:04Z | 32,944,575 | 8 | 2015-10-05T08:52:15Z | [
"python",
"csv",
"url",
"utf-8",
"beautifulsoup"
] | I'm not entirely sure what I need to do about this error. I assumed that it had to do with needing to add .encode('utf-8'). But I'm not entirely sure if that's what I need to do, nor where I should apply this.
**The error is:**
```
line 40, in <module>
writer.writerows(list_of_rows)
UnicodeEncodeError: 'ascii' codec ... | Python 2.x CSV library is broken. You have three options. In order of complexity:
1. Use the fixed library <https://github.com/jdunck/python-unicodecsv> (`pip install unicodecsv`). Use as a drop-in replacement - Example:
```
with open("myfile.csv", 'rb') as my_file:
r = unicodecsv.DictReader(my_file,... |
Error installing Pillow on ubuntu 14.04 | 32,942,861 | 36 | 2015-10-05T06:57:06Z | 32,942,958 | 71 | 2015-10-05T07:03:50Z | [
"python",
"pip",
"ubuntu-14.04",
"pillow"
] | I'm trying to install Pillow on Ubuntu 14.04 using this command:
```
pip install Pillow
```
but the installation fails with this error:
```
ValueError: --enable-jpeg requested but jpeg not found, aborting.
``` | The problem was that the package `libjpeg-dev` was not installed. To solve the problem you should do this:
```
sudo apt-get install libjpeg-dev
``` |
Error installing Pillow on ubuntu 14.04 | 32,942,861 | 36 | 2015-10-05T06:57:06Z | 34,965,341 | 16 | 2016-01-23T15:35:56Z | [
"python",
"pip",
"ubuntu-14.04",
"pillow"
] | I'm trying to install Pillow on Ubuntu 14.04 using this command:
```
pip install Pillow
```
but the installation fails with this error:
```
ValueError: --enable-jpeg requested but jpeg not found, aborting.
``` | Make sure Python-development packages are installed, if not then install it using the following commands :
**For Ubuntu**
```
sudo apt-get install python3-dev python3-setuptools
```
**For Fedora**
```
sudo dnf install python-devel
```
After installing the development packages install the following :
**For Ubuntu*... |
How to access weighting of indiviual decision trees in xgboost? | 32,950,607 | 6 | 2015-10-05T14:06:26Z | 34,331,573 | 7 | 2015-12-17T09:57:08Z | [
"python",
"decision-tree",
"xgboost",
"boosting"
] | I'm using xgboost for ranking with
```
param = {'objective':'rank:pairwise', 'booster':'gbtree'}
```
As I understand gradient boosting works by calculating the weighted sum of the learned decision trees. How can I access the weights that are assigned to each learned booster? I wanted to try to post-process the weight... | Each tree is given the same weight `eta` and the overall prediction is the sum of the predictions of each tree, as you say.
You'd perhaps expect that the earlier trees are given more weight than the latter trees but that's not necessary, due to the way the response is updated after every tree. Here's a toy example:
S... |
zip iterators asserting for equal length in python | 32,954,486 | 8 | 2015-10-05T17:32:57Z | 32,954,700 | 10 | 2015-10-05T17:45:03Z | [
"python",
"itertools"
] | I am looking for a nice way to `zip` several iterables raising an exception if the lengths of the iterables are not equal.
In the case where the iterables are lists or have a `len` method this solution is clean and easy:
```
def zip_equal(it1, it2):
if len(it1) != len(it2):
raise ValueError("Lengths of it... | I can a simpler solution, use `itertools.zip_longest()` and raise an exception if the sentinel value used to pad out shorter iterables is present in the tuple produced:
```
from itertools import zip_longest
def zip_equal(*iterables):
sentinel = object()
for combo in zip_longest(*iterables, fillvalue=sentinel)... |
In Python, is there an async equivalent to multiprocessing or concurrent.futures? | 32,955,846 | 23 | 2015-10-05T18:56:44Z | 33,055,158 | 23 | 2015-10-10T14:39:04Z | [
"python",
"asynchronous"
] | Basically, I'm looking for something that offers a parallel map using python3 coroutines as the backend instead of threads or processes. I believe there should be less overhead when performing highly parallel IO work.
Surely something similar already exists, be it in the standard library or some widely used package? | **DISCLAIMER** [PEP 0492](https://www.python.org/dev/peps/pep-0492/) defines only syntax and usage for coroutines. They require an event loop to run, which is most likely [`asyncio`'s event loop](https://docs.python.org/3/library/asyncio-eventloop.html).
### Asynchronous map
I don't know any implementation of `map` b... |
Python pickle error: UnicodeDecodeError | 32,957,708 | 11 | 2015-10-05T20:53:53Z | 32,957,860 | 10 | 2015-10-05T21:03:51Z | [
"python",
"pickle",
"textblob"
] | I'm trying to do some text classification using Textblob. I'm first training the model and serializing it using pickle as shown below.
```
import pickle
from textblob.classifiers import NaiveBayesClassifier
with open('sample.csv', 'r') as fp:
cl = NaiveBayesClassifier(fp, format="csv")
f = open('sample_classifi... | By choosing to `open` the file in mode `wb`, you are choosing to write in raw binary. There is no character encoding being applied.
Thus to read this file, you should simply `open` in mode `rb`. |
Select rows with alphabet characters only | 32,959,463 | 4 | 2015-10-05T23:28:15Z | 32,959,553 | 10 | 2015-10-05T23:40:08Z | [
"python",
"regex",
"alphabet"
] | My data are in the following format:
```
data = [['@datumbox', '#machinelearning'],
['@datumbox', '#textanalysis'],
['@things_internet', '#iot'],
['@things_internet', '#h...'],
['@custmrcom', '#analytics123'],
['@custmrcom', '#strategy...123'],
['@custmrcom', '#1knowledgetweet'],
['@tamaradull', '#@bigbrother']... | Use a list comprehension with a condition:
```
newdata = [x for x in data if x[1][1:].isalpha()]
print newdata
```
Gives the output
```
[['@datumbox', '#machinelearning'], ['@datumbox', '#textanalysis'], ['@things_internet', '#iot']]
``` |
How to return a specific point after an error in 'while' loop | 32,961,271 | 13 | 2015-10-06T03:33:59Z | 32,963,059 | 8 | 2015-10-06T06:23:09Z | [
"python",
"loops",
"python-3.x",
"while-loop",
"continue"
] | I'm trying to write a program that include a `while` loop, in this loop I have an error message if something goes wrong. It's kinda like this;
```
while True:
questionx = input("....")
if x =="SomethingWrongabout questionX":
print ("Something went wrong.")
continue
other codes...
ques... | [EDIT from generator to function]
You can try a function:
```
def check_answer(question, answer):
while True:
current_answer = input(question)
if current_answer == answer:
break
print "Something wrong with question {}".format(question)
return current_answer
answerX = check... |
Change the number of processes to spawn depending on the CPU usage in Python | 32,963,814 | 2 | 2015-10-06T07:09:32Z | 32,964,021 | 7 | 2015-10-06T07:21:29Z | [
"python",
"multiprocessing",
"python-3.4"
] | I want to change the number of processes to spawn depending on the CPU usage in python.
Suppose the CPU in my laptop comes with 8 cores and currently 3 cores are fully used, which means maximum of 5 cores are available. Then I want my python program to spawn 5 processes on runtime.
Is there any way to achieve this in P... | You can get the number of cores using
```
import multiprocessing
cores = multiprocessing.cpu_count()
```
and to get the current load average,
```
import os
loadavg = os.getloadavg()[0]
```
You can use these to determine your number of spawned processes. |
Under the hoods what's the difference between subclassing the user and creating a one to one field? | 32,974,687 | 5 | 2015-10-06T16:11:37Z | 32,974,984 | 9 | 2015-10-06T16:26:22Z | [
"python",
"django"
] | I want to implement users in my system. I know that Django already has an authentication system, and I've been reading the documentation. But I don't know yet the difference between
```
from django.contrib.auth.models import User
class Profile(User):
# others fields
```
And
```
from django.contrib.auth.models i... | Your first example is [multi-table inheritance](https://docs.djangoproject.com/en/1.8/topics/db/models/#multi-table-inheritance).
```
class Profile(User):
```
If you have a `profile`, you can access all the fields on the user model directly (e.g. `profile.username` and `profile.email`). In this case, Django creates a... |
Flask Cache not caching | 32,975,598 | 6 | 2015-10-06T17:02:58Z | 32,975,741 | 10 | 2015-10-06T17:13:10Z | [
"python",
"caching",
"flask",
"flask-cache"
] | I followed a [tutorial](http://brunorocha.org/python/flask/using-flask-cache.html) of Flask-Cache and tried to implement it myself.
Given the following example, why would Flask not cache the time?
```
from flask import Flask
import time
app = Flask(__name__)
cache = Cache(config={'CACHE_TYPE': 'simple'})
cache.init_a... | You are using the `SimpleCache` setup:
```
cache = Cache(config={'CACHE_TYPE': 'simple'})
```
This uses a single global dictionary to hold the cache, and this in turn will only work if you are using a WSGI server that uses *one Python interpreter* to serve all your WSGI requests. If you use a WSGI server that uses se... |
How do I run psycopg2 on El Capitan without hitting a libssl error | 32,978,365 | 13 | 2015-10-06T19:43:51Z | 33,015,245 | 14 | 2015-10-08T12:02:56Z | [
"python",
"psycopg2",
"osx-elcapitan",
"libssl"
] | I've got a python django dev setup on my mac and have just upgraded to El Capitan.
I've got psycopg2 installed in a virtualenv but when I run my server I get the following error -
```
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/aidan/Environments/supernova/lib/python2.7/s... | I tried the following:
I have brew installed on my machine. Running `$ brew doctor` gave me a suggestion to do the following:
`$ sudo chown -R $(whoami):admin /usr/local`
Once this was done, I re-installed `psycopg2` and performed the following:
```
$ sudo ln -s /Library/PostgreSQL/9.3/lib/libssl.1.0.0.dylib /usr/l... |
How do I run psycopg2 on El Capitan without hitting a libssl error | 32,978,365 | 13 | 2015-10-06T19:43:51Z | 33,385,275 | 14 | 2015-10-28T07:31:37Z | [
"python",
"psycopg2",
"osx-elcapitan",
"libssl"
] | I've got a python django dev setup on my mac and have just upgraded to El Capitan.
I've got psycopg2 installed in a virtualenv but when I run my server I get the following error -
```
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/aidan/Environments/supernova/lib/python2.7/s... | The reason is indeed psycopg2 using relative paths to a few PostgreSQL libraries. To fix it I used
```
sudo install_name_tool -change libpq.5.dylib /Library/PostgreSQL/9.4/lib/libpq.5.dylib /Library/Python/2.7/site-packages/psycopg2/_psycopg.so
sudo install_name_tool -change libcrypto.1.0.0.dylib /Library/PostgreSQL/9... |
Inheriting a patched class | 32,981,141 | 8 | 2015-10-06T22:58:02Z | 32,981,306 | 7 | 2015-10-06T23:16:17Z | [
"python",
"python-2.7",
"python-unittest",
"python-mock"
] | I have a base class extending unittest.TestCase, and I want to patch that base class, such that classes extending this base class will have the patches applied as well.
Code Example:
```
@patch("some.core.function", mocked_method)
class BaseTest(unittest.TestCase):
#methods
pass
class TestFunctions(BaseT... | You probably want a metaclass here: a metaclass simply defines how a class is created.
By default, all classes are created using Python's built-in class `type`:
```
>>> class Foo:
... pass
...
>>> type(Foo)
<class 'type'>
>>> isinstance(Foo, type)
True
```
So classes are actually instances of `type`.
Now, we can ... |
Encode and assemble multiple features in PySpark | 32,982,425 | 8 | 2015-10-07T01:40:58Z | 32,984,795 | 11 | 2015-10-07T05:59:07Z | [
"python",
"apache-spark",
"apache-spark-sql"
] | I have a Python class that I'm using to load and process some data in Spark. Among various things I need to do, I'm generating a list of dummy variables derived from various columns in a Spark dataframe. My problem is that I'm not sure how to properly define a User Defined Function to accomplish what I need.
I *do* cu... | Well, you can write an UDF but why would you? There are already quite a few tools designed to handle this category of tasks:
```
from pyspark.sql import Row
from pyspark.mllib.linalg import DenseVector
row = Row("gender", "foo", "bar")
df = sc.parallelize([
row("0", 3.0, DenseVector([0, 2.1, 1.0])),
row("1", 1.0... |
Python requests ImportError: cannot import name HeaderParsingError | 32,986,626 | 4 | 2015-10-07T07:50:54Z | 32,988,728 | 7 | 2015-10-07T09:32:25Z | [
"python",
"python-2.7",
"python-requests",
"urllib3"
] | OS: Mac OS X. When I'm trying to run the code below, I get the error:
> ImportError: cannot import name HeaderParsingError
I've attached traceback below the code.
I've tried to solve this issue for 20 min now, using Google and other stackoverflow. I have tried running:
> pip install urllib3 --upgrade
I've also tri... | `requests` comes with its own copy of the `urllib3` library, in the `requests/packages` subdirectory. It is *this copy* that is somehow broken.
Reinstall `requests` itself; either upgrade (you have at most [version 2.1.0](https://github.com/kennethreitz/requests/releases/tag/v2.1.0), given the `from .packages import c... |
Comparing values in two lists in Python | 32,996,293 | 6 | 2015-10-07T15:25:48Z | 32,996,311 | 19 | 2015-10-07T15:26:22Z | [
"python",
"list",
"python-2.7",
"list-comprehension"
] | In Python 2.7, I have two lists of integers:
```
x = [1, 3, 2, 0, 2]
y = [1, 2, 2, 3, 1]
```
I want to create a third list which indicates whether each element in `x` and `y` is identical, to yield:
```
z = [1, 0, 1, 0, 0]
```
How can I do this using list comprehension?
My attempt is:
```
z = [i == j for i,j in .... | You are looking for [`zip`](https://docs.python.org/2/library/functions.html#zip)
```
z = [i == j for i,j in zip(x,y)]
```
But you better add [`int`](https://docs.python.org/2/library/functions.html#int) call to get your desired output
```
>>> z = [int(i == j) for i,j in zip(x,y)]
>>> z
[1, 0, 1, 0, 0]
```
else you... |
Are constant computations cached in Python? | 33,000,483 | 13 | 2015-10-07T19:09:05Z | 33,000,595 | 12 | 2015-10-07T19:13:52Z | [
"python"
] | Say I have a function in Python that uses a constant computed float value like 1/3.
```
def div_by_3(x):
return x * (1/3)
```
If I call the function repeatedly, will the value of 1/3 be automatically cached for efficiency? Or do I have to do something manually such as the following?
```
def div_by_3(x, _ONE_THIR... | Find out for yourself! The [dis](https://docs.python.org/3/library/dis.html) module is great for inspecting this sort of stuff:
```
>>> from dis import dis
>>> def div_by_3(x):
... return x * (1/3.)
...
>>> dis(div_by_3)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)... |
Python - re-ordering columns in a csv | 33,001,490 | 3 | 2015-10-07T20:05:28Z | 33,002,011 | 7 | 2015-10-07T20:37:21Z | [
"python",
"csv",
"order"
] | I have a bunch of csv files with the same columns but in different order. We are trying to upload them with SQL\*Plus but we need the columns with a fixed column arrange.
Example
required order: A B C D E F
csv file: A C D E B (sometimes a column is not in the csv because it is not available)
is it achievable with ... | You can use the [csv module](https://docs.python.org/2/library/csv.html) to read, reorder, and then and write your file.
**Sample File:**
```
$ cat file.csv
A,B,C,D,E
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
```
**Code**
```
import csv
with open('file.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
# output ... |
Cassandra cqlsh "unable to connect to any servers" | 33,002,404 | 11 | 2015-10-07T21:05:35Z | 36,380,659 | 20 | 2016-04-03T01:28:53Z | [
"python",
"cassandra"
] | I get the following message when executing cqlsh.bat on the command line
```
Connection error: ('Unable to connect to any servers', {'127.0.0.1': ProtocolError("cql_version '3.3.0' is not supported by remote (w/ native protocol). Supported versions: [u'3.2.0']",)})
```
I'm running Python version 2.7.10 along with Cas... | You can force cqlsh to use a specific cql version using the flag
> --cqlversion="#.#.#"
Example cqlsh usage (and key/values):
```
cqlsh 12.34.56.78 1234 -u username -p password --cqlversion="3.2.0"
cqlsh (IP ADDR) (PORT) (DB_USERN) (DB_PASS) (VER)
``` |
TypeError: a bytes-like object is required, not 'str' | 33,003,498 | 9 | 2015-10-07T22:29:22Z | 34,313,671 | 13 | 2015-12-16T13:44:36Z | [
"python",
"sockets"
] | ```
from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print (modifiedMessage)
clientSocket.close()
```... | This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with `sendto` command.
```
clientSocket.sendto(message.encode(),(serverName, serverPort))
``... |
How can i count occurrence of each word in document using Dictionary comprehension | 33,005,949 | 15 | 2015-10-08T03:11:48Z | 33,006,265 | 12 | 2015-10-08T03:48:07Z | [
"python",
"list",
"python-2.7",
"dictionary",
"dictionary-comprehension"
] | I have a list of lists in python full of texts. It is like set words from each document. So for every document i have a list and then on list for all documents.
All the list contains only unique words. **My purpose is to count occurrence of each word in the complete document**. I am able to do this successfully using ... | Like explained in the other answers, the issue is that dictionary comprehension creates a new dictionary, so you don't get reference to that new dictionary until after it has been created. You cannot do dictionary comprehension for what you are doing.
Given that, what you are doing is trying to re-implement what is al... |
OneHotEncoder with string categorical values | 33,008,644 | 4 | 2015-10-08T06:54:33Z | 33,010,943 | 7 | 2015-10-08T08:50:08Z | [
"python",
"scikit-learn"
] | I have the following numpy matrix:
```
M = [
['a', 5, 0.2, ''],
['a', 2, 1.3, 'as'],
['b', 1, 2.3, 'as'],
]
M = np.array(M)
```
I would like to encode categorical values (`'a', 'b', '', 'as'`). I tried to encode it using [OneHotEncoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessin... | You can use `DictVectorizer`:
```
from sklearn.feature_extraction import DictVectorizer
import pandas as pd
dv = DictVectorizer(sparse=False)
df = pd.DataFrame(M).convert_objects(convert_numeric=True)
dv.fit_transform(df.to_dict(orient='records'))
array([[ 5. , 0.2, 1. , 0. , 1. , 0. ],
[ 2. , 1.3, 1.... |
Gevent is in an unsupported or invalid wheel | 33,009,545 | 3 | 2015-10-08T07:41:04Z | 33,010,122 | 11 | 2015-10-08T08:09:12Z | [
"python",
"osx",
"gevent",
"osx-elcapitan"
] | I try on my osX (el capitan) to install Odoo.
Then i've download the package and when I try to install the 3rf party lib with `pip install -r requirements.txt`, it gives me:
```
gevent is in an unsupported or invalid wheel
```
Any idea ?
Xcode is installed, the command line tools too. | Impossible to install gevent via pip then according to the official doc, i've used:
```
pip install cython git+git://github.com/gevent/gevent.git#egg=gevent
```
and it works |
Spark RDD - Mapping with extra arguments | 33,019,420 | 7 | 2015-10-08T14:59:55Z | 33,020,269 | 13 | 2015-10-08T15:40:30Z | [
"python",
"apache-spark",
"pyspark",
"rdd"
] | Is it possible to pass extra arguments to the mapping function in pySpark?
Specifically, I have the following code recipe:
```
raw_data_rdd = sc.textFile("data.json", use_unicode=True)
json_data_rdd = raw_data_rdd.map(lambda line: json.loads(line))
mapped_rdd = json_data_rdd.flatMap(processDataLine)
```
The function ... | 1. You can use an anonymous function either directly in a `flatMap`
```
json_data_rdd.flatMap(lambda j: processDataLine(j, arg1, arg2))
```
or to curry `processDataLine`
```
f = lambda j: processDataLine(dataline, arg1, arg2)
json_data_rdd.flatMap(f)
```
2. You can generate `processDataLine` ... |
How to properly round up half float numbers in Python? | 33,019,698 | 3 | 2015-10-08T15:11:43Z | 33,019,948 | 7 | 2015-10-08T15:24:29Z | [
"python",
"python-3.x",
"floating-point",
"rounding",
"precision"
] | I am facing a strange behavior of the `round()` function:
```
for i in range(1, 15, 2):
n = i / 2
print(n, "=>", round(n))
```
This code prints:
```
0.5 => 0
1.5 => 2
2.5 => 2
3.5 => 4
4.5 => 4
5.5 => 6
6.5 => 6
```
I expected the floating values to be always rounded up, but instead, it is rounded to the ne... | The [*Numeric Types* section](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex) documents this behaviour explicitly:
> `round(x[, n])`
> *x* rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
Note the *rounding half to even*. This is also called *bankers ro... |
built-in max heap API in Python | 33,024,215 | 11 | 2015-10-08T19:19:14Z | 33,062,490 | 13 | 2015-10-11T07:14:06Z | [
"python",
"algorithm",
"queue",
"priority-queue"
] | Default heapq is min queue implementation and wondering if there is an option for max queue? Thanks.
I tried the solution using \_heapify\_max for max heap, but how to handle dynamically push/pop element? It seems \_heapify\_max could only be used during initialization time.
```
import heapq
def heapsort(iterable):
... | In the past I have simply used [sortedcontainers](https://pypi.python.org/pypi/sortedcontainers)'s `SortedList` for this, as:
```
> a = SortedList()
> a.add(3)
> a.add(2)
> a.add(1)
> a.pop()
3
```
It's not a heap, but it's fast and works directly as required.
If you absolutely need it to be a heap, you could make a... |
Raw unicode literal that is valid in Python 2 and Python 3? | 33,027,281 | 4 | 2015-10-08T22:56:30Z | 33,027,349 | 7 | 2015-10-08T23:02:39Z | [
"python",
"python-3.x",
"unicode",
"python-2.x"
] | Apparently the `ur""` syntax has been disabled in Python 3. However, I need it! *"Why?"*, you may ask. Well, I need the `u` prefix because it is a unicode string and my code needs to work on Python 2. As for the `r` prefix, maybe it's not essential, but the markup format I'm using requires a lot of backslashes and it w... | Why don't you just use raw string literal (`r'....'`), you don't need to specify `u` because in Python 3, strings are unicode strings.
```
>>> tamil_letter_ma = "\u0bae"
>>> marked_text = r"\a%s\bthe Tamil\cletter\dMa\e" % tamil_letter_ma
>>> marked_text
'\\aà®®\\bthe Tamil\\cletter\\dMa\\e'
```
To make it also work ... |
Why doesn't my while loop stop? | 33,027,597 | 5 | 2015-10-08T23:29:33Z | 33,027,635 | 7 | 2015-10-08T23:34:26Z | [
"python",
"while-loop"
] | I've been reading other posts and couldn't figure it out. No matter what I enter at the end of this repeat it always repeats the loop. I've tried `while(repeat != "Quit" or repeat != "quit" or repeat != "b" or repeat != "B" or repeat != "no" or repeat != "No"):`but it still never worked. I don't know what else to try. ... | Well, let's take a look at that condition:
```
while repeat != "Quit" or repeat != "quit"
```
Think about it. No matter what the value of `repeat` is, **this is always true**. `repeat` will always be different from `"Quit"` **OR FROM** `"quit"`. If it's the one, it won't be the other.
You need it to be different fro... |
Prevent string being printed python | 33,028,298 | 7 | 2015-10-09T01:00:19Z | 33,028,363 | 8 | 2015-10-09T01:08:29Z | [
"python",
"io",
"output",
"stdout"
] | I'm using some library and I can't edit its source. There is a function in the library that I have to call, and when I call it, it makes this file that I want; however, at the same time, it prints this warning to the screen hundreds of times. The warning is always the same.
> Warning during export : no corresponding G... | I would use something like...
**3.x**
```
import sys
from _io import TextIOWrapper
class StdoutFilter(TextIOWrapper):
def __init__(self, stdout):
super().__init__(stdout)
self.stdout = stdout
def write(self, output):
if output != "don't write this":
self.stdout.write(out... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.