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
listlengths
1
5
compare an array with two other arrays in python
38,609,502
<p>i have a set of 3 arrays which i would compare to eachother. array a contain a set of values and the values of array b and c should be partly the same.</p> <p>it is so that if let say <code>a[0] == b[0]</code> than is <code>c[0]</code> always a wrong value</p> <p>for better explanation i try to show what i mean.</p> <pre><code>import numpy as np a = np.array([2, 2, 3, 4]) b = np.array([1, 3, 3, 4]) c = np.array([2, 2, 4, 3]) print(a == b) # return: [False False True True] print(a == c) # return: [True True False False] </code></pre> <p>as you can see the from both sets i have two True and two False. so if one of both is true the total should be true. when i do the following i get a single True/ False for an array. and the answers are what i want...</p> <pre><code>print((a == b).all()) # return: False print((a == c).all()) # return: False print(a.all() == (b.all() or c.all())) # return: True </code></pre> <p>When i make the array b and c so that i have one vallue that in both cases is wrong i should end with a False</p> <pre><code>import numpy as np a = np.array([2, 2, 3, 4]) b = np.array([1, 3, 3, 4]) c = np.array([5, 2, 4, 3]) print(a == b) # return: [False False True True] print(a == c) # return: [False True False False] print((a == b).all()) # return: False print((a == c).all()) # return: False </code></pre> <p>So far so Good</p> <pre><code>print(a.all() == (b.all() or c.all())) # return: True </code></pre> <p>this part is not good this should be a False!! How do i get an or function like this so that i end with an True when for each value in <code>a</code> an same value exist in <code>b</code> or <code>c</code>??</p> <p>EDIT: explanation about <code>a[0] == b[0]</code> than is <code>c[0]</code>: i have an python function where phase information comes in and have to do some actions. before that i want check if i have to do with an array of imaginary values or with an array with phase angles. I want to check this before i do something. The problem is the phase angle because the right side is the inverted phase +/- pi. so for every value i have two options. and yes most of the time it is an exclusive or but in the case +/- pi/2 it is not since both are true and that is also fine...</p>
2
2016-07-27T09:50:02Z
38,610,395
<blockquote> <p>Actually all() function Return True if all elements of the iterable are true (or if the iterable is empty). And in programming language 0 is considered as false and any other integer is considered as true. So here in your array a,b,c every element is non zero and a.all(), b.all() and c.all() they all are seperately returning true so finally you are getting true.</p> </blockquote>
-1
2016-07-27T10:28:29Z
[ "python", "arrays", "python-3.x", "numpy" ]
PIL attribute error: Shape when creating an array
38,609,557
<p>I'm trying to warp two images of different sizes using PIL; specifically, by setting the shape (size) for future warped target image as a numpy array and I'm encountering AttributeError:</p> <p>File "C:\Anaconda2\lib\site-packages\PIL\Image.py", line 632, in <strong>getattr</strong> raise AttributeError(name) AttributeError: shape</p> <p>Why does this happen? I'm under the impression that I was doing this exact thing some time ago and it was working just fine, not to mention the fact that I absolutely don't understand what is it that python doesn't understand (the shape attribute should take this as an input with no problem)</p> <pre><code>import skimage.io from PIL import Image import numpy as np Img1 = Image.open(picture1 + ".png") Img1 Img2 = Image.open(picture2 + ".png") Img2 r, c = Img2.shape[:2] # creates array for the future shape in x,y corners = np.array([[0, 0], [0, r], [c, 0], [c, r]]) ... </code></pre> <p>Regards, JJ</p>
1
2016-07-27T09:52:37Z
38,609,730
<p>I think Image objects have <em>size</em> attributes and arrays have <em>shape</em> attributes. Try renaming it in your code. (See : <a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">http://effbot.org/imagingbook/image.htm</a>)</p>
1
2016-07-27T09:59:25Z
[ "python", "numpy", "scipy", "python-imaging-library" ]
Anaconda3 install PATH issue
38,609,561
<p>ISSUE FIXED: Restart fixed the issue.</p> <p>I've just finished installing Anaconda3 on Ubuntu 16.04. It automatically added the following line to .bashrc.</p> <blockquote> <p>export PATH="/home/username/anaconda3/bin:$PATH"</p> </blockquote> <p>However when I run python I still get the default python 2 version.</p> <blockquote> <p>printenv PATH</p> </blockquote> <p>gives me</p> <blockquote> <p>/home/username/anaconda/bin:/home/username/bin: ...</p> </blockquote> <p>What is causing the 3 to be dropped from the path?</p>
0
2016-07-27T09:52:48Z
38,609,999
<p>Fixed the issue with a simple restart. Still not sure where the original PATH without the 3 in it came from as I hadn't restarted before.</p>
0
2016-07-27T10:11:43Z
[ "python", "ubuntu", "path", "anaconda" ]
Python: TypeError: Only 2-D and 3-D images supported with scikit-image regionprops
38,609,599
<p>Given a <code>numpy.ndarray</code> of the kind</p> <pre><code>myarray= array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) </code></pre> <p>I want to use <code>scikit-image</code> on the array (which is already labelled) to derive some properties.</p> <p>This is what I do:</p> <pre><code>myarray.reshape((11,11)) labelled=label(myarray) props=sk.measure.regionprops(labelled) </code></pre> <p>But then I get this error: <code>TypeError: Only 2-D and 3-D images supported.</code>, pointing at <code>props</code>. <strong>What is the problem? The image I am passing to <code>props</code> is already a 2D object.</strong></p> <p>Shape of <code>myarray</code>:</p> <pre><code>In [17]: myarray Out[17]: array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) </code></pre>
0
2016-07-27T09:54:54Z
38,611,636
<p>I tried this code and I got no errors:</p> <pre><code>import numpy as np from skimage.measure import label, regionprops myarray = np.random.randint(1, 4, (11,11), dtype=np.int64) labelled = label(myarray) props = regionprops(labelled) </code></pre> <p>Sample output:</p> <pre><code>In [714]: myarray Out[714]: array([[1, 2, 1, 1, 3, 3, 1, 1, 3, 3, 3], [1, 1, 3, 1, 3, 2, 2, 2, 3, 3, 2], [3, 3, 3, 1, 3, 3, 1, 1, 2, 3, 1], [1, 3, 1, 1, 1, 2, 1, 3, 1, 3, 3], [3, 2, 3, 3, 1, 1, 2, 1, 3, 2, 3], [3, 2, 1, 3, 1, 1, 3, 1, 1, 2, 2], [1, 3, 1, 1, 1, 1, 3, 3, 1, 2, 2], [3, 3, 1, 1, 3, 2, 1, 2, 2, 2, 1], [1, 1, 1, 3, 3, 2, 2, 3, 3, 3, 1], [1, 2, 2, 2, 2, 2, 1, 3, 3, 2, 2], [3, 2, 2, 3, 1, 3, 3, 1, 3, 3, 2]], dtype=int64) In [715]: labelled Out[715]: array([[ 0, 1, 0, 0, 2, 2, 3, 3, 4, 4, 4], [ 0, 0, 5, 0, 2, 6, 6, 6, 4, 4, 7], [ 5, 5, 5, 0, 2, 2, 0, 0, 6, 4, 8], [ 9, 5, 0, 0, 0, 10, 0, 4, 0, 4, 4], [ 5, 11, 5, 5, 0, 0, 10, 0, 4, 12, 4], [ 5, 11, 0, 5, 0, 0, 13, 0, 0, 12, 12], [14, 5, 0, 0, 0, 0, 13, 13, 0, 12, 12], [ 5, 5, 0, 0, 15, 12, 0, 12, 12, 12, 16], [ 0, 0, 0, 15, 15, 12, 12, 17, 17, 17, 16], [ 0, 12, 12, 12, 12, 12, 18, 17, 17, 19, 19], [20, 12, 12, 21, 22, 17, 17, 18, 17, 17, 19]], dtype=int64) In [716]: props[0].area Out[716]: 1.0 In [717]: props[1].centroid Out[717]: (1.0, 4.4000000000000004) </code></pre> <p>I noticed that when all the elements of <code>myarray</code> have the same value (as in your example), <code>labelled</code> is an array of zeros. I also read this in the <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html?highlight=label#skimage.measure.regionprops" rel="nofollow"><code>regionprops</code></a> documentation:</p> <blockquote> <p><strong>Parameters:</strong> &nbsp;&nbsp;&nbsp; <strong>label_image</strong> : (N, M) ndarray<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Labeled input image. Labels with value 0 are ignored.</p> </blockquote> <p>Perhaps you should use a <code>myarray</code> with more than one distinct value in order to get meaningful properties...</p>
2
2016-07-27T11:25:40Z
[ "python", "numpy", "image-processing", "2d", "scikit-image" ]
How to move color scale labels to middle of colored fields in matplotlib/xarray?
38,609,648
<p>I have a heatmap with discrete values (=categories/factors), created as follows:</p> <pre><code>import xarray dats = xarray.DataArray([[2,4,3,5,1],[8,4,5,3,2], [9,3,4,4,1]]) dats.plot(levels=range(0, 11, 1), cmap='Blues') </code></pre> <p><a href="http://i.stack.imgur.com/lwGxI.png" rel="nofollow"><img src="http://i.stack.imgur.com/lwGxI.png" alt="Heatmap"></a></p> <p>I would like to move the numbers at the color scale / legend to the middle of the respective field. I (and colleagues) find their position at the intersection of fields a bit misleading, especially considering that the ticks at the x-axis in the heatmap itself are in the very middle of the fields. </p> <p>How can I move those values at the color scale up to the middle of the fields (and cut off the 10, which is not a value in the data set)?</p>
1
2016-07-27T09:56:39Z
38,610,350
<p>For this purpose you have to use matplotlib directly:</p> <pre><code>import xarray import matplotlib.pylab as plt dats = xarray.DataArray([[2,4,3,5,1],[8,4,5,3,2], [9,3,4,4,1]]) qm = dats.plot(levels=range(0, 11, 1), cmap='Blues', add_colorbar = False) cbar = plt.colorbar(qm) cbar.ax.get_yaxis().set_ticks([]) for j in range(0, 10, 1): cbar.ax.text(.5, (j+.5) / 10., j, ha='center', va='center', color='red') cbar.ax.get_yaxis().labelpad = 15 plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/GCfim.png" rel="nofollow"><img src="http://i.stack.imgur.com/GCfim.png" alt="enter image description here"></a></p>
2
2016-07-27T10:26:31Z
[ "python", "matplotlib", "colorbar", "categorical-data", "python-xarray" ]
Being told I have an infinite loop, but I'm unsure how to fix it. (Python Coding Course)
38,609,669
<p>I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.</p> <pre><code>num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num &lt; 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) # At this point the program should take your now factorial and give you the fibonacci sequence # takes your factorial and makes it the fibonacci nterms = factorial # first two terms n1 = 0 n2 = 1 count = 2 # check if the number of terms is valid if nterms &lt;= 0: print("Plese enter a positive integer") elif nterms == 1: print("Fibonacci sequence:") print(n1) else: print("Fibonacci sequence:") print(n1,",",n2,end=', ') while count &lt; nterms: nth = n1 + n2 print(nth,end=' , ') # update values n1 = n2 n2 = nth count += 1 </code></pre> <p>I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it. </p>
0
2016-07-27T09:57:18Z
38,609,811
<p>First, you already know what a loop is and how it works. You should review the loop in your code and make sure any variable used is defined. Since this is an assignment, this is the best I can do for you, to be honest your problem is already solved.</p> <p>Maybe try enclosing your code in a function with arguments/input-variables, this way your code might run smoother and better. Hope this helps.</p>
0
2016-07-27T10:03:07Z
[ "python" ]
Being told I have an infinite loop, but I'm unsure how to fix it. (Python Coding Course)
38,609,669
<p>I'm currently in a python coding class and this is an assignment. I apparently have an infinite loop somewhere in my code, yet I can't seem to find it.</p> <pre><code>num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num &lt; 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) # At this point the program should take your now factorial and give you the fibonacci sequence # takes your factorial and makes it the fibonacci nterms = factorial # first two terms n1 = 0 n2 = 1 count = 2 # check if the number of terms is valid if nterms &lt;= 0: print("Plese enter a positive integer") elif nterms == 1: print("Fibonacci sequence:") print(n1) else: print("Fibonacci sequence:") print(n1,",",n2,end=', ') while count &lt; nterms: nth = n1 + n2 print(nth,end=' , ') # update values n1 = n2 n2 = nth count += 1 </code></pre> <p>I've used both the debugging tool and attempted to find the problem myself by running the programming and attempting various break sequences but I'm just not grasping it. </p>
0
2016-07-27T09:57:18Z
38,610,188
<p>There is no infinite loop in your code, both loops will finish in finite time. What is happening is that your teacher, without looking at your code, has discovered that the finite time is very, very long and mistaken this for an infinite loop.</p> <p>The reason it's taking so long is that you have misunderstood the question - "I was asked to make a program that took an integer and gave me said factorial of an integer. Then give the Fibonacci sequence of the integer" - means find the factorial and Fibonacci sequence of the <em>same</em> integer rather than feeding the first result into the second. Simply replace the line <code>nterms = factorial</code> with the line <code>nterms = num</code> to fix the problem.</p> <p>(See comments on question for additional information used in this answer)</p>
2
2016-07-27T10:19:54Z
[ "python" ]
Create numpy array (contour) to be used with opencv functions
38,609,676
<p>I'm new to python and I don't know how to create numpy array that may be used in opencv functions. I've got two vectors defined as follows:</p> <pre><code>X=np.array(x_list) Y=np.array(y_list) </code></pre> <p>and the result is:</p> <pre><code>[ 250.78 250.23 249.67 ..., 251.89 251.34 250.78] [ 251.89 251.89 252.45 ..., 248.56 248.56 251.89] </code></pre> <p>I want to create opencv contour to be used in ex. <code>cv2.contourArea(contour)</code>. I read <a href="http://stackoverflow.com/questions/8369547/checking-contour-area-in-opencv-using-python">Checking contour area in opencv using python</a> but cannot write my contour numpy array properly. What's the best way to do that?</p>
2
2016-07-27T09:57:48Z
38,610,116
<p>Here's some example code, that first checks the dimensions of a contour calculated from a test image, and makes a test array and has success with that as well. I hope this help you!</p> <pre><code>import cv2 import numpy as np img = cv2.imread('output6.png',0) #read in a test image ret,thresh = cv2.threshold(img,127,255,0) im2,contours,hierarchy = cv2.findContours(thresh, 1, 2) cnt = contours[0] print cnt.shape #this contour is a 3D numpy array print cv2.contourArea(cnt) #the function prints out the area happily #######Below is the bit you asked about contour = np.array([[[0,0]], [[10,0]], [[10,10]], [[5,4]]]) #make a fake array print cv2.contourArea(contour) #also compatible with function </code></pre>
0
2016-07-27T10:16:35Z
[ "python", "opencv" ]
Multiple new columns dependent on other column value
38,609,684
<p>I have a dataframe that looks like this:</p> <p><code>Node Node1 Length Spaces Dist T 1 2 600 30 300 100 1 3 400 20 200 100 2 1 600 30 300 100 2 6 500 25 250 400 3 1 400 20 200 100 3 4 400 20 200 200 3 12 400 20 200 200 4 3 400 20 200 200 4 5 200 10 100 500 4 11 600 30 300 1400 5 4 200 10 100 500 5 6 400 20 200 200 5 9 500 25 250 800 6 2 500 25 250 400 6 5 400 20 200 200 6 8 200 10 100 800</code></p> <p>This tells us that, for example in the first row, there are 30 spaces between nodes 1 and 2. How could I create, say, 30 new columns with a value of 1 to represent each space seperately. Then do the same for each row.</p>
0
2016-07-27T09:58:09Z
38,612,696
<p>The code below should work (col 'A' is your 'NoSpaces'):</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD')) max_val = df['A'].max() for itr in range(max_val): colname = 'A%d' % itr df[colname] = (df['A'] &gt;=itr).astype('int') </code></pre>
0
2016-07-27T12:15:51Z
[ "python", "pandas" ]
Copy space delimited string columns to list
38,609,794
<p>I am trying to copy the content of a space delimited .txt file into separate lists corresponding to the columns, but I could not find a way to solve this.</p> <p>A sample of a .txt file is this:</p> <pre><code>Product 6153990c-14fa-47d2-81cf-a253f9294f96 - Date: 2016-06-29T09:47:27Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 3.08 GB Product cac95c2a-2d6e-477a-848f-caccbd219d39 - Date: 2016-06-29T09:47:27Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.32 GB Product c65147d3-ee3c-4f33-9e09-ea234d3543f7 - Date: 2016-06-29T09:40:32Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 4.00 GB Product fd1860e3-5d57-429e-b0c7-628a07b4bd5c - Date: 2016-06-27T09:03:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.25 GB Product ba8e4be4-502a-4986-94ce-d0f4dec23b5c - Date: 2016-06-27T09:03:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.52 GB Product b95cb837-6606-484b-89d6-b10bfaead9bd - Date: 2016-06-26T09:30:35Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.81 GB Product 96b64cfe-fc2e-4808-8356-2760d9671839 - Date: 2016-06-26T09:30:35Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.14 GB Product 20bb3c9e-bd15-417a-8713-3ece6090dd95 - Date: 2016-06-24T08:51:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 4.89 GB Product 5bf78d9b-a12b-4e54-aba7-299ae4ac0756 - Date: 2016-06-24T08:51:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.93 GB </code></pre> <p>If I split the file using the space delimiter, the columns will be (commas are included in some columns):</p> <pre><code>Product 59337094-226a-4d64-94b1-3fee5f5cbfe2 - Date: 2016-07-26T09:30:38Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.07 GB </code></pre> <p>What I tried doing is (example for the first column):</p> <pre><code>list = [] with open('D:\GIS\Sentinel\cmd_output.txt', 'r') as file: reader = csv.reader (file, delimiter = ' ') for a,b,c,d,e,f,g,h,i,j,k,l,m,n in reader: list.append(a) print list </code></pre> <p>But it doesn't work and send the error:</p> <blockquote> <p>ValueError: need more than 1 value to unpack</p> </blockquote> <p>How can I do this for each of the columns in file? Thanks!</p>
0
2016-07-27T10:02:21Z
38,610,051
<p>Your <code>reader</code> variable does not have the shape you think, see : <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">https://docs.python.org/2/library/csv.html#csv.reader</a> "Each row read from the csv file is returned as a list of strings."</p> <p>So you should probably try for your first column :</p> <pre><code>list = [] with open('D:\GIS\Sentinel\cmd_output.txt', 'r') as file: reader = csv.reader (file, delimiter = ' ') for row in reader: list.append(row[0]) print list </code></pre>
1
2016-07-27T10:13:42Z
[ "python", "list" ]
Copy space delimited string columns to list
38,609,794
<p>I am trying to copy the content of a space delimited .txt file into separate lists corresponding to the columns, but I could not find a way to solve this.</p> <p>A sample of a .txt file is this:</p> <pre><code>Product 6153990c-14fa-47d2-81cf-a253f9294f96 - Date: 2016-06-29T09:47:27Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 3.08 GB Product cac95c2a-2d6e-477a-848f-caccbd219d39 - Date: 2016-06-29T09:47:27Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.32 GB Product c65147d3-ee3c-4f33-9e09-ea234d3543f7 - Date: 2016-06-29T09:40:32Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 4.00 GB Product fd1860e3-5d57-429e-b0c7-628a07b4bd5c - Date: 2016-06-27T09:03:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.25 GB Product ba8e4be4-502a-4986-94ce-d0f4dec23b5c - Date: 2016-06-27T09:03:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.52 GB Product b95cb837-6606-484b-89d6-b10bfaead9bd - Date: 2016-06-26T09:30:35Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.81 GB Product 96b64cfe-fc2e-4808-8356-2760d9671839 - Date: 2016-06-26T09:30:35Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 6.14 GB Product 20bb3c9e-bd15-417a-8713-3ece6090dd95 - Date: 2016-06-24T08:51:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 4.89 GB Product 5bf78d9b-a12b-4e54-aba7-299ae4ac0756 - Date: 2016-06-24T08:51:49Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.93 GB </code></pre> <p>If I split the file using the space delimiter, the columns will be (commas are included in some columns):</p> <pre><code>Product 59337094-226a-4d64-94b1-3fee5f5cbfe2 - Date: 2016-07-26T09:30:38Z, Instrument: MSI, Mode: , Satellite: Sentinel-2, Size: 5.07 GB </code></pre> <p>What I tried doing is (example for the first column):</p> <pre><code>list = [] with open('D:\GIS\Sentinel\cmd_output.txt', 'r') as file: reader = csv.reader (file, delimiter = ' ') for a,b,c,d,e,f,g,h,i,j,k,l,m,n in reader: list.append(a) print list </code></pre> <p>But it doesn't work and send the error:</p> <blockquote> <p>ValueError: need more than 1 value to unpack</p> </blockquote> <p>How can I do this for each of the columns in file? Thanks!</p>
0
2016-07-27T10:02:21Z
38,610,085
<p>You can implement this with basic <code>split</code> like this.</p> <pre><code>file_pointer = open('a.txt') text = file_pointer.read() major_list = [] filtered_list = [i for i in text.split('\n') if i] for item in filtered_list: major_list.append(item.split()) first_row = [item[0] for item in major_list] second_row = [item[1] for item in major_list] #As may you want. </code></pre>
1
2016-07-27T10:15:18Z
[ "python", "list" ]
Python - How to avoid discrepancy of base y**log base y of x, in gmpy2
38,609,934
<p>The Following code examples my problem which does not occur between 10 power 10 and 10 power 11, but does for the example given in code and above it. </p> <p>I can't see where in my code I am not properly handling the retrieval of the original value. May be I have just missed something simple.</p> <p>I need to be sure that I can recover <code>x</code> from <code>log x</code> for various bases. Rather than rely on a library function such as <code>gmpy2</code>, is there any reverse <strong>anti-log</strong> algorithm which guarantees that for say <code>2**log2(x)</code> it will give <code>x</code>.</p> <p>I can see how to directly develop a log, but not how to get back, eg, Taylor series needs a lot of terms... <a href="http://stackoverflow.com/questions/2882706/how-can-i-write-a-power-function-myself">How can I write a power function myself?</a> and @dan04 reply. Code follows.</p> <pre><code>from gmpy2 import gcd, floor, next_prime, is_prime from gmpy2 import factorial, sqrt, exp, log,log2,log10,exp2,exp10 from gmpy2 import mpz, mpq, mpfr, mpc, f_mod, c_mod,lgamma from time import clock import random from decimal import getcontext x=getcontext().prec=1000 #also tried 56, 28 print(getcontext()) def rint():#check accuracy of exp(log(x)) e=exp(1) l2=log(2) l10=log(10) #x=random.randint(10**20,10**21) --replaced with an actual value on next line x=481945878080003762113 # logs to different bases x2=log2(x) x10=log10(x) xe=log(x) # logs back to base e x2e=xe/l2 x10e=xe/l10 # e2=round(2**x2) e10=round(10**x10) ex=round(e**xe) # ex2e=round(2**x2e) ex10e=round(10**x10e) error=5*x-(e2+e10+ex+ex2e+ex10e) print(x,"error sum",error) #print(x,x2,x10,xe) #print(x2e,x10e) print(e2,e10,ex) print(ex2e,ex10e) rint() </code></pre>
0
2016-07-27T10:08:42Z
38,614,637
<p>As long as you set the decimal module accuracy, the usual suggestion is to use Decimal datatype</p> <pre><code>from decimal import Decimal, getcontext getcontext().prec = 1000 # Just a different method to get the random number: x = Decimal(round(10**20 * (1 + 9 * random.random()))) x10 = Decimal.log10(x) e10 = 10**x10 e10 - x #outputs: Decimal('5.2E-978') </code></pre> <p>For different bases you may want to use the logarithmic formula:</p> <pre><code>x2 = Decimal.log10(x) / Decimal.log10(Decimal('2')) e2 = 2**x2 e2 - x #outputs: Decimal('3.9E-978') </code></pre>
1
2016-07-27T13:40:00Z
[ "python", "logarithm", "gmpy" ]
Python - How to avoid discrepancy of base y**log base y of x, in gmpy2
38,609,934
<p>The Following code examples my problem which does not occur between 10 power 10 and 10 power 11, but does for the example given in code and above it. </p> <p>I can't see where in my code I am not properly handling the retrieval of the original value. May be I have just missed something simple.</p> <p>I need to be sure that I can recover <code>x</code> from <code>log x</code> for various bases. Rather than rely on a library function such as <code>gmpy2</code>, is there any reverse <strong>anti-log</strong> algorithm which guarantees that for say <code>2**log2(x)</code> it will give <code>x</code>.</p> <p>I can see how to directly develop a log, but not how to get back, eg, Taylor series needs a lot of terms... <a href="http://stackoverflow.com/questions/2882706/how-can-i-write-a-power-function-myself">How can I write a power function myself?</a> and @dan04 reply. Code follows.</p> <pre><code>from gmpy2 import gcd, floor, next_prime, is_prime from gmpy2 import factorial, sqrt, exp, log,log2,log10,exp2,exp10 from gmpy2 import mpz, mpq, mpfr, mpc, f_mod, c_mod,lgamma from time import clock import random from decimal import getcontext x=getcontext().prec=1000 #also tried 56, 28 print(getcontext()) def rint():#check accuracy of exp(log(x)) e=exp(1) l2=log(2) l10=log(10) #x=random.randint(10**20,10**21) --replaced with an actual value on next line x=481945878080003762113 # logs to different bases x2=log2(x) x10=log10(x) xe=log(x) # logs back to base e x2e=xe/l2 x10e=xe/l10 # e2=round(2**x2) e10=round(10**x10) ex=round(e**xe) # ex2e=round(2**x2e) ex10e=round(10**x10e) error=5*x-(e2+e10+ex+ex2e+ex10e) print(x,"error sum",error) #print(x,x2,x10,xe) #print(x2e,x10e) print(e2,e10,ex) print(ex2e,ex10e) rint() </code></pre>
0
2016-07-27T10:08:42Z
38,630,610
<p>Aguy solved my problem, as acknowledged. I had not taken account of needing more than 15 digits of precision. This answer to another question covers that ground. <a href="http://stackoverflow.com/questions/33059198/gmpy2-log2-not-accurate-after-16-digits">gmpy2 log2 not accurate after 16 digits</a></p>
0
2016-07-28T08:10:37Z
[ "python", "logarithm", "gmpy" ]
Python - How to avoid discrepancy of base y**log base y of x, in gmpy2
38,609,934
<p>The Following code examples my problem which does not occur between 10 power 10 and 10 power 11, but does for the example given in code and above it. </p> <p>I can't see where in my code I am not properly handling the retrieval of the original value. May be I have just missed something simple.</p> <p>I need to be sure that I can recover <code>x</code> from <code>log x</code> for various bases. Rather than rely on a library function such as <code>gmpy2</code>, is there any reverse <strong>anti-log</strong> algorithm which guarantees that for say <code>2**log2(x)</code> it will give <code>x</code>.</p> <p>I can see how to directly develop a log, but not how to get back, eg, Taylor series needs a lot of terms... <a href="http://stackoverflow.com/questions/2882706/how-can-i-write-a-power-function-myself">How can I write a power function myself?</a> and @dan04 reply. Code follows.</p> <pre><code>from gmpy2 import gcd, floor, next_prime, is_prime from gmpy2 import factorial, sqrt, exp, log,log2,log10,exp2,exp10 from gmpy2 import mpz, mpq, mpfr, mpc, f_mod, c_mod,lgamma from time import clock import random from decimal import getcontext x=getcontext().prec=1000 #also tried 56, 28 print(getcontext()) def rint():#check accuracy of exp(log(x)) e=exp(1) l2=log(2) l10=log(10) #x=random.randint(10**20,10**21) --replaced with an actual value on next line x=481945878080003762113 # logs to different bases x2=log2(x) x10=log10(x) xe=log(x) # logs back to base e x2e=xe/l2 x10e=xe/l10 # e2=round(2**x2) e10=round(10**x10) ex=round(e**xe) # ex2e=round(2**x2e) ex10e=round(10**x10e) error=5*x-(e2+e10+ex+ex2e+ex10e) print(x,"error sum",error) #print(x,x2,x10,xe) #print(x2e,x10e) print(e2,e10,ex) print(ex2e,ex10e) rint() </code></pre>
0
2016-07-27T10:08:42Z
38,651,311
<p><em>Note: I maintain the <code>gmpy2</code> library.</em></p> <p>In your example, you are using <code>getcontext()</code> from the <code>decimal</code> module. You are not changing the precision used by <code>gmpy2</code>. Since the default precision of <code>gmpy2</code> is 53 bits and your value of x requires 69 bits, it is expected that you have an error.</p> <p>Here is a corrected version of your example that illustrates how the accumulated error changes as you increase the precision.</p> <pre><code>import gmpy2 def rint(n): gmpy2.get_context().precision = n # check accuracy of exp(log(x)) e = gmpy2.exp(1) l2 = gmpy2.log(2) l10 = gmpy2.log(10) x = 481945878080003762113 # logs to different bases x2 = gmpy2.log2(x) x10 = gmpy2.log10(x) xe = gmpy2.log(x) # logs back to base e x2e = xe/l2 x10e = xe/l10 # e2 = round(2**x2) e10 = round(10**x10) ex = round(e**xe) # ex2e = round(2**x2e) ex10e = round(10**x10e) error = 5 * x - (e2 + e10 + ex + ex2e + ex10e) print("precision", n, "value", x, "error sum", error) for n in range(65, 81): rint(n) </code></pre> <p>And here are the results.</p> <pre><code>precision 65 value 481945878080003762113 error sum 1061 precision 66 value 481945878080003762113 error sum 525 precision 67 value 481945878080003762113 error sum -219 precision 68 value 481945878080003762113 error sum 181 precision 69 value 481945878080003762113 error sum -79 precision 70 value 481945878080003762113 error sum 50 precision 71 value 481945878080003762113 error sum -15 precision 72 value 481945878080003762113 error sum -14 precision 73 value 481945878080003762113 error sum 0 precision 74 value 481945878080003762113 error sum -2 precision 75 value 481945878080003762113 error sum 1 precision 76 value 481945878080003762113 error sum 0 precision 77 value 481945878080003762113 error sum 0 precision 78 value 481945878080003762113 error sum 0 precision 79 value 481945878080003762113 error sum 0 precision 80 value 481945878080003762113 error sum 0 </code></pre>
1
2016-07-29T05:46:23Z
[ "python", "logarithm", "gmpy" ]
Flatten Pandas DataFrame from nested json list
38,609,971
<p>perhaps somebody could help me. I tried to flat the following ist into a pandas dataframe: </p> <pre><code>[{u'_id': u'2', u'_index': u'list', u'_score': 1.4142135, u'_source': {u'name': u'name3'}, u'_type': u'doc'}, {u'_id': u'5', u'_index': u'list', u'_score': 1.4142135, u'_source': {u'dat': u'2016-12-12', u'name': u'name2'}, u'_type': u'doc'}, {u'_id': u'1', u'_index': u'list', u'_score': 1.4142135, u'_source': {u'name': u'name1'}, u'_type': u'doc'}] </code></pre> <p>The result should look like:</p> <pre><code>|_id | _index | _score | name | dat | _type | ------------------------------------------------------ |1 |list |1.4142..| name1| nan | doc | |2 |list |1.4142..| name3| nan | doc | |3 |list |1.4142..| name1| 2016-12-12 | doc | </code></pre> <p>But all I tried to do is not possible to get the desired result. I used something like this:</p> <pre><code>df = pd.concat(map(pd.DataFrame.from_dict, res['hits']['hits']), axis=1)['_source'].T </code></pre> <p>But then I loose the types wich is outside the _source field. I also tried to work with</p> <pre><code>test = pd.DataFrame(list) for index, row in test.iterrows(): test.loc[index,'d'] = </code></pre> <p>But I have no idea how to come to the point to use the field _source and append it to the original data frame.</p> <p>Did somebody has an idea how to to that and become the desired outcome?</p>
1
2016-07-27T10:10:14Z
38,610,160
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow"><code>json_normalize</code></a>:</p> <pre><code>from pandas.io.json import json_normalize df = json_normalize(data) print (df) _id _index _score _source.dat _source.name _type 0 2 list 1.414214 NaN name3 doc 1 5 list 1.414214 2016-12-12 name2 doc 2 1 list 1.414214 NaN name1 doc </code></pre>
1
2016-07-27T10:18:48Z
[ "python", "json", "pandas", "dataframe", "nested" ]
Python beautifulsoup remove self closing tag
38,609,977
<p>I'm trying to remove the <code>br</code> tag from an html code by using beautifulsoup.</p> <p>html eg:</p> <pre><code>&lt;span class="qualification" style="font-size:14px; font-family: Helvetica, sans-serif;"&gt; Doctor of Philosophy ( Software Engineering ), Universiti Teknologi Petronas &lt;br&gt; Master of Science (Computer Science), Government College University Lahore &lt;br&gt; Master of Science ( Computer Science ), University of Agriculture Faisalabad &lt;br&gt; Bachelor of Science (Hons) ( Agriculture ),University of Agriculture Faisalabad &lt;br&gt;&lt;/span&gt; </code></pre> <p>My python code:</p> <pre><code> for link2 in soup.find_all('br'): link2.extract() for link2 in soup.findAll('span',{'class':'qualification'}): print(link2.string) </code></pre> <p>The problem is that the previous code only gets the first qualification.</p>
0
2016-07-27T10:10:38Z
38,610,230
<p>Because none of those <code>&lt;br&gt;</code>s have closing counterparts, Beautiful Soup adds them automatically thus producing the following HTML:</p> <pre><code>In [23]: soup = BeautifulSoup(html) In [24]: soup.br Out[24]: &lt;br&gt; Master of Science (Computer Science), Government College University Lahore &lt;br&gt; Master of Science ( Computer Science ), University of Agriculture Faisalabad &lt;br&gt; Bachelor of Science (Hons) ( Agriculture ),University of Agriculture Faisalabad &lt;br/&gt;&lt;/br&gt;&lt;/br&gt;&lt;/br&gt; </code></pre> <p>When you call <code>Tag.extract</code> on the first <code>&lt;br&gt;</code> tag you remove all of its descendants and strings its descendants contain:</p> <pre><code>In [27]: soup Out[27]: &lt;span class="qualification" style="font-size:14px; font-family: Helvetica, sans-serif;"&gt; Doctor of Philosophy ( Software Engineering ), Universiti Teknologi Petronas &lt;/span&gt; </code></pre> <p>It appears that you just have to extract all text from the <code>span</code> element. If that's the case, don't bother removing anything:</p> <pre><code>In [28]: soup.span.text Out[28]: '\nDoctor of Philosophy ( Software Engineering ), Universiti Teknologi Petronas\n\nMaster of Science (Computer Science), Government College University Lahore\n\nMaster of Science ( Computer Science ), University of Agriculture Faisalabad\n\nBachelor of Science (Hons) ( Agriculture ),University of Agriculture Faisalabad\n' </code></pre> <p>The <code>Tag.text</code> property extracts all strings from the given tag.</p>
1
2016-07-27T10:21:30Z
[ "python", "beautifulsoup" ]
Python beautifulsoup remove self closing tag
38,609,977
<p>I'm trying to remove the <code>br</code> tag from an html code by using beautifulsoup.</p> <p>html eg:</p> <pre><code>&lt;span class="qualification" style="font-size:14px; font-family: Helvetica, sans-serif;"&gt; Doctor of Philosophy ( Software Engineering ), Universiti Teknologi Petronas &lt;br&gt; Master of Science (Computer Science), Government College University Lahore &lt;br&gt; Master of Science ( Computer Science ), University of Agriculture Faisalabad &lt;br&gt; Bachelor of Science (Hons) ( Agriculture ),University of Agriculture Faisalabad &lt;br&gt;&lt;/span&gt; </code></pre> <p>My python code:</p> <pre><code> for link2 in soup.find_all('br'): link2.extract() for link2 in soup.findAll('span',{'class':'qualification'}): print(link2.string) </code></pre> <p>The problem is that the previous code only gets the first qualification.</p>
0
2016-07-27T10:10:38Z
38,610,239
<p>using unwrap should work</p> <pre><code>soup = BeautifulSoup(html) for match in soup.findAll('br'): match.unwrap() </code></pre>
0
2016-07-27T10:22:04Z
[ "python", "beautifulsoup" ]
Python beautifulsoup remove self closing tag
38,609,977
<p>I'm trying to remove the <code>br</code> tag from an html code by using beautifulsoup.</p> <p>html eg:</p> <pre><code>&lt;span class="qualification" style="font-size:14px; font-family: Helvetica, sans-serif;"&gt; Doctor of Philosophy ( Software Engineering ), Universiti Teknologi Petronas &lt;br&gt; Master of Science (Computer Science), Government College University Lahore &lt;br&gt; Master of Science ( Computer Science ), University of Agriculture Faisalabad &lt;br&gt; Bachelor of Science (Hons) ( Agriculture ),University of Agriculture Faisalabad &lt;br&gt;&lt;/span&gt; </code></pre> <p>My python code:</p> <pre><code> for link2 in soup.find_all('br'): link2.extract() for link2 in soup.findAll('span',{'class':'qualification'}): print(link2.string) </code></pre> <p>The problem is that the previous code only gets the first qualification.</p>
0
2016-07-27T10:10:38Z
38,610,588
<p>Here's a way to do it:</p> <pre><code>for link2 in soup.findAll('span',{'class':'qualification'}): for s in link2.stripped_strings: print(s) </code></pre> <p>It's not necessary to remove the <code>&lt;br&gt;</code> tags, unless you require them removed for later processing. Here <code>link2.stripped_strings</code> is a generator that yields each string in the tag, stripped of leading and trailing whitespace. The print loop can be written more succinctly as:</p> <pre><code>for link2 in soup.findAll('span',{'class':'qualification'}): print(*link2.stripped_strings, sep='\n') </code></pre>
0
2016-07-27T10:37:38Z
[ "python", "beautifulsoup" ]
Pandas compare columns of list
38,610,042
<p>I have columns in my DataFrame storing <code>lists</code> and I would like to compare each element in the column with a <code>lists</code>.</p> <p>All the methods I have tried fails:</p> <pre><code>df.list_col == ['3', '4'] df.list_col.isin([['3', '4']]) df.list_col.equals(['3', '4']) </code></pre> <p>Is there a simple solution to this?</p>
1
2016-07-27T10:13:27Z
38,610,111
<p>You can use <code>apply</code> with <code>in</code>:</p> <pre><code>df = pd.DataFrame({'A':[[1,2],[2,4],[3,1]], 'B':[4,5,6]}) print (df) A B 0 [1, 2] 4 1 [2, 4] 5 2 [3, 1] 6 print (df.A.apply(lambda x: 2 in x)) 0 True 1 True 2 False Name: A, dtype: bool </code></pre>
2
2016-07-27T10:16:17Z
[ "python", "list", "pandas", "dataframe", "comparison" ]
How do I get the text decoding of the Chinese?
38,610,329
<p>Python in the Chinese part of the result of requests.get (url) is </p> <p>"æ ?? ¯ä¸? ǧ? Å? ¯ä» ¥ è ?? ªç? ± å? ¼å? ¸ç? ??? Æ ???? è§? ï¼ "</p> <p>came out in this way.</p> <p>How it is necessary to decode Can you print Chinese characters?</p> <p>In the following method, source and other statements will be output.</p> <ol> <li>result.content.decode("gbk","ignore").encode("utf-8","ignore")</li> <li>content.encode('utf-8').decode('gbk')</li> </ol> <p>Example of a site is here. <a href="https://lvyou.baidu.com/notes/20fd27d671563fe1e8927d21?sid=9739db6e97289b7e6b22f9ea?request_id=831992042&amp;idx=0" rel="nofollow">https://lvyou.baidu.com/notes/20fd27d671563fe1e8927d21?sid=9739db6e97289b7e6b22f9ea?request_id=831992042&amp;idx=0</a></p> <p>Let us know would really appreciate.</p>
-2
2016-07-27T10:25:27Z
38,649,228
<p>The problem has been resolved.</p> <p>Set the encoding option in requests, we were able to obtain the required value.</p> <p>Thank you very much.</p> <pre><code>sub_result = requests.get(sub_url) sub_result.encoding = 'utf-8' sub_soup = BeautifulSoup(sub_result.text, 'lxml') </code></pre>
0
2016-07-29T01:40:46Z
[ "python", "encoding", "utf-8", "python-requests" ]
How to convert a dash separated range to several entries with "X" when difference is 9 in Python
38,610,354
<p>let me try to explain what I´m trying to do:</p> <p>I have a range like this: <code>20934-21021</code></p> <p>I´m trying to figure out a way to get an output like:</p> <pre><code>20934,20935,20936,20937,20938,20939,2094X,2095X,2096X,2097X,2098X,2099X,2100X,2101X,21020,21021 </code></pre> <p>Currently I´m just getting the difference between both numbers and getting the output increasing the number by one each time but I would be looking for something more appropriate. </p> <p>Current code:</p> <pre><code>import re text = "20934-21021" startRange = re.findall(r'(\d*)-', text) endRange = re.findall(r'-(\d*)', text) while int(startRange[0]) &lt;= int(endRange[0]): print int(startRange[0]) startRange[0]= int(startRange[0]) +1 </code></pre> <p>Any ideas?</p> <p>PS: values are stored in a list and using <code>findall</code> because the same line can contain several ranges.</p> <p>EDIT: The aim is to simplify the output (string) from: 20934,20935,20936,20937,20938,20939,20940,20941.... To a format where any range which is 0-9 will be replaced by an X: 20934,20935,20936,20937,20938,20939,2094X,2095X...</p> <p>If the difference is bigger, it would do the same for the rest of the digits, i.e: Range= 20119-22400 Output: 20119,2012X,2013X,2014X,2015X,2016X,2017X,2018X,2019X,202XX,203XX,204XX,205XX,206XX,207XX,208XX,209XX,21XXX,220XX,221XX,222XX,223XX,22400</p>
-1
2016-07-27T10:26:44Z
38,610,524
<p>The <code>range</code> function can do this for you. In Python 2 it returns a list, in Python 3 it's a generator, but these differences don't matter for the code you need.</p> <pre><code>text = "20934-21021" start, end = text.split("-") start = int(start) # needs error checks end = int(end) # as does this result = ",".join(str(i) for i in range(start, end+1)) </code></pre>
-1
2016-07-27T10:34:18Z
[ "python", "regex" ]
How to convert a dash separated range to several entries with "X" when difference is 9 in Python
38,610,354
<p>let me try to explain what I´m trying to do:</p> <p>I have a range like this: <code>20934-21021</code></p> <p>I´m trying to figure out a way to get an output like:</p> <pre><code>20934,20935,20936,20937,20938,20939,2094X,2095X,2096X,2097X,2098X,2099X,2100X,2101X,21020,21021 </code></pre> <p>Currently I´m just getting the difference between both numbers and getting the output increasing the number by one each time but I would be looking for something more appropriate. </p> <p>Current code:</p> <pre><code>import re text = "20934-21021" startRange = re.findall(r'(\d*)-', text) endRange = re.findall(r'-(\d*)', text) while int(startRange[0]) &lt;= int(endRange[0]): print int(startRange[0]) startRange[0]= int(startRange[0]) +1 </code></pre> <p>Any ideas?</p> <p>PS: values are stored in a list and using <code>findall</code> because the same line can contain several ranges.</p> <p>EDIT: The aim is to simplify the output (string) from: 20934,20935,20936,20937,20938,20939,20940,20941.... To a format where any range which is 0-9 will be replaced by an X: 20934,20935,20936,20937,20938,20939,2094X,2095X...</p> <p>If the difference is bigger, it would do the same for the rest of the digits, i.e: Range= 20119-22400 Output: 20119,2012X,2013X,2014X,2015X,2016X,2017X,2018X,2019X,202XX,203XX,204XX,205XX,206XX,207XX,208XX,209XX,21XXX,220XX,221XX,222XX,223XX,22400</p>
-1
2016-07-27T10:26:44Z
38,611,655
<p>Here is my proposed solution:</p> <pre><code>&gt;&gt;&gt; def range_x(s): start, end = s.split('-') result = '' if start[-1] == '0': string1 = start[:-1]+'X' else: r1 = range(int(start[-1]), 10) string1 = ','.join(map(lambda i:start[:-1]+str(i), r1)) r2 = range(int(start[:-1])+1, int(end[:-1])) string2 = ','.join(map(lambda i: str(i) + 'X', r2)) if end[-1] == '0': string3 = end[:-1]+'X' else: r3 = range(0,int(end[-1])+1) string3 = ','.join(map(lambda i: end[:-1]+str(i), r3)) result = ','.join([string1, string2, string3]) return result &gt;&gt;&gt; s = '20930-21020' &gt;&gt;&gt; range_x(s) '2093X,2094X,2095X,2096X,2097X,2098X,2099X,2100X,2101X,2102X' &gt;&gt;&gt; s = '20934-21021' &gt;&gt;&gt; range_x(s) '20934,20935,20936,20937,20938,20939,2094X,2095X,2096X,2097X,2098X,2099X,2100X,2101X,21020,21021' </code></pre>
1
2016-07-27T11:26:47Z
[ "python", "regex" ]
How to convert a dash separated range to several entries with "X" when difference is 9 in Python
38,610,354
<p>let me try to explain what I´m trying to do:</p> <p>I have a range like this: <code>20934-21021</code></p> <p>I´m trying to figure out a way to get an output like:</p> <pre><code>20934,20935,20936,20937,20938,20939,2094X,2095X,2096X,2097X,2098X,2099X,2100X,2101X,21020,21021 </code></pre> <p>Currently I´m just getting the difference between both numbers and getting the output increasing the number by one each time but I would be looking for something more appropriate. </p> <p>Current code:</p> <pre><code>import re text = "20934-21021" startRange = re.findall(r'(\d*)-', text) endRange = re.findall(r'-(\d*)', text) while int(startRange[0]) &lt;= int(endRange[0]): print int(startRange[0]) startRange[0]= int(startRange[0]) +1 </code></pre> <p>Any ideas?</p> <p>PS: values are stored in a list and using <code>findall</code> because the same line can contain several ranges.</p> <p>EDIT: The aim is to simplify the output (string) from: 20934,20935,20936,20937,20938,20939,20940,20941.... To a format where any range which is 0-9 will be replaced by an X: 20934,20935,20936,20937,20938,20939,2094X,2095X...</p> <p>If the difference is bigger, it would do the same for the rest of the digits, i.e: Range= 20119-22400 Output: 20119,2012X,2013X,2014X,2015X,2016X,2017X,2018X,2019X,202XX,203XX,204XX,205XX,206XX,207XX,208XX,209XX,21XXX,220XX,221XX,222XX,223XX,22400</p>
-1
2016-07-27T10:26:44Z
38,611,766
<p>Here is my solution. </p> <p>There are places for optimization, but I tried to make it easy and straight forward. </p> <pre><code>a,b = map(int, '20934-21021'.split('-')) output_str = '' l = (a/10 + 1) * 10 u= (b/10) * 10 output_str += ','.join(map(str, range(a,l))) output_str += ',' lower = a/10 + 1 upper = b/10 -1 output_str +=','.join(["{0}X".format(i) for i in range(lower, upper+1)]) output_str += ',' output_str += ','.join(map(str,range(u, b+1))) print output_str </code></pre> <p>Output:</p> <pre><code>20934,20935,20936,20937,20938,20939,2094X,2095X,2096X,2097X,2098X,2099X, 2100X,2101X,21020,21021 </code></pre>
1
2016-07-27T11:32:21Z
[ "python", "regex" ]
Reading a complex text file in Python
38,610,526
<p>I'm a newbie in Python and I've a problem.</p> <p>I've to compare the values between two files, one is an Excel file (and I don't have any problem with it), the other one is a text file formatted with spaces and "blocks" of lines.</p> <p>The text file is like this:</p> <pre><code>LISON Kontoauszug 10.07.2016 20:13 Monat/Jahr: 06.16 Seite: 1 Lief. : AKJsjak0 (V Sachbearb.: Name Surname LT : VW0012 Lief.-Eigene.: 0 Tel.: xxxxxxxxxx Saldo Vorm.: 170 BEL.: 253 ENTL: 181 Endsaldo: 242 B-Dat Abs/Empfae BEL. ENTL Saldo BA Bel-Nr WK-LG-LR Bemerkung 050416 000590178 0 1 169 50 16103483 49-12-00 FERSR IM SY 050416 000590178 0 1 168 50 16103484 49-16-00 FERSR IM SY 050516 000590030 0 2 166 50 16104633 16-01-K1 160516 000590030 0 1 165 50 16104980 16-01-K1 170516 000590030 0 2 163 50 16105015 16-01-K1 210516 000590120 1 0 164 51 36873 37- - 000590120 230516 000590178 1 0 165 51 16105229 49-16-00 MPYTRRIN 240516 000590030 0 2 163 50 16105243 16-01-K1 300516 000590030 0 1 162 50 16105484 16-01-K1 300516 000590030 0 1 161 50 16105483 16-01-K1 310516 000590030 2 0 163 51 697321 26- - KOR.GJKE.MB 310516 000590030 0 2 161 50 16105536 16-01-K1 310516 000590030 0 1 160 50 16105542 16-01-K1 010616 000590120 2 0 162 21 39694 37- - 000590120 010616 000710030 12 0 174 21 627948 21- - 000710030 010616 000590120 0 1 173 50 39694 37- - 030616 000712550 0 2 171 10 16105627 28-05-60 030616 000710130 0 1 170 10 16105628 11-01-K4 030616 000448489 0 2 168 10 16105638 18-66-23 030616 000590120 0 2 166 10 16105626 37-75-I4 060616 000590030 41 0 207 21 698299 26- - 000590030 070616 000712550 0 2 205 10 16105714 28-05-60 070616 000712550 0 1 204 10 16105717 28-08-60 070616 000590178 0 1 203 10 16105710 49-16- 070616 000590120 0 1 202 10 16105702 37-75-I4 070616 000590120 0 1 201 10 16105703 37-78-I4 070616 000590120 0 1 200 10 16105704 37-78-I8 070616 000590235 0 1 199 10 16105707 33-07-K9 070616 000710030 0 1 198 10 16105715 24-06-S2 070616 000590030 0 1 197 10 16105716 16-01-K1 070616 000590030 0 1 196 10 16105722 16-01-K1 070616 000590030 0 3 193 10 16105726 16-01-K1 070616 000711420 0 1 192 10 16105706 40-01-K1 080616 000590120 1 0 193 21 31456 37- - 000590120 080616 000590120 1 0 194 21 31456 37- - 000590120 080616 000710030 2 0 196 21 630076 21- - 000710030 080616 000710030 2 0 198 21 630076 21- - 000710030 080616 000710030 4 0 202 21 630076 21- - 000710030 080616 000710136 0 1 201 10 16105769 15-01-F4 090616 000590178 2 0 203 21 491379 49- - 000590178 090616 000710030 0 1 202 10 16105842 21-01-P0 090616 000710030 0 4 198 10 16105843 21-01-P0 ------------------------------------------------------------------------------- - - BA=10 Entlast. durch Lieferschein BA=11 Belast. durch Lieferschein BA=20 Entlast. durch PV-Schein BA=21 Belast. durch PV-Schein BA=22 Entlast. durch MRV-/Lieferschein BA=23 Belast. durch MRV- /Lieferschein BA=30 Entlast. durch Querverkehr BA=31 Belast. durch Querverkehr BA=50 Entlast. durch Korrektur BA=51 Belast. durch Korrektur BA=70 Entlast. durch Inventurangleich BA=71 Belast. durch Inventurangleich BA=NE Entlast. durch NeG neutr. Buch. BA=NB Belast. durch NeG neutr. Buch. BA=NK Neukauf BA=VS Verschrottung BA=NW Neukauf Wertersatz BA=NR Neukauf Recycling BA=VR Verschrottung Recycling LISON Kontoauszug 10.07.2016 20:13 Monat/Jahr: 06.16 Seite: 2 </code></pre> <p>And so on for thousands of lines... I need a list(maybe?) or a np.array (if it's better) that is made of every columns of the txt (B-Dat Abs/Empfae BEL etc.) + the LT code of every line.</p> <p>The TXT is like "For this LT code, these movement are made... In this day, with this ID, this quantity are gone"</p> <p>I just write this code, but I don't know how to procede... I've tried both np and also standard modules...</p> <pre><code>with open("elementi/june/VW.txt", "r") as ins: testo_VW = [] # lines length 77 chars for line in ins: testo_VW.append(line) codiceCasse = [ "VW0012", "001210", "114003", "004147", "151774", "151743", "511912", "525411", "528879", "006280" ] indiciVW = [] codcasseVW = [] b_dat = [] # array di date prese dal file VW abs_empfae = [] bel = [] entl = [] bel_nr = [] wk_lg_lr = [] count = 0 for i in range(0, len(testo_VW)): if any(x in testo_VW[i] for x in codiceCasse): # ----&gt; trovo i numeri delle casse nel txt riga = testo_VW[i] codice_cassa = riga[8:14] i += 6 count += 1 </code></pre> <p>Can you please give me any advice? Or maybe something for implementing the code...</p> <p>Thank you in advance.</p>
1
2016-07-27T10:34:26Z
38,611,043
<p>One approach would be to read the file in a line at a time and use a regular expression to decide if it is one of the data lines. If it is, append to a list. You will also need to keep a note of the LT line and append it to any following data lines as follows:</p> <pre><code>import re data = [] lt = 'unknown' with open('input.txt') as f_input: for row in f_input: data_row = re.match(r'(\d+) +(\d+) +(\d+) +(\d+) +(\d+) +(\d+) +(\d+) +(.{8}) +(.*)|LT +: (\w+)', row) if data_row: if data_row.groups()[0]: data.append([lt] + list(data_row.groups()[:-1])) else: lt = data_row.groups()[-1] print data </code></pre> <p>This would give you the following to work with:</p> <pre><code>[['VW0012', '050416', '000590178', '0', '1', '169', '50', '16103483', '49-12-00', 'FERSR IM SY'], ['VW0012', '050416', '000590178', '0', '1', '168', '50', '16103484', '49-16-00', 'FERSR IM SY'], ['VW0012', '210516', '000590120', '1', '0', '164', '51', '36873', '37- - ', '000590120'], ['VW0012', '230516', '000590178', '1', '0', '165', '51', '16105229', '49-16-00', 'MPYTRRIN'], ['VW0012', '310516', '000590030', '2', '0', '163', '51', '697321', '26- - ', 'KOR.GJKE.MB'], ['VW0012', '010616', '000590120', '2', '0', '162', '21', '39694', '37- - ', '000590120'], ['VW0012', '010616', '000710030', '12', '0', '174', '21', '627948', '21- - ', '000710030'], ['VW0012', '060616', '000590030', '41', '0', '207', '21', '698299', '26- - ', '000590030'], ['VW0012', '080616', '000590120', '1', '0', '193', '21', '31456', '37- - ', '000590120'], ['VW0012', '080616', '000590120', '1', '0', '194', '21', '31456', '37- - ', '000590120'], ['VW0012', '080616', '000710030', '2', '0', '196', '21', '630076', '21- - ', '000710030'], ['VW0012', '080616', '000710030', '2', '0', '198', '21', '630076', '21- - ', '000710030'], ['VW0012', '080616', '000710030', '4', '0', '202', '21', '630076', '21- - ', '000710030'], ['VW0012', '090616', '000590178', '2', '0', '203', '21', '491379', '49- - ', '000590178']] </code></pre>
1
2016-07-27T10:57:33Z
[ "python", "parsing", "text-files", "python-3.5" ]
Convert spark DataFrame column to python list
38,610,559
<p>I work on a dataframe with two column, mvv and count.</p> <pre><code>+---+-----+ |mvv|count| +---+-----+ | 1 | 5 | | 2 | 9 | | 3 | 3 | | 4 | 1 | </code></pre> <p>i would like to obtain two list containing mvv values and count value. Something like</p> <pre><code>mvv = [1,2,3,4] count = [5,9,3,1] </code></pre> <p>So, I tried the following code: The first line should return a python list of row. I wanted to see the first value:</p> <pre><code>mvv_list = mvv_count_df.select('mvv').collect() firstvalue = mvv_list[0].getInt(0) </code></pre> <p>But I get an error message with the second line:</p> <blockquote> <p>AttributeError: getInt</p> </blockquote>
0
2016-07-27T10:36:18Z
38,611,657
<p>See, why this way that you are doing is not working. First, you are trying to get integer from a Row Type, the output of your collect is like this:</p> <pre><code>&gt;&gt;&gt; mvv_list = mvv_count_df.select('mvv').collect() &gt;&gt;&gt; mvv_list[0] Out: Row(mvv=1) </code></pre> <p>If you take something like this:</p> <pre><code>&gt;&gt;&gt; firstvalue = mvv_list[0].mvv Out: 1 </code></pre> <p>You will get the mvv value. If you want all the information of the array you can take something like this:</p> <pre><code>&gt;&gt;&gt; mvv_array = [int(i.mvv) for i in mvv_list.collect()] &gt;&gt;&gt; mvv_array Out: [1,2,3,4] </code></pre> <p>But if you do this row below you get:</p> <pre><code>&gt;&gt;&gt; count_array = [int(i.count) for i in mvv_list.collect()] Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method' </code></pre> <p>This Happens due to the method count is a built-in method. And the column has the same name as count. A work around to do this is change the column name of count to _count:</p> <pre><code>&gt;&gt;&gt; mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count") </code></pre> <p>And then try to do this:</p> <pre><code>&gt;&gt;&gt; mvv_array = [int(i.mvv) for i in mvv_list.collect()] &gt;&gt;&gt; mvv_count = [int(i._count) for i in mvv_list.collect()] </code></pre> <p>And finally it work!</p> <p>I hope that will help you.</p>
3
2016-07-27T11:26:50Z
[ "python", "apache-spark", "pyspark", "spark-dataframe" ]
Find indices of duplicated rows in python ndarray
38,610,634
<p>I coded the for loop to enumerate a multidimensional ndarray containing n rows of 28x28 pixel values.</p> <p>I am looking for the index of each row that is duplicated and the indices of the duplicates without redundancies.</p> <p>I found this code <a href="http://stackoverflow.com/questions/15787582/find-index-of-item-with-duplicates">here</a> (thanks unutbu) and modified it to read the ndarray, it works 70% of the time, however 30% of the time it is identifying the wrong images as duplicates. </p> <p>How can it be improved to detect the correct rows?</p> <pre><code>def overlap_same(arr): seen = [] dups = collections.defaultdict(list) for i, item in enumerate(arr): for j, orig in enumerate(seen): if np.array_equal(item, orig): dups[j].append(i) break else: seen.append(item) return dups </code></pre> <p>e.g. return overlap_same(train) returns:</p> <pre><code>defaultdict(&lt;type 'list'&gt;, {34: [1388], 35: [1815], 583: [3045], 3208: [4426], 626: [824], 507: [4438], 188: [338, 431, 540, 757, 765, 806, 808, 834, 882, 1515, 1539, 1715, 1725, 1789, 1841, 2038, 2081, 2165, 2170, 2300, 2455, 2683, 2733, 2957, 3290, 3293, 3311, 3373, 3446, 3542, 3565, 3890, 4110, 4197, 4206, 4364, 4371, 4734, 4851]}) </code></pre> <p>plotting some samples of the correct case on matplotlib gives:</p> <pre><code>fig = plt.figure() a=fig.add_subplot(1,2,1) plt.imshow(train[35]) a.set_title('train[35]') a=fig.add_subplot(1,2,2) plt.imshow(train[1815]) a.set_title('train[1815]') plt.show </code></pre> <p><a href="http://i.stack.imgur.com/RVPMx.png" rel="nofollow"><img src="http://i.stack.imgur.com/RVPMx.png" alt="train data 35 vs 1815"></a></p> <p>which is correct</p> <p>However:</p> <pre><code>fig = plt.figure() a=fig.add_subplot(1,2,1) plt.imshow(train[3208]) a.set_title('train[3208]') a=fig.add_subplot(1,2,2) plt.imshow(train[4426]) a.set_title('train[4426]') plt.show </code></pre> <p><a href="http://i.stack.imgur.com/XuHyu.png" rel="nofollow"><img src="http://i.stack.imgur.com/XuHyu.png" alt="enter image description here"></a></p> <p>is incorrect as they do not match</p> <p>Sample data (train[:3])</p> <pre><code>array([[[-0.5 , -0.5 , -0.5 , ..., 0.48823529, 0.5 , 0.17058824], [-0.5 , -0.5 , -0.5 , ..., 0.48823529, 0.5 , -0.0372549 ], [-0.5 , -0.5 , -0.5 , ..., 0.5 , 0.47647059, -0.24509804], ..., [-0.49215686, 0.34705883, 0.5 , ..., -0.5 , -0.5 , -0.5 ], [-0.31176472, 0.44901961, 0.5 , ..., -0.5 , -0.5 , -0.5 ], [-0.11176471, 0.5 , 0.49215686, ..., -0.5 , -0.5 , -0.5 ]], [[-0.24509804, 0.2764706 , 0.5 , ..., 0.5 , 0.25294119, -0.36666667], [-0.5 , -0.47254902, -0.02941176, ..., 0.20196079, -0.46862745, -0.5 ], [-0.49215686, -0.5 , -0.5 , ..., -0.47647059, -0.5 , -0.49607843], ..., [-0.49215686, -0.49607843, -0.5 , ..., -0.5 , -0.5 , -0.49215686], [-0.5 , -0.5 , -0.26862746, ..., 0.13137256, -0.46470588, -0.5 ], [-0.30000001, 0.11960784, 0.48823529, ..., 0.5 , 0.28431374, -0.24117647]], [[-0.5 , -0.5 , -0.5 , ..., -0.5 , -0.5 , -0.5 ], [-0.5 , -0.5 , -0.5 , ..., -0.5 , -0.5 , -0.5 ], [-0.5 , -0.5 , -0.5 , ..., -0.5 , -0.5 , -0.5 ], ..., [-0.5 , -0.5 , -0.5 , ..., 0.48431373, 0.5 , 0.31568629], [-0.5 , -0.49215686, -0.5 , ..., 0.49215686, 0.5 , 0.04901961], [-0.5 , -0.5 , -0.5 , ..., 0.04117647, -0.17450981, -0.45686275]]], dtype=float32) </code></pre>
2
2016-07-27T10:39:47Z
38,613,404
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package has a lot of functionality to solve these type of problems efficiently.</p> <p>For instance, (unlike numpy's builtin unique) this will find your unique images:</p> <pre><code>import numpy_indexed as npi unique_training_images = npi.unique(train) </code></pre> <p>Or if you want to find all the indices of each unique group, you can use:</p> <pre><code>indices = npi.group_by(train).split(np.arange(len(train))) </code></pre> <p>Note that these functions do not have quadratic time complexity, like in your original post, and are fully vectorized, and thus in all likelihood a lot more efficient. Also, unlike pandas it does not have a preferred data format, and is fully nd-array capable, so acting on arrays with shape [n_images, 28, 28] 'just works'.</p>
1
2016-07-27T12:46:05Z
[ "python", "numpy", "multidimensional-array", "data-science" ]
Python 3.x: Multiprocess cannot serialize 'ExFileObject' object
38,610,709
<p>I try to read txt file from the archive(tar) and process file with function. I have a lot of files and decided to use multiprocessing lib to speed up calculations. But I got error "cannot serialize 'ExFileObject' object". Below is an example of my code. How to serialize 'ExFileObject' object or how to speed up my calculations with multiprocessing lib? I am using Python 3.4</p> <pre><code>import tarfile from multiprocessing import Process, Manager def start(): result = {} file_path = '...somepath' tar = tarfile.open(file_path, 'r') for file in tar: extr_file = tar.extractfile(file) p = Process(target=straight_calc, args=(extr_file, result)) #thows error p.start() p.join() print(result) def straight_calc(file, result): content = file.readlines() for line in content: pass if __name__ == '__main__': start() </code></pre>
0
2016-07-27T10:42:49Z
38,612,701
<p>Your example code works fine for me. I would only add a <code>NoneType</code> check because <code>NoneType</code> has no <code>readlines</code> attribute and <code>tar.extractfile(file)</code> might return a <code>NoneType</code> value.</p> <pre><code>import tarfile from multiprocessing import Process, Manager def start(): result = {} file_path = '...somepath' tar = tarfile.open(file_path, 'r') for file in tar: extr_file = tar.extractfile(file) if extr_file is not None: p = Process(target=straight_calc, args=(extr_file, result)) p.start() p.join() print(result) def straight_calc(file, result): content = file.readlines() for line in content: pass if __name__ == '__main__': start() </code></pre> <p>You might try pickling your extr_file with <code>picklestring = pickle.dumps(extr_file)</code>. Pickling extr_file before executing Process should throw a more useful exception.</p>
0
2016-07-27T12:16:05Z
[ "python", "multithreading", "multiprocessing" ]
Pandas - Creating Dataframe from Generator object using read_csv
38,610,717
<p>I have a propitiatory cursor (arcpy.da.SearchCursor) object that I need to load into a pandas dataframe.</p> <p>It implements next(), reset() as you would expect for a generator object in Python.</p> <p>Using another post in <a href="http://stackoverflow.com/questions/18915941/create-a-pandas-dataframe-from-generator">stackexchange</a>, which is brilliant, I created a class that makes the generator act like a file-like object. This works for the default case, where chunksize is not set, but when I go to set the chunk size for each dataframe, it crashes python. </p> <p>My guess is that the n=0 needs to be implemented so x number of rows are returned, but so far this has been wrong.</p> <p>What is the proper way to implement my class so I can use generators to load a dataframe? I need to use chunksize because my datasets are huge.</p> <p>So the pseudo code would be:</p> <pre><code>customfileobject = Reader(cursor) dfs = pd.read_csv(customfileobject, columns=cursor.fields, chunksize=10000) </code></pre> <p>I am using Pandas version 0.16.1 and Python 2.7.10.</p> <p>Class below:</p> <pre><code>class Reader(object): """allows a cursor object to be read like a filebuffer""" def __init__(self, fc=None, columns="*", cursor=None): if cursor or fc: if fc: self.g = arcpy.da.SearchCursor(fc, columns) else: self.g = cursor else: raise ValueError("You must provide a da.SearchCursor or table path and column names") def read(self, n=0): try: vals = [] if n == 0: return next(self.g) else: # return multiple rows? for x in range(n): try: vals.append(self.g.next()) except StopIteration: return '' except StopIteration: return '' def reset(self): self.g.reset() </code></pre>
1
2016-07-27T10:43:13Z
38,620,505
<p>Try the following <code>read</code> function:</p> <pre><code>def read(self, n=0): if n == 0: try: return next(self.g) except StopIteration: return '' else: vals = [] try: for x in range(n): vals.append(next(self.g)) except StopIteration: pass finally: return ''.join(vals) </code></pre> <p>You should tell <code>pd.read_csv</code> the column names using the <code>names</code> argument (not <code>columns</code>), and that you have no header row (<code>header=None</code>).</p>
0
2016-07-27T18:22:58Z
[ "python", "python-2.7", "pandas" ]
pandas insert dataframe into database
38,610,723
<p>I'm using <code>sqlalchemy</code> in pandas to query postgres database and then insert results of a transformation to another table on the same database. But when I do <code>df.to_sql('db_table2', engine)</code> I get this error message: <code>ValueError: Table 'db_table2' already exists.</code> I noticed it want to create a new table. How to insert pandas dataframe to an already existing table ? </p> <pre><code>df = pd.read_sql_query('select * from "db_table1"',con=engine) #do transformation then save df to db_table2 df.to_sql('db_table2', engine) ValueError: Table 'db_table2' already exists </code></pre>
0
2016-07-27T10:43:23Z
38,610,751
<p>make use of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow">if_exists</a> parameter:</p> <pre><code>df.to_sql('db_table2', engine, if_exists='replace') </code></pre> <p>or</p> <pre><code>df.to_sql('db_table2', engine, if_exists='append') </code></pre> <p>from docstring:</p> <pre><code>""" if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table exists, drop it, recreate it, and insert data. - append: If table exists, insert data. Create if does not exist. """ </code></pre>
0
2016-07-27T10:44:45Z
[ "python", "pandas" ]
Why Python can not execute the cmd command 'tskill'?
38,610,730
<p>In general, we can use Python to execute Windows's cmd command, for example:</p> <pre><code> os.system('ipconfig') </code></pre> <p>but I find that <code>tskill</code> can not be executed by Python, if I use:</p> <pre><code>os.system('tskill 8684') </code></pre> <p>to kill a process by its pid, Python will show cmd's error:</p> <pre><code>'tskill' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>but it work well if I use cmd to run the command.</p> <p>As I know <code>tskill.exe</code> is located in C:\Windows\System32, but this path is not in Python's environment variable. It is maybe the reason, but <code>ipconfig.exe</code> is also in System32, it can be executed.</p> <p>So why <code>tskill</code> can not be executed by <strong>os.system</strong> or <strong>subprocess.Popen</strong>?</p>
1
2016-07-27T10:43:34Z
38,615,461
<p>Use taskkill, which can do pretty much everything as tskill</p> <p>But if you want to stick to tskill.exe in your scripts/code. Please run the scripts from elevated command prompts. (Right click on cmd.exe and run it as administrator)</p> <pre><code>os.system('c:\windows\system32\tskill.exe 8684') </code></pre>
0
2016-07-27T14:12:30Z
[ "python" ]
Why Python can not execute the cmd command 'tskill'?
38,610,730
<p>In general, we can use Python to execute Windows's cmd command, for example:</p> <pre><code> os.system('ipconfig') </code></pre> <p>but I find that <code>tskill</code> can not be executed by Python, if I use:</p> <pre><code>os.system('tskill 8684') </code></pre> <p>to kill a process by its pid, Python will show cmd's error:</p> <pre><code>'tskill' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>but it work well if I use cmd to run the command.</p> <p>As I know <code>tskill.exe</code> is located in C:\Windows\System32, but this path is not in Python's environment variable. It is maybe the reason, but <code>ipconfig.exe</code> is also in System32, it can be executed.</p> <p>So why <code>tskill</code> can not be executed by <strong>os.system</strong> or <strong>subprocess.Popen</strong>?</p>
1
2016-07-27T10:43:34Z
38,649,148
<p>I have found the root reason:</p> <p>My Python is 32-bit, while My PC is Windows7 64-bit, so Python's <code>os.system</code> can not run <code>tskill</code>. If I use Python 64-bit instead, everything is OK.</p>
1
2016-07-29T01:27:57Z
[ "python" ]
How to create generic 2d array in python
38,610,924
<p>In Java you would do it like this: <code>Node[][] nodes;</code> where Node.java is a custom class. How do I do it in python where Node.py:</p> <pre><code>class Node(object): def __init__(self): self.memory = [] self.temporal_groups = [] </code></pre> <p>I have imported <code>numpy</code> and created an object type </p> <pre><code>typeObject = numpy.dtype('O') # O stands for python objects nodes = ??? </code></pre>
1
2016-07-27T10:52:26Z
38,612,912
<p>You can try it this way, inside your node class create a function that will return the generic array: </p> <pre><code>def genArray(a, b): return [[0 for y in range(a)] for x in range(b)] </code></pre> <p>then you can assign them the way you want. Maybe you might change the 0 to your node object. Let me know if this helps</p>
1
2016-07-27T12:25:19Z
[ "python", "numpy", "generics" ]
How to create generic 2d array in python
38,610,924
<p>In Java you would do it like this: <code>Node[][] nodes;</code> where Node.java is a custom class. How do I do it in python where Node.py:</p> <pre><code>class Node(object): def __init__(self): self.memory = [] self.temporal_groups = [] </code></pre> <p>I have imported <code>numpy</code> and created an object type </p> <pre><code>typeObject = numpy.dtype('O') # O stands for python objects nodes = ??? </code></pre>
1
2016-07-27T10:52:26Z
38,617,230
<p>You have two easy options: use <code>numpy</code> or declare a nested list. The latter approach is more conceptually similar to <code>Node[][]</code> since it allows for ragged lists, as does Java, but the former approach will probably make processing faster.</p> <p><strong>numpy arrays</strong></p> <p>To make an array in <code>numpy</code>:</p> <pre><code>import numpy as np x = np.full((m, n), None, dtype=np.object) </code></pre> <p>In <code>numpy</code>, you have to have some idea about the size of the array (here <code>m</code>, <code>n</code>) up-front. There are ways to grow an array, but they are not very efficient, especially for large arrays. <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html" rel="nofollow"><code>np.full</code></a> will initialize your array with a copy of whatever reference you want. You can modify the elements as you wish after that.</p> <p><strong>Python lists</strong></p> <p>To create a ragged list, you do not have to do much:</p> <pre><code>x = [] </code></pre> <p>This creates an empty list. This is equivalent to <code>Node[][]</code> in Java because that declares a list too. The main difference is that Python lists can change size and are untyped. They are effectively always <code>Object[]</code>.</p> <p>To add more dimensions to the list, just do <code>x[i] = []</code>, which will insert a nested list into your outer list. This is similar to defining something like</p> <pre><code>Node[][] nodes = new Node[m][]; nodes[i] = new Node[n]; </code></pre> <p>where <code>m</code> is the number of nested lists (rows) and <code>n</code> is the number of elements in each list (columns). Again, the main difference is that once you have a list in Python, you can expand or contract it as you Java.</p> <p>Manipulate with <code>x[i][j]</code> as you would in Java. You can add new sublists by doing <code>x.append([])</code> or <code>x[i] = []</code>, where <code>i</code> is an index past the end of <code>x</code>.</p>
0
2016-07-27T15:23:45Z
[ "python", "numpy", "generics" ]
unittest - assertRaises return an error instead of passing
38,610,943
<p>I've written a piece of code that uses a config file (in JSON-format) </p> <pre><code>def test_read_config_file(self): self.assertRaises(ValueError, self.read_config_file('no_json.txt') </code></pre> <p>The original function looks like this:</p> <pre><code>def read_config_file(file_name) config_data = None try: with open(file_name, 'r') as infile: config_data = json.load(infile) except ValueError as err: LOGGER.error(str(err)) return config_data </code></pre> <p>When i run my testcase i get this:</p> <pre><code>2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded 2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded 2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded 2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded </code></pre> <p>no_json.txt just contains "Hi". Why am i getting 4 error here?</p> <p>Thanks,</p>
1
2016-07-27T10:53:28Z
38,612,082
<p>You are not using the <code>unittest</code> library correctly. When you write this:</p> <pre><code>def test_read_config_file(self): self.assertRaises(ValueError, self.read_config_file('no_json.txt')) # Btw. there was a missing closing `)` </code></pre> <p>the <code>self.read_config_file()</code> method is executed before the <code>self.assertRaises</code>. If it fails the <code>self.assertRaises</code> will never be called. Instead the exception bubbles up until something else catches it.</p> <p>You want the <code>self.assertRaises</code> method to execute the <code>self.read_config_file</code> method. Because then and only then it can catch a potential <code>ValueError</code>. To do this you have two options:</p> <p>Pass the method to test and the arguments separately:</p> <pre><code>self.assertRaises(ValueError, self.read_config_file, "no_json.txt") </code></pre> <p>Like this <code>self.assertRaises</code> will call the function you passed into it with the arguments specified. Then the exception occurs inside <code>self.assertRaises</code> where it can be caught and let the test succeed.</p> <p>The second option is to use a context manager:</p> <pre><code>def test_read_config_file(self): with self.assertRaises(ValueError): self.read_config_file("no_json.txt") </code></pre> <p>Like this the exception will happen inside the <code>with</code> statement. In the cleanup step of the context manager the presence of such an exception can then again let the test succeed.</p> <p><strong>EDIT:</strong> From your edit i can see that you already handle the <code>ValueError</code> in your <code>self.read_config_file</code> method. So any <code>self.assertRaises</code> approach will fail anyway. Either let the <code>self.read_config_file</code> raise the error or change your test.</p>
0
2016-07-27T11:46:59Z
[ "python", "python-unittest" ]
unittest - assertRaises return an error instead of passing
38,610,943
<p>I've written a piece of code that uses a config file (in JSON-format) </p> <pre><code>def test_read_config_file(self): self.assertRaises(ValueError, self.read_config_file('no_json.txt') </code></pre> <p>The original function looks like this:</p> <pre><code>def read_config_file(file_name) config_data = None try: with open(file_name, 'r') as infile: config_data = json.load(infile) except ValueError as err: LOGGER.error(str(err)) return config_data </code></pre> <p>When i run my testcase i get this:</p> <pre><code>2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded 2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded 2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded 2016-07-27 12:41:09,616 ERROR read_config_file(158) No JSON object could be decoded </code></pre> <p>no_json.txt just contains "Hi". Why am i getting 4 error here?</p> <p>Thanks,</p>
1
2016-07-27T10:53:28Z
38,612,195
<p>The problem is that your function catches the <code>ValueError</code> exception that <code>json.load</code> raises, performs the logging, then simply goes on to return the value of <code>config_data</code>. Your test asserts that the function should raise an exception, but there is no code to ensure that the function does that.</p> <p>The easiest way to fix this would be to modify the code by adding a <code>raise</code> statement to ensure that the <code>ValueError</code> is re-raised to be trapped by the <code>assertRaises</code> call:</p> <pre><code>def read_config_file(file_name) config_data = None try: with open(file_name, 'r') as infile: config_data = json.load(infile) except ValueError as err: LOGGER.error(str(err)) raise return config_data </code></pre>
0
2016-07-27T11:52:43Z
[ "python", "python-unittest" ]
Dealing with big data to perform random forest classification
38,610,955
<p>I am currently working on my thesis, which involves dealing with quite a sizable dataset: ~4mln observations and ~260ths features. It is a dataset of chess games, where most of the features are player dummies (130k for each colour). </p> <p>As for the hardware and the software, I have around 12GB of RAM on this computer. I am doing all my work in Python 3.5 and use mainly pandas and scikit-learn packages. </p> <p>My problem is that obviously I can't load this amount of data to my RAM. What I would love to do is to generate the dummy variables, then slice the database into like a thousand or so chunks, apply the Random Forest and aggregate the results again. </p> <p>However, to do that I would need to be able to first create the dummy variables, which I am not able to do due to memory error, even if I use sparse matrices. Theoretically, I could just slice up the database first, then create the dummy variables. However, the effect of that will be that I will have different features for different slices, so I'm not sure how to aggregate such results. </p> <p><strong>My questions:</strong><br> 1. How would you guys approach this problem? Is there a way to "merge" the results of my estimation despite having different features in different "chunks" of data?<br> 2. Perhaps it is possible to avoid this problem altogether by renting a server. Are there any trial versions of such services? I'm not sure exactly how much CPU/RAM would I need to complete this task. </p> <p>Thanks for your help, any kind of tips will be appreciated :)</p>
3
2016-07-27T10:53:57Z
38,612,762
<p>I would suggest you give CloudxLab a try. </p> <p>Though it is not free it is quite affordable ($25 for a month). It provides complete environment to experiment with various tools such as HDFS, Map-Reduce, Hive, Pig, Kafka, Spark, Scala, Sqoop, Oozie, Mahout, MLLib, Zookeeper, R, Scala etc. Many of the popular trainers are using CloudxLab.</p>
4
2016-07-27T12:18:46Z
[ "python", "pandas", "scikit-learn", "bigdata", "sparse-matrix" ]
Django {%trans%} not working, despite django.po being generated
38,610,962
<p>I have a template file <code>templates/admin/base_site.html</code> which includes one <code>trans</code> tag: <code>{% trans "Event List" %}</code>.</p> <p><code>settings.py</code> includes:</p> <pre><code>LANGUAGE_CODE = 'sv' LOCALE_PATHS = ( '/srv/mysite/locale/', ) </code></pre> <p>The Django-admin pages are correctly translated into Swedish, apart from the text in the <code>trans</code> tag.</p> <p>When I run <code>python manage.py makemessages -l sv</code> it correctly generates a <code>locale/sv/LC_MESSAGES/django.po</code> file, whose last few lines are:</p> <pre><code>#: templates/admin/base_site.html:9 msgid "Event List" msgstr "Event List" </code></pre> <p>I then change it to:</p> <pre><code>#: templates/admin/base_site.html:9 msgid "Event List" msgstr "Händelselista" </code></pre> <p>When I run <code>python manage.py runserver</code> again, the string is not translated on the web page.</p> <p>The rest of the admin page is still translated into Swedish, as it was before.</p> <p>What am I missing?</p>
1
2016-07-27T10:54:03Z
38,611,079
<p>Have you restarted the webserver? It won't be serving the newly compiled po files if you haven't. </p> <p><strong>Edit:</strong> and be sure to restart Django server after you do as well.</p>
0
2016-07-27T10:59:01Z
[ "python", "django", "django-i18n" ]
Django {%trans%} not working, despite django.po being generated
38,610,962
<p>I have a template file <code>templates/admin/base_site.html</code> which includes one <code>trans</code> tag: <code>{% trans "Event List" %}</code>.</p> <p><code>settings.py</code> includes:</p> <pre><code>LANGUAGE_CODE = 'sv' LOCALE_PATHS = ( '/srv/mysite/locale/', ) </code></pre> <p>The Django-admin pages are correctly translated into Swedish, apart from the text in the <code>trans</code> tag.</p> <p>When I run <code>python manage.py makemessages -l sv</code> it correctly generates a <code>locale/sv/LC_MESSAGES/django.po</code> file, whose last few lines are:</p> <pre><code>#: templates/admin/base_site.html:9 msgid "Event List" msgstr "Event List" </code></pre> <p>I then change it to:</p> <pre><code>#: templates/admin/base_site.html:9 msgid "Event List" msgstr "Händelselista" </code></pre> <p>When I run <code>python manage.py runserver</code> again, the string is not translated on the web page.</p> <p>The rest of the admin page is still translated into Swedish, as it was before.</p> <p>What am I missing?</p>
1
2016-07-27T10:54:03Z
38,611,365
<p><code>django.po</code> files are only meant for editing purpose. You must compile them to <code>django.mo</code> files so that they are interpreted:</p> <pre><code>python manage.py compilemessages </code></pre> <p>See also <a href="https://docs.djangoproject.com/en/1.9/topics/i18n/translation/#compiling-message-files" rel="nofollow">Django docs</a> and <a class='doc-link' href="http://stackoverflow.com/documentation/django/2579/internationalization/11494/translating-strings#t=201607271113517793053">example</a>.</p>
1
2016-07-27T11:13:25Z
[ "python", "django", "django-i18n" ]
Unable to open the link in proxy
38,610,965
<p>I am actually using a proxy to scrape data from some sites but the problem is sometimes some proy url returns nothing and programmed stopped after a few tries, I need some logic to overcome this issue so that even if IP does not respond program should renew the IP and try to open the page again, I am using TOR as a proxy in python.</p> <p>Here is my website opening code:</p> <pre><code>mainPage = requests.get("http://proxy_IP/?link=http://example.com/") mainTree = html.fromstring(mainPage.text) </code></pre>
1
2016-07-27T10:54:14Z
38,611,053
<p>You can simply put your code in while loop and give it certain condition, when that condition becomes TRUE, it means your page is properly opened.</p> <pre><code>mainPage = requests.get("http://proxy_IP/?link=http://example.com/") mainTree = html.fromstring(mainPage.text) mainTree while (mainTree.xpath('boolean(some_xpath_to_be_true])') != True): mainPage = requests.get("http://proxy_IP/?link=http://example.com/") mainTree = html.fromstring(mainPage.text) </code></pre> <p>Now your mainTree contains the page source correctly.</p>
0
2016-07-27T10:57:51Z
[ "python", "proxy" ]
Plot some numbers in x axis
38,610,994
<p>My question is related to the figure format generated using the matplotlib library.</p> <p>So, in the x axis, I have the integers from 1 to 100, but in my code I plot just the data related to some numbers (e.g 1,5,77,86,97).</p> <p>At the end, my code shows me a figure with x axis from 1 to 100.</p> <p>How can I show just the needed numbers (1,5,77,86,97)?</p> <p>My code is shown below:</p> <pre><code>def Plot(self,x,y, steps, nb,bool): if(bool == False): labelfont = { 'family' : 'sans-serif', # (cursive, fantasy, monospace, serif) 'color' : 'black', # html hex or colour name 'weight' : 'normal', # (normal, bold, bolder, lighter) 'size' : 20, # default value:12 } titlefont = { 'family' : 'serif', 'color' : 'black', 'weight' : 'bold', 'size' : 20, } x = np.array(x) y = np.array(y) pylab.plot(x, y, 'darkmagenta', # colour linestyle='', # line style linewidth=10, # line width marker = '+', mew=6, ms=12) axes = plt.gca() axes.grid(True) axes.set_xlim([1, x_max) # x-axis bounds axes.set_ylim([1, nb]) # y-axis bounds pylab.title('Title' , fontdict=titlefont) pylab.xlabel('x', fontdict=labelfont) pylab.ylabel('y', fontdict=labelfont) pylab.subplots_adjust(left=0.15) # prevents overlapping of the y label else: test_steps.insert(0,"") pylab.yticks(nb, steps,rotation=0, size=10) pylab.margins(0.2) pylab.xticks(np.arange(0, x_max, 1.0),rotation=90, size=10) # Tweak spacing to prevent clipping of tick-labels pylab.subplots_adjust(bottom=0.15) F = pylab.gcf() DefaultSize = F.get_size_inches() if x_max &lt; 100 and len(steps) &lt; 100: Xx = 2.5 Yy = 2.5 elif x_max &lt; 200 and len(steps) &lt; 200: Xx = 5 Yy = 5 elif ix_max &lt; 300 and len(steps) &lt; 300: Xx = 8 Yy = 8 elif x_max &lt; 400 and steps &lt; 400: Xx = 10 Yy = 10 elif x_max &lt; 500 and steps &lt; 500: Xx = 12 Yy = 12 else: Xx = 15 Yy = 15 F.set_size_inches((DefaultSize[0]*Xx , DefaultSize[1]*Yy)) F.savefig('Out.png', bbox_inches='tight') pylab.close(F) </code></pre>
-1
2016-07-27T10:55:28Z
38,611,271
<p>If you have a <code>matplotlib.Axes</code> object you can modify the ticks along the x-axis with <code>set_xticks</code>:</p> <pre><code>import matplotlib.pyplot as plt plt.plot([0,1,5,77,86,97],range(6),'o-') ax = plt.gca() ax.set_xticks([1,5,77,86,97]) </code></pre> <p>with output:</p> <p><a href="http://i.stack.imgur.com/RtKRd.png" rel="nofollow"><img src="http://i.stack.imgur.com/RtKRd.png" alt="enter image description here"></a></p> <p><strong>EDIT</strong>: assuming you want to plot the values equally separated (though at this point you really should be considering something like bar graphs with the numbers as labels), you could just make a fake x-axis and rename the ticks using <code>set_xticklabels</code>:</p> <pre><code>import matplotlib.pyplot as plt x = range(5) y = range(5) real_x = [1,5,77,86,97] plt.plot(x,y,'o-') ax = plt.gca() ax.set_xticks(x) ax.set_xticklabels(real_x) </code></pre> <p><a href="http://i.stack.imgur.com/pqYeI.png" rel="nofollow"><img src="http://i.stack.imgur.com/pqYeI.png" alt="enter image description here"></a></p>
2
2016-07-27T11:09:02Z
[ "python", "matplotlib" ]
Plot some numbers in x axis
38,610,994
<p>My question is related to the figure format generated using the matplotlib library.</p> <p>So, in the x axis, I have the integers from 1 to 100, but in my code I plot just the data related to some numbers (e.g 1,5,77,86,97).</p> <p>At the end, my code shows me a figure with x axis from 1 to 100.</p> <p>How can I show just the needed numbers (1,5,77,86,97)?</p> <p>My code is shown below:</p> <pre><code>def Plot(self,x,y, steps, nb,bool): if(bool == False): labelfont = { 'family' : 'sans-serif', # (cursive, fantasy, monospace, serif) 'color' : 'black', # html hex or colour name 'weight' : 'normal', # (normal, bold, bolder, lighter) 'size' : 20, # default value:12 } titlefont = { 'family' : 'serif', 'color' : 'black', 'weight' : 'bold', 'size' : 20, } x = np.array(x) y = np.array(y) pylab.plot(x, y, 'darkmagenta', # colour linestyle='', # line style linewidth=10, # line width marker = '+', mew=6, ms=12) axes = plt.gca() axes.grid(True) axes.set_xlim([1, x_max) # x-axis bounds axes.set_ylim([1, nb]) # y-axis bounds pylab.title('Title' , fontdict=titlefont) pylab.xlabel('x', fontdict=labelfont) pylab.ylabel('y', fontdict=labelfont) pylab.subplots_adjust(left=0.15) # prevents overlapping of the y label else: test_steps.insert(0,"") pylab.yticks(nb, steps,rotation=0, size=10) pylab.margins(0.2) pylab.xticks(np.arange(0, x_max, 1.0),rotation=90, size=10) # Tweak spacing to prevent clipping of tick-labels pylab.subplots_adjust(bottom=0.15) F = pylab.gcf() DefaultSize = F.get_size_inches() if x_max &lt; 100 and len(steps) &lt; 100: Xx = 2.5 Yy = 2.5 elif x_max &lt; 200 and len(steps) &lt; 200: Xx = 5 Yy = 5 elif ix_max &lt; 300 and len(steps) &lt; 300: Xx = 8 Yy = 8 elif x_max &lt; 400 and steps &lt; 400: Xx = 10 Yy = 10 elif x_max &lt; 500 and steps &lt; 500: Xx = 12 Yy = 12 else: Xx = 15 Yy = 15 F.set_size_inches((DefaultSize[0]*Xx , DefaultSize[1]*Yy)) F.savefig('Out.png', bbox_inches='tight') pylab.close(F) </code></pre>
-1
2016-07-27T10:55:28Z
38,611,309
<p>How about masking x with y and then plotting it? like:</p> <pre><code>pylap.plot(x[y != 0], y, 'darkmagenta', # colour linestyle='', # line style linewidth=10, # line width marker = '+', mew=6, ms=12) </code></pre> <p>Or if y contains more numbers != 0 and you only want to plot those listed above, just mask x with these numbers...</p>
0
2016-07-27T11:10:56Z
[ "python", "matplotlib" ]
Plot some numbers in x axis
38,610,994
<p>My question is related to the figure format generated using the matplotlib library.</p> <p>So, in the x axis, I have the integers from 1 to 100, but in my code I plot just the data related to some numbers (e.g 1,5,77,86,97).</p> <p>At the end, my code shows me a figure with x axis from 1 to 100.</p> <p>How can I show just the needed numbers (1,5,77,86,97)?</p> <p>My code is shown below:</p> <pre><code>def Plot(self,x,y, steps, nb,bool): if(bool == False): labelfont = { 'family' : 'sans-serif', # (cursive, fantasy, monospace, serif) 'color' : 'black', # html hex or colour name 'weight' : 'normal', # (normal, bold, bolder, lighter) 'size' : 20, # default value:12 } titlefont = { 'family' : 'serif', 'color' : 'black', 'weight' : 'bold', 'size' : 20, } x = np.array(x) y = np.array(y) pylab.plot(x, y, 'darkmagenta', # colour linestyle='', # line style linewidth=10, # line width marker = '+', mew=6, ms=12) axes = plt.gca() axes.grid(True) axes.set_xlim([1, x_max) # x-axis bounds axes.set_ylim([1, nb]) # y-axis bounds pylab.title('Title' , fontdict=titlefont) pylab.xlabel('x', fontdict=labelfont) pylab.ylabel('y', fontdict=labelfont) pylab.subplots_adjust(left=0.15) # prevents overlapping of the y label else: test_steps.insert(0,"") pylab.yticks(nb, steps,rotation=0, size=10) pylab.margins(0.2) pylab.xticks(np.arange(0, x_max, 1.0),rotation=90, size=10) # Tweak spacing to prevent clipping of tick-labels pylab.subplots_adjust(bottom=0.15) F = pylab.gcf() DefaultSize = F.get_size_inches() if x_max &lt; 100 and len(steps) &lt; 100: Xx = 2.5 Yy = 2.5 elif x_max &lt; 200 and len(steps) &lt; 200: Xx = 5 Yy = 5 elif ix_max &lt; 300 and len(steps) &lt; 300: Xx = 8 Yy = 8 elif x_max &lt; 400 and steps &lt; 400: Xx = 10 Yy = 10 elif x_max &lt; 500 and steps &lt; 500: Xx = 12 Yy = 12 else: Xx = 15 Yy = 15 F.set_size_inches((DefaultSize[0]*Xx , DefaultSize[1]*Yy)) F.savefig('Out.png', bbox_inches='tight') pylab.close(F) </code></pre>
-1
2016-07-27T10:55:28Z
38,611,748
<p>That will do:</p> <pre><code>import matplotlib.pyplot as plt x = y = list(range(100)) idx = [1,5,77,86,97] new_y = [y[i] for i in idx] plt.plot(range(len(idx)), new_y, 'o-') plt.xticks(range(len(idx)),idx) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/xbT2a.png" rel="nofollow"><img src="http://i.stack.imgur.com/xbT2a.png" alt="output"></a></p> <p>If you want only dots just remove the <code>-</code>:</p> <pre><code>plt.plot(range(len(idx)), new_y, 'o') # ---^--- instead of 'o-' </code></pre>
2
2016-07-27T11:31:18Z
[ "python", "matplotlib" ]
Pass a variable number of arguments to the map function
38,611,073
<p>Suppose I have a function whose the prototype is:</p> <pre><code>def my_func(fixed_param, *args) </code></pre> <p>I would like to run this function with multiple arguments (not necessary the same number of arguments for each run) such as:</p> <pre><code>res = map(partial(my_func, fixed_param=3), [[1, 2, 3], [1, 2, 3, 4]]) </code></pre> <p>where [1, 2, 3] and [1, 2, 3, 4] respectively correspond to the first and second set of parameters for args.</p> <p>But this line of code fails with the following error:</p> <pre><code>TypeError: my_func() got multiple values for keyword argument 'fixed_param' </code></pre>
3
2016-07-27T10:58:47Z
38,611,262
<p>You can unpack the argument list if you use a list comprehension:</p> <pre><code>res= [my_func(3, *args) for args in [[1, 2, 3], [1, 2, 3, 4]]] </code></pre> <p>But you can't do this with <code>map</code>. If you insist on using <code>map</code>, you'll need a helper function:</p> <pre><code>def unpack(args): return my_func(3, *args) res= map(unpack, [[1, 2, 3], [1, 2, 3, 4]]) </code></pre>
3
2016-07-27T11:08:44Z
[ "python" ]
Pass a variable number of arguments to the map function
38,611,073
<p>Suppose I have a function whose the prototype is:</p> <pre><code>def my_func(fixed_param, *args) </code></pre> <p>I would like to run this function with multiple arguments (not necessary the same number of arguments for each run) such as:</p> <pre><code>res = map(partial(my_func, fixed_param=3), [[1, 2, 3], [1, 2, 3, 4]]) </code></pre> <p>where [1, 2, 3] and [1, 2, 3, 4] respectively correspond to the first and second set of parameters for args.</p> <p>But this line of code fails with the following error:</p> <pre><code>TypeError: my_func() got multiple values for keyword argument 'fixed_param' </code></pre>
3
2016-07-27T10:58:47Z
38,611,267
<p>I would not be so sure about <code>map</code> vs list comprehension performance, as oftentimes it's a question of the function you use. Anyway, your options are:</p> <pre><code>map(lambda x: my_func(3, *x), ...) </code></pre> <p>Or </p> <pre><code>from itertools import starmap starmap(partial(my_func, 3), ...) </code></pre> <p>Like all function in <code>itertools</code>, <code>starmap</code> retuts an iterator, hence you must pass it to the <code>list</code> constructor, if you want a list. That will be slower than a listcomp for sure. </p> <p><strong>EDIT</strong> Benchmarks:</p> <pre><code>In [1]: def my_func(x, *args): ...: return (x, ) + args ...: In [2]: from functools import partial In [3]: from itertools import starmap In [4]: import random In [5]: samples = [range(random.choice(range(10))) for _ in range(100)] In [6]: %timeit map(lambda x: my_func(3, *x), samples) 10000 loops, best of 3: 39.2 µs per loop In [7]: %timeit list(starmap(partial(my_func, 3), samples)) 10000 loops, best of 3: 33.2 µs per loop In [8]: %timeit [my_func(3, *s) for s in samples] 10000 loops, best of 3: 32.8 µs per loop </code></pre> <p>For the sake of comparison, lets change the function a bit </p> <pre><code>In [9]: def my_func(x, args): ...: return (x, ) + tuple(args) ...: In [10]: %timeit [my_func(3, s) for s in samples] 10000 loops, best of 3: 37.6 µs per loop In [11]: %timeit map(partial(my_func, 3), samples) 10000 loops, best of 3: 42.1 µs per loop </code></pre> <p>Once again, list comprehension is faster. </p>
5
2016-07-27T11:08:55Z
[ "python" ]
Pass a variable number of arguments to the map function
38,611,073
<p>Suppose I have a function whose the prototype is:</p> <pre><code>def my_func(fixed_param, *args) </code></pre> <p>I would like to run this function with multiple arguments (not necessary the same number of arguments for each run) such as:</p> <pre><code>res = map(partial(my_func, fixed_param=3), [[1, 2, 3], [1, 2, 3, 4]]) </code></pre> <p>where [1, 2, 3] and [1, 2, 3, 4] respectively correspond to the first and second set of parameters for args.</p> <p>But this line of code fails with the following error:</p> <pre><code>TypeError: my_func() got multiple values for keyword argument 'fixed_param' </code></pre>
3
2016-07-27T10:58:47Z
38,611,555
<p>I think your code will work with a few small changes:</p> <pre><code>def f(l, all_args): print "Variable", all_args print "Fixed", l map(partial(f, 1), [[1, 2, 3], [1, 2, 3, 4]]) &gt;&gt;&gt; Variable [1, 2, 3] &gt;&gt;&gt; Fixed 1 &gt;&gt;&gt; Variable [1, 2, 3, 4] &gt;&gt;&gt; Fixed 1 </code></pre>
2
2016-07-27T11:22:05Z
[ "python" ]
Django forms show cleaned data if validation fails
38,611,278
<p>I have the following function declared in a django form:</p> <pre><code>def clean_name(self): name = self.cleaned_data.get('name') name = re.sub('\s+', ' ', name).strip().title() return name </code></pre> <p>I have an unique constraint on the name field and I would like to have the name trimmed in the form if the validation hits.</p> <p>What is the proper way to do that in Django?</p> <p>Thanks</p>
1
2016-07-27T11:09:29Z
38,613,064
<p>So I've read some articles, finally i came to this solution, to override the full_clean method:</p> <pre><code>def full_clean(self): cleaned_data = {} for i,v in self.data.items(): if isinstance(v, basestring): cleaned_data[i] = re.sub('\s+', ' ', v).strip() else: cleaned_data[i] = v self.data = cleaned_data super(MyForm, self).full_clean() </code></pre> <p>It works, but it looks kind of dirty to me, anyother suggestions?</p>
0
2016-07-27T12:31:06Z
[ "python", "django", "django-forms" ]
Parallel execution of 2 seperate python scripts using subprocess from the main Python script
38,611,285
<p>Using python, I want to start two subprocesses in parallel. One will start an HTTP Server, while other will start execution of another program(which is a python script generated by selenium IDE plugin to open firefox, navigate to a website and do some interactions). On the other hand, I want to stop execution of the first subprocess(the HTTP Server) when the second subprocess is finished executing.</p> <p>The logic of my code is that the selenium script will open a website. The website will automatically make a few GET calls to my HTTP Server. After the selenium script is finished executing, the HTTP Server is supposed to be closed so that it can log all the captured requests in a file.</p> <p>Here is my code:</p> <pre><code>class Myclass(object): HTTPSERVERPROCESS = "" def startHTTPServer(self): print "********HTTP Server started*********" try: self.HTTPSERVERPROCESS=subprocess.Popen('python CustomSimpleHTTPServer.py', \ shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT) self.HTTPSERVERPROCESS.communicate() except Exception as e: print "Exception captured while starting HTTP Server process: %s\n" % e def startNavigatingFromBrowser(self): print "********Opening firefox to start navigation*********" try: process=subprocess.Popen('python navigationScript.py', \ shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.communicate() process.wait() except Exception as e: print "Exception captured starting Browser Navigation process : %s\n" % e try: if process.returncode==0: print "HTTPSERVEPROCESS value: %s" % self.HTTPSERVERPROCESS.returncode print self.HTTPSERVERPROCESS self.HTTPSERVERPROCESS.kill() #print "HTTPSERVEPROCESS value: %s" % self.HTTPSERVERPROCESS.returncode except Exception as e: print "Exception captured while killing HTTP Server process : %s\n" % e def startCapture(self): print "********Starting Parallel execution of Server initiation and firefox navigation script*********" t1 = threading.Thread(target=self.startHTTPServer()) t2 = threading.Thread(target=self.startNavigatingFromBrowser()) t1.start() t2.start() t2.join() </code></pre> <p><strong>Note: Execution starts by calling startCapture()</strong></p> <p>The problem is that I get following in my terminal upon running the above code</p> <pre><code>********Starting Parallel execution of HTTP Server initiation and firefox navigation script********* ********HTTP Server started********* ********Opening firefox to start navigation********* Process finished with exit code 0 </code></pre> <p>My program finishes execution even when the thread started for startNavigatingFromBrowser() is still active. I can see that the firefox is navigating through the website even after I get "Process finished with exit code 0" for my program. Due to this I am not able to detect when my browser navigation thread finishes execution**(This is necessary because I am using process.returncode returned from navigationScript subprocess to kill my HTTP Server process)**.</p> <p>What changes should I make to the code so that I can successfully detect when the selenium navigation subprocess is finished executing so that I can stop my HTTP Server?</p>
3
2016-07-27T11:09:50Z
38,611,426
<p>Call <code>t2.join()</code> before exiting your program. This waits for the navigation thread to terminate, before execution continues.</p> <p>Edit:</p> <p>Your navigation thread terminates immediately because you are not waiting for the child process to exit. This should solve the issue:</p> <pre><code>process=subprocess.Popen('python navigationScript.py', \ shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) process.wait() </code></pre> <p>This will halt the thread until the subprocess is done.</p>
1
2016-07-27T11:15:45Z
[ "python", "selenium", "python-multithreading" ]
Child dialog doesn't show up in PyQt5
38,611,296
<p><br></p> <p>Hi, I'm trying to make simple GUI application using PyQt5, Python 3.4 and Windows 7.</p> <p>Below code works properly. </p> <pre><code># coding: utf-8 import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog class MainWnd(QMainWindow): def __init__(self): super().__init__() self.popup_dlg = None self.init_ui() def init_ui(self): self.setGeometry(100, 100, 300, 200) self.show() self.popup_dlg = ChildWnd() class ChildWnd(QDialog): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.resize(200, 100) self.show() if __name__ == "__main__": app = QApplication(sys.argv) mw = MainWnd() sys.exit(app.exec_()) </code></pre> <p>Two windows are created. One is main window and the other is child window(popup window). <strong>But what I want is to make child window's default location is centered of main window</strong>. </p> <p>So I've modified the code like this.</p> <pre><code># coding: utf-8 import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog class MainWnd(QMainWindow): def __init__(self): super().__init__() self.popup_dlg = None self.init_ui() def init_ui(self): self.setGeometry(100, 100, 300, 200) self.show() self.popup_dlg = ChildWnd(self) # make instance with parent window argument. class ChildWnd(QDialog): def __init__(self, parent_wnd): super().__init__() self.setParent(parent_wnd) # set child window's parent self.init_ui() def init_ui(self): self.resize(200, 100) self.show() if __name__ == "__main__": app = QApplication(sys.argv) mw = MainWnd() sys.exit(app.exec_()) </code></pre> <p>But this code makes problem. Child window doesn't show up. Only main window(=parent window) shows. In Qt's QDialog's manual, I found this.</p> <blockquote> <p>but if it has a parent, its default location is centered on top of the parent's top-level widget (if it is not top-level itself).</p> </blockquote> <p>This is why I added the <strong>setParent()</strong>.</p> <p>What should I do?</p> <p>Please help me!!</p>
0
2016-07-27T11:10:30Z
38,611,885
<p>As specified in the <a href="http://doc.qt.io/qt-5.7/qdialog.html" rel="nofollow">documentation</a> calling <code>setParent</code> will just change the ownership of the <code>QDialog</code> widget. If you want the <code>QDialog</code> widget to be centered within it's parent, you need to pass the parent widget instance to the super constructor of your <code>QDialog</code>:</p> <pre><code>class ChildWnd(QDialog): def __init__(self, parent_wnd): super().__init__(parent_wnd) self.init_ui() def init_ui(self): self.resize(200, 100) self.show() </code></pre>
0
2016-07-27T11:38:08Z
[ "python", "pyqt", "pyside" ]
Formulating Linear Integer Programming Constraint
38,611,360
<p>I'm trying to formulate a constraint for an optimization problem that forces the solution (a combination of products, represented by binary numbers to signify if they got picked or not) to have a certain property in order.</p> <p>So let's say products 1, 2 and 5 got selected, that solution is represented by [1, 1, 0, 0, 1]. These products have another property (location) that has to be in order. A Python function for checking would be:</p> <pre><code>def products_in_order(products_selected): locations = [p.location for p in products_selected] # locations = [80, 79, 81] (for instance) return max(locations) - min(locations) &lt;= 2 </code></pre> <p>(This works because they're never in the same location)</p> <p><em>However</em>, it gets harder. The maximum location is 99, wrapping around: so [98, 99, 0] is a valid solution as well.</p> <p>There are always exactly three products selected.</p> <p>Thanks for any help you can give, I've been struggling with this for quite some time. Right now I'm enumerating all possible configurations, resulting in 100 constraints (which makes things sloooow).</p> <p>JR</p>
3
2016-07-27T11:13:20Z
38,614,427
<p>The condition you are looking for is</p> <pre><code>return abs( mod( max(locations) - min(locations) +50,100)-50) &lt;=2 </code></pre> <p>or in a general form:</p> <pre><code>abs(mod( distance + range/2,range)-range/2) </code></pre> <p>This gives the minimum distance in a circular space. It is commonly used to compute the angular distance of 2 given points in a circle, where range is <code>2*pi</code> and distance is <code>angle2-angle1</code></p>
0
2016-07-27T13:30:39Z
[ "python", "matlab", "mathematical-optimization", "linear-programming" ]
Formulating Linear Integer Programming Constraint
38,611,360
<p>I'm trying to formulate a constraint for an optimization problem that forces the solution (a combination of products, represented by binary numbers to signify if they got picked or not) to have a certain property in order.</p> <p>So let's say products 1, 2 and 5 got selected, that solution is represented by [1, 1, 0, 0, 1]. These products have another property (location) that has to be in order. A Python function for checking would be:</p> <pre><code>def products_in_order(products_selected): locations = [p.location for p in products_selected] # locations = [80, 79, 81] (for instance) return max(locations) - min(locations) &lt;= 2 </code></pre> <p>(This works because they're never in the same location)</p> <p><em>However</em>, it gets harder. The maximum location is 99, wrapping around: so [98, 99, 0] is a valid solution as well.</p> <p>There are always exactly three products selected.</p> <p>Thanks for any help you can give, I've been struggling with this for quite some time. Right now I'm enumerating all possible configurations, resulting in 100 constraints (which makes things sloooow).</p> <p>JR</p>
3
2016-07-27T11:13:20Z
38,678,926
<p>I ended up solving this problem with a meta solution, that a friend of mine came up with.</p> <p>Since choosing the product with position X infers the other allowed choices (namely X+1 and X+2) it makes sense to optimize on groups of products, not on individual products. I've built this and it works beautifully.</p> <p>Thanks for the responses!</p>
1
2016-07-30T22:08:48Z
[ "python", "matlab", "mathematical-optimization", "linear-programming" ]
Classification using SVM
38,611,447
<p>In an attempt to classify text I want to use SVM. I want to classify test data into one of the labels(health/adult) The training &amp; test data are text files</p> <p>I am using python's scikit library. While I was saving the text to txt files I encoded it in <code>utf-8</code> that's why i am decoding them in the snippet. Here's my attempted code</p> <pre><code>String = String.decode('utf-8') String2 = String2.decode('utf-8') bigram_vectorizer = CountVectorizer(ngram_range=(1, 2), token_pattern=r'\b\w+\b', min_df=1) X_2 = bigram_vectorizer.fit_transform(String2).toarray() X_1 = bigram_vectorizer.fit_transform(String).toarray() X_train = np.array([X_1,X_2]) print type(X_train) y = np.array([1, 2]) clf = SVC() clf.fit(X_train, y) #prepare test data print(clf.predict(X)) </code></pre> <p>This is the error I am getting</p> <pre><code> File "/Users/guru/python_projects/implement_LDA/lda/apply.py", line 107, in &lt;module&gt; clf.fit(X_train, y) File "/Users/guru/python_projects/implement_LDA/lda/lib/python2.7/site-packages/sklearn/svm/base.py", line 150, in fit X = check_array(X, accept_sparse='csr', dtype=np.float64, order='C') File "/Users/guru/python_projects/implement_LDA/lda/lib/python2.7/site-packages/sklearn/utils/validation.py", line 373, in check_array array = np.array(array, dtype=dtype, order=order, copy=copy) ValueError: setting an array element with a sequence. </code></pre> <p>When I searched for the error, I found some results but they even didn't help. I think I am logically wrong here in applying SVM model. Can someone give me a hint on this?</p> <p>Ref: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC" rel="nofollow">[1]</a><a href="http://scikit-learn.org/stable/modules/feature_extraction.html" rel="nofollow">[2]</a></p>
0
2016-07-27T11:16:41Z
38,612,882
<p>You have to combine your samples, vectorize them and then fit the classifier. Like this:</p> <pre><code>String = String.decode('utf-8') String2 = String2.decode('utf-8') bigram_vectorizer = CountVectorizer(ngram_range=(1, 2), token_pattern=r'\b\w+\b', min_df=1) X_train = bigram_vectorizer.fit_transform(np.array([String, String2])) print type(X_train) y = np.array([1, 2]) clf = SVC() clf.fit(X_train, y) #prepare test data print(clf.predict(bigram_vectorizer.transform(np.array([X1, X2, ...])))) </code></pre> <p>But 2 sample it's a very few amount of data so likely your prediction will not be accurate.</p> <p><strong>EDITED:</strong></p> <p>Also you can combine transformation and classification in one step using Pipeline.</p> <pre><code>from sklearn.pipeline import Pipeline print type(X_train) # Should be a list of texts length 100 in your case y_train = ... # Should be also a list of length 100 clf = Pipeline([ ('transformer', CountVectorizer(...)), ('estimator', SVC()), ]) clf.fit(X_train, y_train) X_test = np.array(["sometext"]) # array of test texts length = 1 print(clf.predict(X_test)) </code></pre>
2
2016-07-27T12:23:51Z
[ "python", "machine-learning", "classification", "svm", "text-classification" ]
Django - Export ASCII CSV
38,611,456
<p>I want to export a CSV-file encoded in ASCII but the default is UTF-8 if I encode the strings i get the bytecode written in the csv (b'String')</p> <pre><code> response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="datev_export.csv"' writer = csv.writer(response, delimiter=";",) row = ['some', 'strings'] writer.writerow(first_row) return response </code></pre> <p>So how can I encode my string to ASCII without the leading b'' ?</p>
0
2016-07-27T11:16:59Z
38,612,747
<p>You can use the encode method of strings like</p> <pre><code>"asdf".encode("ascii") </code></pre> <p>for bytes there is the decode method for getting things back like</p> <pre><code>b"asdf".decode("ascii") </code></pre>
0
2016-07-27T12:18:06Z
[ "python", "django", "export-to-csv" ]
Python: get every possible combination of weights for a portfolio
38,611,467
<p>I think this problem can be solved using either itertools or cartesian, but I'm fairly new to Python and am struggling to use these:</p> <p>I have a portfolio of 5 stocks, where each stock can have a weighting of -0.4, -0.2, 0, 0.2 or 0.4, with weightings adding up to 0. How do I create a function that produces a list of every possible combination of weights. e.g. [-0.4, 0.2, 0, 0.2, 0]... etc</p> <p>Ideally, the function would work for n stocks, as I will eventually want to do the same process for 50 stocks. </p> <p>edit: To clarify, I'm looking for all combinations of length n (in this case 5), summing to 0. <strong>The values can repeat</strong>: e.g: [0.2, 0.2, -0.4, 0, 0], [ 0.4, 0, -0.2, -0.2, 0.4], [0,0,0,0.2,-0.2], [0, 0.4, -0.4, 0.2, -0.2] etc. So [0,0,0,0,0] would be a possible combination. The fact that there are 5 possible weightings and 5 stocks is a coincidence (which i should have avoided!), this same question could be with 5 possible weightings and 3 stocks or 7 stocks. Thanks.</p>
6
2016-07-27T11:17:23Z
38,611,682
<p>Is this what you are looking for: if <code>L = [-0.4, 0.2, 0, 0.2, 0]</code></p> <pre><code>AllCombi = itertools.permutations(L) for each in AllCombi: print each </code></pre>
-3
2016-07-27T11:27:56Z
[ "python", "list", "itertools", "cartesian-product" ]
Python: get every possible combination of weights for a portfolio
38,611,467
<p>I think this problem can be solved using either itertools or cartesian, but I'm fairly new to Python and am struggling to use these:</p> <p>I have a portfolio of 5 stocks, where each stock can have a weighting of -0.4, -0.2, 0, 0.2 or 0.4, with weightings adding up to 0. How do I create a function that produces a list of every possible combination of weights. e.g. [-0.4, 0.2, 0, 0.2, 0]... etc</p> <p>Ideally, the function would work for n stocks, as I will eventually want to do the same process for 50 stocks. </p> <p>edit: To clarify, I'm looking for all combinations of length n (in this case 5), summing to 0. <strong>The values can repeat</strong>: e.g: [0.2, 0.2, -0.4, 0, 0], [ 0.4, 0, -0.2, -0.2, 0.4], [0,0,0,0.2,-0.2], [0, 0.4, -0.4, 0.2, -0.2] etc. So [0,0,0,0,0] would be a possible combination. The fact that there are 5 possible weightings and 5 stocks is a coincidence (which i should have avoided!), this same question could be with 5 possible weightings and 3 stocks or 7 stocks. Thanks.</p>
6
2016-07-27T11:17:23Z
38,611,752
<p>If you just want a list of all the combinations, use <a class='doc-link' href="http://stackoverflow.com/documentation/python/1564/itertools-module/9828/itertools-combinations#t=201607271138098681664"><code>itertools.combinations</code></a>:</p> <pre><code>w = [-0.4, -0.2, 0, 0.2, 0.4] l = len(w) if __name__ == '__main__': for i in xrange(1, l+1): for p in itertools.combinations(w, i): print p </code></pre> <p>If you want to count the different weights that can be created with these combinations, it's a bit more complicated.</p> <p>First, you generate permutations with 1, 2, 3, ... elements. Then you take the sum of them. Then you add the sum to the set (will no do anything if the number is already present, very fast operation). Finally you convert to a list and sort it.</p> <pre><code>from itertools import combinations def round_it(n, p): """rounds n, to have maximum p figures to the right of the comma""" return int((10**p)*n)/float(10**p) w = [-0.4, -0.2, 0, 0.2, 0.4] l = len(w) res = set() if __name__ == '__main__': for i in xrange(1, l+1): for p in combinations(w, i): res.add(round_it(sum(p), 10)) # rounding necessary to avoid artifacts print sorted(list(res)) </code></pre>
-1
2016-07-27T11:31:39Z
[ "python", "list", "itertools", "cartesian-product" ]
Python: get every possible combination of weights for a portfolio
38,611,467
<p>I think this problem can be solved using either itertools or cartesian, but I'm fairly new to Python and am struggling to use these:</p> <p>I have a portfolio of 5 stocks, where each stock can have a weighting of -0.4, -0.2, 0, 0.2 or 0.4, with weightings adding up to 0. How do I create a function that produces a list of every possible combination of weights. e.g. [-0.4, 0.2, 0, 0.2, 0]... etc</p> <p>Ideally, the function would work for n stocks, as I will eventually want to do the same process for 50 stocks. </p> <p>edit: To clarify, I'm looking for all combinations of length n (in this case 5), summing to 0. <strong>The values can repeat</strong>: e.g: [0.2, 0.2, -0.4, 0, 0], [ 0.4, 0, -0.2, -0.2, 0.4], [0,0,0,0.2,-0.2], [0, 0.4, -0.4, 0.2, -0.2] etc. So [0,0,0,0,0] would be a possible combination. The fact that there are 5 possible weightings and 5 stocks is a coincidence (which i should have avoided!), this same question could be with 5 possible weightings and 3 stocks or 7 stocks. Thanks.</p>
6
2016-07-27T11:17:23Z
38,612,134
<p>I like using the <code>filter</code> function:</p> <pre><code>from itertools import permutations w = [-0.4, -0.2, 0, 0.2, 0.4] def foo(w): perms = list(permutations(w)) sum0 = filter(lambda x: sum(x)==0, perms) return sum0 print foo(w) </code></pre>
0
2016-07-27T11:48:50Z
[ "python", "list", "itertools", "cartesian-product" ]
Python: get every possible combination of weights for a portfolio
38,611,467
<p>I think this problem can be solved using either itertools or cartesian, but I'm fairly new to Python and am struggling to use these:</p> <p>I have a portfolio of 5 stocks, where each stock can have a weighting of -0.4, -0.2, 0, 0.2 or 0.4, with weightings adding up to 0. How do I create a function that produces a list of every possible combination of weights. e.g. [-0.4, 0.2, 0, 0.2, 0]... etc</p> <p>Ideally, the function would work for n stocks, as I will eventually want to do the same process for 50 stocks. </p> <p>edit: To clarify, I'm looking for all combinations of length n (in this case 5), summing to 0. <strong>The values can repeat</strong>: e.g: [0.2, 0.2, -0.4, 0, 0], [ 0.4, 0, -0.2, -0.2, 0.4], [0,0,0,0.2,-0.2], [0, 0.4, -0.4, 0.2, -0.2] etc. So [0,0,0,0,0] would be a possible combination. The fact that there are 5 possible weightings and 5 stocks is a coincidence (which i should have avoided!), this same question could be with 5 possible weightings and 3 stocks or 7 stocks. Thanks.</p>
6
2016-07-27T11:17:23Z
38,612,748
<p>I understand the values can repeat, but all have to sum to zero, therefore the solution might be:</p> <pre><code>&gt;&gt;&gt; from itertools import permutations &gt;&gt;&gt; weights = [-0.4, -0.2, 0, 0.2, 0.4] &gt;&gt;&gt; result = (com for com in permutations(weights) if sum(com)==0) &gt;&gt;&gt; for i in result: print(i) </code></pre> <hr> <p>edit: you might use <code>product</code> as @Steve Jassop suggested. </p> <pre><code>combi = (i for i in itertools.product(weights, repeat= len(weights)) if not sum(i)) for c in combi: print(c) </code></pre>
1
2016-07-27T12:18:08Z
[ "python", "list", "itertools", "cartesian-product" ]
Python: get every possible combination of weights for a portfolio
38,611,467
<p>I think this problem can be solved using either itertools or cartesian, but I'm fairly new to Python and am struggling to use these:</p> <p>I have a portfolio of 5 stocks, where each stock can have a weighting of -0.4, -0.2, 0, 0.2 or 0.4, with weightings adding up to 0. How do I create a function that produces a list of every possible combination of weights. e.g. [-0.4, 0.2, 0, 0.2, 0]... etc</p> <p>Ideally, the function would work for n stocks, as I will eventually want to do the same process for 50 stocks. </p> <p>edit: To clarify, I'm looking for all combinations of length n (in this case 5), summing to 0. <strong>The values can repeat</strong>: e.g: [0.2, 0.2, -0.4, 0, 0], [ 0.4, 0, -0.2, -0.2, 0.4], [0,0,0,0.2,-0.2], [0, 0.4, -0.4, 0.2, -0.2] etc. So [0,0,0,0,0] would be a possible combination. The fact that there are 5 possible weightings and 5 stocks is a coincidence (which i should have avoided!), this same question could be with 5 possible weightings and 3 stocks or 7 stocks. Thanks.</p>
6
2016-07-27T11:17:23Z
38,613,816
<p>Something like this, although it's not really efficient.</p> <pre><code>from decimal import Decimal import itertools # possible optimization: use integers rather than Decimal weights = [Decimal("-0.4"), Decimal("-0.2"), Decimal(0), Decimal("0.2"), Decimal("0.4")] def possible_weightings(n = 5, target = 0): for all_bar_one in itertools.product(weights, repeat = n - 1): final = target - sum(all_bar_one) if final in weights: yield all_bar_one + (final,) </code></pre> <p>I repeat from comments, you <em>cannot</em> do this for <code>n = 50</code>. The code yields the right values, but there isn't time in the universe to iterate over all the possible weightings.</p> <p>This code isn't brilliant. It does some unnecessary work examining cases where, for example, the sum of all but the first two is already greater than 0.8 and so there's no point separately checking all the possibilities for the first of those two.</p> <p>So, this does <code>n = 5</code> in nearly no time, but there is some value of <code>n</code> where this code becomes infeasibly slow, and you could get further with better code. You still won't get to 50. I'm too lazy to write that better code, but basically instead of <code>all_bar_one</code> you can make recursive calls to <code>possible_weightings</code> with successively smaller values of <code>n</code> and a value of <code>target</code> equal to the target you were given, minus the sum you have so far. Then prune all the branches you don't need to take, by bailing out early in cases where <code>target</code> is too large (positive or negative) to be reached using only <code>n</code> values.</p>
3
2016-07-27T13:04:36Z
[ "python", "list", "itertools", "cartesian-product" ]
Python: get every possible combination of weights for a portfolio
38,611,467
<p>I think this problem can be solved using either itertools or cartesian, but I'm fairly new to Python and am struggling to use these:</p> <p>I have a portfolio of 5 stocks, where each stock can have a weighting of -0.4, -0.2, 0, 0.2 or 0.4, with weightings adding up to 0. How do I create a function that produces a list of every possible combination of weights. e.g. [-0.4, 0.2, 0, 0.2, 0]... etc</p> <p>Ideally, the function would work for n stocks, as I will eventually want to do the same process for 50 stocks. </p> <p>edit: To clarify, I'm looking for all combinations of length n (in this case 5), summing to 0. <strong>The values can repeat</strong>: e.g: [0.2, 0.2, -0.4, 0, 0], [ 0.4, 0, -0.2, -0.2, 0.4], [0,0,0,0.2,-0.2], [0, 0.4, -0.4, 0.2, -0.2] etc. So [0,0,0,0,0] would be a possible combination. The fact that there are 5 possible weightings and 5 stocks is a coincidence (which i should have avoided!), this same question could be with 5 possible weightings and 3 stocks or 7 stocks. Thanks.</p>
6
2016-07-27T11:17:23Z
38,618,914
<p>Different approach. </p> <h1>1 Figure out all sequences of the weights that add up to zero, in order.</h1> <p>for example, these are some possibilities (using whole numbers to type less):<br> [0, 0, 0, 0, 0]<br> [-4, 0, 0, +2, +2]<br> [-4, 0, 0, 0, +4]</p> <p>[-4, +4, 0, 0, 0] is incorrect because weights are not picked in order.</p> <h1>2 Permute what you got above, because the permutations will add up to zero as well.</h1> <p>This is where you'd get your [-4, 0, 0, 0, +4] <strong>and</strong> [-4, +4, 0, 0, 0]</p> <p>OK, being lazy. I am going to pseudo-code/comment-code a good deal of my solution. Not that strong at recursion, the stuff is too tricky to code quickly and I have doubts that this type of solution scales up to 50.</p> <p>i.e. I don't think I am right, but it might give someone else an idea.</p> <pre><code>def find_solution(weights, length, last_pick, target_sum): # returns a list of solutions, in growing order, of weights adding up to the target_sum # weights are the sequence of possible weights - IN ORDER, NO REPEATS # length is how many weights we are adding up # last_pick - the weight picked by the caller # target_sum is what we are aiming for, which will always be &gt;=0 solutions = [] if length &gt; 1: #since we are picking in order, having picked 0 "disqualifies" -4 and -2. if last_pick &gt; weights[0]: weights = [w for w in weights if w &gt;= last_pick] #all remaining weights are possible for weight in weights: child_target_sum = target_sum + weight #basic idea, we are picking in growing order #if we start out picking +2 in a [-4,-2,0,+2,+4] list in order, then we are constrained to finding -2 #with just 2 and 4 as choices. won't work. if child_target_sum &lt;= 0: break child_solutions = find_solution(weights, length=length-1, last_pick=weight, target_sum=child_target_sum) [solutions.append([weight] + child ) for child in child_solutions if child_solution] else: #only 1 item to pick left, so it has be the target_sum if target_sum in weights: return [[target_sum]] return solutions weights = list(set(weights)) weights.sort() #those are not permutated yet solutions = find_solutions(weights, len(solution), -999999999, 0) permutated = [] for solution in solutions: permutated.extend(itertools.permutations(solution)) </code></pre>
0
2016-07-27T16:48:40Z
[ "python", "list", "itertools", "cartesian-product" ]
How to model "family and others" thing?
38,611,528
<p>I need to model family, parents, children and ordinary people entities. How can I do that? Obviously, I could create 4 or even 5 different classess: family, 2 for both parents, one for a children and one for people. But I think there's redundancy in this approach. On the other hand, if I introduce a field "type" being either family, mother, etc..., then I'd have to create also nullable field-reference for family and maybe other stuff.</p> <p>Your advice?</p>
0
2016-07-27T11:20:33Z
38,611,607
<p>In this case I think it would make sense to simply have two classes, for example</p> <pre><code>class Person: def __init__(self, name): self.name = name class Family: def __init__(self): self.children = [] self.parents = [] </code></pre> <p>Then <code>Family.children</code> and <code>Family.parents</code> could be lists of <code>Person</code> objects, where you could have any number of children or parents.</p> <p>You could also add some more attributes to <code>Person</code> if you wanted to store relationships, like a <code>Person</code> could have members of their <code>.siblings</code> or <code>.parents</code> or <code>.children</code></p>
2
2016-07-27T11:24:17Z
[ "python", "django", "oop" ]
I need to figure out how to make my program repeat. (Python coding class)
38,611,900
<p>I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.</p> <pre><code>import random x = int(input("Please enter an integer: ")) if x &lt; 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') maximum = 10 ** x; maximum += 1 firstnum = random.randrange(1,maximum) # return an int from 1 to 100 secondnum = random.randrange(1, maximum) compsum = firstnum + secondnum # adds the 2 random numbers together # print (compsum) # print for troubleshooting print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user added = int(input("Your answer is: ")) # gets user input if added == compsum: # compares user input to real answer print("You are correct!!!") else: print ("Sorry, you are incorrect") </code></pre>
0
2016-07-27T11:38:55Z
38,612,003
<p>If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.</p>
0
2016-07-27T11:43:30Z
[ "python" ]
I need to figure out how to make my program repeat. (Python coding class)
38,611,900
<p>I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.</p> <pre><code>import random x = int(input("Please enter an integer: ")) if x &lt; 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') maximum = 10 ** x; maximum += 1 firstnum = random.randrange(1,maximum) # return an int from 1 to 100 secondnum = random.randrange(1, maximum) compsum = firstnum + secondnum # adds the 2 random numbers together # print (compsum) # print for troubleshooting print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user added = int(input("Your answer is: ")) # gets user input if added == compsum: # compares user input to real answer print("You are correct!!!") else: print ("Sorry, you are incorrect") </code></pre>
0
2016-07-27T11:38:55Z
38,612,057
<p>You'll want to do something like this:</p> <pre><code>def foo(): print("Doing good work...") while True: foo() if input("Want to do more good work? [y/n] ").strip().lower() == 'n': break </code></pre> <p>I've seen this construct (i.e., using a <code>break</code>) used more often than using a <a href="https://en.wikipedia.org/wiki/Sentinel_value" rel="nofollow">sentinel</a> in Python, but either will work. The sentinel version looks like this:</p> <pre><code>do_good_work = True while do_good_work: foo() do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n' </code></pre> <p>You'll want to do more error checking than me in your code, too.</p>
4
2016-07-27T11:45:55Z
[ "python" ]
I need to figure out how to make my program repeat. (Python coding class)
38,611,900
<p>I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.</p> <pre><code>import random x = int(input("Please enter an integer: ")) if x &lt; 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') maximum = 10 ** x; maximum += 1 firstnum = random.randrange(1,maximum) # return an int from 1 to 100 secondnum = random.randrange(1, maximum) compsum = firstnum + secondnum # adds the 2 random numbers together # print (compsum) # print for troubleshooting print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user added = int(input("Your answer is: ")) # gets user input if added == compsum: # compares user input to real answer print("You are correct!!!") else: print ("Sorry, you are incorrect") </code></pre>
0
2016-07-27T11:38:55Z
38,612,876
<p>Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:</p> <pre><code>print('Would you like to test your adding or subtracting skills?') user_choice = input('Answer A for adding or S for subtracting: ') if user_choice.upper() == 'A': # ask adding question elif user_choice.upper() == 'S': # ask substracting question else: print('Sorry I did not understand your choice') </code></pre> <p>For repeating the code <code>While</code> loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.</p> <pre><code>while True: # Condition is always satisfied code will run forever # put your program logic here if input('Would you like another test? [Y/N]').upper() == 'N': break # Break statement exits the loop </code></pre> <p>The result of using <code>input()</code> function is always a string. We use a <code>.upper()</code> method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.</p>
1
2016-07-27T12:23:38Z
[ "python" ]
how to enable serial port(ttyAMA0) communication using "pi serial" in pi3?
38,611,986
<p>i want to enable serial port communication in pi 3 using pi serial. but when i try to open a port like this</p> <p>test=serial.Serial("/dev/ttyAMA0", 115200) </p> <p>it gives me the error "<strong>port already open</strong>".</p> <p>how can i solve it?</p>
1
2016-07-27T11:42:57Z
38,611,987
<p><strong>finally this got work for my pi3 (os: debian jessie)</strong></p> <p>please follow these 6 steps carefully.</p> <p><strong>Step 1</strong> - Install Raspbian Jessie onto a SD card and boot the Pi when connected to a network Login via terminal or desktop and shell Configure the system with:</p> <pre><code>sudo raspi-config </code></pre> <p>Expand filesystem and enable serial on advanced page, exit and reboot.</p> <p><strong>Step 2</strong> -this won't necessary if you have jessie new release. Update the system with:</p> <pre><code> sudo apt-get update sudo apt-get upgrade </code></pre> <p><strong>Step 3</strong> - Device Tree settings as below:</p> <p>Add device tree to <strong>/boot/config.txt</strong> to disable the Raspberry Pi 3 bluetooth.</p> <pre><code>sudo nano /boot/config.txt </code></pre> <p><strong>Add at the end of the file</strong></p> <p>*if you want to change the blutooth to miniuart port(bad)</p> <pre><code>dtoverlay=pi3-miniuart-bt </code></pre> <p>*if you want to disable the blutooth(good)</p> <pre><code>dtoverlay=pi3-disable-bt </code></pre> <p>Exit the editor saving your changes.</p> <p><strong>Step 4</strong> - reboot the pi</p> <pre><code>sudo reboot </code></pre> <p><strong>step 5</strong> -</p> <p>a)to disable the Serial Console edit the file using</p> <pre><code>sudo nano /boot/cmdline.txt </code></pre> <p>remove the word phase "<code>console=serial0,115200</code>" or "<code>console=ttyAMA0,115200</code>"</p> <p>Exit and save your changes</p> <p>b)to Enable the Serial Console edit the file using</p> <pre><code>sudo nano /boot/cmdline.txt </code></pre> <p>Change the file to the following:</p> <pre><code>dwc_otg.lpm_enable=0 console=tty1 console=serial0(or ttyAMA0),115200 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait </code></pre> <p>Exit and save your changes </p> <p><strong>Step 6</strong> - reboot the pi</p> <pre><code>sudo reboot -----------------**that's all,have fun**------------------------------- </code></pre>
1
2016-07-27T11:42:57Z
[ "python", "serial-port", "serial-communication", "raspberry-pi3" ]
Eve: Endpoint representing currently logged-in user
38,612,038
<p>I am using the auth feature in combination with oauth. I would like to have an endpoint like: <code>/api/v1/user/current</code> representing the currently logged-in user. Is there a way to do that?</p>
1
2016-07-27T11:45:11Z
38,639,692
<p>You could use regular Flask routing to achieve that. Remember Eve is a Flask subclass, so whatever works with Flask generally work with Eve too, enabling custom endpoints included:</p> <pre><code>from eve import Eve app = Eve() @app.route('/user/current') def current_user(): # perform your magic here user_name = your_own_logic() return 'Welcome back, %s' % user_name if __name__ == '__main__': app.run() </code></pre> <p>See <a href="http://nicolaiarocci.com/building-custom-endpoint-handlers-with-eve/" rel="nofollow">this article</a> for details.</p>
0
2016-07-28T14:43:46Z
[ "python", "eve" ]
Pandas Flatten a dataframe to a single column
38,612,154
<p>I have dataset in the following format:</p> <pre><code>df = pd.DataFrame({'x':[1,2,3], 'y':[10,20,30], 'v1':[3,2,3] , 'v2':[13,25,31] }) &gt;&gt; v1 v2 x y 3 13 1 10 2 25 2 20 3 31 3 30 </code></pre> <p>Setting the index column with x, I want to flatten the data combining v1 and v2 (V), The expected output is like:</p> <pre><code>&gt;&gt; x y V 1 10 3 1 10 13 2 20 2 2 20 25 3 30 3 3 30 31 </code></pre> <p>And again bringing to the original format of df. I tried reshaping using stack and unstack, but I couldn't get it the way, which I was expecting.</p> <p>Many Thanks!</p>
1
2016-07-27T11:50:21Z
38,612,189
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> column <code>level_2</code>:</p> <pre><code>print (df.set_index(['x','y']).stack().reset_index(name='V').drop('level_2', axis=1)) x y V 0 1 10 3 1 1 10 13 2 2 20 2 3 2 20 25 4 3 30 3 5 3 30 31 </code></pre> <p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>:</p> <pre><code>print (pd.melt(df, id_vars=['x','y'], value_name='V') .drop('variable', axis=1) .sort_values('x')) x y V 0 1 10 3 3 1 10 13 1 2 20 2 4 2 20 25 2 3 30 3 5 3 30 31 </code></pre>
2
2016-07-27T11:52:24Z
[ "python", "python-3.x", "pandas" ]
Pandas Flatten a dataframe to a single column
38,612,154
<p>I have dataset in the following format:</p> <pre><code>df = pd.DataFrame({'x':[1,2,3], 'y':[10,20,30], 'v1':[3,2,3] , 'v2':[13,25,31] }) &gt;&gt; v1 v2 x y 3 13 1 10 2 25 2 20 3 31 3 30 </code></pre> <p>Setting the index column with x, I want to flatten the data combining v1 and v2 (V), The expected output is like:</p> <pre><code>&gt;&gt; x y V 1 10 3 1 10 13 2 20 2 2 20 25 3 30 3 3 30 31 </code></pre> <p>And again bringing to the original format of df. I tried reshaping using stack and unstack, but I couldn't get it the way, which I was expecting.</p> <p>Many Thanks!</p>
1
2016-07-27T11:50:21Z
38,612,286
<p><code>pd.lreshape</code> can reformat wide data to long format:</p> <pre><code>In [55]: pd.lreshape(df, {'V':['v1', 'v2']}) Out[57]: x y V 0 1 10 3 1 2 20 2 2 3 30 3 3 1 10 13 4 2 20 25 5 3 30 31 </code></pre> <p><code>lreshape</code> is an undocumented "experimental" feature. To learn more about <code>lreshape</code> see <code>help(pd.lreshape)</code>.</p> <hr> <p>If you need reversible operations, use jezrael's <code>pd.melt</code> solution to go from wide to long format, and use <code>pivot_table</code> to go from long to wide format:</p> <pre><code>In [72]: melted = pd.melt(df, id_vars=['x', 'y'], value_name='V'); melted Out[72]: x y variable V 0 1 10 v1 3 1 2 20 v1 2 2 3 30 v1 3 3 1 10 v2 13 4 2 20 v2 25 5 3 30 v2 31 In [74]: df2 = melted.pivot_table(index=['x','y'], columns=['variable'], values='V').reset_index(); df2 Out[74]: variable x y v1 v2 0 1 10 3 13 1 2 20 2 25 2 3 30 3 31 </code></pre> <p>Notice that you must hang on to the <code>variable</code> column if you wish to return to <code>df2</code>. Also keep in mind that it is more efficient to simply retain a reference to <code>df</code> than to <em>recompute</em> it using <code>melted</code> and <code>pivot_table</code>.</p>
2
2016-07-27T11:57:18Z
[ "python", "python-3.x", "pandas" ]
Create dict with key/value and key/value reversed
38,612,266
<p>Having such list </p> <p><code>example = ['ab', 'cd']</code></p> <p>I need to get <code>{'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}</code></p> <p>With regular loop I could do this like:</p> <pre><code>result = {} for i,j in example: result[i] = j result[j] = i </code></pre> <p>Question: How can I do the same on one line?</p>
3
2016-07-27T11:56:29Z
38,612,430
<p>list comprehension with dictionary updates</p> <pre><code>[result.update({x[0]:x[1],x[1]:x[0]}) for x in example] </code></pre>
0
2016-07-27T12:03:47Z
[ "python", "generator", "list-comprehension" ]
Create dict with key/value and key/value reversed
38,612,266
<p>Having such list </p> <p><code>example = ['ab', 'cd']</code></p> <p>I need to get <code>{'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}</code></p> <p>With regular loop I could do this like:</p> <pre><code>result = {} for i,j in example: result[i] = j result[j] = i </code></pre> <p>Question: How can I do the same on one line?</p>
3
2016-07-27T11:56:29Z
38,612,458
<p>A <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a> should do:</p> <pre><code>In [726]: {k: v for (k, v) in map(tuple, example + map(reversed, example))} # Python 2 Out[726]: {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'} In [727]: {s[0]: s[1] for s in (example + [x[::-1] for x in example])} # Python 3 Out[727]: {'b': 'a', 'a': 'b', 'd': 'c', 'c': 'd'} </code></pre>
0
2016-07-27T12:05:14Z
[ "python", "generator", "list-comprehension" ]
Create dict with key/value and key/value reversed
38,612,266
<p>Having such list </p> <p><code>example = ['ab', 'cd']</code></p> <p>I need to get <code>{'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}</code></p> <p>With regular loop I could do this like:</p> <pre><code>result = {} for i,j in example: result[i] = j result[j] = i </code></pre> <p>Question: How can I do the same on one line?</p>
3
2016-07-27T11:56:29Z
38,612,576
<p>Another possible solution:</p> <pre><code>dict(example + [s[::-1] for s in example]) </code></pre> <p><code>[s[::-1] for s in example]</code> <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions">creates a new list with all strings reversed</a>. <code>example + [s[::-1] for s in example]</code> combines the lists together. Then the <code>dict</code> constructor builds a dictionary from the list of key-value pairs (the first character and the last character of each string):</p> <pre><code>In [5]: dict(example + [s[::-1] for s in example]) Out[5]: {'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'} </code></pre>
2
2016-07-27T12:10:56Z
[ "python", "generator", "list-comprehension" ]
Create dict with key/value and key/value reversed
38,612,266
<p>Having such list </p> <p><code>example = ['ab', 'cd']</code></p> <p>I need to get <code>{'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}</code></p> <p>With regular loop I could do this like:</p> <pre><code>result = {} for i,j in example: result[i] = j result[j] = i </code></pre> <p>Question: How can I do the same on one line?</p>
3
2016-07-27T11:56:29Z
38,612,610
<p>You can use <code>;</code> to seperate logical lines</p> <pre><code>result=dict(example); result.update((k,v) for v,k in example) </code></pre> <p>But of course </p> <pre><code>result=dict(example+map(reversed,example)) # only in python 2.x </code></pre> <p>or</p> <pre><code>result=dict([(k,v) for k,v in example]+[(k,v) for v,k in example]) </code></pre> <p>work, too.</p>
0
2016-07-27T12:12:18Z
[ "python", "generator", "list-comprehension" ]
Create dict with key/value and key/value reversed
38,612,266
<p>Having such list </p> <p><code>example = ['ab', 'cd']</code></p> <p>I need to get <code>{'a': 'b', 'b': 'a', 'c': 'd', 'd': 'c'}</code></p> <p>With regular loop I could do this like:</p> <pre><code>result = {} for i,j in example: result[i] = j result[j] = i </code></pre> <p>Question: How can I do the same on one line?</p>
3
2016-07-27T11:56:29Z
38,613,093
<pre><code>example = ['ab', 'cd'] res1={x[1]:x[0] for x in example} res2={x[0]:x[1] for x in example} res=res1.update(res2) print res1 </code></pre>
0
2016-07-27T12:32:29Z
[ "python", "generator", "list-comprehension" ]
How to create Temporary Security Credentials on AWS
38,612,442
<p>I'm trying to use <code>Apache Libcloud</code> <a href="https://libcloud.apache.org/index.html" rel="nofollow">(Web)</a> and reading the <a href="http://libcloud.readthedocs.io/en/latest/compute/drivers/ec2.html" rel="nofollow">Documentation</a> of how to use it with Amazon EC2 I'm stuck on a step at the beginning.</p> <p>On this step:</p> <pre><code>from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.EC2) driver = cls('temporary access key', 'temporary secret key', token='temporary session token', region="us-west-1") </code></pre> <p>You need to pass the temporary access data and tells you to read <a href="http://docs.aws.amazon.com/es_es/IAM/latest/UserGuide/id_credentials_temp_request.html" rel="nofollow">Amazon Documentation</a> but also I've read the documentation I don't get very clear what I have to do to get my temporal credentials.</p> <p>On the doc says that you can interact with the <code>AWS STS API</code> to connect to the endpoint but I don't understand how do you get the credentials. Moreover, on the example of Libcloud Web they use the personal credentials:</p> <pre><code>ACCESS_ID = 'your access id' SECRET_KEY = 'your secret key' </code></pre> <p>So I'm a bit lost. How I can get my temporal credentials to use it on my code?</p> <p>Thanks and regards.</p>
0
2016-07-27T12:04:22Z
38,620,051
<p>If this code does not run on an EC2 instance I suggest you go with static credentials:</p> <pre><code>ACCESS_ID = 'your access id' SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(ACCESS_ID, SECRET_KEY, region="us-west-1") </code></pre> <p>to create access credentials:</p> <ol> <li>Sign in to the Identity and Access Management (IAM) console at <a href="https://console.aws.amazon.com/iam/" rel="nofollow">https://console.aws.amazon.com/iam/</a>.</li> <li>In the navigation pane, choose Users.</li> <li>Choose the name of the desired user, and then choose the Security Credentials tab.</li> </ol> <p>If needed, expand the Access Keys section and do any of the following:</p> <p>Choose Create Access Key and then choose Download Credentials to save the access key ID and secret access key to a CSV file on your computer. Store the file in a secure location. You will not have access to the secret access key again after this dialog box closes. After you have downloaded the CSV file, choose Close.</p> <p>if you want to run your code from an EC2 machine you can get temporary credentials by assuming an IAM role using the AWS SDK for Python <a href="https://boto3.readthedocs.io/en/latest/guide/quickstart.html" rel="nofollow">https://boto3.readthedocs.io/en/latest/guide/quickstart.html</a> by calling assume_role() on the STS service <a href="https://boto3.readthedocs.io/en/latest/reference/services/sts.html" rel="nofollow">https://boto3.readthedocs.io/en/latest/reference/services/sts.html</a></p>
1
2016-07-27T17:55:49Z
[ "python", "amazon-web-services", "amazon-ec2", "libcloud" ]
Pyplot "cannot connect to X server localhost:10.0" despite ioff() and matplotlib.use('Agg')
38,612,473
<p>I have a piece of code which gets called by a different function, carries out some calculations for me and then plots the output to a file. Seeing as the whole script can take a while to run for larger datasets and since I may want to analyse multiple datasets at a given time I start it in <code>screen</code> then disconnect and close my putty session and check back on it the next day. I am using Ubuntu 14.04. My code looks as follows (I have skipped the calculations):</p> <pre><code>import shelve import os, sys, time import numpy import timeit import logging import csv import itertools import graph_tool.all as gt import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.ioff() #Do some calculations print 'plotting indeg' # Let's plot its in-degree distribution in_hist = gt.vertex_hist(g, "in") y = in_hist[0] err = numpy.sqrt(in_hist[0]) err[err &gt;= y] = y[err &gt;= y] - 1e-2 plt.figure(figsize=(6,4)) plt.errorbar(in_hist[1][:-1], in_hist[0], fmt="o", label="in") plt.gca().set_yscale("log") plt.gca().set_xscale("log") plt.gca().set_ylim(0.8, 1e5) plt.gca().set_xlim(0.8, 1e3) plt.subplots_adjust(left=0.2, bottom=0.2) plt.xlabel("$k_{in}$") plt.ylabel("$NP(k_{in})$") plt.tight_layout() plt.savefig("in-deg-dist.png") plt.close() print 'plotting outdeg' #Do some more stuff </code></pre> <p>The script runs perfectly happily until I get to the plotting commands. To try and get to the root of the problem I am currently running it in putty without screen and with no X11 applications. The ouput I get is the following:</p> <pre><code>plotting indeg PuTTY X11 proxy: unable to connect to forwarded X server: Network error: Connection refused : cannot connect to X server localhost:10.0 </code></pre> <p>I presume this is caused by the code trying to open a window but I thought that by explicitely setting <code>plt.off()</code> that would be disabled. Since it wasn't I followed this thread (<a href="http://stackoverflow.com/questions/4931376/generating-matplotlib-graphs-without-a-running-x-server">Generating matplotlib graphs without a running X server</a> ) and specified the backend, but that didn't solve the problem either. Where might I be going wrong?</p>
1
2016-07-27T12:06:10Z
38,618,012
<p>The calling function calls other functions too which also use matplotlib. These get called only after this one but during the <code>import</code> statement their dependecies get loaded. Seeing as they were loaded first they disabled the subsequent <code>matplotlib.use('Agg')</code> declaration. Moving that declaration to the main script has solved the problem.</p>
0
2016-07-27T16:00:50Z
[ "python", "matplotlib", "x11", "x11-forwarding" ]
Nested Try in While loop
38,612,496
<p>Can someone help me?</p> <p>I've a problem with a nested try statement inside a while statement. The code looks like this:</p> <pre><code>number = raw_input("what is the number? ") if number &lt; 11: Print "that is good!" else: print "your number had to be lower then 11" raw_input("kies een getal: ") while number &lt; 11: try: number == int(number) except ValueError: raw_input(" try again: ") </code></pre> <p>When I run the code it will skip the the whole loop! </p> <p>Can someone explain this and help me?</p>
-2
2016-07-27T12:07:21Z
38,612,571
<p><code>raw_input</code> returns a string. You don't want that.</p> <p>Most of your code doesn't make sense. Here's what I <em>assume</em> you want to do:</p> <ul> <li><p>Take input from a user.</p></li> <li><p>If the input can be converted to a number, convert it and continue. Otherwise, keep asking for input.</p></li> <li><p>If the input <strong>as a number</strong> is less than 11, it's fine. Otherwise, keep asking for input.</p></li> </ul> <p>Here's a way to do this in Python:</p> <pre><code>def get_number(): while True: try: number = int(raw_input("what is the number? ")) return number except ValueError: print("Enter a number, you fool!") num = get_number() while num &gt;= 11: print("Number should be less than 11...") number = get_number() </code></pre>
3
2016-07-27T12:10:44Z
[ "python", "python-2.7" ]
Nested Try in While loop
38,612,496
<p>Can someone help me?</p> <p>I've a problem with a nested try statement inside a while statement. The code looks like this:</p> <pre><code>number = raw_input("what is the number? ") if number &lt; 11: Print "that is good!" else: print "your number had to be lower then 11" raw_input("kies een getal: ") while number &lt; 11: try: number == int(number) except ValueError: raw_input(" try again: ") </code></pre> <p>When I run the code it will skip the the whole loop! </p> <p>Can someone explain this and help me?</p>
-2
2016-07-27T12:07:21Z
38,612,676
<p>What's the purpose of that script? Two of the raw_input commands are not being stored in any variable and the value of 'number' doesn't change within your loop, so it would run forever until you stop it with Ctrl+C.</p> <p>If the loop is not executed, that's because the condition number &lt; 11 is not met in the first place.</p>
0
2016-07-27T12:15:09Z
[ "python", "python-2.7" ]
How to run a Python script without Windows console appearing
38,612,509
<p>Is there any way to run a Python script without a command shell momentarily appearing? Naming my files with the ".pyw" extension doesn't work.</p> <p>EDIT: problem solved with ShellExecute()</p>
0
2016-07-27T12:07:47Z
38,612,596
<p>Try using the Python's <code>pythonw.exe</code> executable to start your script.</p> <p>In Windows OSes, executables that are <em>console applications</em> (<code>python.exe</code> with out the <code>w</code> is a console app) are run showing a console window; in the other hand regular Windows applications do not spawn that black console window.</p> <p>You can find the details about these two executables in this old question: <a href="http://stackoverflow.com/questions/9705982/pythonw-exe-or-python-exe">pythonw.exe or python.exe?</a></p> <p>And about Windows different types of applications here: <a href="http://stackoverflow.com/questions/574911/difference-between-windows-and-console-application">Difference between Windows and Console application</a></p>
1
2016-07-27T12:11:47Z
[ "python", "windows" ]
How to run a Python script without Windows console appearing
38,612,509
<p>Is there any way to run a Python script without a command shell momentarily appearing? Naming my files with the ".pyw" extension doesn't work.</p> <p>EDIT: problem solved with ShellExecute()</p>
0
2016-07-27T12:07:47Z
38,612,723
<p>This info from another post may help: <a href="http://stackoverflow.com/a/30313091/6470259">http://stackoverflow.com/a/30313091/6470259</a></p> <ul> <li><p><strong><code>python.exe</code></strong> is a console (terminal) application <strong>for launching CLI-type scripts</strong>.</p> <ul> <li>Unless run from an existing console window, <code>python.exe</code> <strong>opens a new console window</strong>.</li> <li><strong>Standard streams</strong> <code>sys.stdin</code>, <code>sys.stdout</code> and <code>sys.stderr</code> are <strong>connected to the console window</strong>.</li> <li>Execution is <strong>synchronous</strong>: <ul> <li>If a new console window was created, it stays open until the script terminates.</li> <li>When invoked from an existing console window, the prompt is blocked until the script terminates.</li> </ul></li> </ul></li> <li><p><strong><code>pythonw.exe</code></strong> is a GUI app <strong>for launching GUI/no-UI-at-all scripts</strong>.</p> <ul> <li><strong>NO console window</strong> is opened.</li> <li>Execution is <strong>asynchronous</strong>: <ul> <li>When invoked from a console window, the script is merely <em>launched</em> and the prompt returns right away, whether the script is still running or not.</li> </ul></li> <li><strong>Standard streams</strong> <code>sys.stdin</code>, <code>sys.stdout</code> and <code>sys.stderr</code> are <strong>NOT available</strong>. <ul> <li><strong>Caution</strong>: <strong>Unless you take extra steps</strong>, this has <strong>potentially unexpected side effects</strong>: <ul> <li><strong>Unhandled exceptions</strong> cause the script to <strong>abort <em>silently</em></strong>.</li> <li><strong>In Python 2.x, simply trying to use <code>print()</code> can cause that to happen</strong> (in 3.x, <code>print()</code> simply has no effect).</li> <li>To <strong>prevent that from within your script</strong>, and to learn more, see <a href="http://stackoverflow.com/a/30310192/45375">this answer</a> of mine.</li> <li><strong>Ad-hoc</strong>, you can use <strong>output redirection</strong>:<sup>Thanks, @handle.</sup><br> <code>pythonw.exe yourScript.pyw 1&gt;stdout.txt 2&gt;stderr.txt</code><br> (from PowerShell:<br> <code>cmd /c pythonw.exe yourScript.pyw 1&gt;stdout.txt 2&gt;stderr.txt</code>) to capture stdout and stderr output in <em>files</em>.<br> If you're confident that use of <code>print()</code> is the only reason your script fails silently with <code>pythonw.exe</code>, and you're not interested in stdout output, use @handle's command from the comments:<br> <code>pythonw.exe yourScript.pyw 1&gt;NUL 2&gt;&amp;1</code><br> <strong>Caveat</strong>: This output redirection technique seemingly does <em>not</em> work when invoking <code>*.pyw</code> scripts <em>directly</em> (as opposed to by passing the script file path to <code>pythonw.exe</code>). <sup>Do let me know if you know why and/or if it does work for you.</sup></li> </ul></li> </ul></li> </ul></li> </ul> <p>You can <strong>control which of the executables runs your script by default</strong> - such as when opened from Explorer - by <strong>choosing the right filename extension</strong>:</p> <ul> <li><code>*.py</code> files are by default associated (invoked) with <code>python.exe</code></li> <li><code>*.pyw</code> files are by default associated (invoked) with <code>pythonw.exe</code></li> </ul>
-1
2016-07-27T12:16:55Z
[ "python", "windows" ]
How to run a Python script without Windows console appearing
38,612,509
<p>Is there any way to run a Python script without a command shell momentarily appearing? Naming my files with the ".pyw" extension doesn't work.</p> <p>EDIT: problem solved with ShellExecute()</p>
0
2016-07-27T12:07:47Z
38,612,907
<p>In all python installs since 2.5 (and possibly earlier), if the install has been done properly, <code>.py</code> files are associated to <code>python.exe</code> and <code>.pyw</code> files are associated to <code>pythonw.exe</code></p> <p>If the associations have been tampered with, or overridden for a particular user, that may be different.</p> <p>Run the following command in a cmd:</p> <pre><code>ftype | find "pythonw" assoc | find ".pyw" </code></pre> <p>I get:</p> <pre><code> Python.NoConFile="D:\Program Files\Python27\pythonw.exe" "%1" %* .pyw=Python.NoConFile </code></pre> <p>If you don't have that, you can do several things to fix that:</p> <ol> <li>re-install/repair python installation (run installer, it will propose to repair install)</li> <li><p>if you're not administrator of your machine, you can associate <code>.pyw</code> files to <code>pythonw.exe</code>. Minor problem with that, you have to alter the registry key afterwards to add the extra arguments or dropping a parameter on your .pyw file won't take it into account (it's seldom used but still)</p> <p><code>[HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command] @="\"L:\\Portable_Python_2.7.3.1\\App\\pythonw.exe\" \"%1\" %*"</code></p></li> </ol>
0
2016-07-27T12:24:55Z
[ "python", "windows" ]
Angular code not playing nice with my python django application
38,612,655
<p>For some reason I can't get my angular code to play nice with my python django application. When I submit the page it saves all null values in my db and my get response isn't working correctly either because nothing is returned. Any help will be greatly appreciated, I also included screen shots for a better picture of what I am trying to do. </p> <p>angular code </p> <pre><code>var dim = angular.module('Dim', ['ngResource']); dim.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]); dim.factory("Dim", function ($resource) { return $resource("/_dims.html/:id", { id: '@id' }, { index: { method: 'GET', isArray: true, responseType: 'json' }, update: { method: 'PUT', responseType: 'json' } }); }) dim.controller("DimController", function ($scope, $http, Dim) { $scope.dims = Dim.index() $scope.addDim = function () { dim = Dim.save($scope.newDim) $scope.dims.push(Dim) $scope.newDim = {} } $scope.deleteDim = function (index) { dim = $scope.dims[index] Dim.delete(dim) $scope.dims.splice(index, 1); } }) </code></pre> <p>views.py </p> <pre><code>def add_dimensions(request): if request.method == 'POST': c_date = datetime.now() u_date = datetime.now() description = request.POST.get('description') style = request.POST.get('style') target = request.POST.get('target') upper_limit = request.POST.get('upper_limit') lower_limit = request.POST.get('lower_limit') inspection_tool = request.POST.get('inspection_tool') critical = request.POST.get('critical') units = request.POST.get('units') metric = request.POST.get('metric') target_strings = request.POST.get('target_strings') ref_dim_id = request.POST.get('ref_dim_id') nested_number = request.POST.get('nested_number') met_upper = request.POST.get('met_upper') met_lower = request.POST.get('met_lower') valc = request.POST.get('valc') sheet_id = request.POST.get('sheet_id') data = {} dim = Dimension.objects.create( description=description, style=style, target=target, upper_limit=upper_limit, lower_limit=lower_limit, inspection_tool=inspection_tool, critical=critical, units=units, metric=metric, target_strings=target_strings, ref_dim_id=ref_dim_id, nested_number=nested_number, met_upper=met_upper, met_lower=met_lower, valc=valc, sheet_id=sheet_id, created_at=c_date, updated_at=u_date) data['description'] = dim.description; data['style'] = dim.style; data['target'] = dim.target; data['upper_limit'] = dim.upper_limit; data['lower_limit'] = dim.lower_limit; data['inspection_tool'] = dim.inspection_tool; data['critical'] = dim.critical; data['units'] = dim.units; data['metric'] = dim.metric; data['target_strings'] = dim.target_strings; data['ref_dim_id'] = dim.ref_dim_id; data['nested_number'] = dim.nested_number; data['met_upper'] = dim.met_upper; data['met_lower'] = dim.met_lower; data['valc'] = dim.valc; data['sheet_id'] = dim.sheet_id; return HttpResponse(json.dumps(data), content_type="application/json",) else: return render(request, 'app/_dims.html') </code></pre> <p>url.py </p> <pre><code>urlpatterns = [ # Examples: url(r'^$', app.views.home, name='home'), url(r'^contact$', app.views.contact, name='contact'), url(r'^about', app.views.about, name='about'), #url(r'^sheet', app.views.sheet, name='sheet'), url(r'^sheet/(?P&lt;customer_id&gt;\w+)$', app.views.sheet, name='sheet_customer'), url(r'^sheet/sheet_form_create.html$', app.views.sheet_form_create, name='sheet_form_create'), url(r'^sheet/sheet_form_create.html/get_work$', app.views.get_work, name='get_work'), url(r'^sheet/(?P&lt;pk&gt;\d+)/sheet_update$', app.views.update_sheet, name='sheet_update'), url(r'^_dims.html$', app.views.add_dimensions, name='dim_update'), url(r'^sheet/(?P&lt;pk&gt;\d+)/delete_sheet$', app.views.delete_sheet, name='sheet_delete'), url(r'^sheet/sheet_form_create.html/_dim$', app.views.add_dimensions, name='dim'), url(r'^_dims.html(?P&lt;pk&gt;\d+)$', app.views.add_dimensions, name='dim'), url(r'^$', app.views.dimtable_asJson, name='dim_table_url'), #url(r^'grid_json/', include (djqgrid.urls)), </code></pre> <p>_dims.html </p> <pre><code>{% block content %} &lt;div class="container" ng-app="Dim"&gt; &lt;h1&gt;Dimensions&lt;/h1&gt; &lt;div ng-controller="DimController"&gt; &lt;div class="well"&gt; &lt;h3&gt;Add Dimensions&lt;/h3&gt; &lt;form ng-submit="addDim()"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.description" placeholder="Description" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.style" placeholder="Style" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.target" placeholder="Target" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.upper_limit" placeholder="Upper Limit" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.lower_limit" placeholder="Lower Limit" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.inspecton_tool" placeholder="Inspection Tool" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.critical" placeholder="Critical" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.units" placeholder="Units" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.metric" placeholder="Metric" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.target_strings" placeholder="Target Strings" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.ref_dim_id" placeholder="Ref Dim Id" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.nested_number" placeholder="Nested Number" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.met_upper" placeholder="Met Upper" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.met_lower" placeholder="Met Lower" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.valc" placeholder="Valc" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;input class="form-control" ng-model="newDim.sheet_id" placeholder="Sheet ID" type="text"&gt;&lt;/input&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 text-center"&gt; &lt;br/&gt; &lt;input class="btn btn-primary" type="submit" value="Save Dimension"&gt;/&lt;/input&gt; {% csrf_token %} &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;table class="table table-bordered trace-table"&gt; &lt;thead&gt; &lt;tr class="trace-table"&gt; &lt;th class="ts jp" style="border: solid black;"&gt;Description&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tr class="trace-table"&gt; &lt;tr ng-repeat="dim in dims track by $index"&gt; &lt;td class="trace-table" style="border: solid black;"&gt;{{ dim.description }}&lt;/td&gt; &lt;/tr&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;a class="btn btn-danger" ng-click="deleteDim($index)"&gt;_&lt;/a&gt; {% endblock %}. </code></pre> <p><a href="http://i.stack.imgur.com/tBUhJ.gif" rel="nofollow"><img src="http://i.stack.imgur.com/tBUhJ.gif" alt="Screenshot"></a></p> <p><a href="http://i.stack.imgur.com/0Jl0N.gif" rel="nofollow"><img src="http://i.stack.imgur.com/0Jl0N.gif" alt="Screenshot2"></a></p>
2
2016-07-27T12:14:21Z
38,613,139
<p>As your network tab screenshot shows, you're sending JSON, not form-encoded data. So in Django you need to use <code>json.loads(request.body)</code> to get the data as a dict, rather than accessing <code>request.POST</code> which will always be empty.</p> <p>Note that if you're doing something like this, you should almost certainly be using django-rest-framework, which allows you to define serializers and deserializers that will automatically convert your models to and from JSON, and additionally validate the submitted data.</p>
2
2016-07-27T12:34:17Z
[ "python", "angularjs", "django" ]
Suggestions to make website fast by breaking a request in two parts
38,612,836
<p>I am trying to speed up my website. So at the moment, controller fetches data from database, do calculation on data and display on view. what I plan to do is, controller/action fetches half the data and display to the view. Than come back to different controller/action and do calculation on data and display data on screen.</p> <p>But what I want to know is once I fetch data and display on screen, how do I go back to controller automatically(without any click by user) to do calculations on same data.</p>
0
2016-07-27T12:21:53Z
38,612,965
<p>Why don't you use ajax function , post data to the server and when proccess to the server is done display the result to the html page </p>
2
2016-07-27T12:27:31Z
[ "python", "performance", "model-view-controller", "pyramid" ]
Scikit-image: why major axis length is zero with multiple objects?
38,612,909
<p>An image with multiple objects is labelled like this:</p> <pre><code>image= [[ 1 0 0 0 2 2 0 3 3 3 3] [ 3 0 0 0 0 0 0 0 4 4 4] [ 4 0 5 5 0 0 0 0 6 6 6] [ 6 0 0 0 0 0 0 0 0 7 7] [ 7 0 0 0 0 0 0 0 0 8 8] [ 0 0 0 0 0 0 0 9 9 9 9] [ 9 0 0 0 0 0 10 10 10 10 10] [ 0 0 0 0 0 0 0 0 0 0 11] [ 0 0 0 0 0 0 0 0 0 0 12] [12 12 0 0 13 13 0 0 0 0 14] [14 14 0 0 0 0 0 0 0 0 15]] </code></pre> <p>Since I want to know about the major axis length of the equivalent ellipse, I use this function of image processing:</p> <pre><code>import skimage as sk from skimage import measure props=sk.measure.regionprops(image) maj_ax_le=round(props[0].major_axis_length,3) </code></pre> <p>But when I ask for the result, I get:</p> <pre><code>In [1]: maj_ax_le Out[1]: 0.0 </code></pre> <p>Is this because of the presence of multiple objects (15, in this case)? If so, how can I compute the individual <code>maj_ax_le</code> for all the objects?</p>
0
2016-07-27T12:25:09Z
38,614,181
<p>One can read in the <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html?highlight=label#skimage.measure.regionprops" rel="nofollow"><code>regionprops</code></a> documentation:</p> <blockquote> <p><strong>Returns:</strong> &nbsp;&nbsp;&nbsp; <strong>properties</strong> : list of RegionProperties<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Each item describes one labeled region, and can be accessed using the<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;attributes listed below.</p> </blockquote> <p>Therefore, to get the major axis length of all the objects in your image, you simply need to iterate over <code>props</code>:</p> <pre><code>import numpy as np from skimage.measure import regionprops img = np.array([[ 1, 0, 0, 0, 2, 2, 0, 3, 3, 3, 3], [ 3, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4], [ 4, 0, 5, 5, 0, 0, 0, 0, 6, 6, 6], [ 6, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7], [ 7, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8], [ 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9], [ 9, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12], [12, 12, 0, 0, 13, 13, 0, 0, 0, 0, 14], [14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 15]]) props = regionprops(img) print 'Label \tMajor axis' for p in props: print '%5d %12.3f' % (p.label, p.major_axis_length) </code></pre> <p>And this is what you get:</p> <pre><code>Label Major axis 1 0.000 2 2.000 3 14.259 4 15.934 5 2.000 6 15.934 7 18.085 8 2.000 9 14.259 10 5.657 11 0.000 12 18.085 13 2.000 14 18.085 15 0.000 </code></pre>
2
2016-07-27T13:19:44Z
[ "python", "for-loop", "image-processing", "scikit-image" ]
Can not authenticate using Django and ldap
38,612,960
<p>I am using a simple form which takes an username and a password and tries to use a ldap server to authenticate that user. The actual portal of the dashboard is written in php, but I have to rewrite it using django (and pyldap). In my settings.py file, I have the following set up (I modified the URI since is used by the company where I am working at).</p> <pre><code># LDAP Settings # Set backends AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', ) # LDAP Server AUTH_LDAP_SERVER_URI = 'ldaps://eddie.xy.zzzzz.com:3268' AUTH_LDAP_START_TLS = True # Search settings AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=xy,dc=zzzzz,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") </code></pre> <p>In my views.py, I have the following code (just to test things)</p> <pre><code>from django.shortcuts import render from django.contrib.auth import authenticate from django_auth_ldap.backend import LDAPBackend # Greyed out def login(request): if request.method == 'POST': # Get info from POST request usr = request.POST['username'] pas = request.POST['password'] # Authenticate the user using provided data user = authenticate(username=usr, password=pas) print(str(user)) if user is not None: return render(request, 'dashboard/index.html', {}) else: print("The username and password were incorrect.") return render(request, 'dashboard/error.html', {}) elif request.method == 'GET': return render(request, 'dashboard/login.html', {}) </code></pre> <p>login.html contains a simple HTML code with a form in it, with method="post" action="/login/". Index.html contains a simple "success" message, and error.html contains a simple "wrong!" message. I am using my (working) credentials in the form I made, but I can't get a success message. </p> <p>What I also tried, was this:</p> <pre><code>at = LDAPBackend() user = authenticate(username=usr, password=pas) </code></pre> <p>instead of the authenticate method used in the code above. Unfortunately, I'm getting the same behavior. What am I missing, where is my mistake?</p>
1
2016-07-27T12:27:20Z
38,616,462
<p>Finnaly, I manage to do it. I had to set this variable:</p> <pre><code>AUTH_LDAP_USER_DN_TEMPLATE = "%(user)s" </code></pre> <p>and now it's working perfectly. I hope this will maybe help the others. Thanks anyway!</p> <p>Have a good day!</p>
0
2016-07-27T14:52:46Z
[ "php", "python", "django", "authentication", "ldap" ]
start pandas dataframe index from specified number
38,612,968
<p>Rather than having a pandas dataframe index starting at 0, how to start from a specified number i.e. 120. My naive approach uses <code>len(df.index)</code> to get row count, then using that to generate a list of sequential numbers which is then attached to the dataframe and set to index. Any better way to just start index at a particular number instead of this naive approach?</p>
0
2016-07-27T12:27:42Z
38,613,022
<p>You can construct the dataframe with an index parameter. IE:</p> <pre><code>df = DataFrame(columns=['a','b','c'], index=[1,2,3], data) </code></pre>
0
2016-07-27T12:29:53Z
[ "python", "pandas" ]
start pandas dataframe index from specified number
38,612,968
<p>Rather than having a pandas dataframe index starting at 0, how to start from a specified number i.e. 120. My naive approach uses <code>len(df.index)</code> to get row count, then using that to generate a list of sequential numbers which is then attached to the dataframe and set to index. Any better way to just start index at a particular number instead of this naive approach?</p>
0
2016-07-27T12:27:42Z
38,613,060
<p>You have to overwrite the <code>IndexArray</code> object directly, you can use <code>np.arange</code> or <code>pd.RangeIndex</code> to do this:</p> <pre><code>In [109]: df = pd.DataFrame(np.random.randn(5,3), columns=list('abc')) df Out[109]: a b c 0 -0.743707 -0.579372 -0.559999 1 0.902517 -0.595641 0.060594 2 1.285828 0.633603 -1.194275 3 0.944658 -0.133695 0.687517 4 -0.863778 0.631133 1.897758 In [114]: df.index = pd.RangeIndex(120,120 + len(df)) df Out[114]: a b c 120 -0.743707 -0.579372 -0.559999 121 0.902517 -0.595641 0.060594 122 1.285828 0.633603 -1.194275 123 0.944658 -0.133695 0.687517 124 -0.863778 0.631133 1.897758 </code></pre>
0
2016-07-27T12:31:03Z
[ "python", "pandas" ]
start pandas dataframe index from specified number
38,612,968
<p>Rather than having a pandas dataframe index starting at 0, how to start from a specified number i.e. 120. My naive approach uses <code>len(df.index)</code> to get row count, then using that to generate a list of sequential numbers which is then attached to the dataframe and set to index. Any better way to just start index at a particular number instead of this naive approach?</p>
0
2016-07-27T12:27:42Z
38,613,320
<p>this works and its easy :</p> <pre><code> df.index +=120 </code></pre>
1
2016-07-27T12:42:37Z
[ "python", "pandas" ]
Pandas: checking if a string contains at least two words from a list
38,613,043
<p>I am using the fast, vectorized <code>str.contains</code> method in <code>Pandas</code> to check whether each row in my dataframe contains <strong>at least one word</strong> from my <code>list_word</code>. </p> <pre><code>list_words='foo ber haa' df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa', 'foo bar', 'bar bur', 'foo fer', 'foo for']}) df Out[113]: A 0 foo foor 1 bar bar 2 foo hoo 3 bar haa 4 foo bar 5 bar bur 6 foo fer 7 foo for df.A.str.contains("|".join(list_words.split(" "))) Out[114]: 0 True 1 False 2 True 3 True 4 True 5 False 6 True 7 True Name: A, dtype: bool </code></pre> <p>Problem is: how can I check whether each row contains at least <strong>two words from the list?</strong>. </p> <p>I want to stick to <code>str.contains</code> because it is so much faster than the other python string matching algorithms.</p>
1
2016-07-27T12:30:34Z
38,613,324
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <code>list comprehension</code>:</p> <pre><code>#changed ber to bar list_words='foo bar haa' df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa', 'foo bar', 'bar bur', 'foo fer', 'foo for']}) print (df) A 0 foo foor 1 bar bar 2 foo hoo 3 bar haa 4 foo bar 5 bar bur 6 foo fer 7 foo for print((pd.concat([df.A.str.contains(word,regex=False) for word in list_words.split()],axis=1)) .sum(1) &gt; 1) 0 False 1 False 2 False 3 True 4 True 5 False 6 False 7 False dtype: bool </code></pre> <p><strong>Timings</strong>:</p> <pre><code>def jon(df): set_words = set(list_words.split()) return df.A.apply(lambda L: len(set(L.split()) &amp; set_words) &gt; 1) </code></pre> <hr> <pre><code>In [292]: %timeit ((pd.concat([df.A.str.contains(word) for word in list_words.split()], axis=1)).sum(1) &gt; 1) 100 loops, best of 3: 16 ms per loop In [325]: %timeit (jon(df)) 100 loops, best of 3: 8.97 ms per loop In [294]: %timeit ((pd.concat([df.A.str.contains(word,regex=False) for word in list_words.split()], axis=1)).sum(1) &gt; 1) 100 loops, best of 3: 8.13 ms per loop In [295]: %timeit df['A'].map(lambda x: check(x, list_words)) 100 loops, best of 3: 14.7 ms per loop </code></pre>
2
2016-07-27T12:42:48Z
[ "python", "pandas" ]
Pandas: checking if a string contains at least two words from a list
38,613,043
<p>I am using the fast, vectorized <code>str.contains</code> method in <code>Pandas</code> to check whether each row in my dataframe contains <strong>at least one word</strong> from my <code>list_word</code>. </p> <pre><code>list_words='foo ber haa' df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa', 'foo bar', 'bar bur', 'foo fer', 'foo for']}) df Out[113]: A 0 foo foor 1 bar bar 2 foo hoo 3 bar haa 4 foo bar 5 bar bur 6 foo fer 7 foo for df.A.str.contains("|".join(list_words.split(" "))) Out[114]: 0 True 1 False 2 True 3 True 4 True 5 False 6 True 7 True Name: A, dtype: bool </code></pre> <p>Problem is: how can I check whether each row contains at least <strong>two words from the list?</strong>. </p> <p>I want to stick to <code>str.contains</code> because it is so much faster than the other python string matching algorithms.</p>
1
2016-07-27T12:30:34Z
38,613,931
<p>Assuming that <code>ber</code> should be <code>bar</code>, you can use <code>.apply</code> with sets - note this does <em>whole words</em> - not substrings (eg <code>foo</code> won't be found in <code>foor</code>)...</p> <pre><code>import pandas as pd list_words='foo bar haa' set_words = set(list_words.split()) df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa', 'foo bar', 'bar bur', 'foo fer', 'foo for']}) df.A.apply(lambda L: len(set(L.split()) &amp; set_words) &gt; 1) </code></pre> <p>Gives you:</p> <pre><code>0 False 1 False 2 False 3 True 4 True 5 False 6 False 7 False Name: A, dtype: bool </code></pre>
2
2016-07-27T13:09:05Z
[ "python", "pandas" ]
Pandas: checking if a string contains at least two words from a list
38,613,043
<p>I am using the fast, vectorized <code>str.contains</code> method in <code>Pandas</code> to check whether each row in my dataframe contains <strong>at least one word</strong> from my <code>list_word</code>. </p> <pre><code>list_words='foo ber haa' df = pd.DataFrame({'A' : ['foo foor', 'bar bar', 'foo hoo', 'bar haa', 'foo bar', 'bar bur', 'foo fer', 'foo for']}) df Out[113]: A 0 foo foor 1 bar bar 2 foo hoo 3 bar haa 4 foo bar 5 bar bur 6 foo fer 7 foo for df.A.str.contains("|".join(list_words.split(" "))) Out[114]: 0 True 1 False 2 True 3 True 4 True 5 False 6 True 7 True Name: A, dtype: bool </code></pre> <p>Problem is: how can I check whether each row contains at least <strong>two words from the list?</strong>. </p> <p>I want to stick to <code>str.contains</code> because it is so much faster than the other python string matching algorithms.</p>
1
2016-07-27T12:30:34Z
38,614,290
<p>I am a beginner with pandas (and python in general) so wanted to try it as a challenge rather than getting upvotes :). Just used the techniques I know but they significantly slower than those proposed by others.</p> <pre><code>def check(row, string): #tokenize string string_list = string.split() #tokenize row row_list = row.split() counter = 0 used_words = [] for word in row_list: used_words.append(word) if word in string_list and not(used_words.count(word) &gt;1): counter += 1 if counter &gt;= 2: return True else: return False df['check'] = df['A'].map(lambda x: check(x, list_words)) </code></pre> <p>I will check the techniques proposed by others :)</p>
1
2016-07-27T13:24:54Z
[ "python", "pandas" ]
How to upgrade pip3?
38,613,316
<p>I want to use python3.5 to develop basically,but many times when i install the module for the python3.5,it always failed.And the termimal told me that higher version is available,it did not work when I upgrade it. <img src="http://i.stack.imgur.com/75IDN.png" alt="enter image description here"></p>
0
2016-07-27T12:42:32Z
38,613,503
<p>You are using pip3 to install flask-script which is associated with python 3.5. However, you are trying to upgrade pip associated with the python 2.7, try running <code>pip3 install --upgrade pip</code>.</p> <p>It might be a good idea to take some time and read about virtual environments in Python. It isn't a best practice to install all of your packages to the base python installation. This would be a good start: <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">http://docs.python-guide.org/en/latest/dev/virtualenvs/</a></p>
0
2016-07-27T12:50:39Z
[ "python", "linux", "python-3.x" ]
Python: Read value from code in a website
38,613,466
<p>I have a problem i first thought many would experience, but i couldn't find any similar questions. The language i'm using is <strong>Python</strong>.</p> <p>I want to read a specific value from a website, which is embedded in another code behind. I first thought <a href="http://stackoverflow.com/questions/19175180/read-value-from-web-page-using-python">this approach here</a> could work. (Downloading the html page, then reading a specific line). But the problem is, that the value i am looking for is generated constantly in another class or code. So basically when i tried to look at the html-code with Chrome, i couldn't find my preferred value.</p> <p>The page i am trying to read: <a href="http://ether.price.exchange/" rel="nofollow">Page</a>. The value i need is the <strong>Price per Ether in Euro</strong>. </p> <p>I appreciate your help!</p>
-1
2016-07-27T12:49:07Z
38,614,014
<p>The data on the page comes from an XHR loaded json blob, which it is possible to query directly.</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; import pprint &gt;&gt;&gt; r = requests.get('http://ether.price.exchange/update') &gt;&gt;&gt; pprint.pprint(r.json()) {u'AUD': {u'15m': 873.83, u'buy': 873.83, u'last': 873.83, u'sell': 873.85, u'symbol': u'$'}, u'BRL': {u'15m': 2140.39, u'buy': 2140.39, u'last': 2140.39, u'sell': 2140.42, u'symbol': u'R$'}, u'CAD': {u'15m': 860, u'buy': 860, u'last': 860, u'sell': 860.02, u'symbol': u'$'}, u'CHF': {u'15m': 643.67, u'buy': 643.67, u'last': 643.67, u'sell': 643.68, u'symbol': u'CHF'}, u'CLP': {u'15m': 428297.17, u'buy': 428297.17, u'last': 428297.17, u'sell': 428303.73, u'symbol': u'$'}, u'CNY': {u'15m': 4359.5, u'buy': 4359.5, u'last': 4359.5, u'sell': 4359.56, u'symbol': u'\xa5'}, u'DKK': {u'15m': 4416.7, u'buy': 4416.7, u'last': 4416.7, u'sell': 4416.76, u'symbol': u'kr'}, u'EUR': {u'15m': 593.66, u'buy': 593.66, u'last': 593.66, u'sell': 593.67, u'symbol': u'\u20ac'}, u'GBP': {u'15m': 496.02, u'buy': 496.02, u'last': 496.02, u'sell': 496.02, u'symbol': u'\xa3'}, u'HKD': {u'15m': 5062.79, u'buy': 5062.79, u'last': 5062.79, u'sell': 5062.87, u'symbol': u'$'}, u'ISK': {u'15m': 79579.79, u'buy': 79579.79, u'last': 79579.79, u'sell': 79581.01, u'symbol': u'kr'}, u'JPY': {u'15m': 69110.23, u'buy': 69110.23, u'last': 69110.23, u'sell': 69111.28, u'symbol': u'\xa5'}, u'KRW': {u'15m': 742032.87, u'buy': 742032.87, u'last': 742032.87, u'sell': 742044.24, u'symbol': u'\u20a9'}, u'NZD': {u'15m': 933.8, u'buy': 933.8, u'last': 933.8, u'sell': 933.82, u'symbol': u'$'}, u'PLN': {u'15m': 2589.46, u'buy': 2589.46, u'last': 2589.46, u'sell': 2589.5, u'symbol': u'z\u0142'}, u'RUB': {u'15m': 42472.95, u'buy': 42472.95, u'last': 42472.95, u'sell': 42473.6, u'symbol': u'RUB'}, u'SEK': {u'15m': 5637.68, u'buy': 5637.68, u'last': 5637.68, u'sell': 5637.77, u'symbol': u'kr'}, u'SGD': {u'15m': 887.79, u'buy': 887.79, u'last': 887.79, u'sell': 887.81, u'symbol': u'$'}, u'THB': {u'15m': 22835.96, u'buy': 22835.96, u'last': 22835.96, u'sell': 22836.31, u'symbol': u'\u0e3f'}, u'TWD': {u'15m': 20965.35, u'buy': 20965.35, u'last': 20965.35, u'sell': 20965.67, u'symbol': u'NT$'}, u'USD': {u'15m': 652.7, u'buy': 652.7, u'last': 652.7, u'sell': 652.71, u'symbol': u'$'}, u'baseVolume': u'71691.55099130', u'high': u'0.02070000', u'high24hr': u'0.02070000', u'highestBid': u'0.01957006', u'id': 148, u'isFrozen': u'0', u'last': u'0.01956700', u'low': u'0.01760000', u'low24hr': u'0.01760000', u'lowestAsk': u'0.01958372', u'percentChange': u'0.07570270', u'price': u'0.01956700', u'quoteVolume': u'3802775.62565674', u'volume': u'71691.55099130'} </code></pre> <p>Reading the javascript in the page, the price of 1 ether in a currency is <code>1 * data['price'] * data['EUR']['last']</code>:</p> <pre><code>&gt;&gt;&gt; r = requests.get('http://ether.price.exchange/update') &gt;&gt;&gt; d = r.json() &gt;&gt;&gt; float(d['price']) * float(d['EUR']['last']) 11.562597087999999 </code></pre>
1
2016-07-27T13:12:47Z
[ "python", "html", "url" ]
Python: Read value from code in a website
38,613,466
<p>I have a problem i first thought many would experience, but i couldn't find any similar questions. The language i'm using is <strong>Python</strong>.</p> <p>I want to read a specific value from a website, which is embedded in another code behind. I first thought <a href="http://stackoverflow.com/questions/19175180/read-value-from-web-page-using-python">this approach here</a> could work. (Downloading the html page, then reading a specific line). But the problem is, that the value i am looking for is generated constantly in another class or code. So basically when i tried to look at the html-code with Chrome, i couldn't find my preferred value.</p> <p>The page i am trying to read: <a href="http://ether.price.exchange/" rel="nofollow">Page</a>. The value i need is the <strong>Price per Ether in Euro</strong>. </p> <p>I appreciate your help!</p>
-1
2016-07-27T12:49:07Z
38,618,148
<p>I was able to get the value from another webpage. The code looks like this:</p> <p><code>def get_current_value(): chrome_path = r"C:\Users\Chris\Desktop\Chrome_driver\chromedriver.exe" driver = webdriver.Chrome(chrome_path) driver.get("https://cryptowatch.de/kraken/etheur") a = driver.find_element_by_xpath("""//*[@id="price-ticker"]""").text unicodedata.normalize("NFD",a)#.encode('ascii','ignore') return a</code></p> <p>I added this code here <code>unicodedata.normalize("NFD",a)#.encode('ascii','ignore')</code> to transform the output, which was apparently unicode, to a string.</p> <p>The problem i face now, is that the output for a is something like : €12.99 <br> How can i remove the euro sign so i can transform the string to a float?<br></p> <p>I have to post this as answer since someone downvoted me for no reason so i can't ask another question today..</p>
0
2016-07-27T16:06:50Z
[ "python", "html", "url" ]
EXE with MatplotLib Crashes
38,613,476
<p>I'm developing an application using Python 3.4 and PyQt4 with LiClipse as the IDE and have an issue with plotting graphs closing the entire program with no error after I've compiled the program into an executable. I've pin-pointed the problem area and know that calling matplotlib.figure.Figure() is the crash culprit but I don't know where to go from here.</p> <pre><code>import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure class GraphWidget(FigureCanvas): def __init__(self,parent=None,width = 500, height = 600, dpi = 100): self.width = width/dpi self.height = height/dpi self.dpi = dpi #================crashes here=============# self.figure = Figure((self.width,self.height), dpi=self.dpi) #=========================================# alert = QMessageBox() alert.setText("Passed Figure()") alert.exec_() FigureCanvas.__init__(self,self.figure) alert = QMessageBox() alert.setText("Passed super init") alert.exec_() self.canvas = self self.axis = self.figure.add_subplot(111) self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding) self.parent = parent def set_new_graph(self,data,labels): self.layoutVert = QVBoxLayout(self) size = QSize(self.width*self.dpi,self.height*self.dpi) self.axis.hold(False) mined = min(data.totalamount) - round(min(data.totalamount)*.1,0) if mined &gt; 0: mined = 0 maxed = max(data.totalamount) + round(max(data.totalamount)*.1,0) if maxed == mined: maxed += 5 data.plot(x = data.totalamount , ax = self.axis , kind = 'bar' , rot=0 , legend = False , sharex = True , sharey = True # , xticks = labels , ylim = (mined,maxed) , table = False) # self.axis.set_ylim(mined,maxed) self.axis.set_xticklabels(labels, fontsize = 'small') self.axis.set_title("Sales History over Past Year") self.canvas.draw() self.resize(size) self.layoutVert.addWidget(self.canvas) </code></pre> <p>My py2exe setup script produces a usable executable for all functions except when a graph is initialized on the page:</p> <pre><code>mpld = matplotlib.get_py2exe_datafiles() include = ['sip','pandas','reportlab' , 'PyQt4' , 'PyQt4.QtGui' , 'PyQt4.QtCore' , 'PyQt4.Qt' ,'reportlab.rl_settings','scipy','win32com' ,'win32com.client' , 'matplotlib' , 'matplotlib.backends' , 'matplotlib.backends.backend_qt4agg' , 'matplotlib.figure' ] exclude = ['nbformat','win32com.gen_py',"six.moves.urllib.parse", '_gtkagg', '_tkagg', '_agg2', '_cairo', '_cocoaagg', '_fltkagg', '_gtk', '_gtkcairo'] setup(name="ServiceMgmt", # console based executables console=[], # windows subsystem executables (no console) windows=['ServiceMgmt.py'], # py2exe options #zipfile=None, options={"py2exe": py2exe_options}, data_files=mpld ) </code></pre> <p>I am able to run all other functions of my application in the executable but without issue. No visible error is shown, and the application works fine prior to compiling. </p> <p>Thank you for your help.</p>
0
2016-07-27T12:49:39Z
38,663,420
<p>My troubleshooting found numpy.core to be the culprit of my issue. I re-installed numpy and the executable runs properly now.</p>
0
2016-07-29T16:22:50Z
[ "python", "matplotlib", "py2exe" ]
Prepare Data Frames to be compared. Index manipulation, datetime and beyond
38,613,514
<p>Ok, this is a question in two steps. </p> <p><strong>Step one:</strong> I have a pandas DataFrame like this:</p> <pre><code> date time value 0 20100201 0 12 1 20100201 6 22 2 20100201 12 45 3 20100201 18 13 4 20100202 0 54 5 20100202 6 12 6 20100202 12 18 7 20100202 18 17 8 20100203 6 12 ... </code></pre> <p>As you can see, for instance between rows 7 and 8 there is data missing (in this case, the value for the 0 time). Sometimes, several hours or even a full day could be missing. </p> <p>I would like to convert this DataFrame to the format like this:</p> <pre><code> value 2010-02-01 00:00:00 12 2010-02-01 06:00:00 22 2010-02-01 12:00:00 45 2010-02-01 18:00:00 13 2010-02-02 00:00:00 54 2010-02-02 06:00:00 12 2010-02-02 12:00:00 18 2010-02-02 18:00:00 17 ... </code></pre> <p>I want this because I have another DataFrame (let's call it "reliable DataFrame") in this format that I am sure it has no missing values.</p> <p><strong>EDIT 2016/07/28:</strong> Studying the problem it seems there were also duplicated data in the dataframe. See the solution to also address this problem.</p> <p><strong>Step two:</strong> With the previous step done I want to compare row by row the index in the "reliable DataFrame" with the index in the DataFrame with missing values.</p> <p>I want to add a row with the <code>value</code> NaN where there are missing entries in the first DataFrame. The final check would be to be sure that both DataFrames have the same dimension.</p> <p>I know this is a long question, but I am stacked. I have tried to manage the dates with the <code>dateutil.parser.parse</code> and to use <code>set_index</code> as the method to set a new index, but I have lots of errors in the code. I am afraid this is clearly above my pandas level.</p> <p>Thank you in advance.</p>
0
2016-07-27T12:50:59Z
38,615,165
<p><strong>Step 1 Answer</strong></p> <pre><code>df['DateTime'] = (df['date'].astype(str) + ' ' + df['time'].astype(str) +':'+'00'+':'+'00').apply(lambda x: pd.to_datetime(str(x))) df.set_index('DateTime', drop=True, append=False, inplace=True, verify_integrity=False) df.drop(['date', 'time'], axis=1, level=None, inplace=True, errors='raise') </code></pre> <p><strong>If there are duplicates these can be removed by:</strong></p> <p><code>df = df.reset_index().drop_duplicates(subset='DateTime',keep='last').set_index('DateTime')</code></p> <p><strong>Step 2</strong></p> <pre><code>df_join = df.join(df1, how='outer', lsuffix='x',sort=True) </code></pre>
1
2016-07-27T14:01:12Z
[ "python", "datetime", "pandas" ]
How can I create many columns after a list in pandas?
38,613,517
<p>I have a dataframe, I want to create a lot of new columns after a list and filled with <code>0</code>, how can I do it?</p> <p>For example: </p> <pre><code>df = pd.DataFrame({"a":["computer", "printer"]}) print(df) &gt;&gt;&gt; a &gt;&gt;&gt;0 computer &gt;&gt;&gt;1 printer </code></pre> <p>I have a list</p> <pre><code>myList=["b","c","d"] </code></pre> <p>I want my new dataframe looks like:</p> <pre><code>&gt;&gt;&gt; a b c d &gt;&gt;&gt;0 computer 0 0 0 &gt;&gt;&gt;1 printer 0 0 0 </code></pre> <p>How can I do it?</p>
1
2016-07-27T12:51:10Z
38,613,551
<p>Use fastest solution:</p> <pre><code>for col in myList: df[col] = 0 print(df) a b c d 0 computer 0 0 0 1 printer 0 0 0 </code></pre> <p>Another solution is use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor:</p> <pre><code>pd.concat([df3,pd.DataFrame(columns=myList, index=df.index, data=0)], axis=1) </code></pre> <hr> <p><strong>Timings</strong>:</p> <p><em>[20000 rows x 300 columns]</em>:</p> <pre><code>In [286]: %timeit pd.concat([df,pd.DataFrame(columns=myList)], axis=1).fillna(0) 1 loop, best of 3: 1.17 s per loop In [287]: %timeit pd.concat([df3,pd.DataFrame(columns=myList, index=df.index,data=0)],axis=1) 10 loops, best of 3: 81.7 ms per loop In [288]: %timeit (orig(df4)) 10 loops, best of 3: 59.2 ms per loop </code></pre> <p>Code for timings:</p> <pre><code>myList=["b","c","d"] * 100 df = pd.DataFrame({"a":["computer", "printer"]}) print(df) df = pd.concat([df]*10000).reset_index(drop=True) df3 = df.copy() df4 = df.copy() df1= pd.concat([df,pd.DataFrame(columns=myList)], axis=1).fillna(0) df2 = pd.concat([df3,pd.DataFrame(columns=myList, index=df.index, data=0)], axis=1) print(df1) print(df2) def orig(df): for col in range(300): df[col] = 0 return df print (orig(df4)) </code></pre>
1
2016-07-27T12:52:35Z
[ "python", "pandas", "dataframe", "append", "multiple-columns" ]
How can I create many columns after a list in pandas?
38,613,517
<p>I have a dataframe, I want to create a lot of new columns after a list and filled with <code>0</code>, how can I do it?</p> <p>For example: </p> <pre><code>df = pd.DataFrame({"a":["computer", "printer"]}) print(df) &gt;&gt;&gt; a &gt;&gt;&gt;0 computer &gt;&gt;&gt;1 printer </code></pre> <p>I have a list</p> <pre><code>myList=["b","c","d"] </code></pre> <p>I want my new dataframe looks like:</p> <pre><code>&gt;&gt;&gt; a b c d &gt;&gt;&gt;0 computer 0 0 0 &gt;&gt;&gt;1 printer 0 0 0 </code></pre> <p>How can I do it?</p>
1
2016-07-27T12:51:10Z
38,613,640
<p>It'll be more performant to <code>concat</code> an empty df for large dfs rather than incrementally adding new columns as this will grow the df incrementally rather than just make a single allocation of the final df dimensions:</p> <pre><code>In [116]: myList=["b","c","d"] df = pd.concat([df,pd.DataFrame(columns=myList)], axis=1).fillna(0) df Out[116]: a b c d 0 computer 0 0 0 1 printer 0 0 0 </code></pre>
1
2016-07-27T12:56:40Z
[ "python", "pandas", "dataframe", "append", "multiple-columns" ]
Send large email via Gmail API in Python
38,613,797
<p>Recently Google disabled their "legacy" upload capability, so I was forced to change our applications to use the Google users().messages().send api.</p> <p>However it doesn't work on anything over 5mb. I've seen one post on the www about how to do it in PHP, but nothing in Python.</p> <p>Here's my existing code:</p> <pre><code>http = #My login routine service = build('gmail','v1',http=http) email = {'raw':base64.urlsafe_b64encode(message)} reply = (service.users().messages().send(userId=user,body=email).execute()) </code></pre> <p>Google has extensive documentation, but NOT on the specific ability to send large emails in Python. In fact at this page:</p> <p><a href="https://developers.google.com/gmail/api/v1/reference/users/messages/send" rel="nofollow">https://developers.google.com/gmail/api/v1/reference/users/messages/send</a></p> <p>They talk about using the base API to send messages as large as 35MB, but that simply doesn't work. I receive a "ResponseNotReady()" error.</p> <p>I've been reading about chunked uploads, resumable uploads, but nothing has come to fruition.</p> <p>Any thoughts out there?</p>
1
2016-07-27T13:03:51Z
38,636,747
<p>I had the same issue <a href="http://stackoverflow.com/questions/24908700/mail-attachment-wrong-media-type-gmail-api/24957873#24957873">two years ago</a>, and I still think the only way to send messages with large attachments is to circumvent the official client library.</p> <p>This is an example using the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> library instead:</p> <pre><code>url = 'https://www.googleapis.com/gmail/v1/users/me/messages/send?uploadType=multipart' headers = { 'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'message/rfc822' } requests.post(url, headers=headers, payload=message) </code></pre> <p>The message is not encoded. I think you can extract the access token from the service object, but I'm not sure exactly how.</p>
0
2016-07-28T12:44:20Z
[ "python", "gmail", "gmail-api" ]
Can we include partial css files into a template file?
38,613,812
<p>I intend to create a main page in a modular way. The main page might have a header, a footer, and a main section, I'd like to keep the markup and the css that is specific to each of those sections separate. So that if I need those sections on other pages, I can just include the files.</p> <p>So I need to be able to include a css file into a template in a similar way I can include an html one. I could just keep all the styling on the same css file, but if I later remove some html file, I want the styling for that file to be removed as well.</p> <p>So I came up with this minimal example, and it works on my setup, but I'm not sure it will work everywhere, or if it's idiomatic in django.</p> <p>As you can see bellow I define one head section on the base html file, and another on the included html file. I need both these sections to define a link to the corresponding css files. I read the documentation on the <em>head</em> html tag though, and I'm not so sure I can just define multiple head sections, and I'm not sure where the <em>head</em> section from the included file will even end up, it seems like it will end up inside the <em>body</em> section of the base file, which I don't know if all browsers will render correctly.</p> <p>So my questions are: Can I do this on all platforms? Should I do this? Is there another, better way, of doing this?</p> <p>I received some suggestions to use inheritance, I'm not sure that will work, I don't have a base file that I can make a few changes to on a child, and then render the child. I have several files, that define several different sections of a main page, that I need to bring together.</p> <p>base.html:</p> <pre><code>{% load static %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/base.css" %}" /&gt; &lt;/head&gt; &lt;body&gt; {% include "header.html" %} {% include "main.html" %} {% include "footer.html" %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>base.css:</p> <pre><code>.header { background-color: red; } .footer { background-color: blue; } </code></pre> <p>main.html:</p> <pre><code>{% load static %} &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/main.css" %}" /&gt; &lt;/head&gt; &lt;main&gt; main &lt;/main&gt; </code></pre> <p>main.css:</p> <pre><code>.main { background-color: green; } </code></pre>
1
2016-07-27T13:04:28Z
38,613,983
<p>You shouldn't define multiple head sections in HTML. But there's no need to; you should use template inheritance and blocks just like you do with any other element. You shouldn't really be using <code>include</code> here at all; inheritance is much more powerful.</p> <p>So, base.html looks like this:</p> <pre><code>{% load static %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/base.css" %}" /&gt; {% block extrastyles %}{% endblock %} &lt;/head&gt; &lt;body&gt; &lt;header&gt;header&lt;/header&gt; {% block main %}{% endblock %} &lt;footer&gt;footer&lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and main.html is:</p> <pre><code>{% extends "base.html" %} {% load static %} {% block extrastyles %} &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/main.css" %}" /&gt; {% endblock %} {% block main %} main {% endblock %} </code></pre> <p>and in your view you render main.html, not base.html.</p>
2
2016-07-27T13:11:12Z
[ "python", "html", "css", "django", "django-templates" ]
Can we include partial css files into a template file?
38,613,812
<p>I intend to create a main page in a modular way. The main page might have a header, a footer, and a main section, I'd like to keep the markup and the css that is specific to each of those sections separate. So that if I need those sections on other pages, I can just include the files.</p> <p>So I need to be able to include a css file into a template in a similar way I can include an html one. I could just keep all the styling on the same css file, but if I later remove some html file, I want the styling for that file to be removed as well.</p> <p>So I came up with this minimal example, and it works on my setup, but I'm not sure it will work everywhere, or if it's idiomatic in django.</p> <p>As you can see bellow I define one head section on the base html file, and another on the included html file. I need both these sections to define a link to the corresponding css files. I read the documentation on the <em>head</em> html tag though, and I'm not so sure I can just define multiple head sections, and I'm not sure where the <em>head</em> section from the included file will even end up, it seems like it will end up inside the <em>body</em> section of the base file, which I don't know if all browsers will render correctly.</p> <p>So my questions are: Can I do this on all platforms? Should I do this? Is there another, better way, of doing this?</p> <p>I received some suggestions to use inheritance, I'm not sure that will work, I don't have a base file that I can make a few changes to on a child, and then render the child. I have several files, that define several different sections of a main page, that I need to bring together.</p> <p>base.html:</p> <pre><code>{% load static %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/base.css" %}" /&gt; &lt;/head&gt; &lt;body&gt; {% include "header.html" %} {% include "main.html" %} {% include "footer.html" %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>base.css:</p> <pre><code>.header { background-color: red; } .footer { background-color: blue; } </code></pre> <p>main.html:</p> <pre><code>{% load static %} &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/main.css" %}" /&gt; &lt;/head&gt; &lt;main&gt; main &lt;/main&gt; </code></pre> <p>main.css:</p> <pre><code>.main { background-color: green; } </code></pre>
1
2016-07-27T13:04:28Z
38,614,095
<p>The first problem, it not correct to pu <code>head</code> into <code>body</code>. It make so as your <code>main.html</code> is not a separate html file but the part of <code>base.html</code>. The second is it is not such easy to include another file if you need to once in a future.</p> <p>I make such thing in slight another way. When using base file it looks more useful to extend base template instead of including files. So, in base template we can make some placeholder blocks.</p> <pre><code>{% load static %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/base.css" %}" /&gt; {% block 'additional_includes' %}{% endblock %} &lt;/head&gt; &lt;body&gt; &lt;header&gt;header&lt;/header&gt; {% block 'content' %}{% endblock %} &lt;footer&gt;footer&lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Then we are going to use it. So create child template and redefine needed blocks (if you don't redefine them, they will just stay empty):</p> <pre><code>{$ extends '/path_to_base/base.html' %} {% load static %} {% block 'additional_includes' %} &lt;link rel="stylesheet" type="text/css" href="{% static "appfolder/css/main.css" %}" /&gt; {% endblock %} {% block 'content' %} your content {% endblock %} </code></pre> <p>That's all. You need to reference to <code>main.html</code> in your views instead of <code>base.html</code>. And, of course, you can lots of other child templates.</p> <p><strong>Upd.</strong></p> <p>Decided to edit my reply. The common structure of html file is:</p> <pre><code>&lt;!DOCTYPE ...&gt; &lt;html&gt; &lt;head&gt; &lt;!-- all your meta tags --&gt; &lt;!-- title --&gt; &lt;!-- css and other includes, you can include so many files as you need, but it is better to use as little as possible as it can reduce server performance --&gt; &lt;!-- scripts definitions (not necessary to put there, often they are paced in the end of file) --&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- content of file you can divide this part in several parts and include them but you can't use head here, because it is body --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This structure must be used in any framework in different languages, because it is just an html used by browser. Any framework must have instruments to render simple html pages with it template engine. And django has it own engine, that provide to create lots of big files from small parts using extending and including. You can include some parts that are common for all of your pages. You can redefine thisa includes wrapping this includes in block tags. And you can create different pages with the same layout using extend, so you don't have to copy your code (for header or footer) many times.</p> <p>So, in django you can create following structure. I use some sort of it and it seems comfortable enough:</p> <p><em>base.html</em></p> <pre><code>&lt;!DOCTYPE ...&gt; &lt;html&gt; &lt;head&gt; {% load static %} {% include 'meta.html' %} &lt;title&gt;{% block 'title' %}Main page{% endblock %} - my site&lt;/title&gt; &lt;link href='{% static "appfolder/css/base.css" %}' ... /&gt; {% block 'additional_includes' %}{% endblock %} &lt;/head&gt; &lt;body&gt; {% block 'header' %}{% include 'header.html' %}{% endblock %} &lt;!-- header is just visible site header, not including files --&gt; {% block 'content' %}{% endblock %} {% block 'footer' %}{% include 'footer.html' %}{% endblock %} &lt;/body&gt; &lt;/html&gt; </code></pre> <p><em>first-page.html</em></p> <pre><code>{$ extends 'base.html' %} {% load static %} {% block 'title' %}First-page{% endblock %} {% block 'additional_includes' %} &lt;link href='{% static "appfolder/css/first-page.css" %}' ... /&gt; {% endblock %} &lt;!-- if you DON'T use block, then the content defined in base template file will remain --&gt; {% block 'content' %} Some page content {% endblock %} </code></pre> <p><em>second-page.html</em></p> <pre><code>{$ extends 'base.html' %} {% load static %} {% block 'title' %}Second-page{% endblock %} {% block 'additional_includes' %} &lt;link href='{% static "appfolder/css/second-page.css" %}' ... /&gt; {% endblock %} &lt;!-- if you USE block, then its content will be rewritten with new data. you can use {{ block.super }} to add the content of block from base template --&gt; {% block 'header' %}{% include 'header_for_second_page.html' %}{% endblock %} {% block 'content' %} Another page content {% endblock %} </code></pre>
0
2016-07-27T13:16:28Z
[ "python", "html", "css", "django", "django-templates" ]
python popen pipe in loop
38,613,964
<p>I'm trying to write a function to create a shell pipeline in a loop that gets its command parameters from a list and pipes the last stdout to the new stdin. At the and of the command list, I want to call the communicate method on the Popen object to get the output.</p> <p>The output is always empty. What am I doing wrong?</p> <p>See following example:</p> <pre><code>lstCmd = ["tasklist", "grep %SESSIONNAME%", "grep %s" % (strAutName)] lstPopen = [subprocess.Popen(lstCmd[0].split(), stdout=subprocess.PIPE)] for i in range(len(lstCmd) - 1): lstPopen.append(subprocess.Popen(lstCmd[i + 1].split(), stdin=lstPopen[i].stdout, stdout=subprocess.PIPE)) lstPopen[i].stdout.close() strProcessInfo = lstPopen[-1].communicate()[0] </code></pre> <p>I'm on a Windows environment with additional unix functions. Following command works on my Windows command line and should be written to strProcessInfo:</p> <pre><code>C:\&gt;tasklist | grep %SESSIONNAME% | grep tasklist tasklist.exe 18112 Console 1 5.948 K </code></pre>
0
2016-07-27T13:10:28Z
38,616,831
<p>The problem is with grep %SESSIONNAME%. When you execute same thing on commandline, the %SESSIONNAME% is actually getting replaced by "Console". But when executed in python script, it is not getting replaced. It is trying to find exact %SESSIONNAME% which is not present. That's why output is blank.</p> <p>Below is code. </p> <p><strong>Grep</strong> replaced by <strong>findstr</strong> and <strong>%SESSIONNAME%</strong> replaced by word <strong>"Console"</strong>.</p> <pre><code>import sys import subprocess lstCmd = ["tasklist", "findstr Console","findstr tasklist"] lstPopen = [subprocess.Popen(lstCmd[0].split(), stdout=subprocess.PIPE)] for i in range(len(lstCmd) - 1): lstPopen.append(subprocess.Popen(lstCmd[i + 1].split(), stdin=lstPopen[i].stdout, stdout=subprocess.PIPE)) lstPopen[i].stdout.close() strProcessInfo = lstPopen[-1].communicate()[0] print strProcessInfo </code></pre> <p>Output:</p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python abc.py tasklist.exe 12316 Console 1 7,856 K C:\Users\dinesh_pundkar\Desktop&gt; </code></pre> <p>Please let me know if it is helpful.</p>
0
2016-07-27T15:06:57Z
[ "python", "python-2.7", "subprocess", "popen" ]
Download only part of genbank file with biopython
38,614,031
<p>I am new to Biopython and I have a performance issue when parsing genbank files.</p> <p>I have to parse a lot of gb files, from which I have the accession numbers. After parsing, I only want to examine the taxonomy and the organelle of the file. Right now, I have this code:</p> <pre><code>from Bio import SeqIO from Bio import Entrez gb_acc1 = Entrez.efetch(db='nucleotide', id=access1, rettype='gb', retmode='text') #Where access1 contents the accession number rec = SeqIO.read(gb_acc1, 'genbank') cache[access1] = rec #where cache is just a dictionary where saving the gb files already downloaded feat = cache[access1].features[0] if 'organelle' in feat.qualifiers.keys(): #And the code goes on </code></pre> <p>In order to look for the taxonomy I have:</p> <pre><code>gi_h = Entrez.efetch(db='nucleotide', id=access, rettype='gb', retmode='text') gi_rec = SeqIO.read(gi_h, 'genbank') cache[access]=gi_rec if cache[access].annotations['taxonomy'][1] == 'Fungi': fungi += 1 #And the code goes on </code></pre> <p>This (the whole script) works fine. My problem is that I am downloading the whole gb file (which sometimes is huge) just to look into these 2 features: the organelle and the taxonomy. If I could only download this part of the gb file my script would be much faster, but I have not figured out if this is possible.</p> <p>Does someone know if this can be done, and if so, how? Thanks a lot in advance</p>
1
2016-07-27T13:13:25Z
38,624,674
<p>You can use <a href="http://www.ncbi.nlm.nih.gov/books/NBK25499/" rel="nofollow">seq_start and seq_stop</a> to truncate your sequence and then parse it as before, e.g.</p> <pre><code>gb_acc1 = Entrez.efetch(db='nuccore', id=access1, rettype='gb', retmode='xml', seq_start=1, seq_stop=1) </code></pre> <p>Perhaps you don't even need to store the whole GenBank file but only a dictionary with the ID as key and taxonomy and organelle as values?</p>
1
2016-07-27T23:14:10Z
[ "python", "parsing", "biopython", "genbank" ]