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
Longest increasing subsequence in O(n) time?
39,952,186
<p>I'm studying this algorithm for the first time. CLRS (15-4.6) asks to write an algorithm to run in O(n lg n) time. The algorithm I came up with seems to run in O(n). I think I must be misunderstanding something, because even wikipedia says it should take O(n lg n) time. (<a href="https://en.wikipedia.org/wiki/Lo...
0
2016-10-10T06:09:00Z
39,952,405
<p>I'll leave some of the debugging to you, but the following does not produce the maximum length substring using your algorithm. I simply added a few numbers to the example you had, so it should have produced <code>[0, 4, 6, 9, 11, 15]</code> again, but didn't:</p> <pre><code>&gt;&gt;&gt; print(subseq([0, 12,12,15,14...
0
2016-10-10T06:29:15Z
[ "python", "algorithm", "longest-substring" ]
python-rope/ropevim doesn't work properly
39,952,334
<p>I've already installed these, pip list:</p> <pre><code>rope (0.10.3) ropemode (0.3) ropevim (0.7.0) </code></pre> <p>All the vim plugins I have:</p> <pre><code>Plugin 'gmarik/vundle' Plugin 'scrooloose/nerdtree' Plugin 'jistr/vim-nerdtree-tabs' Plugin 'altercation/vim-colors-solarized' Plugin 'kien/ctrlp.vim' Plu...
0
2016-10-10T06:22:51Z
39,968,142
<p>What does <code>:map</code> shows? What does <code>:imap</code> shows for <code>Ctrl-]</code>? I have this in my <code>~/.vimrc</code>:</p> <pre><code>let ropevim_vim_completion=1 let ropevim_extended_complete=1 let ropevim_codeassist_maxfixes=1 let ropevim_goto_def_newwin="tabnew" let ropevim_autoimport_modules = ...
0
2016-10-10T23:14:27Z
[ "python", "vim", "rope" ]
How to get the outuput in the correct format
39,952,498
<p><img src="http://i.stack.imgur.com/ERBAv.png" alt="enter image description here"> </p> <pre><code>def read_ndfa(file : open) -&gt; {str:{str:{str}}}: pass </code></pre> <p>file =</p> <pre><code>start;0;start;1;start;0;near near;1;end end </code></pre> <p>correct output = <code>{'end': {}, 'start': {'1': {...
-4
2016-10-10T06:37:00Z
39,952,830
<p>You can take a look at this :</p> <pre><code>import csv f = open('data.csv', 'r') r = csv.reader(f, delimiter=';') out = {} for row in r: out[row[0]] = {} # Set the top level key # Loop on all odd elements for pos in range(1, len(row), 2): if row[pos] in out[row[0]]: # Add the ...
0
2016-10-10T07:04:18Z
[ "python" ]
Wrong math result with calling C extension in Python
39,952,565
<p>I am calling the <code>pow()</code> function of C's math library. My installation is Python3.5 on Windows 10 but I tried the same program in Python2.7 with same result. The return from the function is not as expected. Not sure what's happening. The code is given below. The result I get is 1.0.</p> <pre><code>from c...
0
2016-10-10T06:41:59Z
39,952,623
<p>There is a type mismatch. Use c_double for power as well. Like this. It should work.</p> <p>libc.pow.argtypes = [c_double, c_double]</p>
1
2016-10-10T06:46:40Z
[ "python", "python-c-extension" ]
Wrong math result with calling C extension in Python
39,952,565
<p>I am calling the <code>pow()</code> function of C's math library. My installation is Python3.5 on Windows 10 but I tried the same program in Python2.7 with same result. The return from the function is not as expected. Not sure what's happening. The code is given below. The result I get is 1.0.</p> <pre><code>from c...
0
2016-10-10T06:41:59Z
39,952,655
<p>pow in C libray takes double, double as input arguments. That's why.</p> <pre><code>from ctypes import * libc = cdll.msvcrt libc.pow.argtypes = [c_double, c_double] libc.pow.restype = c_double libc.pow(2.3, 2.0) </code></pre>
0
2016-10-10T06:49:16Z
[ "python", "python-c-extension" ]
Wrong math result with calling C extension in Python
39,952,565
<p>I am calling the <code>pow()</code> function of C's math library. My installation is Python3.5 on Windows 10 but I tried the same program in Python2.7 with same result. The return from the function is not as expected. Not sure what's happening. The code is given below. The result I get is 1.0.</p> <pre><code>from c...
0
2016-10-10T06:41:59Z
39,952,662
<p>Double check your types, I'm pretty sure the prototype for pow is </p> <blockquote> <p>double pow(double a, double b);</p> </blockquote> <p>So changes this line </p> <blockquote> <p>libc.pow.argtypes = [c_double, c_int]</p> </blockquote> <p>To </p> <blockquote> <p>libc.pow.argtypes = [c_double, c_double]<...
1
2016-10-10T06:49:55Z
[ "python", "python-c-extension" ]
tf.image.decode_jpeg raise InvalidArgumentError
39,952,592
<p>I am testing tf.image.decode_jpeg and I got InvalidArgumentError. I am using Python3, in order to let it act like Python2, I added encoding="latin-1"..</p> <p>My Question: How can I fix this problem? </p> <pre><code>import tensorflow as tf with open("/root/PycharmProjects/mscoco/train2014/COCO_train2014_0000002...
0
2016-10-10T06:44:14Z
39,955,190
<p>The input to <code>decode_jpg</code> is a string Tensor with the file contents (see the <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/image.html#decode_jpeg" rel="nofollow">API</a> here), not the result of python's <code>read()</code>.</p> <p>So, you should do something like this:</p> <pre><co...
1
2016-10-10T09:27:11Z
[ "python", "tensorflow" ]
Compare two list of dictionaries and create a new list with all keys and values in python
39,952,634
<pre><code>a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}] b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}] </code></pre> <p>Here I have two list of dict. I want to compare these and generate a new list like this:</p> <pre><code>newlist = [{'a':{'a':1,'b':0}}, {'b':{'a':1,'b':1}}, {'c':{'a':0,'b':0}}] </code></pre>
1
2016-10-10T06:47:52Z
39,958,162
<pre><code>A_list = [{'a':{'A':1}}, {'b':{}}] B_list = [{'b': {'B': 1}}, {'a': {'A': 0}}] list_with_all_keys = [{'a':{}}, {'b':{}}, {'c':{}}] new_lod = [{k:{'A':(1 if k in A_list and 'A' in A_list[k] and A_list[k]['A'] is 1 else 0), 'B':(1 if k in B_list and 'B' in B_list[k] and B_list[k]['B'] is 1 else...
0
2016-10-10T12:19:48Z
[ "python", "list", "dictionary" ]
Compare two list of dictionaries and create a new list with all keys and values in python
39,952,634
<pre><code>a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}] b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}] </code></pre> <p>Here I have two list of dict. I want to compare these and generate a new list like this:</p> <pre><code>newlist = [{'a':{'a':1,'b':0}}, {'b':{'a':1,'b':1}}, {'c':{'a':0,'b':0}}] </code></pre>
1
2016-10-10T06:47:52Z
39,959,397
<p>A more readable way of doing it would be </p> <pre><code>a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}] b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}] result = {} for c in a + b: for key,value in c.items(): result[key] = dict() result[key]['a'] = value.get('a', 0) result[key]['b'] = value.get(...
0
2016-10-10T13:25:14Z
[ "python", "list", "dictionary" ]
Should I put the main in a class in Python?
39,952,675
<p>So far I've running the <code>main()</code> module in a script way (different .py file and not in a class or whatever) and then call the different instances from my other modules.</p> <p>Is this right or should I make a class just for the <code>main</code> too?</p> <p>Regards and thank.</p>
0
2016-10-10T06:51:31Z
39,952,785
<p>You're overthinking it. Don't shoe-gaze over stuff that doesn't have a clear purpose. If you find a good reason to put a "main" function in a class, go ahead. Otherwise just save yourself the trouble.</p> <p>To answer your question directly, I've never seen the "<code>main</code>" method defined in a <code>class</c...
2
2016-10-10T07:00:22Z
[ "python" ]
Should I put the main in a class in Python?
39,952,675
<p>So far I've running the <code>main()</code> module in a script way (different .py file and not in a class or whatever) and then call the different instances from my other modules.</p> <p>Is this right or should I make a class just for the <code>main</code> too?</p> <p>Regards and thank.</p>
0
2016-10-10T06:51:31Z
39,952,942
<p>If you don't know whether you need a new class then you should not write it.</p>
0
2016-10-10T07:11:36Z
[ "python" ]
HDF5 min_itemsize error: ValueError: Trying to store a string with len [##] in [y] column but this column has a limit of [##]!
39,952,715
<p>I am getting the following error after using <code>pandas.HDFStore().append()</code></p> <pre><code>ValueError: Trying to store a string with len [150] in [values_block_0] column but this column has a limit of [127]! Consider using min_itemsize to preset the sizes on these columns </code></pre> <p>I am creating ...
0
2016-10-10T06:54:53Z
39,954,996
<p><strong>UPDATE:</strong></p> <p>you have misspelled <code>data_columns</code> parameter: <code>data_column</code> - it should be <code>data_columns</code>. As a result you didn't have any indexed columns in your HDF Store and HDF store added <code>values_block_X</code>:</p> <pre><code>In [70]: store = pd.HDFStore(...
1
2016-10-10T09:17:15Z
[ "python", "pandas", "hdf5", "pytables", "hdf5storage" ]
Python Pandas - Group index by minute and compute average
39,952,753
<p>So I have a pandas dataframe called 'df' and I want to remove the seconds and just have the index in YYYY-MM-DD HH:MM format. But also the minutes are then grouped and the average for that minute is displayed.</p> <p>So I want to turn this dataFrame</p> <pre><code> value 2015-05-03 00:00:00 ...
1
2016-10-10T06:58:05Z
39,952,846
<p>You need first convert index to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow"><code>DatetimeIndex</code></a>:</p> <pre><code>df.index = pd.DatetimeIndex(df.index) #another solution #df.index = pd.to_datetime(df.index) print (df['value'].resample('1Min').me...
1
2016-10-10T07:05:21Z
[ "python", "pandas", "group", "average", "minute" ]
How to run functions in random order?
39,952,782
<p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p> <p>Input:</p> <pre><code>def a(): print('a') def b(): print('b') def c(): print('c') shuffle([a,b,c]) </code></pre> <p>This is output what I want:</p> <pre><code>a b c </code></pre> <p>...
1
2016-10-10T07:00:10Z
39,952,856
<p><a href="https://docs.python.org/3/library/random.html#random.shuffle" rel="nofollow"><code>random.shuffle</code></a> is an in-place operation. So you need to keep the list separately and shuffle it.</p> <pre><code>functions = [a, b, c] shuffle(functions) </code></pre> <p>Now, the functions are shuffled and you ju...
5
2016-10-10T07:05:54Z
[ "python", "function", "python-3.x", "random" ]
How to run functions in random order?
39,952,782
<p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p> <p>Input:</p> <pre><code>def a(): print('a') def b(): print('b') def c(): print('c') shuffle([a,b,c]) </code></pre> <p>This is output what I want:</p> <pre><code>a b c </code></pre> <p>...
1
2016-10-10T07:00:10Z
39,952,990
<p>Or make a list and take random: </p> <pre><code>import random def a(): print('a') def b(): print('b') def c(): print('c') my_list = [a, b, c] random.choice(my_list)() </code></pre>
1
2016-10-10T07:14:22Z
[ "python", "function", "python-3.x", "random" ]
How to run functions in random order?
39,952,782
<p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p> <p>Input:</p> <pre><code>def a(): print('a') def b(): print('b') def c(): print('c') shuffle([a,b,c]) </code></pre> <p>This is output what I want:</p> <pre><code>a b c </code></pre> <p>...
1
2016-10-10T07:00:10Z
39,952,997
<pre><code>import random def a(): print('a') def b(): print('b') def c(): print('c') # map the inputs to the function blocks options = {0 : a, 1 : b, 2 : c, } num = random.randint(0, 2) options[num]() </code></pre> <p>That's a simple way to randomly choose the functions</p>
-1
2016-10-10T07:14:54Z
[ "python", "function", "python-3.x", "random" ]
How to run functions in random order?
39,952,782
<p>I want to run functions with random order. It looks like "shuffle" function which shuffle a variables list.</p> <p>Input:</p> <pre><code>def a(): print('a') def b(): print('b') def c(): print('c') shuffle([a,b,c]) </code></pre> <p>This is output what I want:</p> <pre><code>a b c </code></pre> <p>...
1
2016-10-10T07:00:10Z
39,953,439
<p>Here is how I would do. Basically what <strong>thefourtheye</strong> has suggested. <a href="https://repl.it/DsMk/0" rel="nofollow">Run this Code</a></p> <pre><code>from random import shuffle def a(): print('a') def b(): print('b') def c(): print('c') def main(): lis = [a,b,c] shuffle(lis) ...
1
2016-10-10T07:43:48Z
[ "python", "function", "python-3.x", "random" ]
Python 3.5 async/await with real code example
39,952,799
<p>I've read tons of articles and tutorial about Python's 3.5 async/await thing. I have to say I'm pretty confused because some use get_event_loop() and run_until_complete() some use ensure_future() some use asyncio.wait() and some use call_soon().</p> <p>It seems like I have a lot choices but I have no idea if they a...
0
2016-10-10T07:01:42Z
39,953,219
<p>If 3rd party library is not compatible with <code>async/await</code> then obviously you can't use it easily. There are 2 cases:</p> <p>1) Let's say that the function in the library is asynchronous and it gives you a callback, e.g.</p> <pre><code>def fn(..., clb): ... </code></pre> <p>So you can do:</p> <pre>...
1
2016-10-10T07:28:41Z
[ "python", "asynchronous", "async-await", "python-3.5" ]
How to know the folder size in a zipfile (Python)
39,952,867
<p>I know that you can get the size in bytes of a file in a ZIP file using the .file_size method But is there any what I can get the size of a folder instead?</p> <p>Ex: </p> <pre><code>import zipfile, os os.chdir('C:\\') zp= zipfile.ZipFile('example.zip') spamInfo = zp.getinfo('spam.txt') #Here, Instead of ...
1
2016-10-10T07:06:21Z
39,953,116
<p>Just put below code into your program.</p> <pre><code>size = sum([zinfo.file_size for zinfo in zp.filelist]) zip_kb = float(size)/1000 #kB </code></pre> <p>Hopefully, It will work for you. :)</p>
3
2016-10-10T07:22:45Z
[ "python", "size", "folder", "zipfile" ]
Win32: Python to get all Column Names from Excel
39,952,931
<p>How can I get all defined names from a Excel Worksheet using the COM-interface, i.e. Win32 API in Python?</p> <p>I want to obtain some sort of a dict, e.g. in the example below it would be:</p> <pre><code>cols['Stamm_ISIN'] = 2 </code></pre> <p>so that I could access the column later using it's ID 2 to set some v...
0
2016-10-10T07:10:57Z
39,956,132
<p>The following script shows you how to display all of the column headings for a given WorkSheet. First it calculates the number of columns used and then enumerates each column. Next it displays all of the named ranges for a given WorkBook, for each it stores the instance into the <code>cols</code> dictionary. This ca...
1
2016-10-10T10:23:42Z
[ "python", "excel", "winapi", "com" ]
How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key?
39,952,982
<p>In Python, Suppose there is a dictionary named fruits:</p> <pre><code>fruits={ "apple":5, "orange":7, "mango":9 } </code></pre> <p>On reading the dictionary items, it should create 3 lists having same name as dictionary keys viz. apple, orange and mango and size of theses lists should be 5, 7 and 9 respectively. T...
-2
2016-10-10T07:14:08Z
39,953,203
<pre><code>d = { "apple":5, "orange":7, "mango":9 } for k in d: temp = [] for k2 in range(0,d[k]): print "enter the next "+str(k)+":" temp.append(raw_input()) exec(str(k)+"="+str(temp)) </code></pre> <p>but don't. <a href="http://stackoverflow.com/questions/8818318/how-to-eval-a-string-cont...
0
2016-10-10T07:27:24Z
[ "python", "list", "python-3.x", "dictionary" ]
How do I create lists out of dictionary, having same name as dictionary keys and same size as value of that key?
39,952,982
<p>In Python, Suppose there is a dictionary named fruits:</p> <pre><code>fruits={ "apple":5, "orange":7, "mango":9 } </code></pre> <p>On reading the dictionary items, it should create 3 lists having same name as dictionary keys viz. apple, orange and mango and size of theses lists should be 5, 7 and 9 respectively. T...
-2
2016-10-10T07:14:08Z
39,954,428
<p>Got a solution for this-</p> <pre><code>fruit = { "apple": 5, "banana" : 10 } for key in fruit.items(): key = list(fruit.get(key)*[None]) </code></pre> <p>This will serve my need.</p>
3
2016-10-10T08:43:31Z
[ "python", "list", "python-3.x", "dictionary" ]
Python Pandas: select column with the number of unique values greater than 10
39,953,068
<p>In R, we can use <code>sapply</code> to extract columns with the number of unique values greater than 10 by:</p> <pre><code>X[, sapply(X, function(x) length(unique(x))) &gt;=10] </code></pre> <p>How can we do the same thing in Python Pandas?</p> <p>Also, how can we choose columns with missing proportion less t...
1
2016-10-10T07:19:27Z
39,953,117
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nunique.html" rel="nofollow"><code>nunique</code></a> with <code>apply</code>, because it works only with <code>Series</code>:</p> <pre><code>print (df.ix[:, df.apply(lambda x: x.nunique()) &gt;= 10]) </code></pre> <p>and seco...
3
2016-10-10T07:22:50Z
[ "python", "pandas", "sapply" ]
split long string inside one list to small lists
39,953,075
<p>How do you split this long string of one list to small multi-lists as show on the output ? (I have file has 100 lines)</p> <pre><code>Num=['S', 'I', 'R', 'T', 'S', 'A', 'V', 'P', 'S', 'P', 'C', 'G', 'K', 'Y', 'Y', 'T', 'L', 'N', 'G', 'S', 'K', '\n', ',', 'S', 'T', 'P', 'C', 'T', 'T', 'I', 'N', 'K', 'V', 'K', 'A', ...
-1
2016-10-10T07:20:07Z
39,953,135
<p>First <code>join</code> the elements, <code>strip()</code> leading-trailing whitespace characters, <code>split</code> on a new line <code>\n</code> and comma <code>,</code> and then map them to a list again.</p> <p>In short:</p> <pre><code>l1, l2 = map(list, "".join(Num).strip().split('\n,')) </code></pre> <p>Now...
1
2016-10-10T07:24:01Z
[ "python", "string", "python-2.7", "python-3.x" ]
Clustering words on the basis of similarity in meaning which is provided in trainings set
39,953,134
<p>Which machine learning algorithm would serve to starting point for the below problem ?</p> <p>I have a list of words which is similar to the below.</p> <p><strong>curate</strong> : a member of the clergy in certain churches (such as the Anglican church) who assists the priest in charge of a church or a group of c...
0
2016-10-10T07:23:52Z
39,963,454
<p>This is a problem of text similarity, where you want to match the similarity of a given block of text to a known set. For example, "nurse: a person working healthcare...". If the similarity is above a certain threshold, then there is a match, otherwise it is considered to not be a match.</p> <p>To start, you will n...
0
2016-10-10T17:14:44Z
[ "python", "python-3.x", "machine-learning", "cluster-analysis", "word" ]
Can variables have synonyms?
39,953,156
<p>I have very big string, which give me access to my dictionary in another dictionary in another class.</p> <pre><code>self.app_data.ip_table[self.app_data.cfg.MY_IP]['tasks'] </code></pre> <p>If I used this dict in sequence of strings, I can write something like this (I think so):</p> <pre><code>with self.app_data...
-1
2016-10-10T07:25:20Z
39,953,428
<p>Use properties maybe?</p> <pre><code>class C: def __init__(self, ...): self.app_data = get_app_data() @property def var(self): return self.app_data.very['long'].path.here @var.setter def var(self, value): self.app_data.very['long'].path.here = value c = C() print c.var...
1
2016-10-10T07:42:51Z
[ "python", "python-2.7", "variables", "dictionary" ]
How to call codes of a package directly without installing and importing module?
39,953,159
<p>Sorry I am a newbie. I have a python package created with one of my colleagues which is not available currently. Now I have to make small changes to module. I don't want to install the module. I want to just call the codes directly. Is there any way to copy files in the same folder and call it directly? </p> <p>How...
-4
2016-10-10T07:25:30Z
39,972,235
<p>If you want to use anything defined within another file, you will have to <code>import</code> it.</p> <p>To be able to <code>import</code> a module, you do <em>not</em> have to install it into the system-wide package directory. Python will look up modules you're trying to <code>import</code> on the <code>PYTHONPATH...
1
2016-10-11T07:23:06Z
[ "python", "python-3.x" ]
How can I alter the index of loop for a list
39,953,254
<p>I've a list and I want to display the content with index by manually changing the value of index. I've tried to do it in two ways but it is not working.</p> <p>way 1:</p> <pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python'] for i,item in enumerate(x): print (i,...
-1
2016-10-10T07:30:18Z
39,953,496
<p>The issue here is that both <code>enumerate()</code> and <code>xrange()</code> generate a series of values that is unaffected by external changes to <code>i</code>, which is an unconnected variable. Using @efferalgans's suggestion the best way might be to call the <code>next()</code> function twice, but this will me...
1
2016-10-10T07:46:56Z
[ "python", "python-2.7", "nltk" ]
How can I alter the index of loop for a list
39,953,254
<p>I've a list and I want to display the content with index by manually changing the value of index. I've tried to do it in two ways but it is not working.</p> <p>way 1:</p> <pre><code>x=['hello','how','are','you','hope','you','are','fine','I','am','doing','work','in','python'] for i,item in enumerate(x): print (i,...
-1
2016-10-10T07:30:18Z
39,954,192
<p>Just use a while loop. It's the simplest, clearest and most flexible solution:</p> <pre><code>i = 0 while i &lt; len(x): print x[i] if x[i] == 'are': i+=1 i += 1 </code></pre> <p>As you can see, looping over a string is simple and you are completely free to change the index on the fly -- <code>...
1
2016-10-10T08:29:14Z
[ "python", "python-2.7", "nltk" ]
Get video dimension in python-opencv
39,953,263
<p>I can get size of image, like this:</p> <pre><code>import cv2 img = cv2.imread('my_image.jpg',0) height, width = img.shape[:2] </code></pre> <p>How about video?</p>
0
2016-10-10T07:30:52Z
39,953,739
<p>It gives <code>width</code> and <code>height</code> of file or camera as float (so you may have to convert to integer)</p> <p>But it always gives me <code>0.0 FPS</code>.</p> <pre><code>import cv2 vcap = cv2.VideoCapture('video.avi') # 0=camera if vcap.isOpened(): # get vcap property width = vcap.get(c...
1
2016-10-10T08:01:14Z
[ "python", "opencv", "video" ]
I can't remove file, created by memmap
39,953,501
<p>I can't remove file created <code>numpy.memmap</code> funtion</p> <pre><code>class MyClass def __init__(self): self.fp = np.memmap(filename, dtype='float32', mode='w+', shape=flushed_chunk_shape) ... def __del__(self): del self.fp os.remove(filename) </code></pre> <p>When I run <code>del myclass...
0
2016-10-10T07:47:10Z
39,954,126
<p>Numpy memmapped files are not unmapped until garbage collected, and <code>del self.fp</code> does not ensure garbage collection. A file which is not unmapped yet cannot be deleted.</p> <p>The numpy.memmap docs say "Deletion flushes memory changes to disk". It does not say it unmaps, because it doesn't unmap.</p> ...
0
2016-10-10T08:26:05Z
[ "python", "numpy", "numpy-memmap" ]
Updating an ordered list of dicts from a new list of dicts (priority merge)
39,953,539
<p>I'm currently faced with having to semi-regularly update (synchronize) a large-ish list of dicts from a canonical changing source while maintaining my own updates to it. A non-standard merge, for which the simplest description is probably:-</p> <ul> <li><code>A</code> is my own list of dicts (updated by my program ...
1
2016-10-10T07:49:42Z
39,956,818
<p>As I told hash method could help you to ensure comparison, based only on <code>keys</code> list you will able to find the intersection element (element to merged) and difference element. </p> <pre><code>class HashedDictKey(dict): def __init__(self, keys_, **kwargs): super().__init__(**kwargs) s...
0
2016-10-10T11:04:45Z
[ "python", "algorithm", "merge" ]
Is there any function as TentativeRoughFix in Python?
39,953,571
<p>I have applied Boruta on my dataset to determine the importance of features with respect to a predictor variable. However it is unable to determine the importance of several features.They are being shown as tentative. Is there any function as TentativeRoughFix in Python. The TentativeRoughFix function is present in ...
0
2016-10-10T07:51:47Z
39,953,911
<p>There are plenty of options for feature selection in scikit-learn (see <a href="http://scikit-learn.org/stable/modules/feature_selection.html" rel="nofollow">docu</a>).</p> <p>There is also a Boruta python implementation <a href="https://github.com/danielhomola/boruta_py" rel="nofollow">Boruta_py</a>, but I never t...
0
2016-10-10T08:11:39Z
[ "python", "machine-learning", "feature-selection" ]
rpy2 running R function
39,953,624
<p>I have an R function</p> <pre><code> square_num &lt;- function(x) { return(x*x) } </code></pre> <p>when I run this via rpy2 as:</p> <pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP string = """ square_num &lt;- function(x) { return(x*x) } """ testy = STAP(s...
0
2016-10-10T07:54:57Z
39,962,390
<p>Did you check the content of your Python variable <code>string</code> ? </p> <p>The following should work:</p> <pre><code>from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP string = """ square_num &lt;- function(x) { return(x*x) } """ testy = STAP(string, "testy") Jack = test...
0
2016-10-10T16:08:55Z
[ "python", "rpy2" ]
Can't get my Apache to work with mod_wsgi
39,953,696
<p>As per guide I downloaded the <a href="https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/modwsgi/mod_wsgi-win32-ap22py27-3.3.so" rel="nofollow">mod_wsgi-win32-ap22py27-3.3.so</a>, renamed it to mod_wsgi.so and put it into the /modules folder of Apache.</p> <p>Next I added the 'LoadModu...
0
2016-10-10T07:59:01Z
39,953,980
<p>Solved the issue.</p> <p>I had to set the environment variables PYTHONHOME and PYTHONPATH for it to fix the 'ImportError: No module named site' error.</p> <pre><code>set PYTHONHOME=c:\Python27 set PYTHONPATH=c:\Python27\Lib set PATH=%PYTHONHOME%;%PATH% </code></pre>
1
2016-10-10T08:15:59Z
[ "python", "apache", "mod-wsgi" ]
install ns3.21 in ubuntu16.04 error
39,954,098
<ol> <li><p>When I try to "sudo apt-get install gsl-bin libgsl0-dev libgsl0ldbl" 16.04 cannot find the package libgsl0ldbl for the reason that libgsl0-dev is replaced by libgsl-dev and libgsl0ldbl is obslolete, now replaced by libgsl2. I don't know if it matters.</p></li> <li><p>When I run the command "./build.py –en...
0
2016-10-10T08:23:52Z
40,142,985
<p>I personally tried to do that and it didn't worth the trouble at all so I ended up installing it on Ubuntu 14.04.</p> <p>In case you have no other choice, try watching this <a href="https://www.youtube.com/watch?v=SckgZkBg-Oc" rel="nofollow">tutorial</a></p>
0
2016-10-19T23:13:49Z
[ "python", "ubuntu", "ubuntu-16.04", "ns-3" ]
Looping each row in file1.txt over all rows of file2.txt for comparing
39,954,370
<p>I have two text files, say file1.txt contains something like</p> <p>100.145 10.0728</p> <p>100.298 10.04</p> <p>and file2.txt contains something like</p> <p>100.223 8.92739</p> <p>100.209 9.04269</p> <p>100.084 9.08411</p> <p>100.023 9.01252</p> <p>I want to compare column 1 and column 2 of both files and pr...
-3
2016-10-10T08:39:46Z
39,956,275
<p>you can try this;</p> <pre><code>#!/bin/bash while read line; do while read line2; do Col1F1=$(echo $line | awk '{print $1}') Col1F2=$(echo $line2 | awk '{print $1}') Col2F1=$(echo $line | awk '{print $2}') Col2F2=$(echo $line2 | awk '{print $2}') if [ ! -z "${Col1F1}" ] &amp;&amp; [ ...
-1
2016-10-10T10:32:20Z
[ "python", "awk" ]
POST request works in Postman but not in Python
39,954,475
<p>When I make this POST request in Postman, I get the data. When I do it in Python 2.7 (using a Jupyter notebook), I get the error "No JSON object could be decoded". What am I doing wrong and how can I make it work?</p> <pre><code>import json import requests url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/B...
1
2016-10-10T08:46:31Z
39,954,514
<p>Set <code>json=payload</code> and requests will add the headers you need:</p> <pre><code>url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy' payload = .... r = requests.post(url, json=payload) </code></pre> <p>That will give you your json:</p> <pre><code>In [7]: ...: r = requests...
1
2016-10-10T08:49:02Z
[ "python", "json" ]
My module has __init__.py and still Python can't import it
39,954,495
<p>I have a small python module </p> <pre><code>+-- address_book | +-- models.py | +-- __init__.py +-- test | +-- test_models.py </code></pre> <p>When I run <code>python address_book/test/test_models.py</code> I get this error </p> <pre><code>Traceback (most recent call last): File "address_book/te...
1
2016-10-10T08:47:40Z
39,954,623
<p>Your file structure should look like </p> <pre><code>+-- address_book | +-- __init__.py | +-- models.py +-- test | +-- test_models.py | +-- __init__.py </code></pre> <p>For your code to work you also have to be in the directory above address_book.</p>
2
2016-10-10T08:55:49Z
[ "python" ]
My module has __init__.py and still Python can't import it
39,954,495
<p>I have a small python module </p> <pre><code>+-- address_book | +-- models.py | +-- __init__.py +-- test | +-- test_models.py </code></pre> <p>When I run <code>python address_book/test/test_models.py</code> I get this error </p> <pre><code>Traceback (most recent call last): File "address_book/te...
1
2016-10-10T08:47:40Z
39,954,628
<p>Like said in comment, your tree looks strange. Put tests on the same level as address_book.</p> <p>To run the tests, you should use auto test discovery tools like nose or pytest (in doubt, go for pytest). Those tools automatically find the packages they are testing so that you don't have to install them or care in ...
2
2016-10-10T08:55:55Z
[ "python" ]
My module has __init__.py and still Python can't import it
39,954,495
<p>I have a small python module </p> <pre><code>+-- address_book | +-- models.py | +-- __init__.py +-- test | +-- test_models.py </code></pre> <p>When I run <code>python address_book/test/test_models.py</code> I get this error </p> <pre><code>Traceback (most recent call last): File "address_book/te...
1
2016-10-10T08:47:40Z
39,955,868
<pre><code>There is problem with import of module from parent directory as __main__ lies in child folder if you do the folder structure like below your same code for import will work +----test +---test_models.py +---__init__.py +---address_book +---__init__.py +---models.py </code></pr...
0
2016-10-10T10:05:36Z
[ "python" ]
My module has __init__.py and still Python can't import it
39,954,495
<p>I have a small python module </p> <pre><code>+-- address_book | +-- models.py | +-- __init__.py +-- test | +-- test_models.py </code></pre> <p>When I run <code>python address_book/test/test_models.py</code> I get this error </p> <pre><code>Traceback (most recent call last): File "address_book/te...
1
2016-10-10T08:47:40Z
39,956,380
<p>The problem stems from the fact that python does not know where to look for <code>address_book</code>. You can fix this by setting the <code>PYTHONPATH</code> environment variable before starting python.</p> <p>Given the following directory structure:</p> <pre><code>base_dir +-- address_book | +-- __init__.py |...
1
2016-10-10T10:38:42Z
[ "python" ]
How to ajaxable validate a PasswordChangeForm?
39,954,578
<p>I have some forms that I want to validate with an ajax view.</p> <pre><code>class ProfileEditPasswordForm(PasswordChangeForm): class Meta: model = User class AjaxValidation(generic.edit.FormView): def get(self, request, *args, **kwargs): return HttpResponseRedirect('/') def form_invali...
0
2016-10-10T08:53:14Z
39,956,875
<p>I think the problem is that django <code>FormView</code> is not compatible with <code>PasswordChangeForm</code>. The form requires the user to be passed to its constructor, but the view will not do that. You could try overriding <code>get_form_kwargs</code> method like this:</p> <pre><code>class AjaxValidation(gene...
1
2016-10-10T11:07:49Z
[ "python", "ajax", "django", "python-2.7", "django-1.8" ]
How to convert column with list of values into rows in Pandas DataFrame
39,954,668
<p>Hi I have a dataframe like this:</p> <pre><code> A B 0: some value [[L1, L2]] </code></pre> <p>I want to change it into:</p> <pre><code> A B 0: some value L1 1: some value L2 </code></pre> <p>How can I do that?</p>
2
2016-10-10T08:58:21Z
39,955,283
<p>you can do it this way:</p> <pre><code>In [84]: df Out[84]: A B 0 some value [[L1, L2]] 1 another value [[L3, L4, L5]] In [85]: (df['B'].apply(lambda x: pd.Series(x[0])) ....: .stack() ....: .reset_index(level=1, drop=True) ....: .to_frame('B...
2
2016-10-10T09:32:11Z
[ "python", "pandas", "dataframe" ]
How to convert column with list of values into rows in Pandas DataFrame
39,954,668
<p>Hi I have a dataframe like this:</p> <pre><code> A B 0: some value [[L1, L2]] </code></pre> <p>I want to change it into:</p> <pre><code> A B 0: some value L1 1: some value L2 </code></pre> <p>How can I do that?</p>
2
2016-10-10T08:58:21Z
39,955,506
<p>I can't find a elegant way to handle this, but the following codes can work...</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame([{"a":1,"b":[[1,2]]},{"a":4, "b":[[3,4,5]]}]) z = [] for k,row in df.iterrows(): for j in list(np.array(row.b).flat): z.append({'a':row.a, 'b':j}) result...
0
2016-10-10T09:44:24Z
[ "python", "pandas", "dataframe" ]
How to convert column with list of values into rows in Pandas DataFrame
39,954,668
<p>Hi I have a dataframe like this:</p> <pre><code> A B 0: some value [[L1, L2]] </code></pre> <p>I want to change it into:</p> <pre><code> A B 0: some value L1 1: some value L2 </code></pre> <p>How can I do that?</p>
2
2016-10-10T08:58:21Z
39,959,302
<p>Faster solution with <code>chain.from_iterable</code> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>numpy.repeat</code></a>:</p> <pre><code>df = pd.DataFrame({'A':['a','b'], 'B':[[['A1', 'A2']],[['A1', 'A2', 'A3']]]}) print (df) A ...
0
2016-10-10T13:20:42Z
[ "python", "pandas", "dataframe" ]
How to save fileobject/stream to text file on disk in python?
39,954,670
<p>I have a file object which is just a string with a large number of youtube urls taken from a playlist, how would I go about saving it to a .txt file? Thanks</p>
-5
2016-10-10T08:58:26Z
39,954,744
<p>Assuming your file object is f:</p> <pre><code>with open("urls.txt", "w") as urls_file: urls_file.write(f.read()) </code></pre> <p>It may need improvement depending on the file size.</p>
1
2016-10-10T09:02:19Z
[ "python", "python-3.x" ]
How to create a graph in Python using a CSV File data by graph-tool?
39,954,768
<p>I'm trying to create a graph with graph-tool (<a href="https://graph-tool.skewed.de" rel="nofollow">https://graph-tool.skewed.de</a>) from csv file that content like:</p> <pre><code>A,B,50 A,C,34 C,D,55 D,D,80 A,D,90 B,D,78 </code></pre> <p>Now I want to create a graph with A, B, C, D as nodes and the third column...
0
2016-10-10T09:03:46Z
39,957,150
<p>Assuming you already know how to read the CSV file in Python (for example, using the <a href="https://docs.python.org/3.6/library/csv.html" rel="nofollow">CSV library</a>), The docs on the website <a href="https://graph-tool.skewed.de/static/doc/quickstart.html#creating-and-manipulating-graphs" rel="nofollow">explai...
1
2016-10-10T11:24:13Z
[ "python", "csv", "graph-tool" ]
Python webcam record
39,954,788
<p>I want to create a webcam streaming app that records webcam stream for, say about 30 seconds, and save it as <code>myFile.wmv</code>. Now To get live camera feed I know this code :-</p> <pre><code>import cv2 import numpy as np c = cv2.VideoCapture(0) while(1): _,f = c.read() cv2.imshow('e2',f) if cv2.w...
-2
2016-10-10T09:04:46Z
39,955,438
<p><em>ABOUT TIME</em></p> <p>Why do not use the python <a href="https://docs.python.org/2/library/time.html" rel="nofollow">time function</a>? In particular <code>time.time()</code> Look at this <a href="http://stackoverflow.com/a/23197503/6564973">answer about time in python</a></p> <p>NB OpenCV should have (or had...
1
2016-10-10T09:40:50Z
[ "python", "python-2.7", "opencv", "video", "webcam" ]
Collapse the result of the cartesian product
39,954,890
<p>To calculate cartesian product with python is very simple. Just need to use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a></p> <pre><code>&gt;&gt;&gt; source = [['a', 'b', 'c'], [1, 2, 3]] &gt;&gt;&gt; list(itertools.product(*source)) [('a', 1), ('...
1
2016-10-10T09:10:47Z
39,955,028
<p>Its only a partial solution but assuming you <strong>know for certain</strong> that the result is a valid cartesian product generated by <code>itertools.product</code> and it is over lists of <strong>distinct</strong> values</p> <pre><code>&gt;&gt;&gt; [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartes...
6
2016-10-10T09:18:47Z
[ "python", "itertools" ]
Mapping Python list values to dictionary values
39,955,222
<p>I have a list of rows...</p> <p><code>rows = [2, 21]</code></p> <p>And a dictionary of data...</p> <p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p> <p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p> <p><code>dataRows = {2: {'x': 46, 'y': 20...
2
2016-10-10T09:28:49Z
39,955,362
<p>Your issue is that you are not puting sub-dictionaries inside dataRows. The fix would be this:</p> <pre><code>for i, row in enumerate(rows): dataRows[row] = {} for key, value in data.items(): dataRows[row][key] = value[i] </code></pre>
7
2016-10-10T09:36:56Z
[ "python" ]
Mapping Python list values to dictionary values
39,955,222
<p>I have a list of rows...</p> <p><code>rows = [2, 21]</code></p> <p>And a dictionary of data...</p> <p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p> <p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p> <p><code>dataRows = {2: {'x': 46, 'y': 20...
2
2016-10-10T09:28:49Z
39,955,393
<p>Following code works for me:</p> <pre><code>rows = [2, 21] data = {'x': [46, 35], 'y': [20, 30]} dataRows = {} for i, row in enumerate(rows): dataRows[row] = {} dataRows[row]['x'] = data['x'][i] dataRows[row]['y'] = data['y'][i] print dataRows </code></pre> <p>UPDATE:</p> <p>You can also use collections...
2
2016-10-10T09:38:25Z
[ "python" ]
Mapping Python list values to dictionary values
39,955,222
<p>I have a list of rows...</p> <p><code>rows = [2, 21]</code></p> <p>And a dictionary of data...</p> <p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p> <p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p> <p><code>dataRows = {2: {'x': 46, 'y': 20...
2
2016-10-10T09:28:49Z
39,955,429
<p>In a line:</p> <pre><code>&gt;&gt;&gt; {r: {k: v[i] for k, v in data.items()} for i, r in enumerate(rows)} {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}} </code></pre>
0
2016-10-10T09:40:26Z
[ "python" ]
Mapping Python list values to dictionary values
39,955,222
<p>I have a list of rows...</p> <p><code>rows = [2, 21]</code></p> <p>And a dictionary of data...</p> <p><code>data = {'x': [46, 35], 'y': [20, 30]}</code></p> <p>I'd like to construct a second dictionary, <code>dataRows</code>, keyed by the row that looks like this...</p> <p><code>dataRows = {2: {'x': 46, 'y': 20...
2
2016-10-10T09:28:49Z
39,955,582
<p>Here's a Python 3 solution with only one explicit loop:</p> <pre><code>{r: dict(zip(data.keys(), d)) for r, *d in zip(rows, *data.values())} </code></pre>
0
2016-10-10T09:48:18Z
[ "python" ]
Python Django official tutorial "Polls", beginner gets frustrating errors
39,955,232
<p>I am trying to follow through the Python Django Tutorial from the official site.</p> <p>However I find it hard to follow. I did everything as written but I got the following error"</p> <p><a href="http://i.stack.imgur.com/o8pce.jpg" rel="nofollow">ERROR screen caption</a></p> <p>It sounds like something is wrong ...
-1
2016-10-10T09:29:19Z
39,955,273
<p>You are missing the line <code>from django.conf.urls import include, url</code>.</p>
1
2016-10-10T09:31:37Z
[ "python", "django", "compiler-errors", "virtualenv" ]
Pandas pivot table: columns order and subtotals
39,955,336
<p>I'm using Pandas 0.19.</p> <p>Considering the following data frame:</p> <pre><code>FID admin0 admin1 admin2 windspeed population 0 cntry1 state1 city1 60km/h 700 1 cntry1 state1 city1 90km/h 210 2 cntry1 state1 city2 60km/h 100 3 cntry1 state2 city3 60km/h 70 4 c...
5
2016-10-10T09:35:19Z
39,956,010
<p>you can do it using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow">reindex()</a> method and custom sorting:</p> <pre><code>In [26]: table Out[26]: population windspeed 120km/h 60km/h 90km/h admin0 admin1 admin2 cntry1 s...
2
2016-10-10T10:15:05Z
[ "python", "pandas", "dataframe", "pivot" ]
Pandas pivot table: columns order and subtotals
39,955,336
<p>I'm using Pandas 0.19.</p> <p>Considering the following data frame:</p> <pre><code>FID admin0 admin1 admin2 windspeed population 0 cntry1 state1 city1 60km/h 700 1 cntry1 state1 city1 90km/h 210 2 cntry1 state1 city2 60km/h 100 3 cntry1 state2 city3 60km/h 70 4 c...
5
2016-10-10T09:35:19Z
39,956,469
<p>Solution with subtotals and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_arrays.html" rel="nofollow"><code>MultiIndex.from_arrays</code></a>. Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and al...
4
2016-10-10T10:44:19Z
[ "python", "pandas", "dataframe", "pivot" ]
Django How can I use redis in Windows10?
39,955,449
<p>I am developing small system with Django framework and Windows 10. I am going to use Redis for caching on memory. Well, I found that Redis doesn't support Windows OS officially but MsOpenTech provides a package for Windows 64 bit. I installed it with chocolatey package manager. <a href="https://chocolatey.org/packag...
0
2016-10-10T09:41:18Z
39,956,710
<p>You uninstalled the Python <code>redis</code> package thinking it was the Redis server but it's just a Python package with code to <em>access</em> Redis. You need to reinstall it. But you seem to have that part fixed.</p> <p>As for using Redis with Django on Windows 10 the way you installed it, I would say it depen...
1
2016-10-10T10:57:10Z
[ "python", "django", "redis", "windows-10" ]
Python google query with requests module, get responce in http format
39,955,450
<p>I want to execute a google query with requests module in python. Here is my script:</p> <pre><code>import requests searchfor = 'test' payload = {'q': searchfor, 'key': API_KEY, 'cx': SEARCH_ENGINE_ID} link = 'https://www.googleapis.com/customesearch/v1' r = requests.get(link, paramas=payload) print r.content </cod...
0
2016-10-10T09:41:21Z
39,956,133
<p>The google api only supports <a href="https://developers.google.com/custom-search/json-api/v1/overview" rel="nofollow">atom/Json</a>. </p> <p>So you have to parse the JSON to HTML. You maybe want to check <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json package</a>.</p> <p>append something...
1
2016-10-10T10:23:47Z
[ "python", "json", "http", "google-app-engine", "request" ]
sqlalchemy existing database query
39,955,521
<p>I am using SQLAlchmey as ORM for a python project. I have created few models/schema and it is working fine. Now I need to query a existing mysql database, no insert/update just the select statement. </p> <p>How can I create a wrapper around the tables of this existing database? I have briefly gone through the sqlal...
1
2016-10-10T09:45:25Z
39,966,711
<p>You seem to have an impression that SQLAlchemy can only work with a database structure created by SQLAlchemy (probably using <code>MetaData.create_all()</code>) - this is not correct. SQLAlchemy can work perfectly with a pre-existing database, you just need to define your models to match database tables. One way to ...
1
2016-10-10T21:02:46Z
[ "python", "sqlalchemy", "pyramid", "pylons" ]
Flask GAE app giving error
39,955,605
<p>I created a flask app which is working fine on pythonanywhere but when i deployed it on google app engine ,its giving error <a href="http://aapkatool.appspot.com/" rel="nofollow">http://aapkatool.appspot.com/</a></p> <p>here is my code</p> <pre><code>from flask import Flask, request, session, redirect,url_for,rend...
1
2016-10-10T09:49:46Z
39,960,128
<p>Is the <code>calculate</code> function defined in both deployments on <a href="http://kk268.pythonanywhere.com/emi-calc" rel="nofollow">http://kk268.pythonanywhere.com/emi-calc</a> and <a href="http://aapkatool.appspot.com/" rel="nofollow">http://aapkatool.appspot.com/</a> ? The only error I'm seeing in my browser i...
0
2016-10-10T14:03:05Z
[ "python", "google-app-engine", "flask", "jinja2" ]
Flask GAE app giving error
39,955,605
<p>I created a flask app which is working fine on pythonanywhere but when i deployed it on google app engine ,its giving error <a href="http://aapkatool.appspot.com/" rel="nofollow">http://aapkatool.appspot.com/</a></p> <p>here is my code</p> <pre><code>from flask import Flask, request, session, redirect,url_for,rend...
1
2016-10-10T09:49:46Z
39,970,620
<p>I am not sure why you even have the <code>initialize.py</code> file at all. It doesn't look like you need it. The <a href="https://cloud.google.com/appengine/docs/python/tools/webapp/" rel="nofollow"><code>google.appengine.ext.webapp</code></a> package docs state that its for the deprecated Python 2.5 environment an...
0
2016-10-11T04:42:58Z
[ "python", "google-app-engine", "flask", "jinja2" ]
matplotlib update plot in while-loop with dates as x-axis
39,955,701
<p>This might be obvious, so sorry in advance for this nooby question. I want to update a time series dynamically with matplotlib.pyplot. More precisely, I want to plot newly generated data in a while-loop. </p> <p>This is my attempt so far:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt; plt.ion()...
0
2016-10-10T09:55:20Z
39,957,630
<p>As Andras Deak pointed out, you should tell pandas explicitly that your <code>time</code> column is datetime. When you do <code>df.info()</code> at the end of your code, you will see that it takes <code>df['time']</code> as float64. You can achieve this with <code>df['time'] = pd.to_datetime(df['time'])</code>. </p...
1
2016-10-10T11:51:33Z
[ "python", "matplotlib", "plot", "while-loop" ]
Send Persian string from C# server to python client with socket
39,955,744
<p>I use socket programming to connect a python program to a C# program. python code is client and C# code is server. C# code send a string to python with this code:</p> <pre><code>byte[] R=Encoding.UTF8.GetBytes("one string"); Client.Send(R); </code></pre> <p>and i receive data in python code with this:</p> <pre><c...
1
2016-10-10T09:57:56Z
39,957,141
<p>try </p> <pre><code>byte[] R = Encoding.Default.GetBytes("Persian String"); </code></pre>
1
2016-10-10T11:23:41Z
[ "c#", "python", "sockets", "encode" ]
Python turning multiple objects into a dictionary
39,955,844
<p>I've got an Object which has a name and an indefinite amount of parameters (which is also an object with a name and a value)</p> <p>I'm pretty new to python so this gets a bit over my head I want to get all parameters and put them into a dictionary. My code looks like this:</p> <pre><code>data = {} for parameter ...
0
2016-10-10T10:04:34Z
39,958,428
<p>By looking at your output it looks like you class structure is something like this</p> <pre><code>class class1(object): def __init__(self, p1, p2): self.name = p1 self.value = p2 class class2(object): def __init__(self): self.parameters = [class1("param1", "value1"), class1("param2...
0
2016-10-10T12:34:46Z
[ "python", "dictionary" ]
How to check if a file is empty avoid reading the whole file in a submit form?
39,955,940
<p>I am using django, and in a web submit form, I want to check if a uploading file is empty, but avoid uploading or reading the whole file to get the file size, because it might be huge and take time to calculate.</p>
0
2016-10-10T10:10:27Z
39,956,020
<p>You are probably looking for <a href="https://docs.python.org/2/library/os.html#os.stat" rel="nofollow">os.stat</a></p> <p>os.stat(path)</p> <blockquote> <p>Perform the equivalent of a stat() system call on the given path. (This function follows symlinks; to stat a symlink use lstat().)</p> <p>The return ...
2
2016-10-10T10:15:39Z
[ "python", "django", "web" ]
How to check if a file is empty avoid reading the whole file in a submit form?
39,955,940
<p>I am using django, and in a web submit form, I want to check if a uploading file is empty, but avoid uploading or reading the whole file to get the file size, because it might be huge and take time to calculate.</p>
0
2016-10-10T10:10:27Z
39,956,051
<pre><code>import os &gt;&gt;&gt; os.stat("file").st_size == 0 True </code></pre> <p>by using this code you can check file is empty or not </p>
2
2016-10-10T10:17:31Z
[ "python", "django", "web" ]
flask importerror: cannot import name storage
39,956,099
<p>I try to use flask-cloudy to uploads files, but I can't import storage (a model in flask-cloudy) this is how I config it :</p> <pre><code>class DevelopmentConfig(): DEBUG = True SECRET_KEY = 'I_will_never_told_you' STORAGE_PROVIDER = "LOCAL" STORAGE_CONTAINER = "./data" STORAGE_KEY = "" STOR...
1
2016-10-10T10:21:14Z
39,959,951
<p>You need to put your storage initialisation outside of the <code>create_app</code> function.</p> <p>The <code>storage</code> variable right now is only accessible inside the <code>create_app</code> function. </p>
0
2016-10-10T13:54:00Z
[ "python", "flask", "flask-extensions" ]
hangman: UnboundLocalError: local variable referenced before assignment
39,956,149
<p>I made a program to play hangman. I got pretty far but no matter how many times i try to fix it or make a different variation, the shell just comes up with the same thing.</p> <p><code>UnboundLocalError: local variable '' referenced before assignment. </code></p> <p>I'm fairly new so can you make the answers as si...
-2
2016-10-10T10:24:58Z
39,956,337
<p>I think you are missing a <strong>global</strong> statement such as</p> <pre><code>def guesses (): global tries #... some of your code... #and now this line will work! :) tries = tries - 1 </code></pre> <p>this kind of error usually comes up when you see code like this:</p> <pre><code>def f(): ...
-1
2016-10-10T10:36:20Z
[ "python", "debugging" ]
hangman: UnboundLocalError: local variable referenced before assignment
39,956,149
<p>I made a program to play hangman. I got pretty far but no matter how many times i try to fix it or make a different variation, the shell just comes up with the same thing.</p> <p><code>UnboundLocalError: local variable '' referenced before assignment. </code></p> <p>I'm fairly new so can you make the answers as si...
-2
2016-10-10T10:24:58Z
39,956,357
<p>For starters, <code>output</code> is undefined. Note that you never assign to, or otherwise define <code>output</code> before you use it. Second, I can't help but to notice you try to use names defined inside of a function outside of it. There are two problems with this:</p> <ul> <li><p>Names defined inside of a f...
0
2016-10-10T10:37:32Z
[ "python", "debugging" ]
hangman: UnboundLocalError: local variable referenced before assignment
39,956,149
<p>I made a program to play hangman. I got pretty far but no matter how many times i try to fix it or make a different variation, the shell just comes up with the same thing.</p> <p><code>UnboundLocalError: local variable '' referenced before assignment. </code></p> <p>I'm fairly new so can you make the answers as si...
-2
2016-10-10T10:24:58Z
39,958,351
<p>Apart for your snippet's indentation being off (remember that in python indentation is part of the syntax so take care about this when posting snippets), your main problem is with global vs local namespace. </p> <p>The global namespace holds "top level" names (names defined at the top level of your script / module,...
0
2016-10-10T12:30:23Z
[ "python", "debugging" ]
Vectorise Python code
39,956,313
<p>I have coded a kriging algorithm but I find it quite slow. Especially, do you have an idea on how I could vectorise the piece of code in the cons function below:</p> <pre><code>import time import numpy as np B = np.zeros((200, 6)) P = np.zeros((len(B), len(B))) def cons(): time1=time.time() for i in range(len...
3
2016-10-10T10:35:21Z
39,956,406
<p>Your problem seems very simple to vectorize. For each pair of rows of <code>B</code> you want to compute</p> <pre><code>P[i,j] = np.exp(-np.sum(np.abs(B[i,:] - B[j,:]))) </code></pre> <p>You can make use of array broadcasting and introduce a third dimension, summing along the last one:</p> <pre><code>P2 = np.exp(...
4
2016-10-10T10:40:50Z
[ "python", "numpy", "vectorization" ]
Django DRF serializer on PrimaryKeyRelatedField
39,956,348
<p>Question about PrimaryKeyRelatedField serialization in Django DRF version 3.4.7.</p> <h1>models</h1> <pre><code>class UserModel(AbstractEmailUser): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.email) c...
0
2016-10-10T10:36:59Z
39,957,989
<p>The issue is there:</p> <pre><code>class ConversationSerializer(serializers.ModelSerializer): msg_conv = MessagesSerializer() </code></pre> <p>By doing this, you are saying that <code>Conversation</code> has a FK to <code>Message</code>. Therefore DRF tries to do the mapping and fails because it's the oposit....
1
2016-10-10T12:10:01Z
[ "python", "json", "django", "serialization", "django-rest-framework" ]
aiohttp how to log access log?
39,956,400
<p>I am trying to get a basic logger for aiohttp working, but there are simply no log messages being logged. Note_ logging custom messages works as expected.</p> <pre><code>async def main_page(request: web.Request): return "hello world" def setup_routes(app): app.router.add_get('/', main_page) async def ini...
1
2016-10-10T10:40:11Z
39,979,270
<p><code>LOG_FORMAT</code> should be "%s" if any. <code>'%a %l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'</code> is a valid parameter for <code>.make_handler(access_log_format=...)</code> call, not <code>logging.Formatter</code>.</p> <p>As first step I suggest setting up root logger and after that going down to...
0
2016-10-11T14:12:35Z
[ "python", "aiohttp" ]
Python argparse - arguments strip off when bash special character is passed as argument
39,956,435
<p>I writing CLI tool using argparse.</p> <p>Below is my code snippet:</p> <pre><code>parser.ArgumentParser() parser.add_argument('--username') parser.add_argument('--password') args = parser.parse_args() print(args.password) </code></pre> <p>I run the script on my Mac:</p> <p><code>&gt;&gt;&gt; prog.py --username ...
1
2016-10-10T10:42:23Z
39,956,503
<p>You can put a backslash in front of the <code>$</code>: <code>prog.py --username xyz --password abc\$xyz</code>.</p> <p>Otherwise, no. You correctly observed that it is bash that is doing this so, by the time Python/argparse receives the command, there is nothing that can be done.</p>
-1
2016-10-10T10:46:02Z
[ "python", "bash", "argparse" ]
Simpy Resource : Get ID?
39,956,444
<p>I have two airport runways as a Simpy Resource:</p> <pre><code>runway = simpy.Resource(env, capacity=2) # two runways </code></pre> <p>This works all fine, but how can I access the runway id (1 or 2) so that I can have an output such as 'Plane #1 taking off from runway #1'?</p>
0
2016-10-10T10:42:47Z
39,971,073
<p>You can’t (officially). Internally, the slots are just a list so you could in theory use the list index of the Request.</p> <p>Alternatively, you might use <code>Store</code> and put two "Runway" objects into it. These objects have (of course) an ID an can also carry additional information (whatever you can ima...
0
2016-10-11T05:38:00Z
[ "python", "simpy" ]
Django Patch Side effect IntegrityError not being raised
39,956,479
<p>I have the following view, which excepts POST requests, and serializes an objects data (a Draftschedule) to create a new copy (a FrozenSchedule):</p> <pre><code>from reports.tasks import create_frozen_schedule def freeze_schedule(request, pk): """Valid post request will freeze a Draft Schedule serializing its ...
0
2016-10-10T10:44:45Z
39,956,582
<p>Your view catches IntegrityError and returns a redirect. The client post, which is what your test calls, doesn't raise an error at all.</p> <p>Rather, you should be testing that the actions in the except block happen: is the warning set, and does the post redirect to the draft schedule instead of the frozen one.</p...
1
2016-10-10T10:50:48Z
[ "python", "django", "mocking" ]
Seaching big files using list in Python - How can improve the speed?
39,956,510
<p>I have a folder with 300+ .txt files with total size of 15GB+. These files contain tweets. Each line is a different tweet. I have a list of keywords I'd like to search the tweets for. I have created a script that searches each line of every file for every item on my list. If the tweet contains the keyword, then it w...
1
2016-10-10T10:46:29Z
39,956,830
<h2>1) External library</h2> <p>If you're willing to lean on external libraries (and time to execute is more important than the one-off time cost to install), you might be able to gain some speed by loading each file into a simple Pandas DataFrame and performing the keyword search as a vector operation. To get the mat...
1
2016-10-10T11:05:34Z
[ "python", "list", "python-3.x", "search", "twitter" ]
Seaching big files using list in Python - How can improve the speed?
39,956,510
<p>I have a folder with 300+ .txt files with total size of 15GB+. These files contain tweets. Each line is a different tweet. I have a list of keywords I'd like to search the tweets for. I have created a script that searches each line of every file for every item on my list. If the tweet contains the keyword, then it w...
1
2016-10-10T10:46:29Z
39,956,886
<p><strong>Why it's slow</strong></p> <p>You are regex searching through a json dump, which is not always a good idea. For example, if you keywords include words like user, time, profile and image each line will result in a match because the json format for tweets has all these terms as dictionary keys. </p> <p>Besid...
1
2016-10-10T11:08:15Z
[ "python", "list", "python-3.x", "search", "twitter" ]
Python read input lines through function call
39,956,534
<p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p> <pre><code>def get_list(): file = open('list.txt', 'r') lines = file.read().splitlines()[2:5] print (lines) get_list() </code></pre> <p>However I am required to implement something w...
1
2016-10-10T10:47:50Z
39,956,580
<p>Just return lines !</p> <pre><code>def get_list(): file = open('list.txt', 'r') lines = file.read().splitlines() return lines </code></pre>
0
2016-10-10T10:50:44Z
[ "python", "file", "text", "input" ]
Python read input lines through function call
39,956,534
<p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p> <pre><code>def get_list(): file = open('list.txt', 'r') lines = file.read().splitlines()[2:5] print (lines) get_list() </code></pre> <p>However I am required to implement something w...
1
2016-10-10T10:47:50Z
39,956,626
<pre><code>def get_list(): with open('list.txt', 'r') as file: lines = file.read().splitlines() return lines print(get_list()[2:5]) </code></pre>
1
2016-10-10T10:52:44Z
[ "python", "file", "text", "input" ]
Python read input lines through function call
39,956,534
<p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p> <pre><code>def get_list(): file = open('list.txt', 'r') lines = file.read().splitlines()[2:5] print (lines) get_list() </code></pre> <p>However I am required to implement something w...
1
2016-10-10T10:47:50Z
39,957,053
<p>As I mentioned in the question comments, this is <em>not</em> a sensible thing to do, but here's how it can be done. To test this code I created a text file containing the integers 0 to 9, using the GNU coreutils command <code>seq</code>:</p> <pre><code>seq 0 9 &gt;list.txt </code></pre> <p>And here's the Python c...
1
2016-10-10T11:18:58Z
[ "python", "file", "text", "input" ]
Create a custom URL and outputting HTML form data
39,956,590
<p>For my first Flask project I wanted to create a basic Flask app using Riot Game's API for League of Legends. I've got all the processing of API working but I'm having trouble going about outputting it.</p> <p>I take the input from a form on one page.</p> <pre><code>&lt;form class="navbar-form navbar-left" action="...
0
2016-10-10T10:51:05Z
39,956,684
<p>You should post the error as well.</p> <p>In a quick looks this should be fixed:</p> <pre><code>@app.route('/currentgame/&lt;string:region&gt;/&lt;string:name&gt;', methods=['POST']) def current_game_output(region, name): region = request.form['region'] summoner_name = request.form['summoner_name'] api...
0
2016-10-10T10:56:01Z
[ "python", "forms", "python-3.x", "flask" ]
Insertion sort not working - list index out of range
39,956,663
<p>Trying to create insertion sort but receive an error...</p> <p>Don't really know why it is happening. It always tends to miss 37 aswell</p> <pre><code>numbers = [45,56,37,79,46,18,90,81,50] def insertionSort(items): Tsorted = [] Tsorted.append(items[0]) items.remove(items[0]) for i in range(0,len(...
0
2016-10-10T10:54:49Z
39,956,837
<p>You are removing elements from <code>items</code> over the course of the loop; thus, <code>i</code> may become a value that was a valid index in the original <code>items</code>, but is no longer in the shortened one.</p> <p>If you need to remove elements from <code>items</code>, it looks like you should wait until ...
0
2016-10-10T11:05:48Z
[ "python", "python-2.7", "insertion-sort" ]
Insertion sort not working - list index out of range
39,956,663
<p>Trying to create insertion sort but receive an error...</p> <p>Don't really know why it is happening. It always tends to miss 37 aswell</p> <pre><code>numbers = [45,56,37,79,46,18,90,81,50] def insertionSort(items): Tsorted = [] Tsorted.append(items[0]) items.remove(items[0]) for i in range(0,len(...
0
2016-10-10T10:54:49Z
39,956,838
<p>First thing: you are removing items from the Array that you are iterating inside the loop here: <code>items.remove(items[i])</code>. This is generally not a good idea.</p> <p>Second: This algorithm doesn't implement insertion sort, even if you fix the deletion issue. You should review the algorithm, e.g. here <a hr...
1
2016-10-10T11:05:51Z
[ "python", "python-2.7", "insertion-sort" ]
Insertion sort not working - list index out of range
39,956,663
<p>Trying to create insertion sort but receive an error...</p> <p>Don't really know why it is happening. It always tends to miss 37 aswell</p> <pre><code>numbers = [45,56,37,79,46,18,90,81,50] def insertionSort(items): Tsorted = [] Tsorted.append(items[0]) items.remove(items[0]) for i in range(0,len(...
0
2016-10-10T10:54:49Z
39,956,844
<p>That's because you're calling <code>tems.remove()</code>. Your code fails when i=4 and <code>items=[37, 46, 90, 50]</code>. </p> <p>So they already has no an element with index <code>4</code> but with <code>3</code> since indexing starts with 0.</p>
0
2016-10-10T11:06:13Z
[ "python", "python-2.7", "insertion-sort" ]
Insertion sort not working - list index out of range
39,956,663
<p>Trying to create insertion sort but receive an error...</p> <p>Don't really know why it is happening. It always tends to miss 37 aswell</p> <pre><code>numbers = [45,56,37,79,46,18,90,81,50] def insertionSort(items): Tsorted = [] Tsorted.append(items[0]) items.remove(items[0]) for i in range(0,len(...
0
2016-10-10T10:54:49Z
39,957,029
<p><code>range(0,len(items)</code> will only be calculated the first time your code hits your for-loop, at which state <code>len(list) = 8</code>. Which means that you wlil iterate</p> <pre><code>for i in [0,1,2,3,4,5,6,7] #Do stuff... </code></pre> <p>But at the same time you remove items from your list in each ...
0
2016-10-10T11:17:02Z
[ "python", "python-2.7", "insertion-sort" ]
Reject or loop over user input if two conditions not met
39,956,782
<p>I am a real beginner with Python, although I am loving every minute of it so far.</p> <p>I am making a little program that takes user input and then does stuff with it. My issue is that the numbers the user inputs have to </p> <p>(1) All add up to not more than one (i.e. a1+ a2+ a3 \leq 1)</p> <p>(2) Each individ...
2
2016-10-10T11:01:59Z
39,956,909
<pre><code>input_list = [] input_number = 1 while True: input_list.append(raw_input('Enter percentage {} (in decimal form):'.format(input_number)) if float(input_list[-1]) &gt; 1: # Last input is larger than one, remove last input and print reason input_list.remove(input_list[-1]) print('T...
4
2016-10-10T11:09:21Z
[ "python", "loops", "input" ]
Python "trouble shooting machine " needs fixing
39,956,833
<p>The following code is designed to be an automated troubleshooter in Python.</p> <pre><code># Welcoming the user to the program print("Hello this is a automated mobile phone troubleshooter ") print("The code will ask you a few questions try to answer them to the best of your ability") # Explaining what the code wil...
-6
2016-10-10T11:05:41Z
39,957,633
<p>Whats about doing it with "if statements" and raw_input ? </p> <pre><code>x = raw_input("Is there a problem with your hardware or is do you need technical assistance. Please type technical assistance or hardware") if x == ("technical assistant"): print("This troubleshooter is only for hardware problems please ...
-1
2016-10-10T11:51:38Z
[ "python" ]
Python: decorator/wrapper for try/except statement
39,956,960
<p>I have some blocks of code which need to be wrapped by function.</p> <pre><code>try: if config.DEVELOPMENT == True: # do_some_stuff except: logger.info("Config is not set for development") </code></pre> <p>Then I'll do again:</p> <pre><code>try: if config.DEVELOPMENT == True: # do_some...
0
2016-10-10T11:12:26Z
39,967,851
<p>You could pass in a function.</p> <pre><code>boolean = True def pass_this_in(): print("I just did some stuff") def the_try_except_bit(function): try: if boolean: function() except: print("Excepted") # Calling the above code the_try_except_bit(pass_this_in) </code></pre> ...
0
2016-10-10T22:43:41Z
[ "python", "try-catch", "wrapper", "decorator" ]
Python: decorator/wrapper for try/except statement
39,956,960
<p>I have some blocks of code which need to be wrapped by function.</p> <pre><code>try: if config.DEVELOPMENT == True: # do_some_stuff except: logger.info("Config is not set for development") </code></pre> <p>Then I'll do again:</p> <pre><code>try: if config.DEVELOPMENT == True: # do_some...
0
2016-10-10T11:12:26Z
39,993,645
<p>I am not sure that a context manager is the good method to achieve what you want. The context manager goal is to provide a mecanism to open/instantiate a resource, give access to it (or not) and close/clean it automatically when you no more need it.</p> <p>IMHO, what you need is a <a href="http://thecodeship.com/pa...
0
2016-10-12T08:12:36Z
[ "python", "try-catch", "wrapper", "decorator" ]
How to capture the ZPL ^HV ouotput
39,957,025
<p>I need help implementing the ^HV ZPL command and to capture it as the host.</p> <p>I want to read the TID and encode it to the EPC using Python, i can send print and encode command to the printer but how do i read back from it ?</p> <p>If I'm using the "Direct Communication" program in the Zebra Setup Utilities to...
0
2016-10-10T11:16:49Z
39,965,941
<p>Communicating with a Zebra printer over TCP is the same as any other TCP connection. If the question is how to use the ^HV command, it is usually put into a stored format. The response happens when you use the format to print. Here's a snippet I modified from <a href="https://wiki.python.org/moin/TcpCommunication"...
1
2016-10-10T20:05:28Z
[ "python", "rfid", "zebra-printers", "zpl", "zpl-ii" ]
Python - difference between self.method, lambda: self.method() and self.method() on startup
39,957,044
<p>In order to understand the difference in use of method calls, I wrote a MVC in python 2.7. Here is the code:</p> <pre><code>import Tkinter as tk class Model(object): def __init__(self, *args, **kwargs): # dict self.data = {} # -- &gt;values self.data["Value_One"] = tk.IntVar() ...
0
2016-10-10T11:18:10Z
39,957,247
<p>All in all, there is no mystery here. </p> <p>The command argument of the Button constructor takes a callback, i.e. a function that will be executed when the button is pressed. You do this for buttons 1 and 3. So when the corresponding buttons are clicked, the function (be it the lambda or the bound method) is call...
2
2016-10-10T11:29:19Z
[ "python", "lambda", "method-call" ]
Python Daemon dies
39,957,122
<p>I created a Daemon process with these lib<a href="https://www.python.org/dev/peps/pep-3143/" rel="nofollow">linktosite</a> I connect trough ssh and start the process with python myDaemon.py start.</p> <p>I use a loop within the daemon method to do my tasks. But as soon as I logout the daemon stops(dies).</p> <p>Do...
-1
2016-10-10T11:22:41Z
39,957,558
<p>Use the shebang line in your <code>python</code> script. Make it executable using the command. chmod +x test.py Use no hangup to run a program in background even if you close your terminal.</p> <pre><code>nohup /path/to/test.py &amp; </code></pre> <p>Do not forget to use <code>&amp;</code> to put it in backgro...
-1
2016-10-10T11:47:02Z
[ "python", "linux", "daemon" ]
Read list of zlib archives
39,957,136
<p>I have a file that contains many zlib archives in itself. Structure of the file looks like:</p> <pre><code>+-------------------------+ |+-----------------------+| || CMF+FLG (78DA) || |+-----------------------+| |+-----------------------+| ||...compressed data 1...|| |+-----------------------+| |+-----------...
-2
2016-10-10T11:23:24Z
39,960,680
<p>You should be able to use a series of decompression objects like this:</p> <pre><code>import zlib with open(filename, 'rb') as compressed: data = compressed.read() file_no = 0 while data: d = zlib.decompressobj() with open('{}_decompressed.{}'.format(filename, file_no), 'wb') as f: ...
2
2016-10-10T14:32:23Z
[ "python", "file", "zlib" ]
Pandas does not drop nan
39,957,341
<p>I have the following group</p> <pre><code> unemp nobsRel measure rank nobsRel2 nobsCumSummed year foo 2000 8010 0.000024 0.000167 1.0 348.0 0.000167 0.980176 4950 0.000264 0.003630 1.0 349.0 0.003630 ...
0
2016-10-10T11:34:59Z
39,957,438
<p>Sadly it appears that <code>drop_duplicates</code> doesn't do what you want. It removes duplicates, but not the original row that the duplicates are a duplicate of ...</p> <p>Fortunately that can be overridden with a <code>keep=False</code> option to the call.</p>
1
2016-10-10T11:40:38Z
[ "python", "pandas" ]
Pandas does not drop nan
39,957,341
<p>I have the following group</p> <pre><code> unemp nobsRel measure rank nobsRel2 nobsCumSummed year foo 2000 8010 0.000024 0.000167 1.0 348.0 0.000167 0.980176 4950 0.000264 0.003630 1.0 349.0 0.003630 ...
0
2016-10-10T11:34:59Z
39,957,443
<p>The <code>drop_duplicates()</code>method drops the duplicates except the first one (by default). However, you can choose which one to keep by changing the parameter <strong>keep</strong> setting it to <code>last</code>, <code>first</code> or <code>False</code>. Look at the <a href="http://pandas.pydata.org/pandas-do...
4
2016-10-10T11:40:57Z
[ "python", "pandas" ]
Split string of expression
39,957,476
<p>I want to split string like</p> <pre><code>Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))" </code></pre> <p>I use str.split() but it split the number like: "3 2 4 + 1 7"</p> <p>output:</p> <pre><code>"( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )" </code></p...
-1
2016-10-10T11:43:06Z
39,957,885
<p>I think what you nee is to insert space in between every non numeric characters. Split wont be able to do the that job for you and you could use re.sub for the same.</p> <p>This is what I could come up quickly and there could be better expression to do this in single iteration but it will give you a idea </p> <pr...
2
2016-10-10T12:04:56Z
[ "python" ]
Split string of expression
39,957,476
<p>I want to split string like</p> <pre><code>Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))" </code></pre> <p>I use str.split() but it split the number like: "3 2 4 + 1 7"</p> <p>output:</p> <pre><code>"( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )" </code></p...
-1
2016-10-10T11:43:06Z
39,958,085
<p>You could use a dictionary to replace certain characters by their padded equivalents:</p> <pre><code>&gt;&gt;&gt; Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))" &gt;&gt;&gt; d = {'(':'( ', ')':' )', '+': ' + ', '-': ' - ', '*': ' * ', '/': ' / '} &gt;&gt;&gt; ''.join(d[c] if c in d else c for c in ...
0
2016-10-10T12:15:04Z
[ "python" ]
Split string of expression
39,957,476
<p>I want to split string like</p> <pre><code>Expression = "((((324+17)*3)/((936-51)+124))-((13*(72-41))+6))" </code></pre> <p>I use str.split() but it split the number like: "3 2 4 + 1 7"</p> <p>output:</p> <pre><code>"( ( ( ( 324 + 17 ) * 3 ) / ( ( 936 - 51 ) + 124 ) ) - ( ( 13 * ( 72 - 41 ) ) + 6 ) )" </code></p...
-1
2016-10-10T11:43:06Z
39,959,303
<p>You're looking to <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow">tokenize</a> the string. For a Python expression you could do it using the tokenize module, or for a plainer form you could use various search functions. Here are two examples:</p> <pre><code>&gt;&gt;&gt; expression = "((((32...
0
2016-10-10T13:20:42Z
[ "python" ]