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
Iterate only one dict list from multi list dict
39,624,778
<p>I have a dict of lists like so:</p> <pre><code>edu_options = { 'Completed Graduate School' : ['medical','litigation','specialist'...], 'Completed College' : ['linguistic','lpn','liberal','chicano'... ], 'Attended College' : ['general','inprogress','courseworktowards','continu'...], </code></...
0
2016-09-21T19:13:58Z
39,625,463
<pre><code> for edu_level in edu_options: for option in edu_options[edu_level]: if cleaned_string in edu_options["Completed Graduate School"]: user = "Completed Graduate School" return user elif cleaned_string in edu_o...
0
2016-09-21T19:54:53Z
[ "python", "list", "dictionary" ]
Putting the return of my Python Script into a CSV file
39,624,781
<p>I have been recently working on a python script to look for missing reverse entries in our DNS servers on BIND and am having trouble figuring out a good way to able to return the output in preferably a CSV file.</p> <p>Here's the code I am working with and I know it is rough around the edges right now. Any help / i...
0
2016-09-21T19:14:02Z
39,625,860
<p>Try <code>openpyxl</code> instead, that one seems to work better for me.</p> <p><a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow" title="Documentation">Documentation</a></p>
0
2016-09-21T20:18:47Z
[ "python" ]
How do I add headers for the output csv for apache beam dataflow?
39,624,809
<p>I noticed in the java sdk, there is a function that allows you to write the headers of a csv file. <a href="https://cloud.google.com/dataflow/java-sdk/JavaDoc/com/google/cloud/dataflow/sdk/io/TextIO.Write.html#withHeader-java.lang.String-" rel="nofollow">https://cloud.google.com/dataflow/java-sdk/JavaDoc/com/google...
1
2016-09-21T19:15:07Z
39,625,500
<p>This feature does not yet exist in the Python SDK</p>
0
2016-09-21T19:57:26Z
[ "python", "google-cloud-dataflow", "apache-beam" ]
How do I add headers for the output csv for apache beam dataflow?
39,624,809
<p>I noticed in the java sdk, there is a function that allows you to write the headers of a csv file. <a href="https://cloud.google.com/dataflow/java-sdk/JavaDoc/com/google/cloud/dataflow/sdk/io/TextIO.Write.html#withHeader-java.lang.String-" rel="nofollow">https://cloud.google.com/dataflow/java-sdk/JavaDoc/com/google...
1
2016-09-21T19:15:07Z
39,625,521
<p>This is not implemented at this moment. However you can implement/extend it yourself (see <a href="https://gist.github.com/Fematich/97703910d867f972e9d01b21d8f41221" rel="nofollow">attached notebook</a> for an example+test with my version of apache_beam).</p> <p>This is based on a <a href="https://github.com/apache...
0
2016-09-21T19:58:53Z
[ "python", "google-cloud-dataflow", "apache-beam" ]
am getting a typeerror while executing python program
39,624,813
<p>I have typed </p> <pre><code>x = input("enter name: ") Print ("hey") + x </code></pre> <p>But when compiled am getting</p> <pre><code>Typeerror: unsupported operand type(s) for +: 'nonetype' and 'str' </code></pre> <p>I'm using python 3.6.0b1.</p>
-1
2016-09-21T19:15:18Z
39,624,868
<p>You are trying to add to the return value of <code>print</code> (which is <code>None</code>) to a string. Setting parentheses correctly is important.</p> <pre><code>x = input("enter name: ") print("hey" + x) </code></pre>
0
2016-09-21T19:18:33Z
[ "python", "typeerror" ]
am getting a typeerror while executing python program
39,624,813
<p>I have typed </p> <pre><code>x = input("enter name: ") Print ("hey") + x </code></pre> <p>But when compiled am getting</p> <pre><code>Typeerror: unsupported operand type(s) for +: 'nonetype' and 'str' </code></pre> <p>I'm using python 3.6.0b1.</p>
-1
2016-09-21T19:15:18Z
39,624,904
<p>print() is a function call which takes a string, so you need to pass the string inside the brackets to the function call like so;</p> <pre><code>x = input("enter name: ") print ("hey " + x) </code></pre> <p>Further reading on print() is available here: <a href="https://docs.python.org/3/tutorial/inputoutput.html" ...
0
2016-09-21T19:20:38Z
[ "python", "typeerror" ]
Anaconda allensdk NEURON model
39,624,891
<p>I've download Allen neuron model: Nr5a1-Cre VISp layer 2/3 473862496</p> <p>Installed Anaconda with all the required packages, have the NEURON: <a href="https://alleninstitute.github.io/AllenSDK/install.html" rel="nofollow">https://alleninstitute.github.io/AllenSDK/install.html</a></p> <p>now how do I use allensdk...
-1
2016-09-21T19:19:50Z
40,004,532
<p>Thanks for the question. The first example in your documentation link shows how to download a model, as you've probably done. I do this by writing a python script and running it from the command prompt.</p> <p>The script looks like this:</p> <pre class="lang-py prettyprint-override"><code>from allensdk.api.queri...
0
2016-10-12T17:12:38Z
[ "python", "neuron-simulator" ]
TypeError during assignment to attribute reference?
39,624,929
<p>Reading about <a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">Assignment statements</a> in the Python's docs I found this:</p> <blockquote> <p>If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an obje...
1
2016-09-21T19:21:59Z
39,624,994
<p>If you want to raise TypeError in your code:</p> <pre><code>raise TypeError </code></pre> <p>I suggest you read up on exceptions and exception handling in Python for more information. <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">https://docs.python.org/3/tutorial/errors.html</a> </p>
-2
2016-09-21T19:25:51Z
[ "python", "python-3.x", "typeerror", "attr" ]
TypeError during assignment to attribute reference?
39,624,929
<p>Reading about <a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">Assignment statements</a> in the Python's docs I found this:</p> <blockquote> <p>If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an obje...
1
2016-09-21T19:21:59Z
39,625,088
<p>This documentation line is just really out of date. It dates back to at least <a href="https://docs.python.org/release/1.4/ref/ref6.html#HDR2" rel="nofollow">Python 1.4</a>, long before type/class unification. I believe back then, trying to do something like</p> <pre><code>x = 1 x.foo = 3 </code></pre> <p>would ha...
4
2016-09-21T19:31:48Z
[ "python", "python-3.x", "typeerror", "attr" ]
TypeError during assignment to attribute reference?
39,624,929
<p>Reading about <a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">Assignment statements</a> in the Python's docs I found this:</p> <blockquote> <p>If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an obje...
1
2016-09-21T19:21:59Z
39,625,177
<p>This code produces a <code>TypeError</code> and it seems like it is what the documentation describes:</p> <pre><code>&gt;&gt;&gt; def f(): pass ... &gt;&gt;&gt; f.func_globals = 0 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: readonly attribute </code></pre> <p>But...
0
2016-09-21T19:38:06Z
[ "python", "python-3.x", "typeerror", "attr" ]
Need a bidirectional Map which allows duplicate values, and returns list of values given a key
39,624,938
<p>I have a need for a data structure which I think should be a common need<br> I need a Map which allows duplicate values(most commonly do, but wait.. getting to the point).. see this sample<br></p> <pre><code>k1 -&gt; v1 k2 -&gt; v1 k3 -&gt; v1 k4 -&gt; v2 k5 -&gt; v2 </code></pre> <p>Now if I do map.getByValue(v1)...
0
2016-09-21T19:23:02Z
39,625,050
<p>High performance means that you need some sort of index to search for a key. There are no indexes that work in both directions, so actually you need two of them. So you have to use two multimaps, one for each direction, and a wrapper that will maintain them in consistent state.</p>
0
2016-09-21T19:29:18Z
[ "java", "c#", "python", "data-structures" ]
pymongo: no such cmd: update
39,624,983
<p>I am using TxMongo 16.1.0 (this one uses pymongo under the hood), Mongodb 2.4.14 in my program.<br> I don't understand why I receive this pymongo.errors.OperationFailure: (It cannot recognize <code>update</code> cmd???) </p> <pre><code>TxMongo: command SON([('update', u'units'), ('updates', [SON([('q', {'baseIP'...
0
2016-09-21T19:25:18Z
39,626,444
<p>It turns out that this might be a bug of update_one() in TxMongo. Switch to update() will be fine. </p>
0
2016-09-21T20:56:13Z
[ "python", "pymongo" ]
AttributeError: 'module' object has no attribute 'urls'
39,625,054
<p>Python 2.7 &amp; Django 1.10 ERROR:</p> <pre><code>AttributeError: 'module' object has no attribute 'urls' </code></pre> <p><strong>main/urls.py</strong></p> <pre><code>from django.conf.urls import url, include from django.contrib import admin import article urlpatterns = [ url(r'^admin/', include(admin.sit...
0
2016-09-21T19:29:35Z
39,625,409
<p>It's easier to put just quotes around the includes and don't import articles. Like so:</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('article.urls')) ] </code></pre>
0
2016-09-21T19:52:02Z
[ "python", "django", "python-2.7", "web" ]
AttributeError: 'module' object has no attribute 'urls'
39,625,054
<p>Python 2.7 &amp; Django 1.10 ERROR:</p> <pre><code>AttributeError: 'module' object has no attribute 'urls' </code></pre> <p><strong>main/urls.py</strong></p> <pre><code>from django.conf.urls import url, include from django.contrib import admin import article urlpatterns = [ url(r'^admin/', include(admin.sit...
0
2016-09-21T19:29:35Z
39,630,954
<p>In main/urls.py</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin from article import urls urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include(urls)) ] </code></pre> <p>Or</p> <pre><code>from django.conf.urls import url, include from djang...
0
2016-09-22T05:31:25Z
[ "python", "django", "python-2.7", "web" ]
Improving code for similar code found
39,625,092
<p>I passed codeclimate to my code, and I obtained the following:</p> <blockquote> <p>Similar code found in 1 other location</p> </blockquote> <p>This is my code:</p> <pre><code>stradd = 'iterable_item_added' if stradd in ddiff: added = ddiff[stradd] npos_added = parseRoots(added) dics_added = makeAddD...
0
2016-09-21T19:32:05Z
39,625,366
<p>just abstract the parameters and create an helper method:</p> <pre><code>def testmethod(name,localTable,m,ddiff,pk): if name in ddiff: npos = parseRoots(ddiff[name]) rval = m(localTable, pk, npos) else: rval = [] return rval </code></pre> <p>the call it:</p> <pre><code>dics_ad...
1
2016-09-21T19:49:38Z
[ "python", "optimization", "code-climate" ]
Fitting only 2 paramter of a function with many parameters in python
39,625,122
<p>I know there is a question <br> <a href="http://stackoverflow.com/questions/12208634/fitting-only-one-paramter-of-a-function-with-many-parameters-in-python">Fitting only one paramter of a function with many parameters in python</a> <br> but I have a little bit different situation. Problem with parameters of lambda f...
0
2016-09-21T19:34:22Z
39,625,729
<p>Here is the solution for all 4 parameters of Lorentz function</p> <pre><code>import numpy as np from scipy.optimize import curve_fit def lorentz(ph, A, xc, w, f0): return f0 + A * w**2 / (w**2 + (ph - xc)**2) A, xc, w, f0 = 2,2,2,2 # true values ph = np.linspace(-5, 10, 100) y = lorentz(ph, A, xc, w, f0) ...
1
2016-09-21T20:10:52Z
[ "python", "lambda", "scipy", "curve-fitting" ]
Selecting the right else statement depending on user input
39,625,125
<p>I'm working on a little program where the user inputs a price and then the program would output the shipping cost based on the input.</p> <pre><code>#Initilaize variables lowUS = 6.00; medUS = 9.00; highUS = 12.00; lowCan = 8.00; medCan = 12.00; highCan = 15.00; #Greet user and ask for input print("Welcome to Ben...
0
2016-09-21T19:34:31Z
39,625,227
<p>Your first <code>if</code> only enters if it's less than or equal to 50... the next check you make is if it's greater than 50 which it can't be - so that block will never execute... So your <code>else</code> clause is the only one that can execute... Basically, your nested <code>if</code> statements won't execute be...
1
2016-09-21T19:41:34Z
[ "python", "variables", "if-statement" ]
Selecting the right else statement depending on user input
39,625,125
<p>I'm working on a little program where the user inputs a price and then the program would output the shipping cost based on the input.</p> <pre><code>#Initilaize variables lowUS = 6.00; medUS = 9.00; highUS = 12.00; lowCan = 8.00; medCan = 12.00; highCan = 15.00; #Greet user and ask for input print("Welcome to Ben...
0
2016-09-21T19:34:31Z
39,625,322
<p>Your logic is a bit screwy. If the amount is &lt;= $50, then it is not > $50 or &lt;= $100, so anything following that nested "if" will never execute:</p> <pre><code>if orderTotal &lt;= 50.00: if orderTotal &gt; 50.00 and orderTotal &lt;= 100.00: # ** this will never run ** else: # This will...
0
2016-09-21T19:47:15Z
[ "python", "variables", "if-statement" ]
Algorithm Complexity Analysis for Variable Length Queue BFS
39,625,159
<p>I have developed an algorithm that is kind of a variation of a BFS on a tree, but it includes a probabilistic factor. To check whether a node is the one I am looking for, a statistical test is performed (I won't get into too much detail about this). If the test result is positive, the node is added to another queue ...
1
2016-09-21T19:36:58Z
39,625,684
<p>The worst case scenario is the following process:</p> <blockquote> <ol> <li>All elements <em>1 : n-1</em> pass the test and are appended to the <code>tested</code> queue.</li> <li>Element <em>n</em> fails the test, is removed from <code>q</code>, and <em>n-1</em> elements from <code>tested</code> are pushed b...
0
2016-09-21T20:08:01Z
[ "python", "algorithm", "time-complexity", "analysis" ]
Cannot convert {'price_total__sum': Decimal('258.00')} to Decimal
39,625,175
<p>I get this error when I do a Sum of an entire column:</p> <pre><code>Cannot convert {'price_total__sum': Decimal('258.00')} to Decimal </code></pre> <p>here the entire project: <a href="https://github.com/pierangelo1982/djangocommerce/tree/berge" rel="nofollow">https://github.com/pierangelo1982/djangocommerce/tree...
-1
2016-09-21T19:38:01Z
39,625,236
<p>As the error shows, your <code>aggregate()</code> call returns a dictionary: <code>{'price_total__sum': Decimal('258.00')}</code>. You can't set that dict as a DecimalField in the target model; you need to extract the actual value first.</p> <pre><code>price_total = CartItem.objects.filter(user_id=request.user.id)....
1
2016-09-21T19:42:08Z
[ "python", "django", "virtualenv" ]
Difference between a+b and a.__add__(b)
39,625,229
<p>I am currently trying to understand where the difference between using <code>a+b</code> and <code>a.__add__(b)</code> is when it comes to custom classes. There are numerous websites that say that using the '+'-operator results in using the special method <code>__add__</code> - which is fine so far.</p> <p>But when ...
1
2016-09-21T19:41:46Z
39,625,287
<p><code>a+b</code> is equivalent to <code>import operator; operator.add(a,b)</code>. It starts by calling <code>a.__add__(b)</code> and then, if necessary, <code>b.__radd__(a)</code>. But <code>ifsubclass(type(b), type(a))</code>, then <code>b.__radd__(a)</code> is called first.</p> <p>Based on the <a href="https://d...
2
2016-09-21T19:44:47Z
[ "python" ]
find first instance of a row in pandas dataframe matching a criterion
39,625,302
<p>I have a dataframe giving event time (in days) and a value associated with each event. </p> <p>sorry for placing this in as code snippet, not sure of any other way to show format as a table in this question.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div...
0
2016-09-21T19:45:50Z
39,625,407
<p>Here's one approach using <code>searchsorted</code> -</p> <pre><code>df.EventTime[df.Value.searchsorted([.4,.7,.9])] </code></pre> <p>Sample run -</p> <pre><code>In [281]: df Out[281]: EventTime Value 0 333.690569 0.097736 1 942.624952 0.136822 2 211.588088 0.246093 3 514.476542 0.483235 4 650.7...
2
2016-09-21T19:51:51Z
[ "python", "pandas" ]
Pandas Grouping By Datetime
39,625,328
<p>I'm attempting to count the number of users that login to a system on an hourly basis on a given date. The date I have resembles: </p> <pre><code>df= Name Date name_1 2012-07-12 22:20:00 name_1 2012-07-16 22:19:00 name_1 2013-12-16 17:50:00 ... name_2 2010-01-11 19:54:00 name_2 2010-02-06 12:...
1
2016-09-21T19:47:25Z
39,625,417
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by column <code>Date</code> converted to <code>h</code> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel...
3
2016-09-21T19:52:39Z
[ "python", "datetime", "pandas", "time-series", "hour" ]
Pandas Grouping By Datetime
39,625,328
<p>I'm attempting to count the number of users that login to a system on an hourly basis on a given date. The date I have resembles: </p> <pre><code>df= Name Date name_1 2012-07-12 22:20:00 name_1 2012-07-16 22:19:00 name_1 2013-12-16 17:50:00 ... name_2 2010-01-11 19:54:00 name_2 2010-02-06 12:...
1
2016-09-21T19:47:25Z
39,625,651
<p>Another answer using resampling. Not very efficient, I think, but interesting.</p> <pre><code># Test data d = {'Date': ['2012-07-12 22:20:00', '2012-07-12 22:19:00', '2013-12-16 17:50:00', '2010-01-11 19:54:00', '2010-02-06 12:10:00', '2012-07-18 22:12:00'], 'Name': ['name_1', 'name_1', 'name_1', 'name_2', 'na...
1
2016-09-21T20:06:14Z
[ "python", "datetime", "pandas", "time-series", "hour" ]
How do I call a secured Google Apps Script web app endpoint?
39,625,336
<p>I want to make a POST request to my Google Apps Script Web App, but I don't know what format google wants me to send my credentials in. I have restricted access to the API to anyone in my gmail domain. The script that is making the POST request is written in Python and running automatically on a server, no user inpu...
-1
2016-09-21T19:47:59Z
39,665,062
<p>Up until a few months ago there was no authenticated way to do server to webapp calls. The webapp had to run as the author with anonymous access. Recently a new service was released called the Execution API. Which allows someone to execute a script using a simple REST call. </p> <p>Overview of the service:</p> <b...
0
2016-09-23T16:00:56Z
[ "python", "google-apps-script" ]
How to separate and graph lines in array by a value in each line
39,625,442
<p>I'm new to Python and am trying to pull data from a growing CSV, and create a live updating plot. I want to create two different x,y arrays depending on which antenna the data is coming through (one of the values in each line of data separated by commas). The data file looks like the following:</p> <p><div class="s...
1
2016-09-21T19:53:51Z
39,636,557
<p>You can simply plot each data set using the same axis. </p> <p>The following approach uses the Python <code>csv.DictReader</code> to help with reading in the data, along with a <code>defaultdict(list)</code> to automatically split the data into lists based on the antenna for each row.</p> <p>This also adds code to...
0
2016-09-22T10:26:27Z
[ "python" ]
generate a modified copy of a tuple
39,625,459
<p>I know I can't modify a tuple and I've seen ways to create a tuple from another one concatenating parts of the original manually like <a href="http://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple">here</a>.</p> <p>But wonder whether there has emerged some pythonic way to 'modify' a tuple by ...
1
2016-09-21T19:54:43Z
39,625,515
<p>You could use some kind of comprehension:</p> <pre><code>source_tuple = ('this', 'is', 'the', 'old', 'tuple') new_tuple = tuple((value if x != 3 else 'new' for x, value in enumerate(source_tuple))) # ('this', 'is', 'the', 'new', 'tuple') </code></pre> <p>This is rather idotic in this case but gi...
0
2016-09-21T19:58:27Z
[ "python", "tuples", "immutability" ]
generate a modified copy of a tuple
39,625,459
<p>I know I can't modify a tuple and I've seen ways to create a tuple from another one concatenating parts of the original manually like <a href="http://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple">here</a>.</p> <p>But wonder whether there has emerged some pythonic way to 'modify' a tuple by ...
1
2016-09-21T19:54:43Z
39,626,364
<p>If you need to create new tuple with replaced element, you may use something like this:</p> <pre><code>def replace_value_in_tuple(t, ind, value): return tuple( map(lambda i: value if i == ind else t[i], range(len(t))) ) </code></pre>
0
2016-09-21T20:50:35Z
[ "python", "tuples", "immutability" ]
generate a modified copy of a tuple
39,625,459
<p>I know I can't modify a tuple and I've seen ways to create a tuple from another one concatenating parts of the original manually like <a href="http://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple">here</a>.</p> <p>But wonder whether there has emerged some pythonic way to 'modify' a tuple by ...
1
2016-09-21T19:54:43Z
39,626,421
<hr> <p>You can use a slice on the tuple (which yields a new tuple) and concatenate:</p> <pre><code>&gt;&gt;&gt; x=3 &gt;&gt;&gt; new_tuple=source_tuple[0:x]+('new',)+source_tuple[x+1:] &gt;&gt;&gt; new_tuple ('this', 'is', 'the', 'new', 'tuple') </code></pre> <p>Which you can then support either a list or tuple lik...
2
2016-09-21T20:54:43Z
[ "python", "tuples", "immutability" ]
generate a modified copy of a tuple
39,625,459
<p>I know I can't modify a tuple and I've seen ways to create a tuple from another one concatenating parts of the original manually like <a href="http://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple">here</a>.</p> <p>But wonder whether there has emerged some pythonic way to 'modify' a tuple by ...
1
2016-09-21T19:54:43Z
39,626,638
<p>If you're thinking of swapping values on the fly, then a <code>list</code> is the more appropriate data structure; as we already know tuples are <em>immutable</em>.</p> <p>On another note, if you're looking for a <em>swap-value</em> logic in a <code>tuple</code>, you can have a look at <a href="https://docs.python....
1
2016-09-21T21:08:57Z
[ "python", "tuples", "immutability" ]
How do I retain source lines in tracebacks when running dynamically-compiled code objects?
39,625,465
<p>Say I use <a href="https://docs.python.org/2/library/functions.html#compile" rel="nofollow">compile</a> to create a <code>code</code> object from a string and a name:</p> <pre><code>&gt;&gt;&gt; a = compile('raise ValueError\n', '&lt;at runtime&gt;', 'exec') </code></pre> <p>I would like the lines within that stri...
1
2016-09-21T19:55:01Z
39,625,821
<p>Using the undocumented <code>cache</code> member of the builtin <a href="https://docs.python.org/2/library/linecache.html" rel="nofollow"><code>linecache</code></a>, this seems to work:</p> <pre><code>def better_compile(src, name, mode): # there is an example of this being set at # https://hg.python.org/cpy...
2
2016-09-21T20:15:50Z
[ "python" ]
How do I retain source lines in tracebacks when running dynamically-compiled code objects?
39,625,465
<p>Say I use <a href="https://docs.python.org/2/library/functions.html#compile" rel="nofollow">compile</a> to create a <code>code</code> object from a string and a name:</p> <pre><code>&gt;&gt;&gt; a = compile('raise ValueError\n', '&lt;at runtime&gt;', 'exec') </code></pre> <p>I would like the lines within that stri...
1
2016-09-21T19:55:01Z
39,626,362
<p>Well, you could write your own exception handler which fills the data:</p> <pre><code>code = """ def f1(): f2() def f2(): 1 / 0 f1() """ a = compile(code, '&lt;at runtime&gt;', 'exec') import sys import traceback try: exec(a) except: etype, exc, tb = sys.exc_info() exttb = traceback.extract...
0
2016-09-21T20:50:30Z
[ "python" ]
Django Form Failure
39,625,487
<p>I have the following form:</p> <pre><code># coding=utf-8 class SelectTwoTeams(BootstrapForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) self.currentSelectedTeam1 = kwargs.pop('currentSelectedTeam1', None) self.currentSelectedTeam2 = kwargs.pop('currentSelecte...
0
2016-09-21T19:56:24Z
39,625,921
<p>The difference between those is not "separating the fields". It is that you have switched from the full form representation - including form labels, layout, and most importantly errors - to only displaying the two input fields themselves. </p> <p>That's fine to do of course, as for most purposes you will want the e...
1
2016-09-21T20:22:17Z
[ "python", "django" ]
How do you optimize this code for nn prediction?
39,625,552
<p>How do you optimize this code? At the moment it is running to slow for the amount of data that goes through this loop. This code runs 1-nearest neighbor. It will predict the label of the training_element based off the p_data_set</p> <pre><code># [x] , [[x1],[x2],[x3]], [l1, l2, l3] def pr...
1
2016-09-21T20:00:38Z
39,625,784
<p>You could use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist" rel="nofollow"><code>distance.cdist</code></a> to directly get the distances <code>temp</code> and then use <code>.argmin()</code> to get min-index, like so -</p> <pre><code>min...
1
2016-09-21T20:13:42Z
[ "python", "performance", "numpy", "scipy", "nearest-neighbor" ]
How do you optimize this code for nn prediction?
39,625,552
<p>How do you optimize this code? At the moment it is running to slow for the amount of data that goes through this loop. This code runs 1-nearest neighbor. It will predict the label of the training_element based off the p_data_set</p> <pre><code># [x] , [[x1],[x2],[x3]], [l1, l2, l3] def pr...
1
2016-09-21T20:00:38Z
39,625,848
<p>Use a <a href="https://en.wikipedia.org/wiki/K-d_tree" rel="nofollow"><em>k</em>-D tree</a> for fast nearest-neighbour lookups, e.g. <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html" rel="nofollow"><code>scipy.spatial.cKDTree</code></a>:</p> <pre><code>from scipy.spatial impor...
2
2016-09-21T20:17:35Z
[ "python", "performance", "numpy", "scipy", "nearest-neighbor" ]
How do you optimize this code for nn prediction?
39,625,552
<p>How do you optimize this code? At the moment it is running to slow for the amount of data that goes through this loop. This code runs 1-nearest neighbor. It will predict the label of the training_element based off the p_data_set</p> <pre><code># [x] , [[x1],[x2],[x3]], [l1, l2, l3] def pr...
1
2016-09-21T20:00:38Z
39,626,372
<p>Python can be quite fast programming language if used properly. This is my suggestion (faster_prediction):</p> <pre><code>import numpy as np import time def euclidean(a,b): return np.linalg.norm(a-b) def prediction(training_element, p_data_set, p_label_set): temp = np.array([], dtype=float) for p in p...
0
2016-09-21T20:51:26Z
[ "python", "performance", "numpy", "scipy", "nearest-neighbor" ]
When do system variables update in IPython kernel?
39,625,721
<p>I started a notebook by doing <code>jupyter notebook</code>, and then creating a new notebook. </p> <p>Then, I went to the terminal, and I set the PATH:</p> <pre><code>export PATH=$PATH:&lt;absolute path&gt; </code></pre> <p>But, then when I go back to the IPython notebook, I try to print this new system variabl...
0
2016-09-21T20:10:17Z
39,625,875
<p>When you do</p> <pre><code>export PATH=$PATH:&lt;absolute path&gt; </code></pre> <p>in a terminal, it is only effective in this terminal session. That is to say, this <code>export</code> command has no effect on other terminal sessions.</p> <p>If you want your PATH environment to be effective all the way, you nee...
1
2016-09-21T20:19:46Z
[ "python", "osx", "environment-variables", "ipython", "jupyter-notebook" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,625,900
<p>Not sure why you need the <code>for</code> in the <code>sum</code>. It appears that <code>x</code> isn't used anywhere. This could be simplified to:</p> <pre><code>def sum_array(arr): return 0 if not arr else sum(sorted(arr)[1:-1]) </code></pre>
1
2016-09-21T20:21:20Z
[ "python", "if-statement", "list-comprehension" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,625,920
<p>The easiest way to know where both the max and min is is to sort the list.</p> <pre><code>arr = sorted(arr) </code></pre> <p>arr[0] is the smallest, arr[-1] is the largest</p> <p>So</p> <pre><code>if arr is None: return 0 else: return sum(sorted(arr)[1:-1]) </code></pre>
0
2016-09-21T20:22:17Z
[ "python", "if-statement", "list-comprehension" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,625,927
<p>Your code is almost correct except that the last logic doesn't apply.</p> <pre><code>def sum_array(arr): return sum(sorted(arr)[1:-1]) if arr else 0 </code></pre>
0
2016-09-21T20:22:34Z
[ "python", "if-statement", "list-comprehension" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,625,936
<blockquote> <p>Beautiful is better than ugly.</p> </blockquote> <pre><code>def sum_array(arr): if arr is None or len(arr) &lt;= 1: return 0 else: return sum(sorted(arr)[1:-1]) </code></pre>
2
2016-09-21T20:23:01Z
[ "python", "if-statement", "list-comprehension" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,626,090
<p>Here's a version which meets your requirements:</p> <pre><code>def sum_array(arr): return (None if len(arr) &lt;= 1 else 0) if not arr else sum(sorted(arr)[1:-1]) cases = [[j + 1 for j in range(i)] for i in range(5)] for c in cases: print(c, sum_array(c)) # Requirements: Objective is to calculate sum of ...
0
2016-09-21T20:33:28Z
[ "python", "if-statement", "list-comprehension" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,626,538
<p>You get <code>TypeError</code> because you try to <code>sum</code> lists. Let me change your code a little bit:</p> <pre><code> In[1]: arr = [1, 2, 3, 4, 5] [sorted(arr)[1:-1] for x in range(len(arr))] Out[1]: [[2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4]] </code></pre> <p>I change your generator...
0
2016-09-21T21:02:08Z
[ "python", "if-statement", "list-comprehension" ]
Sum of list without lowest and highest list integers (python)
39,625,834
<p>Trying to practice my list comprehension, but at this point my code is looking a little (too) long per line length comprehension: </p> <pre><code>def sum_array(arr): return 0 if arr == None else sum(sorted(arr)[1:-1] for x in range(len(arr or [])-2)) </code></pre> <p>Objective is to calculate sum of integers ...
0
2016-09-21T20:16:32Z
39,627,125
<p>Just an alternative way using <code>lambda</code> and <code>reduce</code>:</p> <pre><code>s = 0 if arr == None else reduce(lambda x, y: x+y, sorted(arr)[1:-1]) </code></pre>
0
2016-09-21T21:50:46Z
[ "python", "if-statement", "list-comprehension" ]
Crash when sending email in Python 2.7.10
39,625,905
<p>I'm trying to send an email within python, but the program is crashing when I run it either as a function in a larger program or on it's own in the interpreter.</p> <pre><code>import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText fromaddr = "[email protected]" toaddr ...
-1
2016-09-21T20:21:36Z
39,654,563
<p>My standard suggestion (as I'm the developer of it) is <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a>.</p> <p>Install: <code>pip install yagmail</code></p> <p>Then:</p> <pre><code>import yagmail yag = yagmail.SMTP(fromaddr, "pasword") yag.send(toaddr, "Hi there", "example") </code></pre>...
0
2016-09-23T07:00:39Z
[ "python", "email", "smtp" ]
Crash when sending email in Python 2.7.10
39,625,905
<p>I'm trying to send an email within python, but the program is crashing when I run it either as a function in a larger program or on it's own in the interpreter.</p> <pre><code>import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText fromaddr = "[email protected]" toaddr ...
-1
2016-09-21T20:21:36Z
39,654,848
<p>That's because you are getting error when trying to connect Google SMTP server. Note that if you are using Google SMTP you should use:</p> <p>Username: Your gmail address<br> Password: Your gmail password</p> <p>And you should be already logged in. If you still get an error, you should check what is the problem in...
0
2016-09-23T07:16:22Z
[ "python", "email", "smtp" ]
Parsing CSV using Python
39,625,962
<p>I have the following csv file that has three fields Vulnerability Title, Vulnerability Severity Level , Asset IP Address which shows vulnerabilities name , level of vulnerability and IP address that is having that vulnerability. I am trying to print a report that would list vulnerability in a column severity next t...
1
2016-09-21T20:24:37Z
39,626,554
<p>Answer considering your car example. Essentially, I am creating a dictionary which has the car brand as the key, and a two element tuple. The first element of the tuple is the color and the second, a list of owners.):</p> <pre><code>import csv car_dict = {} with open('&lt;file_to_read&gt;', 'rb') as fi: reader...
1
2016-09-21T21:03:22Z
[ "python", "csv", "dictionary", "setdefault" ]
Parsing CSV using Python
39,625,962
<p>I have the following csv file that has three fields Vulnerability Title, Vulnerability Severity Level , Asset IP Address which shows vulnerabilities name , level of vulnerability and IP address that is having that vulnerability. I am trying to print a report that would list vulnerability in a column severity next t...
1
2016-09-21T20:24:37Z
39,626,676
<p>When manipulate structured date, especially large data set. I would like to suggest you to use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>.</p> <p>For your problem, I will give you an example of pandas groupby feature as solution. Suppose you have the data:</p> <pre><code>data = [['vt1', 3, '10.0...
1
2016-09-21T21:12:22Z
[ "python", "csv", "dictionary", "setdefault" ]
Getting position of user click in pygame
39,626,018
<p>I have a pygame window embedded in a a frame in tkinter. In another frame I have a button which calls the following function when clicked:</p> <pre><code>def setStart(): global start # set start position for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: start = event.pos pr...
0
2016-09-21T20:28:59Z
39,648,328
<p>First I have to say that I don't know anything about pygame. However, if you are already using Tkinter, I could help you maybe: I would define a new function (let's call it mouse_click). In the button-click-function I would bind the new function to the game's surface. In the new function I print out the current mous...
0
2016-09-22T20:28:59Z
[ "python", "python-2.7", "tkinter", "pygame", "pygame-surface" ]
Getting position of user click in pygame
39,626,018
<p>I have a pygame window embedded in a a frame in tkinter. In another frame I have a button which calls the following function when clicked:</p> <pre><code>def setStart(): global start # set start position for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: start = event.pos pr...
0
2016-09-21T20:28:59Z
39,660,950
<p>In the most basic form here's how you do it in pygame:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((100, 100)) clock = pygame.time.Clock() while True: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: # or MOUSEBUTTONDOWN depen...
0
2016-09-23T12:37:14Z
[ "python", "python-2.7", "tkinter", "pygame", "pygame-surface" ]
Make a list of ranges in numpy
39,626,041
<p>I want to make a list of integer sequences with random start points. The way I would do this in pure python is </p> <pre> x = np.zeros(1000, 10) # 1000 sequences of 10 elements each starts = np.random.randint(1, 1000, 1000) for i in range(len(x)): x[i] = np.arange(starts[i], starts[i] + 10) </pre> <p>I wonder ...
0
2016-09-21T20:30:17Z
39,626,089
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> after extending <code>starts</code> to a <code>2D</code> version and adding in the <code>1D</code> range array, like so -</p> <pre><code>x = starts[:,None] + np.arange(10) </code></pre> ...
0
2016-09-21T20:33:24Z
[ "python", "numpy" ]
delete space in one line prints
39,626,058
<p>How to remove spaces in this print ?</p> <p>For example</p> <pre><code>for i in range(5): print i, </code></pre> <p>Will prints: 1 2 3 4 5</p> <p>But I would like to get print like: 12345</p> <p>Someone can help ?</p>
-4
2016-09-21T20:31:51Z
39,626,273
<p>In Python 3, you can use:</p> <pre><code>for i in range(5): print(i, end="") </code></pre> <p>In Python 2, however you can not achieve it via simple print. There are two ways to do it:</p> <pre><code># Way 1: Using "sys.stdout". But this will write to stdout &gt;&gt;&gt; import sys &gt;&gt;&gt; for i in rang...
0
2016-09-21T20:44:06Z
[ "python", "printing", "spaces" ]
pyFFTW doesn't find libfftw3l.so while import
39,626,070
<p>In my Raspbian system I have succesfully installed pyFFTW, but there is a problem while import package.</p> <pre><code> import pyfftw File "/usr/local/lib/python3.4/dist-packages/pyfftw/__init__.py", line 16, in &lt;module&gt; from .pyfftw import ( ImportError: libfftw3l.so.3: cannot open shared object file...
0
2016-09-21T20:32:28Z
39,626,071
<p>The problem was with PYTHONPATH.</p> <p>To check if the file is somewhere at the disk:</p> <pre><code>$ sudo file / -name libfftw3l.so.3 /home/pi/bin/fftw-3.3.5/.libs/libfftw3.so.3 /usr/lib/arm-linux-gnueabihf/libfftw3.so.3 /usr/local/lib/libfftw3.so.3 </code></pre> <p>And add a line before import pyfftw (see <a ...
0
2016-09-21T20:32:28Z
[ "python", "path", "pyfftw" ]
Python (pip) throwing [SSL: CERTIFICATE_VERIFY_FAILED] even if certificate chain updated
39,626,142
<p>This is a followup to a <a href="http://stackoverflow.com/q/39356413/827480">previous SO post</a>.</p> <p>I am using Windows/cygwin and I have the need for python to understand a custom CA certificate, as the network infrastructure resigns all SSL requests with its own certificate.</p> <p>If I try to run <code>pip...
0
2016-09-21T20:36:40Z
39,626,495
<p>You can add pip command line option defaults to its configuration file. In windows, it should be located under %APPDATA%\pip\pip.ini.</p> <p>To add a certificate, put the following lines in the file:</p> <pre><code>[global] cert = windows path to your certificate </code></pre>
1
2016-09-21T21:00:01Z
[ "python", "windows", "ssl", "https", "cygwin" ]
Why i can't install autopy?
39,626,215
<p>I'm using MacBook and Operating System is MacOS Sierra.</p> <p>I use this command to install autopy:</p> <pre><code>sudo pip install autopy </code></pre> <p>But i get this error:</p> <pre><code>Collecting autopy Downloading autopy-0.51.tar.gz (74kB) 100% |███████████████████...
0
2016-09-21T20:40:54Z
39,626,280
<p>There is a known issue that for some reason wasn't fixed.</p> <p>Issue: <a href="https://github.com/msanders/autopy/issues/75" rel="nofollow">https://github.com/msanders/autopy/issues/75</a></p> <p>It contains following workaround (commands to type in console):</p> <pre><code>brew install libpng CFLAGS="-Wno-retu...
1
2016-09-21T20:45:02Z
[ "python", "osx", "macos-sierra", "autopy" ]
How did numpy implement multi-dimensional broadcasting?
39,626,233
<p>Memory (row major order):</p> <pre><code>[[A(0,0), A(0,1)] [A(1,0), A(1,1)]] has this memory layout: [A(0,0), A(0,1), A(1,0), A(1,1)] </code></pre> <p>I guess the algorithm work like this in the following cases.</p> <p>Broadcasting Dimension is last dimension:</p> <pre><code>[[0, 1, 2, 3] [[1] ...
3
2016-09-21T20:42:04Z
39,626,641
<p>To really get into broadcasting details you need to understand array shape and strides. But a lot of the work is now implemented in <code>c</code> code using <code>nditer</code>. You can read about it at <a href="http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html" rel="nofollow">http://docs.scipy.org/doc...
3
2016-09-21T21:09:18Z
[ "python", "c", "numpy" ]
How do I draw a plot using pyqtgraph on PyQt4 widget created in QT Designer?
39,626,294
<p>I'm just starting with pyqtgraph. I have a graphicsView widget that I promoted with QT designer per the documentation. I would like to try a plot to see if it works. When I tried <code>pg.plot(x,y)</code> the program created a plot in a separate window rather than in the graphicsView widget. I'm using Windows 10, Py...
0
2016-09-21T20:46:03Z
40,052,282
<p>Can you share the ui_pumptest.py file source? Otherwise it's hard to tell what your intentions are. If not, at least detail what construct you used to place in the QGraphicsView promotion process in QtDesigner (assuming you followed <a href="http://www.pyqtgraph.org/documentation/how_to_use.html#embedding-widgets-i...
0
2016-10-14T21:29:18Z
[ "python", "pyqt4", "pyqtgraph" ]
Return from root to user using python os.system('kill') not working
39,626,329
<p>I need to run a command from my python script as a root user (just sudo wont work), so I use os.system('sudo su') and am able to get root access. But again I need to return back to user . I tried os.system('exit'), but it still doesnt come out of root login to user login. I have to manually enter exit in the termina...
0
2016-09-21T20:48:17Z
39,640,415
<p>Your <code>echo</code> command doesn't work with <code>sudo</code> because the redirection to <code>&gt; /sys/bus/...</code> is made by your own user, and then given to <code>sudo echo</code>, but root is required to access the file in the 1st place.</p> <p>Try using <code>sudo bash -c 'command &gt; redirect'</code...
0
2016-09-22T13:27:43Z
[ "python", "root", "exit", "os.system" ]
n-dataframes inner joined to final dataframe
39,626,332
<p>I'm trying to figure out how to inner merge n-dataframes to a single final dataframe.</p> <p>I need to be able to specify a list of dataframes in which the inner join of <strong>all</strong> is output as another dataframe. Again, the exact number will not be known in advance, but the integer count can be.</p> <p>S...
1
2016-09-21T20:48:26Z
39,627,468
<p>How about this:</p> <pre><code>dflist = [df1, df2, df3, df4] result_final = reduce(lambda x,y: x.merge(y, on=['Col1', 'Col2', 'Col3', 'Col4'], how='inner'), dflist) </code></pre>
1
2016-09-21T22:23:23Z
[ "python", "pandas" ]
n-dataframes inner joined to final dataframe
39,626,332
<p>I'm trying to figure out how to inner merge n-dataframes to a single final dataframe.</p> <p>I need to be able to specify a list of dataframes in which the inner join of <strong>all</strong> is output as another dataframe. Again, the exact number will not be known in advance, but the integer count can be.</p> <p>S...
1
2016-09-21T20:48:26Z
39,631,467
<pre><code>cols = ['Col1', 'Col2', 'Col3', 'Col4'] pd.concat([d.set_index(cols) for d in [df_1, df_2, df_3, df_4]], axis=1) </code></pre>
1
2016-09-22T06:09:04Z
[ "python", "pandas" ]
Python data will not input into CSV file
39,626,359
<p>I am working on a project for my shop that would allow me to track dimensions for my statistical process analysis. I have a part with 2 dimensions that I will measure 5 samples for. The dimension are OAL (Over All Length) and a Barb Diameter. I got Python and tKinter to create the window and put all the data into...
0
2016-09-21T20:50:18Z
39,627,644
<p>Simply pass those variables in the method, <code>writeCsv()</code>. Because the <em>groupOas</em> are local to the <code>submitEntry()</code> function, its called function, <code>writeCsv</code>, does not see such objects. Also, below uses the <a href="http://stackoverflow.com/questions/36901/what-does-double-star-a...
0
2016-09-21T22:44:56Z
[ "python", "csv", "tkinter" ]
How to get odds-ratios and other related features with scikit-learn
39,626,401
<p>I'm going through this <a href="http://www.ats.ucla.edu/stat/mult_pkg/faq/general/odds_ratio.htm" rel="nofollow">odds ratios in logistic regression tutorial</a>, and trying to get the exactly the same results with the logistic regression module of scikit-learn. With the code below, I am able to get the coefficient a...
0
2016-09-21T20:53:29Z
39,630,166
<p>You can get the odds ratios by taking the exponent of the coeffecients:</p> <pre><code>import numpy as np X = df.female.values.reshape(200,1) clf.fit(X,y) np.exp(clf.coef_) # array([[ 1.80891307]]) </code></pre> <p>As for the other statistics, these are not easy to get from scikit-learn (where model evaluation is...
0
2016-09-22T04:16:42Z
[ "python", "scikit-learn" ]
How to get odds-ratios and other related features with scikit-learn
39,626,401
<p>I'm going through this <a href="http://www.ats.ucla.edu/stat/mult_pkg/faq/general/odds_ratio.htm" rel="nofollow">odds ratios in logistic regression tutorial</a>, and trying to get the exactly the same results with the logistic regression module of scikit-learn. With the code below, I am able to get the coefficient a...
0
2016-09-21T20:53:29Z
39,711,837
<p>In addition to @maxymoo's answer, to get other statistics, <code>statsmodel</code> can be used. Assuming that you have your data in a <code>DataFrame</code> called <code>df</code>, the code below should show a good summary:</p> <pre><code>import pandas as pd from patsy import dmatrices import statsmodels.api as sm ...
0
2016-09-26T20:28:57Z
[ "python", "scikit-learn" ]
add dimension to an xarray DataArray
39,626,402
<p>I need to add a dimension to a <code>DataArray</code>, filling the values across the new dimension. Here's the original array.</p> <pre><code>a_size = 10 a_coords = np.linspace(0, 1, a_size) b_size = 5 b_coords = np.linspace(0, 1, b_size) # original 1-dimensional array x = xr.DataArray( np.random.random(a_siz...
2
2016-09-21T20:53:30Z
39,627,264
<p>You've done a pretty thorough analysis of the current options, and indeed none of these are very clean.</p> <p>This would certainly be useful functionality to write for xarray, but nobody has gotten around to implementing it yet. Maybe you would be interested in helping out?</p> <p>See this GitHub issue for some A...
1
2016-09-21T22:03:56Z
[ "python", "python-xarray" ]
how to calculate entropy from np histogram
39,626,432
<p>I have an example of a histogram with:</p> <pre><code>mu1 = 10, sigma1 = 10 s1 = np.random.normal(mu1, sigma1, 100000) </code></pre> <p>and calculated </p> <pre><code>hist1 = np.histogram(s1, bins=50, range=(-10,10), density=True) for i in hist1[0]: ent = -sum(i * log(abs(i))) print (ent) </code></pre> <p>No...
1
2016-09-21T20:55:30Z
39,626,753
<p>You can calculate the entropy using vectorized code:</p> <pre><code>import numpy as np mu1 = 10 sigma1 = 10 s1 = np.random.normal(mu1, sigma1, 100000) hist1 = np.histogram(s1, bins=50, range=(-10,10), density=True) data = hist1[0] ent = -(data*np.log(np.abs(data))).sum() # output: 7.1802159512213191 </code></pre>...
1
2016-09-21T21:19:22Z
[ "python", "numpy", "histogram", "entropy" ]
Appropriate Time to Dynamically Set Variable Names?
39,626,439
<p>Edit: Turns out the answer is an emphatic "no". However, I'm still struggling to populate the lists with the right amount of entries. </p> <hr> <p>I've been searching StackOverflow all over for this, and I keep seeing that dynamically setting variable names is not a good solution. However, I can't think of another...
0
2016-09-21T20:55:46Z
39,626,943
<p>So, like this?</p> <pre><code>import collections import csv import io reader = csv.DictReader(io.StringIO(''' week,str1,str2,str3 1,8,2,5 2,1,0,3 3,2,1,1 '''.strip())) data = collections.defaultdict(list) for row in reader: for key in ('str1', 'str2', 'str3'): data[key].extend([row['week']]*int(row[ke...
1
2016-09-21T21:35:30Z
[ "python", "pandas", "dataframe" ]
distance from root search of tree fails
39,626,562
<p>The tree is as follows:</p> <pre class="lang-py prettyprint-override"><code> (1,1) / \ (2,1) (1,2) / \ / \ (3,1)(2,3) (3,2)(1,3) and onward </code></pre> <p>The root is (1,1), all values in the tree are tuples.</p> <pre><code>Where (x,y) is an element of the tree: The leftChil...
1
2016-09-21T21:04:06Z
39,652,148
<p>Floor division allows for no loss, but maybe -1 in error which I consider for the code below.</p> <pre class="lang-py prettyprint-override"><code>def answer(M,F): M = int(M) F = int(F) i = 0 while True: if M == 1 and F == 1: return str(i) if M &gt; F: x = F-M ...
0
2016-09-23T03:34:09Z
[ "python", "algorithm", "data-structures", "tree", "binary-tree" ]
Confusion on how to do add basic indexing in sqlalchemy after table creation
39,626,659
<p>I am trying to get a simple example of indexing working with a database that has 100,000 entries and see how it improves speed. The table looks something like this:</p> <pre><code>user = Table('user', metadata, Column('id', Integer, primary_key=True), Column('first_name', String(16), nullable=False), Co...
1
2016-09-21T21:10:36Z
39,626,777
<p>Indexing in SQL and thus in SQLAlchemy is happening behind the scene.</p> <p>Indexing is a feature of the underlying SQL engine and doesn't need any special query in order to utilize the performance gain. The mere definition is sufficient.</p>
0
2016-09-21T21:21:38Z
[ "python", "mysql", "indexing", "sqlalchemy" ]
Solving a first order BVP with two boundary conditions with scipy's solve_bvp
39,626,681
<p>I am using scipy's BVP solver: </p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_bvp.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_bvp.html</a></p> <p>The problem I am running into is that you can only have as many boundary c...
2
2016-09-21T21:12:47Z
39,643,988
<p>If you specify two boundary conditions y(0)=1 and y(1)=1 for a first order ODE, then in general the problem is overdetermined and <em>there is no solution</em>. If you specify just the initial condition y(0)=y0, you have a first order initial value problem. In fact, in this case, you can derive the exact solution: y...
1
2016-09-22T16:11:07Z
[ "python", "numpy", "scipy", "numerical-methods", "differential-equations" ]
Python Jinja2 call to macro results in (undesirable) newline
39,626,767
<p>My JINJA2 template is like below.</p> <pre><code>{% macro print_if_john(name) -%} {% if name == 'John' -%} Hi John {%- endif %} {%- endmacro %} Hello World! {{print_if_john('Foo')}} {{print_if_john('Foo2')}} {{print_if_john('John')}} </code></pre> <p>The resulting output is</p> <pre><code>Hello•World! Hi•...
1
2016-09-21T21:20:27Z
39,626,907
<p>The newlines come from the <code>{{print_if_john(...)}}</code> lines themselves, <em>not</em> the macro. </p> <p>If you were to join those up or use <code>-</code> within those blocks, the newlines disappear:</p> <pre><code>&gt;&gt;&gt; from jinja2 import Template &gt;&gt;&gt; t = Template('''\ ... {% macro print_...
1
2016-09-21T21:32:24Z
[ "python", "macros", "jinja2" ]
Getting new objects in the image
39,626,806
<p>i am trying to build a card recognition machine. The thing is the cards will be put on top of a cenario.</p> <p>That being said i come for help on how can i compare to images, one is the empty background(cenario) and the other is the same cenario with a card on top of it.</p> <pre><code>import numpy as np from PIL...
1
2016-09-21T21:23:52Z
39,627,314
<p>If you are working with real images, I suggest the following:</p> <ul> <li>read colour images</li> <li>do some initial presmoothing</li> <li>substract grayscale images and threshold the result</li> <li>optionally do some morphological closing</li> <li>find the biggest region on the thresholded image with labelling<...
0
2016-09-21T22:08:32Z
[ "python", "opencv" ]
Python Pandas: Write certain rows in file
39,626,818
<p>The csv file is way to big, so I am reading it chunk by chunk. Therefore, I use read_csv with chunksize.</p> <p>I want to store all rows, where the last entry has the value 1 in one file and all the other rows where the last entry is 0 in another file.</p> <p>Suppose it looks like this:</p> <pre><code>ID A B...
0
2016-09-21T21:25:42Z
39,626,851
<p>From <a href="http://stackoverflow.com/questions/19674212/pandas-data-frame-select-rows-and-clear-memory">this</a> post:</p> <blockquote> <pre><code>reader = pd.read_csv('big_table.txt', sep='\t', header=0, index_col=0, usecols=the_columns_i_want_to_use, chunksize=10000) ...
1
2016-09-21T21:28:24Z
[ "python", "pandas" ]
Python Pandas: Write certain rows in file
39,626,818
<p>The csv file is way to big, so I am reading it chunk by chunk. Therefore, I use read_csv with chunksize.</p> <p>I want to store all rows, where the last entry has the value 1 in one file and all the other rows where the last entry is 0 in another file.</p> <p>Suppose it looks like this:</p> <pre><code>ID A B...
0
2016-09-21T21:25:42Z
39,630,613
<p>I would simply do it like this:</p> <pre><code>first = True df = pd.read_csv('file.csv', chunksize=1e5) for chunk in df: if first: chunk[chunk['C'] == 1].to_csv('ones.csv', header=True) chunk[chunk['C'] == 0].to_csv('zero.csv', header=True) first = False chunk[chunk['C'] == 1].to_csv...
0
2016-09-22T04:59:59Z
[ "python", "pandas" ]
Python SSH and comparing output to an imported list
39,626,819
<p>I am looking to ssh to multiple servers 1 at a time , compare the output of an ssh command to a list, and then run a command on the items in that appear in both the output and a separate list.</p> <p>I'd like to ssh to each server in a loop "ssh " but I'm unsure how to import the next server from the list into the...
-3
2016-09-21T21:25:45Z
39,627,891
<p>The answer to your question if I understood correctly lies in Operative Systems principles,</p> <p>You iterate the SSH connection list, and by using Popen you are able to SSH via Shell.</p> <p>After that you need to keep a second process open as well a Pipe for the 2 processes to communicate(the one that opened th...
0
2016-09-21T23:14:47Z
[ "python", "list", "loops", "ssh" ]
else essentially superfluous
39,626,857
<p>I don't have a background in programming, so this is probably really dumb, but I've never considered this before: it seems that the <code>else</code> statement is essentially superfluous because when the condition is False, Python just moves to the next unindented line .</p> <p>For example, normally you would write...
0
2016-09-21T21:28:40Z
39,626,893
<p>If the conditions are mutually exclusive then <code>else</code> is superfluous. It's not if the conditions overlap, though.</p> <pre><code>x = 2 if x &gt; 0: print 'foo' else: # better -- elif x &gt; 1: if x &gt; 1: print 'bar' </code></pre> <p>This program prints <code>foo</code>...
2
2016-09-21T21:31:13Z
[ "python", "if-statement", "syntax" ]
else essentially superfluous
39,626,857
<p>I don't have a background in programming, so this is probably really dumb, but I've never considered this before: it seems that the <code>else</code> statement is essentially superfluous because when the condition is False, Python just moves to the next unindented line .</p> <p>For example, normally you would write...
0
2016-09-21T21:28:40Z
39,626,896
<p>Else is never a must but is rather a convenience. Here are some:</p> <pre><code>if x == 1: value = "one" else: value = "not_one" </code></pre> <p>or</p> <pre><code>if x &lt; 1: value = "less_than_one" elif x &lt; 2: value = "between_one_and_two" else: value = "more_than_two" </code></pre> <...
0
2016-09-21T21:31:26Z
[ "python", "if-statement", "syntax" ]
else essentially superfluous
39,626,857
<p>I don't have a background in programming, so this is probably really dumb, but I've never considered this before: it seems that the <code>else</code> statement is essentially superfluous because when the condition is False, Python just moves to the next unindented line .</p> <p>For example, normally you would write...
0
2016-09-21T21:28:40Z
39,627,132
<p>The <code>else</code> clause is useful if you are looking for a specific case (using <code>if</code>) and then everything else that is not covered by the <code>if</code> (using <code>else</code>). </p> <p>Often a <a href="https://docs.python.org/2.5/whatsnew/pep-308.html" rel="nofollow">conditional expression</a> i...
0
2016-09-21T21:51:11Z
[ "python", "if-statement", "syntax" ]
else essentially superfluous
39,626,857
<p>I don't have a background in programming, so this is probably really dumb, but I've never considered this before: it seems that the <code>else</code> statement is essentially superfluous because when the condition is False, Python just moves to the next unindented line .</p> <p>For example, normally you would write...
0
2016-09-21T21:28:40Z
39,627,407
<p><code>else</code> <em>remembers</em> that the condition was <code>False</code>. For example, consider this code:</p> <pre><code>if x == 1: x = 2 print("bar") else: if x == 2: print("foo") </code></pre> <p><em>With</em> the <code>else</code>, only one of "bar" or "foo" will be printed.</p> <p><em...
1
2016-09-21T22:16:17Z
[ "python", "if-statement", "syntax" ]
Scrapy Pipeline not starting
39,626,870
<p>I'm having problems with Scrapy pipelines. EnricherPipeline is never starting. I put a debugger in the fist line of process_item and it never gets control. JsonPipeline does start, but the first argument it receives is of type <code>generator object process_item</code> and not the MatchItem instance it should receiv...
0
2016-09-21T21:29:47Z
39,640,297
<p>Ok, so the problem was that EnricherPipeline was yielding and not returning a result. After that it worked as expected, although I still don't understand why a debugger is not working in that first pipeline.</p>
0
2016-09-22T13:23:03Z
[ "python", "scrapy" ]
boto3 query using KeyConditionExpression
39,626,894
<p>I'm having trouble understanding why below query on a DynamoDB table doesn't work:</p> <pre><code>dict_table.query(KeyConditionExpression='norm = :cihan', ExpressionAttributeValues={':cihan': {'S': 'cihan'}}) </code></pre> <p>and throws this error: </p> <p><code>ClientError: An error occurred (ValidationException...
1
2016-09-21T21:31:18Z
39,633,493
<p>Please change the ExpressionAttributeValues as mentioned below. </p> <pre><code>ExpressionAttributeValues={':cihan': 'cihan'} </code></pre>
0
2016-09-22T08:02:41Z
[ "python", "amazon-web-services", "amazon-dynamodb", "boto3" ]
Python iterating over matrix class
39,626,898
<pre><code>from collections.abc import Sequence class Map(Sequence): """ Represents a map for a floor as a matrix """ def __init__(self, matrix): """ Takes a map as a matrix """ self.matrix = matrix self.height = len(matrix) self.width = len(matrix[0]) super().__init__(...
0
2016-09-21T21:31:33Z
39,626,948
<p>You may implement <code>__iter__()</code> like so:</p> <pre><code>from itertools import chain def __iter__(self): return chain.from_iterable(self.matrix) </code></pre> <p><code>itertools.chain.from_iterable()</code> takes an iterable of iterables and combines them all together. It creates a generator thus doe...
0
2016-09-21T21:35:38Z
[ "python", "class", "iterable" ]
Assigning a class variable and then reassigning in a definition without using global in Python
39,626,913
<p>So my question is in the title and the following two snippets of code are my attempts around this. I am trying to assign a variable as soon as the script is started and then just run the loop definition at certain time intervals and update that same variable. I do not want to use a global.</p> <pre><code>from twi...
0
2016-09-21T21:33:04Z
39,628,234
<p>I think you want a <code>classmethod</code>, and you need to start the the task outside of the class definition. I would expect something like the following code to work</p> <pre><code>from twisted.internet import task, reactor class DudeWheresMyCar(object): counter = 20 stringInit = 'Initialized string' ...
1
2016-09-22T00:01:34Z
[ "python", "python-3.x" ]
find the CSS path (ancestor tags) in HTML using python
39,626,940
<p>I want to get all the ancestor div tags where I match a text. So for example if the html looks like <a href="http://i.stack.imgur.com/aePNZ.png" rel="nofollow">HTML snippet</a></p> <p>And i'm searching for "Earl E. Byrd". I wanna get a list which contains {"buyer-info","buyer-name"}</p> <p>This is what i did </p> ...
0
2016-09-21T21:35:13Z
39,627,053
<p>A solution using an <a href="/questions/tagged/xpath" class="post-tag" title="show questions tagged &#39;xpath&#39;" rel="tag">xpath</a> expression :</p> <pre><code>//div[@title="buyer-info"]/div[text() = "Carlson Busses"]/ancestor::div </code></pre>
0
2016-09-21T21:44:44Z
[ "python", "web-scraping", "bs4" ]
find the CSS path (ancestor tags) in HTML using python
39,626,940
<p>I want to get all the ancestor div tags where I match a text. So for example if the html looks like <a href="http://i.stack.imgur.com/aePNZ.png" rel="nofollow">HTML snippet</a></p> <p>And i'm searching for "Earl E. Byrd". I wanna get a list which contains {"buyer-info","buyer-name"}</p> <p>This is what i did </p> ...
0
2016-09-21T21:35:13Z
39,627,506
<p>If you want to search for the div by text and get all the previous divs that have <em>title</em> attributes, first find the div using the text, then use <code>find_all_previous</code> setting <code>title=True</code></p> <pre><code>soup = BeautifulSoup(r.text,"lxml") div = soup.find('div', text="Earl E. Byrd") pri...
0
2016-09-21T22:27:54Z
[ "python", "web-scraping", "bs4" ]
Python downloading PDF into a .zip
39,627,036
<p>What I am trying to do is loop through a list of URL to download a series of .pdfs, and save them to a .zip. At the moment I am just trying to test code using just one URL. The ERROR I am getting is:</p> <pre><code>Traceback (most recent call last): File "I:\test_pdf_download_zip.py", line 36, in &lt;module&gt; ...
0
2016-09-21T21:43:07Z
39,627,509
<p>Your <code>download_pdf()</code> function is saving a file but it doesn't return anything. You need to modify it so it actually returns the file path to <code>myzip.write()</code>. You don't want to hardcode test.pdf but pass unique paths to your download function so you don't end up with multiple <code>test.pdf</co...
0
2016-09-21T22:28:03Z
[ "python", "pdf", "zip", "python-requests" ]
Eliminating stop words from a text, while NOT deleting duplicate regular words
39,627,066
<p>I'm trying to create a list with the most common 50 words within a specific text file, however I want to eliminate the stop words from that list. I have done that using this code.</p> <pre><code>from nltk.corpus import gutenberg carroll = nltk.Text(nltk.corpus.gutenberg.words('carroll-alice.txt')) carroll_list = Fr...
0
2016-09-21T21:45:25Z
39,627,368
<p>As you have it written now, <code>list</code> is already a distribution containing the words as keys and the occurrence count as the value:</p> <pre><code>&gt;&gt;&gt; list FreqDist({u',': 1993, u"'": 1731, u'the': 1527, u'and': 802, u'.': 764, u'to': 725, u'a': 615, u'I': 543, u'it': 527, u'she': 509, ...}) </code...
1
2016-09-21T22:13:31Z
[ "python", "nltk" ]
Python BeautifulSoup Mac Installation Error
39,627,108
<p>I am completely new to all things programming. As I am working to learn the basics of Python, I have run into a problem that I've been unable to work through by reading and Googling.</p> <p>I am trying to install BeautifulSoup, and I thought I had done so successfully, but when I try to test whether or not it's in...
0
2016-09-21T21:48:58Z
39,627,606
<p>You can use pip to install beautifulsoup on mac, by typing in the following command in Terminal:</p> <pre><code>pip install beautifulsoup4 </code></pre> <p>You might be facing some permission problems if you are running the OS X preinstalled python as interpreter. I would suggest installing python with Homebrew if...
-2
2016-09-21T22:40:57Z
[ "python", "beautifulsoup" ]
Sort dict keys into list
39,627,112
<p>I have a dictionary containing IP addresses and hd space for each IP. </p> <p>{'192.168.100.102': '7.3G', '192.168.100.103': '3.5G', '192.168.100.101': '7.4G', '192.168.100.107': '17G'} </p> <p>I want to take three IPs with the greatest space and put them into a list. Is this possible?</p>
-2
2016-09-21T21:49:08Z
39,627,153
<p>This should work:</p> <pre><code>ips = {'192.168.100.102': '7.3G', '192.168.100.103': '3.5G', '192.168.100.101': '7.4G', '192.168.100.107': '17G'} sorted(ips, key=ips.get)[:3] </code></pre> <p>Actually this doesn't work because of the G in each value, use @Moses Koledoye's answer below. </p>
0
2016-09-21T21:52:43Z
[ "python", "dictionary" ]
Sort dict keys into list
39,627,112
<p>I have a dictionary containing IP addresses and hd space for each IP. </p> <p>{'192.168.100.102': '7.3G', '192.168.100.103': '3.5G', '192.168.100.101': '7.4G', '192.168.100.107': '17G'} </p> <p>I want to take three IPs with the greatest space and put them into a list. Is this possible?</p>
-2
2016-09-21T21:49:08Z
39,627,175
<p>Slice off the trailing <code>'G'</code> part from the values and convert them to <code>float</code> in the <em>sort key</em>:</p> <pre><code>ips = {'192.168.100.102': '7.3G', '192.168.100.103': '3.5G', '192.168.100.101': '7.4G', '192.168.100.107': '17G'} sorted_ips = sorted(ips, key=lambda x: float(ips[x][:-1]), r...
1
2016-09-21T21:54:26Z
[ "python", "dictionary" ]
Why isn't my RNN learning?
39,627,187
<p>I'm trying to implement a simple RNN using numpy (based on <a href="https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/" rel="nofollow">this article</a>), and I'm training it to do binary addition where it adds two 8-bit unsigned integers one bit at a time (starting from the end) with the purpose of having i...
1
2016-09-21T21:55:36Z
39,628,442
<p>I figured it out. In case anyone wants to know why it wasn't working, it was because I was only multiplying one part of the hidden error (the part that came from the output error) by the derivative of the hidden layer activation. Now it's easily learning the addition problem within a few thousand iterations.</p>
0
2016-09-22T00:27:23Z
[ "python", "numpy", "machine-learning", "neural-network", "recurrent-neural-network" ]
Concurrent download and processing of large files in python
39,627,188
<p>I have a list of URLs for large files to <strong>download</strong> (e.g. compressed archives), which I want to <strong>process</strong> (e.g. decompress the archives). </p> <p>Both download and processing take a long time and processing is heavy on disk IO, so I want to have <strong>just one of each to run at a tim...
3
2016-09-21T21:55:36Z
39,627,242
<p>I'd simply use <code>threading.Thread(target=process, args=(fname,))</code> and start a new thread for processing.</p> <p>But before that, end last processing thread :</p> <pre><code>t = None for fname in download(urls): if t is not None: # wait for last processing thread to end t.join() t = thread...
0
2016-09-21T22:01:21Z
[ "python", "concurrency", "yield", "coroutine", "yield-from" ]
Error: 'float' object does not support item assignment
39,627,259
<p>I'm programming in python and I don't understand what i'm doing wrong:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from math import exp x=np.linspace(0.0,4.0,100) y1=x for i in range(100): y2[i]=1.5*(1-exp(-x[i])) </code></pre> <p>This last line gives me an error that says: float object d...
0
2016-09-21T22:03:16Z
39,627,290
<p>As <em>Jean-François Fabre</em> and <em>Barmar</em> have noted, you get this message only if you have y2 already assigned to a float. IN any case, you'll need to build the list one way or another.</p> <p>Using the <strong>numpy</strong> array facilities (credit to <em>John1024</em>):</p> <pre><code>y2 = 1.5*(1-n...
1
2016-09-21T22:06:15Z
[ "python" ]
Process hangs if web browser crashes in selenium
39,627,390
<p>I am using selenium + python, been using implicit waits and try/except code on python to catch errors. However I have been noticing that if the browser crashes (let's say the user closes the browser during the program's executing), my python program will hang, and the timeouts of implicit wait seems to not work when...
2
2016-09-21T22:14:46Z
39,628,352
<p>The code you have provided will always hang in the event that there is an exception getting the google home page. What is probably happening is that attempting to get the google home page is resulting in an exception which would normally halt the program, but you are masking that out with the except clause.</p> <p>...
0
2016-09-22T00:15:36Z
[ "python", "selenium" ]
How to add `colorbar` to `networkx` using a `seaborn` color palette? (Python 3)
39,627,490
<p>I'm trying to add a <code>colorbar</code> to my <code>networkx</code> drawn <code>matplotlib ax</code> from the range of <code>1</code> (being the lightest) and <code>3</code> (being the darkest) [check out the line w/ <code>cmap</code> below]. I'm trying to combine a lot of <code>PyData</code> functionalities. </p>...
3
2016-09-21T22:26:00Z
39,628,280
<p>I think the best thing to do here is to fake it following <a href="http://stackoverflow.com/a/11558629/5285918">this answer</a> since you don't have a "ScalarMappable" to work with.</p> <p>For a discrete colormap</p> <pre><code>from matplotlib.colors import ListedColormap sm = plt.cm.ScalarMappable(cmap=ListedColo...
3
2016-09-22T00:06:15Z
[ "python", "matplotlib", "colors", "networkx", "seaborn" ]
Forward WSGI cookies to Requests
39,627,548
<p>I am developing a WSGI middleware application (Python 2.7) using Werkzeug. This app works within a SAML SSO environment and needs a SAML token to be accessed. </p> <p>The middleware also performs requests to other applications in the same SAML environment, acting on behalf of the logged in user. In order to do that...
0
2016-09-21T22:33:44Z
39,627,858
<p>Cookies are just <a href="https://tools.ietf.org/html/rfc6265#section-4.1" rel="nofollow">HTTP headers</a>. Just use pull the cookie value from http.cookies.SimpleCookie, and add it to your requests session's cookie <a href="http://docs.python-requests.org/en/master/_modules/requests/cookies/" rel="nofollow">jar</a>...
0
2016-09-21T23:10:40Z
[ "python", "python-requests", "session-cookies", "saml", "wsgi" ]
how can i fix entropy yielding nan?
39,627,634
<p>I am trying to calculate entropy from array resulted from np.histogram by</p> <pre><code>mu1, sigma1 = 0, 1 s1 = np.random.normal(mu1, sigma1, 100000) hist1 = np.histogram(s1, bins=100, range=(-20,20), density=True) data1 = hist1[0] ent1 = -(data1*np.log(np.abs(data1))).sum() </code></pre> <p>However, this ent1 w...
1
2016-09-21T22:43:42Z
39,627,718
<p>The problem is that you have zero probabilities in your histogram, which don't make numerical sense when applying Shannon's entropy formula. A solution is to ignore the zero probabilities.</p> <pre><code>mu1, sigma1 = 0, 1 s1 = np.random.normal(mu1, sigma1, 100000) hist1 = np.histogram(s1, bins=100, range=(-20,20),...
2
2016-09-21T22:53:36Z
[ "python", "numpy", "entropy" ]
how can i fix entropy yielding nan?
39,627,634
<p>I am trying to calculate entropy from array resulted from np.histogram by</p> <pre><code>mu1, sigma1 = 0, 1 s1 = np.random.normal(mu1, sigma1, 100000) hist1 = np.histogram(s1, bins=100, range=(-20,20), density=True) data1 = hist1[0] ent1 = -(data1*np.log(np.abs(data1))).sum() </code></pre> <p>However, this ent1 w...
1
2016-09-21T22:43:42Z
39,627,816
<p>To compute the entropy, you could use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.entr.html" rel="nofollow"><code>scipy.special.entr</code></a>. For example,</p> <pre><code>In [147]: from scipy.special import entr In [148]: x = np.array([3, 2, 1, 0, 0.5, 2.5, 5]) In [149]: entr(x)....
2
2016-09-21T23:05:32Z
[ "python", "numpy", "entropy" ]
Sum in Spark gone bad
39,627,773
<p>Based on <a href="http://stackoverflow.com/questions/39235576/unbalanced-factor-of-kmeans">Unbalanced factor of KMeans?</a>, I am trying to compute the Unbalanced Factor, but I fail.</p> <p>Every element of the RDD <code>r2_10</code> is a pair, where the key is cluster and the value is a tuple of points. All these ...
2
2016-09-21T22:59:52Z
39,627,819
<p>The problem is because you missed to count the number of points grouped in each cluster, thus you have to change how <code>pdd</code> was created.</p> <pre><code>pdd = r2_10.map(lambda x: (x[0], len(x[1]))).reduceByKey(lambda a, b: a + b) </code></pre> <p>However, You could obtain the same result in a single pass ...
1
2016-09-21T23:05:39Z
[ "python", "function", "apache-spark", "machine-learning", "distributed-computing" ]
Create Folder with Numpy Savetxt
39,627,787
<p>I'm trying loop over many arrays and create files stored in different folders.</p> <p>Is there a way to have np.savetxt creating the folders I need as well?</p> <p>Thanks</p>
0
2016-09-21T23:01:38Z
39,628,096
<p><code>savetxt</code> just does a <code>open(filename, 'w')</code>. <code>filename</code> can include a directory as part of the path name, but you'll have to first create the directory with something like <code>os.mkdir</code>. In other words, use the standard Python directory and file functions.</p>
1
2016-09-21T23:40:22Z
[ "python", "numpy" ]
Create Folder with Numpy Savetxt
39,627,787
<p>I'm trying loop over many arrays and create files stored in different folders.</p> <p>Is there a way to have np.savetxt creating the folders I need as well?</p> <p>Thanks</p>
0
2016-09-21T23:01:38Z
39,640,835
<p>Actually in order to make all intermediate directories if needed the <code>os.makedirs(path, exist_ok=True)</code> . If not needed the command will not throw an error.</p>
0
2016-09-22T13:45:42Z
[ "python", "numpy" ]