title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
calculate accuracy using r value | 37,791,338 | <p>I'm using a linear regression model to predict the weather data for one year. Prediction is done using Python's <code>sklearn</code> library. The problem is that I need to find the accuracy of the prediction. After a quick internet search I found out that r^2 is the way to find out the accuracy. I calculated the r ... | -3 | 2016-06-13T13:40:54Z | 37,792,352 | <p>For regression problems, you can use the following metrics to determine the quality of the fit (<a href="http://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics" rel="nofollow">http://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics</a>): </p>
<ul>
<li>Mean squared er... | 0 | 2016-06-13T14:27:58Z | [
"python",
"scikit-learn"
] |
Delete all items except the item with highest value from a list of arrays | 37,791,351 | <p>Let's say I have a list of arrays like:</p>
<pre><code>list= [[(1,2),124,10001],[(1,2),124,10002],[(1,2),124,10003][(1,2),101,10001],...]
</code></pre>
<p>How could one extract all arrays with, in this case, the value 124 and sort these arrays by their last value and keep only the highest (here:10003). So that I'm... | 1 | 2016-06-13T13:41:17Z | 37,791,631 | <p>Not the most pythonic way but it still does the trick:</p>
<pre><code>l = [[(1,2),124,10001],[(1,2),124,10002],[(1,2),124,10003],[(1,2),101,10001]]
l.sort(key=lambda x: x[2], reverse=True)
l.sort(key=lambda x: x[1])
pr = None
lmax = []
for i in l:
if i[1] != pr:
lmax.append(i)
pr = i[1]
print lma... | 0 | 2016-06-13T13:56:15Z | [
"python",
"arrays"
] |
Delete all items except the item with highest value from a list of arrays | 37,791,351 | <p>Let's say I have a list of arrays like:</p>
<pre><code>list= [[(1,2),124,10001],[(1,2),124,10002],[(1,2),124,10003][(1,2),101,10001],...]
</code></pre>
<p>How could one extract all arrays with, in this case, the value 124 and sort these arrays by their last value and keep only the highest (here:10003). So that I'm... | 1 | 2016-06-13T13:41:17Z | 37,792,599 | <p>My attempt, with big disclaimer: this is my understanding of your question:</p>
<ul>
<li>have a list of lists of 3 elements: tuple, first index, second index</li>
<li>you would like to select one first index value (e.g. 124) and implode it - remove all items with first index is equal to chosen value, keeping only t... | 0 | 2016-06-13T14:38:28Z | [
"python",
"arrays"
] |
Why does my script keep looping over the files? Python | 37,791,366 | <p>Hi essentially my script below works but then once its looped and counted over all the files it then keeps doing it again and again. Is there something weird in my code?
I'm also using the dirs, files and, name variables in the code any help you could give would be great </p>
<pre><code>for root, dirs, files in ... | 0 | 2016-06-13T13:42:19Z | 37,791,520 | <p>you are opening your gzipped files in the the folder that you are walking over , this is creating another file for it to loop over when the files don't exist. This will trigger another iteration of os.walk as the new file arrives.</p>
| -1 | 2016-06-13T13:50:45Z | [
"python"
] |
Parse RSA key pair from string in Python | 37,791,368 | <p>I'm trying to generate/read a RSA-keypair from the publicKey and the privateKey as a String. </p>
<p>Something like this:</p>
<pre><code>priK = "-----BEGIN RSA PRIVATE KEY-----MIIBOQIBAAJAVJhUS0gLqXLOmVv2xG23oFPwim9+rVxGhLUXqKShQCvB3iRMOHn7/GNJumpwmnglcsNXuqAhN0OxqKGGJdtYdwIDAQABAkBP0VrXnSbDvvuIX+k59Xvo3sp7FDAmSoa... | 0 | 2016-06-13T13:42:23Z | 37,798,292 | <p><code>RSA.importKey(key)</code> imports one key. It cannot import concatenated keys. </p>
<p>If you import a private key, then you can extract a public key from that, because common PKCS#1 and PKCS#8 format have all the necessary information to create public key. So, you don't even need to concatenate the public ke... | 1 | 2016-06-13T20:08:47Z | [
"python",
"cryptography",
"rsa",
"pycrypto",
"key-pair"
] |
Serial comms from Arduino to RPi via pins | 37,791,375 | <p>I am stuck and dont know why. I am trying to transmit from an Arduino Nano to a RPi via the TX and Rx pins respectively. </p>
<p>This my code so far:</p>
<p>Arduino TX:</p>
<pre><code>void setup(){
Serial.begin(9600);
}
void loop(){
bProgramLoop = 1
while(bProgramLoop == 1){
Serial.write(1);
}
}
</co... | 0 | 2016-06-13T13:42:47Z | 37,800,305 | <p>I have found the a solution to the problem I am having. I am still a proper noob, but as far as I can figure it out, sending serial data over the Tx pin is problematic because it is used by the usb port and then to your PC. </p>
<p>Thus the solution is to use the SoftwareSerial library. I have modified my two code ... | 0 | 2016-06-13T22:44:20Z | [
"python",
"arduino",
"ide",
"raspberry-pi2",
"hardware-programming"
] |
comparing date using dd/mm/yy format in python | 37,791,386 | <p>I want to write a program where i can compare current date with couple of dates that i have.</p>
<p>my data is </p>
<p>12 JUN 2016</p>
<p>21 MAR 1989</p>
<p>15 MAR 1958</p>
<p>15 SEP 1958</p>
<p>23 OCT 1930</p>
<p>15 SEP 1928</p>
<p>10 MAR 2010</p>
<p>23 JAN 1928</p>
<p>15 NOV 1925</p>
<p>26 AUG 2009</p>
... | -3 | 2016-06-13T13:43:29Z | 37,791,526 | <p>You have to create a <code>datetime</code> object using the string data. You can create the object by parsing the date string using <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow">strptime</a> method.</p>
<pre><code>from datetime import datetime
mydate = datet... | 0 | 2016-06-13T13:51:01Z | [
"python",
"python-2.7",
"python-3.x"
] |
Numpy array value "contamination" | 37,791,468 | <p>I have a 2D numpy array filled with 0 and 1, and I would like to transform it so that every value neighboring a 1 is transformed to a 1 (hence the "contamination" in the title).</p>
<p>For example :</p>
<pre><code>0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 1 0 0 0
0 0 0 0 0 0
</code></pre>
<p>Becomes :</... | 1 | 2016-06-13T13:47:54Z | 37,791,800 | <p>That's basically <a href="https://en.wikipedia.org/wiki/Dilation_(morphology)" rel="nofollow"><code>dilation operation in Image-processing domain</code></a>. So, you can use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_dilation.html" rel="nofollow"><code>Scipy's... | 2 | 2016-06-13T14:04:33Z | [
"python",
"arrays",
"numpy",
"python-3.5"
] |
Numpy array value "contamination" | 37,791,468 | <p>I have a 2D numpy array filled with 0 and 1, and I would like to transform it so that every value neighboring a 1 is transformed to a 1 (hence the "contamination" in the title).</p>
<p>For example :</p>
<pre><code>0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 1 0 0 0
0 0 0 0 0 0
</code></pre>
<p>Becomes :</... | 1 | 2016-06-13T13:47:54Z | 37,791,821 | <p>The operation that you described is known as "binary dilation". There is an implementation in <code>scipy.ndimage</code>. For example,</p>
<pre><code>In [369]: a
Out[369]:
array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
... | 0 | 2016-06-13T14:05:18Z | [
"python",
"arrays",
"numpy",
"python-3.5"
] |
Compile libxgboost.so fail when install xgboost under cygwin of win10-64bit | 37,791,513 | <p>I use python under <strong>cygwin</strong> and now I need to install <strong>xgboost</strong>.</p>
<p>When I use xgboost in windows. I first use <strong>mingw</strong> to make <strong>libxgboost.dll</strong> and then use <code>python setup.py install</code> to successfully install.</p>
<p>But in cygwin, what I nee... | 0 | 2016-06-13T13:50:28Z | 37,793,617 | <p>fopen64 is defined on 32 bit to allow 64bit operation. However on cygwin 64 bit it should be replaced by fopen. </p>
<p>add some </p>
<pre><code>#if defined(__x86_64__)
#define fopen64 fopen
#endif
</code></pre>
<p>in </p>
<pre><code>./dmlc-core/src/io/local_filesys.cc
./dmlc-core/src/io/single_file_split.h
./ra... | 0 | 2016-06-13T15:25:18Z | [
"python",
"windows",
"cygwin",
"fopen",
"xgboost"
] |
Django: Access "through" model from ManyToManyField | 37,791,616 | <p>In Django (1.9) I want to access the implicitly defined intermediary model given the <code>field</code> that creates the relations. Let's say I have the models</p>
<pre><code>class Book(models.Model):
title = models.CharField(max_length=255)
author = models.ManyToManyField('Author')
class Author(models.Mod... | 0 | 2016-06-13T13:55:34Z | 37,791,617 | <p>The answer was quite simple. <code>Book._meta.get_field('author').remote_field.through</code> will indeed give you the same class as <code>Book.author.through</code>. This class is obviously callable a by using <code>through()</code> you instantiate a new instances of that class that are unequal to each other as ins... | 2 | 2016-06-13T13:55:34Z | [
"python",
"django",
"django-models"
] |
Python counting occurrence in a list: how to make it faster? | 37,791,622 | <p>I have a list of strings which contains about 6 millions items, and I am trying to count the occurrence for each of the unique values.</p>
<p>Here is my code:</p>
<pre><code>lines = [6 million strings]
unique_val = list(set(lines)) # contains around 500k items
mydict = {}
for val in unique_val:
mydict[val]... | 0 | 2016-06-13T13:55:49Z | 37,791,998 | <p>If you didn't want to use the <code>collections</code> module.</p>
<pre><code>counts = dict()
for line in lines:
counts[line] = counts.get(line,0) + 1
</code></pre>
<p>Or if you just don't want to use <code>Counter</code></p>
<pre><code>from collection import defaultdict
counts = defaultdict(int)
for line in ... | 1 | 2016-06-13T14:13:06Z | [
"python",
"performance",
"list",
"counting"
] |
Python counting occurrence in a list: how to make it faster? | 37,791,622 | <p>I have a list of strings which contains about 6 millions items, and I am trying to count the occurrence for each of the unique values.</p>
<p>Here is my code:</p>
<pre><code>lines = [6 million strings]
unique_val = list(set(lines)) # contains around 500k items
mydict = {}
for val in unique_val:
mydict[val]... | 0 | 2016-06-13T13:55:49Z | 37,792,025 | <p>How about this,</p>
<pre><code>from collections import defaultdict
import collections
lines = [600 million strings]
d = defaultdict(int)
for line in lines:
for word, count in collections.Counter(line).items():
d[word] += count
</code></pre>
| 1 | 2016-06-13T14:13:54Z | [
"python",
"performance",
"list",
"counting"
] |
Python counting occurrence in a list: how to make it faster? | 37,791,622 | <p>I have a list of strings which contains about 6 millions items, and I am trying to count the occurrence for each of the unique values.</p>
<p>Here is my code:</p>
<pre><code>lines = [6 million strings]
unique_val = list(set(lines)) # contains around 500k items
mydict = {}
for val in unique_val:
mydict[val]... | 0 | 2016-06-13T13:55:49Z | 37,792,046 | <p><strong>Numpy Solution</strong></p>
<p>I think numpy will give you the fastest answer, using <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.unique.html" rel="nofollow">unique</a>:</p>
<pre><code>result = dict(zip(*np.unique(lines, return_counts=True)))
</code></pre>
<p>Numpy is pretty h... | 1 | 2016-06-13T14:14:56Z | [
"python",
"performance",
"list",
"counting"
] |
Python counting occurrence in a list: how to make it faster? | 37,791,622 | <p>I have a list of strings which contains about 6 millions items, and I am trying to count the occurrence for each of the unique values.</p>
<p>Here is my code:</p>
<pre><code>lines = [6 million strings]
unique_val = list(set(lines)) # contains around 500k items
mydict = {}
for val in unique_val:
mydict[val]... | 0 | 2016-06-13T13:55:49Z | 37,792,385 | <p>Calling <code>list.count</code> is very expensive. Dictionary access (O(1) amortized time) and the <code>in</code> operator however are relatively cheap. The following snippet shows much better time complexity.</p>
<pre><code>def stats(lines):
histogram = {}
for s in lines:
if s in histogram:
... | 1 | 2016-06-13T14:29:12Z | [
"python",
"performance",
"list",
"counting"
] |
How do I do something like exec() with importing my variables? | 37,791,633 | <p>I'm trying to do something like this for a project:</p>
<pre><code>def printhi():
print("Hi")
myinput = input() # for example printhi()
exec(myinput)
</code></pre>
<p>Now I get an error, because exec() just starts a new session and ignores my functions and variables. How can I change that?</p>
| 1 | 2016-06-13T13:56:19Z | 37,791,701 | <p>The <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec</code></a> builtin takes two additional arguments that can be used to pass in the local and global scope:</p>
<pre><code>x = 10
exec("print(x)", globals(), locals()) # Prints "10"
</code></pre>
<p>Update: Given your examp... | 2 | 2016-06-13T13:59:32Z | [
"python",
"python-3.x"
] |
Scipy.optimize.minimize SLSQP with linear constraints fails | 37,791,680 | <p>Consider the following (convex) optimization problem:</p>
<pre><code>minimize 0.5 * y.T * y
s.t. A*x - b == y
</code></pre>
<p>where the optimization (vector) variables are <code>x</code> and <code>y</code> and <code>A</code>, <code>b</code> are a matrix and vector, respectively, of appropriate dimensions.</p>... | 0 | 2016-06-13T13:58:38Z | 37,792,650 | <p>You've run into the <a href="http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures" rel="nofollow">"late binding closures" <em>gotcha</em></a>. All the calls to <code>cons_i</code> are being made with the second argument equal to 19.</p>
<p>A fix is to use the <code>args</code> dictionary e... | 2 | 2016-06-13T14:40:30Z | [
"python",
"numpy",
"optimization",
"scipy"
] |
Display folders/files with different icons in QTreeView | 37,791,718 | <p>I have written a function in Python which goes through a specified directory and gets all its files and sub-folders recursively and filtering it to only list certain file formats. How do I display this in a treeview with an different icon for folders vs files?</p>
<p><strong>recursive directory function:</strong></... | 1 | 2016-06-13T14:00:50Z | 37,795,342 | <p>When adding a new item to the tree, it first has to find the item in the tree that it should be parented to. For example</p>
<pre><code>path = '/path/to/file.jpg'
</code></pre>
<p>To create this item in the tree, I first need to find the top-level item for <code>path</code>. Then, I need to find a child of that ... | 1 | 2016-06-13T17:00:49Z | [
"python",
"pyqt",
"pyside",
"qtreeview"
] |
Display folders/files with different icons in QTreeView | 37,791,718 | <p>I have written a function in Python which goes through a specified directory and gets all its files and sub-folders recursively and filtering it to only list certain file formats. How do I display this in a treeview with an different icon for folders vs files?</p>
<p><strong>recursive directory function:</strong></... | 1 | 2016-06-13T14:00:50Z | 38,027,571 | <p>Try to use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstandarditemmodel.html" rel="nofollow">QStandardItemModel</a> and <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qstandarditem.html" rel="nofollow">QStandardItem</a> when you build directory tree.</p>
<p>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4... | 0 | 2016-06-25T10:43:01Z | [
"python",
"pyqt",
"pyside",
"qtreeview"
] |
How do I fill a DataFrame from another DataFrame, adding rows and replacing nulls? | 37,791,719 | <p>I have two <code>pandas.DataFrame</code>s with overlapping columns and indices, like</p>
<pre><code>X = pandas.DataFrame({"A": ["A0", "A1", "A2"], "B": ["B0", None, "B2"]},
index=[0, 1, 2])
Y = pandas.DataFrame({"A": [V, "A3"], "B": ["B1", "B3"], "C": ["C1", "C3"]},
index=[... | 0 | 2016-06-13T14:00:55Z | 37,792,224 | <p>The <code>combine_first</code> method is half the deal, thanks to @IanS for pointing it out.</p>
<pre><code>>>> X.combine_first(Y)[list(X.columns)]
A B
0 A0 B0
1 A1 B1
2 A2 B2
3 A3 B3
</code></pre>
<p>Now, if <code>V</code> is nice, we should get the same result when <code>combine_first</cod... | 0 | 2016-06-13T14:23:13Z | [
"python",
"pandas"
] |
takes 1 positional argument but 2 were given | 37,791,744 | <p>hi i would like to run a command line tool to run in a separate function and passed to the button click the additional comando for this program but I get each time as respons </p>
<p><strong>takes 1 positional argument but 2 were given</strong></p>
<pre><code>from tkinter import *
import subprocess
class Stdo... | 1 | 2016-06-13T14:01:56Z | 37,792,143 | <p>It is because you are providing it a positional argument here: </p>
<pre><code>button = Button(self.parent, text="Check Device", command= self.adb("devices"))
</code></pre>
<p>command want's a callback function. and you are passing it the response from the <code>adb</code> method. (see here fore more: <a href="htt... | 3 | 2016-06-13T14:19:07Z | [
"python",
"python-3.x",
"tkinter",
"subprocess",
"popen"
] |
takes 1 positional argument but 2 were given | 37,791,744 | <p>hi i would like to run a command line tool to run in a separate function and passed to the button click the additional comando for this program but I get each time as respons </p>
<p><strong>takes 1 positional argument but 2 were given</strong></p>
<pre><code>from tkinter import *
import subprocess
class Stdo... | 1 | 2016-06-13T14:01:56Z | 37,794,301 | <p>The problem is in the way you declare <code>args</code>: it should be <code>*args</code> (one asterisk) instead of <code>**args</code> (two asterisks). One asterisk specifies any number of positional arguments, where as two asterisks means any number of named arguments.</p>
<p>Also, you need to pass <code>args</cod... | 1 | 2016-06-13T15:59:06Z | [
"python",
"python-3.x",
"tkinter",
"subprocess",
"popen"
] |
Pillow saving to BytesIO or StringIO KeyError: "JPG" | 37,791,782 | <p>I have a Pillow Image object image, that I try to save to an IO.BytesIO object called temp using <code>image.save(temp, format="jpg")</code></p>
<p>When I run this however, it gives a KeyError: "JPG" on this line <code>save_handler = SAVE[format.upper()]</code></p>
<p>Thanks!</p>
| 0 | 2016-06-13T14:03:35Z | 37,793,573 | <p>The format is called <code>jpeg</code>, not <code>jpg</code>, so just use:</p>
<pre><code>image.save(temp, format="jpeg")
</code></pre>
<p>See <a href="http://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html" rel="nofollow">Image file formats</a> for reference of possible values (or <code>PIL.Image... | 0 | 2016-06-13T15:23:18Z | [
"python",
"python-3.x",
"pillow",
"bytesio"
] |
python split array into runs/sequences - preferably numpy | 37,791,945 | <p>How can i split it into sequences/runs/subsequent-numbers, if the run is no longer than 3?</p>
<p>Having an array as follows</p>
<pre><code>[1, 2, 3, 5, 9, 10, 16, 17, 18, 19]
</code></pre>
<p>My expected output would be the following arrays:</p>
<ol>
<li><code>[1, 2, 3]</code></li>
<li><code>[5]</code></li>
<li... | 1 | 2016-06-13T14:10:52Z | 37,792,299 | <p>Something like this?</p>
<pre><code>def split_list(list, sub_list_size = 3):
sublists = []
for i in range(0, len(list), sub_list_size):
start = i
end = i + sub_list_size
sublists.append(list[start:end])
return sublists
# your list
mylist = [1,2,3,4,5,6,7,8, 9, 10, 11]
# your... | -1 | 2016-06-13T14:25:56Z | [
"python",
"arrays",
"numpy"
] |
python split array into runs/sequences - preferably numpy | 37,791,945 | <p>How can i split it into sequences/runs/subsequent-numbers, if the run is no longer than 3?</p>
<p>Having an array as follows</p>
<pre><code>[1, 2, 3, 5, 9, 10, 16, 17, 18, 19]
</code></pre>
<p>My expected output would be the following arrays:</p>
<ol>
<li><code>[1, 2, 3]</code></li>
<li><code>[5]</code></li>
<li... | 1 | 2016-06-13T14:10:52Z | 37,793,316 | <p>If you name your current list, <code>x</code> and the new list of output, <code>new_list</code>, you can try (untested and assumes no repeat values in original list)</p>
<pre><code>k = 0
new_list = [[]]
for i in range(len(x) - 1):
if x[i] not in new_list[max(k - 1, 0)]:
new_list[k].append(x[i])
... | 2 | 2016-06-13T15:12:14Z | [
"python",
"arrays",
"numpy"
] |
python split array into runs/sequences - preferably numpy | 37,791,945 | <p>How can i split it into sequences/runs/subsequent-numbers, if the run is no longer than 3?</p>
<p>Having an array as follows</p>
<pre><code>[1, 2, 3, 5, 9, 10, 16, 17, 18, 19]
</code></pre>
<p>My expected output would be the following arrays:</p>
<ol>
<li><code>[1, 2, 3]</code></li>
<li><code>[5]</code></li>
<li... | 1 | 2016-06-13T14:10:52Z | 37,802,458 | <p>Here's my version that uses <code>numpy</code>:</p>
<pre><code>import numpy as np
from itertools import chain
def split_list(mylist):
"""Function to do the initial split"""
# calculate differences
d = np.diff(mylist)
# when the differences are not 1 save that location
# we need a +1 to get make ... | 1 | 2016-06-14T03:27:01Z | [
"python",
"arrays",
"numpy"
] |
Unable to locate element (text-field) in Angular JS using selenium in Python | 37,791,957 | <p>I'm having a problem sending keys to a text field on an webpage written in angular JS.</p>
<p>Here is the WebElement in question:</p>
<pre><code><input name="CreateUserForename" id="Textc3829619-ad42-4df7-bbe3-5bdbe9fb9bce"
ng-class="{'ng-pristine': controller.$pristine, 'ng-invalid': controller.$invalid,
'... | 1 | 2016-06-13T14:11:19Z | 37,792,384 | <p>OK, it seems that <code>driver.find_element_by_name("CreateUserForename")</code> does the trick.</p>
| 0 | 2016-06-13T14:29:07Z | [
"python",
"angularjs",
"selenium"
] |
Failed Authentication Error while calling Australia Post Shipments API | 37,791,979 | <p>While following the example of <a href="https://developers.auspost.com.au/apis/shipping-and-tracking/reference/create-shipments" rel="nofollow">create-shipments</a> ,i am getting this error response </p>
<pre><code>{
"errors": [
{
"message": "The request failed authentication",
... | 0 | 2016-06-13T14:12:35Z | 37,919,477 | <p>Problem is solved, as <code>shipping/v1/shipments</code> required Basic Authorization so we need to set the header as
:</p>
<pre><code>headers={'Content-Type':'application/json',
'Authorization':'Basic '+base64.b64encode(API_Key+":"+Password_Secret),
'Account-Number':AccountNumber}
</code></pre>
<... | 0 | 2016-06-20T09:55:14Z | [
"python",
"json",
"rest",
"python-requests",
"shipping"
] |
OrderedDict Changing Order after Double Iterator Loop | 37,792,034 | <p>I set up an <code>OrderedDict</code> and perform dictionary comprehensions with different grammars, which I have simplified to a function <code>dictcomp(fn, dictionary, key_or_value):</code>:</p>
<pre><code> x = OrderedDict(self._Median_Colors)
x = self.dictcomp(hex2color, x, 'v')
x = self.dictcomp(rgb_t... | 0 | 2016-06-13T14:14:31Z | 37,793,303 | <p>The problem is because of</p>
<pre><code>for i, j in zip([4, 5, 6], [1, 2, 3]):
print i
print j
</code></pre>
<p>Results in the column:</p>
<p><code>4 1 5 2 6 3</code></p>
<p>It turns out that zip acts as a zipper if using two iterators.</p>
<p>The fix is to get the keyword-value as an iterable tuple:</... | 0 | 2016-06-13T15:11:45Z | [
"python",
"python-2.7",
"ordereddictionary"
] |
python get line+1 from text file | 37,792,074 | <p>I have a file I am looking for a particular sting called "$INGGA". My code prints all the lines with this string but I also want the string from the next line. How do I go about doing this? My current code is:</p>
<pre><code>with open(nmea) as nmeafile:
for num, line in enumerate(nmeafile, 1):
if "$INGG... | 1 | 2016-06-13T14:16:00Z | 37,792,186 | <p>The easier solution here is to place a conditional so that you print the next line when it's its turn in the iterator. Because if you try to print it in the turn before it may not be there (i.e. If $INGGA is the last line)</p>
<pre><code>should_print, text = False, ''
with open(nmea) as nmeafile:
for num, line ... | 1 | 2016-06-13T14:21:01Z | [
"python",
"string",
"file",
"text"
] |
python get line+1 from text file | 37,792,074 | <p>I have a file I am looking for a particular sting called "$INGGA". My code prints all the lines with this string but I also want the string from the next line. How do I go about doing this? My current code is:</p>
<pre><code>with open(nmea) as nmeafile:
for num, line in enumerate(nmeafile, 1):
if "$INGG... | 1 | 2016-06-13T14:16:00Z | 37,792,238 | <p>Here's my preferred method. Read the lines into a list, and then iterate through until the next to last element, preventing you from attempting to print a nonexistent line.</p>
<pre><code>with open("info.txt") as f:
lines = f.readlines()
for i in xrange(len(lines)-1):
if "$INGGA" in line:
... | 0 | 2016-06-13T14:23:47Z | [
"python",
"string",
"file",
"text"
] |
python get line+1 from text file | 37,792,074 | <p>I have a file I am looking for a particular sting called "$INGGA". My code prints all the lines with this string but I also want the string from the next line. How do I go about doing this? My current code is:</p>
<pre><code>with open(nmea) as nmeafile:
for num, line in enumerate(nmeafile, 1):
if "$INGG... | 1 | 2016-06-13T14:16:00Z | 37,792,444 | <p>You can use the <code>itertools</code> recipe <code>pairwise</code>, it will yield the current and the next line per iteration. You check the first one and yield both.</p>
<p>For a file </p>
<pre><code>asd
hello
$INGGA
argh
fpp
$INGGA
cake
sausage
</code></pre>
<p>it will return</p>
<pre><code>$INGGA
argh
$INGGA... | 0 | 2016-06-13T14:31:52Z | [
"python",
"string",
"file",
"text"
] |
Python: __file__ of the caller | 37,792,112 | <p>I want to define a utility function <code>f()</code> in my module <code>m</code> such that</p>
<ol>
<li>if <code>m.f()</code> is invoked in <code>/foo/a.py</code>, it returns <code>/foo/a.py</code></li>
<li>if <code>m.f()</code> invoked in <code>/bar/baz/b.py</code>, it returns <code>/bar/baz/b.py</code></li>
</ol>... | 2 | 2016-06-13T14:17:50Z | 37,792,259 | <p><code>__file__</code> is an attribute of the module loaded. So <code>m.__file__</code> will always give the path of the file from which <code>m</code> was loaded. To make it work for any module, you should call the attribute for that particular module.</p>
<pre><code>import module
def f(m): return m.__file__
prin... | 1 | 2016-06-13T14:24:22Z | [
"python"
] |
Python: __file__ of the caller | 37,792,112 | <p>I want to define a utility function <code>f()</code> in my module <code>m</code> such that</p>
<ol>
<li>if <code>m.f()</code> is invoked in <code>/foo/a.py</code>, it returns <code>/foo/a.py</code></li>
<li>if <code>m.f()</code> invoked in <code>/bar/baz/b.py</code>, it returns <code>/bar/baz/b.py</code></li>
</ol>... | 2 | 2016-06-13T14:17:50Z | 37,792,304 | <p>Take a look at the <code>inspect</code> module. It has a <a href="https://docs.python.org/3.5/library/inspect.html#inspect.stack" rel="nofollow">handy <code>stack()</code> method</a> that returns the entire call stack, each element of which includes the filename. You just need to extract the last one.</p>
| 1 | 2016-06-13T14:26:09Z | [
"python"
] |
Python: __file__ of the caller | 37,792,112 | <p>I want to define a utility function <code>f()</code> in my module <code>m</code> such that</p>
<ol>
<li>if <code>m.f()</code> is invoked in <code>/foo/a.py</code>, it returns <code>/foo/a.py</code></li>
<li>if <code>m.f()</code> invoked in <code>/bar/baz/b.py</code>, it returns <code>/bar/baz/b.py</code></li>
</ol>... | 2 | 2016-06-13T14:17:50Z | 37,792,573 | <p>some.py:</p>
<pre><code>m.f()
</code></pre>
<p>m.py:</p>
<pre><code>import inspect
import os
def f():
return os.path.relpath(
inspect.stack()[1][1],
basePath)
# returns path to caller file relative to some basePath
</code></pre>
| 1 | 2016-06-13T14:37:21Z | [
"python"
] |
Python How to avoid many if statements | 37,792,150 | <p>I'll try to simplify my problem. I'm writing a test program using py.test and appium. Now:</p>
<p>In the application I have 4 media formats: <strong>Video, Audio, Image and Document.</strong>
I have a control interface with <strong>previous, next, play , stop buttons.</strong>
Each media formats has a unique ID lik... | 1 | 2016-06-13T14:19:38Z | 37,803,231 | <p>You can separate out the selectors and operations in two dictionaries which <strong>scales better</strong>. Otherwise the mapping eventually gets huge. Here is the example.</p>
<pre><code>dictMedia = {'video':['video_playbutton', 'video_stopbutton','video_nextbutton'], 'audio':['audio_playbutton', 'audio_stopbutton... | 1 | 2016-06-14T04:52:03Z | [
"python",
"if-statement"
] |
How to read a text file and check against its contents with python | 37,792,187 | <p>I am attempting to read a text file, print its contents, and stop when it reaches the "flag". </p>
<p>My code is:</p>
<pre><code> import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
x = file.readline()
if x != "break":
print(x)
else:
... | 0 | 2016-06-13T14:21:06Z | 37,792,721 | <p>You better try the following:</p>
<p>It's possible <code>sys.path.append</code> does not do what you want (I'm not sure of this). It's better to use file's full path as first argument of open function.</p>
<pre><code>file = open("Full Path of your file", 'r')
line = file.readline()
while line:
if line == 'brea... | -1 | 2016-06-13T14:44:16Z | [
"python",
"string",
"text",
"variable-assignment"
] |
How to read a text file and check against its contents with python | 37,792,187 | <p>I am attempting to read a text file, print its contents, and stop when it reaches the "flag". </p>
<p>My code is:</p>
<pre><code> import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
x = file.readline()
if x != "break":
print(x)
else:
... | 0 | 2016-06-13T14:21:06Z | 37,793,345 | <p>Try something like,</p>
<pre><code>file = open("readmepython.txt", "r")
For line in file:
print line
</code></pre>
<p>or</p>
<pre><code>file = open("readmepython.txt", "r")
For line in file.readlines():
print line
</code></pre>
<p>see also:<a href="http://stackoverflow.com/questions/11726349/python-loopin... | 1 | 2016-06-13T15:13:07Z | [
"python",
"string",
"text",
"variable-assignment"
] |
How to read a text file and check against its contents with python | 37,792,187 | <p>I am attempting to read a text file, print its contents, and stop when it reaches the "flag". </p>
<p>My code is:</p>
<pre><code> import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
x = file.readline()
if x != "break":
print(x)
else:
... | 0 | 2016-06-13T14:21:06Z | 37,794,130 | <p>While many of the answers were extremely helpful for other issues I had, none explicitly answered the question.
<strike>I have used <a href="http://stackoverflow.com/a/37792721/4703192">Mr.Mean's</a> suggestion of .replace to clear up the hidden characters that are returned in text documents.</strike> <a href="http... | 0 | 2016-06-13T15:50:27Z | [
"python",
"string",
"text",
"variable-assignment"
] |
How to read a text file and check against its contents with python | 37,792,187 | <p>I am attempting to read a text file, print its contents, and stop when it reaches the "flag". </p>
<p>My code is:</p>
<pre><code> import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
x = file.readline()
if x != "break":
print(x)
else:
... | 0 | 2016-06-13T14:21:06Z | 37,795,906 | <pre><code>import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
x = file.readline().strip()
if x != "break":
print(x)
else:
break
</code></pre>
| 0 | 2016-06-13T17:35:11Z | [
"python",
"string",
"text",
"variable-assignment"
] |
String matching in lists - Python | 37,792,200 | <p>I have a list like below - from this i have filter the tables that begin with 'test:SF.AcuraUsage_' (string matching)</p>
<pre><code>test:SF.AcuraUsage_20150311
test:SF.AcuraUsage_20150312
test:SF.AcuraUsage_20150313
test:SF.AcuraUsage_20150314
test:SF.AcuraUsage_20150315
test:SF.AcuraUsage_20150316
test:SF.AcuraUs... | 0 | 2016-06-13T14:21:37Z | 37,792,289 | <p>List comprehensions are good for that. </p>
<p>Get a list with all the items that begin with 'test:SF.AcuraUsage_' :</p>
<pre><code>new_list = [x for x in list if x.startswith('test:SF.AcuraUsage_' ')]
</code></pre>
<p>Or the items that do <em>not</em> begin with 'test:SF.AcuraUsage_' :</p>
<pre><code>new_list =... | 0 | 2016-06-13T14:25:37Z | [
"python",
"string",
"list"
] |
String matching in lists - Python | 37,792,200 | <p>I have a list like below - from this i have filter the tables that begin with 'test:SF.AcuraUsage_' (string matching)</p>
<pre><code>test:SF.AcuraUsage_20150311
test:SF.AcuraUsage_20150312
test:SF.AcuraUsage_20150313
test:SF.AcuraUsage_20150314
test:SF.AcuraUsage_20150315
test:SF.AcuraUsage_20150316
test:SF.AcuraUs... | 0 | 2016-06-13T14:21:37Z | 37,792,318 | <p>You shouldn't name your list <code>list</code>, since it overrides the built-in type <code>list</code></p>
<p>But, if you'd like to filter that list using Python, consider using this list comprehension:</p>
<pre><code>acura = [x for x in list if x.startswith('test:SF.AcuraUsage')]
</code></pre>
<p>then, if you'd ... | 3 | 2016-06-13T14:26:56Z | [
"python",
"string",
"list"
] |
String matching in lists - Python | 37,792,200 | <p>I have a list like below - from this i have filter the tables that begin with 'test:SF.AcuraUsage_' (string matching)</p>
<pre><code>test:SF.AcuraUsage_20150311
test:SF.AcuraUsage_20150312
test:SF.AcuraUsage_20150313
test:SF.AcuraUsage_20150314
test:SF.AcuraUsage_20150315
test:SF.AcuraUsage_20150316
test:SF.AcuraUs... | 0 | 2016-06-13T14:21:37Z | 37,792,322 | <p>using re module:</p>
<pre><code>import re
for x in list:
ret = re.match('test:SF.AcuraUsage_(.*)',x)
if ret:
print(re.group())
</code></pre>
| 0 | 2016-06-13T14:27:08Z | [
"python",
"string",
"list"
] |
Class as decorator for class method | 37,792,257 | <p>I want to use a decorator to do some prepare job and record the status the function have , so I write something like that :</p>
<pre><code>class Decorator:
def __init__(self, func):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
self.count += 1 # Simply count t... | 1 | 2016-06-13T14:24:18Z | 37,793,945 | <p>As the decorator is only called once and replaces the method for all instance with one instance of the Decorator class. All it does is:
</p>
<pre><code>Foo.test = Decorator(Foo.test)
</code></pre>
<p>This makes it impossible to detect the instance called. One work-around would be to apply the decorator in the <cod... | 3 | 2016-06-13T15:41:43Z | [
"python",
"decorator"
] |
Class as decorator for class method | 37,792,257 | <p>I want to use a decorator to do some prepare job and record the status the function have , so I write something like that :</p>
<pre><code>class Decorator:
def __init__(self, func):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
self.count += 1 # Simply count t... | 1 | 2016-06-13T14:24:18Z | 37,794,310 | <p>I got this <a href="http://stackoverflow.com/questions/5469956/python-decorator-self-is-mixed-up">here</a></p>
<pre><code>import functools
class Decorator(object):
def __init__(self, func):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
self.count += 1 # Simp... | 0 | 2016-06-13T15:59:39Z | [
"python",
"decorator"
] |
Sqlalchemy in_ subquery | 37,792,261 | <p>I am trying to implement a select with a nested select clause, to find parents without any children. My tables (radically simplified) are as follows:</p>
<pre><code>class Person(Base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=True, default=None)
cl... | 1 | 2016-06-13T14:24:25Z | 37,796,647 | <p>Using a subquery:</p>
<pre><code>sub_stmt = config.Session.query(ChildTable.person_id)
stmt = config.Session.query(Person).filter(~Person.id.in_(sub_stmt))
empty_persons = stmt.all()
</code></pre>
<p>emits the following sql:</p>
<pre><code>SELECT person.id AS person_id, person.name AS person_name
FROM person
WHER... | 2 | 2016-06-13T18:20:56Z | [
"python",
"sqlalchemy"
] |
Matplotlib legend with line and area styles | 37,792,305 | <p>I am trying to plot a line and area graph in the same figure with a legend that displays both the line and area styles. Unfortunately the code below only produces lines and no areas in the legend. </p>
<p>Is it possible to get both lines and areas in the same legend? If not, can I get a second legend for the are... | 2 | 2016-06-13T14:26:21Z | 37,798,966 | <p>You can do it in the following way:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
# data
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)),
index=dates,
columns=lis... | 1 | 2016-06-13T20:56:33Z | [
"python",
"pandas",
"matplotlib"
] |
dnspython not updated when changing resolv.conf | 37,792,450 | <p>This snippet works perfect </p>
<pre><code>import dns
import dns.resolver
default = dns.resolver.get_default_resolver()
nameserver = default.nameservers[0]
</code></pre>
<p>except that if I change /etc/resolv.conf by hand and call again get_default_resolver function it doesn't bring me the updated address. I need... | 0 | 2016-06-13T14:32:02Z | 38,393,360 | <p>If you're on a non-Debian based Linux and using glibc then you have to be aware that glibc caches resolv.conf and won't look at it again unless explicitly told to. Essentially it is up to your application to tell glibc if resolv.conf has changed and needs to be reloaded by calling <code>__res_init</code>. See <a hre... | 1 | 2016-07-15T10:05:19Z | [
"python",
"dns",
"dnspython"
] |
Palindrome Linked List in Python with O(1) Extra Space | 37,792,532 | <p>This is the #234 Leetcode problem:</p>
<blockquote>
<p>Given a singly linked list, determine if it is a palindrome.</p>
<p>Follow up: Could you do it in O(n) time and O(1) space?</p>
</blockquote>
<p>This problem is easy to solve with O(n) space. However, I cannot figure out the O(1) solution. The only way ... | 0 | 2016-06-13T14:35:36Z | 37,792,715 | <p>If you are allowed to modify the list in place, you can do the following:</p>
<ol>
<li>Iterate over the list to count how many elements there are.</li>
<li>Iterate a second time, and starting from the middle of the list, reverse the pointers in the list nodes so that they point to the <em>previous</em> node rather ... | 3 | 2016-06-13T14:43:55Z | [
"python",
"algorithm",
"linked-list",
"palindrome"
] |
Transferring files via Python's ftplib nondeterministically times out | 37,792,538 | <p>I'm trying to use ftplib to transfer a set of files from my computer (running 64-bit Windows 7) to a Linux server. The process is similar to this snippet of test code (server address, username, and password changed, obviously):</p>
<pre><code>import ftplib
import os.path
import os
host = "some.ftp.server.com"
... | 0 | 2016-06-13T14:36:03Z | 37,792,601 | <p>When working with network requests in bulk, it's completely normal to get a certain number of timeouts - it's even expected. Rather than try to prevent timeouts from happening (because they always will), you should add logic to your application to handle cases where timeouts occur. Since you're uploading files in bu... | 0 | 2016-06-13T14:38:29Z | [
"python",
"ftp",
"timeout",
"ftplib"
] |
How to sort nth column columns in text file | 37,792,658 | <p>So my data looks like this:</p>
<pre class="lang-none prettyprint-override"><code>1 3456542 5 may 2014
2 1245678 4 may 2014
3 4256876 2 may 2014
4 5643156 6 may 2014
.....
</code></pre>
<p>I want to sort the 2nd column of 7 digit ID numbers from greatest to least. Also depending on the first number in the ID ... | -2 | 2016-06-13T14:40:54Z | 37,793,083 | <p>Assuming that your input data is text, I would start by separating lines from each other and columns within lines. See the <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> function for this.</p>
<p>The result should be a list of lists. You can then sort... | 0 | 2016-06-13T15:00:13Z | [
"python",
"sorting"
] |
How to sort nth column columns in text file | 37,792,658 | <p>So my data looks like this:</p>
<pre class="lang-none prettyprint-override"><code>1 3456542 5 may 2014
2 1245678 4 may 2014
3 4256876 2 may 2014
4 5643156 6 may 2014
.....
</code></pre>
<p>I want to sort the 2nd column of 7 digit ID numbers from greatest to least. Also depending on the first number in the ID ... | -2 | 2016-06-13T14:40:54Z | 37,793,089 | <p>"I wasn't asking for an answer, I was asking where to start conceptually."</p>
<p>Start reading the text file using <a href="http://www.tutorialspoint.com/python/file_readlines.htm" rel="nofollow"><code>file.readlines</code></a>, split the data using <a href="https://docs.python.org/2/library/stdtypes.html#str.spli... | 0 | 2016-06-13T15:00:26Z | [
"python",
"sorting"
] |
How to sort nth column columns in text file | 37,792,658 | <p>So my data looks like this:</p>
<pre class="lang-none prettyprint-override"><code>1 3456542 5 may 2014
2 1245678 4 may 2014
3 4256876 2 may 2014
4 5643156 6 may 2014
.....
</code></pre>
<p>I want to sort the 2nd column of 7 digit ID numbers from greatest to least. Also depending on the first number in the ID ... | -2 | 2016-06-13T14:40:54Z | 37,793,090 | <p>Heres my way of doing it:</p>
<pre><code>import csv
from operator import itemgetter
#read in file
file_lines = []
with open("test.txt", "r") as csv_file:
reader = csv.reader(csv_file, delimiter=" ")
for row in reader:
file_lines.append(row)
#sort
file_lines.sort(key=itemgetter(1))
#write sorted f... | 0 | 2016-06-13T15:00:27Z | [
"python",
"sorting"
] |
How to sort nth column columns in text file | 37,792,658 | <p>So my data looks like this:</p>
<pre class="lang-none prettyprint-override"><code>1 3456542 5 may 2014
2 1245678 4 may 2014
3 4256876 2 may 2014
4 5643156 6 may 2014
.....
</code></pre>
<p>I want to sort the 2nd column of 7 digit ID numbers from greatest to least. Also depending on the first number in the ID ... | -2 | 2016-06-13T14:40:54Z | 37,793,380 | <p>You could try using pandas. That makes it really easy.</p>
<pre><code>import pandas as pd
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
txt = StringIO('''
a b c d e
1 3456542 5 may 2014
2 1245678 4 may 2014
3 4256876 2 may 2014
4 564315... | 1 | 2016-06-13T15:15:22Z | [
"python",
"sorting"
] |
Accessing Big Query from Cloud DataLab using Pandas | 37,792,709 | <p>I have a Jypyter Notebook accessing Big Query using Pandas as the vehicle:</p>
<pre><code>df = pd.io.gbq.read_gbq( query, project_id = 'xxxxxxx-xxxx' )
</code></pre>
<p>This works fine from my local machine! (great, in fact!)
But when I load the same notebook to Cloud DataLab I get:</p>
<pre><code>DistributionNot... | 2 | 2016-06-13T14:43:39Z | 37,802,533 | <p>Google BigQuery authentication in pandas is normally straight forward, except when pandas code is executed on a remote server. For example, running pandas on Datalab in the cloud. In that case, use the following code to create the credentials file that pandas needs to access Google BigQuery in Google Datalab. </p>
... | 4 | 2016-06-14T03:34:38Z | [
"python",
"pandas",
"google-bigquery",
"google-cloud-datalab"
] |
how to create a matrix of tuples that is initialize with zeroes | 37,792,774 | <p>I am creating a picture and I use numpy.
I tried something like that but got an error
data = np.zeros((pic.size[0], pic.size[1],2),dtype= [[(0,0,0)],])
I am trying to make it look like</p>
<pre><code>[[(0,0,0),(0,0,0),(0,0,0)],[(0,0,0),(0,0,0)]]
</code></pre>
<p>how can i do it? i need to put this data in the... | 2 | 2016-06-13T14:46:32Z | 37,792,980 | <p>You can create a <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.zeros.html#numpy.zeros" rel="nofollow"><code>NumPy array of zeros</code></a>, split it at <code>3rd index</code> and then <a href="https://docs.python.org/3/library/functions.html?highlight=map#map" rel="nofollow"><code>map</c... | 0 | 2016-06-13T14:55:23Z | [
"python",
"image",
"numpy",
"matrix"
] |
how to create a matrix of tuples that is initialize with zeroes | 37,792,774 | <p>I am creating a picture and I use numpy.
I tried something like that but got an error
data = np.zeros((pic.size[0], pic.size[1],2),dtype= [[(0,0,0)],])
I am trying to make it look like</p>
<pre><code>[[(0,0,0),(0,0,0),(0,0,0)],[(0,0,0),(0,0,0)]]
</code></pre>
<p>how can i do it? i need to put this data in the... | 2 | 2016-06-13T14:46:32Z | 37,795,131 | <p>When I test your first line I get an error</p>
<pre><code>In [156]: data=np.zeros((3,4,2),dtype= [[(0,0,0)],])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-156-9f6f75b73353> in <module&... | 0 | 2016-06-13T16:48:37Z | [
"python",
"image",
"numpy",
"matrix"
] |
How do I kill a Python script in Java? | 37,792,785 | <p>I am launching a Python script in Java using <code>Runtime.getRuntime().exec("python myWebService.py")</code> and I am not doing anything else with it in Java. However, now I need to terminate the process from within my Java application. I've tried issuing a <code>pkill</code> command from the terminal, outside of t... | 0 | 2016-06-13T14:47:06Z | 37,792,841 | <p>The <code>Runtime.getRuntime().exec("python myWebService.py")</code> call returns a <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html" rel="nofollow">process</a>, that has a <code>destroy()</code> method to kill it. You can use that:
</p>
<pre><code>Process process = Runtime.getRuntime().exe... | 1 | 2016-06-13T14:50:05Z | [
"java",
"python",
"linux"
] |
python matplotlib anime multi-lines | 37,792,859 | <p>What is wrong with my code. Thanks in advance;
Help please. The code don't do what I want and draw 2 canvas;</p>
<pre><code>from scipy import stats
import numpy as np
import random
import matplotlib.pyplot as plt
import matplotlib.dates as md
from matplotlib import animation
import dateutil
from datetime import dat... | -2 | 2016-06-13T14:50:59Z | 37,834,731 | <p>The animation is still not working, but at least I only have one graph.
<code></p>
<pre> from scipy import stats
import numpy as np
import random
import matplotlib.pyplot as plt
import matplotlib.dates as md
from matplotlib import animation
import dateutil
from datetime import datetim... | 0 | 2016-06-15T11:53:56Z | [
"python",
"matplotlib"
] |
How to get a dictionary with the lowest key value | 37,792,901 | <p>This is my dictionary schema. </p>
<pre><code>f = { 'client_id': {'client_name': [{'transaction_date': date_time,
'transaction_amount': value_in_dollar}]
}
}
</code></pre>
<p>How to get a dictionary with the lowest transaction_amount.</p>
<p>Example inpu... | 1 | 2016-06-13T14:52:23Z | 37,793,072 | <p>You could use a big dict comprehension, or a helper function like this one:</p>
<pre><code>def get_min_by_value(x):
if isinstance(x, dict):
return {k: get_min_by_value(v) for k, v in x.items()}
elif isinstance(x, list):
return [min(x, key=lambda d: d['transaction_amount'])]
out = get_min_by_value(f)
</... | 3 | 2016-06-13T14:59:48Z | [
"python",
"dictionary"
] |
When to use pyodbc and when to use jaydebeapi in Python 2/3? | 37,792,956 | <p>As the title says, simple question...
When to use pyodbc and when to use jaydebeapi in Python 2/3?</p>
<p>Let me elaborate with a couple of example scenarios...</p>
<ol>
<li><p>If I were a solution architect and am looking at a Pyramid Web Server looking to access multiple RDBMS types (HSQLDB, Maria, Oracle, etc) ... | 0 | 2016-06-13T14:54:28Z | 37,793,124 | <p>Simple answer - until more details given in question:</p>
<p>In case you want to speak ODBC with the database: Go with pyodbc or for a pure python solution with pypyodbc</p>
<p>Else if you want to talk JDBC with the database try jaydebeapi </p>
<p>This should depend mor on the channel you want to use between pyth... | 0 | 2016-06-13T15:01:48Z | [
"python",
"python-3.x",
"pyodbc",
"jaydebeapi"
] |
Pandas drop_duplicates - TypeError: type object argument after * must be a sequence, not map | 37,792,999 | <p>I have updated my question to provide a clearer example. </p>
<p>Is it possible to use the drop_duplicates method in Pandas to remove duplicate rows based on a column id where the values contain a list. Consider column 'three' which consists of two items in a list. Is there a way to drop the duplicate rows rather t... | 1 | 2016-06-13T14:56:10Z | 37,833,378 | <p>I think it's because the list type isn't hashable and that's messing up the duplicated logic. As a workaround you could cast to tuple like so:</p>
<pre><code>df['four'] = df['three'].apply(lambda x : tuple(x) if type(x) is list else x)
df.drop_duplicates('four')
one three two fo... | 3 | 2016-06-15T10:51:47Z | [
"python",
"pandas",
"dataframe"
] |
Add a value if this value doesn't exist in dictionary | 37,793,011 | <p>I have a default dictionary. I loop through many strings and add them to the directory under the key as a number but only if there is no that value already in dictionary. So my code looks like this:</p>
<pre><code>from collections import defaultdict
strings = ["val1", "val2", "val2", "val3"]
my_dict = defaultdict(l... | 2 | 2016-06-13T14:56:52Z | 37,793,263 | <p>Notice that <code>my_dict.itervalues()</code> returns a list of lists in your case. So <code>string not in lists</code> always returns <code>True</code>, as you can see from the following code,</p>
<pre><code>>>> "val2" not in [["val1"], ["val2"]]
True
</code></pre>
<p>To get the desired result, flat a li... | 2 | 2016-06-13T15:09:41Z | [
"python",
"python-2.7"
] |
How does pip decide which many linux wheel to use? | 37,793,046 | <p>Binary many-linux wheels are now supported:</p>
<p><a href="https://github.com/pypa/manylinux" rel="nofollow">https://github.com/pypa/manylinux</a></p>
<p>Specifically I would like to install the many linux wheel for scipy on Travis, using the trusty beta operating system. The wheels are listed here:</p>
<p><a hr... | 2 | 2016-06-13T14:57:56Z | 37,793,161 | <p>You need pip 8.1 or later and a linux distribution that is based on glibc (and not musl libc as alpine linux for instance).</p>
<p>EDIT: the function <code>pip.pep425tags.get_supported()</code> should return the list of supported <a href="https://github.com/pypa/pip/blob/master/pip/pep425tags.py" rel="nofollow">pla... | 2 | 2016-06-13T15:03:40Z | [
"python",
"linux",
"scipy",
"pip",
"travis-ci"
] |
How does pip decide which many linux wheel to use? | 37,793,046 | <p>Binary many-linux wheels are now supported:</p>
<p><a href="https://github.com/pypa/manylinux" rel="nofollow">https://github.com/pypa/manylinux</a></p>
<p>Specifically I would like to install the many linux wheel for scipy on Travis, using the trusty beta operating system. The wheels are listed here:</p>
<p><a hr... | 2 | 2016-06-13T14:57:56Z | 37,806,211 | <p>So, the correct answer is that pip has a list of supported tags and will try to match those. <code>pip.pep425tags.get_supported()</code> will list the tags for your platform and will also use that list to match manylinux binary wheels.</p>
| 0 | 2016-06-14T07:59:07Z | [
"python",
"linux",
"scipy",
"pip",
"travis-ci"
] |
how can I solve this ERROR: Expected singleton candidat(1,2,3,4) | 37,793,063 | <pre><code>def _get_index_content(self, cr, uid, ids, fields, args, context=None):
res = dict.fromkeys(ids, '')
Attachment = self.pool.get('ir.attachment')
applicant_ids = self.pool.get('hr.applicant').search(cr, uid, [('email_from', '=', self.browse(cr, uid, ids, context=context).email_candidat)], context=... | 1 | 2016-06-13T14:58:50Z | 37,794,604 | <pre class="lang-py prettyprint-override"><code>applicant_ids = self.pool.get('hr.applicant').search(cr, user, [('email_from', '=', self.browse(cr, user, ids, context=context).email_candidat)], context=context)
</code></pre>
<p>won't work if ids is a list of 2 or more IDs. The browse will get a RecordSet of 2 entries,... | 1 | 2016-06-13T16:16:52Z | [
"python",
"openerp"
] |
Airflow Schedule_Interval Crontab syntax | 37,793,096 | <p>I want to confirm the correct syntax to perform my python scripts task every Monday at 9AM. Currently my script is set to send every Sunday morning at 12AM (0 0 * * 0).</p>
| 0 | 2016-06-13T15:00:33Z | 37,794,657 | <p>To set a schedule to fire every 5 minutes of the day, use the following "skip" entry of crontab:</p>
<pre><code>*/5 * * * *
</code></pre>
| 0 | 2016-06-13T16:19:40Z | [
"python",
"crontab",
"airflow"
] |
Specifying Dense using keras library | 37,793,144 | <p>I slightly misunderstand how to create a simple Sequence for my data.</p>
<p>The data has the following dimensions:</p>
<pre><code>X_train.shape
(2369, 12)
y_train.shape
(2369,)
X_test.shape
(592, 12)
y_test.shape
(592,)
</code></pre>
<p>This is how I create the model:</p>
<pre><code>batch_size = 128
nb_epoch... | 1 | 2016-06-13T15:02:59Z | 37,793,690 | <p>One of your problems is that you seem to misunderstand what a batch is.
A batch is the number of training samples computed at a time, so instead of computing one training sample from <code>X_train</code> at a time you use, for example, 100 at a time. The important bit here is that this has nothing to do with your mo... | 3 | 2016-06-13T15:28:54Z | [
"python",
"keras"
] |
Iterate over some chunks of data starting with certain strings | 37,793,180 | <p>I have worked on a program that could count the numbers of letters in a give data set, which start with <code>>chrome</code> followed by long chains of letters <code>(a,b,c,d at random)</code>.
The chunks of data exactly look like this:</p>
<p><code>("\n" shows space in the command line):
">chrome0001"\n"... | 0 | 2016-06-13T15:05:00Z | 37,793,484 | <p>This is a relatively straight forward parsing problem. First, you want to split the string on the <code>chromeXYZ\n</code> bits and group it with the following string. We can do this fairly easily with regular expressions -- Here's one that works if I understand your input correctly:</p>
<pre><code>>>> i... | 1 | 2016-06-13T15:19:35Z | [
"python",
"loops",
"if-statement"
] |
matplotlib contourf3d plot_surface vs. trisurf | 37,793,189 | <p>I'm trying to do <a href="http://matplotlib.org/examples/mplot3d/contourf3d_demo2.html" rel="nofollow">this</a> with my <a href="https://www.dropbox.com/s/y6jinlva9ey40ag/pes_d0.txt?dl=0" rel="nofollow">data</a> that has the following structure:</p>
<pre><code> 0.90000000 0.90000000 -2133.80472139
0.90000000 0... | 1 | 2016-06-13T15:05:42Z | 37,799,807 | <p>You have to use triangular contour and filled triangular contour:
<code>tricontour</code> and <code>tricontourf</code>: <a href="http://matplotlib.org/examples/pylab_examples/tricontour_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/tricontour_demo.html</a></p>
<p>I have added to you plot ... | 1 | 2016-06-13T21:57:22Z | [
"python",
"python-3.x",
"matplotlib"
] |
How to return values of variables from a function in Python 2.7? | 37,793,247 | <pre><code>import random
import time
#universal variables
attack = 1
defend = 2
heal = 3
v = False
player_health = 0
player_damage = 0
player_heal = 0
player_block = 0
ai_health = 0
ai_damage = 0
ai_heal = 0
ai_block = 0
#player classes in the form of dictionaries
sniper = {}
sniper["health"] = 50
sniper["damage"] ... | -2 | 2016-06-13T15:08:46Z | 37,793,367 | <p>In general to copy value of any variable use <code>copy.deepcopy</code> function:</p>
<pre><code>from copy import deepcopy
z = 1
x = {'a': {'z': 12}}
def copy_args(z, x):
copy_z = deepcopy(z)
copy_x = deepcopy(x)
return copy_z, copy_x
copy_z, copy_x = copy_args(z, x)
print(copy_z, copy_x)
</code></pr... | 0 | 2016-06-13T15:14:03Z | [
"python",
"python-2.7",
"function",
"variables"
] |
pass form name variable into url in django | 37,793,296 | <p>I would like to pass the <code>name</code> variable of a selected inputbox in my django template into a url without going through the django views or url.py. Is there an easy way to do this.</p>
<pre><code><div class="form-group">
<label class="col-xs-3 control-label">Chapter</label>
<d... | 0 | 2016-06-13T15:11:14Z | 37,793,779 | <p>You should do it through javascript.
Store your url value as a JS variable:</p>
<pre><code><script> my_url = "{% url 'api:by_book' 'name' %}"; </script>
</code></pre>
<p>Change the anchor to a button with a onClick event that calls a function.
In that function you can build the URL with my_url and reco... | 1 | 2016-06-13T15:33:22Z | [
"python",
"django"
] |
Fast Numpy Loops | 37,793,370 | <p>How do you optimize this code (<strong><em>without</em></strong> vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial):</p>
<pre><code>slow_lib.py:
import numpy as np
def foo():
size = 200
np.random.seed(1000031212)
bar = np.random.ran... | 11 | 2016-06-13T15:14:11Z | 37,793,744 | <p>Memory permitting, you can use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html"><code>np.einsum</code></a> to perform those heavy calculations in a vectorized manner, like so -</p>
<pre><code>moo = size*np.einsum('ij,ik->jk',bar,bar)
</code></pre>
<p>One can also use <a hre... | 7 | 2016-06-13T15:31:42Z | [
"python",
"numpy",
"vectorization",
"cython"
] |
Fast Numpy Loops | 37,793,370 | <p>How do you optimize this code (<strong><em>without</em></strong> vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial):</p>
<pre><code>slow_lib.py:
import numpy as np
def foo():
size = 200
np.random.seed(1000031212)
bar = np.random.ran... | 11 | 2016-06-13T15:14:11Z | 37,794,513 | <p>Here's the code for <code>outer</code>:</p>
<pre><code>def outer(a, b, out=None):
a = asarray(a)
b = asarray(b)
return multiply(a.ravel()[:, newaxis], b.ravel()[newaxis,:], out)
</code></pre>
<p>So each call to <code>outer</code> involves a number of python calls. Those eventually call compiled co... | 12 | 2016-06-13T16:11:37Z | [
"python",
"numpy",
"vectorization",
"cython"
] |
Fast Numpy Loops | 37,793,370 | <p>How do you optimize this code (<strong><em>without</em></strong> vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial):</p>
<pre><code>slow_lib.py:
import numpy as np
def foo():
size = 200
np.random.seed(1000031212)
bar = np.random.ran... | 11 | 2016-06-13T15:14:11Z | 37,796,522 | <p>Many tutorials and demonstrations of Cython, Numba, etc. make it seem as if these tools can speed up your code automagically, but in practice, this is often not the case: You'll need to modify your code a little to extract the best performance. If you had already implemented some degree of vectorization, it usually ... | 3 | 2016-06-13T18:13:11Z | [
"python",
"numpy",
"vectorization",
"cython"
] |
Fast Numpy Loops | 37,793,370 | <p>How do you optimize this code (<strong><em>without</em></strong> vectorizing, as this leads up to using the semantics of the calculation, which is quite often far from being non-trivial):</p>
<pre><code>slow_lib.py:
import numpy as np
def foo():
size = 200
np.random.seed(1000031212)
bar = np.random.ran... | 11 | 2016-06-13T15:14:11Z | 37,800,351 | <p>The example you show us is kind of inefficient algorithm, since you calculate the same outer product multiple times. The resulting time complexity is O(n^4). It can be reduced to n^3.</p>
<pre><code>for i in range(0,size):
val = bar[i]
moo += size * np.outer(val, val)
</code></pre>
| -1 | 2016-06-13T22:48:30Z | [
"python",
"numpy",
"vectorization",
"cython"
] |
feed a command a comma separated list of file names in a directory, extract a variable motif from file names for labels | 37,793,411 | <p>I have a directory containing files that look like this:</p>
<pre><code>1_reads.fastq
2_reads.fastq
89_reads.fastq
42_reads.fastq
</code></pre>
<p>I would like to feed a comma separated list of these file names to a command from a python program, so the input to the python command would like this:</p>
<pre><code>... | -2 | 2016-06-13T15:16:56Z | 37,793,827 | <p>Try this:</p>
<pre><code>program.py $(cd DIR && var=$(ls) && echo $var | tr ' ' ',')
</code></pre>
<p>That will pass to program.py the string returned by te command line inside the $(..). </p>
<p>That command line will: Enter in your directory, run ls storing the output in a variable, that will r... | 2 | 2016-06-13T15:35:34Z | [
"python",
"bash",
"terminal"
] |
feed a command a comma separated list of file names in a directory, extract a variable motif from file names for labels | 37,793,411 | <p>I have a directory containing files that look like this:</p>
<pre><code>1_reads.fastq
2_reads.fastq
89_reads.fastq
42_reads.fastq
</code></pre>
<p>I would like to feed a comma separated list of these file names to a command from a python program, so the input to the python command would like this:</p>
<pre><code>... | -2 | 2016-06-13T15:16:56Z | 37,794,010 | <p>First: This is a very poorly-thought-out calling convention. Don't use it.</p>
<p>However, if you're using software someone else wrote that already has that convention baked in...</p>
<pre><code>#!/bin/bash
IFS=, # use comma as separator
files=( [[:digit:]]*_* )
[[ -e $files || -L $files ]] || { echo "ERROR: No f... | 2 | 2016-06-13T15:44:26Z | [
"python",
"bash",
"terminal"
] |
feed a command a comma separated list of file names in a directory, extract a variable motif from file names for labels | 37,793,411 | <p>I have a directory containing files that look like this:</p>
<pre><code>1_reads.fastq
2_reads.fastq
89_reads.fastq
42_reads.fastq
</code></pre>
<p>I would like to feed a comma separated list of these file names to a command from a python program, so the input to the python command would like this:</p>
<pre><code>... | -2 | 2016-06-13T15:16:56Z | 37,794,182 | <p>It can be done easily in pure Bash. Make sure you run from within the directory that contains the files.</p>
<pre><code>#!/bin/bash
shopt -s extglob nullglob
# Create an array of files
f=( +([[:digit:]])_reads.fastq )
# Check that there are some files...
if ((${#f[@]}==0)); then
echo "No files found. Exiting... | 2 | 2016-06-13T15:53:00Z | [
"python",
"bash",
"terminal"
] |
how to change data type from byte to list when pulling data from api | 37,793,490 | <pre><code>from requests import Session
import json
import pandas as pd
query = '''SELECT referring_domain, event_name FROM cooladata LIMIT 5000000;'''
def SQLtoURL(query):
data = query.replace('\n', ' ').replace('\t',' ').replace(' ',' ').replace(' ',' ')
return data
def QueryCoola(query, file = None)... | -1 | 2016-06-13T15:19:46Z | 37,793,624 | <p>First of use <code>response.content</code> wich will give you the uninterpreted bytes requests received.</p>
<p>Do want to split the text on the newline character (<code>\n</code>) like </p>
<pre><code>your_list = data.split("\n")
</code></pre>
<p>This will give you this output:</p>
<pre><code>['"referring_domai... | -1 | 2016-06-13T15:25:31Z | [
"python",
"json",
"pandas",
"python-requests"
] |
MySQL Python query works alone but fails when parameterized | 37,793,669 | <p>Basically, I have a MySQL table like this: </p>
<pre><code>CREATE TABLE markets (
id INTEGER AUTO_INCREMENT NOT NULL,
root_symbol VARCHAR(64) NOT NULL,
metadata JSON NOT NULL,
PRIMARY KEY (id)
);
</code></pre>
<p>The metadata column contains a JSON document like this: </p>
<pre><code>metadata = ... | 1 | 2016-06-13T15:27:56Z | 37,793,806 | <p>You need to parameterize the whole field value for the <code>JSON_EXTRACT()</code>:</p>
<pre><code>cur.execute("""
SELECT root_symbol
FROM markets
WHERE JSON_EXTRACT(metadata, %s) = %s""", ('$.currency', "USD"))
cur.execute("""
SELECT root_symbol
FROM markets
WHERE JSON_EXTRACT(metadata, %s) ... | 1 | 2016-06-13T15:34:22Z | [
"python",
"mysql",
"json"
] |
Which exception for a missing external dependency? | 37,793,678 | <p>I have read that for <a href="http://stackoverflow.com/questions/37702938/list-python-dev-as-install-requires-in-setup-py">good reasons</a>, it's not possible to let <code>pip</code> resolve external dependencies (e.g. that are not available from PyPI).</p>
<p>My project requires two of them, so it should certainly... | 0 | 2016-06-13T15:28:28Z | 37,793,931 | <p>There is <code>exceptions.ImportError</code></p>
<p>Edit: Sorry, that's Python2, in Python3 it's just <code>ImportError</code>, as in</p>
<pre><code>raise ImportError('msg')
</code></pre>
| 0 | 2016-06-13T15:40:48Z | [
"python",
"python-3.x",
"exception",
"dependency-management"
] |
isinstance raising typeError when used on multiprocessing Lock | 37,793,716 | <p>I'm using the multiprocessing module on Python3.4. For some reason I get the following error using isinstance():</p>
<pre><code>>>> from multiprocessing import Lock
>>> isinstance(Lock(), Lock)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: isinstan... | 0 | 2016-06-13T15:30:22Z | 37,812,606 | <p>It seems that my PyCharm IDE was leading me to a different definition of Lock than the one being interpreted when <code>isinstance</code> is run. The latter is a function. The Lock class I was looking for is defined in <code>multiprocessing.synchronize.py</code></p>
<pre><code>>>> from multiprocessing impo... | 0 | 2016-06-14T12:52:49Z | [
"python",
"python-3.x",
"multiprocessing",
"pycharm",
"isinstance"
] |
First time organizing columns in text file | 37,793,771 | <p>I am a first time python user. I have a text file of star data that I need to sort the columns and then just take the data from the V band. I have no idea how to start. Can someone please help even if it's to just get me started?</p>
| -3 | 2016-06-13T15:32:54Z | 37,852,611 | <p>If you can install Pandas from <a href="http://pandas.pydata.org/pandas-docs/stable/install.html#installing-from-pypi" rel="nofollow">here</a> then sorting on any column can be done like this:</p>
<pre><code>#!/usr/bin/python
# read_stars.py
import sys
import pandas as pd
filename = sys.argv[1] # or 'star_data.... | 0 | 2016-06-16T07:29:49Z | [
"python"
] |
List Comprehension with IF clause | 37,793,826 | <p>Why below code is not working with IF condition in list comprehension? "Contents" does not exist in "response" to it should return empty list.</p>
<pre><code>response={"Contents1" : [ {"a" : 1, "b" : 1},{"a" : 2, "b" : 2},{"a" : 3, "b" : 3 } ] }
lst=[item["a"] for item in response["Contents"] if "Contents" in respo... | 1 | 2016-06-13T15:35:33Z | 37,794,040 | <p>The comprehension is still trying to access a dictionary with a non-existent key. You could do the following instead:</p>
<pre><code>[item["a"] for k in response for item in response[k] if k == "Contents"]
</code></pre>
| 1 | 2016-06-13T15:45:49Z | [
"python",
"python-2.7"
] |
How to write this ajax call in Python | 37,793,857 | <p>I have a ajax call but I have to call it from a Python script. This is the ajax call:</p>
<pre><code>$.ajax({
dataType: "json",
type: "GET",
url: "saytts",
data: {text: self.tts()}
});
</code></pre>
<p>I tried the package Requests but it's not working. Can someone translate this ajax call to a pyth... | 0 | 2016-06-13T15:37:04Z | 38,809,326 | <p>I had a similar question that was answered on <a href="https://www.experts-exchange.com/questions/28961884/Using-Python-I-want-to-pass-a-URL-some-json-and-get-back-data-imitating-Podbean's-jQuery-AJAX-function.html" rel="nofollow" title="Using Python, I want to pass a URL some json and get back data (imitati... | 0 | 2016-08-06T22:32:46Z | [
"python",
"ajax",
"request"
] |
R - how to embed HTML code into Jupyter notebook output? | 37,793,888 | <p>How can I do something like <a href="http://stackoverflow.com/questions/25698448/how-to-embed-html-into-ipython-output">this</a> using R? Actually I want to set Jupyter notebook cells width to 100%. In python this code works perfectly:</p>
<pre><code>from IPython.core.display import HTML, display
HTML("<style>... | 1 | 2016-06-13T15:38:47Z | 40,034,835 | <p>You can display html code in R using the <code>display_html</code> function <em>e.g.</em>,</p>
<pre><code>IRdisplay::display_html('<iframe src="http://www.w3schools.com" width=1000, height=1000></iframe> ')
</code></pre>
| 0 | 2016-10-14T04:15:46Z | [
"python",
"html",
"styles",
"jupyter-notebook"
] |
Open a url response in the browser | 37,793,923 | <p>I'm writing a script that makes a post request to a url, I'd then like to open the response page in the browser of the system. I'm having trouble finding out how. </p>
| 0 | 2016-06-13T15:40:32Z | 37,794,047 | <p>use <a href="https://docs.python.org/2/library/webbrowser.html" rel="nofollow">webbrowser</a> to open browser:</p>
<pre><code>webbrowser.open(url, new=0, autoraise=True)
webbrowser.open_new(url)
webbrowser.open_new_tab(url)
</code></pre>
<p>Update: the url is the local path of the response page file: <code>file://... | 1 | 2016-06-13T15:46:04Z | [
"python",
"bots"
] |
Open a url response in the browser | 37,793,923 | <p>I'm writing a script that makes a post request to a url, I'd then like to open the response page in the browser of the system. I'm having trouble finding out how. </p>
| 0 | 2016-06-13T15:40:32Z | 37,794,163 | <p>You could save the content to a local file and use <code>webbrowser.open_new("file://yourlocalfile.html")</code> but this has one major flaw:</p>
<p>Because of the browsers same origin policy this site could not load any external js, css or pictures.</p>
| 1 | 2016-06-13T15:52:00Z | [
"python",
"bots"
] |
How to get text from next pages using Beautifulsoup in python 3? | 37,793,929 | <p>Im trying to get all the game outcomes for every page for a team. So far I am able to get all the opponent 1 vs opponent 2 and score outcomes. But I don't know how to get the next page to get the rest of the data. Would I find the next page and put it in a while loop ? here is the link to the team I want</p>
<p><a ... | 1 | 2016-06-13T15:40:47Z | 37,794,008 | <p>Get the last page number and iterate page by page until you hit the last page.</p>
<p>Complete working code:</p>
<pre><code>import re
import requests
from bs4 import BeautifulSoup
url = "http://www.gosugamers.net/counterstrike/teams/7397-natus-vincere/matches"
with requests.Session() as session:
response = ... | 0 | 2016-06-13T15:44:19Z | [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup",
"html-parsing"
] |
Open page in Django using <button> instead of <a> | 37,793,998 | <p>I am creating my first Django app, and I am trying to open a template using a <code>button</code> tag. I have something like this here:</p>
<pre><code><button type="submit" onClick="window.location.href='details'">View</button>
</code></pre>
<p>In my <code>urls.py</code>, I have:</p>
<pre><code>url(r'... | 0 | 2016-06-13T15:43:38Z | 37,794,092 | <p>If you have <code>type="submit"</code>, sounds like you are using a form, right? If you do have a form, your url shouldn't be on the button but on the form <code>action</code> attribute.</p>
<p>You need to give your url a name, like:</p>
<pre><code>url(r'^details/$', TemplateView.as_view(template_name='details.htm... | 1 | 2016-06-13T15:48:39Z | [
"python",
"html",
"django"
] |
Open page in Django using <button> instead of <a> | 37,793,998 | <p>I am creating my first Django app, and I am trying to open a template using a <code>button</code> tag. I have something like this here:</p>
<pre><code><button type="submit" onClick="window.location.href='details'">View</button>
</code></pre>
<p>In my <code>urls.py</code>, I have:</p>
<pre><code>url(r'... | 0 | 2016-06-13T15:43:38Z | 37,794,145 | <p>It would be better to avoid javascript and just make a really simple form:</p>
<pre><code><form method="GET" action="{% url 'details_page' %}">
<button type="submit">View</button>
</form>
</code></pre>
<p>But you also need to name the route like so:</p>
<pre><code>url(r'^details/$', Te... | 0 | 2016-06-13T15:51:21Z | [
"python",
"html",
"django"
] |
Python Appending dictionary in Loop | 37,794,021 | <p>I have several netCDF data files with the same variables. I want to read in multiple data files and store all of the data in a giant dictionary. The problem with my code is that I can append the new dictionary, however, I can no longer separate the elements within the dictionary. For example:</p>
<pre><code>def p... | 0 | 2016-06-13T15:44:56Z | 37,794,203 | <p>Your problem is that you're appending lists to a list, creating a nested list, which is not what you want. </p>
<pre><code>>>> ls = []
>>> ls.append([1, 2, 3])
>>> ls
[[1, 2, 3]]
>>> ls[0]
[1, 2, 3]
</code></pre>
<p>There is, however, another method to add items to a list. It's... | 1 | 2016-06-13T15:53:54Z | [
"python",
"dictionary"
] |
Pandas Dataframe - RemoteDataError - Python | 37,794,095 | <p>I'm trying to pull data from yahoo finance. </p>
<p>Here is the error I'm getting:</p>
<pre><code>File "banana.py", line 35, in <module>
data = web.DataReader(ticker, "yahoo", datetime(2011,1,1), datetime(2015,12,31))
File "C:\Users\ll\Anaconda2\lib\site-packages\pandas_datareader\data.py", line 94, in... | 0 | 2016-06-13T15:48:42Z | 37,795,511 | <p><code>pandas_datareader</code> throws this error when yahoo does not make data for the <code>ticker</code> in question available through its API. </p>
<p>When reading your <code>.csv</code> file, you are including newline characters, so <code>pandas_datareader</code> doesn't recognize the tickers.</p>
<pre><code>d... | 1 | 2016-06-13T17:12:44Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Pandas Dataframe - RemoteDataError - Python | 37,794,095 | <p>I'm trying to pull data from yahoo finance. </p>
<p>Here is the error I'm getting:</p>
<pre><code>File "banana.py", line 35, in <module>
data = web.DataReader(ticker, "yahoo", datetime(2011,1,1), datetime(2015,12,31))
File "C:\Users\ll\Anaconda2\lib\site-packages\pandas_datareader\data.py", line 94, in... | 0 | 2016-06-13T15:48:42Z | 37,796,064 | <p>Try this:
You open the file but didnt <code>.read()</code> on it. </p>
<pre><code> input_file = open("testlist.csv", 'r').read()
</code></pre>
<p>Please run these: </p>
<pre><code>input_file = open("Companylistnysenasdaq.csv", 'r').read()
for x in input_file: print x
input_file = open("Companylistnysenasdaq.c... | 0 | 2016-06-13T17:45:06Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Sort list based on pattern | 37,794,129 | <p>I'd like to know how I can easily generate a list based on the values/order of two other lists:</p>
<pre><code>list_a = ['web1','web2','web3','web1','web4']
list_b = ['web2','web4','web1','web5','web1']
</code></pre>
<p>I'd like to retrieve the "list_b" list ordered by value from "list_a":</p>
<pre><code>final = ... | 1 | 2016-06-13T15:50:25Z | 37,794,338 | <p>An extremely simplistic way would be to just iterate over <code>list_a</code>, and should you find each element in <code>list_b</code> you remove it and append it to a list. Then after iterating all that remains in <code>list_b</code> are the elements that you need to add to the end of your list. </p>
<pre><code>li... | 1 | 2016-06-13T16:01:07Z | [
"python",
"list"
] |
Sort list based on pattern | 37,794,129 | <p>I'd like to know how I can easily generate a list based on the values/order of two other lists:</p>
<pre><code>list_a = ['web1','web2','web3','web1','web4']
list_b = ['web2','web4','web1','web5','web1']
</code></pre>
<p>I'd like to retrieve the "list_b" list ordered by value from "list_a":</p>
<pre><code>final = ... | 1 | 2016-06-13T15:50:25Z | 37,794,365 | <p>You can use the <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow">sorted</a> method to sort like this. To do this use the key parameter:
</p>
<pre><code>list_a = ['web1','web2','web3','web1','web4']
list_b = ['web2','web4','web1','web5','web1']
def getKey(element):
try:
r... | -2 | 2016-06-13T16:03:10Z | [
"python",
"list"
] |
try to normalize data ,but got TypeError: unhashable type | 37,794,151 | <p>I am trying to normalize my data frame using the first row of stock price. Below are my normalize function. </p>
<pre><code>def get_data(symbols, dates, addSPY=True, colname = 'Adj. Close'):
"""Read stock data (adjusted close) for given symbols from CSV files."""
##df = pd.DataFrame(index=dates)
for symbol in symb... | 0 | 2016-06-13T15:51:38Z | 37,795,100 | <p>Assuming you are starting with a <code>pd.DataFrame</code> with a single <code>column</code>, <code>'Adj.Close'</code>:</p>
<pre><code>s = pd.to_numeric(df.squeeze()) # alternatively to df.squeeze(), you could use df.loc[:, 'Adj. Close']
Adj. Close
Date
2016-06-09 153.42
2016-06-... | 1 | 2016-06-13T16:46:34Z | [
"python",
"pandas"
] |
Can I use more than 26 letters in `numpy.einsum`? | 37,794,245 | <p>I am using <code>np.einsum</code> to multiply probability tables like:</p>
<pre><code>np.einsum('ijk,jklm->ijklm', A, B)
</code></pre>
<p>The issue is that I am dealing with more than 26 random variables (axes) overall, so if I assign each random variable a letter I run out of letters. Is there another way I ca... | 4 | 2016-06-13T15:56:18Z | 37,795,166 | <p>If you are talking about the letters <code>ijk</code> in your example and having more then the available alphabetic characters, then no you can't.</p>
<p>In the einsum numpy code <a href="https://github.com/numpy/numpy/blob/9d3f4757fe7600efc9c77aa945bea9476fa9dcd0/numpy/core/src/multiarray/einsum.c.src#L1953" rel="... | 2 | 2016-06-13T16:50:07Z | [
"python",
"numpy",
"numpy-einsum"
] |
Can I use more than 26 letters in `numpy.einsum`? | 37,794,245 | <p>I am using <code>np.einsum</code> to multiply probability tables like:</p>
<pre><code>np.einsum('ijk,jklm->ijklm', A, B)
</code></pre>
<p>The issue is that I am dealing with more than 26 random variables (axes) overall, so if I assign each random variable a letter I run out of letters. Is there another way I ca... | 4 | 2016-06-13T15:56:18Z | 37,795,286 | <p>You could use the <code>einsum(op0, sublist0, op1, sublist1, ..., [sublistout])</code> form instead of <code>i,j,ik->ijk</code>, which the API is not restricted to 52 axes*. How this verbose form corresponds to the ijk form are shown <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum... | 2 | 2016-06-13T16:57:26Z | [
"python",
"numpy",
"numpy-einsum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.