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
Check whether a list starts with the elements of another list
32,149,202
3
2015-08-21T21:02:35Z
32,149,245
9
2015-08-21T21:05:47Z
[ "python", "list" ]
What is the easiest (most pythonic way) to check, if the beginning of the list are exactly the elements of another list? Consider the following examples: ``` li = [1,4,5,3,2,8] #Should return true startsWithSublist(li, [1,4,5]) #Should return false startsWithSublist(list2, [1,4,3]) #Should also return false, althou...
Use list slicing: ``` >>> li = [1,4,5,3,2,8] >>> sublist = [1,4,5] >>> li[:len(sublist)] == sublist True ```
WxPython: PyInstaller fails with No module named _core_
32,154,849
7
2015-08-22T10:05:36Z
32,334,301
7
2015-09-01T14:30:34Z
[ "python", "ubuntu", "wxpython", "ubuntu-14.04", "pyinstaller" ]
I am converting my wxpython (3.0.2.0) application to binaries using PyInstaller. The binaries work fine when built and executed on Ubuntu 12.04. However if I build on Ubuntu 14.04, I get the following error. (The application works when I launch the python script directly i.e. python my\_application.py even in Ubuntu 14...
Fundamentally the problem is with the PyInstaller version - you need to be on the `develop` version. This issue has been seen and is documented on a [PyInstaller Github issue](https://github.com/pyinstaller/pyinstaller/issues/1300). To install the latest version and rectify - at the command prompt type: ``` $ pip ins...
How to convert string like '001100' to numpy.array([0,0,1,1,0,0]) quickly?
32,155,011
4
2015-08-22T10:23:55Z
32,155,109
7
2015-08-22T10:35:14Z
[ "python", "numpy", "types", "format", "type-conversion" ]
I have a string consists of 0 and 1, like `'00101'`. And I want to convert it to numpy array `numpy.array([0,0,1,0,1]`. I am using `for` loop like: ``` import numpy as np X = np.zeros((1,5),int) S = '00101' for i in xrange(5): X[0][i] = int(S[i]) ``` But since I have many strings and the length of each string is...
map should be a bit faster than a list comp: ``` import numpy as np arr = np.array(map(int,'00101')) ``` Some timings show it is on a string of 1024 chars: ``` In [12]: timeit np.array([int(c) for c in s]) 1000 loops, best of 3: 422 µs per loop In [13]: timeit np.array(map(int,s)) 1000 loops, best of 3: 389 µs ...
Python Bokeh: remove toolbar from chart
32,158,939
8
2015-08-22T17:35:38Z
32,679,286
11
2015-09-20T12:13:55Z
[ "python", "bokeh" ]
I don't seem to be able to remove the toolbar from a bokeh Bar chart. Despite setting the *tools* argument to *None* (or *False* or *''*) I always end up with the bokeh logo and a grey line, e.g. with this code: ``` from bokeh.charts import Bar, output_file, show # prepare some data data = {"y": [6, 7, 2, 4, 5], "z":...
If you want to remove the logo and the toolbar you can do: ``` p.logo = None p.toolbar_location = None ``` Hope this resolves your problem
Django - CSS stops working when I change urls
32,160,561
5
2015-08-22T20:41:01Z
32,160,637
7
2015-08-22T20:49:14Z
[ "python", "css", "django", "url" ]
So I ran into a problem on my website where I then created two separate html pages. I then edited the urls.py so the urls would be different for the 2 pages but the css stops working if I do this. My code is below and I will explain more thoroughly after. part of my head.html ``` <!-- Bootstrap core CSS --> <link h...
The URL for static is going up two directories; but your path is now three directories deep, so the URL is wrong. You shouldn't be using relative URLs for your static links. Instead, use absolute ones: ``` <link href="/static/textchange/index.css" rel="stylesheet"> ``` even better, use the `{% static %}` tag which t...
How can I efficiently read and write files that are too large to fit in memory?
32,162,295
17
2015-08-23T01:15:43Z
32,166,257
7
2015-08-23T11:40:28Z
[ "python", "numpy", "memory-management" ]
I am trying to calculate the cosine similarity of 100,000 vectors, and each of these vectors has 200,000 dimensions. From reading other questions I know that [memmap](http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html), PyTables and h5py are my best bets for handling this kind of data, and I am curr...
Memory maps are exactly what the name says: mappings of (virtual) disk sectors into memory pages. The memory is managed by the operating system on demand. If there is enough memory, the system keeps parts of the files in memory, maybe filling up the whole memory, if there is not enough left, the system may discard page...
How can I efficiently read and write files that are too large to fit in memory?
32,162,295
17
2015-08-23T01:15:43Z
32,166,493
7
2015-08-23T12:09:57Z
[ "python", "numpy", "memory-management" ]
I am trying to calculate the cosine similarity of 100,000 vectors, and each of these vectors has 200,000 dimensions. From reading other questions I know that [memmap](http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html), PyTables and h5py are my best bets for handling this kind of data, and I am curr...
In terms of memory usage, there's nothing particularly wrong with what you're doing at the moment. Memmapped arrays are handled at the level of the OS - data to be written is usually held in a temporary buffer, and only committed to disk when the OS deems it necessary. Your OS should never allow you to run out of physi...
Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied
32,167,418
3
2015-08-23T13:57:25Z
32,199,615
9
2015-08-25T08:53:44Z
[ "python", "pip" ]
I get the following error when using PIP to either install new packages or even upgrade pip itself to the latest version. I am running pip on a windows 8.1 machine with Python 3.4. It seems there is either a problem with deleting some of the Temp files created when pip tries to uninstall the previous version or the mes...
For those that may run into the same issue: Run the command prompt as administrator. Having administrator permissions in the account is not always enough. In Windows, things can be run as administrator by right-clicking the executable and selecting "Run as Administrator". So, type "cmd" to the Start menu, right click ...
How to create a pandas DatetimeIndex with year as frequency?
32,168,848
5
2015-08-23T16:25:01Z
32,168,932
11
2015-08-23T16:34:16Z
[ "python", "python-3.x", "pandas", "date-range" ]
Using the `pandas.date_range(startdate, periods=n, freq=f)` function you can create a range of pandas `Timestamp` objects where the `freq` optional paramter denotes the frequency (second, minute, hour, day...) in the range. The [documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.htm...
# Annual indexing to the beginning or end of the year Frequency is `freq='A'` for end of year frequency, `'AS'` for start of year. Check the [aliases in the documentation](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases). eg. `pd.date_range(start=pd.datetime(2000, 1, 1), periods=4, freq='A'...
copy 2D array into 3rd dimension, N times (Python)
32,171,917
4
2015-08-23T21:51:14Z
32,171,971
7
2015-08-23T21:58:39Z
[ "python", "arrays", "numpy" ]
I'm looking for a succinct way to copy a numpy 2D array into a third dimension; that is, for example, if I had such a matrix: ``` [[1,2];[1,2]] ``` I could make it into a 3D matrix with N such copies in a new dimension, something like this for N=3: ``` [[[1,2];[1,2]];[[1,2];[1,2]];[[1,2];[1,2]]] ``` Now I know you ...
Probably the cleanest way is to use [`np.repeat`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html): ``` a = np.array([[1, 2], [1, 2]]) print(a.shape) # (2, 2) # indexing with np.newaxis inserts a new 3rd dimension, which we then repeat the # array along, (you can achieve the same effect by inde...
How can I retrieve the current seed of NumPy's random number generator?
32,172,054
7
2015-08-23T22:10:14Z
32,172,816
8
2015-08-24T00:06:06Z
[ "python", "numpy", "random", "random-seed", "mersenne-twister" ]
The following imports NumPy and sets the seed. ``` import numpy as np np.random.seed(42) ``` However, I'm not interested in setting the seed but more in reading it. `random.get_state()` does not seem to contain the seed. The [documentation](http://docs.scipy.org/doc/numpy/reference/routines.random.html) doesn't show ...
The short answer is that you simply can't (at least not in general). The [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) RNG used by numpy has 219937-1 possible internal states, whereas a single 64 bit integer has only 264 possible values. It's therefore impossible to map every RNG state to a unique...
Should python imports take this long?
32,173,861
3
2015-08-24T02:54:12Z
32,173,887
7
2015-08-24T02:57:50Z
[ "python", "time", "import" ]
For the following command ``` time python test.py ``` on this script, test.py ``` import numpy as np from math import * import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm from scipy import stats ``` I get the output: ``` real 0m1.933s user 0m1.322s sys 0m0.2...
Some modules initialize when you use them, while others initialize everything once you start it up. Matplotlib is one of those modules. Since matplotlib is a huge package that includes a whole lot of functionality, I'm not surprised that it takes this long, although it can get annoying. So, in answer to your question...
Hard coded variables in python function
32,179,653
4
2015-08-24T10:07:51Z
32,179,672
10
2015-08-24T10:09:00Z
[ "python", "constants", "python-internals" ]
Sometimes, some values/strings are hard-coded in functions. For example in the following function, I define a "constant" comparing string and check against it. ``` def foo(s): c_string = "hello" if s == c_string: return True return False ``` Without discussing too much about why it's bad to do thi...
Because the string is immutable (as would a tuple), it is stored with the bytecode object for the function. It is loaded by a very simple and fast index lookup. This is actually *faster* than a global lookup. You can see this in a disassembly of the bytecode, using the [`dis.dis()` function](https://docs.python.org/2/...
Making Python run a few lines before my script
32,184,440
7
2015-08-24T14:10:04Z
32,236,228
7
2015-08-26T20:34:51Z
[ "python", "python-import" ]
I need to run a script `foo.py`, but I need to also insert some debugging lines to run before the code in `foo.py`. Currently I just put those lines in `foo.py` and I'm careful not to commit that to Git, but I don't like this solution. What I want is a separate file `bar.py` that I don't commit to Git. Then I want to ...
You can use [`execfile()`](https://docs.python.org/2/library/functions.html#execfile) if the file is `.py` and [uncompyle2](https://github.com/wibiti/uncompyle2/blob/master/scripts/uncompyle2) if the file is `.pyc`. Let's say you have your file structure like: ``` test|-- foo.py |-- bar |--bar.py ``` **...
Break // in x axis of matplotlib
32,185,411
2
2015-08-24T14:56:23Z
32,186,074
7
2015-08-24T15:28:03Z
[ "python", "matplotlib", "plot" ]
Best way to describe what I want to achieve is using my own image: [![enter image description here](http://i.stack.imgur.com/REeKv.png)](http://i.stack.imgur.com/REeKv.png) Now I have a lot of dead space in the spectra plot, especially between 5200 and 6300. My question is quite simple, how would I add in a nice litt...
You could adapt [the matplotlib example](http://matplotlib.org/examples/pylab_examples/broken_axis.html) for a break in the x-axis directly: ``` """ Broken axis example, where the x-axis will have a portion cut out. """ import matplotlib.pylab as plt import numpy as np x = np.linspace(0,10,100) x[75:] = np.linspace(...
from matplotlib.backends import _tkagg ImportError: cannot import name _tkagg
32,188,180
9
2015-08-24T17:29:33Z
34,030,409
22
2015-12-01T21:21:35Z
[ "python", "matplotlib", "pip", "virtualenv", "tk" ]
While trying to run [this](http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html) example to test how matplotlib works with Tkinter, I am getting the error: ``` (env)fieldsofgold@fieldsofgold-VirtualBox:~/new$ python test.py Traceback (most recent call last): File "test.py", line 7, in <module> fro...
I just ran into this (Ubuntu 15.10 but same idea) and fixed it by: ``` sudo apt-get install tk-dev pip uninstall -y matplotlib pip --no-cache-dir install -U matplotlib ``` I think the third step was the critical one; if the cache is permitted then `pip` appeared to be just using the previously-built installation of `...
Getting the indices of several elements in a NumPy array at once
32,191,029
3
2015-08-24T20:18:56Z
32,191,125
9
2015-08-24T20:24:33Z
[ "python", "arrays", "numpy" ]
Is there any way to get the indices of several elements in a NumPy array at once? E.g. ``` import numpy as np a = np.array([1, 2, 4]) b = np.array([1, 2, 3, 10, 4]) ``` I would like to find the index of each element of `a` in `b`, namely: `[0,1,4]`. I find the solution I am using a bit verbose: ``` import numpy as...
You could use [`in1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html) and [`nonzero`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html) (or `where` for that matter): ``` >>> np.in1d(b, a).nonzero()[0] array([0, 1, 4]) ``` This works fine for your example arrays, but in gene...
Python AND operator on two boolean lists - how?
32,192,163
8
2015-08-24T21:38:24Z
32,192,248
10
2015-08-24T21:44:45Z
[ "python", "list", "boolean", "operator-keyword" ]
I have two boolean lists, e.g., ``` x=[True,True,False,False] y=[True,False,True,False] ``` I want to AND these lists together, with the expected output: ``` xy=[True,False,False,False] ``` I thought that expression `x and y` would work, but came to discover that it does not: in fact, `(x and y) != (y and x)` Outp...
`and` simply returns either the first or the second operand, based on their truth value. If the first operand is considered false, it is returned, otherwise the other operand is returned. Lists are considered *true* when *not empty*, so both lists are considered true. Their contents *don't play a role here*. Because ...
Error with Sklearn Random Forest Regressor
32,198,355
3
2015-08-25T07:49:37Z
32,198,885
7
2015-08-25T08:17:01Z
[ "python", "numpy", "machine-learning", "scikit-learn", "random-forest" ]
When trying to fit a Random Forest Regressor model with y data that looks like this: ``` [ 0.00000000e+00 1.36094276e+02 4.46608221e+03 8.72660888e+03 1.31375786e+04 1.73580193e+04 2.29420671e+04 3.12216341e+04 4.11395711e+04 5.07972062e+04 6.14904935e+04 7.34275322e+04 7.87333933e+04 8.4...
The shape of `X` should be `[n_samples, n_features]`, you can transform `X` by ``` X = X[:, None] ```
How to do while() the "pythonic way"
32,199,150
4
2015-08-25T08:30:52Z
32,199,207
11
2015-08-25T08:33:34Z
[ "python" ]
I want to do this: ``` from django.db import connection cursor = connection.cursor() cursor.execute("PRAGMA table_info(ventegroupee)") while row = cursor.fetchone(): print(row) ``` I get this: ``` File "<input>", line 1 while row = cursor.fetchone(): ^ SyntaxError: invalid syntax ``` What i...
You don't have to use `while` loop at all, because cursors are iterable: ``` for row in cursor: print(row) ``` From the "Connections and cursors" section of [Django documentation](https://docs.djangoproject.com/en/1.8/topics/db/sql/#connections-and-cursors): > *connection* and *cursor* mostly implement the stand...
Finding the "best" combination for a set
32,202,797
17
2015-08-25T11:27:19Z
32,360,908
7
2015-09-02T18:48:53Z
[ "python", "algorithm", "statistics", "combinations", "linguistics" ]
I have a set, `sentences`, which contains sentences from the English language in the form of strings. I wish to create a subset of `sentences`, `sentences2`, which contains sentences containing only 20 unique words. Of course, there are many, many such subsets, but I'm looking for the "best" one and by "best" I mean th...
**Disclaimer:** You have not specified data characteristics, so my answer will assume that it is not too large(more than 1,000,000 sentences, each at most 1,000). Also Description is a bit complicated and I might have not understood the problem fully. **Solution:** Instead of focusing on different combinations, why ...
how to determine the minimal value in a column of a list of tuples in python
32,205,413
3
2015-08-25T13:31:49Z
32,205,472
10
2015-08-25T13:34:05Z
[ "python" ]
I have the following list of tuples ``` lstoflsts = [(1.2, 2.1, 3.1), (0.9, 3.4, 7.4), (2.3, 1.1, 5.1)] ``` I would like to get the minimum value of the 2nd column (which is *1.1* based on above example). I tried playing around with `min(listoflists)` without success. any suggestions how t...
Simplest way, you can use `min`, ``` >>> lstoflsts = [(1.2, 2.1, 3.1), ... (0.9, 3.4, 7.4), ... (2.3, 1.1, 5.1)] >>> >>> min(lstoflsts, key=lambda x: x[1]) (2.3, 1.1, 5.1) >>> min(lstoflsts, key=lambda x: x[1])[1] 1.1 ```
Is there a multi-dimensional version of arange/linspace in numpy?
32,208,359
5
2015-08-25T15:41:25Z
32,208,788
9
2015-08-25T16:02:16Z
[ "python", "numpy" ]
I would like a list of 2d numpy arrays (x,y) , where each x is in {-5, -4.5, -4, -3.5, ..., 3.5, 4, 4.5, 5} and the same for y. I could do ``` x = np.arange(-5, 5.1, 0.5) y = np.arange(-5, 5.1, 0.5) ``` and then iterate through all possible pairs, but I'm sure there's a nicer way... I would like something back that...
You can use [`np.mgrid`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mgrid.html) for this, it's often more convenient than [`np.meshgrid`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html) because it creates the arrays in one step: ``` import numpy as np X,Y = np.mgrid[-5:5.1:0.5, ...
Why can a floating point dictionary key overwrite an integer key with the same value?
32,209,155
27
2015-08-25T16:22:07Z
32,209,354
13
2015-08-25T16:32:05Z
[ "python", "dictionary", "floating-point", "int" ]
I'm working through <http://www.mypythonquiz.com>, and [question #45](http://www.mypythonquiz.com/question.php?qid=255) asks for the output of the following code: ``` confusion = {} confusion[1] = 1 confusion['1'] = 2 confusion[1.0] = 4 sum = 0 for k in confusion: sum += confusion[k] print sum ``` The output is...
You should consider that the `dict` aims at storing data depending on the logical numeric value, not on how you represented it. The difference between `int`s and `float`s is indeed just an implementation detail and not conceptual. Ideally the only number type should be an arbitrary precision number with unbounded accu...
Why can a floating point dictionary key overwrite an integer key with the same value?
32,209,155
27
2015-08-25T16:22:07Z
32,211,042
24
2015-08-25T18:04:15Z
[ "python", "dictionary", "floating-point", "int" ]
I'm working through <http://www.mypythonquiz.com>, and [question #45](http://www.mypythonquiz.com/question.php?qid=255) asks for the output of the following code: ``` confusion = {} confusion[1] = 1 confusion['1'] = 2 confusion[1.0] = 4 sum = 0 for k in confusion: sum += confusion[k] print sum ``` The output is...
First of all: the behaviour is documented explicitly in the docs for the [hash](https://docs.python.org/3.5/library/functions.html#hash) function: > **`hash(object)`** > > Return the hash value of the object (if it has one). Hash values are > integers. They are used to quickly compare dictionary keys during a > dictio...
Can I add arguments to python code when I submit spark job?
32,217,160
4
2015-08-26T02:43:08Z
32,217,235
9
2015-08-26T02:50:08Z
[ "python", "apache-spark" ]
I'm trying to use `spark-submit` to execute my python code in spark cluster. Generally we run `spar-submit` with python code like below. ``` # Run a Python application on a cluster ./bin/spark-submit \ --master spark://207.184.161.138:7077 \ my_python_code.py \ 1000 ``` But I wanna run `my_python_code.py`by pa...
**Yes**: Put this in a file called args.py ``` #import sys print sys.argv ``` If you run ``` spark-submit args.py a b c d e ``` You will see: ``` ['/spark/args.py', 'a', 'b', 'c', 'd', 'e'] ```
How to know which version of PyMongo is running on my project
32,221,694
3
2015-08-26T08:34:48Z
32,221,874
7
2015-08-26T08:43:42Z
[ "python", "mongodb", "pymongo" ]
I'm developing a python project, in the requirements file I have three different types of PyMongo ``` Flask-PyMongo==0.3.1 pymongo==2.7 flask-mongoengine==0.7.1 ``` How can I define which version I'm using?
If you got `pip` installed, you can try this in terminal: ``` $ pip freeze | grep pymongo pymongo==3.0.2 ```
Computing mean and variance of numpy memmap Infinity output
32,227,847
2
2015-08-26T13:21:16Z
32,229,510
7
2015-08-26T14:33:10Z
[ "python", "numpy", "memory" ]
Creation of memmap array: ``` out = np.memmap('my_array.mmap', dtype=np.float16, mode='w+', shape=(num_axis1, num_axis2)) for index,row in enumerate(temp_train_data): __,cd_i=pywt.dwt(X_train[index:index+1001].ravel(),'haar') out[index]=(cd_i) (Pdb) out.shape (1421392L, 3504L) ``` Now, I simply fe...
[According to Wikipedia](https://en.wikipedia.org/wiki/Half-precision_floating-point_format#Precision_limitations_on_integer_values), the `float16` data type can't handle integers larger than 65520. The sum of all the values in your collection is probably larger than that, so it gets rounded up to infinity when calcula...
Django ImportError: No module named middleware
32,230,490
4
2015-08-26T15:17:16Z
32,232,787
8
2015-08-26T17:16:24Z
[ "python", "django", "django-settings", "django-middleware" ]
I am using Django version 1.8 and python 2.7. I am getting the following error after running my project. ``` Traceback (most recent call last): File "C:\Python27\lib\wsgiref\handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "C:\Python27\lib\site-packages\django\con...
Open up a python shell by running `python manage.py shell` in your project directory. Run the following commands **one at a time** in the python shell: ``` >>> from corsheaders.middleware import CorsMiddleware >>> from oauth2_provider.middleware import OAuth2TokenMiddleware >>> from django.contrib.auth.middleware imp...
What makes an element eligible for a set membership test in Python?
32,232,182
5
2015-08-26T16:42:30Z
32,232,229
7
2015-08-26T16:46:00Z
[ "python", "collections", "set" ]
I would like to understand which items can be tested for `set` membership in Python. In general, set membership testing works like `list` membership testing in Python. ``` >>> 1 in {1,2,3} True >>> 0 in {1,2,3} False >>> ``` However, sets are different from lists in that they cannot contain unhashable objects, for ex...
The confusion comes because when you say 'if set in set', I think python is casting the left hand set to a frozenset and then testing that. E.g. ``` >>> f = frozenset({1}) >>> f frozenset([1]) >>> x = {f, 2, 3} >>> {1} in x True ``` However, there is no equivalent to frozenset for a dict, so it cannot convert the dic...
Command prompt can't write letter by letter?
32,233,636
10
2015-08-26T18:04:20Z
32,233,670
10
2015-08-26T18:06:34Z
[ "python", "python-3.x" ]
``` import time def textinput(txt,waittime=0.04): end = len(txt) letters = 0 while end != letters: print(txt[letters], end = '') letters += 1 time.sleep(waittime) textinput('Hello there!') ``` This is basically my function for writing words letter by letter, it works flawlessly on I...
Output is probably buffered, trying flushing it by adding the following line after your print: ``` sys.stdout.flush() ```
Command prompt can't write letter by letter?
32,233,636
10
2015-08-26T18:04:20Z
32,233,850
16
2015-08-26T18:15:47Z
[ "python", "python-3.x" ]
``` import time def textinput(txt,waittime=0.04): end = len(txt) letters = 0 while end != letters: print(txt[letters], end = '') letters += 1 time.sleep(waittime) textinput('Hello there!') ``` This is basically my function for writing words letter by letter, it works flawlessly on I...
You don't need to use `sys`, you just need `flush=True`: ``` def textinput(txt,waittime=0.4): for letter in txt: print(letter, end = '',flush=True) time.sleep(waittime) ``` You can also simply iterate over the string itself.
How to get rows from DF that contain value None in pyspark (spark)
32,236,135
3
2015-08-26T20:28:50Z
32,236,207
7
2015-08-26T20:33:31Z
[ "python", "apache-spark", "pyspark" ]
In below example `df.a == 1` predicate returns correct result but `df.a == None` returns 0 when it should return 1. ``` l = [[1], [1], [2], [2], [None]] df = sc.parallelize(l).toDF(['a']) df # DataFrame[a: bigint] df.collect() # [Row(a=1), Row(a=1), Row(a=2), Row(a=2), Row(a=None)] df.where(df.a == 1).count() ...
You can use [`Column.isNull`](https://spark.apache.org/docs/1.3.1/api/python/pyspark.sql.html#pyspark.sql.Column.isNull) method: ``` df.where(df.a.isNull()).count() ``` On a side note this behavior is what one could expect from a [normal SQL query](http://sqlfiddle.com/#!15/6c1d3/1). Since `NULL` marks *"missing info...
python flask redirect to https from http
32,237,379
2
2015-08-26T21:57:37Z
32,238,093
7
2015-08-26T23:03:19Z
[ "python", "ssl", "flask" ]
I have a website build using python3.4 and flask...I have generated my own self-signed certificate and I am currently testing my website through localhost. I am using the python ssl module along with this flask extension: <https://github.com/kennethreitz/flask-sslify> ``` context = ('my-cert.pem', 'my-key.pem') app =...
To me, it appears you're making it more complicated than it needs to be. Here is the code I use in my views.py script to force user to HTTPS connections: ``` @app.before_request def before_request(): if request.url.startswith('http://'): url = request.url.replace('http://', 'https://', 1) code = 30...
Find the closest date to a given date
32,237,862
2
2015-08-26T22:39:47Z
32,237,949
15
2015-08-26T22:48:51Z
[ "python", "date", "datetime" ]
I have an array of datetime objects, and I would like to find which element in the array is the closest to a given date (e.g `datetime.datetime(2014,12,16)`) [This](http://stackoverflow.com/questions/17249220/getting-the-closest-date-to-a-given-date) post shows how to find the nearest date *which is not before the giv...
``` def nearest(items, pivot): return min(items, key=lambda x: abs(x - pivot)) ``` *Note that this will work for numbers too.*
Why does this Jython loop fail after a single run?
32,239,955
15
2015-08-27T02:58:08Z
32,383,489
7
2015-09-03T19:01:56Z
[ "java", "python", "loops", "exception-handling", "jython" ]
I've got the following code: ``` public static String getVersion() { PythonInterpreter interpreter = new PythonInterpreter(); try { interpreter.exec(IOUtils.toString(new FileReader("./Application Documents/Scripts/Version.py"))); PyObject get_version = interpreter.get("get_latest_version...
The python library `urllib2`, which you use, uses `Netty`. `Netty` has a problem, which is widely known: * [Hopper: java.util.concurrent.RejectedExecutionException: event executor terminated](https://bugs.mojang.com/browse/MC-38028) * [Error recurrent : DefaultPromise Failed to notify a listener. Event loop shut down...
How to rotate x-axis label in Pandas barplot
32,244,019
9
2015-08-27T08:11:34Z
32,244,161
28
2015-08-27T08:18:49Z
[ "python", "pandas", "matplotlib" ]
With the following code: ``` import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]}) df = df[["celltype","s1","s2"]] df.set_index(["celltype"],inplace=True) df.plot(kind='bar',al...
Pass param [`rot=0`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html#pandas.DataFrame.plot) to rotate the xticks: ``` import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,...
How to save a Seaborn plot into a file
32,244,753
20
2015-08-27T08:51:07Z
32,245,025
8
2015-08-27T09:03:19Z
[ "python", "pandas", "matplotlib", "seaborn" ]
I tried the following code (`test_seaborn.py`): ``` import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import seaborn as sns sns.set() df = sns.load_dataset('iris') sns_plot = sns.pairplot(df, hue='species', size=2.5) fig = sns_plot.get_figure() fig.savefig("output.p...
You should just be able to use the `savefig` method of `sns_plot` directly. ``` sns_plot.savefig("output.png") ``` For clarity with your code if you did want to access the matplotlib figure that `sns_plot` resides in then you can get it directly with ``` fig = sns_plot.fig ``` In this case there is no `get_figure` ...
How to save a Seaborn plot into a file
32,244,753
20
2015-08-27T08:51:07Z
32,245,026
24
2015-08-27T09:03:20Z
[ "python", "pandas", "matplotlib", "seaborn" ]
I tried the following code (`test_seaborn.py`): ``` import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import seaborn as sns sns.set() df = sns.load_dataset('iris') sns_plot = sns.pairplot(df, hue='species', size=2.5) fig = sns_plot.get_figure() fig.savefig("output.p...
Remove the `get_figure` and just use `sns_plot.savefig('output.png')` ``` df = sns.load_dataset('iris') sns_plot = sns.pairplot(df, hue='species', size=2.5) sns_plot.savefig("output.png") ```
Complexity of len() with regard to sets and lists
32,248,882
44
2015-08-27T12:03:42Z
32,249,047
18
2015-08-27T12:11:42Z
[ "python", "python-3.x", "time-complexity", "python-internals" ]
The complexity of `len()` with regards to sets and lists is equally O(1). How come it takes more time to process sets? ``` ~$ python -m timeit "a=[1,2,3,4,5,6,7,8,9,10];len(a)" 10000000 loops, best of 3: 0.168 usec per loop ~$ python -m timeit "a={1,2,3,4,5,6,7,8,9,10};len(a)" 1000000 loops, best of 3: 0.375 usec per ...
The relevant lines are <http://svn.python.org/view/python/trunk/Objects/setobject.c?view=markup#l640> ``` 640 static Py_ssize_t 641 set_len(PyObject *so) 642 { 643 return ((PySetObject *)so)->used; 644 } ``` and <http://svn.python.org/view/python/trunk/Objects/listobject.c?view=markup#l431> `...
Complexity of len() with regard to sets and lists
32,248,882
44
2015-08-27T12:03:42Z
32,249,059
101
2015-08-27T12:12:17Z
[ "python", "python-3.x", "time-complexity", "python-internals" ]
The complexity of `len()` with regards to sets and lists is equally O(1). How come it takes more time to process sets? ``` ~$ python -m timeit "a=[1,2,3,4,5,6,7,8,9,10];len(a)" 10000000 loops, best of 3: 0.168 usec per loop ~$ python -m timeit "a={1,2,3,4,5,6,7,8,9,10};len(a)" 1000000 loops, best of 3: 0.375 usec per ...
**Firstly,** you have not measured the speed of `len()`, you have measured the speed of creating a list/set *together with* the speed of `len()`. Use the `--setup` argument of `timeit`: ``` $ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timei...
Python and functional programming: is there an apply() function?
32,249,197
7
2015-08-27T12:18:39Z
32,249,304
11
2015-08-27T12:23:07Z
[ "python", "functional-programming" ]
Scala has the [`apply()`](http://stackoverflow.com/questions/9737352/what-is-the-apply-function-in-scala) function. I am new to Python and I am wondering how should I write the following one-liner: ``` (part_a, part_b) = (lambda x: re.search(r"(\w+)_(\d+)", x).groups())(input_string) ``` I would feel better with som...
When writing Haskell write Haskell. When writing Python just write Python: ``` part_a, part_b = re.search(r"(\w+)_(\d+)", input_string).groups() ```
Installing iPython: "ImportError cannot import name path"?
32,252,122
23
2015-08-27T14:27:47Z
32,252,578
25
2015-08-27T14:46:53Z
[ "python", "ipython" ]
I'm trying to install IPython. I have run `pip install ipython[notebook]` without any errors, but now I get this: ``` $ ipython notebook Traceback (most recent call last): File "/Users/me/.virtualenvs/.venv/bin/ipython", line 7, in <module> from IPython import start_ipython File "/Users/me/.virtualenvs/.venv/l...
Looks like this is a [known issue](https://github.com/pickleshare/pickleshare/issues/8), caused by a change in the `path.py` package. Reverting to an older version of `path.py` solves this : ``` sudo pip3 install -I path.py==7.7.1 ```
Shortest way to get a value from a dictionary or a default if the key is not present
32,256,997
2
2015-08-27T18:33:12Z
32,257,017
11
2015-08-27T18:34:41Z
[ "python", "dictionary" ]
I am just curious if ``` p = 'padding' in ui and ui['padding'] or 0 ``` is the shortest way (or if there is an even shorter way) of writing ``` if 'padding' in ui: p = ui['padding'] else: p = 0 ``` in Python.
If `ui` is a dictionary, you can even simplify that with the [`dict.get`](https://docs.python.org/3/library/stdtypes.html#dict.get) method, like this ``` p = ui.get('padding', 0) ``` Here, if the key `padding` exists in the dictionary, then the value corresponding to that will be returned. Otherwise, the default valu...
Why is bytearray not a Sequence in Python 2?
32,258,275
12
2015-08-27T19:51:37Z
32,258,443
7
2015-08-27T20:02:38Z
[ "python", "bytearray", "python-internals", "abc" ]
I'm seeing a weird discrepancy in behavior between Python 2 and 3. In Python 3 things seem to work fine: ``` Python 3.5.0rc2 (v3.5.0rc2:cc15d736d860, Aug 25 2015, 04:45:41) [MSC v.1900 32 b it (Intel)] on win32 >>> from collections import Sequence >>> isinstance(bytearray(b"56"), Sequence) True ``` But not in Python...
Abstract classes from `collections` use [`ABCMeta.register(subclass)`](https://docs.python.org/3/library/abc.html#abc.ABCMeta.register) to > Register *subclass* as a “virtual subclass” of this ABC. In Python 3 `issubclass(bytearray, Sequence)` returns `True` because `bytearray` is explicitly registered as a subcl...
what is function(var1)(var2) in python
32,258,881
4
2015-08-27T20:31:10Z
32,258,909
16
2015-08-27T20:32:53Z
[ "python" ]
I have a piece of code I pulled from someone I don't understand: ``` def __init__(self, func): self.func = func wraps(func)(self) ``` I've seen things like `wraps(func)(self)` several times but never seen it explained. How is there a function with parameters and then another `(var)` thing after it? Wh...
Functions are [**first-class objects**](https://en.wikipedia.org/wiki/First-class_function) in Python. You have no doubt encountered this on the command line if you have typed the name only of a function without parentheses. ``` In [2]: a Out[2]: <function __main__.a> ``` When you see `a(b)(c)` it is a method of cha...
How to add legend on Seaborn facetgrid bar plot
32,261,619
7
2015-08-28T00:42:46Z
32,301,804
7
2015-08-30T22:33:25Z
[ "python", "pandas", "matplotlib", "seaborn" ]
I have the following code: ``` import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import seaborn as sns sns.set(style="white") # Create a dataset with many short random walks rs = np.random.RandomState(4) pos = rs.randint(-1, ...
Some how there is one legend item for each of the subplot. Looks like if we want to have legend corresponds to the bars in each of the subplot, we have to manually make them. ``` # Let's just make a 1-by-2 plot df = df.head(10) # Initialize a grid of plots with an Axes for each walk grid = sns.FacetGrid(df, col="walk...
Reading large file (52mb) of lines in Python, is it better to iterate the lines or use readlines?
32,276,616
3
2015-08-28T17:26:46Z
32,276,685
8
2015-08-28T17:31:33Z
[ "python", "file-io" ]
I have a list of 4 million words in a txt file that I want to add to a list. I have two options: ``` l=[line for line in open(wordlist)] ``` or: ``` wordlist = file.readlines() ``` readlines() appears to be much faster, I'm guessing this is because the data is read into the memory in one go. The first option would ...
Both options read the whole thing into memory in one big list. The first option is slower because you delegate looping to Python bytecode. If you wanted to create one big list with all lines from your file, then there is no reason to use a list comprehension here. I'd not use *either*. Loop over the file *and process ...
Pylab - 'module' object has no attribute 'Figure'
32,279,887
3
2015-08-28T21:16:48Z
33,510,341
14
2015-11-03T22:32:21Z
[ "python", "matplotlib", "tkinter" ]
I'm trying to use Tkinter to create a view, and therefore I'm also using pylab. My problem is that I get an error saying: > AttributeError: 'module' object has no attribute 'Figure' and the error comes from this line of code: ``` self.fig = FigureCanvasTkAgg(pylab.figure(), master=self) ``` I'm new to python, so I ...
If you're unable to run any of the other `pylab` functions then there's a problem with your install. I just ran into a similar error when I installed `matplotlib` and then `pylab`, and it turns out that installing `matplotlib` will *also* install `pylab` for you and that separately installing `pylab` on top of it will ...
how to change a Dataframe column from String type to Double type in pyspark
32,284,620
9
2015-08-29T09:34:08Z
32,286,450
16
2015-08-29T13:15:11Z
[ "python", "apache-spark", "pyspark", "apache-spark-1.4" ]
I have a dataframe with column as String. I wanted to change the column type to Double type in pyspark. Following is the way, I did,- ``` toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType()) changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show'])) ``` > Just wanted to know , is this the right ...
There is no need for an UDF here. `Column` already provides [`cast` method](https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.cast) with `DataType` instance: ``` from pyspark.sql.types.import DoubleType changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType())) ```...
How do I randomly select a variable from a list, and then modify it in python?
32,288,236
4
2015-08-29T16:28:29Z
32,288,253
7
2015-08-29T16:30:01Z
[ "python", "list", "python-3.x", "random" ]
Here's my python 3 code. I would like to randomly select one of the cell variables (c1 through c9) and change its value to the be the same as the cpuletter variable. ``` import random #Cell variables c1 = "1" c2 = "2" c3 = "3" c4 = "4" c5 = "5" c6 = "6" c7 = "7" c8 = "8" c9 = "9" cells = [c1, c2, c3, c4, c5, c6, c7, ...
## Problem: `random.choice(cells)` returns a random value from your list, for example `"3"`, and you are trying to assign something to it, like: ``` "3" = "X" ``` which is wrong. Instead of this, you can modify the `list`, for example: ``` cells[5] = "X" ``` ## Solution: You can use [`random.randrange()`](https:...
chunk string in Python without breaking words
32,295,475
2
2015-08-30T10:19:36Z
32,295,512
7
2015-08-30T10:24:55Z
[ "python", "raspberry-pi" ]
I have this code which is meant to display some text on a 20x2 LCD display: ``` #!/usr/bin/python LCDCHARS = 20 LCDLINES = 2 def WriteLCD(text_per_LCD): chunked = (text_per_LCD[i:LCDCHARS+i] for i in range (0, len(text_per_LCD), LCDCHARS)) count_l = 0 for text_per_line in chunked: # print will be...
Use the [`textwrap`](https://docs.python.org/2/library/textwrap.html) module: ``` >>> textwrap.wrap("This text will display on 3 LCD lines", 20) ['This text will', 'display on 3 LCD', 'lines'] ```
removing duplicates of a list of sets
32,296,933
9
2015-08-30T13:15:05Z
32,296,966
13
2015-08-30T13:18:56Z
[ "python", "list", "set", "unique", "duplicate-removal" ]
I have a list of sets : ``` L = [set([1, 4]), set([1, 4]), set([1, 2]), set([1, 2]), set([2, 4]), set([2, 4]), set([5, 6]), set([5, 6]), set([3, 6]), set([3, 6]), set([3, 5]), set([3, 5])] ``` (actually in my case a conversion of a list of reciprocal tuples) and I want to remove duplicates to get : ``` L = [set([1,...
The best way is to convert your sets to `frozenset`s (which are hashable) and then use `set` to get only the unique sets, like this ``` >>> list(set(frozenset(item) for item in L)) [frozenset({2, 4}), frozenset({3, 6}), frozenset({1, 2}), frozenset({5, 6}), frozenset({1, 4}), frozenset({3, 5})] ``` If you want t...
Wolfram Alpha and scipy.integrate.quad give me different answers for the same integral
32,302,231
4
2015-08-30T23:38:15Z
32,302,387
8
2015-08-31T00:04:26Z
[ "python", "math", "numpy", "scipy", "wolframalpha" ]
Consider the following function: ``` import numpy as np from scipy.special import erf def my_func(x): return np.exp(x ** 2) * (1 + erf(x)) ``` When I evaluate the integral of this function from `-14` to `-4` using `scipy`'s `quad` function, I get the following result: ``` In [3]: from scipy import integrate In...
TL;DR: The integrand is equivalent to `erfcx(-x)`, and the implementation of `erfcx` at [`scipy.special.erfcx`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.erfcx.html) takes care of the numerical issues: ``` In [10]: from scipy.integrate import quad In [11]: from scipy.special import erfcx In [...
Could not find a version that satisfies the requirement <package>
32,302,379
15
2015-08-31T00:02:24Z
32,302,448
8
2015-08-31T00:15:41Z
[ "python", "pip", "requirements.txt" ]
I'm installing several Python packages in Ubuntu 12.04 using the following `requirements.txt` file: ``` numpy>=1.8.2,<2.0.0 matplotlib>=1.3.1,<2.0.0 scipy>=0.14.0,<1.0.0 astroML>=0.2,<1.0 scikit-learn>=0.14.1,<1.0.0 rpy2>=2.4.3,<3.0.0 ``` and these two commands: ``` $ pip install --download=/tmp -r requirements.txt ...
This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., `six`, `pytz` etc). You should therefore manually include ...
Trouble installing "distribute": NameError: name 'sys_platform' is not defined
32,303,152
5
2015-08-31T02:18:27Z
34,694,350
10
2016-01-09T13:58:29Z
[ "python" ]
I'm trying to install the Python package "distribute". I've got it downloaded and it begins to work, but then quits out with the error seen here: [![enter image description here](http://i.stack.imgur.com/PMV3z.png)](http://i.stack.imgur.com/PMV3z.png) I have a feeling the solution is somehow related to me going in an...
As stated by Burhan you have to install the `setuptools` package: just use the command: ``` pip install setuptools ``` Most importantly, **do not forget to also uninstall the `distribute` package** (since tools provided by that package are already included by `setuptools`). Just use the command: ``` pip uninstall d...
Error while starting new scrapy project
32,304,886
3
2015-08-31T06:07:39Z
32,584,004
18
2015-09-15T10:43:27Z
[ "python", "scrapy" ]
I have installed Scrapy using Ubuntu packages provided in the Scrapy website. But on starting a Scrapy project ``` scrapy startproject test ``` I am getting error message as. ``` Traceback (most recent call last): File "/usr/bin/scrapy", line 5, in <module> from pkg_resources import load_entry_point File ...
I tried `sudo pip install pyasn1 --upgrade` and it works.
No output from pycharm profiling when running a Flask container
32,319,971
4
2015-08-31T21:05:09Z
34,663,714
7
2016-01-07T19:37:40Z
[ "python", "pycharm" ]
Running PyCharm 4.5.3 Build #141.1899 Professional Edition and licensed. I run a Flask app using the profiler command using a configuration similar to: ``` python app.py ``` which looks like: ``` def create_app(): app = Flask(__name__, static_folder='static') app.register_blueprint( consumer_v1.bp, url_prefi...
To fix this I simply installed [yappi](https://code.google.com/p/yappi/) instead of the default python profiler. `pip install yappi` I hope this works for you too!
How do I get IPython profile behavior from Jupyter 4.x?
32,320,836
8
2015-08-31T22:24:12Z
32,516,383
7
2015-09-11T05:52:42Z
[ "python", "ipython", "ipython-notebook", "jupyter" ]
There was official(?) recommendation of running an IPython Notebook server, and creating a profile via ``` $ ipython profile create nbserver ``` as recommended in <http://ipython.org/ipython-doc/1/interactive/public_server.html>. This allowed for very different and very useful behavior when starting an IPython Notebo...
Using some code from this blog post <http://www.svds.com/jupyter-notebook-best-practices-for-data-science/> and updating it. The easiest solution appears to be to create an alias, like: ``` alias jupyter-nbserver='JUPYTER_CONFIG_DIR=~/.jupyter-nbserver jupyter notebook' ``` So now you can run the jupyter notebook wit...
In Python, how can I translate *(1+(int*)&x)?
32,320,974
4
2015-08-31T22:38:30Z
32,321,142
7
2015-08-31T22:58:31Z
[ "python", "c", "floating-point", "bit-representation" ]
This question is a follow-up of [this one](http://stackoverflow.com/questions/32300386/in-suns-libm-what-does-1intx-do-where-x-is-of-type-double). In [Sun's math library](http://www.netlib.org/fdlibm/readme) (in C), the expression ``` *(1+(int*)&x) ``` is used to retrieve the high word of the floating point number `x...
You can do this more easily with [`struct`](https://docs.python.org/3/library/struct.html): ``` high_word = struct.pack('<d', x)[4:8] return struct.unpack('<i', high_word)[0] ``` Here, `high_word` is a `bytes` object (or a `str` in 2.x) consisting of the four most significant bytes of `x` in little endian order (usin...
What is the difference between the AWS boto and boto3
32,322,503
27
2015-09-01T02:09:11Z
32,323,454
44
2015-09-01T04:17:41Z
[ "python", "amazon-web-services", "boto", "boto3" ]
I'm new to AWS using Python and I'm trying to learn the boto API however I notice there are two major versions/packages for Python. That would be boto, and boto3. I haven't been able to find an article with the major advantages/disadvantages or differences between these packages.
The [boto](https://github.com/boto/boto) package is the hand-coded Python library that has been around since 2006. It is very popular and is fully supported by AWS but because it is hand-coded and there are so many services available (with more appearing all the time) it is difficult to maintain. So, [boto3](https://g...
makedirs gives OSError: [Errno 13] Permission denied: '/pdf_files'
32,329,976
2
2015-09-01T11:03:35Z
32,330,046
7
2015-09-01T11:08:09Z
[ "python", "directory", "operating-system", "folder", "createfile" ]
I'm trying to create a folder inside a folder, first I check if that directory exists and create it if necessary: ``` name = "User1" if not os.path.exists("/pdf_files/%s" % name): os.makedirs('/pdf_files/%s' % name ) ``` Problem is that i'm getting an error : `OSError: [Errno 13] Permission denied: '/pdf_files'` ...
You are trying to create your folder inside root directory (`/`). Change `/pdf_files/%s` to `pdf_files/%s` or `/home/username/pdf_files/%s`
Create a custom Transformer in PySpark ML
32,331,848
4
2015-09-01T12:36:56Z
32,337,101
13
2015-09-01T16:56:02Z
[ "python", "apache-spark", "nltk", "pyspark", "apache-spark-ml" ]
I am new to Spark SQL DataFrames and ML on them (PySpark). How can I create a costume tokenizer, which for example removes stop words and uses some libraries from [nltk](/questions/tagged/nltk "show questions tagged 'nltk'")? Can I extend the default one? Thanks.
> Can I extend the default one? Not really. Default `Tokenizer` is a subclass of `pyspark.ml.wrapper.JavaTransformer` and, same as other transfromers and estimators from `pyspark.ml.feature`, delegates actual processing to its Scala counterpart. Since you want to use Python you should extend `pyspark.ml.pipeline.Trans...
Numpy item faster than operator[]
32,333,765
13
2015-09-01T14:06:08Z
32,334,114
18
2015-09-01T14:22:20Z
[ "python", "performance", "numpy" ]
I have a following code in python that at least for me produces strange results: ``` import numpy as np import timeit a = np.random.rand(3,2) print timeit.timeit('a[2,1] + 1', 'from __main__ import a', number=1000000) print timeit.timeit('a.item((2,1)) + 1', 'from __main__ import a', number=1000000) ``` This gives ...
In this case, they don't return quite the same thing. `a[2,1]` returns a `numpy.float64`, while `a.item((2,1))` returns a native python float. ## Native vs `numpy` *scalars* (`float`, `int`, etc) A `numpy.float64` scalar isn't quite identical to a native python `float` (they behave identically, however). Simple opera...
SimpleBlobDetector not found in opencv 3.0 for python
32,334,203
2
2015-09-01T14:26:03Z
32,395,088
9
2015-09-04T09:53:32Z
[ "python", "opencv" ]
I am trying to use SimpleBlobDetector in python with cv2 version 3.0. However when I run: ``` import cv2 detector = cv2.SimpleBlobDetector() ``` The console returns me: ``` AttributeError: 'module' object has no attribute 'SimpleBlobDetector' ``` Does anyone know if the function name has changed from cv2 version 2....
The new function is `cv2.SimpleBlobDetector_create(params)` if i'm not wrong.
Why does this recursive function continue even after its base case has been satisfied
32,339,236
2
2015-09-01T19:13:36Z
32,339,304
7
2015-09-01T19:18:17Z
[ "python", "recursion" ]
I was playing around with [/r/dailyprogrammer's](https://www.reddit.com/r/dailyprogrammer/comments/3i99w8/20150824_challenge_229_easy_the_dottie_number/) easy challenge earlier; in this case you are challenged to discover The Dottie Number (~0.739085). Whilst the challenge wanted it in `radians` I decided to keep it in...
The numbers shown to you are not the actual values, because calling `str` on a number doesn't show you all the digits. If you use `repr` instead, you'll get this: ``` Dottie number: 0.7390851332151607 Previous = 0.7390851332151607 Current = 0.7390851332151607 Previous = 0.7390851332151606 Current = 0.7390851332151...
Python Pandas: How to I round datetime column to nearest quarter hour
32,344,533
5
2015-09-02T04:13:05Z
32,344,636
12
2015-09-02T04:25:40Z
[ "python", "datetime", "pandas", "python-datetime" ]
I have loaded a data file into a Python pandas dataframe. I has a datetime column of the format `2015-07-18 13:53:33.280`. What I need to do is create a new column that rounds this out to its nearest quarter hour. So, the date above will be rounded to `2015-07-18 13:45:00.000`. How do I do this in pandas? I tried usi...
Assuming that your series is made up of `datetime` objects, You need to use `Series.apply` . Example - ``` import datetime df['<column>'] = df['<column>'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,15*(dt.minute // 15))) ```
How to use the same line of code in all functions?
32,347,159
19
2015-09-02T07:36:08Z
32,347,255
45
2015-09-02T07:41:05Z
[ "python" ]
I am newbie in Python. I wonder if it is possible that all functions inherit the same line of code? `with open(filename, 'r') as f:` as this line of code is the same in all three functions. Is it possible to inherit the code without using classes? I tried to find the answer on stackoverflow and python documentation, ...
The common code in your case is ``` with open(filename, 'r') as f: contents = f.read() ``` So just move it to its own function: ``` def get_file_contents(filename): with open(filename, 'r') as f: return f.read() def word_count(filename): return len(get_file_contents(filename).split()) def line_...
How to use the same line of code in all functions?
32,347,159
19
2015-09-02T07:36:08Z
32,347,261
15
2015-09-02T07:41:23Z
[ "python" ]
I am newbie in Python. I wonder if it is possible that all functions inherit the same line of code? `with open(filename, 'r') as f:` as this line of code is the same in all three functions. Is it possible to inherit the code without using classes? I tried to find the answer on stackoverflow and python documentation, ...
What I've done in the past is split the code out into another function, in your example ``` with open(filename, 'r') as f: f.read() ``` Is common within all of your methods, so I'd look at rewriting it like so. ``` def read_file(filename): with open(filename, 'r') as f: return f.read() def wor...
Efficiency vs legibility of code?
32,347,732
4
2015-09-02T08:04:02Z
32,347,789
9
2015-09-02T08:06:35Z
[ "python" ]
Let's say I have a simple function which calculates the cube root of a number and returns it as a string: ``` def cuberoot4u(number): return str(pow(number, 1/3)) ``` I could rewrite this as: ``` def cuberoot4u(number): cube_root = pow(number, 1/3) string_cube_root = str(cube_root) return string_cub...
In general you should prioritise legibility over efficiency in your code, however if you have proved that your codes performance is causing an issue then ([and only then](http://c2.com/cgi/wiki?PrematureOptimization)) should you start to optimise. If you do need to make your code less legible in order to speed it up y...
does this line of python close the file when its finished?
32,356,115
2
2015-09-02T14:36:35Z
32,356,184
8
2015-09-02T14:39:39Z
[ "python" ]
I have a line of python that splits a file by carriage return character: ``` lines = open(sFile, 'r').read().split("0d".decode('hex')) ``` Was this file is closed? If not, can I acquire the file handle somehow?
The short answer is "probably". The open file object *should* get garbage collected which will close the file. However, there are some circumstances where that might not be true and the open file handle can live on. Best practice is to **always** close your file handles. The beauty of context managers is hard to over-...
Using Spyder IDE, how do you return from "goto definition"?
32,358,012
15
2015-09-02T16:08:39Z
32,404,840
9
2015-09-04T18:55:08Z
[ "python", "ide", "keyboard-shortcuts", "spyder" ]
## Description of the problem: I like to jump around code a lot with the keyboard but I am hitting a wall of usability in Spyder IDE. I can use the "goto definition" feature to jump to the definition of some function but then I can't go back to where my cursor was (so it takes a while to manually find where I was befo...
Spyder have a one strange [bug](https://groups.google.com/forum/#!topic/spyderlib/a-lVayczSKY). Shortcut "Previous cursor position" only work if "Source toolbar" is present. Turn on "View -> Toolbars -> Source toolbar". You can try it.
What difference between subprocess.call() and subprocess.Popen() makes PIPE less secure for the former?
32,364,849
9
2015-09-02T23:40:32Z
32,396,937
8
2015-09-04T11:26:33Z
[ "python", "python-2.7", "subprocess", "popen", "python-2.6" ]
I've had a look at the documentation for both of them. This question is prompted by J.F.'s comment here: [Retrieving the output of subprocess.call()](http://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call#comment31660313_1996540) The current Python documentation for [`subprocess.call()`](...
[`call()` is just `Popen().wait()` (± error handling)](https://github.com/python/cpython/blob/b01cfb8f69e0990be0615b8613a7412f88bd217a/Lib/subprocess.py#L552-L566). **You should not use `stdout=PIPE` with `call()`** because it does not read from the pipe and therefore the child process will hang as soon as it fills t...
How to handle the "else" clause when converting an "if..elif..else" statement into a dictionary lookup?
32,367,882
3
2015-09-03T05:51:28Z
32,367,906
8
2015-09-03T05:53:51Z
[ "python", "if-statement", "technical-debt" ]
I am trying to convert an "if else" statement in python into a dictionary. I tried to convert it into a dictionary, but how do I handle the last else clause? ``` val=3 if val==1: print "a" elif val==2: print "b" elif val==3: print "c" elif val==4: print "d" else: print "value not found:" print "==========...
You can use the `dict.get` method: ``` print DATA_SOURCE.get(val, "value not found") ``` That will return `"value not found"` if `val` is not a key, without affecting the dictionary. As always, if in doubt, use the help: ``` >>> help(dict) ```
How to Include image or picture in jupyter notebook
32,370,281
19
2015-09-03T08:09:58Z
32,370,538
17
2015-09-03T08:23:25Z
[ "python", "ipython-notebook", "jupyter" ]
I would like to include image in a jupyter notebook. If I did the following, it works : ``` from IPython.display import Image Image("img/picture.png") ``` But I would like to include the images in a markdown cell and the following code gives a 404 error : ``` ![title]("img/picture.png") ``` I also tried ``` ![tex...
There are several ways to post an image in Jupyter notebooks: ## via HTML: ``` from IPython.display import Image from IPython.core.display import HTML Image(url= "http://my_site.com/my_picture.jpg") ``` You retain the ability to use HTML tags to resize, etc... ``` Image(url= "http://my_site.com/my_picture.jpg", wi...
How to Include image or picture in jupyter notebook
32,370,281
19
2015-09-03T08:09:58Z
32,371,085
19
2015-09-03T08:52:02Z
[ "python", "ipython-notebook", "jupyter" ]
I would like to include image in a jupyter notebook. If I did the following, it works : ``` from IPython.display import Image Image("img/picture.png") ``` But I would like to include the images in a markdown cell and the following code gives a 404 error : ``` ![title]("img/picture.png") ``` I also tried ``` ![tex...
You mustn't use quotation marks around the name of the image files in markdown! If you carefully read your error message, you will see the two `%22` parts in the link. That is the html encoded quotation mark. You have to change the line ``` ![title]("img/picture.png") ``` to ``` ![title](img/picture.png) ```
Why is this generator expression function slower than the loop version?
32,382,230
10
2015-09-03T17:44:07Z
32,382,281
10
2015-09-03T17:47:26Z
[ "python", "performance", "python-2.7", "generator-expression" ]
I have been operating under the theory that generator expressions tend to be more efficient than normal loops. But then I ran into the following example: write a function which given a number, `N`, and some factors, `ps`, returns the sum of all the numbers under `N` that are a multiple of at least one factor. Here is ...
First of all: generator expressions are *memory* efficient, not necessarily speed efficient. Your compact `genexp()` version is slower for two reasons: * Generator expressions are implemented using a new scope (like a new function). You are producing *N* new scopes for each `any()` test. Creating a new scope and tear...
Precision difference when printing Python and C++ doubles
32,386,768
14
2015-09-03T23:05:41Z
32,387,030
9
2015-09-03T23:36:11Z
[ "python", "c++", "floating-point", "double" ]
I'm currently marvelling over this: **C++ 11** ``` #include <iostream> #include <iomanip> #include <limits> int main() { double d = 1.305195828773568; std::cout << std::setprecision(std::numeric_limits<double>::max_digits10) << d << std::endl; // Prints 1.3051958287735681 } ``` **Python** ``` >>> repr(1.305...
you can force python to print the 1 as well (and many more of the following digits): ``` print('{:.16f}'.format(1.305195828773568)) # -> 1.3051958287735681 ``` from <https://docs.python.org/2/tutorial/floatingpoint.html>: > ``` > >>> 7205759403792794 * 10**30 // 2**56 > 100000000000000005551115123125L > ``` > > In v...
Anaconda ImportError: libSM.so.6: cannot open shared object file: No such file or directory
32,389,599
6
2015-09-04T03:27:15Z
32,389,631
12
2015-09-04T03:31:34Z
[ "python", "matplotlib", "anaconda" ]
Here's my python import statements ``` import plotly as py import pandas as pd import numpy as np import plotly.plotly as py import plotly.tools as plotly_tools from plotly.graph_objs import * os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp() from matplotlib.finance import quotes_historical_yahoo import matplotlib.pyp...
**Try this command if you are using ubuntu:** `pyqt4` might be missing ``` sudo apt-get install -y python-qt4 ``` It worked for me.
Import Error: No module name libstdcxx
32,389,977
6
2015-09-04T04:16:56Z
33,897,420
14
2015-11-24T15:21:28Z
[ "python", "c++", "c", "linux" ]
When I use gdb to debug my C++ program with **segmentation fault**, I come with this error in gdb. > Traceback (most recent call last): > File "/usr/share/gdb/auto-load/usr/lib/x86\_64-linux- gnu/libstdc++.so.6.0.19-gdb.py", line 63, in > from libstdcxx.v6.printers import register\_libstdcxx\_printers > ImportError: N...
This is a bug in /usr/lib/debug/usr/lib/$triple/libstdc++.so.6.0.18-gdb.py; When you start gdb, please enter: `python sys.path.append("/usr/share/gcc-4.8/python");`
Import Error: No module name libstdcxx
32,389,977
6
2015-09-04T04:16:56Z
34,350,497
9
2015-12-18T07:31:14Z
[ "python", "c++", "c", "linux" ]
When I use gdb to debug my C++ program with **segmentation fault**, I come with this error in gdb. > Traceback (most recent call last): > File "/usr/share/gdb/auto-load/usr/lib/x86\_64-linux- gnu/libstdc++.so.6.0.19-gdb.py", line 63, in > from libstdcxx.v6.printers import register\_libstdcxx\_printers > ImportError: N...
I encountered this error during using gdb in emacs. (in docker container - ubuntu) I tried it like below and worked well. (1) open libstdc++.so.x.x.x-gdb.py ``` sh> sudo vi /usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19-gdb.py ``` (2) modify that file(libstdc++.so.x.x.x-gdb.py ) like below. `...
Printing nested lists in certain directions - Python
32,397,765
3
2015-09-04T12:11:33Z
32,397,956
9
2015-09-04T12:21:51Z
[ "python" ]
I am trying a problem to make Graphical designs in Python, more specifically ASCII "banner" words. Each letter is made up of a nested list of lines of the character. ``` [[' _______ ', '( )', '| () () |', '| || || |', '| |(_)| |', '| | | |', '| ) ( |', '|/ \\|'], [' _______ ', '( ____ \\', '| ( \\/'...
If you want to print the letters from left to right, you will have to [`zip`](https://docs.python.org/3/library/functions.html#zip) the list of lists with itself, effectively ["transposing"](http://stackoverflow.com/q/4937491/1639625) it. This way, the first list will have all the first rows, the second list all the se...
Pandas read_csv from url
32,400,867
7
2015-09-04T14:44:24Z
32,400,969
10
2015-09-04T14:50:24Z
[ "python", "csv", "pandas", "request" ]
I am using Python 3.4 with IPython and have the following code. I'm unable to read a csv-file from the given URL: ``` import pandas as pd import requests url="https://github.com/cs109/2014_data/blob/master/countries.csv" s=requests.get(url).content c=pd.read_csv(s) ``` I have the following error > "Expected file pa...
Just as the error suggests , `pandas.read_csv` needs a file-like object as the first argument. If you want to read the csv from a string, you can use [`io.StringIO`](https://docs.python.org/3/library/io.html#io.StringIO) (Python 3.x) or [`StringIO.StringIO` (Python 2.x)](https://docs.python.org/2/library/stringio.html...
caffe installation : opencv libpng16.so.16 linkage issues
32,405,035
3
2015-09-04T19:09:21Z
32,514,285
13
2015-09-11T01:49:40Z
[ "python", "opencv", "ubuntu", "anaconda", "caffe" ]
I am trying to compile caffe with python interface on an Ubuntu 14.04 machine. I have installed Anaconda and opencv with `conda install opencv`. I have also installed all the requirement stipulated in the coffee and changed the commentary blocks in `makefile.config` so that PYTHON\_LIB and PYTHON\_INCLUDE point toward...
I came across the same problem. I found it similar to <https://github.com/BVLC/caffe/issues/2007>, and I solved it by ``` cd /usr/lib/x86_64-linux-gnu sudo ln -s ~/anaconda/lib/libpng16.so.16 libpng16.so.16 sudo ldconfig ```
Bitwise-OR the elements of a list in python using lambda
32,406,128
2
2015-09-04T20:30:06Z
32,406,177
9
2015-09-04T20:33:19Z
[ "python", "python-2.7" ]
Can I use the lambda function this way to bitwise-OR all the elements in the list? ``` lst = [1, 1, 1] f = lambda x: x | b for b in lst ``` When I do this I get a `SyntaxError`.
You want [`reduce`](https://docs.python.org/2/library/functions.html#reduce): ``` f = reduce(lambda x, y: x | y, lst) ``` `reduce` accepts a binary function and an iterable, and applies the operator between all elements starting from the first pair. Note: in Python 3 it moves to the [`functools`](https://docs.python....
Why does this Python script delete '.txt' files, as well as all the '.tmp' files?
32,407,377
3
2015-09-04T22:22:04Z
32,407,404
7
2015-09-04T22:25:00Z
[ "python", "python-2.7", "os.walk", "os.path" ]
I'm trying to write a script that will automatically delete all the temp files in a specific folder, and I noticed that this script also deletes all the *text files* in that folder as well. Can anyone explain why it does that? ``` import os path = 'C:\scripts27' for root, dirs, files in os.walk(path): ...
I'm assuming you meant providing a list of extensions. But in your case, `extensions` is defined as `('.tmp')` which is *not* a tuple but a string. This causes your code to loop over all files and check for names ending with `.`, `t`, `m` and `p` thereby deleting your `.txt` files. The fix here is to define extensions...
What does `{...}` mean in the print output of a python variable?
32,408,387
6
2015-09-05T00:39:09Z
32,408,441
11
2015-09-05T00:48:06Z
[ "python", "ellipsis" ]
Someone posted [this interesting formulation](https://stackoverflow.com/questions/32127908/python-assignment-operator-precedence-a-b-ab-5), and I tried it out in a Python 3 console: ``` >>> (a, b) = a[b] = {}, 5 >>> a {5: ({...}, 5)} ``` While there is a lot to unpack here, what I don't understand (and the semantics ...
It's an indication that the dict recurses, i.e. contains itself. A much simpler example: ``` >>> a = [] >>> a.append(a) >>> a [[...]] ``` This is a list whose only element is itself. Obviously the repr can't be printed literally, or it would be infinitely long; instead, the builtin types notice when this has happened...
What is the right way to debug in iPython notebook?
32,409,629
10
2015-09-05T04:53:43Z
32,410,100
7
2015-09-05T06:13:10Z
[ "python", "python-2.7", "ipython", "ipython-notebook", "pdb" ]
As I know, %debug magic can do debug within one cell. However, I have function calls across multiple cells. For example, ``` In[1]: def fun1(a) def fun2(b) # I want to set a breakpoint for the following line # return do_some_thing_about(b) return fun2(a) In[2]: impor...
Use **ipdb** Install it via ``` pip install ipdb ``` Usage: ``` In[1]: def fun1(a): def fun2(a): import ipdb; ipdb.set_trace() # debugging starts here return do_some_thing_about(b) return fun2(a) In[2]: fun1(1) ``` For executing line by line use `n` and for step into a function use `s` and to e...
Python: Define a function only if package exists
32,414,401
8
2015-09-05T14:49:40Z
32,414,442
8
2015-09-05T14:55:11Z
[ "python" ]
Is it possible to tell Python 2.7 to only parse a function definition if a package exists? I have a script that is run on multiple machines. There are some functions defined in the script that are very nice to have, but aren't required for the core operations the script performs. Some of the machines the script is run...
Function definitions and imports are just code in Python, and like other code, you can wrap them in a `try`: ``` try: import bandana except ImportError: pass # Hat-wearing functions are optional else: def wear(hat): bandana.check(hat) ... ``` This would define the `wear` function only if ...
highest value that is less than 0 in a list that has mix of negative and positive values
32,417,954
6
2015-09-05T21:41:26Z
32,417,985
12
2015-09-05T21:45:09Z
[ "python", "list" ]
I have a list with the these values. ``` lst1 = [1,-2,-4,-8,-9,-12,0,39,12,-3,-7] ``` I need to get the max value that is less that zero. If I do `print max(last)`- I get 39 and what is need is -2. `print max(p < 0 for p in lst1)`, I get True and not -2
Never mind, I figured out and it should be ``` print max(p for p in lst1 if p < 0) ```
Accelerating scientific python program
32,426,829
3
2015-09-06T18:24:23Z
32,427,481
8
2015-09-06T19:34:28Z
[ "python", "numpy", "scientific-computing" ]
I have the following code in python: ``` def P(z, u0): x = np.inner(z, u0) tmp = x*u0 return (z - tmp) def powerA2(A, u0): x0 = np.random.rand(len(A)) for i in range(ITERATIONS): x0 = P(np.dot(A, x0), u0) x0 = x0 / np.linalg.norm(x0) return (np.inner(np.dot(A, x0), x0)) ``` `...
You could consider using [pythran](http://pythonhosted.org/pythran). Compiling the following code (`norm.py`): ``` #pythran export powerA2(float [][], float[]) import numpy as np def P(z, u0): x = np.inner(z, u0) tmp = x*u0 return (z - tmp) def norm(x): return np.sqrt(np.sum(np.abs(x)**2)) def power...
Saving Matplotlib graphs to image as full screen
32,428,193
2
2015-09-06T20:52:11Z
32,428,266
8
2015-09-06T21:00:55Z
[ "python", "pandas", "matplotlib" ]
I'm building a small graphing utility using Pandas and MatPlotLib to parse data and output graphs from a machine at work. When I output the graph using ``` plt.show() ``` I end up with an unclear image that has legends and labels crowding each other out like so. [![Sample Bad Image](http://i.stack.imgur.com/eFRBG.p...
The method you use to maximise the window size depends on which matplotlib backend you are using. Please see the following example for the 3 most common backends: ``` import matplotlib.pyplot as plt plt.figure() plt.plot([1,2], [1,2]) # Option 1 # QT backend manager = plt.get_current_fig_manager() manager.window.sho...
Wagtail: Display a list of child pages inside a parent page
32,429,113
4
2015-09-06T23:02:26Z
32,436,798
7
2015-09-07T10:46:59Z
[ "python", "django", "wagtail" ]
In Wagtail CMS, I'm trying to create an index page that will display a list of all its child pages along with a featured image associated with each child page. I have created these two page models in models.py: ``` class IndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels ...
From the [release notes of wagtail version 1.1](https://github.com/torchbox/wagtail/blob/master/docs/releases/1.1.rst): > Usually, an operation that retrieves a queryset of pages (such as `homepage.get_children()`) will return them as basic Page instances, which only include the core page data such as title. The `spec...
What does django rest framework mean trade offs between view vs viewsets?
32,430,689
3
2015-09-07T03:29:43Z
32,431,191
9
2015-09-07T04:39:49Z
[ "python", "django", "python-2.7", "view", "django-rest-framework" ]
I don't know why document said "That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually." If I want to make rest api, which is similar...
The main advantage of using `viewsets` over `views` is brevity. In the simple case you can get more done with fewer lines of code. The main disadvantage is that the simplifying assumptions made by `viewsets` might not always fit the problem space you are working in. As with class-based views in Django, if you try to a...
Cx_freeze ImportError no module named scipy
32,432,887
4
2015-09-07T07:02:56Z
32,480,170
9
2015-09-09T12:56:42Z
[ "python", "scipy", "cx-freeze" ]
Good day all, I am having trouble using cx\_Freeze on a code I am working on converting to a .exe. When I run cx\_Freeze I get the following ImportError that there no no module named scipy ``` running install running build running build_exe Traceback (most recent call last): File "setup.py", line 25, in <module> ...
I had exactly the same issue. Found the solution here: <https://bitbucket.org/anthony_tuininga/cx_freeze/issues/43/import-errors-when-using-cx_freeze-with> Find the hooks.py file in cx\_freeze folder. Change line 548 from finder.IncludePackage("scipy.lib") to finder.IncludePackage("scipy.\_lib"). Leave the "scipy" en...
Python merging two lists with all possible permutations
32,438,350
9
2015-09-07T12:06:57Z
32,438,848
11
2015-09-07T12:31:42Z
[ "python", "list", "itertools" ]
I'm trying to figure out the best way to merge two lists into all possible combinations. So, if I start with two lists like this: ``` list1 = [1, 2] list2 = [3, 4] ``` The resulting list will look like this: ``` [[[1,3], [2,4]], [[1,4], [2,3]]] ``` That is, it basically produces a list of lists, with all the potent...
`repeat` the first list, `permutate` the second and `zip` it all together ``` >>> from itertools import permutations, repeat >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b))) [[(1, 4), (2, 5), (3, 6)], [(1, 4), (2, 6), (3, 5)], [(1, 5), (2, 4), (3, 6)], [(1,...
Python merging two lists with all possible permutations
32,438,350
9
2015-09-07T12:06:57Z
32,442,873
9
2015-09-07T16:29:27Z
[ "python", "list", "itertools" ]
I'm trying to figure out the best way to merge two lists into all possible combinations. So, if I start with two lists like this: ``` list1 = [1, 2] list2 = [3, 4] ``` The resulting list will look like this: ``` [[[1,3], [2,4]], [[1,4], [2,3]]] ``` That is, it basically produces a list of lists, with all the potent...
The accepted answer can be simplified to ``` a = [1, 2, 3] b = [4, 5, 6] [list(zip(a, p)) for p in permutations(b)] ``` (The list() call can be omitted in Python 2)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'
32,440,251
6
2015-09-07T13:47:13Z
32,456,737
11
2015-09-08T11:34:13Z
[ "python", "django", "django-orm" ]
I have made App12/models.py module as: ``` from django.db import models class Question(models.Model): ques_text=models.CharField(max_length=300) pub_date=models.DateTimeField('Published date') def __str__(self): return self.ques_text class Choice(models.Model): # question=models.ForeignKey...
From your migration file it's normal that you get this error, you are trying to store a datetime on a Foreignkey which need to be an int. This is happened when the migration asked you which value will be set for old Choice rows because the new ForeignKey is required. To resolve it, you can change the migration file a...
'UCS-2' codec can't encode characters in position 1050-1050
32,442,608
3
2015-09-07T16:10:03Z
32,442,684
10
2015-09-07T16:15:42Z
[ "python", "unicode" ]
When I run my Python code, I get the following errors: ``` File "E:\python343\crawler.py", line 31, in <module> print (x1) File "E:\python343\lib\idlelib\PyShell.py", line 1347, in write return self.shell.write(s, self.tags) UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 1050-1050: N...
Your data contains characters outside of the [*Basic Multilingual Plane*](https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane). Emoji's for example, are outside the BMP, and the window system used by IDLE, Tk, cannot handle such characters. You could use a [translation table](https://docs.python.org...
Python strange multiprocessing with variable name
32,443,135
7
2015-09-07T16:50:58Z
32,443,422
9
2015-09-07T17:14:00Z
[ "python", "multiprocessing" ]
a simple example: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import multiprocessing class Klass(object): def __init__(self): print "Constructor ... %s" % multiprocessing.current_process().name def __del__(self): print "... Destructor %s" % multiprocessing.current_process().name if __...
The code raises ``` AttributeError: "'NoneType' object has no attribute 'current_process'" ``` if the global variable `multiprocessing` is deleted before `kls` gets deleted. In general, the order in which objects are deleted is not predictable. However, [per the docs](https://docs.python.org/3/reference/datamodel.htm...