title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to read dictionary in different manner? | 38,504,377 | <p>I'm having one dictionary which key is number and value is one or many lists. I want to read this dictionary so that I can separate key and value. </p>
<p><strong>Dictionary-</strong> </p>
<pre><code>{
1468332424064000: '[80000,2]',
1468332423282000: '[30000,6]',
1468332421081000: '[40000,2]',
1468332424121000... | 0 | 2016-07-21T12:30:34Z | 38,504,638 | <p>Try this,</p>
<pre><code>for key,value in d.items():
d[key] = eval(value.replace(']','],',1))
</code></pre>
<p><strong>output</strong></p>
<pre><code>{1468332421046000: ([40000, 2],),
1468332421081000: ([40000, 2],),
1468332421131000: ([40000, 2], [30000, 6]),
1468332421459000: ([30000, 6],),
146833242221... | 0 | 2016-07-21T12:45:02Z | [
"python",
"list",
"dictionary"
] |
How to read dictionary in different manner? | 38,504,377 | <p>I'm having one dictionary which key is number and value is one or many lists. I want to read this dictionary so that I can separate key and value. </p>
<p><strong>Dictionary-</strong> </p>
<pre><code>{
1468332424064000: '[80000,2]',
1468332423282000: '[30000,6]',
1468332421081000: '[40000,2]',
1468332424121000... | 0 | 2016-07-21T12:30:34Z | 38,504,857 | <p>Considering the 'lists' i.e. dictionary values that are been discussed here as string, the numbers can be extracted using regular expressions.</p>
<pre><code>>>> import re
>>> lists = '[30000,2][40000,2]'
>>> out_list = re.findall('\d+',lists)
['30000', '2', '40000', '2'] # The elements... | 0 | 2016-07-21T12:55:05Z | [
"python",
"list",
"dictionary"
] |
Assigning values to multiple names | 38,504,588 | <p>I have seen many Python snippets where they write something like this:</p>
<pre><code>labels, features = targetFeatureSplit(data)
</code></pre>
<p>or something like </p>
<pre><code>ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths, test_size=0.1, random_state=42)
</code>... | 0 | 2016-07-21T12:42:26Z | 38,504,721 | <p>So if you have a function that returns two values like so:</p>
<pre><code>def example():
return 'alice', 'bob'
</code></pre>
<p>You can then call this function and set it to the variable <code>test</code>.</p>
<pre><code>test = example()
</code></pre>
<p>where test is a tuple of 'alice' and 'bob'.</p>
<p>Yo... | 1 | 2016-07-21T12:48:42Z | [
"python",
"python-2.7",
"variables",
"iterable-unpacking"
] |
Filtering dict of dict with dictionary comprehension | 38,504,605 | <p>I have problem with filtering dict of dict while using dict comprehension.</p>
<p>I have dict:</p>
<pre><code>clients = {
'Shop': {'url' : 'url_v', 'customer' : 'cumoster_v',
'some_other_key1' : 'some_value'},
'Gym': {'url' : 'url_v1', 'customer_1' : 'customer_v1', 'customer_2': '... | 2 | 2016-07-21T12:43:12Z | 38,504,793 | <pre><code>>>> {key:{k:v for k,v in dic.items() if 'customer' in k} for key,dic in clients.items()}
{'Shop': {'customer': 'cumoster_v'}, 'Gym': {'customer_2': 'customer_v2', 'customer_1': 'customer_v1'}, 'Bank': {'customer_3': 'customer_v3'}}
</code></pre>
| 4 | 2016-07-21T12:51:47Z | [
"python",
"python-3.x",
"dictionary"
] |
Filtering dict of dict with dictionary comprehension | 38,504,605 | <p>I have problem with filtering dict of dict while using dict comprehension.</p>
<p>I have dict:</p>
<pre><code>clients = {
'Shop': {'url' : 'url_v', 'customer' : 'cumoster_v',
'some_other_key1' : 'some_value'},
'Gym': {'url' : 'url_v1', 'customer_1' : 'customer_v1', 'customer_2': '... | 2 | 2016-07-21T12:43:12Z | 38,504,881 | <pre><code>{k:{k1:v1 for k1,v1 in v.items() if k1.startswith('customer')} for k, v in clients.items()}
</code></pre>
<p>Output :</p>
<pre><code>{'Shop': {'customer': 'cumoster_v'}, 'Gym': {'customer_2': 'customer_v2', 'customer_1': 'customer_v1'}, 'Bank': {'customer_3': 'customer_v3'}}
</code></pre>
| 2 | 2016-07-21T12:56:03Z | [
"python",
"python-3.x",
"dictionary"
] |
Calculate percentage of count for a list of arrays | 38,504,737 | <p>Simple problem, but I cannot seem to get it to work. I want to calculate the percentage a number occurs in a list of arrays and output this percentage accordingly.
I have a list of arrays which looks like this:</p>
<pre><code>import numpy as np
# Create some data
listvalues = []
arr1 = np.array([0, 0, 2])
arr2... | 4 | 2016-07-21T12:49:23Z | 38,505,354 | <p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package has a utility function for this, called count_table, which can be used to solve your problem efficiently as such:</p>
<pre><code>import numpy_indexed as npi
arrs = [arr1, arr2, arr3]
idx = [np.ones(len(a)... | 2 | 2016-07-21T13:16:52Z | [
"python",
"arrays",
"list",
"numpy"
] |
Calculate percentage of count for a list of arrays | 38,504,737 | <p>Simple problem, but I cannot seem to get it to work. I want to calculate the percentage a number occurs in a list of arrays and output this percentage accordingly.
I have a list of arrays which looks like this:</p>
<pre><code>import numpy as np
# Create some data
listvalues = []
arr1 = np.array([0, 0, 2])
arr2... | 4 | 2016-07-21T12:49:23Z | 38,505,399 | <p>You can create a list with the percentages with the following code : </p>
<pre><code>percentage_list = [((counter[i].get(j) if counter[i].get(j) else 0)*10000)//len(listvalues[i])/100.0 for i in range(len(listvalues)) for j in range(3)]
</code></pre>
<p>After that, create a np array from that list :</p>
<pre><cod... | 0 | 2016-07-21T13:19:08Z | [
"python",
"arrays",
"list",
"numpy"
] |
Calculate percentage of count for a list of arrays | 38,504,737 | <p>Simple problem, but I cannot seem to get it to work. I want to calculate the percentage a number occurs in a list of arrays and output this percentage accordingly.
I have a list of arrays which looks like this:</p>
<pre><code>import numpy as np
# Create some data
listvalues = []
arr1 = np.array([0, 0, 2])
arr2... | 4 | 2016-07-21T12:49:23Z | 38,505,456 | <p>Here's an approach -</p>
<pre><code># Get lengths of each element in input list
lens = np.array([len(item) for item in listvalues])
# Form group ID array to ID elements in flattened listvalues
ID_arr = np.repeat(np.arange(len(lens)),lens)
# Extract all values & considering each row as an indexing perform coun... | 1 | 2016-07-21T13:21:36Z | [
"python",
"arrays",
"list",
"numpy"
] |
Calculate percentage of count for a list of arrays | 38,504,737 | <p>Simple problem, but I cannot seem to get it to work. I want to calculate the percentage a number occurs in a list of arrays and output this percentage accordingly.
I have a list of arrays which looks like this:</p>
<pre><code>import numpy as np
# Create some data
listvalues = []
arr1 = np.array([0, 0, 2])
arr2... | 4 | 2016-07-21T12:49:23Z | 38,506,278 | <p>You can get a list of all values and then simply iterate over the individual arrays to get the percentages:</p>
<p><code>values = set([y for row in listvalues for y in row])
print [[(a==x).sum()*100.0/len(a) for x in values] for a in listvalues]
</code></p>
| 2 | 2016-07-21T13:56:51Z | [
"python",
"arrays",
"list",
"numpy"
] |
Calculate percentage of count for a list of arrays | 38,504,737 | <p>Simple problem, but I cannot seem to get it to work. I want to calculate the percentage a number occurs in a list of arrays and output this percentage accordingly.
I have a list of arrays which looks like this:</p>
<pre><code>import numpy as np
# Create some data
listvalues = []
arr1 = np.array([0, 0, 2])
arr2... | 4 | 2016-07-21T12:49:23Z | 38,506,415 | <p>I would like to use functional-paradigm to resolve this problem. For example:</p>
<pre><code>>>> import numpy as np
>>> import pprint
>>>
>>> arr1 = np.array([0, 0, 2])
>>> arr2 = np.array([1, 1, 2, 2])
>>> arr3 = np.array([0, 2, 2])
>>>
>>> ... | 0 | 2016-07-21T14:03:43Z | [
"python",
"arrays",
"list",
"numpy"
] |
Python Pandas DataFrame check if string is other string and fill column | 38,504,740 | <p>I am learning Python and this might be a noob question:</p>
<pre><code>import pandas as pd
A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]
</code></pre>
<p>I want to check rowwise if the string in A is in check_list. The result should be </p>
<pre><code> A YESorN... | 0 | 2016-07-21T12:49:30Z | 38,504,774 | <p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>:</p>
<pre><code>import pandas as pd
import numpy as ... | 1 | 2016-07-21T12:51:09Z | [
"python",
"string",
"if-statement",
"pandas"
] |
Python Pandas DataFrame check if string is other string and fill column | 38,504,740 | <p>I am learning Python and this might be a noob question:</p>
<pre><code>import pandas as pd
A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]
</code></pre>
<p>I want to check rowwise if the string in A is in check_list. The result should be </p>
<pre><code> A YESorN... | 0 | 2016-07-21T12:49:30Z | 38,508,711 | <p>If for some reason you don't want to import numpy,</p>
<pre><code>import pandas as pd
A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]
</code></pre>
<p>Here's the one liner:</p>
<pre><code>A['YESorNO'] = ['YES' if x in check_list else 'NO' for x in A['A']]
</code></pre>
| 1 | 2016-07-21T15:45:28Z | [
"python",
"string",
"if-statement",
"pandas"
] |
Print each n-th row of pandas dataframe | 38,504,756 | <p>is there an elegant solution to print only each n-th row of a pandas dataframe? for instance, I would like to only print each 2nd row.</p>
<p>this could be done via</p>
<pre><code>i = 0
for index, row in df.iterrows():
if ((i%2) == 0):
print(row)
i++
</code></pre>
<p>but is there a more pythonic w... | 2 | 2016-07-21T12:50:12Z | 38,504,785 | <p>slice the df with a step param with <code>iloc</code>:</p>
<pre><code>print(df.iloc[::2])
In [73]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df
Out[73]:
a b c
0 0.613844 -0.167024 -1.287091
1 0.473858 -0.456157 0.037850
2 0.020583 0.368597 -0.147517
3 0.152791 -1... | 4 | 2016-07-21T12:51:31Z | [
"python",
"pandas",
"printing"
] |
Fast calculation of v-disparity with OpenCV-Function calcHist | 38,504,760 | <p>Based on a disparity matrix from a passive stereo-camera system i need to calculate a v-disparity representation for obstacle detection with OpenCV.</p>
<p>A working implementation is <strong>not</strong> the problem. The problem is to do it fast...</p>
<p>(One) Reference for v-Disparity: Labayrade, R. and Aubert,... | 0 | 2016-07-21T12:50:17Z | 38,956,111 | <p>Today i had the possibility to reinvestigate the problem. Remembering the OpenCV basics (<a href="http://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html" rel="nofollow">1</a>) for the <code>Mat</code>-structure and the fact that only one calculation takes a huge amount of time, i ha... | 0 | 2016-08-15T13:35:21Z | [
"python",
"c++",
"opencv",
"computer-vision"
] |
RE pandas resample | 38,504,852 | <p>Been trying to take an average of a month worth of data but I wanted to check that:</p>
<pre><code>df=df.resample('M').mean()
</code></pre>
<p>Does give the monthly mean and NOT the mean of the last calander day of month </p>
<p>Also I've seen <code>W-Mon</code> which would give an average of the monday at a freq... | 2 | 2016-07-21T12:55:01Z | 38,505,500 | <p>try this:</p>
<pre><code>df.assign(y=df.index.year, m=df.index.month).query('m==10').groupby(['y', 'm']).mean()
</code></pre>
<p>PS if you need a neat and tested answer please post sample data set and desired output in your question...</p>
| 1 | 2016-07-21T13:23:37Z | [
"python",
"pandas",
"dataframe",
"time-series"
] |
A more pythonic (or pandorable) way to change a list of columns to different data types | 38,504,885 | <p>Often when wrangling data I have to change datatypes.</p>
<p>For example </p>
<pre><code> In [11]: import pandas as pd
In [12]: import numpy as np
In [13]: df = pd.DataFrame({'col2': {0: 'apples', 1: 'oranges', 2: 'rabbit'}, 'col1': {0: 'white', 1: 'marshmallow', 2: 'bandwagon'}}
)
In [14]: df.d... | 1 | 2016-07-21T12:56:13Z | 38,505,051 | <p>I think your solution is nice.</p>
<p>Another is:</p>
<pre><code>df[['col1','col2']] = df[['col1','col2']].apply(lambda x: x.astype('category'))
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>In [32]: %timeit (orig(df))
10 loops, best of 3: 27.8 ms per loop
In [33]: %timeit df.apply(lambda x: x.astyp... | 1 | 2016-07-21T13:03:40Z | [
"python",
"pandas"
] |
Reading a .VTK polydata file and converting it into Numpy array | 38,504,907 | <p>I want to convert a .VTK ASCII polydata file into numpy array of just the coordinates of the points. I first tried this: <a href="http://stackoverflow.com/a/11894302">http://stackoverflow.com/a/11894302</a> but it stores a (3,3) numpy array where each entry is actually the coordinates of THREE points that make that ... | 0 | 2016-07-21T12:57:13Z | 38,512,033 | <p>You can get the point coordinates from a polydata object like so:</p>
<pre><code>polydata = reader.GetOutput()
points = polydata.GetPoints()
array = points.GetData()
numpy_nodes = vtk_to_numpy(array)
</code></pre>
| 1 | 2016-07-21T18:41:36Z | [
"python",
"arrays",
"numpy",
"vtk"
] |
Python: sorting list of lists not functioning as intended | 38,505,170 | <p>I am trying to sort the following list of lists by the first item of each list in ascending order:</p>
<pre><code>framenos = [
['1468', '2877', 'Pos.:', 95],
['3185', '4339', 'Pos.:', 96],
['195', '1460', 'Pos.:', 97]
]
</code></pre>
<p>I am using the following to do so:</p>
<pre><code>framesorted = s... | 0 | 2016-07-21T13:09:06Z | 38,505,230 | <p>Your values are strings, so you are sorting <a href="https://en.wikipedia.org/wiki/Lexicographical_order"><em>lexicographically</em></a>, not numerically. <code>'1468'</code> is sorted before <code>'195'</code> because <code>'4'</code> comes before <code>'9'</code> in the ASCII standard, just like <code>'Ask'</code>... | 5 | 2016-07-21T13:11:23Z | [
"python",
"list",
"sorting",
"lambda"
] |
Python: sorting list of lists not functioning as intended | 38,505,170 | <p>I am trying to sort the following list of lists by the first item of each list in ascending order:</p>
<pre><code>framenos = [
['1468', '2877', 'Pos.:', 95],
['3185', '4339', 'Pos.:', 96],
['195', '1460', 'Pos.:', 97]
]
</code></pre>
<p>I am using the following to do so:</p>
<pre><code>framesorted = s... | 0 | 2016-07-21T13:09:06Z | 38,505,289 | <p>Since the first element of each list is a string, is is sorting these numbers in alphabetical order. in order to sort these lists based on the integer value of the first element try casting to int:</p>
<pre><code>framesorted = sorted(framenos, key=lambda x: int(x[0]))
</code></pre>
| 0 | 2016-07-21T13:14:06Z | [
"python",
"list",
"sorting",
"lambda"
] |
How to remove double quotes from index of csv file in python | 38,505,250 | <p>I'm trying to read multiple <code>csv</code> files with python. The index of raw data(or the first column) has a little problem, the partial csv file looks like this:</p>
<pre><code>NoDemande;"NoUsager";"Sens";"IdVehiculeUtilise";"NoConducteur";"NoAdresse";"Fait";"HeurePrevue"
42210000003;"42210000529";"+";"265Véh... | 1 | 2016-07-21T13:12:08Z | 39,364,688 | <p>In fact, I was stuck with how to remove double quotes from index. After changing the angle, I think maybe it's better to add a new column, copying the values from the original one and delete it. So the new column will have the index you want.
In my case, I did:</p>
<pre><code>frame['NoDemande'] = frame.ix[:, 0]
tl ... | 0 | 2016-09-07T08:19:03Z | [
"python",
"csv",
"pandas",
"dataframe",
"double-quotes"
] |
How to remove double quotes from index of csv file in python | 38,505,250 | <p>I'm trying to read multiple <code>csv</code> files with python. The index of raw data(or the first column) has a little problem, the partial csv file looks like this:</p>
<pre><code>NoDemande;"NoUsager";"Sens";"IdVehiculeUtilise";"NoConducteur";"NoAdresse";"Fait";"HeurePrevue"
42210000003;"42210000529";"+";"265Véh... | 1 | 2016-07-21T13:12:08Z | 39,364,879 | <p>I think the simpliest is set new column names:</p>
<pre><code>df.columns = ['NoDemande1'] + df.columns[1:].tolist()
print (df)
NoDemande1 NoUsager Sens IdVehiculeUtilise NoConducteur NoAdresse \
0 42210000003 42210000529 + 265Véh 42210000032 42210002932
1 42210000005 4221000180... | 0 | 2016-09-07T08:28:51Z | [
"python",
"csv",
"pandas",
"dataframe",
"double-quotes"
] |
Trigger loop after n lines in a text file | 38,505,339 | <p>I want to execute a loop if and only 5 lines have been executed inside the text file that's being written to. The reason being, I want the average to be calculated from the final 5 lines of the text file and if the program doesn't have 5 numbers to work with, then a rumtime error is thrown. </p>
<pre><code> #Imp... | 1 | 2016-07-21T13:16:27Z | 38,506,115 | <p>Your <code>while</code> loop is never going to end. I think you meant to decrement: <code>pageCount-=1</code>.</p>
| 0 | 2016-07-21T13:49:49Z | [
"python",
"file",
"loops",
"if-statement",
"text"
] |
Trigger loop after n lines in a text file | 38,505,339 | <p>I want to execute a loop if and only 5 lines have been executed inside the text file that's being written to. The reason being, I want the average to be calculated from the final 5 lines of the text file and if the program doesn't have 5 numbers to work with, then a rumtime error is thrown. </p>
<pre><code> #Imp... | 1 | 2016-07-21T13:16:27Z | 38,506,516 | <p>The problem at the end was that the loop wasn't restarting and just finishing on the first average calculation. This was due to the logFile being closed and not being reopen, so the program thought it and appending to the file, it works just as expected. Thanks to all for the help.</p>
<pre><code>#Imports
from bs4 ... | 0 | 2016-07-21T14:08:01Z | [
"python",
"file",
"loops",
"if-statement",
"text"
] |
Django storing a lot of data in table | 38,505,345 | <p>Right now, I use this code to save the data to the database-</p>
<pre><code>for i in range(len(companies)):
for j in range(len(final_prices)):
linechartdata = LineChartData()
linechartdata.foundation = company //this refers to a foreign-key of a different model
linechartdata.date = finald[j]
... | 0 | 2016-07-21T13:16:38Z | 38,505,564 | <p>If you really need to store them in the database you might check <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#bulk-create" rel="nofollow">bulk_create</a>. From the documents: </p>
<blockquote>
<p>This method inserts the provided list of objects into the database in an efficient manner (gen... | 2 | 2016-07-21T13:26:16Z | [
"python",
"django"
] |
How do I convert text lines to columns? | 38,505,404 | <p>It's probably very simple thing but I am totally new in Python so sorry. The cas is I have a lot of files containing this type of text:</p>
<pre><code>name1
[1.0 2.0 3.0],[1.1 2.1 3.1]
</code></pre>
<p>(the directory /data/text1/1.txt)</p>
<p>the other file for example contains</p>
<pre><code>name2
[4.0 5.0 6.0]... | -5 | 2016-07-21T13:19:25Z | 38,505,863 | <p>You can <code>zip</code> and <code>re</code> to solve your problem.
Below is the code:</p>
<pre><code>>>> import re, os
>>> for file in os.listdir("directory"):
>>> with open(file) as fp:
>>> for line in fp.readlines():
>>> lists = [re.findall("\d+... | 1 | 2016-07-21T13:38:03Z | [
"python"
] |
Pandas implicit type casting from index to series | 38,505,415 | <p>This works:</p>
<pre><code> s['Date'] = s.index.get_level_values('Date')
s['Expire Days'] = (pd.to_datetime(s['Expiration']) - s['Date'])
</code></pre>
<p>But this does not:</p>
<pre><code> s['Expire Days'] = (pd.to_datetime(s['Expiration']) - s.index.get_level_values('Date'))
</code></pre>
<p>The erro... | 1 | 2016-07-21T13:20:01Z | 38,505,528 | <p>For me works add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> for converting <code>Series</code> to <code>numpy array</code>:</p>
<pre><code>s['Expire Days'] = pd.to_datetime(s['Expiration']).values -
s.index.get... | 1 | 2016-07-21T13:24:45Z | [
"python",
"pandas"
] |
Efficient NumPy rows rotation over variable distances | 38,505,440 | <p>Given a 2D <code>M x N</code> NumPy array and a list of rotation distances, I want to rotate all <code>M</code> rows over the distances in the list. This is what I currently have:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
M = 6
N = 8
dists = [2,0,2,1,4,2] # for example
matrix = np.rand... | 3 | 2016-07-21T13:20:59Z | 38,506,037 | <p>We can simulate the rolling behaviour with modulus operation after adding <code>dists</code> with a <code>range(0...N)</code> array to give us column indices for each row from where elements are to be picked and shuffled in the same row. We can vectorize this process across all rows with the help of <a href="http://... | 1 | 2016-07-21T13:46:01Z | [
"python",
"python-3.x",
"numpy",
"optimization"
] |
Scapy - How can I hide the report of sendp\sr1 and just get the final?â | 38,505,507 | <p>I am working with scapy and I started to learn how to build packets (if someone has a good example on the internet to learn from it - it will be great! thanks.).</p>
<p>I have the next command in scapy:</p>
<pre><code>srp(Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=ip)/Padding(load='\\x00\\x00\\x00\\x00\\x00\\x00\\x00... | 1 | 2016-07-21T13:23:55Z | 38,507,048 | <p>
Part of the output here come from a warning, due to IPv6, which you may avoid by disabling IPv6 support (from scapy), but you also have output generated by the function <code>srp()</code> itself, and for that you need to set the <code>verbose</code> argument:</p>
<pre><code>from scapy.config import conf
conf.ipv... | 2 | 2016-07-21T14:31:01Z | [
"python",
"scapy",
"packets"
] |
How to escape unicode string for regular expressions? | 38,505,706 | <p>I need to build an re pattern based on the unicode string (e.g. I have "word", and I need something like ^"word"| "word"). However the "word" can contain special re characters. To match the "word" as it is, I need to escape special re characters in unicode string. The basic re.escape() function does the job for asci... | 0 | 2016-07-21T13:32:24Z | 38,506,087 | <p><code>re.escape()</code> inserts a backslash before every character that's not an ASCII alphanumeric. This may in fact lead to a multitude of unnecessary backslashes to be inserted, however, Python ignores backslashes that don't start a recognized escape sequence, so there is no big harm done (except possibly some p... | 1 | 2016-07-21T13:48:31Z | [
"python",
"regex",
"unicode",
"escaping"
] |
jupyter doesn't import numpy after upgrade with anaconda | 38,505,832 | <p>I updated the packages with <code>conda update --all</code> and was using jupyter to work. Before the update, everything was working, but now jupyter doesn't import any module beside the sys, os, copy and time. Numpy, matplotlib and theano are not being imported. But they are definitely in the conda list... the pyth... | 0 | 2016-07-21T13:37:04Z | 38,637,838 | <p>I followed the idea as in <a href="http://stackoverflow.com/questions/9386048/ipython-reads-wrong-python-version">here</a> and changed the file that launches the root jupyter command (cf. <code>cat /dir_where_installed/anaconda2/bin/jupyter</code> and the jupyter-notebook ( cf. <code>cat /dir_where_installed/anacond... | 0 | 2016-07-28T13:27:12Z | [
"python",
"jupyter"
] |
How to delete a function argument early? | 38,505,862 | <p>I'm writing a function which takes a huge argument, and runs for a long time. It needs the argument only halfway. Is there a way for the function to delete the value pointed to by the argument if there are no more references to it?</p>
<p>I was able to get it deleted as soon as the function returns, like this:</p>
... | 1 | 2016-07-21T13:38:02Z | 38,506,738 | <p>From <a href="https://docs.python.org/2/reference/datamodel.html" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p>CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they ... | 1 | 2016-07-21T14:17:51Z | [
"python",
"python-2.7",
"destructor",
"reference-counting"
] |
How do I filter rows in a dataframe that have whole numbers in one column | 38,505,895 | <p>I am new to Python and Pandas and I am struggling a bit with this.</p>
<p>I have a set of data with an <code>Age</code> column of type <code>float64</code>. Some of the values have a fractional part and some do not. I want to remove all the rows that have whole number values for <code>Age</code>.</p>
<p>This was... | 2 | 2016-07-21T13:39:35Z | 38,505,914 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a> for cast to <code>int</code>:</p>
<pre><code>estimatedAges = train[train['Age'].astype(int) < train['Age']]
</code></pre>
<p>Sample:</p>
<pre><code>train = pd.Dat... | 4 | 2016-07-21T13:40:35Z | [
"python",
"pandas",
"dataframe"
] |
How do I filter rows in a dataframe that have whole numbers in one column | 38,505,895 | <p>I am new to Python and Pandas and I am struggling a bit with this.</p>
<p>I have a set of data with an <code>Age</code> column of type <code>float64</code>. Some of the values have a fractional part and some do not. I want to remove all the rows that have whole number values for <code>Age</code>.</p>
<p>This was... | 2 | 2016-07-21T13:39:35Z | 38,506,092 | <p>try this:</p>
<pre><code>In [179]: train[train.Age != train.Age // 1]
Out[179]:
Age
2 3.4
</code></pre>
| 2 | 2016-07-21T13:48:44Z | [
"python",
"pandas",
"dataframe"
] |
How do I filter rows in a dataframe that have whole numbers in one column | 38,505,895 | <p>I am new to Python and Pandas and I am struggling a bit with this.</p>
<p>I have a set of data with an <code>Age</code> column of type <code>float64</code>. Some of the values have a fractional part and some do not. I want to remove all the rows that have whole number values for <code>Age</code>.</p>
<p>This was... | 2 | 2016-07-21T13:39:35Z | 38,517,722 | <p>I ultimately went with @jezreal's answer because his speed tests were convincing but I wanted to add one more solution that I found to the mix. It requires numpy, but if you have imported pandas then you have more than likely imported numpy as well.</p>
<pre><code>import numpy as np
train[np.floor(train['Age']) !=... | 0 | 2016-07-22T03:32:38Z | [
"python",
"pandas",
"dataframe"
] |
numpy testing assert array NOT equal | 38,506,044 | <p>We have <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.testing.assert_array_equal.html#numpy.testing.assert_array_equal" rel="nofollow"><code>numpy.testing.assert_array_equal</code></a> to assert that two arrays are equal.</p>
<p>But what is the best way to do <code>numpy.testing.assert_arra... | 5 | 2016-07-21T13:46:24Z | 38,506,922 | <p>I don't think there is anything built directly into the NumPy testing framework but you could just use:</p>
<pre><code>np.any(np.not_equal(a1,a2))
</code></pre>
<p>and assert true with the built in unittest framework or check with NumPy as <code>assert_equal</code> to <code>True</code> e.g.</p>
<pre><code>np.test... | 3 | 2016-07-21T14:25:54Z | [
"python",
"numpy",
"python-unittest"
] |
numpy testing assert array NOT equal | 38,506,044 | <p>We have <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.testing.assert_array_equal.html#numpy.testing.assert_array_equal" rel="nofollow"><code>numpy.testing.assert_array_equal</code></a> to assert that two arrays are equal.</p>
<p>But what is the best way to do <code>numpy.testing.assert_arra... | 5 | 2016-07-21T13:46:24Z | 38,507,093 | <p>If you want to use specifically NumPy testing, then you can use <code>numpy.testing.assert_array_equal</code> together with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_raises.html#numpy.testing.assert_raises" rel="nofollow">numpy.testing.assert_raises</a> for the opposite result... | 3 | 2016-07-21T14:33:00Z | [
"python",
"numpy",
"python-unittest"
] |
Fitting histograms of log-normal distributions in subplots with shared x-axis | 38,506,120 | <p>I have three arrays, of different lengths, say <code>standx</code>, <code>standy</code> and <code>standz</code>, which contain positive only values.
I want to plot their histogram distributions in a similar fashion than <a href="http://i.stack.imgur.com/gZa3k.png" rel="nofollow">this plot</a>, that is, sharing the x... | 2 | 2016-07-21T13:50:12Z | 38,623,367 | <p>I think you want to fit on log transformed bins and correct the scaling by multiplying at each bin as you do above. </p>
<p><a href="http://i.stack.imgur.com/C5I8E.png" rel="nofollow"><img src="http://i.stack.imgur.com/C5I8E.png" alt="enter image description here"></a></p>
<pre><code>def gaussian(x, a, mean, sigma... | 1 | 2016-07-27T21:19:32Z | [
"python",
"matplotlib",
"gaussian",
"data-fitting"
] |
Trouble using OpenGL mouse callbacks in Pygame | 38,506,181 | <p>I'm using OpenGL through Pygame to render things and I want to get OpenGL mouse information. I know that I can get mouse position & click state directly through Pygame, but I need mouse position in OpenGL's coordinates, not just pixel coordinates of the viewport. The issue is that I can't get OpenGL's mouse ca... | 0 | 2016-07-21T13:52:58Z | 38,506,814 | <p>You might be able to just use <code>pygame coordinates / viewport</code> to get coordinates in the [0;1] interval (e.g. for texture coordinates) or <code>pygame coordinates / viewport * 2 - 1</code> for [-1;1] interval (NDC coordinates).</p>
<p>I think using glut for this won't work, because you create your window ... | 0 | 2016-07-21T14:21:03Z | [
"python",
"opengl",
"pygame",
"pyopengl"
] |
recursing a list of 73033 elements with HTML tags and get context from it | 38,506,210 | <p>I have a long list of elements with a length of 73,033. I would like to get the context from it. In the list, each element has the same structure (if the block of the following code helps), and it looks like this <code><div align="center" class="photocaption"> Author/Designer Carleton Varney with Jim Druckman ... | 0 | 2016-07-21T13:54:04Z | 38,511,386 | <p>What I am going to post is not the most elegant or efficient way to deal with the posted problem. As Welbog pointed out, BeautifulSoup itself has provided the function of extracting context. As I received the error as I posted my original question, however, I was just curious where the error came from. It turned out... | 0 | 2016-07-21T18:06:55Z | [
"python",
"regex",
"list"
] |
How to get input from multiple lines? | 38,506,250 | <p>i want to take input from user in and each value of the input is on consecutive line.this is to be implemented in python</p>
<pre><code>while x=int(raw_input()): ##<=showing error at this line
print(x)
gollum(x)
#the function gollum() has to be called if the input is present
</code></pre>
| -2 | 2016-07-21T13:55:45Z | 38,506,376 | <p>The reason why your code does not work is why wants a condition or an object. As you are assigning a value (<code>x=raw_input()</code>), while does not find anything to test (an assignment does NOT return any value).<br>
You can either request an input, and then do a while loop depending on the value of this input (... | 0 | 2016-07-21T14:01:51Z | [
"python"
] |
How to get input from multiple lines? | 38,506,250 | <p>i want to take input from user in and each value of the input is on consecutive line.this is to be implemented in python</p>
<pre><code>while x=int(raw_input()): ##<=showing error at this line
print(x)
gollum(x)
#the function gollum() has to be called if the input is present
</code></pre>
| -2 | 2016-07-21T13:55:45Z | 38,506,440 | <p>That gives you an error because x=int(raw_input()) doesn't return a boolean, and you need a boolean inside the while condition.
You can try this one:</p>
<pre><code> while True:
x = raw_input()
if x=='':
break
x = int(x)
print(x)
gollum(x)
</code></pre>
<p>tha... | 0 | 2016-07-21T14:04:35Z | [
"python"
] |
For loop output to a string in python | 38,506,358 | <p>So i wrote a code that takes a string and print out the ascii code but i have this problem that i'm printing out the ascii for every letter in a for loop and in the end i want it to be a string of a number.</p>
<p>This is the code:</p>
<pre><code>getname='test'
for letter in getname:
print ord(letter)
</code><... | 0 | 2016-07-21T14:00:42Z | 38,506,422 | <p>You want to create a string and append to it, like this:</p>
<pre><code>getname = 'test'
result = ''
for letter in getname:
result += ord(letter)
print result
</code></pre>
<p>Output: </p>
<pre><code>116101115116
</code></pre>
| 1 | 2016-07-21T14:03:55Z | [
"python",
"string",
"for-loop",
"ascii"
] |
For loop output to a string in python | 38,506,358 | <p>So i wrote a code that takes a string and print out the ascii code but i have this problem that i'm printing out the ascii for every letter in a for loop and in the end i want it to be a string of a number.</p>
<p>This is the code:</p>
<pre><code>getname='test'
for letter in getname:
print ord(letter)
</code><... | 0 | 2016-07-21T14:00:42Z | 38,506,429 | <p>You can do a one line statement like this</p>
<pre><code>>>> "".join(str(ord(x)) for x in getname)
'116101115116'
</code></pre>
| 2 | 2016-07-21T14:04:12Z | [
"python",
"string",
"for-loop",
"ascii"
] |
Randomly concat data frames by row | 38,506,360 | <p>How can I randomly merge, join or concat pandas data frames by row? Suppose I have four data frames something like this (with a lot more rows): </p>
<pre><code>df1 = pd.DataFrame({'col1':["1_1", "1_1"], 'col2':["1_2", "1_2"], 'col3':["1_3", "1_3"]})
df2 = pd.DataFrame({'col1':["2_1", "2_1"], 'col2':["2_2", "2_2"], ... | 2 | 2016-07-21T14:00:43Z | 38,509,931 | <p><strong>UPDATE:</strong> a much better solution from @Divakar:</p>
<pre><code>df1 = pd.DataFrame({'col1':["1_1", "1_1"], 'col2':["1_2", "1_2"], 'col3':["1_3", "1_3"], 'col4':["1_4", "1_4"]})
df2 = pd.DataFrame({'col1':["2_1", "2_1"], 'col2':["2_2", "2_2"], 'col3':["2_3", "2_3"], 'col4':["2_4", "2_4"]})
df3 = pd.Dat... | 2 | 2016-07-21T16:44:14Z | [
"python",
"numpy",
"pandas"
] |
How to format a list when I print it | 38,506,394 | <pre><code>values = [[3.5689651969162908, 4.664618442892583, 3.338666695570425],
[6.293153787450157, 1.1285723419142026, 10.923859694586376],
[2.052506259736077, 3.5496423448584924, 9.995488620338277],
[9.41858935127928, 10.034233496516803, 7.070345442417161]]
def flatten(values):
ne... | 2 | 2016-07-21T14:02:36Z | 38,506,679 | <p>You could use:</p>
<pre><code>print(["{:.2f}".format(val) for val in v])
</code></pre>
<p>Note that you can flatten your list using <code>itertools.chain</code>:</p>
<pre><code>import itertools
v = list(itertools.chain(*values))
</code></pre>
| 3 | 2016-07-21T14:15:09Z | [
"python",
"python-3.x"
] |
How to format a list when I print it | 38,506,394 | <pre><code>values = [[3.5689651969162908, 4.664618442892583, 3.338666695570425],
[6.293153787450157, 1.1285723419142026, 10.923859694586376],
[2.052506259736077, 3.5496423448584924, 9.995488620338277],
[9.41858935127928, 10.034233496516803, 7.070345442417161]]
def flatten(values):
ne... | 2 | 2016-07-21T14:02:36Z | 38,506,682 | <p>You can first flatten the list (<a href="http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python">as described here</a>) and then use <code>round</code> to solve this:</p>
<pre><code>flat_list = [number for sublist in l for number in sublist]
# All numbers are in the same list no... | 0 | 2016-07-21T14:15:21Z | [
"python",
"python-3.x"
] |
How to format a list when I print it | 38,506,394 | <pre><code>values = [[3.5689651969162908, 4.664618442892583, 3.338666695570425],
[6.293153787450157, 1.1285723419142026, 10.923859694586376],
[2.052506259736077, 3.5496423448584924, 9.995488620338277],
[9.41858935127928, 10.034233496516803, 7.070345442417161]]
def flatten(values):
ne... | 2 | 2016-07-21T14:02:36Z | 38,506,724 | <p>I would use the built-in function <code>round()</code>, and while I was about it I would simplify your <code>for</code> loops:</p>
<pre><code>def flatten(values):
new_values = []
for i in values:
for v in i:
new_values.append(round(v, 2))
return new_values
</code></pre>
| 0 | 2016-07-21T14:17:12Z | [
"python",
"python-3.x"
] |
How to format a list when I print it | 38,506,394 | <pre><code>values = [[3.5689651969162908, 4.664618442892583, 3.338666695570425],
[6.293153787450157, 1.1285723419142026, 10.923859694586376],
[2.052506259736077, 3.5496423448584924, 9.995488620338277],
[9.41858935127928, 10.034233496516803, 7.070345442417161]]
def flatten(values):
ne... | 2 | 2016-07-21T14:02:36Z | 38,506,768 | <p>How to flatten and transform the list in one line</p>
<pre><code>[round(x,2) for b in [x for x in values] for x in b]
</code></pre>
<p>It returns a list of two decimals after the comma.</p>
| 0 | 2016-07-21T14:19:07Z | [
"python",
"python-3.x"
] |
How to format a list when I print it | 38,506,394 | <pre><code>values = [[3.5689651969162908, 4.664618442892583, 3.338666695570425],
[6.293153787450157, 1.1285723419142026, 10.923859694586376],
[2.052506259736077, 3.5496423448584924, 9.995488620338277],
[9.41858935127928, 10.034233496516803, 7.070345442417161]]
def flatten(values):
ne... | 2 | 2016-07-21T14:02:36Z | 38,506,845 | <p>One you have v you can use a list comprehension like:</p>
<pre><code>formattedList = ["%.2f" % member for member in v]
</code></pre>
<p>output was as follows:</p>
<pre><code>['3.57', '4.66', '3.34', '6.29', '1.13', '10.92', '2.05', '3.55', '10.00', '9.42', '10.03', '7.07']
</code></pre>
<p>Hope that helps!</p>
| 0 | 2016-07-21T14:22:34Z | [
"python",
"python-3.x"
] |
How do I convert greyscale images represented as strings of space separated pixel values to column of features to train a classifier in scikit-learn? | 38,506,413 | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
data = pd.read_csv('fer2013.csv')
data.head()
</code></pre>
<p><img src="http://i.stack.imgur.com/XeKSW.jpg" alt="First 5 entries in training set"></p>
<pre><code>face1 = np.fromstring(data['pixels'][0]... | 0 | 2016-07-21T14:03:33Z | 38,506,672 | <p>You should show current attempts/ research you've done already to solve the problem when positing questions on SO.</p>
<p>You can load an image in Python easily using OpenCV, the result <code>img</code> is a numpy array, so you can just print it as a string e.g.</p>
<pre><code>import numpy as np
import cv2
# Load... | 0 | 2016-07-21T14:14:58Z | [
"python",
"numpy",
"pandas",
"matplotlib",
"scikit-learn"
] |
How do I convert greyscale images represented as strings of space separated pixel values to column of features to train a classifier in scikit-learn? | 38,506,413 | <pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
data = pd.read_csv('fer2013.csv')
data.head()
</code></pre>
<p><img src="http://i.stack.imgur.com/XeKSW.jpg" alt="First 5 entries in training set"></p>
<pre><code>face1 = np.fromstring(data['pixels'][0]... | 0 | 2016-07-21T14:03:33Z | 38,531,397 | <pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn import svm, metrics
#Read csv file
data = pd.read_csv('fer2013.csv')
#Number of samples
n_samples = len(data)
n_samples_train = 28709
n_samples_test = 3589
n_samples_validation = 3589
#P... | 0 | 2016-07-22T16:32:03Z | [
"python",
"numpy",
"pandas",
"matplotlib",
"scikit-learn"
] |
Python download images with changing variables | 38,506,431 | <p>I was trying to download images with url's that change but got an error.</p>
<pre><code>import urllib.request
import random
random_number=random.randint(500,600)
url_image="'https://csgostash.com/img/skins/s"+str(random_number)+"fn.png'"
image=urllib.request.urlretrieve(url_image, 'skin.png')
</code></pre>
<p>T... | 0 | 2016-07-21T14:04:17Z | 38,506,903 | <p>First, url_image has an weird syntax.</p>
<pre><code> url_image="https://csgostash.com/img/skins/s"+str(random_number)+"fn.png"
</code></pre>
<p>If you fix this, you will notice an 403 - Vax! Protection against bot: use a user agent.</p>
<pre><code>import urllib.request
import random
random_number=random.rand... | 0 | 2016-07-21T14:24:58Z | [
"python",
"image",
"url",
"urllib",
"python-3.5"
] |
Calling a python script with arguments using subprocess | 38,506,442 | <p>I have a python script which call another python script from another directory. To do that I used <code>subprocess.Popen</code> :</p>
<pre><code>import os
import subprocess
arg_list = [project, profile, reader, file, str(loop)]
</code></pre>
<p>where all args are string if not converted implicitely</p>
<pre><cod... | 0 | 2016-07-21T14:04:38Z | 38,506,932 | <p>When you pass parameters to a new process they are passed positionally, the names from the parent process do not survive, only the values. You need to add:</p>
<pre><code>import sys
def main():
if len(sys.argv) == 6:
project, profile, reader, file, loop = sys.argv[1:]
else:
raise ValueE... | 2 | 2016-07-21T14:26:22Z | [
"python",
"arguments",
"subprocess",
"popen"
] |
I keep getting errors like 'ResultSet' object has no attribute 'get' and 'NoneType' object has no attribute 'get' | 38,506,478 | <p>I am trying to scrape the youtube water mark a element href but I can't seem to grab it.</p>
<p>if I try </p>
<pre><code> def youtube_link(url):
youtube_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(youtube_page.text, 'html5lib')
video_row = soupdata.find_all('a', {... | 1 | 2016-07-21T14:06:10Z | 38,506,855 | <p>When I used full value for the class I got the href...</p>
<pre><code>video_row = soupdata.find('a', {'class': 'ytp-watermark yt-uix-sessionlink'})
</code></pre>
<p>and if you want to use findAll you have to iterate over entries. for example create yourself additional list entries_final and do this:</p>
<pre><cod... | 0 | 2016-07-21T14:22:55Z | [
"python",
"django",
"web-scraping",
"beautifulsoup"
] |
How can I edit an object without saved it in Django | 38,506,481 | <p>There is a problem with my Django project, when I add an object it saves immediatly after that I will be redirected by object id to <strong>server_edit</strong> where I can fill fields. If I fill no fields and push "back" (go to previous page) browser button object will be saved without any data even if <strong>Save... | 0 | 2016-07-21T14:06:22Z | 38,507,873 | <p>You should avoid saving object and <strong>then</strong> filling it with data in different view.</p>
<p>Try using generic edit views such as CreateView/EditView or FormView with Django forms (<a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-editing/" rel="nofollow">https://docs.djangopro... | 1 | 2016-07-21T15:06:59Z | [
"python",
"django",
"django-forms"
] |
How can I edit an object without saved it in Django | 38,506,481 | <p>There is a problem with my Django project, when I add an object it saves immediatly after that I will be redirected by object id to <strong>server_edit</strong> where I can fill fields. If I fill no fields and push "back" (go to previous page) browser button object will be saved without any data even if <strong>Save... | 0 | 2016-07-21T14:06:22Z | 38,509,199 | <p>Http calls should be stateless. The connection can be dropped any time, which leaves the DB in the same inconsistent state which is what you try to avoid here. Instead of using the form which only contains name, you could just redirect the user to a new page with the form for the rest of the data with the previously... | 0 | 2016-07-21T16:08:52Z | [
"python",
"django",
"django-forms"
] |
Tornado Escape Pound # character | 38,506,499 | <p>I am writing a program/ service that handle text and its attributes.
localhost:8000/title?img=img_url.jpg&text_color=#FF0000 </p>
<p>and In my handler I have something like:</p>
<pre><code>application = tornado.web.Application([
(r"/title_overlay", MainHandler),
])
class MainHandler(tornado.web.RequestHan... | 0 | 2016-07-21T14:07:17Z | 38,510,311 | <p>Yes, it's because the portion after '#' is called the <a href="https://en.wikipedia.org/wiki/Fragment_identifier" rel="nofollow">fragment identifier</a>, which the browser does not even send to the server when it fetches the URL. In order to encode a color in your URL you'll have to omit the '#' character, or URL-en... | 1 | 2016-07-21T17:05:19Z | [
"python",
"python-2.7",
"web-services",
"url",
"tornado"
] |
Python to convert special unicode characters ( like â¡) to their hexadecimal literals in a string (like 0x2661) | 38,506,568 | <p>I'm writing a program that pulls screen names and tweets from twitter into a txt file. Some screen names contain special unicode characters like â¡. In my Bash terminal these characters show up as an empty box. My sql fails when I try to insert this character and tells me it contains an untranslatable character. Is... | 0 | 2016-07-21T14:10:21Z | 38,506,689 | <p>You can achieve this using the <code>encode</code> method, explained <a href="https://docs.python.org/2.7/howto/unicode.html" rel="nofollow">here</a>. From the docs:</p>
<blockquote>
<p>Another important method is .encode([encoding], [errors='strict']),
which returns an 8-bit string version of the Unicode strin... | 0 | 2016-07-21T14:15:42Z | [
"python",
"string",
"bash",
"unicode",
"tweepy"
] |
Failed to parse arguments | 38,506,569 | <p>I'm trying to run this code:</p>
<pre><code>os.system("""gnome-terminal -e 'bash -c "arpspoof -i " + inter + " -t " + target + " " + gateway" ' """)
</code></pre>
<p>and the error is:</p>
<p>"Failed to parse arguments: Argument to "--command/-e" is not a valid command: Text ended before matching quote was found f... | 1 | 2016-07-21T14:10:21Z | 38,506,694 | <p>The issue is that you're trying to add strings in a triple quoted string. You seem to be trying to put the value of your variables into your triple quoted string, but you're actually passing the literal string <code>gnome-terminal -e 'bash -c "arpspoof -i " + inter + " -t " + target + " " + gateway" '</code> to <c... | 1 | 2016-07-21T14:15:46Z | [
"python",
"linux",
"bash"
] |
Cython: python int to uint8_t | 38,506,662 | <p>For my work, I need to use this C++ function with python.</p>
<pre><code>std::vector<std::string> pinCertificate(const std::vector<uint8_t>& certificate, bool local)
</code></pre>
<p>I've already translated the prototype to this in Cython</p>
<pre><code>vector[string] pinCertificate(const vector[u... | 1 | 2016-07-21T14:14:37Z | 38,513,407 | <p>Well, it seems that the problem came from the internal C++ code I had.</p>
| 0 | 2016-07-21T20:05:31Z | [
"python",
"c++",
"type-conversion",
"cython",
"typeerror"
] |
What does this decorator of decorator do? | 38,506,699 | <p>I'm reading <a href="http://stackoverflow.com/a/1594484/5399734">this answer</a> to understand what decorators are and what can they do, from which my question emerges. The author provide a bonus snippet, which can make any decorator accept generically any argument, and this snippet really confused me:</p>
<pre><co... | 0 | 2016-07-21T14:15:55Z | 38,508,431 | <p>In short, <code>decorator_with_args</code> turns a function call like this:</p>
<pre><code>function(func, *args, **kwargs)
</code></pre>
<p>to this form:</p>
<pre><code>function(*args, **kwargs)(fund)
</code></pre>
<p>Note that both function call return another function.</p>
| 1 | 2016-07-21T15:32:43Z | [
"python",
"python-2.7",
"decorator",
"python-decorators"
] |
How can I get a list of genes from a list of refseq accession numbers (NM_<num> and NR_<num>) | 38,506,744 | <p>I am using python 2.7 and trying to use biopython or pyensembl to obtain a list of genes from a list of refseq accession numbers. Is there a simple way I can do this? </p>
| 0 | 2016-07-21T14:18:05Z | 38,513,914 | <p>Yes, there is a simple way. But you should always show some effort, some code you tried before asking. This is the code you need:</p>
<pre><code>from Bio import Entrez
Entrez.email = "trouselife@gmail.com"
handle = Entrez.efetch(db="nucleotide", id="NM_123456", retmode="xml")
record = Entrez.read(handle)
for feat... | 0 | 2016-07-21T20:35:37Z | [
"python",
"bioinformatics",
"biopython"
] |
Random number does not update every time I call the function | 38,506,759 | <p>I am writing a game, "Guess the number". Initially, the computer chooses a random number in the range 0-99 and the player guesses what number it is. Once the player's guessed the number, the game starts again.</p>
<p>The player can restart the game at any time, using two buttons:
"New game. Range is 0-100"
and
"Ne... | -1 | 2016-07-21T14:18:48Z | 38,507,219 | <p>Let's do it the quick but not so ugly way.</p>
<p>First, let's create a new global variable <code>max_number = 100</code></p>
<p>Then, the changes you must do to <code>new_game()</code></p>
<pre><code>def new_game():
print "Guess the number!"
global secret_number
global max_number
secret_number = ... | 2 | 2016-07-21T14:38:20Z | [
"python"
] |
Deleting previous token in a sentence if same as current token python | 38,506,857 | <p>I have 2 dictionaries of key, value pairs like:</p>
<pre><code>tokenIDs2number = {(6, 7): 1000000000.0, (22,): 700.0, (12,): 3000.0}
tokenIDs2number = {(27, 28): u'South Asia'}
</code></pre>
<p>The keys are tuples of the index locations of number and location slots in the sentence:</p>
<pre><code>GDP in 2007 tot... | 1 | 2016-07-21T14:23:04Z | 38,507,047 | <p>Since <code>tuple</code>s (and usually <code>dict</code> keys in general) are immutable, you can not change the keys directly. However, you can use a dictionary comprehension to transform your dict to what you need in one line:</p>
<pre><code>tokenIDs2number = {(6, 7): 1000000000.0, (22,): 700.0, (12,): 3000.0}
tok... | 1 | 2016-07-21T14:30:59Z | [
"python",
"dictionary",
"tuples"
] |
Python Sqlite3- Python shell can create and edit databases but why can't a .py file create or access any database | 38,506,909 | <pre><code>import sqlite3
db=sqlite3.connect('new.db')
cursor=db.cursor()
cursor.execute('''CREATE TABLE hello(id INTEGER PRIMARY KEY,
Message_type, time_sent, time_received, response)''')
</code></pre>
<p>The above program when executed from the python shell will execute and create a database by the said name but whe... | 0 | 2016-07-21T14:25:12Z | 38,507,004 | <p>I suppose that the .py file did create the database file, but you aren't looking for the database file at the correct location. Add this to the end of your program:</p>
<pre><code>print(os.path.join(os.getcwd(), 'new.db'))
</code></pre>
<p>Whatever it prints, look there for your database file.</p>
| 0 | 2016-07-21T14:29:21Z | [
"python",
"sqlite"
] |
Python Sqlite3- Python shell can create and edit databases but why can't a .py file create or access any database | 38,506,909 | <pre><code>import sqlite3
db=sqlite3.connect('new.db')
cursor=db.cursor()
cursor.execute('''CREATE TABLE hello(id INTEGER PRIMARY KEY,
Message_type, time_sent, time_received, response)''')
</code></pre>
<p>The above program when executed from the python shell will execute and create a database by the said name but whe... | 0 | 2016-07-21T14:25:12Z | 38,507,282 | <pre><code>import sqlite3
from os.path import expanduser
db_dir = expanduser("~")
db=sqlite3.connect(db_dir+'/new.db')
cursor=db.cursor()
cursor.execute('''CREATE TABLE hello(id INTEGER PRIMARY KEY,
Message_type, time_sent, time_received, response)''')
</code></pre>
<p>Now look in your home directory for <code>new.db<... | 0 | 2016-07-21T14:41:01Z | [
"python",
"sqlite"
] |
Copy Image to Local Folder Using Python Selenium | 38,506,978 | <p>How can we copy image from source to local folder using python selenium process.</p>
<p>Kindly help me.</p>
| 0 | 2016-07-21T14:28:25Z | 38,813,784 | <p>Here you go:</p>
<pre><code>import urllib
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.python.org/')
# get the image source
img = driver.find_element_by_xpath('//img[@class="python-logo"]')
src = img.get_attribute('src')
# download the image
urllib.urlretrieve(src, "python-... | 0 | 2016-08-07T11:45:15Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-ide",
"selenium-rc"
] |
Creating an array of pyqtSignal | 38,506,979 | <p>For a QThread I would like to create an array of pyqtSignal</p>
<pre><code>class MyThread(QtCore.QThread):
Trigger = []
for i in range(0,10):
Trigger.append(QtCore.pyqtSignal(int))
def __init__(self, Function):
self.Function = Function
super(MyThread, self).__init__(None)
de... | 0 | 2016-07-21T14:28:30Z | 38,533,205 | <p>You cannot create a list of pyqtSignal(s).</p>
<p>Unfortunately the way pyqt implement signals use a bit of python magics, and the <code>pyqtSignal</code> objects are actually "converted" into <code>pyqtBoundSignal</code> when a <code>QObject</code> subclass (technically a class that have <code>pyqtWrapperType</cod... | 0 | 2016-07-22T18:33:13Z | [
"python",
"arrays",
"qt5",
"pyqt5"
] |
Implementing keyPressEvent in QWidget | 38,507,011 | <p>I have a QDialog window that has a continue button. The continue button is the default button because whenever I press the enter key, the continue button is pressed. I discovered something strange: when I press the enter key three times, the continue button presses three times. However, when I press it a fourth time... | 0 | 2016-07-21T14:29:43Z | 38,514,893 | <p>You can do two ways and one is simply re implement keyPressevent with out any fancy work. Like this</p>
<pre><code>from PyQt4 import QtCore, QtGui
import sys
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.setGeometry(300, 300, 250, 150)
self.show(... | 1 | 2016-07-21T21:46:23Z | [
"python",
"event-handling",
"pyqt",
"keypress"
] |
How can i choose unique users in mongodb | 38,507,020 | <p>I have a database with events that have happened in a game. I am trying to retrieve information about how many unique players have started a level. I use this piece of code for that: </p>
<pre><code>heh = list(db.events.aggregate(
[
{ "$match": {"status": 'start'}},
{"$group": {"_id": "$eventName", ... | 0 | 2016-07-21T14:30:04Z | 38,508,339 | <p>Try this.. $addToSet adds the unique records and then count the records in array</p>
<pre><code>db.events.aggregate(
[
{ "$match": {"status": 'start'}},
{"$group": {"_id": "$eventName", "players": {"$addToSet": "$uid"}}},
{"$project": {"_id": 1, "Count": {"$size": "$players"}}}
])
</code></pre>
<p><a href... | 0 | 2016-07-21T15:28:12Z | [
"python",
"mongodb",
"python-2.7",
"pymongo"
] |
How to make a flight path projection if possible in Python? | 38,507,069 | <p>I have latitude, longitude and altitude data and want to make a plot such as in the image below using Python. The map can be left out, it is unnecessary.
<a href="http://i.stack.imgur.com/PkV0h.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/PkV0h.jpg" alt="enter image description here"></a></p>
<p>I have tr... | 1 | 2016-07-21T14:31:51Z | 38,636,531 | <p>It seems that the easiest way to do this is to use Google Earth. </p>
<p>Now there are two ways to tackle this. The first method is simple if you want a static picture. The second method allows animation of the flight path. Both are explained in this answer.</p>
<h3>Method 1</h3>
<p>Using the following Python cod... | 1 | 2016-07-28T12:34:35Z | [
"python",
"animation",
"3d",
"kml",
"altitude"
] |
Tkinter file dialog combining save and load dialogs | 38,507,251 | <p>I have an entry widget where the user can type in a file location, and underneath that a "save" button and a "load" button. Depending on which button is clicked, the file specified in the entry widget is either opened for writing, or for reading.</p>
<p>This all works fine and dandy.</p>
<p>Now I want to add a "br... | 0 | 2016-07-21T14:39:25Z | 38,525,367 | <p>Is this what you're looking for:</p>
<pre><code>from tkinter import *
from tkinter.filedialog import *
root = Tk()
root.title("Save and Load")
root.geometry("600x500-400+50")
def importFiles():
try:
filenames = askopenfilenames()
global file
for file in filenames:
fileList.i... | 0 | 2016-07-22T11:30:51Z | [
"python",
"tkinter"
] |
Trouble creating pandas pivot table with preexisting Excel file | 38,507,320 | <p>I am very new to the Pandas module, and am trying to create a pivot table from my Excel file. </p>
<p>Here's my code:</p>
<pre><code>excel = pd.ExcelFile(filename)
df = excel.parse
df1 = df[['Product Description', 'Supervisor']]
table1 = pd.pivot_table(df1, index = ['Supervisor'],
colum... | 0 | 2016-07-21T14:42:42Z | 38,508,393 | <p><code>parse</code> is a method (function attached to an object). So you need parentheses after the method name i.e. <code>df = excel.parse()</code>.</p>
<p>See <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.ExcelFile.parse.html" rel="nofollow">the docs</a> for details on how to supply argumen... | 0 | 2016-07-21T15:31:16Z | [
"python",
"pandas"
] |
Image to text python | 38,507,426 | <p>I am using python 3.x and using the following code to convert image into text:</p>
<pre><code>from PIL import Image
from pytesseract import image_to_string
image = Image.open('image.png', mode='r')
print(image_to_string(image))
</code></pre>
<p>I am getting the following error:</p>
<pre><code>Traceback (most rec... | 1 | 2016-07-21T14:47:13Z | 38,509,098 | <p>Your "current" directory is not where you think.</p>
<p>==> You may specify the full path to the image, for example:
image = Image.open(r'C:\Users\hp\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\image.png', mode='r') </p>
| -1 | 2016-07-21T16:04:09Z | [
"python",
"python-3.x",
"pytesser"
] |
Image to text python | 38,507,426 | <p>I am using python 3.x and using the following code to convert image into text:</p>
<pre><code>from PIL import Image
from pytesseract import image_to_string
image = Image.open('image.png', mode='r')
print(image_to_string(image))
</code></pre>
<p>I am getting the following error:</p>
<pre><code>Traceback (most rec... | 1 | 2016-07-21T14:47:13Z | 38,509,168 | <p>You have to have <code>tesseract</code> installed and accesible in your path.</p>
<p><a href="https://github.com/madmaze/pytesseract/blob/master/src/pytesseract.py#L74" rel="nofollow">According to source</a>, <code>pytesseract</code> is merely a wrapper for <code>subprocess.Popen</code> with tesseract binary as a b... | 0 | 2016-07-21T16:07:22Z | [
"python",
"python-3.x",
"pytesser"
] |
Check if list A contains a prefix of an item in list B | 38,507,451 | <p>I have two list, which we can call <code>A</code> and <code>B</code>. I need to check the items in list <code>A</code> and see if items in <code>B</code> starts with an item from <code>A</code> and then stop the check.</p>
<p>Example of content in A:</p>
<pre><code>https://some/path
http://another/path
http://ano... | 1 | 2016-07-21T14:48:20Z | 38,556,585 | <p>Your solution has the worst-case O(nm) time complexity, that is O(n^2) if n ~ m. You can easily reduce it to O(n log(n)) and even O(log(n)). Here is how. </p>
<p>Consider a list of words (your <code>comps</code> attrubute) and a target (your <code>b</code>) </p>
<pre><code>words = ['abdc', 'abd', 'acb', 'abcabc', ... | 1 | 2016-07-24T20:42:23Z | [
"python",
"python-3.x",
"for-loop"
] |
With Beautifulsoup, Extract Tags of Element Except Those specified | 38,507,514 | <p>I'm using Beutifulsoup 4 and Python 3.5+ to extract webdata. I have the following html, from which I am extracting:</p>
<pre><code><div class="the-one-i-want">
<p>
content
</p>
<p>
content
</p>
<p>
content
</p>
<p>
... | 2 | 2016-07-21T14:51:35Z | 38,510,730 | <p>Does this work for you? It should loop through the content adding the text you want while ignoring the div and script tags.</p>
<pre><code>for p in content:
if p.find('div') or p.find('script'):
continue
content_string += str(p)
</code></pre>
| -1 | 2016-07-21T17:30:19Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
With Beautifulsoup, Extract Tags of Element Except Those specified | 38,507,514 | <p>I'm using Beutifulsoup 4 and Python 3.5+ to extract webdata. I have the following html, from which I am extracting:</p>
<pre><code><div class="the-one-i-want">
<p>
content
</p>
<p>
content
</p>
<p>
content
</p>
<p>
... | 2 | 2016-07-21T14:51:35Z | 38,520,734 | <p>You can pass a list of tags that you want:</p>
<pre><code> content = soup.find('div', class_='the-one-i-want').find_all(["p", "ol", "whatever"])
</code></pre>
<p>If we run something similar on your question url looking for p and pre tags, you can see we get both:</p>
<pre><code> ...: for ele in soup.select_one(... | 1 | 2016-07-22T07:35:01Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
With Beautifulsoup, Extract Tags of Element Except Those specified | 38,507,514 | <p>I'm using Beutifulsoup 4 and Python 3.5+ to extract webdata. I have the following html, from which I am extracting:</p>
<pre><code><div class="the-one-i-want">
<p>
content
</p>
<p>
content
</p>
<p>
content
</p>
<p>
... | 2 | 2016-07-21T14:51:35Z | 38,521,123 | <p>You can do that quite easily using</p>
<pre><code>soup = Beautifulsoup(html.text, 'lxml')
desired-tags = {'div', 'ol'} # add what you need
content = filter(lambda x: x.name in desired-tags
soup.find('div', class_='the-one-i-want').children)
</code></pre>
<p>This will go through all <em>direct</em> children o... | 0 | 2016-07-22T07:55:31Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Split Python list into custom chunk size based on second list | 38,507,555 | <p>I am looking for a way to split a list into predefined slices: </p>
<pre><code>a = list(range(1, 1001)) # Added list()
b = [200, 500, 300]
</code></pre>
<p>List <code>a</code> should be sliced into <code>len(b)</code> sublists containing the first 200 elements of a, the following 500, and the last 300. It is safe... | 4 | 2016-07-21T14:53:05Z | 38,507,713 | <p>Make an iterator from the list (if it isn't one already) and get <code>n</code> times the <code>next</code> element from the iterator for each <code>n</code> in <code>b</code>.</p>
<pre><code>>>> a = range(1, 1001)
>>> b = [200, 500, 300]
>>> a_iter = iter(a)
>>> [[next(a_iter) ... | 5 | 2016-07-21T14:59:58Z | [
"python",
"list",
"slice"
] |
Split Python list into custom chunk size based on second list | 38,507,555 | <p>I am looking for a way to split a list into predefined slices: </p>
<pre><code>a = list(range(1, 1001)) # Added list()
b = [200, 500, 300]
</code></pre>
<p>List <code>a</code> should be sliced into <code>len(b)</code> sublists containing the first 200 elements of a, the following 500, and the last 300. It is safe... | 4 | 2016-07-21T14:53:05Z | 38,507,781 | <p>You could also use <a href="https://docs.python.org/2/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a> to consume an iterator of <code>a</code> in the predefined chunks:</p>
<pre><code>>>> from itertools import islice
>>> b = [200, 500, 300]
>>> a ... | 3 | 2016-07-21T15:02:54Z | [
"python",
"list",
"slice"
] |
Split Python list into custom chunk size based on second list | 38,507,555 | <p>I am looking for a way to split a list into predefined slices: </p>
<pre><code>a = list(range(1, 1001)) # Added list()
b = [200, 500, 300]
</code></pre>
<p>List <code>a</code> should be sliced into <code>len(b)</code> sublists containing the first 200 elements of a, the following 500, and the last 300. It is safe... | 4 | 2016-07-21T14:53:05Z | 38,507,786 | <p><code>itertools.islice</code>:</p>
<pre><code>from itertools import islice
a = range(1, 1001)
b = [200, 500, 300]
c = iter(a)
results = [list(islice(c, length)) for length in b]
</code></pre>
<p><code>islice</code> behaves like slice, except that slice takes sequence and returns sequence, whereas <code>islice</c... | 3 | 2016-07-21T15:03:15Z | [
"python",
"list",
"slice"
] |
How to download file using python when url doesn't change | 38,507,599 | <p>I want to download a file from a webpage. That webpage only has one .zip file (that's what I want to download), but when I click on the .zip file, it starts download but the url doesn't change (the url still remains of the form <a href="http://ldn2800:8080/id=2800" rel="nofollow">http://ldn2800:8080/id=2800</a>). Ho... | 1 | 2016-07-21T14:54:49Z | 38,509,911 | <p>Check the HTTP status code to make sure that no error happened. You may use the builtin method raise_for_status to do so: <a href="https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status" rel="nofollow">https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status</a></p... | 1 | 2016-07-21T16:43:18Z | [
"python",
"file",
"url",
"downloadfile"
] |
Summing elements in a sliding window - NumPy | 38,507,672 | <p>There is a numpy way to make a sum each three elements in the interval? For example:</p>
<pre><code>import numpy as np
mydata = np.array([4, 2, 3, 8, -6, 10])
</code></pre>
<p>I would like to get this result:</p>
<pre><code>np.array([9, 13, 5, 12])
</code></pre>
| 0 | 2016-07-21T14:57:49Z | 38,507,725 | <p>We can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html" rel="nofollow"><code>np.convolve</code></a> -</p>
<pre><code>np.convolve(mydata,np.ones(3,dtype=int),'valid')
</code></pre>
<p>The basic idea with <a href="https://en.wikipedia.org/wiki/Convolution" rel="nofollow"><code>co... | 4 | 2016-07-21T15:00:35Z | [
"python",
"numpy"
] |
Python argparse - Mutually exclusive group with default if no argument is given | 38,507,675 | <p>I'm writing a Python script to process a machine-readable file and output a human-readable report on the data contained within.<br>
I would like to give the option of outputting the data to <code>stdout (-s)</code> (by default) or to a txt <code>(-t)</code> or csv <code>(-c)</code> file. I would like to have a switc... | 2 | 2016-07-21T14:57:56Z | 38,508,118 | <p>You could have each of your actions update the same variable, supplying stdout as the default value for that variable.</p>
<p>Consider this program:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument(
'-s', '--stdout', action='sto... | 5 | 2016-07-21T15:18:06Z | [
"python",
"python-3.x",
"argparse"
] |
Python argparse - Mutually exclusive group with default if no argument is given | 38,507,675 | <p>I'm writing a Python script to process a machine-readable file and output a human-readable report on the data contained within.<br>
I would like to give the option of outputting the data to <code>stdout (-s)</code> (by default) or to a txt <code>(-t)</code> or csv <code>(-c)</code> file. I would like to have a switc... | 2 | 2016-07-21T14:57:56Z | 38,508,442 | <p>You can "cheat" with sys.argv : </p>
<pre><code>import sys
def main():
if len(sys.argv) == 2 and sys.argv[1] not in ['-s', '-c', '-t', '-h']:
filename = sys.argv[1]
print "mode : stdout", filename
else:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusiv... | 0 | 2016-07-21T15:33:11Z | [
"python",
"python-3.x",
"argparse"
] |
How to unpack a binary file buffer into two variables? | 38,507,704 | <p>I have a binary file that contains 4-byte binary values that represent a set of two <code>short int</code> each. I know that I can unpack a single 4-byte binary value into two short integers like this:</p>
<pre><code>from struct import unpack
fval = b'\xba\x1e\x99\x01' #actualy read from some file
qualdip, azi = u... | 1 | 2016-07-21T14:59:19Z | 38,508,181 | <p>I don't know a way to unpack the values directly into two lists, but you can unpack the entire file into a tuple and then slice it in two:</p>
<pre><code>fval = b'\xba\x1e\x99\x01' * 3
unpacked= unpack('3h3h', fval)
qualdip = unpacked[0::2]
azi = unpacked[1::2]
</code></pre>
<p>Alternatively, use <a href="https://... | 1 | 2016-07-21T15:21:18Z | [
"python",
"unpack"
] |
How to unpack a binary file buffer into two variables? | 38,507,704 | <p>I have a binary file that contains 4-byte binary values that represent a set of two <code>short int</code> each. I know that I can unpack a single 4-byte binary value into two short integers like this:</p>
<pre><code>from struct import unpack
fval = b'\xba\x1e\x99\x01' #actualy read from some file
qualdip, azi = u... | 1 | 2016-07-21T14:59:19Z | 38,509,977 | <p>I think this might be a faster way to do it:</p>
<pre><code>import os
import struct
def pairwise(iterable):
"s -> (s0,s1), (s2,s3), (s4, s5), ..."
a = iter(iterable)
return zip(a, a)
bfile = 'bfile.bin'
filesize = os.stat(bfile).st_size
numvals = filesize // 2
with open(bfile, 'rb') as bf:
fmt... | 0 | 2016-07-21T16:47:00Z | [
"python",
"unpack"
] |
Cython __pyx_r may be used uninitialized in this function | 38,507,806 | <p>I am trying to utilize cython to provide a wrapper for my C++ utilities. One such function I am trying to make accessible is an accessor that returns an enum based on file type.</p>
<p>Here is how I re-define the function in cython:</p>
<pre><code>cdef extern from "reader.h" namespace "magic_number":
enum mcr_m... | 1 | 2016-07-21T15:03:52Z | 38,523,517 | <p>Try checking self.thisptr for non-NULL value:</p>
<pre><code>if <void*>self.thisptr != NULL:
return self.thisptr.magic_number()
</code></pre>
| 0 | 2016-07-22T09:58:07Z | [
"python",
"c++",
"cython"
] |
ImportError: No module named 'users' | 38,507,856 | <p>When I run <code>python /manage.py runserver</code> , it generates the following error. </p>
<pre><code>ImportError: No module named 'users'
</code></pre>
<p>I was thinking about this error, maybe I had a mistake about app setting.</p>
<p><strong>$tree</strong></p>
<pre><code>.
âââ LICENSE
âââ README... | 0 | 2016-07-21T15:06:03Z | 38,507,938 | <p>You get the import error because the <code>users</code> directory is not on the Python path. The easiest solution is to move the <code>users</code> directory into the project <code>wef</code> directory (the one that contains <code>manage.py</code>). </p>
<pre><code>âââ wef
âââ db.sqlite3
âââ... | 3 | 2016-07-21T15:09:45Z | [
"python",
"django"
] |
Capturing output of scp from python | 38,507,920 | <p>I have a django server, and I have to upload some data through scp. I have this view:</p>
<pre><code>pathFile = '/home/user1/foo.json'
user = 'user1scp'
server = 'someserver.com'
pathServer = '/var/www/foo.json'
os.system("scp %s %s@%s:%s" % (pathFile, user, server, pathServer))
</code></pre>
<p>On the console wi... | 0 | 2016-07-21T15:08:53Z | 38,508,039 | <p>This doesn't directly answer your question, but I won't do the raw <code>scp</code> command in python because the output is hard to parse even if you have it. You should consider using tools like <a href="http://docs.fabfile.org/en/1.11/index.html" rel="nofollow"><code>fabric</code></a> to handle this. It's pythonic... | 1 | 2016-07-21T15:14:18Z | [
"python",
"django",
"scp"
] |
Save a file generated by app running on docker to a given path in the host machine | 38,507,929 | <p>I have a python app running on a docker container and it generates a pdf file. I want to store the generated pdf file in a given path in the host machine.</p>
<p>I am not sure on how can this be achieved. Any ideas? </p>
| 2 | 2016-07-21T15:09:21Z | 38,508,158 | <p>Use volumes to mount directory in a container to host director:</p>
<pre><code>docker run -v /MY/HOST_DIR:/MY/CONTAINER_DIR
</code></pre>
<p>Your pdf file will be stored in /MY/HOST_DIR on host.</p>
| 0 | 2016-07-21T15:20:07Z | [
"python",
"docker",
"docker-compose"
] |
Save a file generated by app running on docker to a given path in the host machine | 38,507,929 | <p>I have a python app running on a docker container and it generates a pdf file. I want to store the generated pdf file in a given path in the host machine.</p>
<p>I am not sure on how can this be achieved. Any ideas? </p>
| 2 | 2016-07-21T15:09:21Z | 38,508,482 | <p>Mount a volume in your container mapped to the desired path in your host</p>
<pre><code>docker run -d -v /host/path:/python_app/output your_docker_image
</code></pre>
<p>Where <code>/python_app/output</code> is the path inside the container where your app is writing the pdf file.</p>
<p>Note that <code>/host/path... | 2 | 2016-07-21T15:34:49Z | [
"python",
"docker",
"docker-compose"
] |
Transform every two fields of rows into columns containing two rows | 38,507,958 | <p>I would like to transform every two fields of rows into columns containing two rows. And loop this transformation for each row</p>
<p>This is the input:</p>
<pre><code>id refpop001 altpop001 refpop002 altpop002 refpop003 altpop003
id1 6 274 2 93 5 95
id2 202 0 220 0 73 0
id3 166 159 0 173 ... | -3 | 2016-07-21T15:11:12Z | 38,508,191 | <p>You can loop through the input and then split it up, maybe something along the lines of this</p>
<pre><code>int i = 0
for row in input:
row_array = row.split()
i = i+=1
ref = row_array[0] + " " + row_array[2] + " " + row_array[4]]
alt = row_array[1] + " " + row_array[3] + " " + row_array[5]
print "id" +... | 0 | 2016-07-21T15:21:54Z | [
"python",
"loops",
"rows"
] |
Transform every two fields of rows into columns containing two rows | 38,507,958 | <p>I would like to transform every two fields of rows into columns containing two rows. And loop this transformation for each row</p>
<p>This is the input:</p>
<pre><code>id refpop001 altpop001 refpop002 altpop002 refpop003 altpop003
id1 6 274 2 93 5 95
id2 202 0 220 0 73 0
id3 166 159 0 173 ... | -3 | 2016-07-21T15:11:12Z | 38,508,197 | <p>Given you are transforming tab delimited plain text which is in file and your data size is not changing, straightforward approach is:</p>
<pre><code>lines=open('file_or_stream_name.txt','r').readlines();
newLines=[]
newLines.append('\t'.join('id','pop001','pop002','pop003')) #header line
for line in lines[1:]:
... | 0 | 2016-07-21T15:22:11Z | [
"python",
"loops",
"rows"
] |
Python. Send Uploaded File To Remote Server | 38,508,111 | <p>In My Flask App, i want to upload a file to a remote server.</p>
<p>i tried this code but i get an error</p>
<pre><code>import subprocess
import os
c_dir = os.path.dirname(os.path.abspath(__file__))
myfile = open(c_dir + '\\cape-kid.png')
p = subprocess.Popen(["scp", myfile, destination])
sts = os.waitpid(p.pi... | 1 | 2016-07-21T15:17:46Z | 38,539,097 | <p>With <code>open()</code> you open an file to read or write on it. What you want is to concatinate the string and use this as parameter for scp. Maybe the file you want to copy also doesn't exist - have you tried printing the path you constructed and checking it manually?
And have you defined <code>destination</code>... | 1 | 2016-07-23T06:58:51Z | [
"python"
] |
Replace values in a large list of arrays (performance) | 38,508,116 | <p>I have a performance problem with replacing values of a list of arrays using a dictionary. </p>
<p>Let's say this is my dictionary:</p>
<pre><code># Create a sample dictionary
keys = [1, 2, 3, 4]
values = [5, 6, 7, 8]
dictionary = dict(zip(keys, values))
</code></pre>
<p>And this is my list of arrays:</p>
<pre>... | 1 | 2016-07-21T15:17:59Z | 38,509,123 | <p>This will do the trick efficiently, using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package. It can be further simplified if all values in 'listvalues' are guaranteed to be present in 'keys'; but ill leave that as an exercise to the reader.</p>
<pre><cod... | 2 | 2016-07-21T16:05:07Z | [
"python",
"arrays",
"performance",
"numpy",
"for-loop"
] |
Django: how to cache a function | 38,508,240 | <p>I have a web application that runs python in the back-end. When my page loads, a django function is called which runs a SQL query and that query takes about 15-20 seconds to run and return the response. And that happens every time the page loads and it would be very annoying for the user to wait 15-20 secs every tim... | 1 | 2016-07-21T15:24:37Z | 38,508,402 | <p>You can the cache the result of the view that runs that query:</p>
<pre><code>from django.views.decorators.cache import cache_page
@cache_page(600) # 10 minutes
def populateDropdown(request):
...
</code></pre>
<p>Or cache the expensive functions in the view which in your case is almost synonymous to caching t... | 2 | 2016-07-21T15:31:32Z | [
"python",
"django",
"caching"
] |
How to get the max/min value in Pandas DataFrame when nan value in it | 38,508,294 | <p>Since one column of my pandas dataframe has <code>nan</code> value, so when I want to get the max value of that column, it just return error. </p>
<pre><code>>>> df.iloc[:, 1].max()
'error:512'
</code></pre>
<p>How can I skip that <code>nan</code> value and get the max value of that column?</p>
| 2 | 2016-07-21T15:26:32Z | 38,508,323 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dropna.html" rel="nofollow">Series.dropna</a>.</p>
<pre><code>res = df.iloc[:, 1].dropna().max()
</code></pre>
| 4 | 2016-07-21T15:27:46Z | [
"python",
"pandas"
] |
How to get the max/min value in Pandas DataFrame when nan value in it | 38,508,294 | <p>Since one column of my pandas dataframe has <code>nan</code> value, so when I want to get the max value of that column, it just return error. </p>
<pre><code>>>> df.iloc[:, 1].max()
'error:512'
</code></pre>
<p>How can I skip that <code>nan</code> value and get the max value of that column?</p>
| 2 | 2016-07-21T15:26:32Z | 38,508,465 | <p>You can use <code>NumPy</code>'s help with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmax.html" rel="nofollow"><code>np.nanmax</code></a>, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmin.html" rel="nofollow"><code>np.nanmin</code></a> :</p>
<pre><code>In [28]: df... | 3 | 2016-07-21T15:34:03Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.