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
preserving text structure information - pyparsing
38,809,710
<p>Using pyparsing, is there a way to extract the context you are in during recursive descent. Let me explain what I mean. I have the following code:</p> <pre><code>import pyparsing as pp openBrace = pp.Suppress(pp.Literal("{")) closeBrace = pp.Suppress(pp.Literal("}")) ident = pp.Word(pp.alphanums + "_" + ".") comme...
4
2016-08-07T00:00:34Z
38,815,250
<p>Thanks to Paul McGuire for his sagely advice. Here are the additions/changes I made, which solved the problem:</p> <pre><code>msgNameStack = [] def pushMsgName(str, loc, tokens): msgNameStack.append(tokens[0]) tokens[0] = '.'.join(msgNameStack) def popMsgName(str, loc, tokens): msgNameStack.pop() clo...
2
2016-08-07T14:40:26Z
[ "python", "python-2.7", "parsing", "text-parsing", "pyparsing" ]
Sympy expression in odeint() gives derivation error
38,809,735
<p>I'm trying to automatise several processes, like generating ODEs from Lagrangians with Sympy and doing numerical integration on them with Numpy and Scipy. <strong>Full code at the end.</strong> As result of generating the ODEs with <code>solve()</code> I get a dictionary with Sympy expressions like the following:</p...
1
2016-08-07T00:06:41Z
38,811,487
<p>If you want to use <code>t</code> as symbol you should avoid declaring <code>t</code> as floating point number in the function declaration. Try replacing the floating point <code>t</code> with another name, <code>s</code> or <code>tt</code> or ...</p>
3
2016-08-07T06:17:33Z
[ "python", "scipy", "sympy", "ode", "derivative" ]
how to read in a JSON file as separate strings inside a list rather than as one big list
38,809,744
<p>I am trying to read in a JSON file that looks like this. They are the timestamps of tweets. When I read in the file with my code, it comes in as one big string. Is there a way to have them separated. When I use str.split() then it splits everything. Is there a was that I can load it in or take it out to make this ea...
1
2016-08-07T00:09:07Z
38,809,751
<p>Collect tweet dates <em>into a list</em> and then dump <em>once</em>:</p> <pre><code>dates = [tweet['created_at'] for tweet in stream] with open('dates.json', 'a') as outfile: json.dump(dates, outfile, indent=4) </code></pre> <hr> <blockquote> <p>With this, how do I get it to stop streaming and dump into t...
1
2016-08-07T00:11:13Z
[ "python", "json", "twitter" ]
Xpath exposes text node in dev console but not in python shell
38,809,759
<p>I'm writing a web scraper that is supposed to be scraping data from rows inside of an html table <a href="https://www.federalreserve.gov/releases/h10/hist/" rel="nofollow">here</a>. I'm able to expose all of the text inside of the rows in the table by using this xpath in firebug: <code>$x('.//*[@class="statistics"]/...
1
2016-08-07T00:12:59Z
38,809,789
<p>This is because of the <code>tbody</code> - it is inserted by the browser and you would not get it when download the page via <code>urllib2</code> or <code>requests</code>:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; from lxml.html import fromstring &gt;&gt;&gt; &gt;&gt;&gt; url = "https://www.federal...
1
2016-08-07T00:16:56Z
[ "python", "shell", "xpath", "web-scraping" ]
Pandas still getting SettingWithCopyWarning even after using .loc
38,809,796
<p>At first, I tried writing some code that looked like this:</p> <pre><code>import numpy as np import pandas as pd np.random.seed(2016) train = pd.DataFrame(np.random.choice([np.nan, 1, 2], size=(10, 3)), columns=['Age', 'SibSp', 'Parch']) complete = train.dropna() complete['AgeGt15'] = com...
3
2016-08-07T00:18:40Z
38,810,015
<p>When <code>complete = train.dropna()</code> is executed, <code>dropna</code> might return a copy, so out of an abundance of caution, Pandas sets <code>complete.is_copy</code> to a Truthy value:</p> <pre><code>In [220]: complete.is_copy Out[220]: &lt;weakref at 0x7f7f0b295b38; to 'DataFrame' at 0x7f7eee6fe668&gt; </...
7
2016-08-07T01:08:52Z
[ "python", "pandas" ]
Replacing linked (recursive) for loops with a more functional approach
38,809,821
<p>If I have:</p> <pre><code>for a in range(100): for b in range(50): my_func(a, b) </code></pre> <p>I can replace that code with:</p> <pre><code>from itertools import product product(*[range(100), range(50)]) </code></pre> <p>But say I have the following:</p> <pre><code>for i in range(100): for j ...
1
2016-08-07T00:25:37Z
38,809,878
<p>Not sure how to do it with <code>itertools</code> but wouldn't a list comprehension or generator expression suffice?</p> <pre><code>gen = ((i, j) for i in range(100) for j in range(i)) for i, j in gen: my_func(i, j) </code></pre>
2
2016-08-07T00:36:52Z
[ "python", "python-3.x" ]
How to print/detect the scancode of a pressed key in pygame?
38,809,840
<p>How to print/detect the scancode of a pressed key in pygame?</p> <p>If I do this:</p> <pre><code>for event in pygame.event.get(): print event </code></pre> <p>It prints out:</p> <pre class="lang-none prettyprint-override"><code>&lt;Event(2-KeyDown {'scancode': 1, 'key': 115, 'unicode': u's', 'mod': 0})&gt; &...
0
2016-08-07T00:28:35Z
38,809,934
<p>Have you tried <code>event.scancode</code>? The <a href="http://www.pygame.org/docs/ref/key.html" rel="nofollow">documentation</a> indicates that key press events have the following attributes:</p> <ul> <li><code>key</code> is the integer ID</li> <li><code>unicode</code> is the UNICODE string for the single charac...
1
2016-08-07T00:49:43Z
[ "python", "dictionary", "pygame" ]
Can I use numpy gradient function with images
38,809,852
<p>I have been trying to test the numpy.gradient function recently. However, it's behavior is little bit strange for me. I have created an array with random variables and then applied the numpy.gradient over it, but the values seems crazy and irrelevant. But when using numpy.diff the values are correct.</p> <p>So, aft...
0
2016-08-07T00:30:09Z
38,810,050
<p>Central differences in the interior and first differences at the boundaries.</p> <pre><code>15 - 10 13 - 10 / 2 24 - 15 / 2 ... 39 - 28 </code></pre>
0
2016-08-07T01:16:52Z
[ "python", "numpy" ]
Django form is not validated
38,809,858
<p>I have a form that should be validated from the template, which both are as follows:</p> <pre><code>from django.shortcuts import render from django.forms import Form from django import forms from django.http import HttpResponse import MyIB.settings import os class MainForm(Form): name = forms.CharField() s...
0
2016-08-07T00:32:06Z
38,810,490
<p>A couple of suggestions:</p> <ol> <li><p>When <a href="https://docs.djangoproject.com/en/dev/ref/forms/api/#binding-uploaded-files" rel="nofollow">including <code>file</code> inputs in the form</a>, you have to use the right <code>&lt;form&gt;</code> tag:</p> <blockquote> <p>In order to upload files, you’ll ne...
2
2016-08-07T03:02:19Z
[ "python", "django" ]
Python Raspberry Pi Create bars in Kivy
38,810,027
<p>My code does not work as expected. The bars should be created only when read_SensorGeral is true, the buzzer should be activated only when read_SensorGeral is true and read_Sensor is false. As create other bars only barGeral equals True ? My code:</p> <pre><code>from kivy.app import App from kivy.clock import Clock...
0
2016-08-07T01:11:35Z
38,813,730
<p>Change your update like this, to get your conditions right:</p> <pre><code>def update(self, dt): self.canvas.clear() if self.read_SensorGeral(self.pin) == True: with self.canvas: Color(self.g, 1, 0, 1) Rectangle(pos=(self.p1,self.p2), size=(35,300)) if not self.read_...
0
2016-08-07T11:37:57Z
[ "python", "raspberry-pi", "kivy", "sensor", "gpio" ]
Scrapy from list to extract key or value
38,810,084
<p>i'm new to python and have some trouble wrapping my head around getting certain value's or keys out of a list.</p> <p>When my scraped item outputs its value's i sometimes get a return like this.</p> <p><strong>first list:</strong></p> <pre><code>'image_urls': [u'http://www.websites.com/1.jpg', u'h...
4
2016-08-07T01:24:56Z
38,810,167
<p><strong>Target based on ranks</strong></p> <pre><code>x['image_urls'][0] </code></pre> <p><strong>Merging list of dictionary values</strong></p> <pre><code>&gt;&gt;&gt; images [{'path': 'full/2efhz768djdzs76dz.jpg', 'url': 'http://www.websites.com/1.jpg', 'checksum': '2efhz768djdzs76dz'}, {'path': 'full/zadz764dh...
2
2016-08-07T01:44:49Z
[ "python", "scrapy" ]
Scrapy from list to extract key or value
38,810,084
<p>i'm new to python and have some trouble wrapping my head around getting certain value's or keys out of a list.</p> <p>When my scraped item outputs its value's i sometimes get a return like this.</p> <p><strong>first list:</strong></p> <pre><code>'image_urls': [u'http://www.websites.com/1.jpg', u'h...
4
2016-08-07T01:24:56Z
38,878,160
<p>I'm not entirely sure what you are asking but looks like it's not scrapy related, removing the scrapy tag may encourage more people to open your question and give advice.</p> <p>Back to your question, even though this solution is not optimal it may give you what you want based on my understanding of your question:<...
2
2016-08-10T15:49:29Z
[ "python", "scrapy" ]
Indexing error scanning list
38,810,107
<p>I apologize ahead of time for the basic nature of this question but I could really use a different set of eyes to see why I'm still getting an <code>IndexError: list index out of range</code>.</p> <p>Here is my code:</p> <pre><code>def longestRun(L): counter=1 ii=0 counts=[1] while ii&lt;=max(range...
1
2016-08-07T01:28:51Z
38,810,125
<p>Your while loop is <code>while ii&lt;=max(range((len(L)))):</code> and then your if statement's condition accesses <code>L[ii+1]</code> which runs off the end of the array.</p>
0
2016-08-07T01:33:52Z
[ "python", "indexing" ]
Indexing error scanning list
38,810,107
<p>I apologize ahead of time for the basic nature of this question but I could really use a different set of eyes to see why I'm still getting an <code>IndexError: list index out of range</code>.</p> <p>Here is my code:</p> <pre><code>def longestRun(L): counter=1 ii=0 counts=[1] while ii&lt;=max(range...
1
2016-08-07T01:28:51Z
38,810,139
<p>It's simple math. Let's say <code>L</code> is of length 10. That makes the last index 9. <code>ii</code> can eventually be 9, thus <code>ii+1</code> is going to be out of range. </p>
0
2016-08-07T01:37:11Z
[ "python", "indexing" ]
urllib.urlretrieve makes GUI window not respond
38,810,111
<p>I'm making a game using Panda3D, and I'm currently making a downloader to download the latest update. If you don't know what Panda3D is, just imagine the GUI I'm talking about as a Tkinter window :P. The functions I use are:</p> <pre><code>def doDownload(): urllib.urlretrieve("http://hiddenfile/hi.txt", "hi.txt...
0
2016-08-07T01:30:08Z
38,810,175
<p>You're on the right track with using a separate thread for I/O. It's probably not working because you need to update the UI from the main thread. Try changing <code>report()</code> to save that information in a structure that can be checked later by the UI thread.</p>
0
2016-08-07T01:46:01Z
[ "python", "python-2.7", "user-interface", "downloading" ]
Blueprints in Flask "Attribute 'function' object has no attribute 'name'
38,810,238
<p><strong>Problem Description</strong></p> <p>Getting error message when trying to start Flask.</p> <pre><code>Traceback (most recent call last): File "./run.py", line 3, in &lt;module&gt; from app import app File "/home/xxxxxx/xxxx.xxxxxxx.com/ClientTracker/app/__init__.py", line 13, in &lt;module&gt; a...
0
2016-08-07T02:01:29Z
38,810,281
<p>Ok, so as seems to happen, I spend an hour looking, another 15 mins composing a question and then after I hit post, I find the answer.</p> <p>I found a post (<a href="https://github.com/pallets/flask/issues/1327" rel="nofollow">https://github.com/pallets/flask/issues/1327</a>) that had the answer. </p> <p>Basical...
0
2016-08-07T02:11:26Z
[ "python", "flask" ]
Python print messages into loop?
38,810,371
<p>How can i show "dynamic" messages into loop? For example:</p> <pre><code>for item in array: print (item + " &gt; Cheking file", end=" ") #Conditions which takes some time. Create a zip file or smth else.. if (some condition): print ("&gt; Creating archive", end=" ") #Another conditions which takes some tim...
0
2016-08-07T02:34:45Z
38,810,408
<p>This is due to buffering of the output stream. You can flush the stream after each write with the <code>flush</code> option to <code>print()</code>:</p> <pre><code>for item in 'a', 'b', 'c': print (item + " &gt; Cheking file", end=" ", flush=True) if (some condition): print ("&gt; Creating archive", en...
1
2016-08-07T02:43:44Z
[ "python" ]
Python print messages into loop?
38,810,371
<p>How can i show "dynamic" messages into loop? For example:</p> <pre><code>for item in array: print (item + " &gt; Cheking file", end=" ") #Conditions which takes some time. Create a zip file or smth else.. if (some condition): print ("&gt; Creating archive", end=" ") #Another conditions which takes some tim...
0
2016-08-07T02:34:45Z
38,810,409
<p>The issue you have with the messages not showing up until after the last <code>print</code> is probably due to buffering. Python's standard output stream is line-buffered by default, so you won't see the text you've printed until a newline is included in one of them (e.g. when no <code>end</code> parameter is set).<...
1
2016-08-07T02:43:51Z
[ "python" ]
How to have Counter count the correct strings
38,810,377
<p>I am trying to get the counter to count which date appears most in the code below. </p> <pre><code>from collections import Counter with open('dates.json', 'rb') as f: data = f.readlines() c = Counter(data) print (c.most_common()[:10]) </code></pre> <p>the JSON data is stored as a list like </p> <pre><code>[...
0
2016-08-07T02:36:32Z
38,810,414
<p>Instead of <code>readlines()</code>, you should use <code>json.load()</code> to load the JSON data into a Python list:</p> <pre><code>import json with open('dates.json', 'r') as f: data = json.load(f) </code></pre>
1
2016-08-07T02:44:46Z
[ "python", "json", "counter" ]
How do I use the generate_events event?
38,810,388
<p>The following python3 code is what I might have expected to generate a few calls to the doit event, followed by a call to the terminate event, which would stop the app, but only the first event fires. What am I doing wrong?</p> <pre><code>from circuits import Component, Event, Debugger import time times = [] cla...
1
2016-08-07T02:39:09Z
38,819,477
<p>The main error in the example is that it doesn't <code>reduce_time_left(time.time() - self.last + self.interval)</code> when there is nothing to do.</p> <p><code>generate_events</code> fires once when the app starts. Each generator needs to set <code>reduce_time_left()</code> to the maximum reasonable time before ...
1
2016-08-07T23:22:06Z
[ "python", "circuits-framework" ]
Cannot create dataframe from list: pyspark
38,810,390
<p>I have a list which is generated by a function. when I execute <code>print</code> on my list:</p> <p><code>print preds_labels</code></p> <p>I obtain:</p> <pre><code>[(0.,8.),(0.,13.),(0.,19.),(0.,19.),(0.,19.),(0.,19.),(0.,19.),(0.,20.),(0.,21.),(0.,23.)] </code></pre> <p>but when I want to create a <code>DataFr...
0
2016-08-07T02:40:17Z
38,827,187
<p>pyspark uses its own type system and unfortunately it doesn't deal with numpy well. It works with python types though. So you could manually convert the <code>numpy.float64</code> to <code>float</code> like</p> <pre><code>df = sqlContext.createDataFrame( [(float(tup[0]), float(tup[1]) for tup in preds_labels], ...
1
2016-08-08T10:45:39Z
[ "python", "pyspark", "spark-dataframe" ]
pandas dataframe sort on column raises keyerror on index
38,810,395
<p>I have the following dataframe, <code>df</code>: </p> <pre><code> peaklatency snr 0 52.99 0.0 1 54.15 62.000000 2 54.12 82.000000 3 54.64 52.000000 4 54.57 42.000000 5 54.13 72.000000 </code></pre> <p>I'm attempting to sort this by <code>snr</code>: </...
0
2016-08-07T02:41:15Z
38,810,458
<p>The <code>by</code> keyword to <code>sort_values</code> expects column names, not the actual Series itself. So, you'd want:</p> <pre><code>In [23]: df.sort_values('snr') Out[23]: peaklatency snr 0 52.99 0.0 4 54.57 42.0 3 54.64 52.0 1 54.15 62.0 5 54.13 72.0 2 ...
2
2016-08-07T02:54:23Z
[ "python", "pandas", "syntax" ]
How do you use the values of a dataframe as a variable in a function to make a different column
38,810,396
<p>I have a dataframe which i want to use as the values in it as the "x" in the function<code>0.00459652*np.exp(4.5*x)+0.000984312</code> here is my code</p> <pre><code>df=pd.read_csv('F:/Data32.csv') df2=df['Temperature'] x=df2.values.tolist() test=df2.apply(0.00459652*np.exp(4.5*x)+0.000984312) test </code></pre> <...
0
2016-08-07T02:41:25Z
38,810,438
<p>If you want to apply the function <code>0.00459652*np.exp(4.5*x)+0.000984312</code> to each value in the <code>Temperature</code> column, just put that column at the <code>x</code> location:</p> <pre><code>test = 0.00459652*np.exp(4.5*df['Temperature'])+0.000984312 </code></pre> <p>The reason why you get that erro...
2
2016-08-07T02:50:09Z
[ "python", "pandas", "numpy", "scipy" ]
AWS EMR import external library from S3
38,810,402
<p>I have setup a cluster using Amazon EMR. I have a python library (cloned from github and not available on pip) on S3.</p> <p>I want to submit a pig work that uses a udf which makes use of the library present in S3.</p> <p>I don't want to add the library to the system path because it will be used only once.</p> <p...
7
2016-08-07T02:42:49Z
39,230,600
<p>carefully read the following given material.</p> <p><strong>Call User Defined Functions from Pig:</strong></p> <p>Pig provides the ability to call user defined functions (UDFs) from within Pig scripts. You can do this to implement custom processing to use in your Pig scripts. The languages currently supported are ...
0
2016-08-30T14:43:08Z
[ "python", "amazon-web-services", "amazon-s3", "apache-pig", "amazon-emr" ]
Extract gurobi muti-dimensional variable value and form a numpy array
38,810,415
<p>I want to know that when I defined a multi-dimension variables in Gurobi, how can I extract all the value of the solution and organize them in to a Numpy array according to the original coordinate of the variable.</p> <p>I have the following decision variables defined in Gurobi using Python API:</p> <pre><code>for...
1
2016-08-07T02:44:48Z
38,835,385
<p>I figured this problem out.</p> <p>Do the following:</p> <pre><code>Array_Station_Size = np.array() Array_Station_Size[i,] = [Station_Size[i,t].X for t in rang(T)] </code></pre>
0
2016-08-08T17:39:46Z
[ "python", "arrays", "numpy", "gurobi" ]
How does one debug NaN values in TensorFlow?
38,810,424
<p>I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that ...
13
2016-08-07T02:47:03Z
38,813,502
<p>It look like you can call it after you complete making the graph.</p> <p><code>check = tf.add_check_numerics_ops()</code></p> <p>I think this will add the check for all floating point operations. Then in the sessions run function you can add the check operation.</p> <p><code>sess.run([check, ...])</code></p>
2
2016-08-07T11:08:37Z
[ "python", "machine-learning", "neural-network", "tensorflow", "conv-neural-network" ]
How does one debug NaN values in TensorFlow?
38,810,424
<p>I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that ...
13
2016-08-07T02:47:03Z
38,844,997
<p>There are a couple of reasons WHY you can get a NaN-result, often it is because of too high a learning rate but plenty other reasons are possible like for example corrupt data in your input-queue or a log of 0 calculation.</p> <p>Anyhow, debugging with a print as you describe cannot be done by a simple print (as th...
3
2016-08-09T07:49:22Z
[ "python", "machine-learning", "neural-network", "tensorflow", "conv-neural-network" ]
How does one debug NaN values in TensorFlow?
38,810,424
<p>I was running TensorFlow and I happen to have something yielding a NaN. I'd like to know what it is but I do not know how to do this. The main issue is that in a "normal" procedural program I would just write a print statement just before the operation is executed. The issue with TensorFlow is that I cannot do that ...
13
2016-08-07T02:47:03Z
38,845,552
<p>First of all, you need to check you input data properly. In most cases this is the reason. But not always, of course.</p> <p>I usually use Tensorboard to see whats happening while training. So you can see the values on each step with </p> <pre><code>Z = tf.pow(Z, 2.0) summary_z = tf.scalar_summary('z', Z) #et...
1
2016-08-09T08:22:41Z
[ "python", "machine-learning", "neural-network", "tensorflow", "conv-neural-network" ]
Merging Dataframes that was obtained via web scraping
38,810,575
<p>I have a code that scrapes tables from a website, and reads it into pandas Dataframe. However, this is done through a <code>for</code> loop because of how the website has been designed. As such, the tables are all tagged with the same <code>name</code> ie: they are tagged under <code>df</code> name</p> <p><strong>C...
-1
2016-08-07T03:20:32Z
38,811,082
<p>If all you need to do is merge a number of DataFrames, you can simply collect them in a list and then merge them using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow" title="pd.concat docs">pd.concat</a>.</p> <p>Something like this should work:</p> <pre><code>dataf...
1
2016-08-07T05:09:52Z
[ "python", "selenium", "pandas", "dataframe" ]
regarding the parameters in os.path.join
38,810,610
<p>I am trying to reproduce a python program, which includes the following line of code</p> <pre><code>data = glob(os.path.join("./data", config.dataset, "*.jpg")) </code></pre> <p>My guess is that it will capture all <code>.jpg</code> files stored in <code>/data</code> folder. But I am not sure the usage of <code>co...
0
2016-08-07T03:28:03Z
38,810,650
<p><code>config.dataset</code> in your code fragment is a variable. It's either a <code>dataset</code> attribute of some <code>config</code> object, or the <code>dataset</code> global variable in an imported <code>config</code> module (from this code's perspective they work the same).</p> <p>As a few people have comme...
2
2016-08-07T03:36:22Z
[ "python" ]
basic calcultor/future temp coverter/ future scientific calculator
38,810,652
<p>this is my first code as a beginner python programmer. I will be trying to add temp.converters and other mathematic use but when i test it the code couldn't recognize the numbers i input to choose the operation. also is there a way to use lists to add multiple numbers at the same time</p> <pre><code>#Returns the...
0
2016-08-07T03:36:57Z
38,810,765
<p>You can take advantage of the <code>operator</code> module in Python and use a dictionary dispatch method, eg:</p> <pre><code>import operator from math import sqrt operations = { '1': operator.add, '2': operator.sub, '3': operator.mul, '4': operator.truediv, '6': sqrt, '99': lambda c: c * 1...
0
2016-08-07T04:02:46Z
[ "python" ]
Python -- sizing frames with weights
38,810,696
<p>In the minimum example code below, you can change the last range(), currently at 3, to 6 and notice that the frames with buttons all get smaller than if you run it with 3. I have configured 6 columns of "lower_frame" to all be weight 1. The expected result is that there are 6 empty columns of the same width no mat...
0
2016-08-07T03:49:57Z
38,813,844
<p>If you want all of the rows and all of the columns to have the same width/height, you can set the <code>uniform</code> attribute of each row and column. All columns with the same <code>uniform</code> value will be the same width, and all rows with the same <code>uniform</code> value will be the same height.</p> <p>...
1
2016-08-07T11:52:24Z
[ "python", "python-2.7", "user-interface", "tkinter", "tk" ]
Python Tkinter changing label text
38,810,703
<p>I know that there are a lot of questions dealing with tkinter but I have looked at a bunch of them and none of them seem to help me.</p> <pre><code>import tkinter class Calculator: def __init__(self): window = tkinter.Tk() window.geometry("200x300") window.title("Calculator") lbl = tkinter.Labe...
1
2016-08-07T03:50:37Z
38,814,971
<p>There are a few problems with your code.</p> <ol> <li><p><code>labelText</code> should, of course, be a <code>StringVar</code> and not a string...</p> <pre><code>labelText = tkinter.StringVar() lbl = tkinter.Label(window, bg="blue", textvariable=labelText) lbl.grid(row=0, column=0, columnspan=3) </code></pre></li>...
1
2016-08-07T14:11:42Z
[ "python", "tkinter" ]
How to return only one document on calling a resource endpoint?
38,810,706
<p>I have a collection 'users'. When i call the resource endpoint like <code>/api/users</code>, it returns all the documents. If i enable authentication, how could i return only that user document on calling <code>api/users</code> based on his/her username?</p> <p>Or else how could i disable this endpoint <code>/api/u...
0
2016-08-07T03:50:56Z
38,829,950
<p>If you are using User-Restricted Resource Access, you can have a <a href="http://python-eve.org/features.html#dynamic-lookup-filters" rel="nofollow">Dynamic Lookup filter</a> using event hooks to filter the <code>users</code> results by the <code>auth_field</code>. Something like this:</p> <pre><code>from flask imp...
1
2016-08-08T13:03:03Z
[ "python", "eve" ]
python xml - search for attribute with regular expressions
38,810,711
<p>In my xml file, I have nodes like this:</p> <pre><code>&lt;waitingJobs idList="J03ac2db8 J03ac2fb0"/&gt; </code></pre> <p>I know how to use <code>.findall</code> to search for attributes but now, it looks like I would need to use regular expressions because <a href="https://docs.python.org/3/library/xml.etree.elem...
1
2016-08-07T03:51:55Z
38,810,731
<p>Unfortunately, things like <code>contains()</code> and <code>starts-with()</code> are not supported by <code>xml.etree.ElementTree</code> built-in library. You can manually check the attribute, finding all <code>waitingJobs</code> and using <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.et...
1
2016-08-07T03:55:53Z
[ "python", "xml", "xpath" ]
"unsupported operand type(s) for /: 'NoneType' and 'float' " in openpyxl
38,810,847
<p>I'm trying to read a column in an Excel file, and write the data to a corresponding text file for the column in Python (with Openpyxl). Some data are missing in the Excel file, like the 2nd column below: </p> <p>"gappy.xlsx":</p> <pre><code>350.2856445313 -424.5273132324 -322.6161499023 609.8883056641 ...
0
2016-08-07T04:20:57Z
38,811,038
<p>Well you can check that both arguments are not None before doing the division. And in case one is <code>None</code> handle it in whatever way you want.</p> <p>Something like this</p> <pre><code>if ws.cell(row = j,column = i).value is not None and factor is not None: file_id.write("{:.3e}\n".format(ws.cell(row ...
0
2016-08-07T05:03:10Z
[ "python", "excel", "openpyxl" ]
In Tornado, how to do non-blocking file read/write?
38,810,868
<p>I've been using Tornado for a while now and I've encountered issues with slow timing (which I asked about in <a href="http://stackoverflow.com/questions/38530886/why-do-long-http-round-trip-times-stall-my-tornado-asynchttpclient">this question</a>). One possible issue that was pointed out by a fellow user was that I...
0
2016-08-07T04:27:51Z
38,811,251
<p>Move all of the code associated with file IO to separate functions decorated with <a href="http://tornado.readthedocs.io/en/stable/concurrent.html#tornado.concurrent.run_on_executor" rel="nofollow">run_on_executor</a>.</p> <pre><code>import os import io from concurrent.futures import ThreadPoolExecutor from PIL ...
1
2016-08-07T05:40:01Z
[ "python", "file-io", "tornado" ]
threads stopped using __stop are not removed from threading.enumerate()
38,810,876
<p>Basically, I have some threads that MAY block on I/O but has to be stopped in some cases. The entire software architecture is already designed like that, so switching to multi-processing can be painful. Therefore, I searched web and found using <code>thread_ref._Thread__stop()</code> seems to be the only way that ca...
0
2016-08-07T04:29:23Z
38,811,126
<p>Expanding on my comment, nobody ever believes this ;-) , so here's some code that <em>shows</em> it (Python 2 only):</p> <pre><code>from time import sleep import threading def f(): while True: print("running") sleep(1) t = threading.Thread(target=f) print("starting thread") t.start() sleep(.5)...
0
2016-08-07T05:16:40Z
[ "python", "multithreading", "python-multithreading" ]
Subprocess.call and --stdout
38,810,897
<pre><code>subprocess.call(["espeak", "-s 5 -ven", "where are you", "--stdout", 'shell=True', "aplay"]) </code></pre> <p>The output of this will just be a massive output of special characters, and not the audio from the espeak. When i type this:</p> <pre><code>subprocess.call(["espeak", "-s 5 -ven", "where are you", ...
2
2016-08-07T04:35:51Z
38,810,957
<p>From <a href="http://espeak.sourceforge.net/commands.html" rel="nofollow">espeak documentation</a>:</p> <blockquote> <p>--stdout </p> <p>Writes the speech output to stdout as it is produced, rather than speaking it. The data starts with a WAV file header which indicates the sample rate and format of the...
1
2016-08-07T04:48:27Z
[ "python", "raspberry-pi", "subprocess", "stdout", "espeak" ]
Assigning variables inside a function: Strange behaviour
38,810,933
<p>I use Python rarely, so it's unclear to me why such behaviour is allowed: There is no w object and hence it has no s attribute, then why f allows to make <code>w.s</code> assignment?</p> <pre><code>&gt;&gt;&gt; def f(): w.s="ads" #allows, no exception &gt;&gt;&gt; w.s="sds" #outside function Traceback (most r...
2
2016-08-07T04:42:14Z
38,810,946
<p>Try running your function and see what happens. Python doesn't catch it as you write your code but as soon as you run the code it will error. </p> <p>What you see is because python doesn't know that by the time your function runs there won't be an object <code>w</code> with an attribute <code>s</code>. However, whe...
5
2016-08-07T04:45:40Z
[ "python" ]
Assigning variables inside a function: Strange behaviour
38,810,933
<p>I use Python rarely, so it's unclear to me why such behaviour is allowed: There is no w object and hence it has no s attribute, then why f allows to make <code>w.s</code> assignment?</p> <pre><code>&gt;&gt;&gt; def f(): w.s="ads" #allows, no exception &gt;&gt;&gt; w.s="sds" #outside function Traceback (most r...
2
2016-08-07T04:42:14Z
38,810,950
<p>A function is not yet being run because it hasn't been called yet, as opposed to the assignment of <code>w.s</code> to <code>"sds"</code> being done outside of the function.</p>
4
2016-08-07T04:46:14Z
[ "python" ]
Assigning variables inside a function: Strange behaviour
38,810,933
<p>I use Python rarely, so it's unclear to me why such behaviour is allowed: There is no w object and hence it has no s attribute, then why f allows to make <code>w.s</code> assignment?</p> <pre><code>&gt;&gt;&gt; def f(): w.s="ads" #allows, no exception &gt;&gt;&gt; w.s="sds" #outside function Traceback (most r...
2
2016-08-07T04:42:14Z
38,812,092
<p>Such behaviour is allowed because Python is a dynamic language. At compilation time, when the <code>f</code> function definition is executed (i.e., compiled to byte code), the interpreter knows that there in no local object in the function bound to the name <code>w</code>, so <code>w</code> must refer to a global ob...
2
2016-08-07T07:52:11Z
[ "python" ]
Distinguish document title versus section title
38,811,016
<p>In the <a href="http://docutils.sourceforge.net/docs/ref/doctree.html" rel="nofollow">Docutils document tree</a>, a <code>title</code> node may occur inside a section, or inside the document itself.</p> <p>For a particular Docutils <code>NodeVisitor</code> I am creating, I need to be able to distinguish whether the...
0
2016-08-07T04:59:25Z
38,811,273
<p>You can add <code>visit_section</code> and <code>depart_section</code>:</p> <pre><code>class DocumentTitleSkippingVisitor: def __init__(self): self.in_section = False def visit_section(self, node): self.in_section = True def depart_section(self,node): self.in_section = False ...
0
2016-08-07T05:44:33Z
[ "python", "docutils" ]
How to build a recommendation system using tf-idf and cosine similarity?
38,811,078
<p>I have been trying to build a beer recommendation engine, I have decided to make it simply using tf-idf and Cosine similarity . </p> <p>Here is my code so far: `</p> <pre><code>import pandas as pd import re import numpy as np from bs4 import BeautifulSoup from sklearn.feature_extraction.text import TfidfVec...
0
2016-08-07T05:09:26Z
38,888,899
<p>A simple implementation would be to compute the distance to each of the other beers using <code>cdist</code>, and then return your recommendations using <code>argsort</code>:</p> <pre><code>from scipy.spatial.distance import cdist import numpy as np vec = TfidfVectorizer() beerlist = np.array(['heinekin lager', 'c...
0
2016-08-11T06:34:29Z
[ "python", "scikit-learn", "tf-idf" ]
Is possible to use Selenium with Python, for Electron apps?
38,811,123
<p>I am pretty new to the Selenium testing with Electron apps; I know how to use Python to drive Chrome via the webdriver, and how to use Selenium IDE on Firefox, but I am having trouble to find a good source of info.</p> <p>So far I have an app made with Electron, and I would like to use Selenium to drive it and auto...
0
2016-08-07T05:15:57Z
38,839,391
<p>I did find a way to catch the application.</p> <p>You need to download Chromedriver; and run it on a port that you like(example: 8765).</p> <p>Then you can access the application written via Electron, in Python using</p> <pre><code>from selenium import webdriver remote_app = webdriver.remote.webdriver.WebDri...
0
2016-08-08T22:23:12Z
[ "python", "selenium", "electron" ]
Can I somehow avoid using time.sleep() in this script?
38,811,134
<p>I have the following python script:</p> <pre><code>#! /usr/bin/python import os from gps import * from time import * import time import threading import sys gpsd = None #seting the global variable class GpsPoller(threading.Thread): def __init__(self): threading.Thread.__init__(self) global gpsd #b...
4
2016-08-07T05:18:49Z
38,811,296
<p>I see two options here:</p> <ol> <li>GpsPoller will check if data changed and raise a flag</li> <li>GpsPoller will check id data changed and put new data in the queue.</li> </ol> <p>Option #1:</p> <pre><code>global is_speed_changed = False def run(self): global gpsd, is_speed_changed while gpsp.runni...
1
2016-08-07T05:47:30Z
[ "python", "gpsd" ]
Can I somehow avoid using time.sleep() in this script?
38,811,134
<p>I have the following python script:</p> <pre><code>#! /usr/bin/python import os from gps import * from time import * import time import threading import sys gpsd = None #seting the global variable class GpsPoller(threading.Thread): def __init__(self): threading.Thread.__init__(self) global gpsd #b...
4
2016-08-07T05:18:49Z
38,847,273
<p>As a generic design rule, you should have one thread for each input channel or more generic, for each "loop over a blocking call". Blocking means that the execution stops at that call until data arrives. E.g. <code>gpsd.next()</code> is such a call.</p> <p>To synchronize multiple input channels, use a <code>Queue</...
2
2016-08-09T09:43:19Z
[ "python", "gpsd" ]
"import: command not found" running Python script
38,811,153
<p>I am a beginner without much knowledge of coding. I am attempting to run the following python script... <a href="https://github.com/Sdocquir/moneyonbots/blob/master/shopify3/shopify3.py" rel="nofollow">https://github.com/Sdocquir/moneyonbots/blob/master/shopify3/shopify3.py</a></p> <p>When doing so I receive the fo...
-4
2016-08-07T05:21:32Z
38,811,191
<p>This happens when your script is being run by a shell, not a Python interpreter at all.</p> <p>Put a shebang on the first line of the script:</p> <pre><code>#!/usr/bin/env python </code></pre> <p>...or, as appropriate,</p> <pre><code>#!/usr/bin/env python3 </code></pre> <p>...to specify to the operating system ...
2
2016-08-07T05:28:28Z
[ "python" ]
Django form saying "this field is required" (even text fields) although it's been filled
38,811,294
<p>A few other people have had this problem before but they were all file-related. For me, even text fields that I have filled (and must be filled) return "This Field is Required" error whilst I have done everything people suggested. Have a look at my code:</p> <p><strong>Views</strong></p> <pre><code>class MainForm(...
0
2016-08-07T05:47:16Z
38,811,354
<p>The order of arguments in your form is wrong - <code>request.POST</code> must come first:</p> <pre><code># request.POST must come before request.FILES. form = MainForm(request.POST, request.FILES) </code></pre> <p>Also, you don't need the <code>or None</code>. <code>POST</code> and <code>FILES</code> are always pr...
2
2016-08-07T05:58:07Z
[ "python", "django" ]
Working with django channels and websockets
38,811,668
<p>I have a form to input Line coordinates at <em>127.0.0.1:8000/dashboard/</em> and an "Ok" button to submit the coordinates. The coordinates are posted at <em>127.0.0.1:8000/api/line/</em> by calling the view <code>LineDisplay()</code>. Here I want to push the Line coordinates back to <em>127.0.01:8000/dashboard/</em...
1
2016-08-07T06:45:55Z
38,944,390
<p>You need the group to collect all the Channels that should receive your info. Each connected device gets one Channel. </p> <p>A device's channel identifier is in the <code>message.reply_channel</code>. A Group is just a way to collect all the <code>message.reply_channel</code>s.</p> <p>So, let's say any user who o...
1
2016-08-14T16:49:37Z
[ "python", "django", "websocket", "django-rest-framework", "django-channels" ]
Evaluating expression in loop condition
38,811,681
<p>For some <strong><em>n</em></strong>, lets define result in the following way:</p> <pre><code>result = [x for x in [i for i in range(0, n)]] </code></pre> <p>Does python evaluate the inner list each time? Or does it evaluate it only the first time? Because this is the difference between run time of <strong><em>O(n...
1
2016-08-07T06:48:05Z
38,811,723
<p>Why wouldn't you try that yourself?</p> <pre><code>def foo(): print('foo called') return range(5) result = [x for x in [i for i in foo()]] print(result) &gt;&gt; foo called [0, 1, 2, 3, 4] </code></pre> <p><code>foo</code> is obviously being called once.</p>
4
2016-08-07T06:54:34Z
[ "python" ]
How to use selenium to open multiple instances Firefox simultaneously without clearing cache and cookie
38,811,776
<p>I have a code which scrape friend list from Facebook UID. It worked but it takes a long time to scrape a whole list. So, I want to speed it up by using multiprocessing and Selenium Grid. The following is the approach I use:</p> <ol> <li>Login Facebook with account</li> <li>Open 5 instances Firefox with same cache a...
2
2016-08-07T07:04:03Z
38,812,576
<p>Here is another approach without using selenium grid.</p> <p>This approach opens 5 firefox instances, as well as 3 windows on each instance. The cookies are copied over from the main instance.</p> <pre><code>from pyvirtualdisplay import Display from selenium import webdriver from selenium.webdriver.common.keys imp...
1
2016-08-07T09:04:32Z
[ "python", "selenium", "cookies", "selenium-grid" ]
Setting up Django with mod_wsgi (Apache2)
38,811,855
<pre><code>ServerName test.test.nz ServerAdmin webmaster@localhost DocumentRoot /home/aut/sampleapp WSGIScriptAlias /home/aut/sampleapp /home/aut/sampleapp/sampleapp/wsgi.py WSGIPythonPath /home/aut/sampleapp:/home/aut/sampleapp/env/lib/python2.7/site-packages &lt;Directory /home/aut/sampleapp&g...
0
2016-08-07T07:15:57Z
38,812,050
<p>You haven't defined anything for the root path, /. Your wsgiscriptalias is set to "/home/aut/sampleapp" so only applies to paths under that.</p> <p>I'm not quite sure why you've done this; if you want wsgi to serve your site at the root, as you usually would, you should put <code>/</code> there.</p>
1
2016-08-07T07:45:21Z
[ "python", "django", "apache" ]
How to reformat a 2d numpy array
38,811,989
<p>I have a numpy array such as this:</p> <pre><code>x = np.arange(0,9) y = np.arange(20,29) X = np.array([x, y]) </code></pre> <p>so X looks like [[0,1,2,...9],[20,21,...,29]]</p> <p>but I would like X to be shaped like this:</p> <pre><code>X = np.array([[0, 20], [1, 21], [2, 22], ......
0
2016-08-07T07:37:19Z
38,812,044
<p>you can transpose <code>X</code> to get desired result:</p> <pre><code>In [16]: X Out[16]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8], [20, 21, 22, 23, 24, 25, 26, 27, 28]]) In [17]: X.T Out[17]: array([[ 0, 20], [ 1, 21], [ 2, 22], [ 3, 23], [ 4, 24], [ 5, 25], [ ...
1
2016-08-07T07:45:00Z
[ "python", "numpy" ]
How to reformat a 2d numpy array
38,811,989
<p>I have a numpy array such as this:</p> <pre><code>x = np.arange(0,9) y = np.arange(20,29) X = np.array([x, y]) </code></pre> <p>so X looks like [[0,1,2,...9],[20,21,...,29]]</p> <p>but I would like X to be shaped like this:</p> <pre><code>X = np.array([[0, 20], [1, 21], [2, 22], ......
0
2016-08-07T07:37:19Z
38,812,099
<p>Transpose the array:</p> <pre><code>x = np.arange(0,10) y = np.arange(20,30) X = np.vstack([x, y]).T </code></pre>
0
2016-08-07T07:53:08Z
[ "python", "numpy" ]
python-pandas: dealing with NaT type values in a date columns of pandas dataframe
38,812,020
<p>I have a a dataframe with mixed datatype column, and i applied pd.to_datetime(df['DATE'],coerce=True) and got the below dataframe</p> <pre><code>CUSTOMER_name DATE abc NaT def NaT abc 2010-04-15 19:09:08 def 2011-01-25 15:29:37 abc 2...
1
2016-08-07T07:41:02Z
38,812,096
<p>Say you start with something like this:</p> <pre><code>df = pd.DataFrame({ 'CUSTOMER_name': ['abc', 'def', 'abc', 'def', 'abc', 'fff'], 'DATE': ['NaT', 'NaT', '2010-04-15 19:09:08', '2011-01-25 15:29:37', '2010-04-10 12:29:02', 'NaT']}) df.DATE = pd.to_datetime(df.DATE) </code></pre> <p>(note that the onl...
2
2016-08-07T07:52:55Z
[ "python", "datetime", "pandas" ]
python-pandas: dealing with NaT type values in a date columns of pandas dataframe
38,812,020
<p>I have a a dataframe with mixed datatype column, and i applied pd.to_datetime(df['DATE'],coerce=True) and got the below dataframe</p> <pre><code>CUSTOMER_name DATE abc NaT def NaT abc 2010-04-15 19:09:08 def 2011-01-25 15:29:37 abc 2...
1
2016-08-07T07:41:02Z
38,812,434
<p>Here is an alternative solution:</p> <p><strong>Data:</strong></p> <pre><code>In [96]: x Out[96]: CUSTOMER_name DATE 0 abc T 1 def N 2 abc 2010-04-15 19:09:08 3 def 2011-01-25 15:29:37 4 abc 2010-04-10 12:2...
1
2016-08-07T08:44:31Z
[ "python", "datetime", "pandas" ]
How can I execute arbitrary code via JSON and how to sanitize the input
38,812,106
<p>In the <a href="https://jsonpickle.github.io/" rel="nofollow">documentation</a> of Python's jsonpickle module for JSON serialization and deserialization it states that</p> <blockquote> <p>Loading a JSON string from an untrusted source represents a potential security vulnerability. jsonpickle makes no attempt to...
3
2016-08-07T07:54:08Z
38,812,230
<p><code>jsonpickle</code> is not JSON. <code>jsonpickle</code> allows to create arbitrary Python-Objects that potentially do harmful things. Sanitizing means, that the JSON objects only contain data, that can be interpreted by <code>jsonpickle</code>. Normally wrong data would lead to exceptions, but can may be used t...
0
2016-08-07T08:14:02Z
[ "python", "json", "security", "jsonpickle" ]
Is there a way to save both python stdout and stdin to file using only bash?
38,812,236
<p>There are shell shortcuts to save the python stdout to file like so:</p> <pre><code>python code.py &gt; file python code.py &gt;&gt; file python code.py &amp;&gt; file </code></pre> <p>But this does not save the stdin that I type in through the terminal for in Ubuntu 16.04 LTS. Is there any way to save the text ex...
0
2016-08-07T08:15:59Z
38,812,266
<p>If you want to record an interaction with the terminal you can use <a href="http://man7.org/linux/man-pages/man1/script.1.html" rel="nofollow">script</a>:</p> <blockquote> <p>script makes a typescript of everything displayed on your terminal. It is useful for students who need a hardcopy record of an<br> inte...
1
2016-08-07T08:19:50Z
[ "python", "bash", "file", "stdout", "stdin" ]
Is there a way to save both python stdout and stdin to file using only bash?
38,812,236
<p>There are shell shortcuts to save the python stdout to file like so:</p> <pre><code>python code.py &gt; file python code.py &gt;&gt; file python code.py &amp;&gt; file </code></pre> <p>But this does not save the stdin that I type in through the terminal for in Ubuntu 16.04 LTS. Is there any way to save the text ex...
0
2016-08-07T08:15:59Z
38,812,327
<p>You can save stdin to a variable, write this variable to your text file and then you can pass this variable to whatever programm you want to use it with.</p> <pre><code>read input $input &gt; textfile $input | program </code></pre>
0
2016-08-07T08:28:38Z
[ "python", "bash", "file", "stdout", "stdin" ]
2 columns of values -> 1 column of values + 1 column of labels in pandas
38,812,304
<p>what's the most elegant way of achieving this in one line using pandas?</p> <p>starting point:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[0.2,0.3,0.1,0.45], 'B':[0.5,0.8,0.15,0.55]}) i A B 0 0.2 0.5 1 0.3 0.8 2 0.1 0.15 3 0.45 0.55 </code></pre> <p>desired endpoint:</p> <pre...
0
2016-08-07T08:24:50Z
38,812,344
<pre><code>pd.melt(df) Out: variable value 0 A 0.20 1 A 0.30 2 A 0.15 3 A 0.45 4 B 0.50 5 B 0.80 6 B 0.15 7 B 0.55 </code></pre>
5
2016-08-07T08:31:20Z
[ "python", "pandas" ]
Create a daemon background service?
38,812,354
<p>I'm trying to create a background service in Python. The service will be called from another Python program. It needs to run as a daemon process because it uses a heavy object (300MB) that has to be loaded previously into the memory. I've had a look at <a href="https://pypi.python.org/pypi/python-daemon/" rel="nofol...
0
2016-08-07T08:32:47Z
38,813,560
<p>I had a similar situation when I wanted to access a big binary matrix from a web app.</p> <p>Of course there are many solutions, but I used <a href="http://redis.io/" rel="nofollow">Redis</a>, a popular in-memory database/cache system, to store and access my object successfully. It has practical Python bindings (se...
1
2016-08-07T11:16:24Z
[ "python", "unix", "subprocess", "python-daemon" ]
Django autocomplete: AttributeError: module 'dal_select2.models' has no attribute 'Model'
38,812,391
<p>In my models.py: </p> <pre><code>from dal import autocomplete from dal_select2_queryset_sequence.views import * from queryset_sequence import QuerySetSequence from dal.widgets import * from dal.views import * from dal_queryset_sequence.views import * from dal_select2 import * from dal_queryset_sequence import * c...
0
2016-08-07T08:38:43Z
38,812,540
<p>This is exactly why you shouldn't use the <code>from x import *</code>. One of those modules you import - <code>dal_select_2</code> - defines a name <code>models</code>, which overrides the one you actually wanted which is from <code>django.db</code>.</p> <p>Only import the names you actually use, then this won't h...
0
2016-08-07T09:00:34Z
[ "python", "django", "autocomplete" ]
Getting id of the form in formset which is being edited
38,812,401
<p>I have a Django template that renders a table comprising Django formsets.</p> <p>Template (<em>simplified</em>)</p> <pre><code>&lt;table id = 'my_table'&gt; {% for form in my_formset %} &lt;tr&gt;&lt;td&gt;{{form.my_field}}&lt;/td&gt;&lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now, I hav...
0
2016-08-07T08:39:59Z
38,835,227
<pre><code>if form.has_changed(): if form.is_valid(): form.save() </code></pre>
2
2016-08-08T17:29:02Z
[ "python", "django" ]
Function to capture change between values in different columns
38,812,411
<p>Can someone please help me with a simple function to capture the change between open and Last as per the examples below:</p> <p>The data:</p> <pre><code> Open High Low Last Timestamp 2014-03-04 1783.50 1796.00 1783.50 1793.25 2014-03-05 1793.25 1796.50 ...
0
2016-08-07T08:42:05Z
38,812,438
<pre><code>df['desired'] = (df['Open'] - df['Last']).abs() </code></pre> <p>This gives you the absolute value of the difference (if <code>df['Last']</code> is greater than <code>df['Open']</code>, it becomes <code>df['Last'] - df['Open']</code>)</p> <p>Your sample output is, on the other hand, is the result of <code>...
3
2016-08-07T08:45:08Z
[ "python", "pandas" ]
Method inheritance issue
38,812,557
<p>When I attempt to create a 'BJ_player' object:</p> <pre><code>player = BJ_player(name, number_chips) </code></pre> <p>I receive:</p> <blockquote> <p>TypeError: <strong>init</strong>() takes exactly 2 positional arguments (3 given).</p> </blockquote> <p>I've used the same methodology to inherit from 'BJ_Hand' a...
0
2016-08-07T09:02:05Z
38,812,613
<p>This gives no errors on py2.7 and py3.5:</p> <pre><code>class Hand(object): """A hand of playing cards""" def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + "\t" else: ...
1
2016-08-07T09:08:50Z
[ "python", "class", "inheritance", "methods" ]
Method inheritance issue
38,812,557
<p>When I attempt to create a 'BJ_player' object:</p> <pre><code>player = BJ_player(name, number_chips) </code></pre> <p>I receive:</p> <blockquote> <p>TypeError: <strong>init</strong>() takes exactly 2 positional arguments (3 given).</p> </blockquote> <p>I've used the same methodology to inherit from 'BJ_Hand' a...
0
2016-08-07T09:02:05Z
38,812,834
<p>You defined an <code>__init__</code> method that only takes <em>one</em> argument (plus <code>self</code>):</p> <pre><code>class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): # ^^^^^^^^^^^^ </code></pre> <p>There is no parameter for <code>name</code>, b...
2
2016-08-07T09:39:17Z
[ "python", "class", "inheritance", "methods" ]
Method inheritance issue
38,812,557
<p>When I attempt to create a 'BJ_player' object:</p> <pre><code>player = BJ_player(name, number_chips) </code></pre> <p>I receive:</p> <blockquote> <p>TypeError: <strong>init</strong>() takes exactly 2 positional arguments (3 given).</p> </blockquote> <p>I've used the same methodology to inherit from 'BJ_Hand' a...
0
2016-08-07T09:02:05Z
38,812,836
<p>The <code>BJ_player</code> class has a problem. Modified the class to this:</p> <pre><code>class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, name, number_chips): super(BJ_player, self).__init__(name) self.name = name self.number_chips = number_chips def __str...
1
2016-08-07T09:39:25Z
[ "python", "class", "inheritance", "methods" ]
Method inheritance issue
38,812,557
<p>When I attempt to create a 'BJ_player' object:</p> <pre><code>player = BJ_player(name, number_chips) </code></pre> <p>I receive:</p> <blockquote> <p>TypeError: <strong>init</strong>() takes exactly 2 positional arguments (3 given).</p> </blockquote> <p>I've used the same methodology to inherit from 'BJ_Hand' a...
0
2016-08-07T09:02:05Z
38,812,911
<p>While the other answers have (mostly) correctly diagnosed the specific issue you were describing (not accepting <code>name</code> in <code>BJ_player.__init__</code> and passing it on in the <code>super</code> call), I think there's a larger design issue that may cause you other problems while working with your class...
1
2016-08-07T09:49:48Z
[ "python", "class", "inheritance", "methods" ]
django accessing one-to-one key calls __setattr__ unexpectedly
38,812,596
<p>I have a django model including two model classes (UserProfile and UserNotification). Each profile has optionally a last_notification. Here are the class fields defined in models.py:</p> <pre><code>class UserProfile(models.Model): last_notif = models.OneToOneField('UserNotification', null=True, blank=True, defa...
0
2016-08-07T09:07:10Z
38,812,809
<p>It's called because the act of accessing <code>profile.last_notif</code> loads the UserNotification object from the database, since it hasn't previously been loaded. Doing this obviously requires that all of the fields of the instance are set with the relevant values from the db.</p>
0
2016-08-07T09:36:09Z
[ "python", "django", "python-2.7", "django-models", "one-to-one" ]
numpy's fast Fourier transform yields unexpected results
38,812,611
<p>I am struggling with <code>numpy</code>'s implementation of the fast Fourier transform. My signal is not of periodic nature and therefore certainly not an ideal candidate, the result of the FFT however is far from what I was expecting. It is the same signal, simply stretched by some factor. I plotted a sinus curve, ...
2
2016-08-07T09:08:47Z
38,812,646
<p>[EDIT] I overlooked the crucial thing stated by Stelios! Nevertheless I leave my answer here, since, while not spotting the root cause of your trouble, it is still true and contains things you have to reckon with for a useable FFT.</p> <p>As you say you're tranforming a non-periodical signal. Your signal has some r...
1
2016-08-07T09:13:49Z
[ "python", "numpy", "fft" ]
numpy's fast Fourier transform yields unexpected results
38,812,611
<p>I am struggling with <code>numpy</code>'s implementation of the fast Fourier transform. My signal is not of periodic nature and therefore certainly not an ideal candidate, the result of the FFT however is far from what I was expecting. It is the same signal, simply stretched by some factor. I plotted a sinus curve, ...
2
2016-08-07T09:08:47Z
38,812,832
<p>Numpy's <code>fft</code> is by default applied over rows. Since your <code>signal</code> variable is a column vector, <code>fft</code> is applied over the rows consisting of one element and returns the one-point FFT of each element. </p> <p>Use the axis option of <code>fft</code> to specify that you want FFT applie...
3
2016-08-07T09:39:03Z
[ "python", "numpy", "fft" ]
Got an unexpected keyword argument 'pk'
38,812,634
<p>I have a list of Classes, and i need to get info of certain Class (i.e. student names, Class monitor etc). There is no problem in displaying Classes list (<code>localhost:8000/classes</code>), but when i'm addressing particular class (<code>localhost:8000/classes/nice_guys</code>), i receive <code>class_list() got a...
1
2016-08-07T09:11:25Z
38,812,654
<p>You're including the students urls twice, once with the pk argument, which makes no sense: that means it will be passed to every view, including the class_list one which isn't expecting it (and the class_display one would receive it twice). Remove that first include.</p>
3
2016-08-07T09:15:14Z
[ "python", "django" ]
VSCode doesn't show python script error output
38,812,703
<p>Using Python3 with Visual Studio Code (<a href="https://marketplace.visualstudio.com/items?itemName=donjayamanne.python" rel="nofollow">Python extension</a> installed) within Ubuntu 16.04. I have some basic script written:</p> <pre><code>def mainMethod(): what() #connectToDevice() if __name__ == "__mai...
1
2016-08-07T09:23:11Z
39,474,932
<p>I still can't see the output in <code>Debug Console</code> all the time but I can see it in the <code>Integrated Terminal</code> by setting this option in <code>launch.json</code> file of VSCode. The file looks like this:</p> <pre><code>{ "version": "0.2.0", "configurations": [ { "name": "Python virtual...
0
2016-09-13T16:32:28Z
[ "python", "vscode" ]
Theano lstm - what is initial hidden state
38,812,730
<p>I'm having trouble understanding this line in a piece of code I've found: </p> <pre><code>def has_hidden(layer): """ Whether a layer has a trainable initial hidden state. """ return hasattr(layer, 'initial_hidden_state') </code></pre> <p>My question is what is that initial hidden state? What is...
0
2016-08-07T09:27:06Z
38,812,940
<p>The state of a layer of neurons is the set of all the weights (of its connections) that describe it at that point in time.</p> <p>To get good training performance its necessary that you dont start off with 0's for all the weights for a layer of neurons. The most common solution to this problems is to initialize all...
1
2016-08-07T09:52:18Z
[ "python", "neural-network", "theano", "lstm" ]
Can't find tags in beautifulsoup when I search them through class filter through dictionary
38,812,918
<p>Below is my code.`</p> <pre><code>import urllib from BeautifulSoup import * html=urllib.urlopen('http://yellowpages.sulekha.com/coffee-shops-bars-restaurants_delhi') soup=BeautifulSoup(html) tags=soup.findAll("li",{ "class" : "list-item" }) print tags </code></pre> <p>I wish to find all the 'li' tags which have a...
1
2016-08-07T09:50:17Z
38,815,822
<p>I went and took a look at the site you were trying to scrape and searched for <code>list-item</code>. Then I saw something that looked like the below</p> <pre><code>&lt;li class="list-item " itemtype="http://schema.org/LocalBusiness" itemscope=""&gt; </code></pre> <p>I see that the class is <code>"list-item "</cod...
1
2016-08-07T15:46:11Z
[ "python", "web-scraping", "beautifulsoup" ]
Why cURL response from server is HTTP/1.0?
38,813,071
<p>I had created simple server in terminal</p> <pre><code>python -m SimpleHTTPServer 8000 </code></pre> <p>when I send command <code>curl -I http://localhost:8000</code></p> <p>and command result was a request:</p> <p><code>127.0.0.1 - - [07/Aug/2016 14:53:22] "GET / HTTP/1.1" 200 -</code></p> <p>but response was ...
1
2016-08-07T10:11:37Z
38,813,126
<p>It's just a version number, the server supports the older 1.0 protocol.</p> <p>See <a href="http://stackoverflow.com/questions/246859/http-1-0-vs-1-1">HTTP 1.0 vs 1.1</a></p>
1
2016-08-07T10:17:04Z
[ "python", "http", "curl" ]
Why cURL response from server is HTTP/1.0?
38,813,071
<p>I had created simple server in terminal</p> <pre><code>python -m SimpleHTTPServer 8000 </code></pre> <p>when I send command <code>curl -I http://localhost:8000</code></p> <p>and command result was a request:</p> <p><code>127.0.0.1 - - [07/Aug/2016 14:53:22] "GET / HTTP/1.1" 200 -</code></p> <p>but response was ...
1
2016-08-07T10:11:37Z
38,815,112
<p><code>curl</code> uses HTTP/1.1 by default from version 7.33.0 (yours is 7.43.0). In <code>man curl</code>:</p> <pre><code>--http1.1 (HTTP) Tells curl to use HTTP version 1.1. This is the internal default version. (Added in 7.33.0) </code></pre> <p>So <code>curl</code> will make a request with <code>...
1
2016-08-07T14:26:55Z
[ "python", "http", "curl" ]
How to call methods inside a class?
38,813,090
<p>I have a test Python class named calc with two methods <code>add</code> and <code>sub</code>. How can I run the methods from the python prompt? I am at the python command line ">>>" and typing <code>import calc</code>. Then I type <code>calc.add(5,3)</code> and get "No module named 'calc'". File name is <code>calc.p...
-1
2016-08-07T10:13:49Z
38,813,134
<p><code>calc</code> is the module name <em>and</em> a class in the module. Use <code>import calc</code> and then refer to the class with <code>calc.calc</code>:</p> <p><code>calc.py</code>:</p> <pre><code>class calc: def add(self, x, y): # note the use of "self" answer = x + y print(answer) ...
2
2016-08-07T10:18:23Z
[ "python" ]
How to call methods inside a class?
38,813,090
<p>I have a test Python class named calc with two methods <code>add</code> and <code>sub</code>. How can I run the methods from the python prompt? I am at the python command line ">>>" and typing <code>import calc</code>. Then I type <code>calc.add(5,3)</code> and get "No module named 'calc'". File name is <code>calc.p...
-1
2016-08-07T10:13:49Z
38,813,157
<p>You need to import <code>calc</code> class from your <code>calc</code> module:</p> <pre><code>from calc import calc # we're importing only calc class from that module c = calc() c.add(5,3) </code></pre>
0
2016-08-07T10:21:49Z
[ "python" ]
Caffe: Converting CSV file to HDF5
38,813,120
<p>I have learned a little about Caffe framework (which is used define and train deep learning models)</p> <p>As my first program, I wanted to write a program for training and testing a "Face Emotion Recognition" task using <a href="https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recog...
0
2016-08-07T10:16:38Z
38,827,223
<p>Your input data doesn't have to be in lmdb or hdf5. You can input data from a csv file. All you have to do is to use an ImageData input layer such as this one:</p> <pre><code>layer { name: "data" type: "ImageData" top: "data" top: "label" include { phase: TRAIN } transform_param { mirror: fals...
1
2016-08-08T10:48:18Z
[ "python", "matlab", "csv", "hdf5", "caffe" ]
How to get new column in a data frame Applying Logical operator , if else if
38,813,143
<pre><code>Feature1, Feature2, Feature3, Feature4, TARGET 5.1,3.5,1.4,0.2,Iris-setosa 4.9,3.0,1.4,0.2,Iris-setosa 6.4,3.2,4.5,1.5,Iris-versicolor 6.9,3.1,4.9,1.5,Iris-versicolor 6.3,2.5,5.0,1.9,Iris-virginica 6.5,3.0,5.2,2.0,Iris-virginica </code></pre> <p>how can I work out the target (spe...
0
2016-08-07T10:19:50Z
38,813,940
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> to subset the dataframe according to your desired <code>TARGET</code> column as shown:</p> <pre><code>In [4]: mask = (df['Feature1'] &lt; 5.2) &amp; (df['Feature2'] &gt; 3.4) ...
1
2016-08-07T12:03:17Z
[ "python", "pandas", "filter" ]
How to get new column in a data frame Applying Logical operator , if else if
38,813,143
<pre><code>Feature1, Feature2, Feature3, Feature4, TARGET 5.1,3.5,1.4,0.2,Iris-setosa 4.9,3.0,1.4,0.2,Iris-setosa 6.4,3.2,4.5,1.5,Iris-versicolor 6.9,3.1,4.9,1.5,Iris-versicolor 6.3,2.5,5.0,1.9,Iris-virginica 6.5,3.0,5.2,2.0,Iris-virginica </code></pre> <p>how can I work out the target (spe...
0
2016-08-07T10:19:50Z
38,815,187
<p>Try this: use <code>np.where(cond,if true,if false)</code>, </p> <pre><code>df['new'] = np.where((df['Feature1'] &lt; 5.2) &amp; (df['Feature2'] &gt; 3.4) &amp; (df['Feature3'] &lt; 1.5) &amp; (df['Feature4'] &lt; .3), "iris-setosa", "") </code></pre>
0
2016-08-07T14:33:33Z
[ "python", "pandas", "filter" ]
for event in pygame.event.get(): pygame.error: video system not initialized when using ssh
38,813,215
<p>Here is the code that I'm trying to run via ssh into my raspberry pi. It usually works fine when I have a keyboard and monitor connected directly to the raspberry pi, but it doesn't run when I am using ssh.</p> <pre><code>import pygame, sys, time from pygame.locals import * pygame.init() pygame.joystick.init() joy...
0
2016-08-07T10:30:00Z
38,814,857
<p>Well you have not initialized your window yet. It looks like you may or may not have commented it out: <code>#screen = pygame.display.set_mode((400, 300))</code>. Many of pygame's events rely on the window. Simply un-comment your screen initialization and it should work fine. </p>
0
2016-08-07T14:00:16Z
[ "python", "joystick" ]
How to set pandas Dataframe column name as headers?
38,813,218
<p>I created a Dataframe with the below code.</p> <pre><code>&gt;&gt;&gt;in: df_final = pandas.DataFrame(combined_data, columns=['Item', aa, bb, cc, dd]) &gt;&gt;&gt;out: Item FY2012 FY2013 FY2014 FY2015 0 Total Revenue 654.766 535.79 321.394 445.24...
0
2016-08-07T10:30:32Z
38,813,826
<p>You need to set the Item column as index so it becomes 'columns' when you transpose it:</p> <pre><code>df.set_index('Item').T Out: Item Total Revenue Gross Profit Net Income EBITDA FY2012 654.766 256.776 60.994 111.324 FY2013 535.790 268.412 44.026 110.268 FY2014 ...
2
2016-08-07T11:50:00Z
[ "python", "pandas" ]
Reshaping 4D numpy to 5D array using specific pattern
38,813,310
<p>I have a 4D numpy array of shape <code>(N x 8 x 24 x 98)</code> that I need to reshape to the 5D shape <code>(N x 8 x 24 x 7 x 14)</code> such that the last dimension is split into 2 separate dimensions.</p> <p>If <code>v_i</code> is the value for element <code>i</code> in the last dimension of the old matrix (cont...
0
2016-08-07T10:43:53Z
38,813,698
<p>IIUC you can simply reshape your array / matrix:</p> <pre><code>In [109]: a = np.arange(8*24*98).reshape(8,24,98) In [110]: a.shape Out[110]: (8, 24, 98) In [111]: x = a.reshape(8,24,7,14) In [112]: x.shape Out[112]: (8, 24, 7, 14) </code></pre>
2
2016-08-07T11:33:41Z
[ "python", "numpy", "reshape" ]
python2 to 3 use of list()
38,813,330
<p>I'm converting python2.7 scripts to python3. <code>2to3</code> makes these kinds of suggestions:</p> <pre><code> result = result.split(',') syslog_trace("Result : {0}".format(result), False, DEBUG) - data.append(map(float, result)) + data.append(list(map(float, result))) ...
0
2016-08-07T10:45:21Z
38,814,578
<blockquote> <p>I'm sure the makers of Python3 did not want to do it like that</p> </blockquote> <p>Well, the makers of Python generally don't like seeing Python 2 being used, I've seen that sentiment being expressed in pretty much every recent PyCon.</p> <blockquote> <p>Is there a more pythonic way of doing this...
1
2016-08-07T13:22:53Z
[ "python", "python-2.7", "python-3.x" ]
python2 to 3 use of list()
38,813,330
<p>I'm converting python2.7 scripts to python3. <code>2to3</code> makes these kinds of suggestions:</p> <pre><code> result = result.split(',') syslog_trace("Result : {0}".format(result), False, DEBUG) - data.append(map(float, result)) + data.append(list(map(float, result))) ...
0
2016-08-07T10:45:21Z
38,815,335
<p>What's wrong with the unfixed <code>somma</code>?</p> <p><code>2to3</code> cannot know how <code>somma</code> is going to be used, in that case, as a generator in the next line to compute <code>averages</code> it is OK and optimal, no need to convert it as a list.</p> <p>That's the genius of python 3 list to gener...
2
2016-08-07T14:49:33Z
[ "python", "python-2.7", "python-3.x" ]
Spectral (SPy) label legend
38,813,331
<p>I would like to put a legend below the image drawn by the <a href="http://www.spectralpython.net/" rel="nofollow">spectral</a> module. I wonder if there is an builtin way to do this? I haven't found anything about making legends in the <a href="http://www.spectralpython.net/class_func_glossary.html" rel="nofollow">s...
0
2016-08-07T10:45:22Z
38,814,295
<p>I added the legend like this:</p> <pre><code>from matplotlib import patches from spectral import spy_colors labelPatches = [ patches.Patch(color=spy_colors[x]/255., label=labelDictionary[x]) for x in np.unique(labels) ] </code></pre> <p>Once you have the label patches the legend is easy to add:</p...
0
2016-08-07T12:47:38Z
[ "python", "matplotlib", "spectral" ]
user inputs in python giving float, array multiplication issue
38,813,348
<p>I have following lines of code working fine when inputs given in console:</p> <pre><code>import numpy as np def simple_exponential_smoothing(actuals, n_forecast_periods,alpha): return np.array([np.array([alpha*((1-alpha)**k)*actuals[len(actuals)-k-1] for k in range (len(actuals))]).sum()]*n_forecast_periods) si...
0
2016-08-07T10:47:39Z
38,813,418
<p>First you need to convert the input to a list of integers (or floats):</p> <pre><code>actuals = input("Input list:") actuals = [int(i) for i in actuals.split(',')] </code></pre> <p>I assumed the inputs are separated by commas.</p> <p>For example,</p> <pre><code>Input list:1, 2, 5, 7, 10 Int:2 float:0.3 [ 5.48283...
0
2016-08-07T10:57:48Z
[ "python", "numpy" ]
Python printing binary value and its decimal form
38,813,410
<p>Python 2.6/2.7</p> <p>I have the following program.</p> <pre><code>print 0b10 def p_m(x): print x p_m(bin(2)) </code></pre> <p><strong>Output:</strong></p> <pre><code>2 0b10 </code></pre> <p>What I wanted to print in p_m() is 2 (the decimal value) of "0b10" which is what I'm passing to p_m() as first argu...
1
2016-08-07T10:56:41Z
38,813,448
<p><code>print 0b10</code> gives 2. </p> <p>This is because all the numbers are stored in python as binary.</p> <p><code>bin(2)</code> is a string. So it gives you the binary value.</p> <p>You can use <code>print int('0b10', 2)</code>. Here 2 means the base and '0b10' is the binary you want to convert. <code>0b</cod...
1
2016-08-07T11:02:16Z
[ "python", "python-2.7", "binary", "decimal", "bits" ]
Python printing binary value and its decimal form
38,813,410
<p>Python 2.6/2.7</p> <p>I have the following program.</p> <pre><code>print 0b10 def p_m(x): print x p_m(bin(2)) </code></pre> <p><strong>Output:</strong></p> <pre><code>2 0b10 </code></pre> <p>What I wanted to print in p_m() is 2 (the decimal value) of "0b10" which is what I'm passing to p_m() as first argu...
1
2016-08-07T10:56:41Z
38,813,495
<p>Convert the string <code>0b10</code> back to int using <a href="https://docs.python.org/2/library/functions.html#int" rel="nofollow">2 base parameter</a>:</p> <pre><code>def p_m(x): print int(x, 2) </code></pre>
1
2016-08-07T11:07:24Z
[ "python", "python-2.7", "binary", "decimal", "bits" ]
Python printing binary value and its decimal form
38,813,410
<p>Python 2.6/2.7</p> <p>I have the following program.</p> <pre><code>print 0b10 def p_m(x): print x p_m(bin(2)) </code></pre> <p><strong>Output:</strong></p> <pre><code>2 0b10 </code></pre> <p>What I wanted to print in p_m() is 2 (the decimal value) of "0b10" which is what I'm passing to p_m() as first argu...
1
2016-08-07T10:56:41Z
38,813,505
<p><code>0b10</code> is an int. <code>bin(2)</code> is '0b10' which is a string. You'd have to print <code>int('0b10', 2)</code> to get it to print 2</p>
1
2016-08-07T11:08:53Z
[ "python", "python-2.7", "binary", "decimal", "bits" ]
How to make a cryptographic algorithm less reverse engineerable?
38,813,458
<p>i have developed an AES256 encryption application with but i want to make it more secure. How can i understand how easy it is to reverse engineer and how can i make it less reverse engineerable ? </p> <p>Note : it would be great if you recommend me some reverse engineering books.</p> <p>code: <a href="http://past...
1
2016-08-07T11:03:47Z
38,813,480
<p>Since you added the Python label, I guess your algorithm is written in Python. You could use <a href="https://pypi.python.org/pypi/Opy" rel="nofollow">my obfuscator</a> to make your algorithm hard to decipher. It's one way only.</p> <p>Don't rely on distributing only the .pyc files. They can be trivially reverse en...
0
2016-08-07T11:06:17Z
[ "python", "reverse-engineering" ]
Unable to create REST service in python
38,813,465
<p>I want to create a REST service, So I tried and here's my snippet</p> <pre><code>from bottle import route, run @route('/plot_graph',method='GET') def plot_graph(): #compute graph_list (python object of type list) #done return graph_list if __name__ == "__main__": run(host='0.0.0.0', port=8881, ser...
3
2016-08-07T11:04:32Z
38,813,687
<p><code>graph_list</code> needs to contain strings, however, it looks like your list contains integers. You could convert these integers to strings with this:</p> <pre><code>return (str(i) for i in graph_list) </code></pre> <p>But note that the elements of the list are joined together which might not be what you wan...
2
2016-08-07T11:32:20Z
[ "python", "rest", "bottle" ]
Flask Login sessions not persisting when page changes
38,813,493
<p>I am using flask-login, flask and socketio in python. When I log in the user as can be seen in the login_data() function the session variables are set correctly by flask-login. However when the route changes all of the session variables are lost, which causes flask login to disallow the user to access the /overview ...
1
2016-08-07T11:07:20Z
38,816,353
<p>I have found the answer to this myself. For some unknown reason you cannot use the login_user function of flask-login inside of a flask-socketio event handler, it must instead be done through a normal post request. </p> <p>Hope this helps someone.</p>
1
2016-08-07T16:45:17Z
[ "python", "session", "flask", "flask-login", "flask-socketio" ]
Sum with Pythons uncertainties giving a diferent result than expected
38,813,532
<p>A friend of mine is evaluating data with Pythons package <code>uncertainties</code>. I am her statistics consulter, and I have come up with a weird result in her code.</p> <p><code>sum(array)</code> and <code>sqrt(sum(unumpy.std_devs(array)**2))</code> yield different results, with the second one being the variance...
0
2016-08-07T11:12:09Z
38,818,323
<p>You forgot to square the standard error to make it the variance. This should work and be equal to the error of <code>sum(array)</code>:</p> <pre><code>sqrt(sum(unumpy.std_devs(array)**2)) </code></pre> <p>Then</p> <pre><code>from uncertainties import unumpy import random import math a = [uc.ufloat(random.random(...
0
2016-08-07T20:38:12Z
[ "python", "statistics" ]
Sum with Pythons uncertainties giving a diferent result than expected
38,813,532
<p>A friend of mine is evaluating data with Pythons package <code>uncertainties</code>. I am her statistics consulter, and I have come up with a weird result in her code.</p> <p><code>sum(array)</code> and <code>sqrt(sum(unumpy.std_devs(array)**2))</code> yield different results, with the second one being the variance...
0
2016-08-07T11:12:09Z
39,058,633
<p>This results due to my <code>array</code> being an <code>AffineScalarFunc</code> (as opposed to a <code>Variable</code>), and thus they not only store the value but also all the variables that the value depends on <a href="https://pythonhosted.org/uncertainties/tech_guide.html#python-classes-for-variables-and-functi...
0
2016-08-20T20:56:37Z
[ "python", "statistics" ]
Python not recognizing installed dependencies
38,813,567
<p>I am running Python version 2.7.12 a windows system without internet access and have manually installed modules. However when trying to run a script requiring matplotlib.pyplot and after installing the dependencies <code>dateutil</code> it is still not working. </p> <p><a href="http://i.stack.imgur.com/1r88I.png" r...
0
2016-08-07T11:17:11Z
38,813,766
<p>Try using Pip to install the package. You can download a copy of dateutil 2.5.3 from here <a href="https://pypi.python.org/pypi/python-dateutil/2.5.3" rel="nofollow">https://pypi.python.org/pypi/python-dateutil/2.5.3</a>. </p> <p>Once downloaded, navigate to the folder where you downloaded the dateutil package, and...
0
2016-08-07T11:43:28Z
[ "python", "windows", "python-2.7", "matplotlib" ]
"Can't initialize character set utf8mb4" with Windows mysql-python
38,813,689
<p>I'm getting an error try to connect to a remote mysql database from a Windows 7 client via <strong>python 2.7</strong> + <strong>MySQLdb 1.2.5</strong> + <strong>sqlalchemy 1.0.9</strong>. This is a result of recently changing the server's default character set to <strong>utf8mb4</strong>. The server is running <str...
2
2016-08-07T11:32:29Z
39,844,966
<p>I've gone around in circles trying to get this to work on Windows.</p> <p>The only thing that seems to work for me is to execute this once the connection is established:</p> <pre><code>set names utf8mb4; </code></pre>
0
2016-10-04T05:48:01Z
[ "python", "mysql", "windows", "mysql-python", "utf8mb4" ]