title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
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 + "_" + ".") comment = pp.Literal("//") + pp.restOfLine messageName = ident messageKw = pp.Suppress(pp.Keyword("msg")) text = pp.Word(pp.alphanums + "_" + "." + "-" + "+") otherText = ~messageKw + pp.Suppress(text) messageExpr = pp.Forward() messageExpr &lt;&lt; (messageKw + messageName + openBrace + pp.ZeroOrMore(otherText) + pp.ZeroOrMore(messageExpr) + pp.ZeroOrMore(otherText) + closeBrace).ignore(comment) testStr = "msg msgName1 { some text msg msgName2 { some text } some text }" print messageExpr.parseString(testStr) </code></pre> <p>which produces this output: <code>['msgName1', 'msgName2']</code></p> <p>In the output, I would like to keep track of the structure of embedded matches. What I mean is that, for example, I would like the following output with the test string above: <code>['msgName1', 'msgName1.msgName2']</code> to keep track of the hierarchy in the text. However, I am new to pyparsing and have yet to find a way yet to extract the fact that "<code>msgName2</code>" is embedded in the structure of "<code>msgName1</code>."</p> <p>Is there a way to use the <code>setParseAction()</code> method of <code>ParserElement</code> to do this, or maybe using naming of results?</p> <p>Helpful advice would be appreciated. </p>
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() closeBrace = pp.Suppress(pp.Literal("}")).setParseAction(popMsgName) messageName = ident.setParseAction(pushMsgName) </code></pre> <p>And here is the complete code:</p> <pre><code>import pyparsing as pp msgNameStack = [] def pushMsgName(str, loc, tokens): msgNameStack.append(tokens[0]) tokens[0] = '.'.join(msgNameStack) def popMsgName(str, loc, tokens): msgNameStack.pop() openBrace = pp.Suppress(pp.Literal("{")) closeBrace = pp.Suppress(pp.Literal("}")).setParseAction(popMsgName) ident = pp.Word(pp.alphanums + "_" + ".") comment = pp.Literal("//") + pp.restOfLine messageName = ident.setParseAction(pushMsgName) messageKw = pp.Suppress(pp.Keyword("msg")) text = pp.Word(pp.alphanums + "_" + "." + "-" + "+") otherText = ~messageKw + pp.Suppress(text) messageExpr = pp.Forward() messageExpr &lt;&lt; (messageKw + messageName + openBrace + pp.ZeroOrMore(otherText) + pp.ZeroOrMore(messageExpr) + pp.ZeroOrMore(otherText) + closeBrace).ignore(comment) testStr = "msg msgName1 { some text msg msgName2 { some text } some text }" print messageExpr.parseString(testStr) </code></pre>
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> <pre><code>{Derivative(lambda1(t), t): (y(t) + 1)/(x(t)*y(t)), Derivative(z(t), t): x(t), Derivative(x(t), t): y(t)*z(t), Derivative(y(t), t): -x(t)*z(t) } </code></pre> <p>then from this I would like to integrate the differential equation system with <code>odeint()</code> from Scipy. For this I would need to extract the expressions (with <code>lambdify</code> for example) from the dictionary inside a <code>def Field(Q,t):</code>, to introduce as <code>odeint(Field,Q_0,t_array)</code>. Here is where I run with difficulties:</p> <p>I first tried </p> <pre><code>def Equ2(nQ,t,Q,Field): x1,y1,z1,lamb1 = nQ dQ =[] for f in Q: dQ.append(lambdify(Q, Field[f.diff(t)],'numpy' )(x1,y1,z1,lamb1)) return dQ[0:len(nQ)] </code></pre> <p>but it can't go to <code>odeint()</code> as it it takes fields with 2 arguments, and I tried to pass it in the optional <code>arga=()</code> of <code>odeint()</code>, giving me a (long) error:</p> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-20-63f086b8a252&gt; in Equ2(nQ, t, Q, Field) 20 dQ =[] 21 for f in Q: ---&gt; 22 dQ.append(lambdify(Q, Field[f.diff(t)],'numpy' )(x1,y1,z1,lamb1)) 23 return dQ[0:len(Q)-1] [...] ValueError: Can't calculate 1st derivative wrt 14.0430379424125. </code></pre> <p>So I tried essentially the same but without the loops,</p> <pre><code>def Equ1(nQ,t): x1,y1,z1,lamb1 = nQ dx = lambdify((x,y,z,lam[0]), field[x.diff(t)],'numpy' )(x1,y1,z1,lamb1) dy = lambdify((x,y,z,lam[0]), field[y.diff(t)],'numpy' )(x1,y1,z1,lamb1) dz = lambdify((x,y,z,lam[0]), field[z.diff(t)],'numpy' )(x1,y1,z1,lamb1) dlam = lambdify((x,y,z,lam[0]), field[lam[0].diff(t)],'numpy' )(x1,y1,z1,lamb1) return [dx,dy,dz] </code></pre> <p>and have the (I think) same problem:</p> <pre><code>ValueError Traceback (most recent call last) &lt;ipython-input-20-63f086b8a252&gt; in Equ1(nQ, t) 9 def Equ1(nQ,t): 10 x1,y1,z1,lamb1 = nQ ---&gt; 11 dx = lambdify((x,y,z,lam[0]), field[x.diff(t)],'numpy' )(x1,y1,z1,lamb1) 12 dy = lambdify((x,y,z,lam[0]), field[y.diff(t)],'numpy' )(x1,y1,z1,lamb1) 13 dz = lambdify((x,y,z,lam[0]), field[z.diff(t)],'numpy' )(x1,y1,z1,lamb1) [...] ValueError: Can't calculate 1st derivative wrt 17.6326726993661. </code></pre> <p>If I try simply:</p> <pre><code>def Equ0(nQ,t): x,y,z,lamb = nQ dx = y*z dy = -x*z dz = x dlam = (y+1.)/(x*y) return [dx,dy,dz] </code></pre> <p>the integration works just fine. Also if I call the <code>EquX()</code> functions with similar arguments that it would take inside <code>odeint()</code> they work just fine.</p> <p><strong>FULL CODE</strong></p> <pre><code>from sympy import * from sympy.physics.mechanics import dynamicsymbols from numpy import linspace, sin, cos from scipy.integrate import odeint t = Symbol('t') x = Function('x')(t) y = Function('y')(t) z = Function('z')(t) lam = dynamicsymbols('lambda1:{0}'.format(5)) f = x.diff(t)- y*z eq = Matrix([x.diff(t) - lam[0].diff(t)*y*x*z+z, y.diff(t) +x*z, z.diff(t)-x ]) field = solve(list(eq)+[f],[x.diff(t),y.diff(t),z.diff(t),lam[0].diff(t)]) def Equ0(nQ,t): x,y,z,lamb = nQ dx = y*z dy = -x*z dz = x dlam = (y+1.)/(x*y) return [dx,dy,dz] def Equ1(nQ,t): x1,y1,z1,lamb1 = nQ dx = lambdify((x,y,z,lam[0]), field[x.diff(t)],'numpy' )(x1,y1,z1,lamb1) dy = lambdify((x,y,z,lam[0]), field[y.diff(t)],'numpy' )(x1,y1,z1,lamb1) dz = lambdify((x,y,z,lam[0]), field[z.diff(t)],'numpy' )(x1,y1,z1,lamb1) dlam = lambdify((x,y,z,lam[0]), field[lam[0].diff(t)],'numpy' )(x1,y1,z1,lamb1) return [dx,dy,dz] def Equ2(nQ,t,Q,Field): x1,y1,z1,lamb1 = nQ dQ =[] for f in Q: dQ.append(lambdify(Q, Field[f.diff(t)],'numpy' )(x1,y1,z1,lamb1)) return dQ[0:len(Q)-1] q = [x,y,z,lam[0]] nq = [1,2,3,4] time=linspace(0,10,10) ### This line works just fine: print Equ0(nq,t), Equ1(nq,t), Equ2(nq,t,q,field) #They give the same output sol0 = odeint(Equ0,nq,time) sol1 = odeint(Equ1,nq,time) #Errors here sol2 = odeint(Equ2,nq,time,args=(q,field)) #And here </code></pre> <p>Lastly the full error: </p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-20-63f086b8a252&gt; in Equ1(nQ, t) 9 def Equ1(nQ,t): 10 x1,y1,z1,lamb1 = nQ ---&gt; 11 dx = lambdify((x,y,z,lam[0]), field[x.diff(t)],'numpy' )(x1,y1,z1,lamb1) 12 dy = lambdify((x,y,z,lam[0]), field[y.diff(t)],'numpy' )(x1,y1,z1,lamb1) 13 dz = lambdify((x,y,z,lam[0]), field[z.diff(t)],'numpy' )(x1,y1,z1,lamb1) /usr/local/lib/python2.7/dist-packages/sympy/core/expr.pyc in diff(self, *symbols, **assumptions) 2864 new_symbols = list(map(sympify, symbols)) # e.g. x, 2, y, z--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-20-63f086b8a252&gt; in Equ1(nQ, t) 9 def Equ1(nQ,t): 10 x1,y1,z1,lamb1 = nQ ---&gt; 11 dx = lambdify((x,y,z,lam[0]), field[x.diff(t)],'numpy' )(x1,y1,z1,lamb1) 12 dy = lambdify((x,y,z,lam[0]), field[y.diff(t)],'numpy' )(x1,y1,z1,lamb1) 13 dz = lambdify((x,y,z,lam[0]), field[z.diff(t)],'numpy' )(x1,y1,z1,lamb1) /usr/local/lib/python2.7/dist-packages/sympy/core/expr.pyc in diff(self, *symbols, **assumptions) 2864 new_symbols = list(map(sympify, symbols)) # e.g. x, 2, y, z 2865 assumptions.setdefault("evaluate", True) ---&gt; 2866 return Derivative(self, *new_symbols, **assumptions) 2867 2868 ########################################################################### /usr/local/lib/python2.7/dist-packages/sympy/core/function.pyc in __new__(cls, expr, *variables, **assumptions) 1068 ordinal = 'st' if last_digit == 1 else 'nd' if last_digit == 2 else 'rd' if last_digit == 3 else 'th' 1069 raise ValueError(filldedent(''' ---&gt; 1070 Can\'t calculate %s%s derivative wrt %s.''' % (count, ordinal, v))) 1071 1072 if all_zero and not count == 0: ValueError: Can't calculate 1st derivative wrt 0.0. 2865 assumptions.setdefault("evaluate", True) ---&gt; 2866 return Derivative(self, *new_symbols, **assumptions) 2867 2868 ########################################################################### /usr/local/lib/python2.7/dist-packages/sympy/core/function.pyc in __new__(cls, expr, *variables, **assumptions) 1068 ordinal = 'st' if last_digit == 1 else 'nd' if last_digit == 2 else 'rd' if last_digit == 3 else 'th' 1069 raise ValueError(filldedent(''' ---&gt; 1070 Can\'t calculate %s%s derivative wrt %s.''' % (count, ordinal, v))) 1071 1072 if all_zero and not count == 0: ValueError: Can't calculate 1st derivative wrt 0.0. </code></pre> <p><strong>TL;DR</strong> Some derivation Error appears inside odeint() that I cant reproduce outside odeint() with custom made functions.</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 easiser</p> <pre><code>"Sat Aug 06 23:54:24 +0000 2016""Sat Aug 06 23:54:24 +0000 2016""Sat Aug 06 23:54:24 +0000 2016""Sat Aug 06 23:54:24 +0000 2016" </code></pre> <p>Heres how I am reading it in </p> <pre><code>q = 'Trump' twitter_stream = twitter.TwitterStream(auth=twitter_api.auth) stream = twitter_stream.statuses.filter(track=q) for tweet in stream: print (type(tweet)) tweet = tweet['created_at'] with open('dates.json', 'a') as outfile: json.dump(tweet, outfile, indent=4) </code></pre> <p>and here is how I am currently attempting to get it out</p> <pre><code>with open('dates.json', 'rb') as f: data = f.readlines() </code></pre> <p>I want them to be separated by date so i can covert them to make a time series graph</p> <p>EDIT/UPDATE: Now I have this, but the stream just continously collects tweets without stopping. How do I get it to stop collecting the tweets and dump the JSON data into the file. Whethere manually or automatically</p> <pre><code>q = 'Trump' twitter_stream = twitter.TwitterStream(auth=twitter_api.auth) stream = twitter_stream.statuses.filter(track=q) dates = [tweet['created_at'] for tweet in stream] with open('dates.json', 'a') as outfile: json.dump(dates, outfile, indent=4) </code></pre>
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 the file. Before since it was dumping tweet by tweet I would just restart the shell.</p> </blockquote> <p>I think you should expand the comprehension to a regular loop and put it into a <code>try/finally</code>:</p> <pre><code>dates = [] try: for tweet in stream: dates.append(tweet['created_at']) finally: with open('dates.json', 'a') as outfile: json.dump(dates, outfile, indent=4) </code></pre>
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"]/tbody/tr/th/a/text()')</code>. Running this shows the full set of all of the text nodes in the table. </p> <p>I based this xpath on another similar xpath that I had previously used for this site which also returns all of the desired text nodes: <code>'.//*[@class="productionsEvent"]/text()'</code>. For some reason, when I try to print the text from the rows of the statistics table inside of the python shell after having simply requested the html, I get an empty list. What might the xpath not be working in the shell?</p>
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.federalreserve.gov/releases/h10/hist/" &gt;&gt;&gt; response = requests.get(url) &gt;&gt;&gt; root = fromstring(response.content) &gt;&gt;&gt; root.xpath('.//*[@class="statistics"]/tbody/tr/th/a/text()') # with tbody [] &gt;&gt;&gt; root.xpath('.//*[@class="statistics"]//tr/th/a/text()') # without tbody ['Australia', 'Brazil', 'Canada', 'China, P.R.', 'Denmark', 'EMU member countries', 'Greece', 'Hong Kong', 'India', 'Japan', 'Malaysia', 'Mexico', 'New Zealand', 'Norway', 'Singapore', 'South Africa', 'South Korea', '\r\n ', 'Sri Lanka', 'Sweden', 'Switzerland', 'Taiwan', 'Thailand', 'United Kingdom', 'Venezuela'] </code></pre>
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'] = complete['Age'] &gt; 15 </code></pre> <p>After getting SettingWithCopyWarning, I tried using.loc:</p> <pre><code>complete.loc[:, 'AgeGt15'] = complete['Age'] &gt; 15 complete.loc[:, 'WithFamily'] = complete['SibSp'] + complete['Parch'] &gt; 0 </code></pre> <p>However, I still get the same warning. What gives?</p>
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; </code></pre> <p>This allows Pandas to warn you later, when <code>complete['AgeGt15'] = complete['Age'] &gt; 15</code> is executed that you may be modifying a copy which will have no effect on <code>train</code>. For beginners this may be a useful warning. In your case, it appears you have no intention of modifying <code>train</code> indirectly by modifying <code>complete</code>. Therefore the warning is just a meaningless annoyance in your case.</p> <p>You can silence the warning by setting</p> <pre><code>complete.is_copy = False </code></pre> <p>This is quicker than making an actual copy, and nips the <code>SettingWithCopyWarning</code> in the bud (at the point <a href="https://github.com/pydata/pandas/blob/master/pandas/core/generic.py#L1559">where <code>_check_setitem_copy</code> is called</a>):</p> <pre><code>def _check_setitem_copy(self, stacklevel=4, t='setting', force=False): if force or self.is_copy: ... </code></pre> <hr> <p>If you are really confident you know what you are doing, you can shut off the <code>SettingWithCopyWarning</code> globally with</p> <pre><code>pd.options.mode.chained_assignment = None # None|'warn'|'raise' </code></pre>
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 in range(i): my_func(i, j) </code></pre> <p>How can I perform a similar replacement (assuming this is possible)?</p>
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; &lt;Event(3-KeyUp {'scancode': 1, 'key': 115, 'mod': 0})&gt; </code></pre> <p>but how can I get it to print out the scancode part? e.g. prints out <code>1</code> when I press <code>d</code>.</p> <p>I tried this:</p> <pre><code>for event in pygame.event.get(): print event["scancode"] </code></pre> <p>which throws a error message because is not really a dictionary data structure.</p>
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 character</li> <li><code>scancode</code> is the platform specific key code</li> </ul> <p>I'm guessing that <code>mod</code> is a bit-mask of OR-d bits.</p>
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, after viewing the documentation of numpy.gradient, I see that it uses distance=1 over the desired dimension. </p> <p>This is what I mean:</p> <pre><code>import numpy as np; a= np.array([10, 15, 13, 24, 15, 36, 17, 28, 39]); np.gradient(a) """ Got this: array([ 5. , 1.5, 4.5, 1. , 6. , 1. , -4. , 11. , 11. ]) """ np.diff(a) """ Got this: array([ 5, -2, 11, -9, 21, -19, 11, 11]) """ </code></pre> <p>I don't understand how the values in first result came. If the default distance is supposed to be 1, then I should have got the same results as numpy.diff. </p> <p>Could anyone explain what distance means here. Is it relative to the array index or to the value in the array? If it depends on the value, then does that mean that numpy.gradient could not be used with images since values of neighbor pixels have no fixed value differences?</p>
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() subject = forms.CharField() text = forms.Textarea() file = forms.FileField() password = forms.CharField() def mainpage(request): if request.method == 'POST': form = MainForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponse('Ok') else: return HttpResponse('not ok') form = MainForm() return render(request, "main.html", {'form': form}) def handle_uploaded_file(file): name = file.name with open(os.path.join("static\img", "{0}".format(name)), 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) </code></pre> <p>And as my template goes:</p> <pre><code>{% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html lang="en" xmlns="http://www.w3.org/1999/html"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;{{ siteTitle }}&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css"&gt; &lt;/head&gt; &lt;body&gt; {% include 'header.html' %} &lt;form method="post"&gt; {% csrf_token %} &lt;label class="label" for="name"&gt;Name&lt;/label&gt; &lt;input id="namebox" type="text" name="name" /&gt; &lt;/br&gt; &lt;label class="label" for="subject"&gt;Subject&lt;/label&gt; &lt;input id="subjectbox" type="text" name="subject" /&gt; &lt;/br&gt; &lt;label class="label" for="text"&gt;Text&lt;/label&gt; &lt;textarea id="textedit" name="text"&gt;&lt;/textarea&gt; &lt;/br&gt; &lt;label class="label" for="file"&gt;File&lt;/label&gt; &lt;input type="file" name="file" /&gt; &lt;/br&gt; &lt;label class="label" for="password"&gt;Password&lt;/label&gt; &lt;input type="password" id="passwordbox" name="password" /&gt; &lt;/br&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But every time I send something via the form in my template, it's not validated and it switches to "not ok". Please help. Thanks.</p> <p><strong>Edit</strong> How it is now:</p> <pre><code>&lt;form enctype="multipart/form-data" method="post"&gt; {% csrf_token %} &lt;table&gt; &lt;ul&gt; {{ form.as_table }} &lt;/ul&gt; &lt;/table&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; </code></pre>
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 need to make sure that your element correctly defines the enctype as "multipart/form-data":</p> <pre><code>&lt;form enctype="multipart/form-data" method="post" action="/foo/"&gt; </code></pre> </blockquote> <p>This is probably the cause of your validation issue.</p></li> <li><p>The Forms API is powerful and handles things like <a href="https://docs.djangoproject.com/en/stable/topics/forms/#form-rendering-options" rel="nofollow">rendering forms for you</a>. </p> <p>You should use this because the default renderer will also display form field errors which you currently aren't rendering (so you have no way of knowing what field failed to validate - if you were rendering errors you would know that the issue was with the file input).</p> <p>Alternatively you need to <a href="https://docs.djangoproject.com/en/dev/topics/forms/#rendering-form-error-messages" rel="nofollow">render form errors manually</a>.</p></li> </ol>
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 from kivy.core.window import Window from kivy.graphics import Color, Rectangle from kivy.properties import NumericProperty from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(26, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 1 GPIO.setup(20, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 2 GPIO.setup(21, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 3 GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 4 GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 5 GPIO.setup(27, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 6 GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 7 GPIO.setup(10, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 8 GPIO.setup(9, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino sensor 9 GPIO.setup(19, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #pino master GPIO.setup(12, GPIO.OUT) #pino buzzer pin_Master = 19 pin_1 = 26 pin_2 = 20 pin_3 = 21 pin_4 = 4 pin_5 = 17 pin_6 = 27 pin_7 = 22 pin_8 = 10 pin_9 = 9 class MainLayout(FloatLayout): pass class bar(Widget): r = NumericProperty(1) g = NumericProperty(0) def __init__(self, pin, p1, p2, **kwargs): super(bar, self).__init__(**kwargs) self.pin = pin self.p1 = p1 self.p2 = p2 self.pin_Buzzer = 12 Clock.schedule_interval(self.update, 1.0 / 60.0) 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)) GPIO.output(12, 0) else: with self.canvas: Color(self.r, 0, 0, 1) Rectangle(pos=(self.p1,self.p2), size=(35,30)) GPIO.output(12, 1) def read_Sensor(self, pin): sensor = GPIO.wait_for_edge(pin, GPIO.BOTH, timeout=200) if sensor is None: return False else: return True def read_SensorGeral(self, pin): sensor = GPIO.wait_for_edge(pin, GPIO.BOTH, timeout=200) if sensor is None: return False else: return True class MainApp(App): def build(self): Window.clearcolor = (1, 1, 1, 1) self.mainlayout = Widget() barGeral = bar(pin_Master, 26, 100) bar1 = bar(pin_1, 26, 30) bar2 = bar(pin_2, 106, 30) bar3 = bar(pin_3, 186, 30) bar4 = bar(pin_4, 266, 30) bar5 = bar(pin_5, 346, 30) bar6 = bar(pin_6, 426, 30) bar7 = bar(pin_7, 506, 30) bar8 = bar(pin_8, 586, 30) bar9 = bar(pin_9, 666, 30) self.mainlayout.add_widget(barGeral) self.mainlayout.add_widget(bar1) self.mainlayout.add_widget(bar2) self.mainlayout.add_widget(bar3) self.mainlayout.add_widget(bar4) self.mainlayout.add_widget(bar5) self.mainlayout.add_widget(bar6) self.mainlayout.add_widget(bar7) self.mainlayout.add_widget(bar8) self.mainlayout.add_widget(bar9) return self.mainlayout try: if __name__ == '__main__': MainApp().run() except KeyboardInterrupt: print("Programa finalizado!") GPIO.cleanup() </code></pre>
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_Sensor(self.pin): GPIO.output(12, 1) else: with self.canvas: Color(self.r, 0, 0, 1) Rectangle(pos=(self.p1,self.p2), size=(35,30)) GPIO.output(12, 0) </code></pre> <p>There might be another problem tou. You run <code>update()</code> 60 times per second, but you allow a pin timeout of 200. That means you have several <code>update()</code> threads running at the same time. That might give unexpected results.<br> Maybe you should make the update as a loop in one thread per bar. Like so: </p> <pre><code>from thread import start_new_thread class bar(Widget): r = NumericProperty(1) g = NumericProperty(0) def __init__(self, pin, p1, p2, **kwargs): super(bar, self).__init__(**kwargs) self.pin = pin self.p1 = p1 self.p2 = p2 self.pin_Buzzer = 12 start_new_thread(self.update()) def update(self): 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_Sensor(self.pin): GPIO.output(12, 1) else: with self.canvas: Color(self.r, 0, 0, 1) Rectangle(pos=(self.p1,self.p2), size=(35,30)) GPIO.output(12, 0) time.sleep(10) # maybe a little time sleep between the updates self.update() </code></pre> <p>And initiate the update loop in your <code>__init__</code> method. <code>self.update()</code></p>
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'http://www.websites.com/2.jpg', u'http://www.websites.com/3.jpg'], </code></pre> <p>now i've worked around this by doing a more targeted xpath and selecting elements by numbers [2] but my real problem is with these returns from the scraped images </p> <p><strong>second list:</strong></p> <pre><code>'images': [{'checksum': '2efhz768djdzs76dz', 'path': 'full/2efhz768djdzs76dz.jpg', 'url': 'http://www.websites.com/1.jpg'}, {'checksum': 'zadz764dhqj34dsjs', 'path': 'full/zadz764dhqj34dsjs.jpg', 'url': 'http://www.websites.com/2.jpg'}], </code></pre> <p>i'm using sqlite3 to store al my other scraped data with an item.get</p> <p>item.get('image_urls','')</p> <p>how do you merge a list of value's to a string or target it based on its rank ? (first list)</p> <p>and how do i get the value for the checksum, path and url with an item.get ? (second list)</p> <p><strong>Edit:</strong> i'm still looking for a solution to the second problem :</p> <p>this is the output:</p> <pre><code>'images': [{'checksum': '2efhz768djdzs76dz', 'path': 'full/2efhz768djdzs76dz.jpg', 'url': 'http://www.websites.com/1.jpg'}, {'checksum': 'zadz764dhqj34dsjs', 'path': 'full/zadz764dhqj34dsjs.jpg', 'url': 'http://www.websites.com/2.jpg'}], </code></pre> <p>how do i get the first or the second checksum to go in an sqlite column. i currently use :</p> <p>item.get('scrapy-item','') for which spracy item represents the name of the scraped item, preferably in a code example.</p>
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/zadz764dhqj34dsjs.jpg', 'url': 'http://www.websites.com/2.jpg', 'checksum': 'zadz764dhqj34dsjs'}] &gt;&gt;&gt; list(map(lambda x : x['url'] + '/' + x['path'], images)) ['http://www.websites.com/1.jpg/full/2efhz768djdzs76dz.jpg', 'http://www.websites.com/2.jpg/full/zadz764dhqj34dsjs.jpg'] &gt;&gt;&gt; list(map(lambda x : x['checksum'], images)) ['2efhz768djdzs76dz', 'zadz764dhqj34dsjs'] </code></pre> <p>The above code should give you an overview of how to handle conversion between arrays and dictionaries. You could just as well iterate over the entire array and get your values, though I prefer lambda functions.</p> <p>Hope this helps I am not really familiar with scrapy. So if you are still unsure about something, just drop a comment.</p>
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'http://www.websites.com/2.jpg', u'http://www.websites.com/3.jpg'], </code></pre> <p>now i've worked around this by doing a more targeted xpath and selecting elements by numbers [2] but my real problem is with these returns from the scraped images </p> <p><strong>second list:</strong></p> <pre><code>'images': [{'checksum': '2efhz768djdzs76dz', 'path': 'full/2efhz768djdzs76dz.jpg', 'url': 'http://www.websites.com/1.jpg'}, {'checksum': 'zadz764dhqj34dsjs', 'path': 'full/zadz764dhqj34dsjs.jpg', 'url': 'http://www.websites.com/2.jpg'}], </code></pre> <p>i'm using sqlite3 to store al my other scraped data with an item.get</p> <p>item.get('image_urls','')</p> <p>how do you merge a list of value's to a string or target it based on its rank ? (first list)</p> <p>and how do i get the value for the checksum, path and url with an item.get ? (second list)</p> <p><strong>Edit:</strong> i'm still looking for a solution to the second problem :</p> <p>this is the output:</p> <pre><code>'images': [{'checksum': '2efhz768djdzs76dz', 'path': 'full/2efhz768djdzs76dz.jpg', 'url': 'http://www.websites.com/1.jpg'}, {'checksum': 'zadz764dhqj34dsjs', 'path': 'full/zadz764dhqj34dsjs.jpg', 'url': 'http://www.websites.com/2.jpg'}], </code></pre> <p>how do i get the first or the second checksum to go in an sqlite column. i currently use :</p> <p>item.get('scrapy-item','') for which spracy item represents the name of the scraped item, preferably in a code example.</p>
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:</p> <pre><code>websites_urls=[] checksums=[] paths=[] whole_item=[] for image_url in item.get('image_urls'): for image in item.get('images'): if image_url==image['url']: websites_urls.append(image['url']) checksums.append(image['checksum']) paths.append(image['path']) whole_item.append(image) break </code></pre>
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((len(L)))): if L[ii] &lt;= L[(ii+1)]: counter+=1 ii+=1 else: ii+=1 counts.append(counter) counter=1 continue counts.sort() return counts[-1] </code></pre> <p>It is supposed to count the longest streak of consecutive increases for a list of integers. I got it working by subtracting 1 from the while statement but then it will not always show the right answer because it won't go through the whole list.</p> <p>Here is my specific error message:</p> <pre class="lang-none prettyprint-override"><code>IndexError Traceback (most recent call last) &lt;ipython-input-76-1b4664f2fb31&gt; in &lt;module&gt;() ----&gt; 1 longestRun(L) C:\Users\james_000\Desktop\longestRun.py in longestRun(L) 4 counts=[1] 5 while ii&lt;=max(range((len(L)))): ----&gt; 6 if L[ii] &lt;= L[(ii+1)]: 7 counter+=1 8 ii+=1 </code></pre>
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((len(L)))): if L[ii] &lt;= L[(ii+1)]: counter+=1 ii+=1 else: ii+=1 counts.append(counter) counter=1 continue counts.sort() return counts[-1] </code></pre> <p>It is supposed to count the longest streak of consecutive increases for a list of integers. I got it working by subtracting 1 from the while statement but then it will not always show the right answer because it won't go through the whole list.</p> <p>Here is my specific error message:</p> <pre class="lang-none prettyprint-override"><code>IndexError Traceback (most recent call last) &lt;ipython-input-76-1b4664f2fb31&gt; in &lt;module&gt;() ----&gt; 1 longestRun(L) C:\Users\james_000\Desktop\longestRun.py in longestRun(L) 4 counts=[1] 5 while ii&lt;=max(range((len(L)))): ----&gt; 6 if L[ii] &lt;= L[(ii+1)]: 7 counter+=1 8 ii+=1 </code></pre>
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", reporthook=report) def report(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) gui.downloadBar['value'] = percent </code></pre> <p>However, this makes the GUI window not respond, yet the console window is fine. If it doesn't respond, users will think it's stuck and end its process, and their gamedata will be corrupted. I've tried running on seperate threads, like this:</p> <pre><code>def doDownload(): threading.Thread(target=__doDownload).start() def __doDownload(): urllib.urlretrieve("http://hiddenfile/hi.txt", "hi.txt", reporthook=report) def report(count, blockSize, totalSize): percent = int(count*blockSize*100/totalSize) gui.downloadBar['value'] = percent </code></pre> <p>But that doesn't even download it. Is there any way to download a file, without a window (ex. Tkinter window) going unresponsive?</p>
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; app.register_blueprint(admin) File "/home/xxxxx/xxxxx.xxxxxxx.com/ClientTracker/env/local/lib/python2.7/site-packages/flask/app.py", line 65, in wrapper_func return f(self, *args, **kwargs) File "/home/xxxxx/xxxxx.xxxxxxx.com/ClientTracker/env/local/lib/python2.7/site-packages/flask/app.py", line 958, in register_blueprint if blueprint.name in self.blueprints: AttributeError: 'function' object has no attribute 'name' </code></pre> <p>This is a migration from a simpler hierarchy implementing Blueprints. I'm splitting out the function of the frontend and the admin panel.</p> <p>I built this step by step and <strong>had both sides working fine</strong>. Started migrating (functions and routes). After moving some code, I started getting an error message (basically the same as above, but different line). </p> <p><strong>Troubleshooting</strong></p> <ul> <li>Searched through related posts on stackO</li> <li>Initially it was complaining about the second route statement I had. I started removing code (rolling back) to what I (thought was) a known good state. However I continued to have issues.</li> <li>I have it down to the minimum code I believe I need but still getting errors.</li> <li>If I remove the registration in the <strong>init</strong>.py file, the frontend works perfectly.</li> </ul> <p><strong>Code</strong></p> <pre><code>#ClientTracker/run.py #!env/bin/python from app import app app.run(host='0.0.0.0', port=8080, debug=False) </code></pre> <hr> <pre><code>#ClientTracker/app/__init__.py # Import flask and template operators from flask import Flask, render_template # Define the WSGI application object app = Flask(__name__) # Import a module / component using its blueprint handler variable (mod_auth) #from app.mod_auth.controllers import mod_auth as auth_module from app.admin.views import admin from app.client.views import client # Register blueprint(s) app.register_blueprint(admin) app.register_blueprint(client) </code></pre> <hr> <pre><code>#ClientTracker/app/admin/views.py from flask import render_template, request, Blueprint from app import app import MySQLdb import datetime admin = Blueprint( 'admin', __name__, url_prefix='/admin', template_folder='templates', static_folder='static' ) @admin.route('/') def admin(): return "ok" </code></pre> <p>I'm out of ideas. </p>
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>Basically, you cannot have a function name with the same name as your Blueprint name. Seems obvious now, but certainly stumped me for a while.</p> <p>In thinking about it, my original "working" state had a dummy function name serving the '/'. When I rolled back, I didn't roll back far enough.</p> <p>Replaced def admin(): with def admin1(): (will fix this better in prod) and all worked.</p> <p>I hope this post helps someone else. Please still feel free to comment. As always, the group is always smarter than the individual. Lastly, thanks for reading this far. :-)</p>
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 time. if (some condition): print ("&gt; Done!") </code></pre> <p>I thought that the result must be:</p> <pre><code>FILENAME &gt; Checking file ... *tick tock* ... &gt; Creating archive ... *tick tock* ... &gt; Done! </code></pre> <p>But the line appeares entirely after each loop cycle. How can show messages like CMD style? </p>
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", end=" ", flush=True) if (some condition): print ("&gt; Done!") </code></pre> <p>It's not necessary for the last print (although it won't hurt) since that will print a new line which will flush the output.</p> <p>Note also that you will want to print a new line at the end of each iteration. Considering that you are printing conditionally, the final print might not actually occur, so it's a good idea to use <code>end=' '</code> in all of the prints, and then print a new line at the end of each iteration:</p> <pre><code>for item in 'a', 'b', 'c': print (item + " &gt; Cheking file", end=" ", flush=True) if (some condition): print ("&gt; Creating archive", end=" ", flush=True) if (some condition): print ("&gt; Done!", end=' ') print() </code></pre> <p>Now, if for some reason the final condition is not <code>True</code>, a new line will still be printed.</p>
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 time. if (some condition): print ("&gt; Done!") </code></pre> <p>I thought that the result must be:</p> <pre><code>FILENAME &gt; Checking file ... *tick tock* ... &gt; Creating archive ... *tick tock* ... &gt; Done! </code></pre> <p>But the line appeares entirely after each loop cycle. How can show messages like CMD style? </p>
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).</p> <p>You can work around that buffering by passing <code>flush=True</code> in the calls where you're setting <code>end</code>. That will tell Python to flush the buffer even though there has not been a newline written.</p> <p>So try:</p> <pre><code>for item in array: print(item + " &gt; Cheking file", end=" ", flush=True) #Conditions which takes some time. Create a zip file or smth else.. if some_condition: print("&gt; Creating archive", end=" ", flush=True) #Another conditions which takes some time. if some_other_condition: print("&gt; Done!") </code></pre>
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>["Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016", "Sun Aug 07 01:50:13 +0000 2016"] </code></pre> <p>I would expect the output to be something similar to this (grabbed from another program) </p> <pre><code>[('Sun Aug 07 02:29:45 +0000 2016', 4), ('Sun Aug 07 02:31:05 +0000 2016', 4), ('Sun Aug 07 02:31:04 +0000 2016', 3), ('Sun Aug 07 02:31:08 +0000 2016', 3), ('Sun Aug 07 02:31:22 +0000 2016', 3)] </code></pre> <p>But this is my output</p> <pre><code>[(48, 72), (32, 53), (49, 27), (34, 18), (117, 18), (58, 18), (65, 9), (51, 9), (103, 9), (43, 9)] </code></pre> <p>I dont really understand what its counting there </p>
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 = [] class doit(Event): """doit Event""" class terminate(Event): """terminate Event""" class App(Component): def __init__(self): super().__init__() self.interval = .1 self.last = 0 self.count = 0 def doit(self, origin): times.append(("%s from A at %.03f" % (origin, time.time()))) self.count += 1 self.last = time.time() def generate_events(self, event): if self.last + self.interval &lt; time.time(): event.stop() self.fire(doit('ge')) if self.count &gt;= 5: event.stop() self.fire(terminate()) def terminate(self): self.stop() (Debugger() + App()).run() print("\n".join(times)) </code></pre> <p>I got the same behavior using event.reduce_time_left(0) instead of event.stop(). </p>
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 firing again - so that it will certainly fire again by that time - whether something is generated or not. Reducing the time to 0 indicates that this cycle is complete (and events need to be fired). </p> <p>The preferred solution uses <code>Timer</code> to implement the time functionality, reducing this example to the logic to display how it works.</p> <pre><code>from circuits import BaseComponent, Event, Timer, Debugger, handler import time class doit(Event): """doit Event""" class App(BaseComponent): timer = Timer(.1, doit('A'), persist=True) def __init__(self): super().__init__() self.count = 0 @handler("doit") def _doit(self, origin): print("%s from A at %.03f" % (origin, time.time())) self.count += 1 if self.count &gt; 4: self.stop() (App() + Debugger()).run() </code></pre>
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>DataFrame</code> with this command:</p> <pre><code>df = sqlContext.createDataFrame(preds_labels, ["prediction", "label"]) </code></pre> <p>I get an error message:</p> <blockquote> <p>not supported type: type 'numpy.float64'</p> </blockquote> <p>If I create the list manually, I have no problem. Do you have an idea?</p>
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], ["prediction", "label"] ) </code></pre> <p>Note pyspark will then take them as <code>pyspark.sql.types.DoubleType</code></p>
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>: </p> <pre><code>df.sort_values(df.snr) </code></pre> <p>but this raises</p> <pre><code>_convert_to_indexer(self, obj, axis, is_setter) 1208 mask = check == -1 1209 if mask.any(): -&gt; 1210 raise KeyError('%s not in index' % objarr[mask]) 1211 1212 return _values_from_object(indexer) KeyError: '[ inf 62. 82. 52. 42. 72.] not in index' </code></pre> <p>I am not explicitly setting an index on this DataFrame, it's coming from a list comprehension: </p> <pre><code> import pandas as pd d = [] for run in runs: d.append({ 'snr': run.periphery.snr.snr, 'peaklatency': (run.brainstem.wave5.wave5.argmax() / 100e3) * 1e3 }) df = pd.DataFrame(d) </code></pre>
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 54.12 82.0 </code></pre>
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> <p>I keep getting the error TypeError: can't multiply sequence by non-int of type 'float'</p>
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 error is that <code>x</code> is a python list, which cannot be multiplied by a floating number (4.5 in this case). But <code>df['Temperature']</code> can (it's a pandas.Series)</p> <p>Also, <code>0.00459652*np.exp(4.5*x)+0.000984312</code> is not a python function. You need <code>lambda x : 0.00459652*np.exp(4.5*x)+0.000984312</code></p>
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>I have not been able to try anything meaningful because i am at loss at how to approach this problem, hence do not have any code samples or methods i have tried so far. Help will be deeply appreciated! :)</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 Java, Python/Jython, and JavaScript. (Though JavaScript support is still experimental.)</p> <p>The following sections describe how to register your functions with Pig so you can call them either from the Pig shell or from within Pig scripts. For more information about using UDFs with Pig, go to <a href="http://pig.apache.org/docs/r0.14.0/udf.html" rel="nofollow">http://pig.apache.org/docs/r0.14.0/udf.html</a>.</p> <p><strong>Call JAR files from Pig:</strong></p> <p>You can use custom JAR files with Pig using the REGISTER command in your Pig script. The JAR file is local or a remote file system such as Amazon S3. When the Pig script runs, Amazon EMR downloads the JAR file automatically to the master node and then uploads the JAR file to the Hadoop distributed cache. In this way, the JAR file is automatically used as necessary by all instances in the cluster.</p> <p><strong>To use JAR files with Pig</strong></p> <p>1.Upload your custom JAR file into Amazon S3.</p> <p>2.Use the REGISTER command in your Pig script to specify the bucket on Amazon S3 of the custom JAR file.</p> <pre><code>REGISTER s3://mybucket/path/mycustomjar.jar; </code></pre> <p><strong>Call Python/Jython Scripts from Pig</strong></p> <p>You can register Python scripts with Pig and then call functions in those scripts from the Pig shell or in a Pig script. You do this by specifying the location of the script with the register keyword.</p> <p>Because Pig is written in Java, it uses the Jython script engine to parse Python scripts. For more information about Jython, go to <a href="http://www.jython.org/" rel="nofollow">http://www.jython.org/</a>.</p> <p><strong>To call a Python/Jython script from Pig</strong></p> <p>1.Write a Python script and upload the script to a location in Amazon S3. This should be a bucket owned by the same account that creates the Pig cluster, or that has permissions set so the account that created the cluster can access it. In this example, the script is uploaded to </p> <pre><code>s3://mybucket/pig/python. </code></pre> <p>2.Start a pig cluster. If you'll be accessing Pig from the Grunt shell, run an interactive cluster. If you're running Pig commands from a script, start a scripted Pig cluster. In this example, we'll start an interactive cluster.</p> <p>3.Because we've launched an interactive cluster, we'll now SSH into the master node where we can run the Grunt shell. For more information about how to SSH into the master node, see SSH into the Master Node.</p> <p>4.Run the Grunt shell for Pig by typing pig at the command line.</p> <pre><code>pig </code></pre> <p>5.Register the Jython library and your Python script with Pig using the register keyword at the Grunt command prompt, as shown in the following, where you would specify the location of your script in Amazon S3.</p> <pre><code>grunt&gt; register 'lib/jython.jar'; grunt&gt; register 's3://mybucket/pig/python/myscript.py' using jython as myfunctions; </code></pre> <p>6.Load the input data. The following example loads input from an Amazon S3 location.</p> <pre><code>grunt&gt; input = load 's3://mybucket/input/data.txt' using TextLoader as (line:chararray); </code></pre> <p>7.You can now call functions in your script from within Pig by referencing them using myfunctions.</p> <pre><code>grunt&gt; output=foreach input generate myfunctions.myfunction($1); </code></pre>
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 i in range(N): for t in range(M): Station_Size[i,t] = m.addVar(ub=Q, name = 'Station_Size_%s_%s' %(i,t)) for j in range(N): Admission[i,j,t] = m.addVar(ub = Arrival_Rate[t,i,j], obj=-1, name = 'Admission_Rate_%s_%s_%s' %(i,j,t)) Return[i,j,t] = m.addVar(name = 'Return_Rate_%s_%s_%s' %(i,j,t)) </code></pre> <p>I have the problem solved and I have three dictionary:</p> <pre><code>Station_Size, Admission and Return </code></pre> <p>I know that the solution can be accessed as:</p> <pre><code>Station_Size[i,t].X, Admission[i,j,t].X and Return[i,j,t].X </code></pre> <p>I want to creat three Numpy array such that:</p> <pre><code>Array_Station_Size[i,t] = Station_Size[i,t].X Array_Admission[i,j,t] = Admission[i,j,t].X </code></pre> <p>I can definitely do this by creating three loops and creat the Numpy Array element by element. It's do-able if the loop doesn't take a lot of time. But I just want to know if there is a better way to do this. Please comment if I did not make myself clear.</p>
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 because I first declare (or define) the graph, so adding print statements to the graph definition does not help. Are there any rules, advice, heuristics, anything to track down what might be causing the NaN?</p> <hr> <p>In this case I know more precisely what line to look at because I have the following:</p> <pre><code>Delta_tilde = 2.0*tf.matmul(x,W) - tf.add(WW, XX) #note this quantity should always be positive because its pair-wise euclidian distance Z = tf.sqrt(Delta_tilde) Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) A = tf.exp(Z) </code></pre> <p>when this line is present I have it that it returns NaN as declared by my summary writers. Why is this? Is there a way to at least explore what value Z has after its being square rooted?</p> <hr> <p>For the specific example I posted, I tried <code>tf.Print(0,Z)</code> but with no success it printed nothing. As in:</p> <pre><code>Delta_tilde = 2.0*tf.matmul(x,W) - tf.add(WW, XX) #note this quantity should always be positive because its pair-wise euclidian distance Z = tf.sqrt(Delta_tilde) tf.Print(0,[Z]) # &lt;-------- TF PRINT STATMENT Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) A = tf.exp(Z) </code></pre> <p>I actually don't understand what <code>tf.Print</code> is suppose to do. Why does it need two arguments? If I want to print 1 tensor why would I need to pass 2? Seems bizarre to me.</p> <hr> <p>I was looking at the function <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/control_flow_ops.html#add_check_numerics_ops">tf.add_check_numerics_ops()</a> but it doesn't say how to use it (plus the docs seem to not be super helpful). Does anyone know how to use this?</p> <hr> <p>Since I've had comments addressing the data might be bad, I am using standard MNIST. However, I am computing a quantity that is positive (pair-wise eucledian distance) and then square rooting it. Thus, I wouldn't see how the data specifically would be an issue.</p>
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 because I first declare (or define) the graph, so adding print statements to the graph definition does not help. Are there any rules, advice, heuristics, anything to track down what might be causing the NaN?</p> <hr> <p>In this case I know more precisely what line to look at because I have the following:</p> <pre><code>Delta_tilde = 2.0*tf.matmul(x,W) - tf.add(WW, XX) #note this quantity should always be positive because its pair-wise euclidian distance Z = tf.sqrt(Delta_tilde) Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) A = tf.exp(Z) </code></pre> <p>when this line is present I have it that it returns NaN as declared by my summary writers. Why is this? Is there a way to at least explore what value Z has after its being square rooted?</p> <hr> <p>For the specific example I posted, I tried <code>tf.Print(0,Z)</code> but with no success it printed nothing. As in:</p> <pre><code>Delta_tilde = 2.0*tf.matmul(x,W) - tf.add(WW, XX) #note this quantity should always be positive because its pair-wise euclidian distance Z = tf.sqrt(Delta_tilde) tf.Print(0,[Z]) # &lt;-------- TF PRINT STATMENT Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) A = tf.exp(Z) </code></pre> <p>I actually don't understand what <code>tf.Print</code> is suppose to do. Why does it need two arguments? If I want to print 1 tensor why would I need to pass 2? Seems bizarre to me.</p> <hr> <p>I was looking at the function <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/control_flow_ops.html#add_check_numerics_ops">tf.add_check_numerics_ops()</a> but it doesn't say how to use it (plus the docs seem to not be super helpful). Does anyone know how to use this?</p> <hr> <p>Since I've had comments addressing the data might be bad, I am using standard MNIST. However, I am computing a quantity that is positive (pair-wise eucledian distance) and then square rooting it. Thus, I wouldn't see how the data specifically would be an issue.</p>
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 this would result only in the printing of the tensor-information inside the graph and not print any actual values). </p> <p>However, if you use tf.print as an op in bulding the graph (<a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#Print" rel="nofollow">tf.print</a>) then when the graph gets executed you will get the actual values printed (and it IS a good exercise to watch these values to debug and understand the behavior of your net).</p> <p>However, you are using the print-statement not entirely in the correct manner. This is an op, so you need to pass it a tensor and request a result-tensor that you need to work with later on in the executing graph. Otherwise the op is not going to be executed and no printing occurs. Try this:</p> <pre><code>Z = tf.sqrt(Delta_tilde) Z = tf.Print(Z,[Z], message="my Z-values:") # &lt;-------- TF PRINT STATMENT Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) </code></pre>
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 because I first declare (or define) the graph, so adding print statements to the graph definition does not help. Are there any rules, advice, heuristics, anything to track down what might be causing the NaN?</p> <hr> <p>In this case I know more precisely what line to look at because I have the following:</p> <pre><code>Delta_tilde = 2.0*tf.matmul(x,W) - tf.add(WW, XX) #note this quantity should always be positive because its pair-wise euclidian distance Z = tf.sqrt(Delta_tilde) Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) A = tf.exp(Z) </code></pre> <p>when this line is present I have it that it returns NaN as declared by my summary writers. Why is this? Is there a way to at least explore what value Z has after its being square rooted?</p> <hr> <p>For the specific example I posted, I tried <code>tf.Print(0,Z)</code> but with no success it printed nothing. As in:</p> <pre><code>Delta_tilde = 2.0*tf.matmul(x,W) - tf.add(WW, XX) #note this quantity should always be positive because its pair-wise euclidian distance Z = tf.sqrt(Delta_tilde) tf.Print(0,[Z]) # &lt;-------- TF PRINT STATMENT Z = Transform(Z) # potentially some transform, currently I have it to return Z for debugging (the identity) Z = tf.pow(Z, 2.0) A = tf.exp(Z) </code></pre> <p>I actually don't understand what <code>tf.Print</code> is suppose to do. Why does it need two arguments? If I want to print 1 tensor why would I need to pass 2? Seems bizarre to me.</p> <hr> <p>I was looking at the function <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/control_flow_ops.html#add_check_numerics_ops">tf.add_check_numerics_ops()</a> but it doesn't say how to use it (plus the docs seem to not be super helpful). Does anyone know how to use this?</p> <hr> <p>Since I've had comments addressing the data might be bad, I am using standard MNIST. However, I am computing a quantity that is positive (pair-wise eucledian distance) and then square rooting it. Thus, I wouldn't see how the data specifically would be an issue.</p>
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) #etc.. summary_merge = tf.merge_all_summaries() #on each desired step save: summary_str = sess.run(summary_merge) summary_writer.add_summary(summary_str, i) </code></pre> <p>Also you can simply eval and print the current value:</p> <pre><code> print(sess.run(Z)) </code></pre>
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>Code</strong></p> <pre><code>soup = bs4.BeautifulSoup(driver.page_source, "html.parser") for thead in soup.select(".data-point-container table thead"): tbody = thead.find_next_sibling("tbody") table = "&lt;table&gt;%s&lt;/table&gt;" % (str(thead) + str(tbody)) df = pandas.read_html(str(table))[0] print(df) print('-------------') </code></pre> <p><strong>Result</strong></p> <pre><code> Table1 FY2012 FY2013 FY2014 FY2015 Last 12 Months 0 item1 value1 value2 value3 value4 value5 1 item2 value1 value2 value3 value4 value5 2 item3 value1 value2 value3 value4 value5 3 item4 value1 value2 value3 value4 value5 4 item5 value1 value2 value3 value4 value5 5 item6 value1 value2 value3 value4 value5 ------------- Table2 FY2012 FY2013 FY2014 FY2015 Last 12 Months 0 item1 value1 value2 value3 value4 value5 1 item2 value1 value2 value3 value4 value5 2 item3 value1 value2 value3 value4 value5 3 item4 value1 value2 value3 value4 value5 ------------- Table3 FY2012 FY2013 FY2014 FY2015 Last 12 Months 0 item1 value1 value2 value3 value4 value5 1 item2 value1 value2 value3 value4 value5 2 item3 value1 value2 value3 value4 value5 3 item4 value1 value2 value3 value4 value5 4 item5 value1 value2 value3 value4 value5 5 item6 value1 value2 value3 value4 value5 ------------- Table4 FY2012 FY2013 FY2014 FY2015 Last 12 Months 0 item1 value1 value2 value3 value4 value5 1 item2 value1 value2 value3 value4 value5 2 item3 value1 value2 value3 value4 value5 3 item4 value1 value2 value3 value4 value5 4 item5 value1 value2 value3 value4 value5 5 item6 value1 value2 value3 value4 value5 6 item7 value1 value2 value3 value4 value5 7 item8 value1 value2 value3 value4 value5 </code></pre> <p>Is there a way for me to concat / merge all Dataframes together into just 1 Dataframe? </p>
-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>dataframes = [] for thread in soup.select(...): #your scraper logic here df = pandas.read_html(...) dataframes.append(df) pd.concat(dataframes) </code></pre> <p>Does that help?</p>
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>config.dataset</code> here? Should the folder structure look like <code>/data/config.dataset/*.jpg</code> The reason I need to understand this is because I need to create a data input folder to run the program. The original program does not share the detail on the data organization.</p>
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 commented, for that code to work, <code>config.dataset</code> must evaluate to a string, probably a single directory name. So the result of the <code>join</code> call will be something like <code>"./data/images/*.jpg"</code> (if <code>config.dataset</code> is <code>"images"</code>). The variable could also have a (pre-joined) path section including one or more slashes. For instance, if <code>config.dataset</code> was <code>"path/to/the/images"</code>, you'd end up with <code>"./data/path/to/the/images/*.jpg"</code>.</p>
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 sum of num1 and num2 def add(num1, num2): return num1 + num2 #Returns the result of subtracting num1 - num2 def sub(num1, num2): return num1 - num2 #Returns the result of multiplying num1 * num2 def mul(num1, num2): return num1 * num2 #Returns the result of dividing num1 / num2 def div(num1, num2): return num1 / num2 #Returns the result of dividing num1 / num2 def exp(num1, num2): return num1 ** num2 from math import * print("1: ADDITION") print("2: SUBTRACTION") print("3: MULTIPLICATION") print("4: DIVISION") print("5: Exponent") print("6: Square root") print("7: ") print("8:") print("9:") print("10:") def main(): operation = int(input("operation:")) if(operation == '1'): a = var1("input a:") b = var2("input b:") print(add(var1, var2)) elif(operation == '2'): a = var1("input a:") b = var2("input b:") print(sub(var1, var2)) elif(operation == '3'): a = var1("input a:") b = var2("input b:") print(div(var1, var2)) elif(operation == '4'): a = var1("input a:") b = var2("input b:") print(mul(var1, var2)) elif(operation == '5'): a = var1("input a:") b = var2("input b:") print(exp(var1, var2)) elif(operation == '6'): a = var1("input:") print(sqrt(var1,)) elif(operation == '7'): a = var1("input a:") b = var2("input b:") print(add(var1, var2)) else: main() main() </code></pre>
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.8 + 32 # convert C -&gt; F } for operation in iter(lambda: input('Operation: '), 'quit'): if operation not in operations: print('Sorry - not sure what {} is'.format(operation)) continue args = map(int, input('Enter values: ').split()) print('Result is', operations[operation](*args)) </code></pre>
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 matter how many buttons I put in there. If I put 3 buttons in there, as the example below has by default, the buttons are quite large and leave only room for about 1 more button. If I put 6 buttons in, they fill the space and each gets smaller.</p> <p>How do I achieve the expected result of having equal width columns no matter how many widgets I actually put in the cells? The goal here is a standard size to these buttons that is based on proportion of the screen, not a pixel size, and have it always be the same no matter the number of buttons. I realize I could do a bunch of math with bounding boxes and programatically set the sizes at runtime, but that seems like overkill and lacking elegance.</p> <p>Minimum example:</p> <pre><code>import Tkinter as tk import ttk mods = {} modBtns = {} root = tk.Tk() upper_frame = ttk.Frame(master=root) lower_frame = ttk.Frame(master=root) right_frame = ttk.Frame(master=root) root.columnconfigure(0, weight=3) root.columnconfigure(1, weight=1) root.rowconfigure(0, weight=1) root.rowconfigure(1, weight=5) for i in range(6): lower_frame.columnconfigure(i, weight=1) for i in range(5): lower_frame.rowconfigure(i, weight=1) upper_frame.grid(column=0, row=0, sticky=tk.N + tk.S + tk.E + tk.W) lower_frame.grid(column=0, row=1, sticky=tk.N + tk.S + tk.E + tk.W) right_frame.grid(column=1, row=0, sticky=tk.N + tk.S + tk.E + tk.W) for i in range(3): mods[i] = ttk.Frame(master=lower_frame) mods[i].columnconfigure(0, weight=1) mods[i].rowconfigure(0, weight=1) modBtns[i] = ttk.Button(master=mods[i], text="mod{0}".format(i)) modBtns[i].grid(column=0, row=0, sticky=tk.N + tk.S + tk.E + tk.W) mods[i].grid(column=i, row=0, sticky=tk.N + tk.S + tk.E + tk.W) root.geometry("700x700+0+0") root.mainloop() </code></pre>
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>Note: the actual value to the <code>uniform</code> attribute is irrelevant, as long as it is consistent.</p> <pre><code>for i in range(6): lower_frame.columnconfigure(i, weight=1, uniform='whatever') for i in range(5): lower_frame.rowconfigure(i, weight=1, uniform='whatever') </code></pre>
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.Label(window, text="placeholder", bg="blue", textvariable="labelText") lbl.grid(row=0, column=0, columnspan=3) self.firstNumArray = [] self.secondNumArray = [] self.operation = "" self.currentNum = "first" def appendNumber(self, number): print("Appending Number") if self.currentNum == "first": self.firstNumArray.append(number) print("".join(str(x) for x in self.firstNumArray)) lbl.config(text="".join(str(x) for x in self.firstNumArray)) window.update() else: self.secondNumArray.append(number) for i in range(1,4): string = "Creating button at ({0},{1})".format(0,i) print(string) button = tkinter.Button(text=i, command=lambda: appendNumber(self, i)) button.grid(row=1, column=i-1) for i in range(1,4): string = "Creating button at ({0},{1})".format(1,i) print(string) button = tkinter.Button(text=i+3, command=lambda: appendNumber(self, i+3)) button.grid(row=2, column=i-1) for i in range(1,4): string = "Creating button at ({0},{1})".format(2,i) print(string) button = tkinter.Button(text=i+6, command=lambda: appendNumber(self, i+6)) button.grid(row=3, column=i-1) div = tkinter.Button(text="/") mult = tkinter.Button(text="*") add = tkinter.Button(text="+") sub = tkinter.Button(text="-") add.grid(row=1, column=3) sub.grid(row=2, column=3) mult.grid(row=3, column=3) div.grid(row=4, column=3) button = tkinter.Button(text="0") button.grid(row=4, column=1) window.mainloop() calc = Calculator() </code></pre> <p>When I launch the program the window opens. When I click on a button the text in the label does not change. I have tried using a <code>StringVar</code> as the <code>textvariable</code> and then calling the <code>set()</code> function, but that did not work either. I think it has to do with the scope of the function. I had to place the <code>appendNumber()</code> function inside the <code>__init__()</code> because for some reason <code>self.lbl = tkinter.Label()</code> makes nothing pop up at all.</p>
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> <li><p>Now you can use <code>labelText.set</code> to update the text. Also, no need for <code>self</code> parameter or <code>window.update</code></p> <pre><code>def appendNumber(number): if self.currentNum == "first": self.firstNumArray.append(number) labelText.set("".join(str(x) for x in self.firstNumArray)) else: self.secondNumArray.append(number) </code></pre></li> <li><p>You can put all the buttons in one loop using <code>//</code> (<em>integer (!)</em> division) and <code>%</code> (modulo) operations. Also, be aware that the variable in the <code>lambda</code> is evaluated when the function is called, not when it is declared, i.e. all the <code>lambdas</code> will use the last value of <code>i</code> (<code>9</code> in this case) -- see e.g. <a href="http://stackoverflow.com/q/19837486/1639625">here</a>. As a remedy, use <code>lambda n=i+1: appendNumber(n)</code>.</p> <pre><code>for i in range(9): btn = tkinter.Button(text=i+1, command=lambda n=i+1: appendNumber(n)) btn.grid(row=i//3+1, column=i%3) </code></pre></li> <li><p>Not really a problem, but since you don't need a reference to those buttons, you can make your code a bit more compact (same for the others):</p> <pre><code>tkinter.Button(text="/").grid(row=1, column=3) </code></pre></li> </ol>
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/users</code> and set authentication only to <code>api/users/&lt;email&gt;</code></p>
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 import current_app def pre_GET_users(request, lookup): username = current_app.auth.get_request_auth_value() # only return user with current username lookup["username"] = username app = Eve() app.on_pre_GET_accounts += pre_GET_users app.run() </code></pre>
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.elementtree.html#supported-xpath-syntax" rel="nofollow">I can't just use</a> </p> <pre><code>root.findall('./[@attrib='value']') </code></pre> <p>I'd have to use</p> <pre><code>root.findall('./[@attrib='*value*']') </code></pre> <p><strong>QUESTION</strong></p> <ol> <li>Is this possible with <code>xml.etree</code>?</li> <li>How do you do this with <code>lxml</code>?</li> </ol>
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.etree.ElementTree.Element.attrib" rel="nofollow"><code>.attrib</code></a> to get to the <code>idList</code> value:</p> <pre><code>import xml.etree.ElementTree as ET data = """&lt;jobs&gt; &lt;waitingJobs idList="J03ac2db8 J03ac2fb0"/&gt; &lt;/jobs&gt; """ root = ET.fromstring(data) value = 'J03ac2db8' print([elm for elm in root.findall(".//waitingJobs[@idList]") if value in elm.attrib["idList"]]) </code></pre> <p>With <code>lxml.etree</code>, you can use <code>xpath()</code> method and <code>contains()</code> function:</p> <pre><code>import lxml.etree as ET data = """&lt;jobs&gt; &lt;waitingJobs idList="J03ac2db8 J03ac2fb0"/&gt; &lt;/jobs&gt; """ root = ET.fromstring(data) value = 'J03ac2db8' print(root.xpath(".//waitingJobs[contains(@idList, '%s')]" % value)) </code></pre>
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 -453.6102294922 780.6325683594 -628.981628418 </code></pre> <p>Here is my code:</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('gappy.xlsx', data_only = True) ws = wb.active factor = 1.0 for i in range (1,4): with open('text'+str(i)+'.txt', "wt") as file_id: for j in range (1,ws.max_row+1): file_id.write("{:.3e}\n".format(ws.cell(row = j,column = i).value/factor)) # I've also tried this, but I cannot write a file separately for each cloumn ... # for column in ws.columns: # for cell in column: # print(cell.value) # file_id.write('%f\n' % (ws.columns[i][0].value)) </code></pre> <p>Then, I got this error:</p> <blockquote> <p>TypeError: unsupported operand type(s) for /: 'NoneType' and 'float'</p> </blockquote> <p>The reason is that the blanks in the the 2nd column are read as 'None'. I know it's wrong to read the 2nd column up to 'max_row+1', but I don't know what else to do. Please tell me how to fix this. Thank you in advance.</p>
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 = j,column = i).value/factor)) else: # handle it in a different fashion </code></pre>
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 was using regular <code>open("..." , 'w')</code> to write to files in my co-routine and that this might be a blocking piece of code.</p> <p>So my question is, is there a way to do non-blocking file IO in Tornado? I couldn't find anything in my research that fit my needs.</p>
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 import Image class UploadHandler(web.RequestHandler): executor = ThreadPoolExecutor(max_workers=os.cpu_count()) @gen.coroutine def post(self): file = self.request.files['file'][0] try: thumbnail = yield self.make_thumbnail(file.body) except OSError: raise web.HTTPError(400, 'Cannot identify image file') orig_id, thumb_id = yield [ gridfs.put(file.body, content_type=file.content_type), gridfs.put(thumbnail, content_type='image/png')] yield db.imgs.save({'orig': orig_id, 'thumb': thumb_id}) self.redirect('') @run_on_executor def make_thumbnail(self, content): im = Image.open(io.BytesIO(content)) im.convert('RGB') im.thumbnail((128, 128), Image.ANTIALIAS) with io.BytesIO() as output: im.save(output, 'PNG') return output.getvalue() </code></pre>
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 can guarantee to stop a blocked thread.</p> <p>The problem now is, though that thread is stopped, it is NOT removed from <code>threading.enumerate()</code>. If I call <code>isAlive()</code> on its reference, it returns <code>False</code>. I tried if a thread's <code>run()</code> method returns normally, that thread should be removed from that list.</p> <p>This is bad, because if threading still has a reference to that <code>Thread</code> object, its resources will not be collected, theoretically, and may eventually cause memory leak.</p> <p>What should I do to make sure things are cleaned up after I do <code>_Thread__stop</code> on a thread?</p>
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) print("'stopping' thread") t._Thread__stop() sleep(2) print("huh! thread is still running") sleep(10) </code></pre> <p>And the output:</p> <pre><code>starting thread running 'stopping' thread running running huh! thread is still running running running running running running running running running running running </code></pre> <p><code>_Thread__stop</code> is useless for stopping the thread (there's nothing else in <code>threading</code> that can force a thread to stop either).</p> <p>What calling it <em>does</em> do is put <code>threading</code>'s internals into a confused state. In this case, because <code>._stop()</code> was called some other parts of <code>threading</code> erroneously <em>believe</em> the thread has stopped, so Python merrily exits after the final sleep despite that the non-daemon thread <code>t</code> is still running.</p> <p>But that's not a bug: you use private, undocumented methods (like <code>._stop()</code>) at your own risk.</p>
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", 'shell=True', "aplay"]) </code></pre> <p>then the audio is heard, but there are some problems with the speech being slow sometimes, together with output of messages below:</p> <pre><code>ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.front ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.surround40 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.surround41 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.surround50 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.surround51 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.surround71 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.iec958 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.iec958 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.iec958 ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only playback stream Cannot connect to server socket err = No such file or directory Cannot connect to server request channel jack server is not running or cannot be started </code></pre> <p>Can someone explain what --stdout means here? And why is it causing the error as mentioned? </p>
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 data. The length field is set to zero because the length of the data is unknown when the header is produced.</p> </blockquote> <p>For <code>jack server is not running or cannot be started</code> error check <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=28&amp;t=20923" rel="nofollow">this link</a> for solution:</p> <blockquote> <p>Do you have installed the alsa package (type 'alsa' and the tab key twice, you should see some commands beginning with alsa..)? If it isn't installed, do that with</p> <pre><code>sudo apt-get install alsa-tools alsa-utils </code></pre> </blockquote> <p>Anyway this error shouldn't prevent <code>espeak</code> from working. You can remove it by redirecting <code>stderr</code> to <code>/dev/null</code> as follows:</p> <pre><code>FNULL = open(os.devnull, 'w') retcode = subprocess.call(["espeak", "-s 5", "-ven", "where are you", "aplay"], stdout=FNULL, stderr=subprocess.STDOUT) </code></pre> <p>Also please note that you're using <code>shell=True</code> as one of the arguments to <code>espeak</code>, which should be actually argument of <code>call</code> method itself. Just remove it.</p>
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 recent call last): File "&lt;pyshell#74&gt;", line 1, in &lt;module&gt; w.s="sds" NameError: name 'w' is not defined </code></pre>
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, when you do it outside the function call it checks that there is no <code>w</code> in the scope and thus errors.</p> <p>Try this: </p> <pre><code>def f(): w.s = "one" w.s = "one" # called before there is such an object f() # called before w exists, it will error out class SomeClass(object): def __init__(self): self.s = "two" w = SomeClass() f() # since w exists it will run </code></pre>
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 recent call last): File "&lt;pyshell#74&gt;", line 1, in &lt;module&gt; w.s="sds" NameError: name 'w' is not defined </code></pre>
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 recent call last): File "&lt;pyshell#74&gt;", line 1, in &lt;module&gt; w.s="sds" NameError: name 'w' is not defined </code></pre>
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 object. Sure, there is <em>currently</em> no object in the global scope which is bound to that name, but that doesn't matter: Python assumes you know what you're doing, until proven otherwise :).</p> <p>We can use the <a href="https://docs.python.org/3/library/dis.html" rel="nofollow"><code>dis</code></a> module to disassemble the function's byte code. Here's a short demo.</p> <pre><code>from dis import dis def f(): w.s = "ads" dis(f) print('- ' * 30) class Test(object): pass try: f() except Exception as e: print(e) w = Test() f() print(w.__dict__) </code></pre> <p><strong>output</strong></p> <pre><code> 40 0 LOAD_CONST 1 ('ads') 3 LOAD_GLOBAL 0 (w) 6 STORE_ATTR 1 (s) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - name 'w' is not defined {'s': 'ads'} </code></pre> <p>FWIW, in Python 2 the byte code for <code>f</code> is identical, but the <code>NameException</code> error message is<br> <code>global name 'w' is not defined</code>.</p> <p>So if we try to call <code>f()</code> without a valid <code>w</code> in the global scope at the time of the call we will get an exception, but if there _is _ a valid <code>w</code> then everything's ok.</p> <p>Note that <code>w</code> <em>must</em> be in the global scope, a local <code>w</code> inside another function will not work. Eg:</p> <pre><code>def f(): w.s = "ads" class Test(object): pass def g(): w = Test() try: f() except Exception as e: print(e) print(w.__dict__) g() </code></pre> <p><strong>output</strong></p> <pre><code>name 'w' is not defined {} </code></pre>
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 current <code>title</code> node is the document's title, or is instead within one of several sections in the document: if it's actually the title of the overall document, I just want to skip this title and move on.</p> <p>I would have expected to be able to do this within <code>Visitor.visit_title</code>:</p> <pre class="lang-python prettyprint-override"><code>class DocumentTitleSkippingVisitor: # … def visit_title(self, node): document_node = section_node.parent if section_node is document_node: # This title is actually the document's top level title. raise self._docutils.nodes.SkipNode </code></pre> <p>That doesn't work, though: the visitor encounters the document's top level title inside another <code>section</code> node. Because of this, the above check (correctly) says the parent of the <code>title</code> is <em>not</em> the <code>document</code> node.</p> <p>How can I tell, within the <code>NodeVisitor</code>, that the <code>title</code> is actually the special document title? Alternatively, how can I hook into Docutils such that the <code>title</code> is actually at the document level, to more easily distinguish it from a <code>section</code> title?</p>
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 def visit_title(self, node): if self.in_section: pass # do something </code></pre> <p>For reStructuredText there is no way to specify a document title and subtitle explicitly. In this case:</p> <ul> <li>You can first apply <a href="https://sourceforge.net/p/docutils/code/HEAD/tree/tags/docutils-0.10/docutils/transforms/frontmatter.py#122" rel="nofollow">DocTitle</a></li> <li>You should follow the algorithm used by <a href="https://sourceforge.net/p/docutils/code/HEAD/tree/tags/docutils-0.10/docutils/transforms/frontmatter.py#122" rel="nofollow">DocTitle</a> to find it.</li> </ul>
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 TfidfVectorizer from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer wnlzer = WordNetLemmatizer() train = pd.read_csv("labeledTrainData.tsv" , header = 0 , \ delimiter = '\t' , quoting = 3) def raw_string_to_list_clean_string( raw_train_review ): remove_html = BeautifulSoup( raw_train_review ).text remove_punch = re.sub('[^A-Za-z ]' , "" , remove_html) token = remove_punch.lower().split() srm_token = [wnlzer.lemmatize(i) for i in token if not i in set(stopwords.words('english'))] clean_text = " ".join(srm_token) return(clean_text) ready_train_list = [] length = len(train['review']) for i in range(0 , length): if (i%100 == 0): print "doing %d of %d of training data set" % (i+1 , length) a = raw_string_to_list_clean_string(train['review'][i]) ready_train_list.append(a) vectorizer = TfidfVectorizer(analyzer = "word" , tokenizer = None , preprocessor = None , \ stop_words = None , max_features = 20000) training_our_vectorizer = vectorizer.fit_transform(ready_train_list)` </code></pre> <p>Now I know how to use cosine similarity but I am not able to figure out:</p> <ol> <li>how to make use of cosine </li> <li>how to restrict the recommendation to a max of 5 beers</li> </ol>
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', 'corona lager', 'heinekin ale', 'budweiser lager']) beerlist_tfidf = vec.fit_transform(beerlist).toarray() beer_tfidf = vec.transform(['heinekin lager']).toarray() rec_idx = cdist(beer_tfidf, beerlist_tfidf, 'cosine').argsort() print(beerlist[rec_idx[0][1:]]) #['heinekin ale' 'corona lager' 'budweiser lager'] </code></pre>
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 automate the basics. I did some research and most of the results were using node.js, which I do not know at all. I would like to use Python, so before moving on a whole different language, I would like to ask to a bigger audience, if there is something already to do Selenium testing with Python, on Electron apps</p> <p>In particular, how do you assign the variable that will contain the electron app? with the browser I would say </p> <pre><code>from selenium import webdriver driver = webdriver.Chrome('/chromedriver') </code></pre> <p>but this won't make sense for an electron app.</p>
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.WebDriver( command_executor='http://localhost:8765', desired_capabilities = {'chromeOptions':{ 'binary': '/myapp'}}, browser_profile=None, proxy=None, keep_alive=False) </code></pre> <p>Then you can access the DOM elements on the app as usual. Not sure if it will work on Windows, OSX and Linux, will have to try.</p>
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 #bring it in scope gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true def run(self): global gpsd while gpsp.running: gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer if __name__ == '__main__': gpsp = GpsPoller() # create the thread try: gpsp.start() # start it up while True: print gpsd.fix.speed time.sleep(1) ## &lt;&lt;&lt;&lt; THIS LINE HERE except (KeyboardInterrupt, SystemExit): #when you press ctrl+c print "\nKilling Thread..." gpsp.running = False gpsp.join() # wait for the thread to finish what it's doing print "Done.\nExiting." </code></pre> <p>I'm not very good with python, unfortunately. The script should be multi-threaded somehow (but that probably doesn't matter in the scope of this question).</p> <p>What baffles me is the <code>gpsd.next()</code> line. If I get it right, it was supposed to tell the script that new gps data have been acquired and are ready to be read.</p> <p>However, I read the data using the infinite <code>while True</code> loop with a 1 second pause with <code>time.sleep(1)</code>.</p> <p>What this does, however, is that it sometimes echoes the same data twice (the sensor hasn't updated the data in the last second). I figure it also skips some sensor data somehow too.</p> <p>Can I somehow change the script to print the current speed not every second, but every time the sensor reports new data? According to the data sheet it should be every second (a 1 Hz sensor), but obviously it isn't exactly 1 second, but varies by milliseconds.</p>
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.running: prev_speed = gpsd.fix.speed gpsd.next() if prev_speed != gpsd.fix.speed is_speed_changed = True # raising flag while True: if is_speed_changed: print gpsd.fix.speed is_speed_changed = False </code></pre> <p>Option #2 ( I prefer this one since it protects us from raise conditions):</p> <pre><code>gpsd_queue = Queue.Queue() def run(self): global gpsd while gpsp.running: prev_speed = gpsd.fix.speed gpsd.next() curr_speed = gpsd.fix.speed if prev_speed != curr_speed: gpsd_queue.put(curr_speed) # putting new speed to queue while True: # get will block if queue is empty print gpsd_queue.get() </code></pre>
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 #bring it in scope gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.current_value = None self.running = True #setting the thread running to true def run(self): global gpsd while gpsp.running: gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer if __name__ == '__main__': gpsp = GpsPoller() # create the thread try: gpsp.start() # start it up while True: print gpsd.fix.speed time.sleep(1) ## &lt;&lt;&lt;&lt; THIS LINE HERE except (KeyboardInterrupt, SystemExit): #when you press ctrl+c print "\nKilling Thread..." gpsp.running = False gpsp.join() # wait for the thread to finish what it's doing print "Done.\nExiting." </code></pre> <p>I'm not very good with python, unfortunately. The script should be multi-threaded somehow (but that probably doesn't matter in the scope of this question).</p> <p>What baffles me is the <code>gpsd.next()</code> line. If I get it right, it was supposed to tell the script that new gps data have been acquired and are ready to be read.</p> <p>However, I read the data using the infinite <code>while True</code> loop with a 1 second pause with <code>time.sleep(1)</code>.</p> <p>What this does, however, is that it sometimes echoes the same data twice (the sensor hasn't updated the data in the last second). I figure it also skips some sensor data somehow too.</p> <p>Can I somehow change the script to print the current speed not every second, but every time the sensor reports new data? According to the data sheet it should be every second (a 1 Hz sensor), but obviously it isn't exactly 1 second, but varies by milliseconds.</p>
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</code> and one extra thread. Each input thread should put its "events" on the (same) queue. The extra thread loops over <code>queue.get()</code> and reacts appropriately.</p> <p>From this point of view, your script need not be multithreaded, since there is only one input channel, namely the <code>gpsd.next()</code> loop.</p> <p>Example code:</p> <pre><code>from gps import * class GpsPoller(object): def __init__(self, action): self.gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info self.action=action def run(self): while True: self.gpsd.next() self.action(self.gpsd) def myaction(gpsd): print gpsd.fix.speed if __name__ == '__main__': gpsp = GpsPoller(myaction) gpsp.run() # runs until killed by Ctrl-C </code></pre> <p>Note how the use of the <code>action</code> callback separates the plumbing from the data evaluation.</p> <p>To embed the poller into a script doing other stuff (i.e. handling other threads as well), use the queue approach. Example code, building on the <code>GpsPoller</code> class:</p> <pre><code>from threading import Thread from Queue import Queue class GpsThread(object): def __init__(self, valuefunc, queue): self.valuefunc = valuefunc self.queue = queue self.poller = GpsPoller(self.on_value) def start(self): self.t = Thread(target=self.poller.run) self.t.daemon = True # kill thread when main thread exits self.t.start() def on_value(self, gpsd): # note that we extract the value right here. # Otherwise it could change while the event is in the queue. self.queue.put(('gps', self.valuefunc(gpsd))) def main(): q = Queue() gt = GpsThread( valuefunc=lambda gpsd: gpsd.fix.speed, queue = q ) print 'press Ctrl-C to stop.' gt.start() while True: # blocks while q is empty. source, data = q.get() if source == 'gps': print data </code></pre> <p>The "action" we give to the GpsPoller says "calculate a value by valuefunc and put it in the queue". The mainloop sits there until a value pops out, then prints it and continues.</p> <p>It is also straightforward to put other Thread's events on the queue and add the appropriate handling code.</p>
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 following message</p> <pre class="lang-none prettyprint-override"><code>/Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 1: __author__: command not found /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 3: import: command not found /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 4: import: command not found /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 5: import: command not found /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 6: import: command not found /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 7: import: command not found /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 8: import: command not found from: can't read /var/mail/lxml from: can't read /var/mail/selenium from: can't read /var/mail/requests.adapters /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 15: syntax error near unexpected token `(' /Users/xxx/Downloads/moneyonbots-master/shopify3/shopify3.py: line 15: modes = [('Gift Card', 1), ('Credit Card', 2), ('Paypal', 3)]' </code></pre> <p>In the beginning of the script it says...</p> <pre><code>import requests import sys, traceback import re import arrow import time import Tkinter as tk from lxml import html from selenium import webdriver from requests.adapters import HTTPAdapter </code></pre> <p>Do I need to install other libraries to run the script? What are the commands to install these? I am using mac OSX. Thank you.</p> <p>ENTIRE SCRIPT: <a href="https://github.com/Sdocquir/moneyonbots" rel="nofollow">https://github.com/Sdocquir/moneyonbots</a></p>
-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 that it should be run with a Python interpreter.</p> <hr> <p>You may indeed need to install some 3rd-party packages, but you'll get an error specific to the imports that fail after fixing your interpreter; at that point you can use either the same package manager you used to install Python 3 (if it was installed via MacPorts or Homebrew or similar), or use PyPi, virtualenv, or similar.</p>
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(forms.Form): name = forms.CharField() subject = forms.CharField() text = forms.CharField(widget=forms.Textarea) file = forms.FileField() password = forms.CharField() def mainpage(request): if request.method == 'POST': form = MainForm(request.FILES or None, request.POST or None) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponse('Ok') else: form = MainForm() return render(request, "main.html", {'form': form}) def handle_uploaded_file(file): name = file.name with open(os.path.join("static\img", "{0}".format(name)), 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) </code></pre> <p><strong>Template:</strong></p> <pre><code>{% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;{{ siteTitle }}&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css"&gt; &lt;/head&gt; &lt;body&gt; {% include 'header.html' %} &lt;form enctype="multipart/form-data" method="post"&gt; {% csrf_token %} &lt;table&gt; &lt;ul&gt; {{ form.as_table }} &lt;/ul&gt; &lt;/table&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It should be noted that when I set everything to non-required, it just returns an empty form.</p> <p>Thanks for your generous help.</p>
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 present in the <a href="https://docs.djangoproject.com/en/stable/ref/request-response/#httprequest-objects" rel="nofollow">request object</a>, even if they are empty.</p> <p>You probably also don't want those <code>ul</code> tags in the table:</p> <pre><code>&lt;table&gt; {{ form.as_table }} &lt;/table&gt; </code></pre>
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>.</p> <p>I have done the following so far:</p> <p>urls.py:</p> <pre><code>from django.conf.urls import url,include from django.contrib import admin from . import views urlpatterns = [ url(r'^api/line/$',views.LineDisplay.as_view()), ] </code></pre> <p>view.py:</p> <pre><code>class LineDisplay(APIView): """ Display the most recent line """ def get(self, request, format=None): lines = Line.objects.all() serializer = LineSerializer(lines, many=True) return Response(serializer.data) def post(self, request, format=None): lines = Line.objects.all() for line in lines: line.delete(); serializer = LineSerializer(data=request.data) if serializer.is_valid(): serializer.save() info = "" info += "Line Coordinates are: " lines = Line.objects.all() for line in lines: info += "x1:" + str(line.x1) info += " y1:" + str(line.y1) info += " x2:" + str(line.x2) info += " y2:" + str(line.y2) print info Channel('repeat-me').send({'info': info, 'status': True}) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>consumers.py</p> <pre><code>import json # In consumers.py from channels import Group # Connected to websocket.connect def ws_add(message): Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_message(message): print "Receive Message now" Group("chat").send({ "text": json.dumps({'status': False}) }) # Connected to websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.reply_channel) def repeat_me(message): Group("chat").send({ "text": json.dumps({'status': message.content['status'], 'info': message.content['info']}) }) </code></pre> <p>Similarly, I have added added the following code to : routing.py</p> <pre><code>from channels.routing import route from .consumers import ws_add, ws_message, ws_disconnect, repeat_me channel_routing = [ route("websocket.connect", ws_add), route("websocket.receive", ws_message), route("websocket.disconnect", ws_disconnect), route("repeat-me", repeat_me), ] </code></pre> <p>The following lines have been added to settings.py:</p> <pre><code>CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "TrainingInduct.routing.channel_routing", }, } </code></pre> <p>Currently, I don't know how to deal with the group "chat". I don't even need a group. What are the remaining things to be done in order to get the line coordinates to be displayed at <em>127.0.0.1:8000/dashboard/</em> as soon as a new line is posted?</p> <p>Note: The Line coordinates are getting properly POSTED to <em>/api/line/</em> I think I might have to write a server code in order to get the data from the channel and push it back, am I right? Thanks.</p>
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 opens your <code>/dashboard/</code> page will receive any new "info" item that is posted. First, you need to remember the new client's Channel. That's what your <code>ws_add</code> is for</p> <pre><code>def ws_add(message): Group("all-my-clients").add(message.reply_channel) </code></pre> <p>Now the client who just connected is part of the <code>all-my-clients</code> Group, and whatever message you send via <code>all-my-clients</code>, will be send automatically to that client as well.</p> <p>Of course you want to clean up after yourself, so that's what <code>ws_disconnect</code> is for. Remove the client once they do a WebSocket.close() or they close their browser, etc.</p> <pre><code>def ws_disconnect(message): Group("all-my-clients").discard(message.reply_channel) </code></pre> <p>And finally, there is your <code>ws_message()</code>. It receives any incoming messages. </p> <pre><code>def ws_message(message): # Nothing to do here, because you only push, never receive. pass </code></pre> <p>That's all. Now you can just send messages to the Group you defined above from anywhere in Django. Just make sure you send the response in the correct format. <code>Group().send()</code> takes a <code>dict</code> with a key <code>text</code> that has a string value (see below). The reason is that you could also send other data types, like blobs. But "text" is best for this purpose.</p> <pre><code>def post(self, request, format=None): lines = Line.objects.all() ... print info response_data = {'info': info, 'status': True} Group("all-my-clients").send({ 'text': json.dumps(response_data) }) return Response(serializer.data, status=status.HTTP_201_CREATED) </code></pre> <p>That should be all.</p>
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)</em></strong> or <strong><em>O(n^2)</em></strong>.<br> For example:</p> <pre><code>result = [x for x in func()] </code></pre> <p>Does python call the function <strong><em>func</em></strong> each iteration?</p> <p>This might be a duplicate, I just couldn't find it anywhere.</p>
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 and cookie ( so I don't need to login again)</li> <li>Scrape friend list from 5 different UID simultaneously. 1 instance/1 UID</li> </ol> <p>This is my code but it doesn't work</p> <pre><code>import multiprocessing from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from selenium import webdriver def friend_uid_list(uid, driver): driver.get('https://www.facebook.com/' + uid + '/friends') //scrape friend list target.close() def g(arg): return friend_uid_list(*arg) if __name__ == '__main__': driver = webdriver.Firefox() driver.get("https://www.facebook.com/") driver.find_element_by_css_selector("#email").send_keys("email@gmail.com") driver.find_element_by_css_selector("#pass").send_keys("password") driver.find_element_by_css_selector("#u_0_m").click() pool = multiprocessing.Pool(5) pool.map(g, [(100004159542140,driver),(100004159542140,driver),(100004159542140,driver)]) </code></pre> <p>So, can you show me how to use Selenium Grid to use multiple instances simultaneously ? I searched a lot but don't know how to implement it to my code. Thank you :)</p>
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 import Keys import multiprocessing display = Display(visible=0, size=(800, 600)) display.start() d = webdriver.Firefox() def friend_uid_list(uid, driver): values = [] for handle in driver.window_handles: driver.switch_to_window(handle) # driver.wait_for_element() etc etc values.append(driver.find_element_by_id('#something')) # scrape elements return values def g(arg): return friend_uid_list(*arg) </code></pre> <p>Start an instance and log in:</p> <pre><code>d = webdriver.Firefox() d.get("https://www.facebook.com/") d.find_element_by_css_selector("#email").send_keys("email@gmail.com") d.find_element_by_css_selector("#pass").send_keys("password") d.find_element_by_css_selector("#loginbutton").click() </code></pre> <p>Start multiple instances:</p> <pre><code>drivers = [webdriver.Firefox(), webdriver.Firefox(), webdriver.Firefox(), webdriver.Firefox()] </code></pre> <p>Copy the <code>localStorage</code>:</p> <pre><code>localstorage_kv = d.execute_script("var obj={};for (var i=0,len=localStorage.length;i&lt;len;++i){obj[localStorage.key(i)]=localStorage.getItem(localStorage.key(i));};return obj") </code></pre> <p>Copy the cookies and <code>localStorage</code>:</p> <pre><code>for e in drivers: e.get("https://www.facebook.com/") for x in d.get_cookies(): e.add_cookie(x) for k, v in localstorage_kv.items(): e.execute_script('localStorage.setItem("{}", {})'.format(k,v)) e.refresh() # should be logged in now </code></pre> <p>Add the initial driver back into the drivers array:</p> <pre><code>drivers.append(d) </code></pre> <p>And then loop over the uids:</p> <pre><code>uids = [100004159542140, 100004159542140, 100004159542140, 100004159542140, 100004159542140, 100004159542140] pool = multiprocessing.Pool(5) while uids: for driver in drivers: if len(driver.window_handles) == 1: driver.execute_script('window.open("https://www.facebook.com/' + uids.pop() + '/friends")') driver.execute_script('window.open("https://www.facebook.com/' + uids.pop() + '/friends")') else: for handle in driver.window_handles: handle.get("https://www.facebook.com/" + uids.pop() + "/friends") return_values = pool.map(g, drivers) import pdb;pdb.set_trace() </code></pre> <p>If you really want to share the cookies across nodes on a selenium grid look:</p> <ul> <li><a href="http://stackoverflow.com/questions/16205299/create-and-upload-a-file-on-selenium-grid">Create and upload a file on selenium grid</a></li> <li><a href="http://stackoverflow.com/questions/15058462/how-to-save-and-load-cookies-using-python-selenium-webdriver">How to save and load cookies using python selenium webdriver</a></li> <li><a href="http://selenium-python.readthedocs.io/getting-started.html#selenium-remote-webdriver" rel="nofollow">http://selenium-python.readthedocs.io/getting-started.html#selenium-remote-webdriver</a></li> </ul> <p>Which roughly means pickle the <code>localStorage</code> and <code>cookies</code> and transfer that to each node, from there then read the cookie into each instance on each node.</p>
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&gt; AllowOverride None Options +FollowSymLinks Order allow,deny Allow from all Require all granted &lt;/Directory&gt; &lt;Directory /home/aut/sampleapp/sampleapp&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; </code></pre> <p>The above is the configuration for virtual host port 80. After restarting Apache, I got no errors, but when I go to test.test.nz, I get: </p> <blockquote> <p>The requested URL / was not found on this server.</p> </blockquote> <p>"/home/aut/sampleapp/" is where manage.py is, within that directory, there is another folder called "sampleapp" which contains the urls.py, wsgi.py etc..</p> <p>The urls.py has been edited to set the app as the index page:</p> <pre><code>from django.conf.urls import url from django.contrib import admin from django.contrib.sitemaps import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), ] </code></pre> <p>What seems to be the problem?</p> <p>Any help or direction would be appreciated.</p> <p>Thanks in advance,</p>
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], ... [9, 29]]) </code></pre> <p>How can I do this with x, and y arrays given above?</p>
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], [ 6, 26], [ 7, 27], [ 8, 28]]) </code></pre>
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], ... [9, 29]]) </code></pre> <p>How can I do this with x, and y arrays given above?</p>
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 2010-04-10 12:29:02 </code></pre> <p>Now I want to apply some agg function (here i want to groupby mailid and take min() of Date to find that mailid's date of first transaction).</p> <pre><code>df['DATE'] = [x.date() for x in df['DATE']] #Here the value goes to CUSTOMER_name DATE abc 0001-255-255 ####how?? def 0001-255-255 ###How?? abc 2010-04-15 def 2011-01-25 abc 2010-04-10 #Then when i do a groupby and applying min on DATE df.groupby('CUSTOMER_name')['DATE'].min() #CUSTOMER_name DATE abc 0001-255-255 ####i want 2010-04-10 def 0001-255-255 ### i want 2011-01-25 </code></pre> <p>SO can anyone please suggest , how to deal with this NaT while converting to date() and while doing groupby and min(), how to exclude NaT for calculation. </p> <h2>if for any customer_name only NaT will be there in DATE field, then on groupby and min(), i am okay with nan or Null values.</h2>
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 only difference is adding <code>fff</code> mapped to <code>NaT</code>).</p> <p>Then the following does what you ask:</p> <pre><code>&gt;&gt;&gt; pd.to_datetime(df.DATE.groupby(df.CUSTOMER_name).min()) CUSTOMER_name abc 2010-04-10 12:29:02 def 2011-01-25 15:29:37 fff NaT Name: DATE, dtype: datetime64[ns] </code></pre> <p>This is because <code>groupby</code>-<code>min</code> already excludes missing data where applicable (albeit changing the format of the results), and the final <code>pd.to_datetime</code> coerces the result again to a <code>datetime</code>.</p> <hr> <p>To get the date part of the result (which I think is a separate question), use <code>.dt.date</code>:</p> <pre><code>&gt;&gt;&gt; pd.to_datetime(df.DATE.groupby(df.CUSTOMER_name).min()).dt.date Out[19]: CUSTOMER_name abc 2010-04-10 def 2011-01-25 fff NaN Name: DATE, dtype: object </code></pre>
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 2010-04-10 12:29:02 </code></pre> <p>Now I want to apply some agg function (here i want to groupby mailid and take min() of Date to find that mailid's date of first transaction).</p> <pre><code>df['DATE'] = [x.date() for x in df['DATE']] #Here the value goes to CUSTOMER_name DATE abc 0001-255-255 ####how?? def 0001-255-255 ###How?? abc 2010-04-15 def 2011-01-25 abc 2010-04-10 #Then when i do a groupby and applying min on DATE df.groupby('CUSTOMER_name')['DATE'].min() #CUSTOMER_name DATE abc 0001-255-255 ####i want 2010-04-10 def 0001-255-255 ### i want 2011-01-25 </code></pre> <p>SO can anyone please suggest , how to deal with this NaT while converting to date() and while doing groupby and min(), how to exclude NaT for calculation. </p> <h2>if for any customer_name only NaT will be there in DATE field, then on groupby and min(), i am okay with nan or Null values.</h2>
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:29:02 5 fff sa </code></pre> <p><strong>Solution:</strong></p> <pre><code>In [100]: (x.assign(D=pd.to_datetime(x.DATE, errors='coerce').values.astype('&lt;M8[D]')) .....: .groupby('CUSTOMER_name')['D'] .....: .min() .....: .astype('datetime64[ns]') .....: ) Out[100]: CUSTOMER_name abc 2010-04-10 def 2011-01-25 fff NaT Name: D, dtype: datetime64[ns] </code></pre> <p><strong>Explanation:</strong></p> <p>first, let's create a new virtual column <code>D</code> with truncated time part:</p> <pre><code>In [97]: x.assign(D=pd.to_datetime(x.DATE, errors='coerce').values.astype('&lt;M8[D]')) Out[97]: CUSTOMER_name DATE D 0 abc T NaT 1 def N NaT 2 abc 2010-04-15 19:09:08 2010-04-15 3 def 2011-01-25 15:29:37 2011-01-25 4 abc 2010-04-10 12:29:02 2010-04-10 5 fff sa NaT </code></pre> <p>now we can group by <code>CUSTOMER_name</code> and calclulate minimum <code>D</code> for each group:</p> <pre><code>In [101]: x.assign(D=pd.to_datetime(x.DATE, errors='coerce').values.astype('&lt;M8[D]')).groupby('CUSTOMER_name')['D'].min() Out[101]: CUSTOMER_name abc 1.270858e+18 def 1.295914e+18 fff NaN Name: D, dtype: float64 </code></pre> <p>and finally convert resulting column to <code>datetime64[ns]</code> dtype:</p> <pre><code>In [102]: (x.assign(D=pd.to_datetime(x.DATE, errors='coerce').values.astype('&lt;M8[D]')) .....: .groupby('CUSTOMER_name')['D'] .....: .min() .....: .astype('datetime64[ns]') .....: ) Out[102]: CUSTOMER_name abc 2010-04-10 def 2011-01-25 fff NaT Name: D, dtype: datetime64[ns] </code></pre>
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 sanitize the input</p> </blockquote> <p>But I wonder how is it possible for an attacker to execute arbitrary code via JSON messages?</p> <p>Also, what is the best way to sanitize the input as suggested in the documentation? JSON data in my application is not trust-worthy (it came from the clients that send JSON messages).</p>
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 to trigger unwanted behavior.</p> <p>The <code>__reduce__</code> exploit (see, for example <a href="http://versprite.com/og/into-the-jar-jsonpickle-exploitation/" rel="nofollow" title="Into The Jar | Exploitation of jsonpickle">Into The Jar | Exploitation of jsonpickle</a>)</p> <pre><code>jsonpickle.decode('{"py/object": "list", "py/reduce":[{"py/type": "subprocess.Popen"}, ["ls"], null, null, null]}') </code></pre> <p>is only one direct way to execute any command. More subtle ways depend on your actual code.</p> <p>So the short answer is, not to use <code>jsonpickle</code> in an untrusted environment. Use normal JSON and check the input before using it.</p>
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 exactly like the terminal appears to us at the end of execution of a python script using only shell commands?</p>
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> interactive session as proof of an assignment, as the typescript file can be printed out later with lpr(1).</p> <p>If the argument file is given, script saves the dialogue in this<br> file. If no filename is given, the dialogue is saved in the file<br> typescript.</p> </blockquote>
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 exactly like the terminal appears to us at the end of execution of a python script using only shell commands?</p>
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><code>i value label 0 0.2 A 1 0.3 A 2 0.1 A 3 0.45 A 4 0.5 B 5 0.8 B 6 0.15 B 7 0.55 B </code></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="nofollow">python-daemon</a> and still haven't found out how to do it. In particular, I know how to make a daemon run and periodically do some stuff itself, but I don't know how to make it callable from another program. Could you please give some help?</p>
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 (several probably equivalent wrapper libraries).</p> <p>The main advantage is that when the service goes down, a copy of the data still remains on disk. Also, I noticed that once in place, it could be used for other things in my app (for instance Celery proposes it as backend), and actually, for other services in any other unrelated program.</p>
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 * class Test(models.Model): name = models.CharField(max_length=200) </code></pre> # <p>In my settings.py:</p> <pre><code>INSTALLED_APPS = [ 'dal', 'dal_select2', 'dal_queryset_sequence', 'django.contrib.admin' ...] </code></pre> <p>But the system throws out </p> <blockquote> <p>AttributeError: module 'dal_select2.models' has no attribute 'Model'.</p> </blockquote> <p>How to solve this issue?</p> <p>tried to add "from dal_select2.models import Model or *", but not working.</p>
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 happen.</p>
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 have a Jquery code which looks something like this:</p> <pre><code>$(document).on('change', '#my_table tr input[type = text], input[type = number]', function(){ // currently the following code handles save event // $.post ('/save_my_form/', $form.serialize()) }); </code></pre> <p>And the corresponding Django view</p> <pre><code>def save_my_form(request): # ....... for form in order_draft_formset: if form.is_valid(): form.save() # ....... </code></pre> <p>The problem with this approach is that I modify only one single input element in one single form, whereas the Django view loops through entire formset. The question is, is there any built-in Django way to fetch the form within which the modified input is localized, so that I save only this exact form in my view without going through the entire formset. I feel that Jquery must somehow submit some info via post-request parameters that would help Django do that. As for now, I am thinking of parsing the automatically Django-generated id, f.e, id_form-5-my_field, and getting "5" out of it in Jquery and passing this "5" to Django. But I have a terrible feeling that this is a "dirty" method, and there must be a cleaner way to do that. Any ideas on this ?</p>
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 1790.50 1794.00 2014-03-06 1798.00 1802.25 1795.00 1797.75 2014-03-07 1804.75 1805.50 1790.50 1798.75 </code></pre> <p>Its easy enough for me to do a similar function when capturing something like the range between <code>High</code> and <code>Low</code> with:</p> <pre><code>def daily_range(df): return df['High'] - df['Low'] </code></pre> <p>But how do we do a similar function the with <code>Open</code> and <code>Last</code>?</p> <p>I will use <code>apply</code> on this function to get a new column in my dataframe and desired output is shown below:</p> <pre><code> Open High Low Last Desired output Timestamp 2014-03-04 1783.50 1796.00 1783.50 1793.25 9.75 2014-03-05 1793.25 1796.50 1790.50 1794.00 0.75 2014-03-06 1798.00 1802.25 1795.00 1797.75 -0.25 </code></pre> <p>Basically if <code>Open</code> is higher than <code>Last</code> I need to do <code>Open</code> - <code>Last</code> and if <code>Last</code> is higher than <code>Open</code> I need to do <code>Last</code> - <code>Open</code>. I could do this with an <code>if</code> in the function but there must be a better way to do this simple task and I would like to find this.</p> <p>Update:</p> <p>Sorry if my question was not correctly worded. I did however show desired output with negative values desired output (see above). </p> <p>On 2014-03-06 below the move was -0.25 but the code given in the answer shows 0.25 not -0.25. Can you help with this?</p> <pre><code> Open Last desired Timestamp 2014-03-04 1783.50 1793.25 9.75 2014-03-05 1793.25 1794.00 0.75 2014-03-06 1798.00 1797.75 0.25 </code></pre>
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>df['Last'] - df['Open']</code>, without the absolute value.</p>
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' as I did to inherit from 'Hand'.</p> <p>Could someone please explain?</p> <p>This first class is located in 'cardsmodule':</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: rep = "&lt;empty&gt;" return rep </code></pre> <pre><code>class BJ_hand(cardsmodule.Hand): """A BlackJack hand""" def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_hand,self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): super(BJ_player, self).__init__() #self.name = name self.number_chips = number_chips def __str__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__() </code></pre>
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: rep = "&lt;empty&gt;" return rep class BJ_hand(Hand): """A BlackJack hand""" def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_hand,self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): super(BJ_player, self).__init__('aName') self.number_chips = number_chips def __str__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__() b = BJ_player (3) </code></pre>
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' as I did to inherit from 'Hand'.</p> <p>Could someone please explain?</p> <p>This first class is located in 'cardsmodule':</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: rep = "&lt;empty&gt;" return rep </code></pre> <pre><code>class BJ_hand(cardsmodule.Hand): """A BlackJack hand""" def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_hand,self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): super(BJ_player, self).__init__() #self.name = name self.number_chips = number_chips def __str__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__() </code></pre>
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>, but you are trying to pass that in:</p> <pre><code>player = BJ_player(name, number_chips) # ^^^^ ^^^^^^^^^^^^ </code></pre> <p>Python doesn't look to all base <code>__init__</code> methods for you; it'll only 'see' <code>BJ_player</code>. If you wanted to pass in a <code>name</code> value for <code>BJ_hand.__init__</code>, then <code>BJ_player.__init__()</code> <em>must</em> accept that as an argument. You can then pass it on via the <code>super().__init__()</code> call:</p> <pre><code>class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, name, number_chips): super(BJ_player, self).__init__(name) </code></pre> <p>Note how the <code>name</code> parameter from the method is now passed on in the chain.</p>
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' as I did to inherit from 'Hand'.</p> <p>Could someone please explain?</p> <p>This first class is located in 'cardsmodule':</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: rep = "&lt;empty&gt;" return rep </code></pre> <pre><code>class BJ_hand(cardsmodule.Hand): """A BlackJack hand""" def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_hand,self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): super(BJ_player, self).__init__() #self.name = name self.number_chips = number_chips def __str__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__() </code></pre>
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__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__(self.name) </code></pre> <p>Tried this and it works</p>
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' as I did to inherit from 'Hand'.</p> <p>Could someone please explain?</p> <p>This first class is located in 'cardsmodule':</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: rep = "&lt;empty&gt;" return rep </code></pre> <pre><code>class BJ_hand(cardsmodule.Hand): """A BlackJack hand""" def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_hand,self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep class BJ_player(BJ_hand): """A BlackJack player""" def __init__(self, number_chips): super(BJ_player, self).__init__() #self.name = name self.number_chips = number_chips def __str__(self): rep = self.name + " has " + str(self.number_chips) + " chips.\n" rep += super(BJ_player, self).__init__() </code></pre>
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 classes.</p> <p>Specifically, the relationship between a player and the cards in their hand is not well represented by inheritance. Inheritance is often described as an "IS-A" relationship. For example, it would make sense to define a <code>Dog</code> class that inherits from an <code>Animal</code> parent class, since every Dog <em>is</em> an Animal.</p> <p>This isn't the case with players and hands. A blackjack player <em>is not</em> a certain kind of hand of cards. Each player <em>has a</em> hand of cards. A "HAS-A" relationship between objects is best implemented with composition. That is, a <code>BJ_player</code> instance should have a <code>Hand</code> instance as an instance variable. This might free up your design in other ways. For instance, when it's not busy in a casino, one player can play several hands at once at the same table. That would be impossible to represent with inheritance, but it would be fairly easy to change the single <code>Hand</code> instance being saved in an instance variable on the <code>Player</code> instance to a list of one-or-more <code>Hand</code> instances.</p> <p>I'd also suggest that the <code>name</code> attribute you're storing on <code>BJ_hand</code> is really more appropriate as an attribute on the player. It might still make sense to have a <code>BJ_hand</code> class, which could deal with things like counting the value of the cards dealt (and if you've busted yet or not), but you may need to think a bit on which attributes make sense to store on the hand and which are more appropriate elsewhere.</p>
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, default=None, on_delete=models.SET_DEFAULT) class UserNotification(models.Model): shown = models.BooleanField(default=False) def __setattr__(self, key, value): super(UserNotification, self).__setattr__(key, value) print("SET ATTR", key, value) </code></pre> <p>I have this <a href="https://docs.djangoproject.com/en/1.9/ref/templates/api/#writing-your-own-context-processors" rel="nofollow">context-processor</a> function:</p> <pre><code>def process_notifications(request): if request.user.is_authenticated(): profile = UserProfile.objects.get(...) notif = profile.last_notif </code></pre> <p>When the last line in process_notifications is called, my overwritten <strong>setattr</strong> method in UserNotification is called for all fields in UserNotification class. That is not supposed to happen? Am I right? Any idea why that happens?</p> <p>I am sure that <strong>setattr</strong> is called there.</p>
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, approximating my signal next to it which should illustrate, that I use the FFT function correctly: </p> <pre><code>import numpy as np from matplotlib import pyplot as plt signal = array([[ 0.], [ 0.1667557 ], [ 0.31103874], [ 0.44339886], [ 0.50747922], [ 0.47848347], [ 0.64544846], [ 0.67861755], [ 0.69268326], [ 0.71581176], [ 0.726552 ], [ 0.75032795], [ 0.77133769], [ 0.77379966], [ 0.80519187], [ 0.78756476], [ 0.84179849], [ 0.85406538], [ 0.82852684], [ 0.87172407], [ 0.9055542 ], [ 0.90563205], [ 0.92073452], [ 0.91178145], [ 0.8795554 ], [ 0.89155587], [ 0.87965686], [ 0.91819571], [ 0.95774404], [ 0.95432073], [ 0.96326252], [ 0.99480947], [ 0.94754962], [ 0.9818627 ], [ 0.9804966 ], [ 1.], [ 0.99919711], [ 0.97202208], [ 0.99065786], [ 0.90567128], [ 0.94300558], [ 0.89839004], [ 0.87312245], [ 0.86288378], [ 0.87301008], [ 0.78184963], [ 0.73774451], [ 0.7450479 ], [ 0.67291666], [ 0.63518575], [ 0.57036157], [ 0.5709147 ], [ 0.63079811], [ 0.61821523], [ 0.49526048], [ 0.4434457 ], [ 0.29746173], [ 0.13024641], [ 0.17631683], [ 0.08590552]]) sinus = np.sin(np.linspace(0, np.pi, 60)) plt.plot(signal) plt.plot(sinus) </code></pre> <p>The blue line is my signal, the green line is the sinus.</p> <p><a href="http://i.stack.imgur.com/BiHQu.png" rel="nofollow"><img src="http://i.stack.imgur.com/BiHQu.png" alt="raw.pdf"></a></p> <pre><code>transformed_signal = abs(np.fft.fft(signal)[:30] / len(signal)) transformed_sinus = abs(np.fft.fft(sinus)[:30] / len(sinus)) plt.plot(transformed_signal) plt.plot(transformed_sinus) </code></pre> <p>The blue line is <code>transformed_signal</code>, the green line is the <code>transformed_sinus</code>.</p> <p><a href="http://i.stack.imgur.com/TF4LE.png" rel="nofollow"><img src="http://i.stack.imgur.com/TF4LE.png" alt="fft.pdf"></a></p> <p>Plotting only <code>transformed_signal</code> illustrates the behavior described above:</p> <p><a href="http://i.stack.imgur.com/CzhWQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/CzhWQ.png" alt="enter image description here"></a></p> <p>Can someone explain to me what's going on here?</p> <p><strong>UPDATE</strong></p> <p>I was indeed a problem of calling the FFT. This is the correct call and the correct result:</p> <pre><code>transformed_signal = abs(np.fft.fft(signal,axis=0)[:30] / len(signal)) </code></pre> <p><a href="http://i.stack.imgur.com/J01BQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/J01BQ.png" alt="enter image description here"></a></p>
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 ripples (higher harmonics) which nicely show up in the FFT. The sine does have far less higher freq's and consists largely of a DC component.</p> <p>So far so good. What I don't understand is that your signal also has a DC component, which doesn't show up at all. Could be that this is a matter of scale.</p> <p>Core of the matter is that while the sinus and your signal look quite the same, they have a totally different harmonic content.</p> <p>Most notable none of both hold a frequency that corresponds to the half sinus. This is because a 'half sinus' isn't built by summing whole sinusses. In other words: the underlying full sinus wave isn't in the spectral content of the sinus over half the period.</p> <p>BTW having only 60 samples is a bit meager, Shannon states that your sample frequency should be at least twice the highest signal frequency, otherwise aliasing will happen (mapping freqs to the wrong place). In other words: your signal should visually appear smooth after sampling (unless of course it is discontinuous or has a discontinuous derivative, like a block or triangle wave). But in your case it looks like the sharp peaks are an artifact of undersampling.</p>
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, approximating my signal next to it which should illustrate, that I use the FFT function correctly: </p> <pre><code>import numpy as np from matplotlib import pyplot as plt signal = array([[ 0.], [ 0.1667557 ], [ 0.31103874], [ 0.44339886], [ 0.50747922], [ 0.47848347], [ 0.64544846], [ 0.67861755], [ 0.69268326], [ 0.71581176], [ 0.726552 ], [ 0.75032795], [ 0.77133769], [ 0.77379966], [ 0.80519187], [ 0.78756476], [ 0.84179849], [ 0.85406538], [ 0.82852684], [ 0.87172407], [ 0.9055542 ], [ 0.90563205], [ 0.92073452], [ 0.91178145], [ 0.8795554 ], [ 0.89155587], [ 0.87965686], [ 0.91819571], [ 0.95774404], [ 0.95432073], [ 0.96326252], [ 0.99480947], [ 0.94754962], [ 0.9818627 ], [ 0.9804966 ], [ 1.], [ 0.99919711], [ 0.97202208], [ 0.99065786], [ 0.90567128], [ 0.94300558], [ 0.89839004], [ 0.87312245], [ 0.86288378], [ 0.87301008], [ 0.78184963], [ 0.73774451], [ 0.7450479 ], [ 0.67291666], [ 0.63518575], [ 0.57036157], [ 0.5709147 ], [ 0.63079811], [ 0.61821523], [ 0.49526048], [ 0.4434457 ], [ 0.29746173], [ 0.13024641], [ 0.17631683], [ 0.08590552]]) sinus = np.sin(np.linspace(0, np.pi, 60)) plt.plot(signal) plt.plot(sinus) </code></pre> <p>The blue line is my signal, the green line is the sinus.</p> <p><a href="http://i.stack.imgur.com/BiHQu.png" rel="nofollow"><img src="http://i.stack.imgur.com/BiHQu.png" alt="raw.pdf"></a></p> <pre><code>transformed_signal = abs(np.fft.fft(signal)[:30] / len(signal)) transformed_sinus = abs(np.fft.fft(sinus)[:30] / len(sinus)) plt.plot(transformed_signal) plt.plot(transformed_sinus) </code></pre> <p>The blue line is <code>transformed_signal</code>, the green line is the <code>transformed_sinus</code>.</p> <p><a href="http://i.stack.imgur.com/TF4LE.png" rel="nofollow"><img src="http://i.stack.imgur.com/TF4LE.png" alt="fft.pdf"></a></p> <p>Plotting only <code>transformed_signal</code> illustrates the behavior described above:</p> <p><a href="http://i.stack.imgur.com/CzhWQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/CzhWQ.png" alt="enter image description here"></a></p> <p>Can someone explain to me what's going on here?</p> <p><strong>UPDATE</strong></p> <p>I was indeed a problem of calling the FFT. This is the correct call and the correct result:</p> <pre><code>transformed_signal = abs(np.fft.fft(signal,axis=0)[:30] / len(signal)) </code></pre> <p><a href="http://i.stack.imgur.com/J01BQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/J01BQ.png" alt="enter image description here"></a></p>
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 applied over the columns of <code>signal</code>, i.e., </p> <pre><code>transformed_signal = abs(np.fft.fft(signal,axis=0)[:30] / len(signal)) </code></pre>
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 an unexpected keyword argument 'pk' error</code>.</p> <p><strong>views.py</strong></p> <pre><code>def class_list(request): classes = Class.objects.all() return render(request, 'classes/class_list.html', {'classes': classes}) def class_display(request, pk): class_to_display = get_object_or_404(Class, pk=pk) return render(request, 'classes/class_display.html', {'class_to_display': class_to_display}) </code></pre> <p>application <strong>urls.py</strong></p> <pre><code>urlpatterns = [ url(r'(?P&lt;pk&gt;\w+)', views.class_display), url(r'', views.class_list), ] </code></pre> <p>outer <strong>urls.py</strong></p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^classes/(?P&lt;pk&gt;\w+)', include('students.urls')), url(r'^classes', include('students.urls')), url(r'^$', views.hello_world) ] </code></pre>
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__ == "__main__": mainMethod() </code></pre> <p>When I debug this in Visual Studio Code by hitting F5 I can't see any output with the error in Debug Console:</p> <blockquote> <p>Traceback (most recent call last): File "main.py", line 9, in mainMethod() File "main.py", line 5, in mainMethod what()<br> NameError: name 'what' is not defined</p> </blockquote> <p>If I run <code>python3 main.py</code> in console the output appears.</p> <p>How can I see those errors in VSCode and avoid switching back and forth between it and console?</p>
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 env", "type": "python", "request": "launch", "stopOnEntry": false, "console": "integratedTerminal", "program": "${workspaceRoot}/main.py", "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "RedirectOutput" ], "pythonPath": "${workspaceRoot}/env/bin/python3" } ] } </code></pre> <p>The core line is <code>"console": "integratedTerminal"</code>. Also please note that this configuration is using the interpreter from the Virtual Environment folder and the file which starts is always <code>main.py</code> instead of the default option which runs the file from the active editor.</p>
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 its use? Or what is a state of layer? I am familiar with hidden layers, RNNs, LSTMs from papers and videos, but I cannot find anything about this thing. Thanks for help.</p>
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 the weights to small but non zero numbers. This would describe the initial state of the neural network.</p>
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 class 'list-item'. When I execute the above code, it returns an empty list, but when I type it as </p> <pre><code>tags=soup.findall("li","list-item") </code></pre> <p>it returns the correct list with all the required 'li' tags. Can anyone please tell me why is this happening? I am using python 2.7 and beautifulsoup3.</p>
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 "</code> and not <code>"list-item"</code>. When I added the extra space to your code, it returns the list with all the list-items.</p>
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 a <code>HTTP/1.0</code></p> <pre><code>HTTP/1.0 200 OK Server: SimpleHTTP/0.6 Python/2.7.12 Date: Sun, 07 Aug 2016 10:02:08 GMT Content-type: text/html; charset=utf-8 Content-Length: 9747 </code></pre> <p><code>curl -v http://localhost:8000</code></p> <pre><code>* Rebuilt URL to: http://localhost:8000/ * Trying ::1... * connect to ::1 port 8000 failed: Connection refused * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8000 (#0) &gt; GET / HTTP/1.1 &gt; Host: localhost:8000 &gt; User-Agent: curl/7.43.0 &gt; Accept: */* &gt; * HTTP 1.0, assume close after body &lt; HTTP/1.0 200 OK &lt; Server: SimpleHTTP/0.6 Python/2.7.12 &lt; Date: Sun, 07 Aug 2016 10:02:23 GMT &lt; Content-type: text/html; charset=utf-8 &lt; Content-Length: 9747 &lt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"&gt;&lt;html&gt; ... &lt;/html&gt; * Closing connection 0 </code></pre> <p>How we can explain this? Why server response was not a <code>HTTP/1.1</code></p>
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 a <code>HTTP/1.0</code></p> <pre><code>HTTP/1.0 200 OK Server: SimpleHTTP/0.6 Python/2.7.12 Date: Sun, 07 Aug 2016 10:02:08 GMT Content-type: text/html; charset=utf-8 Content-Length: 9747 </code></pre> <p><code>curl -v http://localhost:8000</code></p> <pre><code>* Rebuilt URL to: http://localhost:8000/ * Trying ::1... * connect to ::1 port 8000 failed: Connection refused * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8000 (#0) &gt; GET / HTTP/1.1 &gt; Host: localhost:8000 &gt; User-Agent: curl/7.43.0 &gt; Accept: */* &gt; * HTTP 1.0, assume close after body &lt; HTTP/1.0 200 OK &lt; Server: SimpleHTTP/0.6 Python/2.7.12 &lt; Date: Sun, 07 Aug 2016 10:02:23 GMT &lt; Content-type: text/html; charset=utf-8 &lt; Content-Length: 9747 &lt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"&gt;&lt;html&gt; ... &lt;/html&gt; * Closing connection 0 </code></pre> <p>How we can explain this? Why server response was not a <code>HTTP/1.1</code></p>
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>HTTP/1.1</code> to your server. </p> <p>This line <code> 127.0.0.1 - - [07/Aug/2016 14:53:22] "GET / HTTP/1.1" 200 - </code></p> <p>is just a log entry which tells you that there is a request made with expected to get <code>HTTP/1.1</code> BUT it doesn't mean server must response with <code>HTTP/1.1</code>, see the link of Karoly Horvath for detail.</p> <p>Looking at source code of <code>SimpleHTTPServer</code>, you can see there is a <a href="https://hg.python.org/cpython/file/2.7/Lib/BaseHTTPServer.py#l230" rel="nofollow">default request version</a> which is <code>HTTP/0.9</code>.</p> <p>This <code>default_request_version</code> variable is then assigned to <code>self.request_version</code> in line 244.</p> <p>The function which does the response is <code>send_response</code> and at line 402 there is a comparison with <code>HTTP/0.9</code>, this leads to the protocol version is <code>protocol_version</code> is <code>HTTP/1.0</code> in <a href="https://hg.python.org/cpython/file/2.7/Lib/BaseHTTPServer.py#l515" rel="nofollow">line 515</a></p>
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.py</code>.</p> <pre><code>class calc: def add(x,y): answer = x + y print(answer) def sub(x,y): answer = x - y print(answer) </code></pre>
-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) def sub(self, x, y): answer = x - y print(answer) </code></pre> <p>Test script:</p> <pre><code>import calc c = calc.calc() c.add(5, 3) </code></pre> <p>Several modules in the standard library exhibit this naming scheme, such as <code>pprint</code>, <code>time</code>, and <code>datetime</code>.</p>
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.py</code>.</p> <pre><code>class calc: def add(x,y): answer = x + y print(answer) def sub(x,y): answer = x - y print(answer) </code></pre>
-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-recognition-challenge/data" rel="nofollow">fer2013</a> dataset</p> <p>The dataset I have downloaded is in "CSV" format. As I know, for working with Caffe, dataset format has to be in either "lmdb" or "hdf5".</p> <p>So it seems that the first thing I have to do is to convert my dataset into hdf5 or lmbd formats.</p> <p>Here is a simple code I tried at first:</p> <pre><code>import pandas as pd import numpy as np import csv csvFile = pd.HDFStore('PrivateTest.csv') PrivateTestHDF5 = csvFile.to_hdf(csvFile) print len(PrivateTestHDF5) </code></pre> <p>But it doesn't work, and I get this error:</p> <blockquote> <p>" Unable to open/create file 'PrivateTest.csv "</p> </blockquote> <p>I have searched alot, I found this <a href="http://stackoverflow.com/questions/27203161/convert-large-csv-to-hdf5">link</a> but I still can not understand how does it read from a CSV file.</p> <p>Also I do not have installed Matlab.</p> <p>I would be happy if anyone can help me on this. Also if any advice about writing caffe models for datasets that are on Kaggle website or any other dataset ( Those who are not on caffe website )</p>
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: false crop_size: 224 mean_file: "./supporting_files/mean.binaryproto" } image_data_param { source: "./supporting_files/labels_train.txt" batch_size: 64 shuffle: true new_height: 339 new_width: 339 } } </code></pre> <p>Here, the file "./supporting_files/labels_train.txt" is just a csv file that contains the paths to the input images stored on the file system as regular images.</p> <p>This is usually the simplest way to provide data to the model. But if you really have to use HDF5 file you can use something like this function:</p> <pre><code>import h5py import sys import numpy as np def create_h5_file(labels,file_name): nr_entries = len(labels) images = np.zeros((nr_entries, 3, width, height), dtype='f4') image_labels = np.zeros((nr_entries, nr_labels_per_image), dtype='f4') for i, l in enumerate(labels): img = caffe.io.load_image(l[0]) # pre process and/or augment your data images[i] = img image_labels[i] = [int(x) for x in l[1]] with h5py.File(file_name, "w") as H: H.create_dataset("data", data=images) H.create_dataset("label", data=image_labels) </code></pre> <p>where file_name is a string with the path of the hdf5 output file and labels are and labels is an array of tuples such as ("/path/to/my/image",["label1","label2",...,"labeln"]).</p> <p>Notice that this function works for datasets with multiple labels per image (one valid reason for using hdf5 instead of a csv file), but you probably only need a single label per image.</p>
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 (species) from the relationship of the feature using if else if or logical operator? For example </p> <p>If <code>feature 1</code> &lt; 5.2 and <code>feature 2</code> >3.4 and <code>feature 3</code> &lt; 1.5 and <code>feature 4</code> &lt;.3 <br> Then print <code>iris-setosa</code></p>
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) \ ...: &amp; (df['Feature3'] &lt; 1.5) &amp; (df['Feature4'] &lt; .3) In [5]: df.loc[mask, "TARGET"] Out[5]: 0 Iris-setosa Name: TARGET, dtype: object </code></pre>
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 (species) from the relationship of the feature using if else if or logical operator? For example </p> <p>If <code>feature 1</code> &lt; 5.2 and <code>feature 2</code> >3.4 and <code>feature 3</code> &lt; 1.5 and <code>feature 4</code> &lt;.3 <br> Then print <code>iris-setosa</code></p>
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() joystick = pygame.joystick.Joystick(0) joystick.init() #screen = pygame.display.set_mode((400,300)) #pygame.display.set_caption('Hello World') interval = 0.01 # get count of joysticks=1, axes=27, buttons=19 for DualShock 3 joystick_count = pygame.joystick.get_count() print("joystick_count") print(joystick_count) print("--------------") numaxes = joystick.get_numaxes() print("numaxes") print(numaxes) print("--------------") numbuttons = joystick.get_numbuttons() print("numbuttons") print(numbuttons) wprint("--------------") loopQuit = False while loopQuit == False: # test joystick axes # outstr = "" # for i in range(0,4): # axis = joystick.get_axis(i) # outstr = outstr + str(i) + ":" + str(axis) + "|" # print(outstr) # test controller buttons outstr = "" for i in range(0,numbuttons): button = joystick.get_button(i) outstr = outstr + str(i) + ":" + str(button) + "|" print(outstr) for event in pygame.event.get(): if event.type == QUIT: loopQuit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: loopQuit = True </code></pre> <p>The error that I am getting is Traceback (most recent call last): File "testing_joystick.py", line 47, in for event in pygame.event.get(): pygame.error: video system not initialized</p> <p>Can anyone help me figure out how to get around this error please?</p>
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.241 1 Gross Profit 256.776 268.412 156.47 220.687 2 Net Income 60.994 44.026 57.469 41.273 3 EBITDA 111.324 110.268 (41.478) 83.382 </code></pre> <p>However, when I try to transpose the code by adding a <code>.T</code>, I get: </p> <pre><code>&gt;&gt;&gt;in: df_final = pandas.DataFrame(combined_data, columns=['Item', aa, bb, cc, dd]).T &gt;&gt;&gt;&gt;out: 0 1 2 3 Item Total Revenue Gross Profit Net Income EBITDA FY2012 654.766 256.776 60.994 111.324 FY2013 535.79 268.412 44.026 110.268 FY2014 321.394 156.47 57.469 (41.478) FY2015 445.241 220.687 41.273 83.382 </code></pre> <p>After <code>Transposing</code>, what should I do so that instead of having <code>[0, 1, 2, 3]</code> as the headers, I make <code>Total Revenue Gross Profit Net Income EBITDA</code> as the headers instead?</p> <p>IE: If I did not <code>Transpose</code> the Dataframe, <code>print(df.columns.values)</code> would give me <code>Item FY2012 FY2013 FY2014 FY2015</code> as the headers. But after <code>Transposing</code> the Dataframe, <code>[0, 1, 2, 3]</code> became the headers, instead of <code>Total Revenue Gross Profit Net Income EBITDA</code></p>
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 321.394 156.470 57.469 -41.478 FY2015 445.241 220.687 41.273 83.382 </code></pre>
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 (containing 98 elements), then the values should be ordered as the following in the 2 new dimensions of shape <code>7 x 14</code>:</p> <p><code>[[v_0, v_1, v_2, v_3, v_4, v_5, v_6], [v_7, v_8, v_9, v_10, v_11, v_12, v_13], ...]</code></p> <p>Performance is not important so the solution could potentially use a for-loop if needed.</p>
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))) if (len(data) &gt; samples): data.pop(0) syslog_trace("Data : {0}".format(data), False, DEBUG) # report sample average if (startTime % reportTime &lt; sampleTime): - somma = map(sum, zip(*data)) + somma = list(map(sum, list(zip(*data)))) # not all entries should be float # 0.37, 0.18, 0.17, 4, 143, 32147, 3, 4, 93, 0, 0 averages = [format(sm / len(data), '.3f') for sm in somma] </code></pre> <p>I'm sure the makers of Python3 did not want to do it like that. At least, it gives me a "you must be kidding" feeling.</p> <p>Is there a more pythonic way of doing this?</p>
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?</p> </blockquote> <p>That really depends on your interpretation of Pythonic, list comps seem more intuitive in your case, you <strong>want</strong> to construct a <code>list</code> so there's no need to create an iterator with <code>map</code> or <code>zip</code> and <strong>then</strong> feed it to <code>list()</code>. </p> <p>Now, why <code>2to3</code> chose <code>list()</code> wrapping instead of comps, I do not know; probably easiest to actually implement.</p>
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))) if (len(data) &gt; samples): data.pop(0) syslog_trace("Data : {0}".format(data), False, DEBUG) # report sample average if (startTime % reportTime &lt; sampleTime): - somma = map(sum, zip(*data)) + somma = list(map(sum, list(zip(*data)))) # not all entries should be float # 0.37, 0.18, 0.17, 4, 143, 32147, 3, 4, 93, 0, 0 averages = [format(sm / len(data), '.3f') for sm in somma] </code></pre> <p>I'm sure the makers of Python3 did not want to do it like that. At least, it gives me a "you must be kidding" feeling.</p> <p>Is there a more pythonic way of doing this?</p>
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 generator changes: most people used those lists as generators already, wasting precious memory materializing lists they did not need.</p> <pre><code> # report sample average if (startTime % reportTime &lt; sampleTime): somma = map(sum, zip(*data)) # not all entries should be float # 0.37, 0.18, 0.17, 4, 143, 32147, 3, 4, 93, 0, 0 averages = [format(sm / len(data), '.3f') for sm in somma] </code></pre> <p>Of course the first statement, unconverted, will fail since we append a generator whereas we need a list. In that case, the error is quickly fixed.</p> <p>If left like this: <code>data.append(map(float, result))</code>, the next trace shows something fishy: <code>'Data : [&lt;map object at 0x00000000043DB6A0&gt;]'</code>, that you can quickly fix by cnverting to <code>list</code> as <code>2to3</code> suggested.</p> <p><code>2to3</code> does its best to create running Python 3 code, but it does not replace manual rework or produce optimal code. When you are in a hurry you can apply it, but always check the diffs vs the old code like the OP did.</p> <p>The <code>-3</code> option of latest Python 2 versions print warnings when an error would be raised using Python 3. It's another approach, better when you have more time to perform your migration.</p>
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">spectral API</a>.</p> <p>Here is an example</p> <pre><code>img = np.array([111, 112, 113, 121, 122, 123, 131, 132, 133, 211, 212, 213, 221, 222, 223, 231, 232, 233, 311, 312, 313, 321, 322, 323, 331, 332, 333]).reshape((3,3,3)) labels = np.array([0, 1, 1, 2, 2, 2, 3, 3, 3]).reshape((3,3)) </code></pre> <p>I can draw <code>img</code> with <code>labels</code> this like this:</p> <pre><code>from spectral import imshow as spyShow imageView = spyShow(data=img, bands=(0,1,2), classes=labels, fignum=1, interpolation='none') imageView.set_display_mode('overlay') </code></pre> <p><a href="http://i.stack.imgur.com/tYwqj.png" rel="nofollow"><img src="http://i.stack.imgur.com/tYwqj.png" alt="enter image description here"></a></p> <p>Now I would like to place a legend below the image.</p> <pre><code>labelDictionary={0:'Unknown', 1:'Gravel', 2:'Aslphalt', 3:'Glass'} </code></pre> <p>From the source code I see that the label colors are taken from:</p> <pre><code>spectral.spy_colors </code></pre> <p>Further they are drawn with the following code:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, NoNorm cm = ListedColormap(np.array(spectral.spy_colors) / 255.) plt.imshow(a, cmap=cm, vmin = 0, interpolation='none', norm=NoNorm()) </code></pre> <p>I think I could extract those colors and map them to the labels and label names using a custom made function. Is this the correct way to make the legend, or is there a ready-made way, for the sake of not reinventing the wheel... </p>
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> <pre><code>plt.legend(handles=labelPatches, ncol=2, fontsize='medium', loc='upper center', bbox_to_anchor=(0.5, -0.05)); </code></pre> <p><a href="http://i.stack.imgur.com/f0JKY.png" rel="nofollow"><img src="http://i.stack.imgur.com/f0JKY.png" alt="enter image description here"></a></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) simple_exponential_smoothing(actuals, n_forecast_periods,alpha) </code></pre> <p>However, it doesn't work when try to get same user inputs in code itself:</p> <pre><code>import numpy as np actuals = [] actuals = input("Input list:") n_forecast_periods = int(input("Int:")) alpha = float(input("float:")) 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) simple_exponential_smoothing(actuals, n_forecast_periods,alpha) </code></pre> <p>Apologize, if this is not a good question. I am new to Python.</p> <p>I have already tried using map function for multiplication; too complex for me to use it in following setup.</p>
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 5.48283] </code></pre> <p>You might want to take a look at <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.ewma.html" rel="nofollow">pandas.ewma</a>, too.</p>
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 argument and getting this value "0b10" in variable x and just printing that x. </p> <p>Why <code>print x</code> inside the function is NOT working like the first line in the program?</p> <p>What should I do in p_m()'s print statement to print the value of "<em>0b10</em>" as <strong>2</strong>.</p>
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</code> part of <code>0b10</code> is not mandatory since <code>int()</code> already knows it converts it to base 2. <a href="https://docs.python.org/2/library/functions.html#int" rel="nofollow">Documentation</a> says,</p> <blockquote> <p>The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O/0, or 0x/0X, as with integer literals in code.</p> </blockquote>
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 argument and getting this value "0b10" in variable x and just printing that x. </p> <p>Why <code>print x</code> inside the function is NOT working like the first line in the program?</p> <p>What should I do in p_m()'s print statement to print the value of "<em>0b10</em>" as <strong>2</strong>.</p>
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 argument and getting this value "0b10" in variable x and just printing that x. </p> <p>Why <code>print x</code> inside the function is NOT working like the first line in the program?</p> <p>What should I do in p_m()'s print statement to print the value of "<em>0b10</em>" as <strong>2</strong>.</p>
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://pastebin.com/uiuBNJ0y" rel="nofollow">http://pastebin.com/uiuBNJ0y</a></p> <p>code: for the citizens of countries which has banned pastebin. <a href="http://paste.ubuntu.com/22563333/" rel="nofollow">http://paste.ubuntu.com/22563333/</a></p>
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 engineered without manual intervention even.</p>
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, server='cherrypy', debug=True) </code></pre> <p>Now when I enter this in browser <a href="http://localhost:8881/plot_graph" rel="nofollow">http://localhost:8881/plot_graph</a> it gives error </p> <pre><code>Error: 500 Internal Server Error Sorry, the requested URL 'http://localhost:8881/plot_graph' caused an error: Unsupported response type: &lt;type 'int'&gt; </code></pre> <p>and my python console says that it is listening but gives this warning</p> <pre><code>Bottle v0.12.9 server starting up (using CherryPyServer())... Listening on http://0.0.0.0:8881/ Hit Ctrl-C to quit. /Users/guru/python_projects/implement_LDA/lda/lib/python2.7/site-packages/bottle.py:2777: ImportWarning: Not importing directory '/Users/guru/python_projects/implement_LDA/lda/cherrypy': missing __init__.py from cherrypy import wsgiserver </code></pre> <p>Any ways to resolve this?</p>
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 want. So another option is to return a dictionary which <code>bottle</code> will convert to a JSON encoded response:</p> <pre><code>return {'val{}'.format(i): val for i, val in enumerate(graph_list, 1)} </code></pre> <p>This creates a dictionary such as <code>{'val1': 1, 'val2': 2, 'val3': 2, 'val4': 5}</code>.</p> <p>For the warning problem, it would appear that you have a directory named <code>cherrypy</code> in the same directory as your main python script. Rename/remove that directory and bottle will import CherryPy from your site-packages directory. Or you could simply remove <code>server='cherrypy'</code> from the call to <code>run()</code> to use the default wsgiref server.</p>
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 page. I have tried long and hard and cannot think why the session variables are lost, I have tried it in chrome, firefox and internet explorer, all with the same outcome.</p> <p>p.s - I know I am not hashing passwords, I will get around to that after this.</p> <p>main.py:</p> <pre><code>#Store from flask import * import nltk import functools import re from users import User #from flask_socketio import SocketIO,send,emit,disconnect from flask_socketio import * from flask_login import LoginManager,login_user,current_user,login_required import flask_login from pymongo import MongoClient client = MongoClient() db = client.database app = Flask(__name__) app.secret_key= 'lemon' socketio = SocketIO(app) login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(email): print('email given: '+email) cursor = db.users.find_one({"user.email":str(email)}) if not cursor: return None return User(email) @app.route('/') def home(): print('overview session') for i in session: print(session[i]) return render_template('index.html') @app.route('/login') def login(): return render_template('login.html') @app.route('/overview') @login_required def overview(): return render_template('overview.html') @socketio.on('login_data') def login_data(email,password): cursor = db.users.find_one({"user.email":str(email),"user.password":str(password)}) if cursor: user = User(cursor['user']['email']) print(user.get_id()) login_user(user,remember=True) print('sessions') for i in session: print(session[i]) emit('auth',[True,current_user.email]) else: emit('auth',False) if __name__ == '__main__': socketio.run(app,host='0.0.0.0',debug=True) </code></pre> <p>Users Class:</p> <pre><code>#Users.py from pymongo import MongoClient class User(object): def __init__(self,email): self.email = email def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.email) </code></pre>
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 method as usually used in engineering.</p> <p>Now, I know that the variance approach is only suited for when the error is small compared to the partial derivate (because of the Taylor series) which isn't given in this case, but how does <code>uncertainties</code> handle this? And how can I reproduce in any way what uncertainties does!?</p>
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(), random.random()) for _ in range(100)] sa = unumpy.std_devs(sum(a)) sb = math.sqrt(sum(unumpy.std_devs(a)**2)) print(sa) print(sb) print(sa == sb) </code></pre> <p>Will result with something like</p> <pre><code>5.793714811166615 5.793714811166615 True </code></pre>
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 method as usually used in engineering.</p> <p>Now, I know that the variance approach is only suited for when the error is small compared to the partial derivate (because of the Taylor series) which isn't given in this case, but how does <code>uncertainties</code> handle this? And how can I reproduce in any way what uncertainties does!?</p>
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-functions-with-uncertainty" rel="nofollow">[1]</a>.</p> <p>Now, my values are not fully independent (which wasn't clear at all at first sight*), and thus <code>sum(array)</code> also considers the off-diagonal elements of my covariance matrix in accordance to <a href="https://de.wikipedia.org/wiki/Fehlerfortpflanzung#Voneinander_abh.C3.A4ngige_fehlerbehaftete_Gr.C3.B6.C3.9Fen" rel="nofollow">this</a> formula (sorry that the article is in German, but English Wikipedias <a href="https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Linear_combinations" rel="nofollow">formula</a> isn't as intuitive), whereas <code>sqrt(sum(unumpy.std_devs(array)**2))</code> obviously doesn't and just adds up the diagonal elements.</p> <p>A way to reproduce what uncertainties does is:</p> <pre><code>from uncertainties import covariance_matrix sum=0 for i in range(0,len(array)): for j in range(0,len(array)): sum+=covariancematrix(array)[i][j] print(sqrt(sum)) </code></pre> <p>And then <code>unumpy.std_devs(sum(array))==sqrt(sum)</code> is <code>True</code>.</p> <p>*Correlation due to the use of data taken from the same interpolation (of measurements) and because the length of a measurement was calculated as the difference of two times (and meassurement were consecutive, so the times are now correlated!)</p>
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" rel="nofollow"><img src="http://i.stack.imgur.com/1r88I.png" alt="enter image description here"></a></p> <p>I am still receiving the error: </p> <p><a href="http://i.stack.imgur.com/aI9BB.png" rel="nofollow"><img src="http://i.stack.imgur.com/aI9BB.png" alt="enter image description here"></a></p> <p>What is the reason for the error? I have been troubleshooting the problem for a long time.</p>
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 install the package with pip:</p> <pre><code>pip install python_dateutil-2.5.3-py2.py3-none-any.whl </code></pre> <p>After the module is installed, simply import as normal in the console or script:</p> <pre><code>import dateutil </code></pre> <p>And here is a quick example:</p> <p><a href="http://i.stack.imgur.com/HdADQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/HdADQ.png" alt="Installing module using pip"></a></p> <p>If you need to install pip, here are <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">some instruction to install pip</a>.</p>
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 <strong>MySQL 5.5.50</strong>.</p> <p>I connect like this:</p> <pre><code>DB_ENGINE = sqlalchemy.create_engine("mysql+mysqldb://{user}:{pass}@{host}:{port}/{database}?charset=utf8mb4".format(**DB_SETTINGS)) Session = sqlalchemy.orm.sessionmaker(bind=DB_ENGINE) </code></pre> <p>The error is:</p> <pre><code> File "C:\Applications\Python27\lib\site-packages\sqlalchemy\engine\default.py", line 385, in connect return self.dbapi.connect(*cargs, **cparams) File "C:\Applications\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "C:\Applications\Python27\lib\site-packages\MySQLdb\connections.py", line 221, in __init__ self.set_character_set(charset) File "C:\Applications\Python27\lib\site-packages\MySQLdb\connections.py", line 312, in set_character_set super(Connection, self).set_character_set(charset) sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2019, "Can't initialize character set utf8mb4 (path: C:\\mysql\\\\share\\charsets\\)") </code></pre> <p>The server's my.cnf contains the following:</p> <pre><code>init_connect = 'SET collation_connection = utf8mb4_unicode_ci' init_connect = 'SET NAMES utf8mb4' character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci skip-character-set-client-handshake </code></pre> <p>I have no problem connecting to the database from an Ubuntu client, so I suspect the problem is with the Windows client and not the server's configuration.</p> <p>The MySQL documentation suggests the error message could be due to the client being compiled without multibyte character set support:</p> <p><a href="http://dev.mysql.com/doc/refman/5.7/en/cannot-initialize-character-set.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.7/en/cannot-initialize-character-set.html</a></p> <p>However, as this is Windows I'm simply downloading the client and don't have control over its compilation flags.</p> <p>I've tried installing MySQLdb in a variety of ways:</p> <ul> <li>Downloading and installing the MySQL Connector/Python .msi from dev.mysql.com</li> <li>Downloading and installing the MySQLdb 1.2.5 .exe from pypi</li> <li>Running "pip install mysql-python" from the Windows command prompt</li> </ul> <p>Each of these results in a MySQLdb library that can't seem to handle the utf8mb4 character set.</p> <p>Any help would be much appreciated!</p>
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" ]