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
Updating model in Django based on dictionary values
39,675,149
<p>I have a dictionary in Django, contains a model's keys and some values. I want to update one of field (<em>score</em>) of the model (<em>A</em>) like this: multiply that field for all the records to a constant, and then, if the record was found in the dictionary, add the corresponding dict value to the field. there ...
0
2016-09-24T10:08:52Z
39,675,515
<p>It doesn't make sense to use a dictionary lookup here; this is transformed into a single SQL query, the value of F() is not resolved in Python so there is no way it can be used to look up in a dictionary.</p> <p>Instead you will probably have to use a <a href="https://docs.djangoproject.com/en/1.10/ref/models/condi...
2
2016-09-24T10:50:54Z
[ "python", "sql", "django" ]
Python readline Auto-Complete
39,675,223
<p>I want to implement auto-complete in Command Line Interface for the following : </p> <pre><code>Food : Fruits: Apples Oranges Vegetables: Carrot Beetroot Snacks: Chocolate </code></pre> <p>The output for the <code>&lt;TAB&gt;</code> would be : food<br> and so on...</p> <p>Commands woul...
-1
2016-09-24T10:17:45Z
39,675,420
<p>If you use a library like <a href="http://click.pocoo.org" rel="nofollow">click</a> for making your CLI you will get this mostly for free <a href="http://click.pocoo.org/5/bashcomplete/" rel="nofollow">http://click.pocoo.org/5/bashcomplete/</a></p>
0
2016-09-24T10:37:54Z
[ "python", "readline" ]
I am trying to find the nth binary palindrome
39,675,412
<p><a href="https://oeis.org/A006995" rel="nofollow">Binary palindromes: numbers whose binary expansion is palindromic.</a> <br> Binary Palindrome -> is a number whose binary representation is a palindrome. <br> <a href="http://ideone.com/CfQZuH" rel="nofollow">Here is link to the solution with naive approach</a></p> ...
-2
2016-09-24T10:37:04Z
39,676,510
<p>Here's a fairly straight-forward implementation of the recursive algorithm given at <a href="https://oeis.org/A006995" rel="nofollow">A006995</a>.</p> <p>To make it more efficient I use bit shifting to perform binary exponentiation: when <code>x</code> is a non-negative integer, <code>1 &lt;&lt; x</code> is equival...
3
2016-09-24T12:47:05Z
[ "python", "algorithm", "binary", "palindrome" ]
I am trying to find the nth binary palindrome
39,675,412
<p><a href="https://oeis.org/A006995" rel="nofollow">Binary palindromes: numbers whose binary expansion is palindromic.</a> <br> Binary Palindrome -> is a number whose binary representation is a palindrome. <br> <a href="http://ideone.com/CfQZuH" rel="nofollow">Here is link to the solution with naive approach</a></p> ...
-2
2016-09-24T10:37:04Z
39,689,086
<p>I am not going to write the full code. Let us exam the algorithm</p> <p>These columns are : bit count , combinations, combinations count</p> <ul> <li>1 1 | 1 </li> <li>2 11 | 1</li> <li>3 101 111 | 2</li> <li>4 1001 1001 | 2</li> <li>5 10001 10101 11011 11111 |4</li> <li>6 100001 101101 110011 11...
1
2016-09-25T16:19:55Z
[ "python", "algorithm", "binary", "palindrome" ]
how to decode a string containing Persian/Arabic characters?
39,675,421
<p>In web scraping sometimes I need to get data from Persian webpages, so when I try to decode it and see the extracted data, the result is not what I expect to be.</p> <p>Here is the step-by-step code for when this problem occurs :</p> <p><strong>1.getting data from a Persian website</strong></p> <pre><code>import ...
-1
2016-09-24T10:37:56Z
39,676,207
<p>Instead of encoding into ascii, you should decode into something else, for example <code>utf-8</code>:</p> <pre><code>final = data.decode(chardet.detect(data)['encoding']).encode('utf-8') </code></pre> <p>In order to view it though, you should write it into a file as most terminals do not display non-ascii chars c...
0
2016-09-24T12:13:37Z
[ "python", "python-2.7", "decode", "python-unicode" ]
how to decode a string containing Persian/Arabic characters?
39,675,421
<p>In web scraping sometimes I need to get data from Persian webpages, so when I try to decode it and see the extracted data, the result is not what I expect to be.</p> <p>Here is the step-by-step code for when this problem occurs :</p> <p><strong>1.getting data from a Persian website</strong></p> <pre><code>import ...
-1
2016-09-24T10:37:56Z
39,677,019
<p>The fundamental problem is that character-set detection is not a completely deterministic problem. <code>chardet</code>, and every program like it, is a <em>heuristic</em> detector. There is no guarantee or expectation that it will guess correctly all the time, and your program needs to cope with that.</p> <p>If yo...
1
2016-09-24T13:42:31Z
[ "python", "python-2.7", "decode", "python-unicode" ]
python, import module in vs code
39,675,568
<p>I installed cocos2d for python and the samples worked well</p> <p>But when I move the python file into the folder that I selected in the visual studio code, it's only saying that it cannot find the module named cocos. </p> <p>I guess I need to change the setting in the launch.json but I don't know how.</p> <p>I'l...
0
2016-09-24T10:57:09Z
39,713,749
<p>You will need to modify the python.pythonPath setting in settings.json to point to this interpreter as follows: <code> "python.pythonPath":"C:/Users/Sanghun/AppData/Local/Programs/Python/Python35-32/python.exe" </code></p> <p>Or you could just launch the command 'Select Workspace Interpreter' (<a href="https://gith...
0
2016-09-26T23:11:47Z
[ "python", "module", "cocos2d-x", "vscode" ]
How do I use the model Inception.tgz in TensorFlow?
39,675,604
<p>I just downloaded the inception.tgz file from tensorflow.org at <a href="http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz" rel="nofollow">http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz</a>. But, I do not know where I should extract this. </p> <p>Also, when...
0
2016-09-24T11:02:10Z
39,678,707
<p>By default the image model gets downloaded to /tmp/imagenet, but you can set your own folder by passing in the <code>--model_dir</code> command line parameter to classify_image.py: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/imagenet/classify_image.py#L56" rel="nofollow">htt...
0
2016-09-24T16:48:15Z
[ "python", "tensorflow" ]
How do I use the model Inception.tgz in TensorFlow?
39,675,604
<p>I just downloaded the inception.tgz file from tensorflow.org at <a href="http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz" rel="nofollow">http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz</a>. But, I do not know where I should extract this. </p> <p>Also, when...
0
2016-09-24T11:02:10Z
39,678,736
<p>I cannot make a comment to your Question since I do not have enough credits yet. So let me give you a generic answer.</p> <ol> <li><p>The <code>inception-2015-12-05.tgz</code> file you mentioned contains two files which you require:</p> <p>a) imagenet_comp_graph_label_strings.txt</p> <p>b) tensorflow_inception_gr...
0
2016-09-24T16:51:00Z
[ "python", "tensorflow" ]
How can I advance the index of a pandas.dataframe by one quarter?
39,675,716
<p>I would like to shift the index of a pandas.dataframe by one quarter. The dataframe looks like:</p> <pre><code> ID Nowcast Forecast 1991-01-01 35 4144.70 4137.40 1991-01-01 40 4114.00 4105.00 1991-01-01 60 4135.00 4130.00 .... </code></pre> <p>So far, I calculate the number of occu...
1
2016-09-24T11:17:16Z
39,680,495
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects" rel="nofollow">pd.DateOffset()</a>:</p> <pre><code>In [110]: df Out[110]: ID Nowcast Forecast 1991-01-01 35 4144.7 4137.4 1991-01-01 40 4114.0 4105.0 1991-01-01 60 4135.0 4130.0 In [...
1
2016-09-24T20:08:42Z
[ "python", "pandas" ]
We changed order for a list, now we need a mechanism for accessing elements by index with matching behaviour
39,675,758
<p>There is a class BaseFormSet. </p> <pre><code>class BaseFormSet(object): def __iter__(self): return iter(self.forms) def __getitem__(self, index): return self.forms[index] </code></pre> <p>Where self.forms is a list. In the documentation they tell us that this class represents a set of for...
0
2016-09-24T11:21:20Z
39,675,818
<p>I'm having trouble understanding your question, but if you mean that you <em>want</em> to raise an exception from your "reversed" indices, then you need to change your <code>get_reversed_index</code> function.</p> <p>Currently, the output of this function is guaranteed to be in the range <code>[0, length)</code> du...
0
2016-09-24T11:29:38Z
[ "python" ]
How do coroutines in Python compare to those in Lua?
39,675,844
<p>Support for coroutines in Lua is provided by <a href="https://www.lua.org/manual/5.3/manual.html#2.6">functions in the <code>coroutine</code> table</a>, primarily <code>create</code>, <code>resume</code> and <code>yield</code>. The developers describe these coroutines as <a href="http://laser.inf.ethz.ch/2012/slides...
15
2016-09-24T11:32:53Z
39,788,063
<p>I just had my first look at <code>lua</code>, which included the <a href="https://www.lua.org/cgi-bin/demo?sieve" rel="nofollow"><code>sieve.lua</code> live demo</a>. It is an implementation of the sieve of Erathostenes using coroutines. My immediate thought was: This would look much cleaner in python:</p> <pre><co...
0
2016-09-30T09:22:58Z
[ "python", "asynchronous", "lua", "async-await", "coroutine" ]
How do coroutines in Python compare to those in Lua?
39,675,844
<p>Support for coroutines in Lua is provided by <a href="https://www.lua.org/manual/5.3/manual.html#2.6">functions in the <code>coroutine</code> table</a>, primarily <code>create</code>, <code>resume</code> and <code>yield</code>. The developers describe these coroutines as <a href="http://laser.inf.ethz.ch/2012/slides...
15
2016-09-24T11:32:53Z
39,879,949
<p>The simple answer is that they are different languages. Yes, Python coroutines are stackful, first-class and asymmetric. See this answer: <a href="http://stackoverflow.com/q/715758/584846">Coroutine vs Continuation vs Generator</a></p> <p>From the Lua <a href="https://www.lua.org/pil/9.1.html" rel="nofollow">docu...
1
2016-10-05T17:07:32Z
[ "python", "asynchronous", "lua", "async-await", "coroutine" ]
Is python += string concatenation bad practice?
39,675,898
<p>I am reading <a href="http://docs.python-guide.org/en/latest/writing/structure/#mutable-and-immutable-types" rel="nofollow">The Hitchhiker’s Guide to Python</a> and there is a short code snippet </p> <pre><code>foo = 'foo' bar = 'bar' foobar = foo + bar # This is good foo += 'ooo' # This is bad, instead you sh...
2
2016-09-24T11:37:39Z
39,680,089
<h2>Is it bad practice?</h2> <p>It's reasonable to assume that it isn't bad practice for this example because:</p> <ul> <li>The author doesn't give any reason. Maybe it's just disliked by him/her.</li> <li>Python documentation doesn't mention it's bad practice (from what I've seen).</li> <li><code>foo += 'ooo'</code>...
3
2016-09-24T19:21:58Z
[ "python", "string", "string-concatenation" ]
Regex Python not working correctly
39,675,984
<p>Hy, I have an issue with regex python 3.</p> <p><strong>Here is my code :</strong></p> <pre><code># Here is regex 1, have to find tk_common on file tmp/out-file.txt regex1 = re.compile(r'tk_common') with open("tmp/out-file.txt") as f: for line in f: result = regex1.search(line) # If fo...
0
2016-09-24T11:47:08Z
39,676,080
<pre><code>if regex1.search is not None: </code></pre> <p>Should be <code>result</code></p> <pre><code>if result is not None </code></pre> <p>Because <code>re.compile().search</code> is a function, and most definitely not <code>None</code>. You want to look at the return value.</p> <p>Also, your loop</p> <pre><cod...
0
2016-09-24T11:58:24Z
[ "python", "python-3.x" ]
Regex Python not working correctly
39,675,984
<p>Hy, I have an issue with regex python 3.</p> <p><strong>Here is my code :</strong></p> <pre><code># Here is regex 1, have to find tk_common on file tmp/out-file.txt regex1 = re.compile(r'tk_common') with open("tmp/out-file.txt") as f: for line in f: result = regex1.search(line) # If fo...
0
2016-09-24T11:47:08Z
39,676,090
<p>This line:</p> <pre><code>if regex1.search is not None: </code></pre> <p>will never be <code>None</code> because <code>regex1.search</code> refers to the <code>search</code> method, not to the return value of that method. Therefore your code always thinks that there is a match.</p> <p>I think that you meant to ch...
1
2016-09-24T11:59:07Z
[ "python", "python-3.x" ]
Different functions return the same item from a Python dictionary
39,676,159
<pre><code>import json, os def load_data(filepath): if not os.path.exists(filepath): return None with open(filepath, 'r') as file: return json.load(file) def get_biggest_bar(data): bars = [] for bar in data: bars.append((bar['Cells']['SeatsCount'] , bar['Number'])) max_numb...
0
2016-09-24T12:07:56Z
39,676,831
<p>You are using a generator to get item, but on the next line that variable is not what you think it is. Item from inside the generator is out of scope. I would prefer to return the actual generated value. Also, you are getting the closest bar to some point, but not the one you passed into the function.</p> <p>Thus I...
2
2016-09-24T13:26:14Z
[ "python", "dictionary" ]
Different functions return the same item from a Python dictionary
39,676,159
<pre><code>import json, os def load_data(filepath): if not os.path.exists(filepath): return None with open(filepath, 'r') as file: return json.load(file) def get_biggest_bar(data): bars = [] for bar in data: bars.append((bar['Cells']['SeatsCount'] , bar['Number'])) max_numb...
0
2016-09-24T12:07:56Z
39,676,867
<p>Assign the result of the call to <code>__next__()</code> before returning it, like this:</p> <pre><code>result = (item for item in data if item['Number'] == closest_bar).__next__() return result, closest_bar </code></pre>
2
2016-09-24T13:29:14Z
[ "python", "dictionary" ]
Different functions return the same item from a Python dictionary
39,676,159
<pre><code>import json, os def load_data(filepath): if not os.path.exists(filepath): return None with open(filepath, 'r') as file: return json.load(file) def get_biggest_bar(data): bars = [] for bar in data: bars.append((bar['Cells']['SeatsCount'] , bar['Number'])) max_numb...
0
2016-09-24T12:07:56Z
39,677,868
<p>Answers what went wrong have been given. Im my opinion the code searching for min and max was not "pythonic". I'd like to suggest another approach:</p> <p>(Using sample data from Kenny Ostrom's answer)</p> <pre><code>data = [ {'Number': 10, 'Cells': {'SeatsCount': 10, 'geoData': {'coordinates': (10, 10)}}}, ...
2
2016-09-24T15:12:24Z
[ "python", "dictionary" ]
Looping over files and plotting (Python)
39,676,294
<p>My data is look like as in the picture. All of my datas are in .txt format and my aim is to loop over files and plot them. First row represents my variables (WL, ABS, T%) so firstly I need to delete them before proceeding. </p> <pre><code>with open('Desktop/100-3.txt', 'r') as f: data = f.read().splitlines(True) w...
0
2016-09-24T12:23:01Z
39,676,484
<p>For data files like this I would prefer <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow">np.genfromtxt</a> over np.loadtxt, it has many useful options you can look up in the docs. The <a href="https://docs.python.org/3/library/glob.html" rel="nofollow">glob</a> modul...
1
2016-09-24T12:44:27Z
[ "python", "numpy", "plot" ]
Indexing dataframe by datetime python ignoring hour, minutes, seconds
39,676,328
<p>I have a pandas dataframe <code>df1</code> like the following, where the left hand column is in datetime index:</p> <pre><code>2016-08-25 19:00:00 144.784598 171.696834 187.392857 2016-08-25 20:30:00 144.837891 171.800840 187.531250 2016-08-25 22:00:00 144.930882 171.982199 187.806134 2016-08-25 23:30:00 ...
0
2016-09-24T12:26:50Z
39,676,415
<p>You can use strings to slice a datetime index:</p> <pre><code>df.loc['2016-08-30':'2016-08-31'] Out: 1 2 3 2016-08-30 01:00:00 144.613005 171.620593 188.083008 2016-08-30 02:30:00 144.532600 171.503879 187.901940 2016-08-30 04:00:00 144.600160 171.569375 1...
1
2016-09-24T12:37:00Z
[ "python", "datetime", "pandas", "dataframe" ]
Group data into classes with numpy
39,676,339
<p>I have a data frame <code>df</code> from which I extract a column <code>mpg</code>.</p> <p>I want to add class label/names to each row based on the value of <code>mpg</code>.</p> <p>I have done it with</p> <pre><code>mpg = df.iloc[:,0] median = np.percentile(mpg, q=50) upper_quartile = np.percentile(mpg, q=75) l...
0
2016-09-24T12:28:29Z
39,676,984
<p>Seems like you are looking for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow">pd.qcut</a>:</p> <pre><code>pd.qcut(df.iloc[:, 0], [0, 0.25, 0.5, 0.75, 1], [0, 1, 2, 3]) Out: 0 1 1 0 2 1 3 0 4 0 5 0 6 0 ... </code></pre> <p>The firs...
3
2016-09-24T13:40:28Z
[ "python", "pandas", "numpy", "dataframe" ]
Setting a cookie in a Django view
39,676,353
<p>I am trying to set a cookie in a view using the following code.</p> <pre><code>def index(request): resp = HttpResponse("Setting a cookie") resp.set_cookie('name', 'value') if 'name' in request.COOKIES: print "SET" else: print "NOT SET" return render(request, 'myapp/base.html', {}...
0
2016-09-24T12:30:28Z
39,676,378
<p>You're creating a response and setting a cookie on it, but then you don't actually do anything with that response. The <code>render</code> shortcut creates its own response which is the one actually sent back to the browser.</p> <p>You should capture the return value from render, and set the cookie on that:</p> <p...
2
2016-09-24T12:32:42Z
[ "python", "django", "cookies" ]
Retrieving comments (disqus) embedded in another web page with python
39,676,407
<p>I'm scrapping a web site using python 3.5 (Beautifulsoup). I can read everything in the source code but I've been trying to retrieve the embedded comments from disqus with no success (which is a reference to a script).</p> <p>The piece of the html code source looks like this:</p> <pre><code>var disqus_identifier =...
0
2016-09-24T12:35:46Z
39,705,046
<p>So, you can construct the Disqus API by studying its network traffic; in the page source all required data are present. Like Disqus API send some query string. Recently I have extracted comments from Disqus API, here is the sample code.</p> <p>Example: Here soup - page source and <code>params_dict = json.loads(str...
0
2016-09-26T14:04:44Z
[ "javascript", "python", "web-scraping", "pyv8" ]
Retrieving comments (disqus) embedded in another web page with python
39,676,407
<p>I'm scrapping a web site using python 3.5 (Beautifulsoup). I can read everything in the source code but I've been trying to retrieve the embedded comments from disqus with no success (which is a reference to a script).</p> <p>The piece of the html code source looks like this:</p> <pre><code>var disqus_identifier =...
0
2016-09-24T12:35:46Z
39,720,555
<p>For Facebook embedded comments,you may use Facebook's graph api to extract the comments in json format.</p> <p>Example-</p> <p>Facebook comments - <code>https://graph.facebook.com/comments/?ids= "link of page"</code></p>
0
2016-09-27T09:07:03Z
[ "javascript", "python", "web-scraping", "pyv8" ]
How to have maximum characters in a text widget
39,676,423
<p>I do not understand how to have a maximum of 4 charachters allowed in the text widget. At the moment, when the buttons are pressed an infinite amount of numbers are shown in the text widget. Example: 123456 but i only want 1234 for this case to be shown.</p> <p>Also if possible how do you change the size of the win...
-2
2016-09-24T12:37:57Z
39,676,561
<p>Based on "how to have a maximum of 4 charachters allowed": you need to have a validation in your program:<br/> Assuming that you only want integer numbers in the range of [1-4] (1, 2, 3, 4):</p> <pre><code>from tkinter import * root = Tk() def valFunc(txt): if len(txt) &lt;= 4: try: txt = i...
1
2016-09-24T12:54:46Z
[ "python", "tkinter" ]
Determinant of a (large) 1554 x 1554 matrix in Python
39,676,437
<p>I need to calculate the determinant of a large 1554,1554 matrix of values with single precision in python. In doing so I encounter a runtime warning:</p> <pre><code>import numpy as np from numpy import linalg as LA a = np.random.random((1554, 1554)) b = np.random.random((1554, 1554)) c = np.dot(a,b) det = LA.d...
2
2016-09-24T12:38:51Z
39,676,766
<p>You can use this relation: <a href="https://wikimedia.org/api/rest_v1/media/math/render/svg/f6404a766d86e9d78a5c4f82e05de37469a5f8e9" rel="nofollow">https://wikimedia.org/api/rest_v1/media/math/render/svg/f6404a766d86e9d78a5c4f82e05de37469a5f8e9</a></p> <p>from <a href="https://en.wikipedia.org/wiki/Determinant#Pro...
2
2016-09-24T13:19:13Z
[ "python", "numpy", "matrix" ]
Trigonometry: sin(x) getting negative value
39,676,531
<p>I am trying to solve a homework: I am required to write a program which will calculate the length of a ladder based on two inputs, that is the desired height to be reached and the angle created by leaning the ladder toward the wall.</p> <p>I used the following formula to convert degrees to radians :</p> <pre><code...
-1
2016-09-24T12:50:37Z
39,676,565
<p>You never used <code>radians</code> after you calculate it. </p> <p>i.e. <code>length = h / math.sin(radians)</code></p>
1
2016-09-24T12:54:55Z
[ "python" ]
Trigonometry: sin(x) getting negative value
39,676,531
<p>I am trying to solve a homework: I am required to write a program which will calculate the length of a ladder based on two inputs, that is the desired height to be reached and the angle created by leaning the ladder toward the wall.</p> <p>I used the following formula to convert degrees to radians :</p> <pre><code...
-1
2016-09-24T12:50:37Z
39,676,618
<p>To make crickt_007's right answer absolutely clear: <code>radians</code> which you did not use after you calculate it should be the argument of the sine:</p> <pre><code>length = h / math.sin(radians) </code></pre>
0
2016-09-24T13:02:22Z
[ "python" ]
Trigonometry: sin(x) getting negative value
39,676,531
<p>I am trying to solve a homework: I am required to write a program which will calculate the length of a ladder based on two inputs, that is the desired height to be reached and the angle created by leaning the ladder toward the wall.</p> <p>I used the following formula to convert degrees to radians :</p> <pre><code...
-1
2016-09-24T12:50:37Z
39,676,734
<p>you calculate <code>radians</code>,thats ok,but problem is you never used that <code>radians</code> value. i think your code must be changed as follows :)</p> <pre><code>def main(): import math print("this program calculates the length of a ladder after you give the height and the angle") h = eval(...
0
2016-09-24T13:16:14Z
[ "python" ]
Adding API to Usage Plan using Serverless Framework
39,676,532
<p>My <code>serverless.yaml</code> file is as follows:</p> <pre><code>service: aws-python provider: name: aws runtime: python2.7 stage: beta region: us-east-1 package: include: - deps - functions - lib functions: hello: handler: functions/handler.function_handler events: - http...
-1
2016-09-24T12:50:40Z
39,706,966
<p>As mentioned in comments, Serverless doesn't support this by default. You should look to add the appropriate resources to your CloudFormation template as a custom resource or create it using the AWS CLI or another SDK.</p>
1
2016-09-26T15:38:38Z
[ "python", "amazon-web-services", "aws-api-gateway", "serverless-framework" ]
Adding API to Usage Plan using Serverless Framework
39,676,532
<p>My <code>serverless.yaml</code> file is as follows:</p> <pre><code>service: aws-python provider: name: aws runtime: python2.7 stage: beta region: us-east-1 package: include: - deps - functions - lib functions: hello: handler: functions/handler.function_handler events: - http...
-1
2016-09-24T12:50:40Z
39,721,244
<p>Used the AWS CLI with the following command</p> <pre><code>aws apigateway update-usage-plan --usage-plan-id &lt;PLAN_ID&gt; --patch-operations op=add,path=/apiStages,value=&lt;API_ID&gt;:&lt;API_STAGE&gt; </code></pre>
0
2016-09-27T09:39:18Z
[ "python", "amazon-web-services", "aws-api-gateway", "serverless-framework" ]
RSA Python & Extended Euclidean algorithm to generate the private key. Variable is None
39,676,595
<p>Problem with simple <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)" rel="nofollow"><strong>RSA</strong></a> encryption algorithm. <a href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm" rel="nofollow"><strong>Extended Euclidean algorithm</strong></a> is used to generate the <strong>private ke...
0
2016-09-24T12:59:05Z
39,676,638
<p>Well I'm not sure about the algorithm itself, and can't tell if you if it's wrong or right, but you only return a value from <code>multiplicative_inverse</code> function when <code>if temp_phi == 1</code>. Otherwise, the result is None. So I bet your <code>temp_phi != 1</code> when you run the function. There's prob...
1
2016-09-24T13:04:22Z
[ "python", "python-3.x", "encryption", "rsa", "private-key" ]
RSA Python & Extended Euclidean algorithm to generate the private key. Variable is None
39,676,595
<p>Problem with simple <a href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)" rel="nofollow"><strong>RSA</strong></a> encryption algorithm. <a href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm" rel="nofollow"><strong>Extended Euclidean algorithm</strong></a> is used to generate the <strong>private ke...
0
2016-09-24T12:59:05Z
39,676,651
<p>I think that this is a problem:</p> <pre><code>if temp_phi == 1: return d + phi </code></pre> <p>This function return some value only under condition that temp_phi is equal to 1, otherwise it will not return any value.</p>
1
2016-09-24T13:06:21Z
[ "python", "python-3.x", "encryption", "rsa", "private-key" ]
generating pi in python
39,676,676
<p>I would like to know how to adapt this code to give me X digits of pi when asked because right now it just prints a random amount</p> <pre><code>while True: print("how many digits of pi would you like") def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 number = int(input()) for j ...
1
2016-09-24T13:09:08Z
39,676,694
<pre><code>print('{:.xf}'.format(math.pi)) </code></pre> <p>Where <code>x</code> is the number of digits of pi you want to print after the decimal.</p> <p>EDIT:</p> <p>IF you want to do it you way then</p> <pre><code>big_string = ''.join(my_array[:x]) </code></pre> <p>Where x is the number of <em>characters</em> i...
1
2016-09-24T13:11:49Z
[ "python", "python-3.x", "pi" ]
generating pi in python
39,676,676
<p>I would like to know how to adapt this code to give me X digits of pi when asked because right now it just prints a random amount</p> <pre><code>while True: print("how many digits of pi would you like") def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 number = int(input()) for j ...
1
2016-09-24T13:09:08Z
39,677,340
<p>full code if interested</p> <p>while True: print("how many digits of pi would you like")</p> <pre><code>def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 for j in range(1000): if 4 * q + r - t &lt; m * t: yield m q, r, t, k, m, x = 10 * q, 10 * (r - m * t), t, k, (10 * ...
0
2016-09-24T14:18:22Z
[ "python", "python-3.x", "pi" ]
Django Apps aren't loaded yet Celery Tasks
39,676,684
<p>What is giving the error below? I'm unsure if this is a problem with an app I have installed or one of mine. The exception below is generated only when running Celery i.e. <code>celery -A demo.apps.wall.tasks worker</code> , runserver does not generate any errors. Which app ios the issue?</p> <pre><code>Traceback (...
0
2016-09-24T13:10:28Z
39,676,957
<p>Ok - after posting your celery app files I compared to what I have and tried running. <em>Think</em> I found your issue - it looks like you're calling tasks.py in <code>celery -A demo.apps.wall.tasks</code>.</p> <p>If your wall module contains celery.py, and tasks.py - you should call <code>celery -A demo.apps.wall...
1
2016-09-24T13:37:50Z
[ "python", "django", "celery" ]
Django Apps aren't loaded yet Celery Tasks
39,676,684
<p>What is giving the error below? I'm unsure if this is a problem with an app I have installed or one of mine. The exception below is generated only when running Celery i.e. <code>celery -A demo.apps.wall.tasks worker</code> , runserver does not generate any errors. Which app ios the issue?</p> <pre><code>Traceback (...
0
2016-09-24T13:10:28Z
39,676,979
<p>Try adding this to the beginning of <code>tasks.py</code>:</p> <pre><code>import django django.setup() </code></pre>
0
2016-09-24T13:39:49Z
[ "python", "django", "celery" ]
Can't get Aptana Studio 3 to run Python code as PyDev
39,676,686
<p>I just installed Aptana Studio to start and learn to code in Python. However, even my Hello World doesn't run, beacuse I run it in PyDev mode, as suggested. </p> <p>I use Python 3.5.2, and I have configured the interpreter. If I click onto "run", all it gives me is this: <a href="http://i.stack.imgur.com/sxRcr.jpg"...
0
2016-09-24T13:10:40Z
39,689,547
<p>The PyDev version included with Aptana Studio 3 is pretty ancient. Please consider getting either LiClipse (<a href="http://liclipse.com" rel="nofollow">http://liclipse.com</a>) which has PyDev builtin or get the latest Eclipse and install PyDev in it (following instructions from: <a href="http://www.pydev.org/downl...
0
2016-09-25T17:06:42Z
[ "python", "pydev", "aptana" ]
Python getting xml same childnodes in same line
39,676,815
<h2>I have a xml file as:</h2> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;SetupConf&gt; &lt;LocSetup&gt; &lt;Src&gt; &lt;Dir&gt;C:\User1\test1&lt;/Dir&gt; &lt;Dir&gt;C:\User2\log&lt;/Dir&gt; &lt;Dir&gt;D:\Users\Checkup&lt;/Dir&gt; &lt;Dir&gt;D:\Work1&lt;/Dir&gt; &...
0
2016-09-24T13:23:55Z
39,676,862
<p>I presume you are trying to store the string so use <em>str.join</em>:</p> <pre><code>output = ",".join([a.childNodes[0].nodeValue for node in Src for a in node.getElementsByTagName('Dir')]) </code></pre> <p>You could add a trailing comma after the print so you don't get a newline printed after each<code>print dir...
0
2016-09-24T13:28:45Z
[ "python", "xml" ]
How can I create a new url in a Django app?
39,676,866
<p>I have implemented a model in a Django app and I would like add an url to handle the view for this model. </p> <pre><code>class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(defau...
-2
2016-09-24T13:29:05Z
39,677,139
<p>I would recommend the Django tutorial as well: <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/1.10/intro/tutorial01/</a></p> <p>However, to answer your question, you could do a setup like this:</p> <p><strong>views.py:</strong></p> <pre><code>fr...
0
2016-09-24T13:56:41Z
[ "python", "django", "url", "view" ]
Django 1.9 Crispy forms 1.6: multiple forms issue
39,676,869
<p>I 'm writing an app in Django 1.9 and installed Crispy forms 1.6 (using bootstrap3 template pack). In that app, I have a profile model, next to the standard User model. Now, I want to allow the users to modify their profile, and I want to display both User fields and Profile fields on one page. The Profile model con...
0
2016-09-24T13:29:33Z
39,937,688
<p>Why you dont create a form as you desire and render fields one by one?</p> <pre><code>&lt;form&gt; {{ pform.avatar|as_crispy_field }} {{ uform.first_name|as_crispy_field }} ... &lt;/form&gt; </code></pre> <p>You may want to initialize forms with different prefixes.</p>
1
2016-10-08T21:45:43Z
[ "python", "django", "forms", "django-crispy-forms" ]
Create a popup widget in IPython
39,676,933
<p>I'm trying to create a Popup widget in Jupyter as described in <a href="https://youtu.be/o7Tb7YhJZR0?t=26m21s" rel="nofollow">this vid</a>: </p> <pre><code>from IPython.html import widgets </code></pre> <p>which gives the following warning: </p> <blockquote> <p>ShimWarning: The <code>IPython.html</code> package...
1
2016-09-24T13:35:56Z
39,679,140
<p>Searching in <a href="https://github.com/ipython/ipython/blob/aa586fd81940e557a1df54ecd0478f9d67dfb6b4/docs/source/whatsnew/version3_widget_migration.rst" rel="nofollow">IPython's repository</a> I found that.. : </p> <blockquote> <p><strong>PopupWidget was removed</strong> from IPython. If you use the PopupWidget...
2
2016-09-24T17:35:32Z
[ "python", "popup", "jupyter", "jupyter-notebook", "ipywidgets" ]
Any way to immediately draw multiple rects/circles in pygame?
39,676,950
<p>Is there any way to draw a lot of circles/rectangles in pygame? I want to draw some objects every frame and I basically have all positions/sizes here ready in a numpy array.</p> <p>Do I really have to run through a slow python <code>for</code>-loop? Doesn't pygame have any optimizations? </p>
-1
2016-09-24T13:37:32Z
39,719,404
<p>Yeah, you do. It shouldn't be too much of a speed issue though: in a previous project I did, drawing up to 400 circles on the screen, every frame, at 60 frames per second, had virtually no lag.</p>
0
2016-09-27T08:08:54Z
[ "python", "pygame" ]
Render series of responses in selenium webdriver
39,676,990
<p>I want to collect a series of responses when navigating a website, and afterwards "recreate" the process <strong>using the responses</strong>.</p> <p>From an <a href="http://stackoverflow.com/questions/36785588/render-http-responsehtml-content-in-selenium-webdriverbrowser">other thread</a> I found this solution to ...
1
2016-09-24T13:40:49Z
39,677,133
<p>You have to account for certain browser-specific things, like the fact that <a href="http://stackoverflow.com/a/9239272/771848"><code>#</code> and <code>%</code> have to be escaped if you use Firefox</a> - from what I understand, you can simply pass the content through <code>quote()</code>:</p> <pre><code>try: ...
1
2016-09-24T13:56:14Z
[ "javascript", "python", "selenium", "selenium-webdriver" ]
Render series of responses in selenium webdriver
39,676,990
<p>I want to collect a series of responses when navigating a website, and afterwards "recreate" the process <strong>using the responses</strong>.</p> <p>From an <a href="http://stackoverflow.com/questions/36785588/render-http-responsehtml-content-in-selenium-webdriverbrowser">other thread</a> I found this solution to ...
1
2016-09-24T13:40:49Z
39,716,670
<p>I found a possible solution, or rather workaround. When saving requests (urls) and responses in a dictionary, you can set up a server that answers each request with its resprective pre-recorded response.</p>
0
2016-09-27T05:32:35Z
[ "javascript", "python", "selenium", "selenium-webdriver" ]
Why is my very simple neural network not doing at all well?
39,677,062
<p>I have created an extremely simple neural network to help my understanding. It has one neuron, and one input, and one weight. The idea is simple: given many random numbers between 0,200, learn that anything over 100 is correct, and under 100 is in correct (instead of just being told). </p> <pre><code>import random ...
0
2016-09-24T13:47:42Z
39,677,251
<p>This is mostly because of this line</p> <p><code> d = random.randint(0,200) </code></p> <p>By the problem itself, you have 50% chances to get the right number (>100). If you increase the maximum value from 200 to 500 as example, you'll get closer to what you want.</p> <p>You need to find a better way to generate ...
-1
2016-09-24T14:08:57Z
[ "python", "machine-learning", "neural-network" ]
Why is my very simple neural network not doing at all well?
39,677,062
<p>I have created an extremely simple neural network to help my understanding. It has one neuron, and one input, and one weight. The idea is simple: given many random numbers between 0,200, learn that anything over 100 is correct, and under 100 is in correct (instead of just being told). </p> <pre><code>import random ...
0
2016-09-24T13:47:42Z
39,677,273
<p>I think your problem here is that you're lacking a bias term. The network you've built is multiplying a positive integer (<code>d</code>) by a weight value, and then comparing the result to see if it's positive or negative. In an ideal universe, what should the value of <code>weight</code> be? If <code>weight</co...
1
2016-09-24T14:11:42Z
[ "python", "machine-learning", "neural-network" ]
Procedure to map all relationships between elements in a list of lists
39,677,070
<p>I'm looking for an algorithm that can map all the relationships between all of the elements in sublists belonging to a list of length <code>n</code>. </p> <p>More concretely, suppose <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> are the names of workers and that e...
2
2016-09-24T13:48:16Z
39,677,393
<p>Pseudo-code algorithm:</p> <pre><code>declare two-dimensional array workers for each shift in shifts_yesterday for each element x in shift add x to workers[x] for each element y != x in shift add y to workers[x] for each list xs in workers print xs[0] + ": " for each element...
1
2016-09-24T14:23:05Z
[ "python", "algorithm", "time-complexity" ]
Procedure to map all relationships between elements in a list of lists
39,677,070
<p>I'm looking for an algorithm that can map all the relationships between all of the elements in sublists belonging to a list of length <code>n</code>. </p> <p>More concretely, suppose <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> are the names of workers and that e...
2
2016-09-24T13:48:16Z
39,677,443
<p>A simplified and more efficient version of your own code using sets to store values and <em>itertools.combinations</em> to pair up the workers:</p> <pre><code>shifts = [['a', 'b', 'c', 'd'], ['b', 'c', 'e', 'f']] from itertools import combinations import collections d = collections.defaultdict(set) for sub in sh...
2
2016-09-24T14:28:36Z
[ "python", "algorithm", "time-complexity" ]
Procedure to map all relationships between elements in a list of lists
39,677,070
<p>I'm looking for an algorithm that can map all the relationships between all of the elements in sublists belonging to a list of length <code>n</code>. </p> <p>More concretely, suppose <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> are the names of workers and that e...
2
2016-09-24T13:48:16Z
39,677,461
<p>There is should be more conditions specified. For instance, if you have a total "shifts_yesterday" array size limited to 64 then you can use long type to store shift-bit for worker. then you can answer on the question via single operation : </p> <pre><code>a = 00000001 b = 00000011 d = 00000010 f = 00000010 ...
1
2016-09-24T14:30:02Z
[ "python", "algorithm", "time-complexity" ]
Procedure to map all relationships between elements in a list of lists
39,677,070
<p>I'm looking for an algorithm that can map all the relationships between all of the elements in sublists belonging to a list of length <code>n</code>. </p> <p>More concretely, suppose <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> are the names of workers and that e...
2
2016-09-24T13:48:16Z
39,677,544
<pre><code>result = defaultdict(set) for shift in shifts: for worker in shift: result[worker].update(shift) # now, result[a] contains: a, b, c, d - so remove the a for k, v in result.iteritems(): v.remove(k) </code></pre>
3
2016-09-24T14:37:57Z
[ "python", "algorithm", "time-complexity" ]
Procedure to map all relationships between elements in a list of lists
39,677,070
<p>I'm looking for an algorithm that can map all the relationships between all of the elements in sublists belonging to a list of length <code>n</code>. </p> <p>More concretely, suppose <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code> and <code>f</code> are the names of workers and that e...
2
2016-09-24T13:48:16Z
39,677,680
<p>I think you're looking for a set membership relationship. Let's call it <code>coworkers</code>:</p> <pre><code>shifts_yesterday = [['a', 'b', 'c', 'd'], ['b', 'c', 'e', 'f']] def coworkers(worker, shifts): coworkers = set() coworkers.update( *[shift for shift in shifts if worker in shift] ) return cowo...
1
2016-09-24T14:52:06Z
[ "python", "algorithm", "time-complexity" ]
Python: Print one or multiple files(copies) on user input
39,677,132
<p>I'm new to Python. I'm trying to create a program that prints set of docs I usually print by hand every week, however I'm running into several problems:</p> <p>Here is the code:</p> <pre><code>import os file_list = os.listdir("C:/Python27/Programs/PrintNgo/Files2print") print ("List of available documents to prin...
1
2016-09-24T13:55:54Z
39,677,350
<p>You should avoid the <code>input</code> function in Python 2. It can be convenient, but it is a security risk. Instead you should use the <code>raw_input</code> function. In Python 3, the function named <code>input</code> is equivalent to Python 2's <code>raw_input</code> and the functionality of the old Python 2 <c...
1
2016-09-24T14:19:01Z
[ "python", "python-2.7" ]
Quickly sampling large number of rows from large dataframes in python
39,677,183
<p>I have a very large dataframe (about 1.1M rows) and I am trying to sample it.</p> <p>I have a list of indexes (about 70,000 indexes) that I want to select from the entire dataframe.</p> <p>This is what Ive tried so far but all these methods are taking way too much time:</p> <p>Method 1 - Using pandas :</p> <pre>...
0
2016-09-24T14:00:44Z
39,677,807
<p>It seems you may benefit from simple <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow">selection methods</a>. We don't have your data, so here is an example of selecting a subset using a pandas <code>Index</code> object and the <code>.iloc</code> selection method.</p> <pre><code>i...
1
2016-09-24T15:06:56Z
[ "python", "pandas", "dataframe", "bigdata", "sampling" ]
Multivariate linear regression in pymc3
39,677,240
<p>I've recently started learning <code>pymc3</code> after exclusively using <code>emcee</code> for ages and I'm running into some conceptual problems. </p> <p>I'm practising with Chapter 7 of <a href="https://arxiv.org/abs/1008.4686" rel="nofollow">Hogg's Fitting a model to data</a>. This involves a mcmc fit to a str...
0
2016-09-24T14:07:56Z
39,685,419
<p>You may try by adapting the following model. Is a "regular" linear regression. But <code>x</code> and <code>y</code> have been replaced by Gaussian distributions. Here I am assuming not only the measured values of the input and output variables but also a reliable estimation of the their error (for example as provid...
1
2016-09-25T09:38:22Z
[ "python", "statistics", "mcmc", "pymc3" ]
python Popen shell=True behavior
39,677,382
<p>Why would this doesn't work: <code>subprocess.Popen(["ls -l | grep myfile"], shell=False)</code> But this line works: <code>subprocess.Popen(["ls -l | grep myfile"], shell=True)</code> I understand this shell=True create a sub shell internally and execute command. But didn't understand how this affect Popen behavior...
0
2016-09-24T14:22:18Z
39,677,446
<p><code>shell=True</code> is used to pass a single <em>string</em> as a command line to a shell. While it's technically possible to pass a list, it's probably never what you want.</p> <pre><code>subprocess.Popen("ls -l | grep myfile", shell=True) </code></pre>
0
2016-09-24T14:28:48Z
[ "python", "python-3.x", "subprocess" ]
python Popen shell=True behavior
39,677,382
<p>Why would this doesn't work: <code>subprocess.Popen(["ls -l | grep myfile"], shell=False)</code> But this line works: <code>subprocess.Popen(["ls -l | grep myfile"], shell=True)</code> I understand this shell=True create a sub shell internally and execute command. But didn't understand how this affect Popen behavior...
0
2016-09-24T14:22:18Z
39,677,485
<p>If you use <code>shell=False</code>, you must be to use like it:</p> <pre><code>subprocess.Popen(["ls","-l"],shell=False) </code></pre>
-1
2016-09-24T14:32:08Z
[ "python", "python-3.x", "subprocess" ]
python Popen shell=True behavior
39,677,382
<p>Why would this doesn't work: <code>subprocess.Popen(["ls -l | grep myfile"], shell=False)</code> But this line works: <code>subprocess.Popen(["ls -l | grep myfile"], shell=True)</code> I understand this shell=True create a sub shell internally and execute command. But didn't understand how this affect Popen behavior...
0
2016-09-24T14:22:18Z
39,677,565
<p>Popen() does the subprocess management with the code inside the subprocess module. It doesn't know about piping with <code>|</code>, and it doesn't know whether the string you pass is a program or an argument, like in your example with <code>ls</code> it will assume that everything else except <code>ls</code> itself...
2
2016-09-24T14:40:58Z
[ "python", "python-3.x", "subprocess" ]
Does not openpyxl.styles have a Style anymore in v2.4.0?
39,677,426
<p>I just upgraded <code>openpyxl</code> to version <code>2.4.0</code> and this code that worked fine in previous versions, doesn't work anymore:</p> <pre><code>style = openpyxl.styles.Style(**style_kwargs) </code></pre> <p>Openpyxl says that it doesn't have a <code>Style</code> attribute:</p> <pre><code>AttributeEr...
-1
2016-09-24T14:26:12Z
39,680,121
<p>The <code>Style</code> class was deprecated several versions ago and has been removed.</p>
1
2016-09-24T19:24:47Z
[ "python", "openpyxl" ]
building datetime from 3 integer/float columns in pandas
39,677,432
<p>After loading a DataFrame with Panda (from a csv) with this structure:</p> <pre><code> startmonth startday startyear endmonth endday endyear caseid 1945121601 12.0 16.0 1945 5.0 27.0 1947.0 194603110...
1
2016-09-24T14:26:54Z
39,678,015
<p>Although not absolutely sure, the issue seems to be that I am trying to feed the parser a pandas Series while they expect only to take string.</p> <p>In this cae, Panda's own to_datetime function can do the work.</p> <pre><code>def dateparser(y=t4.startyear,m=t4.startmonth,d=t4.startday): y = y.astype(str) ...
0
2016-09-24T15:30:09Z
[ "python", "string", "datetime", "pandas" ]
How to keep track of numbered variables made from function call in while loop. How many are there?
39,677,445
<p>So I'm writing a small project using python, But now I'm in trouble.</p> <p>I made some code like this:</p> <pre><code>START_BUTTONS = ("button1", "button2") markup = types.ReplyKeyboardMarkup() lengthof = len(START_BUTTONS) countn = 0 while (countn &lt; lengthof): exec("itembtn" + str(countn) + " = types.Keyboa...
0
2016-09-24T14:28:45Z
39,677,511
<p>You are trying to create numbered variables, which can in all cases be replaced by an array. Try something simple instead:</p> <pre><code>START_BUTTONS = ("button1", "button2") markup = types.ReplyKeyboardMarkup() itembtn = [] for btn in START_BUTTONS: itembtn.append(types.KeyboardButton(btn)) </code></pre> <p>A...
1
2016-09-24T14:34:21Z
[ "python", "python-2.7" ]
Filling holes in image with OpenCV or Skimage
39,677,462
<p>I m trying to fill holes for a chessboard for stereo application. The chessboard is at micro scale thus it is complicated to avoid dust... as you can see :</p> <p><a href="http://i.stack.imgur.com/mCOFl.png" rel="nofollow"><img src="http://i.stack.imgur.com/mCOFl.png" alt="enter image description here"></a></p> <p...
3
2016-09-24T14:30:13Z
39,677,637
<p>You can use following function in order to remove the holes, by replacing the color of each pixel with a maximum colors of it's environment pixels: </p> <pre><code>import numpy as np import cv2 def remove_noise(gray, num): Y, X = gray.shape nearest_neigbours = [[ np.argmax( np.bincount...
2
2016-09-24T14:46:54Z
[ "python", "opencv", "numpy", "scipy", "skimage" ]
Filling holes in image with OpenCV or Skimage
39,677,462
<p>I m trying to fill holes for a chessboard for stereo application. The chessboard is at micro scale thus it is complicated to avoid dust... as you can see :</p> <p><a href="http://i.stack.imgur.com/mCOFl.png" rel="nofollow"><img src="http://i.stack.imgur.com/mCOFl.png" alt="enter image description here"></a></p> <p...
3
2016-09-24T14:30:13Z
39,687,059
<p>You can use morphology: dilate, and then erode with same kernel size. </p>
1
2016-09-25T12:53:07Z
[ "python", "opencv", "numpy", "scipy", "skimage" ]
Python + Sqlite: Add a new column and fill its value at interval of 2
39,677,528
<p>I want to add a new column to a <code>db</code> file and fill its value at an interval of 2. Here I wrote some codes...</p> <pre><code>import sqlite3 WorkingFile = "C:\\test.db" con = sqlite3.connect(WorkingFile) cur = con.cursor() cur.execute("ALTER table MyTable add column 'WorkingID' 'long'") # Add a column "...
0
2016-09-24T14:36:50Z
39,677,628
<p>The SQL engine cannot tell the difference between the rows.</p> <p>You should add an <a href="http://sqlite.org/autoinc.html" rel="nofollow">autoincrement</a> or ROWID column in order to have it set as ID.</p> <p>I do not know the structure of your table as you don't create it here but rather alter it.</p> <p>If ...
1
2016-09-24T14:46:16Z
[ "python", "sqlite" ]
Python + Sqlite: Add a new column and fill its value at interval of 2
39,677,528
<p>I want to add a new column to a <code>db</code> file and fill its value at an interval of 2. Here I wrote some codes...</p> <pre><code>import sqlite3 WorkingFile = "C:\\test.db" con = sqlite3.connect(WorkingFile) cur = con.cursor() cur.execute("ALTER table MyTable add column 'WorkingID' 'long'") # Add a column "...
0
2016-09-24T14:36:50Z
39,677,912
<p>If your table has some unique ID, get a sorted list of them (their actual values do not matter, only their order):</p> <pre><code>ids = [row[0] for row in cur.execute("SELECT id FROM MyTable ORDER BY id")] iCount = 0 for id in ids: iCount += 2 cur.execute("UPDATE MyTable SET WorkingID = ? WHERE id = ?", ...
0
2016-09-24T15:17:01Z
[ "python", "sqlite" ]
Python + Sqlite: Add a new column and fill its value at interval of 2
39,677,528
<p>I want to add a new column to a <code>db</code> file and fill its value at an interval of 2. Here I wrote some codes...</p> <pre><code>import sqlite3 WorkingFile = "C:\\test.db" con = sqlite3.connect(WorkingFile) cur = con.cursor() cur.execute("ALTER table MyTable add column 'WorkingID' 'long'") # Add a column "...
0
2016-09-24T14:36:50Z
39,678,389
<p>If you can't add ID to your table, you can make a really strange way. So.. Before your loop you make a query</p> <pre><code>UPDATE MyTable SET WorkingID = 2 LIMIT 1 </code></pre> <p>And after</p> <pre><code>iCount = 2 for row in rows: iCount = iCount + 2 print iCount cur.execute("UPDATE MyTable SET W...
0
2016-09-24T16:13:06Z
[ "python", "sqlite" ]
Matplotlib - how to rescale pixel intensities for RGB image
39,677,581
<p>I am confused regarding how matplotlib handles fp32 pixel intensities. To my understanding, it rescales the values between max and min values of the image. However, when I try to view images originally in [0,1] by rescaling their pixel intensites to [-1,1] (by im*2-1) using imshow(), the image appears differently co...
0
2016-09-24T14:41:58Z
39,678,117
<p>You are probably using matplotlib wrong here.</p> <p>The normalization-step should work correctly, if it's active. <strong>The <a href="http://matplotlib.org/api/colors_api.html#matplotlib.colors.Normalize" rel="nofollow">docs</a> tell us, that is only active by default, if the input-image is of type float!</strong...
0
2016-09-24T15:41:59Z
[ "python", "image-processing", "matplotlib" ]
Define one SQLAlchemy model to be related to one of multiple other models
39,677,668
<p>I'm designing the database for my own Q&amp;A website, which is somewhat similar to Stack Overflow: </p> <ol> <li>A "question" can have several "answers", but an "answer" has only one "question".</li> <li>Both "questions" and "answers" can have several "comments", but a "comment" has only one "question" or "answer"...
1
2016-09-24T14:50:48Z
39,677,838
<p>So you've already managed the first point.</p> <p>What you're looking for is a generic relationship. You can find it in <a href="https://sqlalchemy-utils.readthedocs.io/en/latest/index.html" rel="nofollow"><code>sqlalchemy_utils</code></a> package.</p> <pre><code>from sqlalchemy_utils import generic_relationship ...
3
2016-09-24T15:09:39Z
[ "python", "sqlalchemy" ]
Define one SQLAlchemy model to be related to one of multiple other models
39,677,668
<p>I'm designing the database for my own Q&amp;A website, which is somewhat similar to Stack Overflow: </p> <ol> <li>A "question" can have several "answers", but an "answer" has only one "question".</li> <li>Both "questions" and "answers" can have several "comments", but a "comment" has only one "question" or "answer"...
1
2016-09-24T14:50:48Z
39,684,299
<p>I suggest you extract a base class for Question and Answer, e.g. Post, and make Comment relate to Post, such that a Post can have multiple Comments.</p> <p>SQLAlchemy ORM supports few strategies to <a href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html" rel="nofollow">implement inheritance in the databa...
2
2016-09-25T07:03:56Z
[ "python", "sqlalchemy" ]
generating pi to more than 2315 places
39,677,809
<p>I have managed to get my code working so it generates pi:</p> <pre><code> while True: print("how many digits of pi would you like?") def make_pi(): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 for j in range(1000000): if 4 * q + r - t &lt; m * t: ...
-1
2016-09-24T15:07:01Z
39,678,014
<p>What about parametrizing that make_pi generator to accept the number of digits?</p> <p>Something like this:</p> <pre><code>def make_pi(num_digits): q, r, t, k, m, x = 1, 0, 1, 1, 3, 3 for j in range(num_digits): if 4 * q + r - t &lt; m * t: yield m q, r, t, k, m, x = 10 * q,...
0
2016-09-24T15:30:06Z
[ "python", "python-3.x", "pi" ]
Are booleans overwritten in python?
39,677,814
<pre><code>def space_check(board, position): return board[position] == ' ' def full_board_check(board): for i in range(1,10): if space_check(board, i): return False return True </code></pre> <p>the last line is return True why not <code>else: return True</code> if the if statemen...
-7
2016-09-24T15:07:37Z
39,677,884
<p>If it was </p> <pre><code>for i in range(1,10): if space_check(board, i): return False else: return True </code></pre> <p>then after the first iteration in the for loop the function would return. This would not lead the the expected behaviour. Currently, you check every space, and not jus...
0
2016-09-24T15:13:29Z
[ "python", "python-3.x" ]
Dataframe filtering in pandas
39,677,851
<p>How can I filter or subset a particular group within a dataframe (e.g., admitted female from the dataframe below)? I am trying to sum up admissions/rejection rates based on gender. This dataframe is small, but what if it was much larger, let's say for example tens of thousands of line, where indexing individual val...
0
2016-09-24T15:10:45Z
39,680,904
<p>To filter the data you can use the very comprehensive <code>query</code>function.</p> <pre><code># Test data df = DataFrame({'Admit': ['Admitted', 'Rejected', 'Admitted', 'Rejected', 'Admitted', 'Rejected', 'Admitted'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male', 'Male', 'Female'], 'Freq'...
1
2016-09-24T20:57:31Z
[ "python", "pandas", "dataframe", "filtering", "subset" ]
idiomatic repeating group file format parsing
39,677,914
<pre><code>repeating_group_field = ['a', 'b', 'c'] ddata = ['l', 'm', 'n', 2, 'a', 'b', 'a', 'c', 'b', 'g', 'h', 2, 'c', 'c', 'l', 2, 'b', 'b'] # output = ['l', 'm', 'n', [['a', 'b'],['a', 'c', 'b']], 'g', 'h', [['c'], ['c']], 'l', 2, [[b], [b]]] def outer(it): last = {'value': None} def rgroup(i, it): ...
0
2016-09-24T15:17:06Z
39,678,251
<p>I doubt there is something clear and simple for such a sophisticated data re-packing procedure.</p> <p>I did a version of this from scratch, but in no way it looks beautiful (though it looks simplier to me).</p> <pre><code>def chew_data(data): def check_type(char): nonlocal inside_group if type...
1
2016-09-24T15:56:44Z
[ "python" ]
Difference between python lambda functions inside class and def
39,677,922
<p>I have the following code.</p> <pre><code>class SomeClass: a = lambda self: self.b() def __init__(self): self.b = lambda self: None s = SomeClass() s.a() </code></pre> <p>It give me "TypeError: () takes exactly 1 argument (0 given)". And I want to understand why. <p>My explanation:</p> <ul> <li...
0
2016-09-24T15:17:41Z
39,678,120
<p>Your problem here is the difference between bound methods and functions</p> <p>Have a simpler example:</p> <pre><code>class Someclass(object): bound = lambda *args: "bound method got {}".format(args) def __init__(self): self.unbound = lambda *args: "function got {}".format(args) </code></pre> <p...
3
2016-09-24T15:42:11Z
[ "python", "oop", "lambda" ]
Python Turtle game, Check not working?
39,677,940
<pre><code>import turtle # Make the play screen wn = turtle.Screen() wn.bgcolor("red") # Make the play field mypen = turtle.Turtle() mypen.penup() mypen.setposition(-300,-300) mypen.pendown() mypen.pensize(5) for side in range(4): mypen.forward(600) mypen.left(90) mypen.hideturtle() # Make the object player ...
0
2016-09-24T15:20:04Z
39,678,576
<p>The problem is that your logic to test if the player has gone out of bounds is at the top level of your code -- it doesn't belong there. You should turn control over to the turtle listener, via <code>mainloop()</code> and handle the bounds detection in one of your callback methods, namely <code>forward()</code>.</p...
0
2016-09-24T16:34:31Z
[ "python", "visual-studio", "if-statement", "turtle-graphics" ]
Python MP3 Player
39,677,957
<p>I Am Trying To Play An MP3 File On Python , But I Can't Find The Right Module! I've Tried This:</p> <pre><code>import os os.startfile('hello.mp3') </code></pre> <p>But I Just Got The <strong>Error</strong>:</p> <pre><code>Traceback (most recent call last): File "/Applications/Youtube/text 2 speech/test.py", lin...
0
2016-09-24T15:21:59Z
39,678,501
<p>You will need to install the <code>vlc.py</code> module from <a href="https://wiki.videolan.org/Python_bindings" rel="nofollow">https://wiki.videolan.org/Python_bindings</a></p> <p>The absolute bare bones for this would be something like:</p> <pre><code>import vlc Inst = vlc.Instance() player = Inst.media_player_n...
0
2016-09-24T16:25:34Z
[ "python", "mp3", "playback" ]
Extract various information
39,677,964
<p><strong>Overview</strong></p> <p>would like to extract various information like name, date and address from a 2 column csv file before writing to another csv file</p> <p><strong>Conditions</strong></p> <ol> <li>Extract <strong>Name</strong> by first row as it will always be the first row. </li> <li>Extract <stron...
0
2016-09-24T15:22:54Z
39,678,472
<p>You can group the sections by <code>ID</code> and from each group you can determine which is the date and which is the address with some simple logic . </p> <pre><code>import csv from itertools import groupby from operator import itemgetter with open("test.csv") as f, open("out.csv", "w") as out: reader = csv....
0
2016-09-24T16:21:55Z
[ "python", "csv" ]
python sampling from different distributions with different probability
39,677,967
<p>I am trying to implement a fucntion which returns 100 samples from three different multivariate gaussian distributions.</p> <p>numpy provides a way to sample from a sinle multivariate gaussian. But I could not find a way to sample from three different multivariate with different sampling probability.</p> <p>My req...
2
2016-09-24T15:23:00Z
39,678,093
<p>Say you create an array of your generators:</p> <pre><code>generators = [ np.random.multivariate_normal([1, 1], [[5, 1], [1, 5]]), np.random.multivariate_normal([0, 0], [[5, 1], [1, 5]]), np.random.multivariate_normal([-1, -1], [[5, 1], [1, 5]])] </code></pre> <p>Now you can create a weig...
3
2016-09-24T15:39:35Z
[ "python", "numpy", "probability", "sampling" ]
!ls in Jupyter notebook (Python 3)
39,678,309
<p>If I use:</p> <pre><code>!ls '/Users/martyn/Documents/rawData' </code></pre> <p>it gives me a list of the files in the required directory.</p> <p>But I want to paramterize this. I tried:</p> <pre><code>pathData = '/Users/martyn/Documents/rawData' !ls pathData </code></pre> <p>But this gives the error:</p> <pre...
0
2016-09-24T16:04:40Z
39,678,425
<p>You probably need</p> <pre><code>!ls {pathData} </code></pre> <p>or</p> <pre><code>!ls $pathData </code></pre>
1
2016-09-24T16:17:32Z
[ "python", "ipython", "jupyter-notebook" ]
python: queue.queue() best practice to set size?
39,678,374
<p>so I have Queue.Queue()</p> <p>i have bunch of producers who puts jobs into that Queue.Queue() and bunch of consumers who pops from the queue</p> <p>1) is there benefit of capping the Queue size vs. not doing so?<br> 2) by not capping the size, does it really not have any size limit? can grow forever?</p> <p>I've...
0
2016-09-24T16:11:31Z
39,678,524
<p>If you don't cap the size, the <code>Queue</code> can grow until you run out of memory. So no size limit is imposed by Python, but your machine still has finite resources.</p> <p>In some applications (probably most), the programmer knows memory consumption can't become a problem, due to the specific character of t...
0
2016-09-24T16:28:09Z
[ "python", "multithreading", "queue" ]
Having trouble installing pyWin32 on my windows 10 operating system based computer
39,678,559
<p><a href="http://i.stack.imgur.com/pkXyV.png" rel="nofollow"><img src="http://i.stack.imgur.com/pkXyV.png" alt=" I tried installing the package in windows command prompt"></a></p> <p>Why will it not install? I thought I followed the correct procedures</p>
-1
2016-09-24T16:32:11Z
39,706,136
<p>Just use bounding quotes for the full path of .whl file.</p> <pre><code>pip install "C:\...full path with spaces\pywin32-...-win_amd64 (1).whl" </code></pre> <p>Of course make sure <code>pip install wheels</code> was run first.</p> <p>Alternative way is using easy_install (not necessary to download the installer ...
0
2016-09-26T14:58:59Z
[ "python", "module", "pywin32", "pyhook" ]
Having a compiling error with Python using PyCharm 4.0.5
39,678,570
<p>The reason for me asking the question here is that I did not find a solution elsewhere. I'm having the following error with my PyCharm 4.0.5 program while trying to run a Python script. It was working fine the one day and when I tried using it this afternoon I got the following error after tying to run a program whi...
0
2016-09-24T16:33:44Z
39,678,668
<p>You must have a python file named <code>os.py</code> which is being imported instead of the "real" os module.</p>
0
2016-09-24T16:43:24Z
[ "python", "pycharm" ]
Uploading empty data to Bigquery using gcloud python
39,678,654
<p>I try to upload a few rows of data using the <a href="https://googlecloudplatform.github.io/google-cloud-python/stable/bigquery-usage.html" rel="nofollow">gcloud python library</a> and don't succeed. Here is the sample code taken from the <a href="https://googlecloudplatform.github.io/google-cloud-python/stable/bigq...
1
2016-09-24T16:42:08Z
39,799,850
<p>Explicitly declaring the schema in your table will help solve this problem. I.e., instead of using <code>table = dataset.table('test_table')</code>, you should use the following:</p> <p><code>left = SchemaField('left', 'STRING', 'REQUIRED') right = SchemaField('right', 'STRING', 'REQUIRED') table = dataset.table('t...
1
2016-09-30T20:47:34Z
[ "python", "google-bigquery", "gcloud-python", "google-cloud-python" ]
How to reinitialize text widget in Tkinter?
39,678,665
<p>I am trying to return the search result of the user in the GUI itself. This is the following code which I am using </p> <pre><code>def printResult(searchResult): global resultsFrame text = Text(resultsFrame) for i in searchResult: text.insert(END,i+'\n') text.pack(side=TOP) </code></pre> <p>where searchResul...
0
2016-09-24T16:43:16Z
39,678,805
<p>Try this:</p> <pre><code>global resultsFrame text = Text(resultsFrame) def printResult(searchResult): for i in searchResult: text.insert(END,i+'\n') ... text.pack(side=TOP) </code></pre> <p>This should solve your issue.</p>
2
2016-09-24T16:58:05Z
[ "python", "python-2.7", "user-interface", "tkinter" ]
Is a python dict comprehension always "last wins" if there are duplicate keys
39,678,672
<p>If I create a python dictionary with a dict comprehension, but there are duplicate keys, am I guaranteed that the last item will the the one that ends up in the final dictionary? It's not clear to me from looking at <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">https://www.python.org/dev/peps/pe...
1
2016-09-24T16:43:35Z
39,678,738
<p>If you mean something like </p> <pre><code>{key: val for (key, val) in pairs} </code></pre> <p>where <code>pairs</code> is an ordered collection (eg, list or tuple) of 2-element lists or tuples then yes, the comprehension will take the collection in order and the last value will "win". </p> <p>Note that if pairs ...
1
2016-09-24T16:51:20Z
[ "python", "dictionary", "duplicates", "dictionary-comprehension" ]
Is a python dict comprehension always "last wins" if there are duplicate keys
39,678,672
<p>If I create a python dictionary with a dict comprehension, but there are duplicate keys, am I guaranteed that the last item will the the one that ends up in the final dictionary? It's not clear to me from looking at <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">https://www.python.org/dev/peps/pe...
1
2016-09-24T16:43:35Z
39,678,945
<p>Last item wins. The best documentation I can find for this is in the <a href="https://docs.python.org/3/reference/expressions.html#dictionary-displays" rel="nofollow">Python 3 language reference, section 6.2.7</a>:</p> <blockquote> <p>A dict comprehension, in contrast to list and set comprehensions, needs two exp...
2
2016-09-24T17:13:24Z
[ "python", "dictionary", "duplicates", "dictionary-comprehension" ]
How to get distinct count of keys along with other aggregations in pandas
39,678,806
<p>My data frame (DF) looks like this </p> <pre><code>Customer_number Store_number year month last_buying_date1 amount 1 20 2014 10 2015-10-07 100 1 20 2014 10 2015-10-09 200 2 20 2014 10 201...
0
2016-09-24T16:58:09Z
39,679,044
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow"><code>groupby.agg</code></a> and supplying the function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofoll...
1
2016-09-24T17:25:43Z
[ "python", "pandas", "group-by", "aggregate" ]
How to add keypress events in event queue for pygame
39,678,811
<p>I have a game made with pygame which runs perfectly okay. I want to create a system which reads keys to press from a file (which will contain codes of keys to press in separate lines) and adds them to the pygame event queue so that the player agent moves on its own without the keys actually being pressed. </p> <p>A...
0
2016-09-24T16:58:41Z
39,681,219
<p>The <a href="http://www.pygame.org/docs/ref/event.html#pygame.event.Event" rel="nofollow">Event object's</a> first argument is its type, which is an integer between <code>pygame.USEREVENT</code> and <code>pygame.NUMEVENTS</code> (24 to 32 exclusive). This is used to identify your event from other events, such as <co...
0
2016-09-24T21:40:55Z
[ "python", "pygame", "keyboard-events" ]
Pandas nested dict to dataframe
39,678,854
<p>I have a simple nested list like this:</p> <pre><code>allFrame= [{'statValues': {'kpi2': 2, 'kpi1': 1}, 'modelName': 'first'},{'statValues': {'kpi2': 4, 'kpi1': 2}, 'modelName': 'second'}, {'statValues': {'kpi2': 3, 'kpi1': 3}, 'modelName': 'third'}] </code></pre> <p>a <code>pd.DataFrame(allFrame)</code> or <code>...
1
2016-09-24T17:03:21Z
39,678,953
<p>Looks like you need to flatten those dicts first.</p> <p>Apply a flattening function on the list first:</p> <pre><code>def flatten_dict(d, prefix='__'): def items(): # A clojure for recursively extracting dict like values for key, value in d.items(): if isinstance(value, dict): ...
1
2016-09-24T17:14:11Z
[ "python", "pandas", "dictionary", "nested" ]
Efficient check if two numbers are co-primes (relatively primes)?
39,678,984
<p>What is the most efficient ("pythonic") way to test/check if two numbers are <strong>co-primes</strong> (relatively prime) in <strong>Python</strong>.</p> <p>For the moment I have this code:</p> <pre><code>def gcd(a, b): while b != 0: a, b = b, a % b return a def coprime(a, b): return gcd(a, b...
1
2016-09-24T17:18:07Z
39,679,114
<p>The only suggestion for improvement might be with your function <code>gcd</code>. Namely, you could use <a href="https://docs.python.org/3/library/math.html#math.gcd" rel="nofollow"><code>gcd</code></a> that's defined in <code>math</code> (for Python <code>3.5</code>) for a speed boost.</p> <p>Defining <code>coprim...
3
2016-09-24T17:32:28Z
[ "python", "algorithm", "python-3.x", "primes", "relative" ]
Python Django Rest Post API without storage
39,679,030
<p>I would like to create a web api with Python and the Django Rest framework. The tutorials that I have read so far incorporate models and serializers to process and store data. I was wondering if there's a simpler way to process data that is post-ed to my api and then return a JSON response without storing any data.<...
0
2016-09-24T17:23:11Z
39,679,125
<p>You can use their generic <a href="http://www.django-rest-framework.org/api-guide/views/" rel="nofollow">APIView</a> class (which doesn't have any attachment to Models or Serializers) and then handle the request yourself based on the HTTP request type. For example:</p> <pre><code>class RetrieveMessages(APIView): ...
1
2016-09-24T17:33:20Z
[ "python", "json", "django", "rest", "web" ]
Read k matrices size nxm from stdin in Python
39,679,049
<p>I need to read k matrices size nxm from stdin in Python. In the first line there must be the number of matrices (k), and then - k descriptions of matrices: in the first line 2 integer numbers for size (n and m) devided by space, then the matrix.</p> <p>Here's an example:</p> <pre><code>2 2 3 4 5 6 3 1 7 4 4 5 3 4 ...
0
2016-09-24T17:26:09Z
39,679,306
<p>You are on a right way. try to break it in simple steps. Basically a n X m matrix is n rows and each row would have m elements (pretty obvious). what if we have n=1 then we have a line in which there would be m element. to take such input we would just </p> <pre><code>matrix = input().split() #read the input mat...
0
2016-09-24T17:53:10Z
[ "python", "matrix", "stdin" ]
Modifying Depth First Search with dictionaries
39,679,149
<p>There are a lot of really good DFS python implementations out there, such as <a href="http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/" rel="nofollow">this one</a>, but none of them include cost. I'd like to be able to record the total cost of a DFS path, but this implementation repres...
0
2016-09-24T17:36:31Z
39,679,444
<p>Looks like <a href="https://networkx.github.io" rel="nofollow">NetworkX</a> is what you are looking for. DFS is included in the package and its graph implementation is what you want. Hope it helps. </p>
0
2016-09-24T18:05:34Z
[ "python", "dictionary", "depth-first-search" ]
How can a class hold an array of classes in django
39,679,167
<p>I have been having trouble using django. Right now, I have a messagebox class that is suppose to hold messages, and a message class that extends it. How do I make it so messagebox will hold messages?</p> <p>Something else that I cannot figure out is how classes are to interact. Like, I have a user that can send mes...
0
2016-09-24T17:38:10Z
39,679,214
<p>You're confusing two different things here. A class can easily have an attribute that is a list which contains instances of another class, there is nothing difficult about that. </p> <p>(But note that there is no way in which a Message should extend MessageBox; this should be composition, not inheritance.)</p> <p>...
3
2016-09-24T17:43:05Z
[ "python", "django" ]
multiple conditions for np.where python pandas
39,679,382
<p>I have the following dataframe:</p> <pre><code>region pop_1 pop_1_source pop_2 pop_2_source pop_3 pop_3_source a 99 x1 84 x2 61 x3 b 64 x1 65 x2 16 x3 c 92 x1 26 x2 6 x3 d 82 x1 60 x2 38 x3 e 45 x1 77 x2 42 x3 </code></pre> <p>I can calculate the highest value fou...
1
2016-09-24T17:59:05Z
39,679,560
<p>I found your question a bit confusing (among other things, <code>df.upper_limit == df['upper_limit']</code> is always true, and your "source" columns are all filled with <code>x1</code> (except for one <code>1x</code> which looks like a typo)). </p> <p>However, it seems like you'd like to find <em>which</em> of the...
1
2016-09-24T18:18:22Z
[ "python", "pandas" ]
Extra newlines in python
39,679,398
<p>I have this python code which is used to give direction to <strong>m</strong> to reach <strong>p</strong>. </p> <p>Here is the code:</p> <pre><code>#!/bin/python def displayPathtoPrincess(n,grid): m = "m" p = "p" for i in range(n): if(m in grid[i]): m_column = grid[i].find(m) ...
0
2016-09-24T18:00:55Z
39,679,450
<p>You are hard-coding a newline after each <code>'DOWN'</code> or <code>'RIGHT'</code> every time you do this:</p> <pre><code> print "DOWN\n"*down_up print "RIGHT\n"*right_left </code></pre> <p>The resulting strings will be <code>'DOWN'</code> or <code>'RIGHT'</code> followed by a newline, the specified numbe...
0
2016-09-24T18:05:58Z
[ "python", "python-2.7" ]
Python scan for WiFi
39,679,421
<p>I was searching for a program that can scan for WiFi networks and print all of the SSIDs. I tried with scapy but I failed. I am using the pyCharm editor. </p> <p>I tried this code:</p> <pre><code>from scapy.all import * from scapy.layers.dot11 import Dot11 def packet_handler(pkt): if pkt.haslayer(Dot1...
0
2016-09-24T18:03:53Z
39,679,678
<p>try <code>pip install wifi</code> then for scanning use</p> <pre><code>from wifi import Cell, Scheme Cell.all('wlan0') </code></pre> <p>This returns a list of Cell objects. Under the hood, this calls iwlist scan and parses the unfriendly output. Each cell object should have the following attributes: ssid, signal, ...
0
2016-09-24T18:33:08Z
[ "python", "wifi", "python-3.5", "scapy", "sniffer" ]
How to load virtual environment for Python on Windows 10 using PowerShell
39,679,423
<p>Following Tyler Butler's <a href="http://www.tylerbutler.com/2012/05/how-to-install-python-pip-and-virtualenv-on-windows-with-powershell/" rel="nofollow">post</a>, I was able to install <code>pip</code>, <code>python</code> and <code>virtualenv</code> to my PowerShell. However, I can only enter a virtual environment...
1
2016-09-24T18:03:55Z
39,682,292
<p>Thanks to the suggestions from: <a href="http://www.voidynullness.net/blog/2014/06/19/install-python-setuptools-pip-virtualenvwrapper-for-powershell-pyside-on-windows/" rel="nofollow">http://www.voidynullness.net/blog/2014/06/19/install-python-setuptools-pip-virtualenvwrapper-for-powershell-pyside-on-windows/</a></p...
0
2016-09-25T00:34:25Z
[ "python", "powershell", "virtualenv" ]
Seaborn visualize groups
39,679,431
<p>How can I plot this data frame using seaborn to show the KPI per model?</p> <pre><code>allFrame = pd.DataFrame({'modelName':['first','second', 'third'], 'kpi_1':[1,2,3], 'kpi_2':[2,4,3]}) </code></pre> <p>Not like <code>sns.barplot(x="kpi2", y="kpi1", hue="mode...
0
2016-09-24T18:04:36Z
39,680,526
<p>Try <code>melt</code>ing the dataframe first, and then you can plot using <code>seaborn</code>:</p> <pre><code>import pandas as pd import seaborn as sns allFrame = pd.DataFrame({'modelName':['first','second', 'third'], 'kpi_1':[1,2,3], 'kpi_2':[2,4,3]}) allFram...
1
2016-09-24T20:11:46Z
[ "python", "plot", "group", "seaborn" ]