title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
session.pop() does not clear cookies
38,304,788
<p>I am new to Flask framework and am playing around with it to learn it better. I am following <a href="https://github.com/realpython/discover-flask" rel="nofollow">this</a> tutorial along my way. </p> <p>As per the <a href="https://www.youtube.com/watch?v=BnBjhmspw4c" rel="nofollow">User Authentication</a> tutorial ...
1
2016-07-11T10:34:38Z
38,305,992
<ol> <li>First of all session and cookie is not the same. Session is more like unique id posted to you browser and something like a key for the dictionary for you backend. So most of the time, when you change session(not session id), you just modify backend part(add or delete values in backend dictionary by that key). ...
1
2016-07-11T11:38:05Z
[ "python", "session", "flask", "session-storage" ]
session.pop() does not clear cookies
38,304,788
<p>I am new to Flask framework and am playing around with it to learn it better. I am following <a href="https://github.com/realpython/discover-flask" rel="nofollow">this</a> tutorial along my way. </p> <p>As per the <a href="https://www.youtube.com/watch?v=BnBjhmspw4c" rel="nofollow">User Authentication</a> tutorial ...
1
2016-07-11T10:34:38Z
38,306,787
<p>You can set the expiry time of cookie to 0, this will make it invalid</p> <pre><code>@app.route('/logout') def logout(): session.pop('token', None) message = 'You were logged out' resp = app.make_response(render_template('login.html', message=message)) resp.set_cookie('token', expires=0) return...
1
2016-07-11T12:21:13Z
[ "python", "session", "flask", "session-storage" ]
Cannot run app pool as service account
38,304,790
<p>I had a Python Flask website that ran fine when I ran the app pool as my own account. When I tried changing this to a service account (which should have permissions), I get the following error</p> <blockquote> <p>HTTP Error 500.0 - Internal Server Error</p> <p>The page cannot be displayed because an internal...
0
2016-07-11T10:34:38Z
38,307,582
<p>FYI after some tinkering, I changed the app pool to run with Managed Pipeline mode of "Classic" instead of "Integrated" and it worked.</p>
0
2016-07-11T12:57:51Z
[ "python", "iis" ]
python/numpy versatile max function
38,304,938
<p>In Python (possibly including numpy) there are various <code>maximum</code>, <code>max</code> and <code>amax</code> functions, which are to some extent covered also in some StackOverflow questions, but none of them seems to solve the rather obvious need of computing <em>the maximum of mixed arguments</em>, i.e. matc...
-1
2016-07-11T10:42:42Z
38,309,052
<p>You can first flatten everything down and compute the max of that:</p> <pre><code>import collections def flatted(data): if isinstance(data, collections.Iterable): for element in data: yield from flatted(data) else: yield data def versatile_max(data, max_function=max): max_f...
0
2016-07-11T14:07:49Z
[ "python", "numpy", "max" ]
Parsing a addition/subtraction/multiplication/division sign from a string
38,304,945
<p>I went through a lesson of creating a simple calculator using Python, and I'm trying to simplify it. The issue is as follows: I know that it is possible to parse a string (number) into a float using "float()", but I'm trying to parse a addition/subtraction/multiplication/division sign from a string into a float or ...
-1
2016-07-11T10:43:16Z
38,304,984
<p>You can use <code>eval</code> in the form eval('1 + 2'), which will give you desired result. You can read more on eval here <a href="https://docs.python.org/2/library/functions.html#eval" rel="nofollow">https://docs.python.org/2/library/functions.html#eval</a></p> <p>but please keep in mind the following statement ...
-1
2016-07-11T10:45:43Z
[ "python", "python-2.7", "python-3.x" ]
Parsing a addition/subtraction/multiplication/division sign from a string
38,304,945
<p>I went through a lesson of creating a simple calculator using Python, and I'm trying to simplify it. The issue is as follows: I know that it is possible to parse a string (number) into a float using "float()", but I'm trying to parse a addition/subtraction/multiplication/division sign from a string into a float or ...
-1
2016-07-11T10:43:16Z
38,305,105
<p>Even though you should be posting the full traceback, the <code>SyntaxError</code> comes from this line:</p> <p><code>operation = user_input_1 float(action) user_input_2</code></p> <p>It is neither a valid Python expression nor a statement. </p> <p>A solution that doesn't involve <code>eval</code>: You can use th...
3
2016-07-11T10:52:39Z
[ "python", "python-2.7", "python-3.x" ]
Parsing a addition/subtraction/multiplication/division sign from a string
38,304,945
<p>I went through a lesson of creating a simple calculator using Python, and I'm trying to simplify it. The issue is as follows: I know that it is possible to parse a string (number) into a float using "float()", but I'm trying to parse a addition/subtraction/multiplication/division sign from a string into a float or ...
-1
2016-07-11T10:43:16Z
38,305,130
<p>In your case this should work :</p> <pre><code>def operation(action): return user_input_1 + action + user_input_2 if user_input == "add": action = actions[0] answer = operation(action) print (eval(answer)) </code></pre> <p>but that's not the best way to do the operations. You can simply <code>add...
1
2016-07-11T10:54:21Z
[ "python", "python-2.7", "python-3.x" ]
Parsing a addition/subtraction/multiplication/division sign from a string
38,304,945
<p>I went through a lesson of creating a simple calculator using Python, and I'm trying to simplify it. The issue is as follows: I know that it is possible to parse a string (number) into a float using "float()", but I'm trying to parse a addition/subtraction/multiplication/division sign from a string into a float or ...
-1
2016-07-11T10:43:16Z
38,315,786
<p>I do not recommend using <strong>eval()</strong> however; setting some rules won't hurt using eval(). This is really basic calculator and its easy to understand. </p> <pre><code>allowed_characters = "0123456789+-/*= " print(""" Basic calculator application. Operators: + addition - subtraction * mu...
0
2016-07-11T20:36:53Z
[ "python", "python-2.7", "python-3.x" ]
When tested http POST with chrome POSTMAN, it doesn't work in django
38,305,269
<p>I use <code>Django 1.9.7 &amp; Python 3.5</code></p> <p>I implement creating user mechanism and tried to test with POSTMAN(chrome application), but it doesn't work and it shows something like belows:</p> <pre><code>Forbidden (CSRF cookie not set.): /timeline/user/create/ </code></pre> <p>This is the code :</p> <...
0
2016-07-11T11:01:42Z
38,305,872
<p>You should put <code>CSRFToken</code> in request headers.<br> After sending request via postman, look at the response <code>Cookies</code> section, take csrftoken value and put in <code>Headers</code> section of request, like this:<br> key:<code>X-CSRFToken</code><br> value: <code>jSdh6c3VAHgLShLEyTjH2N957qCILqmb #...
0
2016-07-11T11:32:29Z
[ "python", "django", "postman" ]
When tested http POST with chrome POSTMAN, it doesn't work in django
38,305,269
<p>I use <code>Django 1.9.7 &amp; Python 3.5</code></p> <p>I implement creating user mechanism and tried to test with POSTMAN(chrome application), but it doesn't work and it shows something like belows:</p> <pre><code>Forbidden (CSRF cookie not set.): /timeline/user/create/ </code></pre> <p>This is the code :</p> <...
0
2016-07-11T11:01:42Z
38,324,687
<p>for <strong>testing</strong> i used the @csrf_exempt decorator.</p> <pre><code>from django.views.decorators.csrf import csrf_exempt @csrf_exempt def user_view(request, method): ... </code></pre> <p>now you should be able to call this function without the csrf cookie.</p> <p>(last time i tried it, i was using...
0
2016-07-12T09:17:38Z
[ "python", "django", "postman" ]
Merging dataframes using a table
38,305,519
<p>I have a matrix of similarity (which is built as a dataframe):</p> <pre><code>mat = pd.DataFrame(index = df.a.values,columns = df.a.values) mat[:] = [[1,0.2,0.3],[0.7,1,0.6],[0,0.4,1]] id1 id2 id3 id1 1.0 0.2 0.3 id2 0.7 1.0 0.6 id3 0.0 0.4 1.0 </code></pre> <p>And I would like ...
1
2016-07-11T11:13:15Z
38,306,033
<p>Subtract the identity matrix, then use <code>DataFrame.idxmax()</code> to find the index of the largest value in each row.</p> <pre><code>import numpy as np import pandas as pd index = ['id1', 'id2', 'id3'] mat = pd.DataFrame([[1, 0.2, 0.3],[0.7, 1, 0.6],[0, 0.4, 1]], index=index, columns=index)...
2
2016-07-11T11:40:09Z
[ "python", "pandas" ]
Merging dataframes using a table
38,305,519
<p>I have a matrix of similarity (which is built as a dataframe):</p> <pre><code>mat = pd.DataFrame(index = df.a.values,columns = df.a.values) mat[:] = [[1,0.2,0.3],[0.7,1,0.6],[0,0.4,1]] id1 id2 id3 id1 1.0 0.2 0.3 id2 0.7 1.0 0.6 id3 0.0 0.4 1.0 </code></pre> <p>And I would like ...
1
2016-07-11T11:13:15Z
38,306,634
<p>One way is to get rid of the diagonal 1s by subtracting a identity matrix of the same order. If you don't want to do any reassigning or subtracting (I don't see a reason why - probably to practice using many functions in Pandas), I would suggest something like this:</p> <pre><code>def closest(x): return mat.loc[x...
1
2016-07-11T12:11:52Z
[ "python", "pandas" ]
The most efficient way to processing images (mahalanobis distances)
38,305,946
<p>I've written a script based on this <a href="http://www.jennessent.com/arcview/mahalanobis_description.htm" rel="nofollow">description</a>. </p> <p>There are few images as 2D numpy arrays, if images are big, it takes a long time to calculate each values. Is there better way do do this than my solution?</p> <p>Cons...
1
2016-07-11T11:36:14Z
38,306,500
<p>Use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a> to compute the distance between each pair of points from 2 collections of inputs. </p> <pre><code>import numpy as np im...
3
2016-07-11T12:04:50Z
[ "python", "numpy", "image-processing", "mahalanobis" ]
first date of week greater than x
38,306,293
<p>I would like to get the <strong><em>first</em></strong> monday in july that is greater than July 10th for a list of dates, and i am wondering if there's an elegant solution that avoids for loops/list comprehension. Here is my code so far that gives all july mondays greater than the 10th:</p> <pre><code>import panda...
0
2016-07-11T11:54:13Z
38,306,846
<p>IIUC you can do it this way:</p> <p>get list of 2nd Mondays within specified date range</p> <pre><code>In [116]: rng = pd.date_range('1-Jan-1999',last_date, freq='WOM-2MON') </code></pre> <p>filter them so that we will have only those in July with <code>day &gt;= 10</code></p> <pre><code>In [117]: rng = rng[(rng...
1
2016-07-11T12:24:05Z
[ "python", "pandas" ]
Tensorflow TypeError on session.run arguments/output
38,306,330
<p>I'm training a CNN quite similar to the one in <a href="http://stackoverflow.com/questions/37901882/tensorflow-reshaping-a-tensor">this</a> example, for image segmentation. The images are 1500x1500x1, and labels are of the same size.</p> <p>After defining the CNN structure, and in launching the session as in this c...
1
2016-07-11T11:55:58Z
38,310,489
<p>Where you use <code>loss = sess.run(loss)</code>, you redefine in python the variable <code>loss</code>.</p> <p>The first time it will run fine. The second time, you will try to do:</p> <pre><code>sess.run(1.4415792e+2) </code></pre> <p>Because <code>loss</code> is now a float. </p> <hr> <p>You should use diffe...
1
2016-07-11T15:15:07Z
[ "python", "tensorflow", "typeerror" ]
How to compare Specific value of two different tables in django?
38,306,352
<p>I have two tables 'Contact' and other is "Subscriber".. I want to Compare Contact_id of both and want to show only those Contact_id which is present in Contact but not in Subscriber.These two tables are in two different Models.</p>
1
2016-07-11T11:56:42Z
38,306,462
<p>Something like this should work:</p> <pre><code>Contact.objects.exclude( id__in=Subscriber.objects.all() ).values_list('id', flat=True) </code></pre> <p>Note that these are actually two SQL queries. I'm sure there are ways to optimize it, but this will usually work fine.</p> <p>Also, the <code>values_list</co...
1
2016-07-11T12:03:01Z
[ "python", "django", "django-models" ]
How to compare Specific value of two different tables in django?
38,306,352
<p>I have two tables 'Contact' and other is "Subscriber".. I want to Compare Contact_id of both and want to show only those Contact_id which is present in Contact but not in Subscriber.These two tables are in two different Models.</p>
1
2016-07-11T11:56:42Z
38,306,514
<p>I assume you have your model like this:</p> <pre><code>class Subscriber(models.Model): contact = models.ForeignKey(Contact) </code></pre> <p>You can do what you want like this:</p> <pre><code>my_list = Subscriber.objects.filter(contact=None) </code></pre> <p>This retrieves Subscribers which don't have a Cont...
1
2016-07-11T12:05:35Z
[ "python", "django", "django-models" ]
How to get unique from dataframe using pandas?
38,306,478
<p>I have df</p> <pre><code>2016-06-21 06:25:09 upi88@yandex.ru GET HTTP/1.1 Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53 200 application/json 2130 https://edge-chat.facebook.com/pull?channel=p_100006170407238&amp;s...
3
2016-07-11T12:03:56Z
38,306,592
<p>Pandas provides the function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow" title="groupby">groupby</a> for DataFrames, which should be suitable for what you require.</p> <pre><code># Generate dataframe with random values mail = ['alice@foo.com', 'bob@b...
1
2016-07-11T12:09:46Z
[ "python", "pandas" ]
How to get unique from dataframe using pandas?
38,306,478
<p>I have df</p> <pre><code>2016-06-21 06:25:09 upi88@yandex.ru GET HTTP/1.1 Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53 200 application/json 2130 https://edge-chat.facebook.com/pull?channel=p_100006170407238&amp;s...
3
2016-07-11T12:03:56Z
38,307,008
<p>You can first extract the info you need from your dates:</p> <pre><code>df['filtered date'] = [w[:10] for w in df['date']] </code></pre> <p>Then you use a `drop duplicates':</p> <pre><code>output = df[['id','filtered date']].drop_duplicates() </code></pre> <p>You can then reorder your data frame for clarity:</p>...
2
2016-07-11T12:31:53Z
[ "python", "pandas" ]
How to get unique from dataframe using pandas?
38,306,478
<p>I have df</p> <pre><code>2016-06-21 06:25:09 upi88@yandex.ru GET HTTP/1.1 Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53 200 application/json 2130 https://edge-chat.facebook.com/pull?channel=p_100006170407238&amp;s...
3
2016-07-11T12:03:56Z
38,307,297
<p>Here's a one-liner (supposing <code>date</code> and <code>ID</code> as the names of the relevant columns)</p> <pre><code>df.groupby('ID').apply(lambda x: (x['date'].str[:10]).unique()) </code></pre> <p>and its output</p> <pre><code>ID lemuska@mail.ru [2016-06-24, 2016-06-25] upi88@yandex.ru [201...
1
2016-07-11T12:44:50Z
[ "python", "pandas" ]
How to get unique from dataframe using pandas?
38,306,478
<p>I have df</p> <pre><code>2016-06-21 06:25:09 upi88@yandex.ru GET HTTP/1.1 Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53 200 application/json 2130 https://edge-chat.facebook.com/pull?channel=p_100006170407238&amp;s...
3
2016-07-11T12:03:56Z
38,308,243
<p>Let's read your sample data in:</p> <pre><code>import pandas as pd import StringIO df = pd.read_table(StringIO.StringIO("""2016-06-21 06:25:09 upi88@yandex.ru GET HTTP/1.1 Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53 ...
1
2016-07-11T13:28:38Z
[ "python", "pandas" ]
How to call python function from java code without use of jpython
38,306,528
<p>I am trying to call my python code from java code , without use of jpython, as my code contains numpy, scipy and other module which is not available on jpython, more over i want to create a api of my python code for java. </p>
-2
2016-07-11T12:06:26Z
38,306,630
<p>Do you want them to run in two different processes? If yes, then you can consider some inter process communication like socket programming.</p>
-1
2016-07-11T12:11:38Z
[ "java", "python" ]
respond to Apple Events in Python without using pipe characters around keys in dictionary
38,306,769
<p>I use appscript and aemreceive in a py2app bundled Python 2.7 application to accept incoming Apple Events and return my app's output as Apple Events to the external application which communicates with my app.</p> <p>This works quite well, with one exception: When I return a dictionary, the keys are surrounded by pi...
0
2016-07-11T12:20:08Z
38,309,291
<p>Figured out how it works.</p> <p>In my sdef file the properties are defined:</p> <pre><code>&lt;property name="has description" code="ashd" type="boolean" description="Whether the library has an XML description."&gt; &lt;/property&gt; &lt;property name="folder" code="asfd" type="file" description="Directory in whi...
0
2016-07-11T14:19:05Z
[ "python", "appleevents", "appscript" ]
open Openoffice calc using system command using python
38,306,774
<p>I am trying to open calc openoffice in listening mode using python. Earlier i was opening it by typing following command in terminal:</p> <pre><code>C:\Program Files\OpenOffice 4\program\soffice" -calc "-accept=socket,host=localhost,port=2002;urp;"&amp; </code></pre> <p>Now it won't open if I use <code>os.system(c...
-1
2016-07-11T12:20:44Z
38,307,138
<p>Which operating system are you using?</p> <p>Nevertheless, I normally avoid <code>os.system</code> calls and prefer <code>subprocess</code>. Here is the link to the <a href="http://docs.python.org/3.2/library/subprocess.html" rel="nofollow">documentation</a>.</p> <p>As an example:</p> <pre><code>subprocess.check_...
0
2016-07-11T12:37:32Z
[ "python", "openoffice.org" ]
Printing one list side by side repeatedly
38,306,821
<p>I'd like to print a list side by side repeatedly. What basically happens in my program is I take a row of data from a spreadsheet in the <em>for</em> loop and populate the list client = []. I then have a series of <em>if</em> and <em>else</em> statements to determine whether or not to print a value. I then clear cli...
0
2016-07-11T12:22:41Z
38,306,924
<p>I am not sure if I understand your question correctly but you can print side by side as follows:</p> <pre><code>print "one", "two" print "one", print "two" </code></pre> <p>You can also save your data in a pandas dataframe (df) and use:</p> <pre><code>print df </code></pre>
0
2016-07-11T12:28:08Z
[ "python" ]
Printing one list side by side repeatedly
38,306,821
<p>I'd like to print a list side by side repeatedly. What basically happens in my program is I take a row of data from a spreadsheet in the <em>for</em> loop and populate the list client = []. I then have a series of <em>if</em> and <em>else</em> statements to determine whether or not to print a value. I then clear cli...
0
2016-07-11T12:22:41Z
38,307,037
<p>I guess you're looking for this:</p> <pre><code>print('a', end=' ') print('b', end=' ') print('c', end=' ') print('d') print('e', end='.') OUTPUT: a b c d OUTPUT: e. </code></pre> <p>If you don't specify an argument for <strong>end</strong> a new line character will be added after every string you print. You can ...
1
2016-07-11T12:33:16Z
[ "python" ]
Printing one list side by side repeatedly
38,306,821
<p>I'd like to print a list side by side repeatedly. What basically happens in my program is I take a row of data from a spreadsheet in the <em>for</em> loop and populate the list client = []. I then have a series of <em>if</em> and <em>else</em> statements to determine whether or not to print a value. I then clear cli...
0
2016-07-11T12:22:41Z
38,307,062
<p>You can append the output into a string and print resultant string at the end.</p> <p>Sample code based on your post description:</p> <pre><code>output_str = '{} {}'.format(client[0], client[9]) if client[12] != "Not Applicable": output_str = output_str + ' S.I. = ' + '$' + str("%0.2f" % client[12]) else: ...
1
2016-07-11T12:34:22Z
[ "python" ]
pywinrm - running New-Mailbox powershell cmdlet remotely
38,306,860
<p>I've been trying to get the <a href="https://pypi.python.org/pypi/pywinrm" rel="nofollow">pywinrm</a> module to run the <code>New-Mailbox</code> Powershell cmdlet remotely. This is what I have so far:</p> <pre><code>import winrm ps_text = "$pass = ConvertTo-SecureString -String '%s' -AsPlainText -Force; \ ...
0
2016-07-11T12:24:49Z
38,312,057
<p>In PowerShell, single quotes will prevent variable expansion from occurring.</p> <p>My recommendation would be:</p> <ul> <li>Remove the single quotes from the <code>$pass</code></li> <li>Notice in the error message you posted, that the error is coming from <code>-serverSettings</code>, not <code>-Password</code></...
0
2016-07-11T16:41:45Z
[ "python", "powershell", "automation", "powershell-remoting", "exchange-server-2010" ]
Simple python script to get a libreoffice base field and play on vlc
38,306,910
<p>I've banged my head for hours on this one, and I don't understand the LibreOffice macro api well enough to know how to make this work:</p> <p>1) This script works in python:</p> <pre><code>#!/usr/bin/env python3 import subprocess def play_vlc(path="/path/to/video.avi"): subprocess.call(['vlc', path]) retu...
0
2016-07-11T12:27:33Z
38,313,600
<p>For example, say the form is based on a table containing a column called <code>PATH</code>. Assign the button's <code>Execute action</code> event to this function:</p> <pre class="lang-py prettyprint-override"><code>def playvlc_button_pressed(oEvent): oForm = oEvent.Source.getModel().getParent() lNameCol =...
1
2016-07-11T18:17:32Z
[ "python", "libreoffice-base" ]
How to set System Property "webdriver.gecko.driver" using Robot Framework?
38,307,054
<p>I'm using the Robot Framework together with the Selenium2Library for automated frontend tests. Usually I ran those tests in Firefox browser. Since version 47 of Firefox the built in FirefoxDriver of the Selenium2Library doesn't work anymore. A searched through the Internet a bit and found, that I have to switch to t...
1
2016-07-11T12:34:05Z
38,310,902
<p>This is an answer to resolve the compatibility issue with Firefox 47 and Selenium2Library (which led you to try Marionette/Gecko driver):</p> <p>Firefox 47 had a bug causing it to crash with selenium webdriver. This bug has been fixed in Firefox 47.0.1 (refer <a href="https://www.mozilla.org/en-US/firefox/47.0.1/re...
0
2016-07-11T15:35:40Z
[ "python", "selenium-webdriver", "robotframework" ]
How to set System Property "webdriver.gecko.driver" using Robot Framework?
38,307,054
<p>I'm using the Robot Framework together with the Selenium2Library for automated frontend tests. Usually I ran those tests in Firefox browser. Since version 47 of Firefox the built in FirefoxDriver of the Selenium2Library doesn't work anymore. A searched through the Internet a bit and found, that I have to switch to t...
1
2016-07-11T12:34:05Z
38,316,485
<p>If you do not want to use Marionette, follow Mukesh's answer and change versions. If you want to use Marionette, the simplest approach is to add wires (or geckodriver in the future) to the system path as suggested <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">by th...
1
2016-07-11T21:25:27Z
[ "python", "selenium-webdriver", "robotframework" ]
make a dict/json from string with duplicate keys Python
38,307,068
<p>I have a string that could be parsed as a json or dict object. My string variable looks like this :</p> <pre><code> my_string_variable = "{ "a":1, "b":{ "b1":1, "b2":2 ...
0
2016-07-11T12:34:42Z
38,307,621
<p>something like the following can be done.</p> <pre><code>import json def join_duplicate_keys(ordered_pairs): d = {} for k, v in ordered_pairs: if k in d: if type(d[k]) == list: d[k].append(v) else: newlist = [] newlist.append(d[k]) ...
2
2016-07-11T12:59:53Z
[ "python", "json", "string", "dictionary" ]
Implementing intersection operator for a set-like class in Python
38,307,203
<p>I'm trying to implement a wrapper class which should ideally allow me to get the intersection of its elements using the notation: </p> <p><code>a &amp; b</code> </p> <p>Is there a specific method that I can implement to achieve this? (I know that the individual elements need to implement the <code>__hash__</code>...
1
2016-07-11T12:40:46Z
38,307,384
<p>Try to override:</p> <pre><code>def __and__(self, *args, **kwargs): # real signature unknown """ Return self&amp;value. """ pass </code></pre> <p>in your class</p>
1
2016-07-11T12:49:29Z
[ "python", "set-intersection" ]
Variable in enclosed local scope vs variable in global scope - Python
38,307,208
<p>hi guys I can't figure out why when <code>find_average()</code> is called, <code>total = 20</code> in the global scope is being used for the <code>find_total()</code> function, instead of <code>total = 10</code> in the enclosing scope? Thanks in advance for any insights and help!</p> <pre><code>total = 20 def fin...
0
2016-07-11T12:40:53Z
38,307,481
<p>Each function has its own scope. It starts at the functions local, inner scope, then goes outwards through enclosing functions until it reaches global (module) scope. This sequence depends on the scope the function is <em>defined in</em>. The stack (calling sequence) is <em>not</em> used for variable lookup.</p> <p...
0
2016-07-11T12:53:04Z
[ "python", "scope", "nested", "global", "local" ]
Extract data from string in python
38,307,213
<p>I have a .csv file with data constructed as <code>[datetime, "(data1, data2)"]</code> in rows and I have managed to import the data into python as <code>time</code> and <code>temp</code>, the problem I am facing is how do I seperate the <code>temp</code> string into two <code>new_temp</code> columns in float format ...
0
2016-07-11T12:41:13Z
38,307,350
<p>Going from the answer in <a href="http://stackoverflow.com/questions/9763116/parse-a-tuple-from-a-string">Parse a tuple from a string?</a></p> <pre><code>from ast import literal_eval as make_tuple temp = ['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456...
1
2016-07-11T12:47:09Z
[ "python", "string", "python-2.7", "floating-point" ]
Extract data from string in python
38,307,213
<p>I have a .csv file with data constructed as <code>[datetime, "(data1, data2)"]</code> in rows and I have managed to import the data into python as <code>time</code> and <code>temp</code>, the problem I am facing is how do I seperate the <code>temp</code> string into two <code>new_temp</code> columns in float format ...
0
2016-07-11T12:41:13Z
38,307,470
<p>You may use this code:</p> <pre><code>import re string = "['(0.0, 0.0)', '(64.4164, 66.2503)', '(63.4768, 65.4108)', '(62.7148, 64.6278)', '(62.0408, 63.9625)', '(61.456, 63.2638)', '(61.0234, 62.837)', '(60.6823, 62.317)']" data = re.findall('[+-]?\d+\.\d+e?[+-]?\d*', string) data = zip(data[0::2], data[1::2]) pri...
1
2016-07-11T12:52:45Z
[ "python", "string", "python-2.7", "floating-point" ]
Python selenium webdriver not consistently selecting element even though it's there
38,307,222
<p>I'm developing a web scraper to collect the src link from a source tag in an html file and add it to a list.</p> <p>The site has a video nested under a load of divs, but all of the pages eventually come to:</p> <pre><code>&lt;video type="video/mp4" poster="someimagelink" preload="metadata" crossorigin="anonymous"&...
0
2016-07-11T12:41:39Z
38,330,845
<p>You probably need to wait for the web element you are looking for. You should explore using WebDriverWait.</p>
1
2016-07-12T13:50:36Z
[ "python", "html", "python-3.x", "selenium", "selenium-webdriver" ]
Truly vectorized routines in python?
38,307,401
<p>Are there really good methods in Python to vectorize matrix like data constructs/containers -operations? What are the according data constructs used?</p> <p>(I could observe and read that pandas and numpy element-wise operations using vectorize or applymap (may also be the case of apply/apply along axis for rows/co...
-1
2016-07-11T12:49:59Z
38,309,778
<p>You need to provide a specific example. </p> <p>Normal per-element MATLAB or Python functions cannot be vectorized in general. The whole point of vectorizing, in both MATLAB and Python, is to off-load the operation onto the much faster underlying C or Fortran libraries that are designed to work on arrays of uniform...
2
2016-07-11T14:41:13Z
[ "python", "performance", "numpy", "pandas", "vectorization" ]
overwriting values in dataframe in python
38,307,485
<p>I'm new to python so this might seem a bit easy problem for you expertise.</p> <p>I've 6 categories(0 to 5),each of which has 4 sub-categories namely: '3','4','5','6'.</p> <p>for this,I've created a dataframe using:</p> <pre><code>df=pd.DataFrame(index=list(range(5)),columns=list([3,4,5,6]) </code></pre> <p>Now,...
0
2016-07-11T12:53:18Z
38,307,875
<p>Not sure if I understand your question correctly, but there are multiple ways to insert a value to a desired dataframe cell.</p> <p>For example line, </p> <pre><code>df.xs(1)['e'] = x </code></pre> <p>inserts value x to a cell that has an index value of 1 and is in column 'e'.</p> <p>If you wan't to calculate th...
0
2016-07-11T13:11:05Z
[ "python", "loops", "pandas", "replace", "dataframe" ]
overwriting values in dataframe in python
38,307,485
<p>I'm new to python so this might seem a bit easy problem for you expertise.</p> <p>I've 6 categories(0 to 5),each of which has 4 sub-categories namely: '3','4','5','6'.</p> <p>for this,I've created a dataframe using:</p> <pre><code>df=pd.DataFrame(index=list(range(5)),columns=list([3,4,5,6]) </code></pre> <p>Now,...
0
2016-07-11T12:53:18Z
38,339,294
<p>your suggestion of appending to DataFrame rows iteratively is not optimal. it will slowdown the code. instead you can append the output to a list and than reshape the list as you like and ultimately convert it to pd.DataFrame. that will be way faster than what you propose. for example:</p> <pre><code>import pandas ...
0
2016-07-12T21:37:50Z
[ "python", "loops", "pandas", "replace", "dataframe" ]
set list as value in a column of a pandas dataframe
38,307,489
<p>Let's say I have a dataframe <code>df</code> and I would like to create a new column filled with 0, I use:</p> <pre><code>df['new_col'] = 0 </code></pre> <p>This far, no problem. But if the value I want to use is a list, it doesn't work:</p> <pre><code>df['new_col'] = my_list ValueError: Length of values does no...
2
2016-07-11T12:53:27Z
38,307,539
<p>You'd have to do:</p> <pre><code>df['new_col'] = [my_list] * len(df) </code></pre> <p>Example:</p> <pre><code>In [13]: df = pd.DataFrame(np.random.randn(5,3), columns=list('abc')) df Out[13]: a b c 0 -0.010414 1.859791 0.184692 1 -0.818050 -0.287306 -1.390080 2 -0.054434 0.106212 1....
2
2016-07-11T12:55:43Z
[ "python", "list", "pandas" ]
Python to SQL Server connection
38,307,499
<p>I'm using Python 3.5.1 with Anaconda package 2.4.0 and try to make a connection to local SQL Server (2008 R2)</p> <p>So doing the next things:</p> <pre><code>import pypyodbc connection_string =pypyodbc.connect('Driver={SQL Server};Server=PC\MSSQLSERVER,1433;Database=localbase;Uid=name;Pwd=pass') connection_string=...
0
2016-07-11T12:54:05Z
38,314,723
<p>You seem to have misunderstood what a "connection string" is. It is the text string that you <em>pass to</em> the <code>.connect</code> method, not what is <em>returned from</em> the <code>.connect</code> method. (What gets returned is a <code>connection</code> object.)</p> <p>So, you need to do something more like...
0
2016-07-11T19:28:57Z
[ "python", "sql-server", "python-3.x", "pypyodbc" ]
Reading a serial port in python with unknown data length
38,307,550
<p>Hello I am trying to read data from a pic32 microcontroller configured as a serial port.</p> <p>The pic32 sends "binary" data variable in length (14 to 26 bytes long). I want to read in the data and separate the bits then convert them to their decimal equivalent.</p> <pre><code>import serial import csv #open the ...
0
2016-07-11T12:56:37Z
38,307,718
<p>I am not sure how you determine if the data is 14 or 26 bytes long or anything in-between.</p> <p>In all cases, you might want to use a wrapper class which wraps the IO.</p> <p>On every request of data, you can have the wrapper either read a certain number of bytes or all bytes which are available, until you have ...
0
2016-07-11T13:04:16Z
[ "python" ]
DataFrame in list boolean?
38,307,590
<p>I can select a subset using Boolean indexing as such:</p> <pre><code>df.loc[df['my column'] == 1] </code></pre> <p>What I'd like to do is replace the <code>== 1</code> with a list, <code>[1, 2]</code>.</p> <p>Something like:</p> <pre><code>df.loc[df['my column'] in [1,2]] </code></pre> <p>This is the equivalent...
0
2016-07-11T12:58:04Z
38,307,614
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> to test membership in a list of values:</p> <pre><code>df.loc[df['my column'].isin([1,2])] </code></pre> <p>Example:</p> <pre><code>In [18]: df = pd.DataFrame({'a':np.random.randn(5), '...
3
2016-07-11T12:59:24Z
[ "python", "pandas" ]
Can anyone explain me the example of an exploit in Python’s pickle module?
38,307,636
<p>I want to understand the the example of exploit in python pickle module? i got a code from github which show exploit in pickle module, but still not able to understand it. please guide me.</p> <pre><code>import os import pickle class Exploit(object): def __reduce__(self): return (os.system, ('cat /etc...
-2
2016-07-11T13:00:13Z
38,307,898
<p>When you unpickle an object, the __reduce__ method is called. The first argument to __reduce__ is a callable, that is, a function. The next argument is a tuple of arguments for __reduce__. In this case, when Exploit is unpickled, os.system is called, and is given 'cat /etc/passwd' as the argument.</p> <p>os.system ...
2
2016-07-11T13:11:58Z
[ "python", "pickle" ]
AttributeError: 'str' object has no attribute 'loads', json.loads()
38,307,724
<p>snippets</p> <pre><code> import json teststr = '{"user": { "user_id": 2131, "name": "John", "gender": 0, "thumb_url": "sd", "money": 23, "cash": 2, "material": 5}}' json = json.load(teststr) </code></pre> <p>throws an exception</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", ...
1
2016-07-11T13:04:30Z
38,308,308
<p><a href="https://docs.python.org/2.7/library/json.html#json.load" rel="nofollow"><code>json.load</code></a> takes in a file pointer, and you're passing in a string. You probably meant to use <a href="https://docs.python.org/2.7/library/json.html#json.loads" rel="nofollow"><code>json.loads</code></a> which takes in a...
2
2016-07-11T13:31:25Z
[ "python", "json" ]
Calling Personality Insights API from Python server
38,307,811
<p>I'm trying to call Personality Insights API from my Python web app but it always return the forbidden error 403 but when I call it from Postman Chrome extension it work successfully. </p> <p>This is my python code:</p> <pre><code>def generatePersonalDescription(request): import requests from requests.auth ...
0
2016-07-11T13:08:25Z
38,313,737
<p>It appears you are using HTTP <code>GET</code> method, while the <a href="http://www.ibm.com/watson/developercloud/personality-insights/api/v2/#response-handling" rel="nofollow">Personality Insights</a> profile API accepts <code>POST</code>. I am not sure this is the cause of HTTP 403 (it should not), but I would do...
1
2016-07-11T18:27:15Z
[ "python", "post", "ibm-bluemix", "personality-insights" ]
Calling Personality Insights API from Python server
38,307,811
<p>I'm trying to call Personality Insights API from my Python web app but it always return the forbidden error 403 but when I call it from Postman Chrome extension it work successfully. </p> <p>This is my python code:</p> <pre><code>def generatePersonalDescription(request): import requests from requests.auth ...
0
2016-07-11T13:08:25Z
38,409,777
<p>I figure it out. The problem is that i'm using free pythonanywhere account which limit the users form sending requests to external servers to this <a href="https://www.pythonanywhere.com/whitelist/" rel="nofollow">whitelist.</a> I need to upgrade my account to allow for unrestricted requests.</p>
1
2016-07-16T09:40:20Z
[ "python", "post", "ibm-bluemix", "personality-insights" ]
Can't do migrations - ... has no field named 'questions'
38,307,849
<p>I'm trying to figure out why does Django return's this error when trying to <code>migrate</code> after <code>makemigrations</code>. I tried to change related names and delete last migrations but nothing works. </p> <p>Maybe you see what's the problem?</p> <p>Error after migrate: <code>django.core.exceptions.FieldD...
0
2016-07-11T13:10:07Z
38,308,112
<p>So the matter is the following one:</p> <pre><code>questions = random.sample(self.quiz.questions,self.max_questions) </code></pre> <p>self.quiz go there :</p> <pre><code>quiz = models.OneToOneField(LanguageQuiz) </code></pre> <p>and quiz.questions go there :</p> <pre><code>class LanguageQuiz(models.Model): ...
1
2016-07-11T13:22:39Z
[ "python", "django", "django-models", "django-migrations" ]
Run entirely a python code in IOS app?
38,307,853
<p>I have some code written in Python. I would like to know if it's possible to make a ios app which can execute the python code ?</p> <p>For example, let's say I have a python code which can classify some picture into different categories by printing the correct category. I would like to create an ios app which take ...
-2
2016-07-11T13:10:18Z
38,321,224
<p>Yes you can use this framework <a href="https://github.com/pybee/Python-Apple-support" rel="nofollow">https://github.com/pybee/Python-Apple-support</a> Check your python version first then Add header and framework search paths. </p>
1
2016-07-12T06:14:15Z
[ "python", "ios", "xcode" ]
Nested dictionary from pandas data frame
38,307,855
<p>I have the following data (see below) in a pandas data frame.</p> <p>I'd like to covert it into a dict that looks like this:</p> <pre><code>my_dict = { 'AB': { 'city1': (0.000000, 0.000000), 'city2' : (0.100000, 0.200000), 'city3' : (0.200000, 0.400000) } 'BC': { 'city...
2
2016-07-11T13:10:26Z
38,309,528
<p>You can first create column <code>zipped</code> by <code>zip</code> <code>lat</code> and <code>lng</code> and then <code>groupby</code> with double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="nofollow"><code>to_dict</code></a>:</p> <pre><code>#python 3 need conver...
2
2016-07-11T14:29:30Z
[ "python", "pandas", "dictionary", "nested" ]
SQLalchemy query_cls for a specific query
38,307,880
<p>Can I specify <code>query_cls</code> <strong>only</strong> for a one query? I tried to use <code>query.session._query_cls</code> and, of course, it doesn't work...</p> <p>I want to perform something like this:</p> <pre><code>query = Session.query(MyModel)... default_querycls_result = query.all() custom_querycls_re...
1
2016-07-11T13:11:18Z
38,312,109
<p>You can just create new query object and copy <code>__dict__</code></p> <pre><code>from sqlalchemy.orm.query import Query class CustomQuery(Query): pass query = Session.query(MyModel) default_querycls_result = query.all() custom_query = CustomQuery(entities=[]) custom_query.__dict__ = query.__dict__.copy() cu...
0
2016-07-11T16:44:37Z
[ "python", "sqlalchemy" ]
How to detect if a String has specific UTF-8 characters in it? (Python)
38,307,982
<p>I have a list of Strings in python. Now I want to remove all the strings from the list that are special utf-8 characters. I want just the strings which include just the characters from "U+0021" to "U+00FF". So, do you know a way to detect if a String just contains these special characters?</p> <p>Thanks :)</p> <p>...
0
2016-07-11T13:15:58Z
38,308,272
<p>You can use regular expression.</p> <pre><code>import re mylist = ['str1', 'štr2', 'str3'] regexp = re.compile(r'[^\u0021-\u00FF]') good_strs = filter(lambda s: not regexp.search(s), mylist) </code></pre> <p><code>[^\u0021-\u00FF]</code> defines a character set, meaning any one character not in the range from <co...
0
2016-07-11T13:29:55Z
[ "python", "python-3.x", "utf-8" ]
How to detect if a String has specific UTF-8 characters in it? (Python)
38,307,982
<p>I have a list of Strings in python. Now I want to remove all the strings from the list that are special utf-8 characters. I want just the strings which include just the characters from "U+0021" to "U+00FF". So, do you know a way to detect if a String just contains these special characters?</p> <p>Thanks :)</p> <p>...
0
2016-07-11T13:15:58Z
38,308,361
<p>What do you mean exactly by "special utf-8 characters" ? </p> <p>If you mean every non-ascii character, then you can try:</p> <p><code>s.encode('ascii', 'strict')</code></p> <p>It will rise an UnicodeDecodeError if the string is not 100% ascii</p>
0
2016-07-11T13:34:25Z
[ "python", "python-3.x", "utf-8" ]
How to detect if a String has specific UTF-8 characters in it? (Python)
38,307,982
<p>I have a list of Strings in python. Now I want to remove all the strings from the list that are special utf-8 characters. I want just the strings which include just the characters from "U+0021" to "U+00FF". So, do you know a way to detect if a String just contains these special characters?</p> <p>Thanks :)</p> <p>...
0
2016-07-11T13:15:58Z
38,308,405
<pre><code>&gt;&gt;&gt; all_strings = ["okstring", "bađštring", "goodstring"] &gt;&gt;&gt; acceptible = set(chr(i) for i in range(0x21, 0xFF + 1)) &gt;&gt;&gt; simple_strings = filter(lambda s: set(s).issubset(acceptible), all_strings) &gt;&gt;&gt; list(simple_strings) ['okstring', 'goodstring'] </code></pre>
1
2016-07-11T13:37:04Z
[ "python", "python-3.x", "utf-8" ]
How to detect if a String has specific UTF-8 characters in it? (Python)
38,307,982
<p>I have a list of Strings in python. Now I want to remove all the strings from the list that are special utf-8 characters. I want just the strings which include just the characters from "U+0021" to "U+00FF". So, do you know a way to detect if a String just contains these special characters?</p> <p>Thanks :)</p> <p>...
0
2016-07-11T13:15:58Z
38,308,654
<p>The latin1 encoding correspond to the 256 first utf8 characters. Say differently, if <code>c</code> is a unicode character with a code in <code>[0-255]</code>, <code>c.encode('latin1')</code> has same value as <code>ord(c)</code>.</p> <p>So to test whether a string has at least one character outside the [0-255] ran...
0
2016-07-11T13:49:15Z
[ "python", "python-3.x", "utf-8" ]
Taking the difference between two dates using pandas?
38,308,003
<p>I am trying to take the time difference between two dates using pandas and am having some trouble. </p> <p>The format the dates are in are as follows:</p> <pre><code>2016/07/06 03:10:39 </code></pre> <p>Using pandas.to_datetime I can get these to a datetime64 type but then cannot figure out a way to take the dif...
1
2016-07-11T13:16:54Z
38,308,288
<p>That's work perfectly:</p> <pre><code>&gt;&gt;&gt; import pandas &gt;&gt;&gt; x = pandas.to_datetime("2016/07/06 03:10:39") &gt;&gt;&gt; y = pandas.to_datetime("2016/07/06 03:11:21") &gt;&gt;&gt; y-x Timedelta('0 days 00:00:42') </code></pre> <p>Post your code if you still can't figure what your problem.</p>
0
2016-07-11T13:30:19Z
[ "python", "datetime", "pandas", "time" ]
What is the difference between render() of DjangoTemplates class and render() method found in django.shortcuts module?
38,308,049
<p>I am trying to learn Django. I am creating a small applicationt to understand its basic functionalities. In views.py of a django app, some tutorials use render() from template while others use render() from django shortcuts module. </p> <p>For instance, in views.py</p> <pre><code>from django.shortcuts import rende...
0
2016-07-11T13:19:10Z
38,308,198
<p><a href="https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render" rel="nofollow"><code>django.shortcuts.render</code></a> is, as its name implies, a shortcut for returning a rendered template as a response from a view. Its use is rather limited to that context. It takes an <code>HttpRequest</code> instan...
2
2016-07-11T13:26:16Z
[ "python", "django", "django-templates" ]
Methods intended for overriding but not part of the public API
38,308,071
<p>I have a class that implements a strategy. As part of a wider strategy API it has a public interface. In this particular class the <code>main_method</code> applies various conditions and has a <code>helper_...</code> method for each condition. Thus, by subclassing and overriding these helper methods you can change t...
0
2016-07-11T13:20:22Z
38,308,282
<p>Just make the methods public and clarify their intended use in the documentation. Take the example from the <a href="https://docs.python.org/3.5/library/ast.html#ast.NodeVisitor" rel="nofollow"><code>ast.NodeVisitor</code></a> class from the standard library:</p> <blockquote> <p>This class is meant to be subclass...
1
2016-07-11T13:30:11Z
[ "python", "design-patterns" ]
Appending To A CSV From A Tuple in Python
38,308,097
<p>I have a CSV that looks something like this. The list will typically contain about 10-50 lines:</p> <pre><code>HASH FILE USER HOST 1C7E2110A55F42F525E196499FF88523 ABC.EXE TEST1 XYZ 3B7E2110A55F42F525E196499AA88421 124.TXT TEST2 SDF </code></pre> <p>I hav...
1
2016-07-11T13:21:59Z
38,308,857
<p>One approach is to first read hashes into dict, and then writing input csv into output by adding new column to each row using the dict.</p> <p>Following is code sample based on your post description:</p> <pre><code>import csv hashes = [('1C7E2110A55F42F525E196499FF88523', '4'), ('5A7E2110A55F42F525E196499FF88511'...
1
2016-07-11T13:58:23Z
[ "python", "csv", "append" ]
Matplotlib: Constrain plot width while allowing flexible height
38,308,133
<p>What I would like to achive are plots with <strong>equal scale aspect ratio</strong>, and <strong>fixed width</strong>, but a <strong>dynamically chosen height</strong>.</p> <p>To make this more concrete, consider the following plotting example:</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as p...
2
2016-07-11T13:23:21Z
38,351,638
<p>Have you tried to fix the width with fig.set_figwidth()?</p>
1
2016-07-13T12:23:12Z
[ "python", "matplotlib", "plot" ]
IOError while reading files
38,308,310
<p>From where does python pick its file for reading.Is there any specific folder,or does it pick from anywhere on the system just given the filename and extension.Is there a need to mention absolute path. I am getting error while reading txt and csv files as no such file or directory. f=open('info.csv') print f ...
0
2016-07-11T13:31:38Z
38,308,473
<p>By default, python checks for the requested file in the same directory the program file is in. If you want python to check for the file in some other location, you have to specify the absolute path.</p> <p>About your error, nothing can be said unless you share your code.</p>
0
2016-07-11T13:40:07Z
[ "python" ]
TensorFlow - Show image from MNIST DataSet
38,308,378
<p>I'm trying to learn TensorFlow and I implemented the MNIST example from the the following link: <a href="http://openmachin.es/blog/tensorflow-mnist" rel="nofollow">http://openmachin.es/blog/tensorflow-mnist</a> I want to be able to actually view the training/test images. So I'm trying to add code that will show the ...
1
2016-07-11T13:35:06Z
38,308,584
<p>After reading the tutorial you can do it all in numpy no need for TF:</p> <pre><code>import matplotlib.pyplot as plt first_array=batch_xs[0] #Not sure you even have to do that if you just want to visualize it #first_array=255*first_array #first_array=first_array.astype("uint8") plt.imshow(first_array) #Actually dis...
1
2016-07-11T13:45:32Z
[ "python", "image", "tensorflow", "mnist" ]
%run Python function in IPython
38,308,460
<p>I'd like to run a function from IPython and load all of its data into the interactive namespace, just like how <code>%run filename.py</code> does it. E.g., here's the file <code>scratch.py</code>:</p> <pre><code>def foo(x): a = x*2 </code></pre> <p>In IPython, I'd like to run this function and be able to acce...
0
2016-07-11T13:39:20Z
38,308,909
<p>In order to make the variable available globally (or in some interactive IPython session), you first have to define it as global:</p> <pre><code>def foo(x): global a a = x*2 </code></pre> <p>Otherwise your <code>a</code> remains a local variable within your function. More infos e.g. here: <a href="http://s...
1
2016-07-11T14:00:51Z
[ "python", "ipython" ]
%run Python function in IPython
38,308,460
<p>I'd like to run a function from IPython and load all of its data into the interactive namespace, just like how <code>%run filename.py</code> does it. E.g., here's the file <code>scratch.py</code>:</p> <pre><code>def foo(x): a = x*2 </code></pre> <p>In IPython, I'd like to run this function and be able to acce...
0
2016-07-11T13:39:20Z
38,313,490
<p>This isn't a <code>ipython</code> or <code>%run</code> issue, but rather a question of what you can do with variables created with a function. It applies to any function run in Python.</p> <p>A function has a <code>local</code> namespace, where it puts the variables that you define in that function. That is, by d...
0
2016-07-11T18:10:51Z
[ "python", "ipython" ]
Unable to Process an image transformed in OpenCV via scikit-image
38,308,480
<p>I want to skeletonize an image using the scikit-image module for skeletonization. This image is pre processed by OpenCV library. Given an Image 'Feb_16-0.jpg', I convert it to gray scale, perform the morphological transformation of opening the image, then apply the Gaussian Blur and adaptive thresholding using OpenC...
0
2016-07-11T13:40:26Z
38,308,895
<p>The input matrix to <code>skeletonize()</code> needs to be binary with either 0/1 or True/False as entries. The output of <code>cv2.threshold()</code> is binary, but with values 0/255. To convert the th4 matrix to 0/1 form you can for example do:</p> <p><code>th4[th4 == 255] = 1</code></p>
2
2016-07-11T14:00:20Z
[ "python", "image", "opencv", "preprocessor", "scikit-image" ]
Unable to Process an image transformed in OpenCV via scikit-image
38,308,480
<p>I want to skeletonize an image using the scikit-image module for skeletonization. This image is pre processed by OpenCV library. Given an Image 'Feb_16-0.jpg', I convert it to gray scale, perform the morphological transformation of opening the image, then apply the Gaussian Blur and adaptive thresholding using OpenC...
0
2016-07-11T13:40:26Z
38,309,586
<p>Please see if the below code works.</p> <pre><code>import cv2 import numpy as np from matplotlib import pyplot as plt from skimage.morphology import skeletonize from skimage.viewer import ImageViewer img = cv2.imread('Feb_16-0.jpg',0) kernel = np.ones((1,1),np.uint8) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, ...
1
2016-07-11T14:31:55Z
[ "python", "image", "opencv", "preprocessor", "scikit-image" ]
Error with pygame (pygame.init())
38,308,518
<p>I'm having an error while using Pygame. I'm using Python 3.5 and Pygame 3.2. I started to learn Pygame just today and it gives me this error:</p> <p>Code:</p> <pre><code>import pygame pygame.init() width, height = 640, 480 screen=pygame.display.set_mode((width, height)) player = pygame.image.load("resources/imag...
0
2016-07-11T13:41:53Z
38,313,410
<p>Delete the "pygame.py" file in your Documents folder, it is shadowing the real pygame you've installed.</p>
-1
2016-07-11T18:05:08Z
[ "python", "pygame" ]
elegant way to reduce a list of dictionaries?
38,308,519
<p>I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested <code>for</code>s).</p> <p>Here is the list:</p> <pre><code>[ { ...
4
2016-07-11T13:41:54Z
38,308,663
<p>Here you go, a solution using <code>reduce()</code>:</p> <pre><code>from functools import reduce # Python 3 compatibility summed = reduce( lambda a, b: {k: a[k] + b[k] for k in a}, list_of_dicts, dict.fromkeys(list_of_dicts[0], 0.0)) result = {k: v / len(list_of_dicts) for k, v in summed.items()} </co...
4
2016-07-11T13:49:40Z
[ "python", "python-3.x", "dictionary", "reduce" ]
elegant way to reduce a list of dictionaries?
38,308,519
<p>I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested <code>for</code>s).</p> <p>Here is the list:</p> <pre><code>[ { ...
4
2016-07-11T13:41:54Z
38,308,715
<p>Here's another way, a little more step-by-step:</p> <pre><code>from functools import reduce d = [ { "accuracy": 0.78, "f_measure": 0.8169374016795885, "precision": 0.8192088044235794, "recall": 0.8172222222222223 }, { "accuracy": 0.77, "f_measure": 0.8159133315763016, "precision":...
-1
2016-07-11T13:52:09Z
[ "python", "python-3.x", "dictionary", "reduce" ]
elegant way to reduce a list of dictionaries?
38,308,519
<p>I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested <code>for</code>s).</p> <p>Here is the list:</p> <pre><code>[ { ...
4
2016-07-11T13:41:54Z
38,308,814
<p>As an alternative, if you're going to be doing such calculations on data, then you may wish to use <a href="http://pandas.pydata.org/">pandas</a> (which will be overkill for a one off, but will greatly simplify such tasks...)</p> <pre><code>import pandas as pd data = [ { "accuracy": 0.78, "f_measure": 0....
7
2016-07-11T13:56:42Z
[ "python", "python-3.x", "dictionary", "reduce" ]
elegant way to reduce a list of dictionaries?
38,308,519
<p>I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested <code>for</code>s).</p> <p>Here is the list:</p> <pre><code>[ { ...
4
2016-07-11T13:41:54Z
38,309,093
<p>You could use a <code>Counter</code> to do the summing elegantly:</p> <pre><code>from itertools import Counter summed = sum((Counter(d) for d in folds), Counter()) averaged = {k: v/len(folds) for k, v in summed.items()} </code></pre> <p>If you really feel like it, it can even be turned into a oneliner:</p> <pre>...
2
2016-07-11T14:09:45Z
[ "python", "python-3.x", "dictionary", "reduce" ]
elegant way to reduce a list of dictionaries?
38,308,519
<p>I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested <code>for</code>s).</p> <p>Here is the list:</p> <pre><code>[ { ...
4
2016-07-11T13:41:54Z
38,310,169
<p>Here is a terrible one liner using list comprehension. You probably are better off not using this.</p> <pre><code>final = dict(zip(lst[0].keys(), [n/len(lst) for n in [sum(i) for i in zip(*[tuple(x1.values()) for x1 in lst])]])) for key, value in final.items(): print (key, value) #Output recall 0.81870370370...
0
2016-07-11T14:59:29Z
[ "python", "python-3.x", "dictionary", "reduce" ]
Mix python output and markdown in jupyter
38,308,620
<p>I want to be able to show the result of a python computation and have some explanation of it in Markdown. This seems like a fairly simple operation, but I can't figure out how to do it. Is there any way to do this without installing any extensions to Jupyter?</p>
1
2016-07-11T13:47:40Z
38,308,738
<p>In the <strong>toolbar</strong> (see image here <a href="http://jupyter-notebook.readthedocs.io/en/latest/_images/jupyter-notebook-default.png" rel="nofollow">http://jupyter-notebook.readthedocs.io/en/latest/_images/jupyter-notebook-default.png</a>), you can set the cell as Markdown in the drop down menu for explana...
0
2016-07-11T13:53:08Z
[ "python", "jupyter", "jupyter-notebook" ]
Condition in pandas dataframe
38,308,726
<p>I have a dataframe called <code>Mix</code>:</p> <pre><code> Name Surname Date Status 0 A A8 1902 aab 1 B B9 1976 ab 2 C C8 1901 aab 3 D D4 1986 abc 4 E E7 1986 abb 5 F F1 1986 ab 6 G G5 ...
2
2016-07-11T13:52:38Z
38,309,642
<p>You can use the result of <code>duplicated</code> to filter the main df using <code>isin</code>:</p> <pre><code>In [38]: duplicated = df[df['Status'].isin(df.loc[df['Status'].duplicated(), 'Status'])] duplicated Out[38]: Name Surname Date Status 0 A A8 1902 aab 1 B B9 1976 ab 2 C ...
2
2016-07-11T14:34:26Z
[ "python", "pandas", "dataframe" ]
PyQT QTreeview + QPushButton/QCombobox signals
38,308,808
<p>I'm trying to load a serries of files that are dics and then load arrays from within dics to my QTreeView and then be able to edit these dics. I have a problem when it comes to connecting signal as it connects all buttons to 1 data - last created one. If I load 20 arrays from 1 dict I should be able to click on each...
0
2016-07-11T13:56:28Z
38,316,794
<p>Use partial :</p> <pre><code> b = QPushButton(str(inx)) b.clicked.connect(partial(self.printData,child1.text())) </code></pre>
0
2016-07-11T21:51:54Z
[ "python", "pyqt", "pyqt4", "qtreeview" ]
How to remove small components from a graph
38,308,865
<p>I'm new to networkx and could do with some help please. </p> <p>I have a set of data which I've processed to generate the nodes and edges. There are around 5000 groups of nodes that have more than 2 links within them (up to 10 nodes in the group in total). But the problem is that there are also several thousand pai...
2
2016-07-11T13:58:43Z
38,311,902
<p>So our goal is to remove all nodes from components with less than 3 nodes (this includes isolated nodes if they exist).</p> <pre><code>for component in list(nx.connected_components(G)): if len(component)&lt;3: for node in component: G.remove_node(node) </code></pre> <p>A small warning is in...
2
2016-07-11T16:32:24Z
[ "python", "networkx" ]
Replace all elements of a matrix by their inverses
38,308,945
<p>I've got a simple problem and I can't figure out how to solve it.</p> <p>Here is a matrix: <code>A = np.array([[1,0,3],[0,7,9],[0,0,8]])</code>.</p> <p>I want to find a quick way to replace all elements of this matrix by their inverses, excluding of course the zero elements.</p> <p>I know, thanks to the search en...
1
2016-07-11T14:03:01Z
38,308,996
<p>Use <code>1. / A</code> (notice the dot for Python 2):</p> <pre><code>&gt;&gt;&gt; A array([[1, 0, 3], [0, 7, 9], [0, 0, 8]], dtype) &gt;&gt;&gt; 1./A array([[ 1. , inf, 0.33333333], [ inf, 0.14285714, 0.11111111], [ inf, inf, 0.125 ]]) </code...
5
2016-07-11T14:04:56Z
[ "python", "python-2.7", "numpy", "matrix" ]
Replace all elements of a matrix by their inverses
38,308,945
<p>I've got a simple problem and I can't figure out how to solve it.</p> <p>Here is a matrix: <code>A = np.array([[1,0,3],[0,7,9],[0,0,8]])</code>.</p> <p>I want to find a quick way to replace all elements of this matrix by their inverses, excluding of course the zero elements.</p> <p>I know, thanks to the search en...
1
2016-07-11T14:03:01Z
38,309,122
<p>And just a note on Antti Haapala's answer, (Sorry, I can't comment yet) if you wanted to keep the 0's, you could use</p> <pre><code>B=1./A #I use the 1. to make sure it uses floats B[B==np.inf]=0 </code></pre>
3
2016-07-11T14:11:36Z
[ "python", "python-2.7", "numpy", "matrix" ]
printing variable inside a def, inside a class
38,308,949
<p>i am new to object oriented programming, what i want to do basicaly is print a variable inside a def wich is on its turn inside a class, i think theres probaly a very simple answer but i just cant figure it out, thanks for the assistance, heres my code:</p> <pre><code>class test(): def test2(): x = 12 p...
-4
2016-07-11T14:03:10Z
38,309,001
<p>You can't do what you want; local variables only exist <em>during the lifetime of a function call</em>. They are not attributes of the function nor are they available outside of the call in any other way. They are created when you call the function, destroyed again when the function exits.</p> <p>You <em>can</em> s...
4
2016-07-11T14:05:12Z
[ "python", "function", "class", "python-3.4" ]
Sorting seems to be slower with 2 threads instead of 1
38,309,025
<p>I'm beginning with threads in <em>Python</em>, and trying to implement a merge sort where, at the beginning, the job gets splitted into 2 threads. I'm using <code>collections.deque</code>, <code>itertools.islice</code>, <code>threading.Thread</code>.</p> <p>I create two threads at the beginning, they do each half t...
0
2016-07-11T14:06:23Z
38,309,129
<blockquote> <p>How can this be possible?</p> </blockquote> <p>Unlike C++, Python is quite difficult to parallelize because of the <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">GIL</a>. </p> <p>While <code>collections.deque</code>'s <code>append</code> and <code>popleft</code> are thre...
1
2016-07-11T14:11:54Z
[ "python", "multithreading", "performance", "sorting", "mergesort" ]
matplotlib x-axis formatting if x-axis is pandas index
38,309,109
<p>I'm using iPython notebook's %matplotlib inline and I'm having trouble formatting my plot.</p> <p><a href="http://i.stack.imgur.com/UsRHv.png" rel="nofollow"><img src="http://i.stack.imgur.com/UsRHv.png" alt="Plot that needs x-axis formatting"></a></p> <p>As you can see, my first and last data point aren't showing...
0
2016-07-11T14:10:50Z
38,309,743
<p>You can see the usage of xlim <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim" rel="nofollow">here</a>. Basically in this case if you ran <code>plt.xlim()</code> you would get<code>(0.0, 8.0)</code>. As you have an index that uses text and not numbers the values for xlim are actually just t...
0
2016-07-11T14:39:21Z
[ "python", "pandas", "matplotlib" ]
Qcut Pandas : ValueError: Bin edges must be unique
38,309,144
<p>I'm using Qcut from Pandas in order to discretize my Data into equal-sized buckets. I want to have price buckets. This is my DataFrame :</p> <pre><code> productId sell_prix categ popularity 11997 16758760.0 28.75 50 524137.0 11998 16758760.0 28.75 50 166795.0 13154 16782...
0
2016-07-11T14:12:23Z
38,309,882
<p>The 'sell_prix' field in your smaller DataFrame don't have enough unique values to break into three equally-sized buckets. As a result, the endpoint of the first and second bucket are the same, which is why you are getting an error. </p> <p>Consider </p> <pre><code>df = pd.DataFrame([[1,2,3],[1,4,5],[1,5,6],[1,3,4...
1
2016-07-11T14:46:15Z
[ "python", "arrays", "pandas", "dataframe" ]
NLTK Tree Format is not as docs show it
38,309,163
<p>On the NLTK docs, this is how printing a tree (in this case, 'entities') is shown to be:</p> <pre><code>import nltk sentence = """At eight o'clock on Thursday morning Arthur didn't feel very good.""" tokens = nltk.word_tokenize(sentence) tagged = nltk.pos_tag(tokens) entities = nltk.chunk.ne_chunk(tagged) entities...
0
2016-07-11T14:13:19Z
38,309,471
<p>Are you sure you just typed <code>entities</code> to get the result you report? What you see in the nltk homepage is the unambiguous representation of the tree object (its “<a href="https://docs.python.org/3.5/library/functions.html#repr" rel="nofollow">repr</a>” form, in python terms). You get when you dump a v...
2
2016-07-11T14:27:09Z
[ "python", "nltk" ]
Get column data by Column name and sheet name
38,309,256
<p>Is there a way to access all rows in a column in a specific sheet by using python xlrd. </p> <p>e.g:</p> <pre><code>workbook = xlrd.open_workbook('ESC data.xlsx', on_demand=True) sheet = workbook.sheet['sheetname'] arrayofvalues = sheet['columnname'] </code></pre> <p>Or do i have to create a dictionary by myself?...
0
2016-07-11T14:17:44Z
38,309,568
<p>This script allows to trasform a xls file to list of dictinnaries, all dict in list represent a row</p> <pre><code>import xlrd workbook = xlrd.open_workbook('esc_data.xlss') workbook = xlrd.open_workbook('esc_data.xlsx', on_demand = True) worksheet = workbook.sheet_by_index(0) first_row = [] # Header for col in ra...
0
2016-07-11T14:31:22Z
[ "python", "excel", "xlrd" ]
Get column data by Column name and sheet name
38,309,256
<p>Is there a way to access all rows in a column in a specific sheet by using python xlrd. </p> <p>e.g:</p> <pre><code>workbook = xlrd.open_workbook('ESC data.xlsx', on_demand=True) sheet = workbook.sheet['sheetname'] arrayofvalues = sheet['columnname'] </code></pre> <p>Or do i have to create a dictionary by myself?...
0
2016-07-11T14:17:44Z
38,339,321
<p>Yes, you are looking for the <code>col_values()</code> worksheet method. Instead of</p> <pre><code>arrayofvalues = sheet['columnname'] </code></pre> <p>you need to do</p> <pre><code>arrayofvalues = sheet.col_values(columnindex) </code></pre> <p>where <code>columnindex</code> is the number of the column (counting...
0
2016-07-12T21:40:30Z
[ "python", "excel", "xlrd" ]
Generic way to filter django query set by multiple fields (e.g. date)?
38,309,270
<p>I'm trying to create a generic date class based view for the blog I'm creating, but it does not seem to work. This is what I've got (regex inspired by <a href="https://gist.github.com/c4urself/1028897" rel="nofollow">this gist</a>):</p> <pre><code>"""Creativeflow URL Configuration the blog app.""" from django.conf....
0
2016-07-11T14:18:23Z
38,326,536
<p>This works, my two main issues were </p> <ol> <li>Not having blogs in the DB</li> <li>As <a href="http://stackoverflow.com/questions/38309270/generic-way-to-filter-django-query-set-by-multiple-fields-e-g-date#comment64035617_38309270">Alasdair said</a>: <blockquote> <p>You are using the keyword months in your u...
0
2016-07-12T10:40:14Z
[ "python", "django", "django-views" ]
Python tkinter - successfully inherit from toplevel
38,309,288
<p>I am trying to use an object-oriented approach to create a class that inherits from tkinter's Toplevel, triggered by pressing a button in the main window.</p> <p>The current code raises an AttributeError ('MakeWindow' object has no attribute 'tk'). Can anyone point me in the right direction?</p> <pre><code>#! pyth...
1
2016-07-11T14:18:59Z
38,309,887
<p>The problem is the <code>super().__init__(self)</code> it should be <code>super().__init__()</code>. Moreover, it is not necesssary to use <code>super</code> in this case (see <a href="http://stackoverflow.com/questions/222877/how-to-use-super-in-python">How to use &#39;super&#39; in Python?</a>). The following cod...
1
2016-07-11T14:46:27Z
[ "python", "inheritance", "tkinter", "toplevel" ]
Creating text file: IOError: [Errno 21] Is a directory: '/Users/muitprogram/PycharmProjects/untitled/HR/train.txt'
38,309,400
<p>I am trying to write to create and write to a text file. However, the error</p> <pre><code>Traceback (most recent call last): File "/Users/muitprogram/PycharmProjects/untitled/histogramSet.py", line 207, in &lt;module&gt; drinktrainfile = open(abs_file_path, "w") IOError: [Errno 21] Is a directory: '/User...
-3
2016-07-11T14:24:25Z
38,310,056
<p>The resource is actually a directory. It was very likely a mistake, as it is not likely that somebody would have created a directory by that name. First, remove that directory, and then try to create and open the file.</p> <p>You can open the file with <code>open('/Users/muitprogram/PycharmProjects/untitled/HR/trai...
0
2016-07-11T14:53:52Z
[ "python", "python-2.7", "file", "filepath" ]
Broadcasting for subtensor created from matrix (Theano)
38,309,429
<p>I want to create two subtensors from a matrix, using indices to select the respective rows. One subtensor has several rows, the other just one, which should be broadcast to allow for element-wise addition.</p> <p>My question is: how do I indicate that I want to allow for broadcasting on the specific dimension in th...
1
2016-07-11T14:25:09Z
38,373,983
<p>The problem is that your theano function does not know in advance that the right (<code>ri</code>) indices will have only 1 element (so for all in knows you'll be trying to subtract a NxD matrix from a MxD matrix, which won't work in general. However for your case you only ever want N=1.)</p> <p>The solution is to...
1
2016-07-14T12:16:34Z
[ "python", "numpy", "matrix", "theano" ]
How to encode unicode strings to utf-8 in a list with both unicode and float values using python
38,309,521
<p>I have a list with both unicode and float values:</p> <pre><code>list=[u'name',523] </code></pre> <p>I want to convert only the string to utf-8 in the list. How can i do that using python?</p> <pre><code>[x.encode('utf-8') for x in items] </code></pre> <p>I have the used the code snippet above to encode but i am...
-1
2016-07-11T14:29:11Z
38,309,613
<p>Can't you do:</p> <pre><code>[x.encode('utf-8') if isinstance(x, str) else x for x in items] </code></pre>
0
2016-07-11T14:32:59Z
[ "python" ]
How to encode unicode strings to utf-8 in a list with both unicode and float values using python
38,309,521
<p>I have a list with both unicode and float values:</p> <pre><code>list=[u'name',523] </code></pre> <p>I want to convert only the string to utf-8 in the list. How can i do that using python?</p> <pre><code>[x.encode('utf-8') for x in items] </code></pre> <p>I have the used the code snippet above to encode but i am...
-1
2016-07-11T14:29:11Z
38,309,632
<p>like so:</p> <pre><code>orig_list = [u'name', 523] mod_list = [x.encode('utf-8') if type(x) == str else x for x in orig_list] print(mod_list) # prints: [b'name', 523] </code></pre>
1
2016-07-11T14:33:53Z
[ "python" ]
How to encode unicode strings to utf-8 in a list with both unicode and float values using python
38,309,521
<p>I have a list with both unicode and float values:</p> <pre><code>list=[u'name',523] </code></pre> <p>I want to convert only the string to utf-8 in the list. How can i do that using python?</p> <pre><code>[x.encode('utf-8') for x in items] </code></pre> <p>I have the used the code snippet above to encode but i am...
-1
2016-07-11T14:29:11Z
38,309,674
<p>For python2: <code>[x.encode('utf-8') if isinstance(x, basestring) else x for x in items]</code></p> <p>For python3: <code>[x.encode('utf-8') if isinstance(x, str) else x for x in items]</code></p> <p>Or use <code>six</code>: <code>[x.encode('utf-8') if isinstance(x, six.string_types) else x for x in items]</code>...
-1
2016-07-11T14:36:04Z
[ "python" ]
How to encode unicode strings to utf-8 in a list with both unicode and float values using python
38,309,521
<p>I have a list with both unicode and float values:</p> <pre><code>list=[u'name',523] </code></pre> <p>I want to convert only the string to utf-8 in the list. How can i do that using python?</p> <pre><code>[x.encode('utf-8') for x in items] </code></pre> <p>I have the used the code snippet above to encode but i am...
-1
2016-07-11T14:29:11Z
38,309,699
<p>For python3, unicode objects are type <code>str</code>, so you want</p> <pre><code>[x.encode('utf-8') if isinstance(x, str) else x for x in items] </code></pre> <p>In python2, it's <code>unicode</code>,</p> <pre><code>[x.encode('utf-8') if isinstance(x, unicode) else x for x in items] </code></pre> <p>With the <...
1
2016-07-11T14:37:11Z
[ "python" ]
Switching between Layouts
38,309,570
<p>I've created a simple screen with a button that calls another screen when the button is clicked.</p> <p>I've searched a lot. But I'm still not able to do this: **How can I switch between my 2 layouts, So that when I click the button in test.py the layout changes to scherm.py **</p> <p>test.py</p> <pre><code>from ...
0
2016-07-11T14:31:25Z
38,309,973
<p>Instead of using <code>subprocess.call()</code>, I suggest you make <code>scherm</code> a QDialog. That way, instead of running another script in your slot <code>fun(self)</code>, you can simply create an instance of the class <code>Ui_PlatjesScherm</code>. You would need to add an <code>__init__</code> method for t...
0
2016-07-11T14:50:12Z
[ "python", "pyqt" ]
Joining Shorter Length Numpy Array to Pandas Dataframe
38,309,692
<p>I have a pandas dataframe with 506 rows. I have a numpy array with 501 elements that are calculated from the dataframe. </p> <p>I would like to join the numpy array to the dataframe, keeping the index of the dataframe and starting the index of the numpy array with the first index value of the dataframe.</p> <p>The...
1
2016-07-11T14:36:50Z
38,309,746
<p>I'd construct a <code>Series</code> from the np array, and then construct a new <code>Series</code> but pass the target df's index, this effectively reindexes the existing <code>Series</code>, introducing <code>NaN</code> values where there are no row values, this will align correctly against the target df:</p> <pr...
1
2016-07-11T14:39:27Z
[ "python", "numpy", "pandas" ]
Not able to implement a dynamic dropdown list in Django
38,309,707
<p>I need to implement two dropdown lists that the values of the seconds depends on the selection of the first.</p> <p>I was able to implement that in the backend but I am struggling to do it in the front end and more specifically with javascript!</p> <pre><code>countries = Country.objects.filter(Enabled=True) cities...
0
2016-07-11T14:37:34Z
38,312,099
<p>There are two solutions:</p> <p><strong>Solution 1:</strong></p> <p>use a for loop:</p> <pre><code>country_objs['{{country|escapejs}}'] = [{% for city in cities %}"city",{% endfor %}]; </code></pre> <p><strong>Solution 2:</strong></p> <p>Switch the line:</p> <pre><code>citiesByCountry[country.Name] = cities </...
1
2016-07-11T16:44:13Z
[ "javascript", "jquery", "python", "django" ]
Not able to implement a dynamic dropdown list in Django
38,309,707
<p>I need to implement two dropdown lists that the values of the seconds depends on the selection of the first.</p> <p>I was able to implement that in the backend but I am struggling to do it in the front end and more specifically with javascript!</p> <pre><code>countries = Country.objects.filter(Enabled=True) cities...
0
2016-07-11T14:37:34Z
38,312,243
<p>I think you want to remove the <code>|escapejs</code> filter for the part you want to be parsed in JavaScript. You might even find you need <code>|safe</code>, but you should be certain that you have control over what gets output there before considering that.</p> <pre><code>var country_objs = {}; {% for country, c...
0
2016-07-11T16:53:00Z
[ "javascript", "jquery", "python", "django" ]
Count unique values with pandas
38,309,729
<p>I should to count quantity unique <code>ID</code> to every <code>domain</code> I have data</p> <pre><code>ID, domain 123, 'vk.com' 123, 'vk.com' 123, 'twitter.com' 456, 'vk.com' 456, 'facebook.com' 456, 'vk.com' 456, 'google.com' 789, 'twitter.com' 789, 'vk.com' </code></pre> <p>I try <code>df.groupby(['domain', '...
2
2016-07-11T14:38:25Z
38,309,807
<p>You can do <code>value_counts()</code> on column <code>domain</code> after dropping the duplicated rows from the data frame:</p> <pre><code>import pandas as pd df.drop_duplicates().domain.value_counts() # 'vk.com' 3 # 'twitter.com' 2 # 'facebook.com' 1 # 'google.com' 1 # Name: domain, dtype: i...
4
2016-07-11T14:43:02Z
[ "python", "pandas" ]
Count unique values with pandas
38,309,729
<p>I should to count quantity unique <code>ID</code> to every <code>domain</code> I have data</p> <pre><code>ID, domain 123, 'vk.com' 123, 'vk.com' 123, 'twitter.com' 456, 'vk.com' 456, 'facebook.com' 456, 'vk.com' 456, 'google.com' 789, 'twitter.com' 789, 'vk.com' </code></pre> <p>I try <code>df.groupby(['domain', '...
2
2016-07-11T14:38:25Z
38,309,823
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html"><code>nunique</code></a>:</p> <pre><code>df = df.groupby('domain')['ID'].nunique() print (df) domain 'facebook.com' 1 'google.com' 1 'twitter.com' 2 'vk.com' 3 Name: ID, dtyp...
5
2016-07-11T14:43:54Z
[ "python", "pandas" ]