title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Divide date as day,month and year
39,301,871
<p>l have 41 year-dataset and l would like to do some calculations by using these dataset but for this, l need to divide the date into day, month and year respectively.</p> <p>example dataset(csv file data)</p> <pre><code> date stations pcp 1.01.1979 6 1.071 2.01.1979 6 5.909 3.01.1979 6 9.134 1.01.1979 5 1.229 2.01.1979 5 0.014 3.01.1979 5 3.241 </code></pre> <p>l need to convert these data in this:</p> <pre><code>day month year stations pcp 1 01 1979 6 1.071 2 01 1979 6 5.909 3 01 1979 6 9.134 </code></pre> <p>when l run code , it stops and l have to close it. No error message. how can l correct this? l m a fresh user and probably ,there are many mistakes. l hope l can learn my mistake here.l made two try and l m not sure which one is correct here is my code:</p> <pre><code>from datetime import date, datetime, timedelta,time import csv import numpy as np a=[] dd=[] mm=[] yy=[] with open('p2.csv') as csvfile: x=[] reader = csv.DictReader(csvfile,fieldnames=("date","stations","pcp"),delimiter=';', quotechar='|') for row in reader: x.append(row["date"]) #try1 for i in range(len (x)): day,month,year=a.split(x[i]) d=int(day) m=int(month) y=int(year) dd.append(d) mm.append(m) yy.append(y) #try2 """for i in range(len(x)): an=x[i] y=datetime.datetime.strftime(an, '%Y') d=datetime.datetime.strftime(an, '%d') m=datetime.datetime.strftime(an, '%m') dd.append(d) mm.append(m) yy.append(y)""" </code></pre>
0
2016-09-02T23:31:49Z
39,302,249
<p>this script will get you a list of lists with your values and will also write the final list into a csv.</p> <pre><code>import csv with open('p2.csv') as csvfile: x=[] reader = csv.reader(csvfile,delimiter=',', quotechar='|') for num, row in enumerate(reader): for i, item in enumerate(row): if i ==0: yy = [] d, m, y = item.split('.') yy.append(d) yy.append(m) yy.append(y) else: yy.append(item) x.append(yy) print x with open('output.csv', 'wb') as csvfile: datawriter = csv.writer(csvfile,delimiter=',', quotechar='|') for datarow in x: datawriter.writerow(datarow) </code></pre>
0
2016-09-03T00:40:18Z
[ "python", "date", "csv" ]
numpy.unique gives non-unique output?
39,301,882
<p>I am trying to get the indices of unique elements of a numpy array (long vector of 3628621 elements). However, I must do something wrong, because when I try to select the unique elements I am still finding duplicates:</p> <pre><code>Vector Out[165]: array([712450, 714390, 718560, ..., 384390, 992041, 94852]) Loc = np.where(np.unique(Vector)) # Find indices of unique elements Vector_New = Vector[Loc] # Create new vector with all unique elements np.where(Vector_New == 173020) # See how often/where '173020' exists Out[166]: (array([ 7098, 11581], dtype=int64),) </code></pre> <p>So, the integer '173020' exists still twice in the new vector, although I expected that all elements should be unique. The new vector is 11594 elements long.</p> <p>Thanks for the help!</p> <p>Regards, Timen</p>
-1
2016-09-02T23:33:42Z
39,302,318
<p><code>np.unique</code> has several parameters that can be activated and will give you the needed information. It's calling signature is:</p> <pre><code>np.unique(ar, return_index=False, return_inverse=False, return_counts=False) </code></pre> <p>read the docs.</p> <pre><code>In [50]: keys Out[50]: array([1, 3, 5, 2, 0, 7, 4, 7, 7, 2, 7, 5, 5, 3, 6, 2, 3, 5, 5, 5, 6, 9, 6, 5, 2, 1, 6, 6, 5, 9, 9, 6, 5, 5, 9, 9, 6, 3, 7, 0, 5, 1, 7, 6, 2, 4, 1, 0, 6, 5, 4, 8, 8, 4, 2, 1, 8, 3, 1, 9, 8, 4, 4, 2, 4, 7, 2, 6, 8, 6, 5, 2, 4, 9, 1, 5, 3, 1, 5, 6, 2, 2, 8, 4, 0, 4, 9, 0, 8, 1, 5, 3, 1, 3, 7, 1, 5, 8, 5, 8]) In [51]: np.unique(keys, return_counts=True, return_index=True) Out[51]: (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([ 4, 0, 3, 1, 6, 2, 14, 5, 51, 21], dtype=int32), array([ 5, 11, 11, 8, 10, 18, 12, 8, 9, 8])) </code></pre>
1
2016-09-03T00:55:05Z
[ "python", "numpy", "unique" ]
What is the difference between 'with open(...)' and 'with closing(open(...))'
39,301,983
<p>From my understanding,</p> <pre><code>with open(...) as x: </code></pre> <p>is supposed to close the file once the <code>with</code> statement completed. However, now I see</p> <pre><code>with closing(open(...)) as x: </code></pre> <p>in one place, looked around and figured out, that <code>closing</code> is supposed to close the file upon finish of the <code>with</code> statement.</p> <p>So, what's the difference between closing the file and <code>closing</code> the file?</p>
4
2016-09-02T23:53:17Z
39,302,016
<p>Assuming that's <code>contextlib.closing</code> and the standard, built-in <code>open</code>, <code>closing</code> is redundant here. It's a wrapper to allow you to use <code>with</code> statements with objects that have a <code>close</code> method, but don't support use as context managers. Since the file objects returned by <code>open</code> are context managers, <code>closing</code> is unneeded.</p>
14
2016-09-02T23:57:41Z
[ "python" ]
Submitting Python Application with Apache Spark Submit
39,302,113
<p>I am trying to follow the examples on the Apache Spark documentation site: <a href="https://spark.apache.org/docs/2.0.0-preview/submitting-applications.html" rel="nofollow">https://spark.apache.org/docs/2.0.0-preview/submitting-applications.html</a></p> <p>I started a Spark standalone cluster and want to run the example Python application. I am in my spark-2.0.0-bin-hadoop2.7 directory and ran the following command</p> <pre><code>./bin/spark-submit \ --master spark://207.184.161.138:7077 \ examples/src/main/python/pi.py \ 1000 </code></pre> <p>However, I get the error</p> <pre><code>jupyter: '/Users/MyName/spark-2.0.0-bin- \ hadoop2.7/examples/src/main/python/pi.py' is not a Jupyter command </code></pre> <p>This is what my bash_profile looks like</p> <pre><code>#setting path for Spark export SPARK_PATH=~/spark-2.0.0-bin-hadoop2.7 export PYSPARK_DRIVER_PYTHON="jupyter" export PYSPARK_DRIVER_PYTHON_OPTS="notebook" alias snotebook='$SPARK_PATH/bin/pyspark --master local[2]' </code></pre> <p>What am I doing wrong?</p>
0
2016-09-03T00:15:08Z
39,347,226
<p>The <code>PYSPARK_DRIVER_PYTHON</code> and <code>PYSPARK_DRIVER_PYTHON_OPTS</code> are meant for running the ipython/jupyter shell when opening the pyspark shell ( More info at <a href="http://stackoverflow.com/questions/31862293/how-to-load-ipython-shell-with-pyspark">How to load IPython shell with PySpark</a> ).</p> <p>You can set this up like:</p> <pre><code>alias snotebook='PYSPARK_DRIVER_PYTHON=jupyter PYSPARK_DRIVER_PYTHON_OPTS=notebook $SPARK_PATH/bin/pyspark --master local[2]' </code></pre> <p>So that it doesn't interfere with pyspark when submitting</p>
0
2016-09-06T10:51:25Z
[ "python", "apache-spark", "pyspark" ]
Getting Flask to Run on Apache on Ubuntu
39,302,129
<p>Having trouble getting Flask to run on Apache. Followed the directions <a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps" rel="nofollow">here</a> to setup mod_wsgi. I put my desired python code into the <code>/var/www/TDAA_reminder/TDAA_reminder/__init__.py</code>. If I manually run the code via <code>sudo python __init__.py</code> and use ngrok it will received a twilio post so I know that code is working. But will not work with the mod_wsgi. The system has auto-generated <code>__init__.pyc</code> so I feel like it is somewhat working maybe, but I am stuck on where to debug next. I have reloaded and restarted apache numerous times. Gone back to ngrok to ensure I hadn't broken anything. Thanks!</p> <p>The directory structure from the tutorial is a bit off what I would have expected so:</p> <pre><code>|--------TDAA_reminder |----------------TDAA_reminder |-----------------------static |-----------------------templates |-----------------------TDAAenv |-----------------------__init__.py |----------------flaskapp.wsgi </code></pre> <p>Error in twilio is <code>11200 HTTP retrieval failure</code>:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;500 Internal Server Error&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Internal Server Error&lt;/h1&gt; &lt;p&gt;The server encountered an internal error or misconfiguration and was unable to complete your request.&lt;/p&gt; &lt;p&gt;Please contact the server administrator at admin@andrewtclaus.com to inform them of the time this error occurred, and the actions you performed just before this error.&lt;/p&gt; &lt;p&gt;More information about this error may be available in the server error log.&lt;/p&gt; &lt;hr&gt; &lt;address&gt;Apache/2.4.7 (Ubuntu) Server at andrewtclaus.com Port 80&lt;/address&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My hook is directed to <code>http://andrewtclaus.com/TDAA_reminder</code>.</p> <p>excerpt from <code>/var/www/TDAA_reminder/TDAA_reminder/__init__.py</code>:</p> <pre><code>app = Flask(__name__) @app.route('/TDAA_reminder', methods=['POST']) def TDAA_reminder(): </code></pre> <p><br> <code>/etc/apache2/sites-available/TDAA_reminder.conf</code>:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName AndrewTClaus.com ServerAdmin admin@andrewtclaus.com WSGIScriptAlias / /var/www/TDAA_reminder/TDAA_reminder.wsgi &lt;Directory /var/www/TDAA_reminder/TDAA_reminder/&gt; Order allow,deny Allow from all &lt;/Directory&gt; Alias /static /var/www/TDAA_reminder/TDAA_reminder/static &lt;Directory /var/www/TDAA_reminder/TDAA_reminder/static/&gt; Order allow,deny Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre> <p><br> <code>/var/www/TDAA_reminder/TDAA_reminder.wsgi</code>:</p> <pre><code>#!/usr/bin/python activate_this = '/var/www/TDAA_reminder/TDAA_reminder/TDAAenv/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/TDAA_reminder/") from TDAA_reminder import app as application </code></pre> <p><br> Apache error codes:</p> <pre><code>[Sat Sep 03 01:53:23.598479 2016] [:error] [pid 17691] [client 192.0.101.226:16488] mod_wsgi (pid=17691): Target WSGI script '/var/www/TDAA_reminder/TDAA_reminder.wsgi' cannot be loaded as Py$ [Sat Sep 03 01:53:23.598508 2016] [:error] [pid 17691] [client 192.0.101.226:16488] mod_wsgi (pid=17691): Exception occurred processing WSGI script '/var/www/TDAA_reminder/TDAA_reminder.wsgi'. [Sat Sep 03 01:53:23.598526 2016] [:error] [pid 17691] [client 192.0.101.226:16488] Traceback (most recent call last): [Sat Sep 03 01:53:23.598542 2016] [:error] [pid 17691] [client 192.0.101.226:16488] File "/var/www/TDAA_reminder/TDAA_reminder.wsgi", line 11, in &lt;module&gt; [Sat Sep 03 01:53:23.598565 2016] [:error] [pid 17691] [client 192.0.101.226:16488] from TDAA_reminder import app as application [Sat Sep 03 01:53:23.598574 2016] [:error] [pid 17691] [client 192.0.101.226:16488] File "/var/www/TDAA_reminder/TDAA_reminder/__init__.py", line 37, in &lt;module&gt; [Sat Sep 03 01:53:23.598639 2016] [:error] [pid 17691] [client 192.0.101.226:16488] flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) [Sat Sep 03 01:53:23.598658 2016] [:error] [pid 17691] [client 192.0.101.226:16488] AttributeError: 'TwilioRestClient' object has no attribute 'flow_from_clientsecrets' [Sat Sep 03 01:57:16.917248 2016] [:error] [pid 17688] [client 54.165.223.88:40658] mod_wsgi (pid=17688): Target WSGI script '/var/www/TDAA_reminder/TDAA_reminder.wsgi' cannot be loaded as Py$ [Sat Sep 03 01:57:16.917277 2016] [:error] [pid 17688] [client 54.165.223.88:40658] mod_wsgi (pid=17688): Exception occurred processing WSGI script '/var/www/TDAA_reminder/TDAA_reminder.wsgi'. [Sat Sep 03 01:57:16.917308 2016] [:error] [pid 17688] [client 54.165.223.88:40658] Traceback (most recent call last): [Sat Sep 03 01:57:16.917324 2016] [:error] [pid 17688] [client 54.165.223.88:40658] File "/var/www/TDAA_reminder/TDAA_reminder.wsgi", line 11, in &lt;module&gt; [Sat Sep 03 01:57:16.917346 2016] [:error] [pid 17688] [client 54.165.223.88:40658] from TDAA_reminder import app as application [Sat Sep 03 01:57:16.917370 2016] [:error] [pid 17688] [client 54.165.223.88:40658] File "/var/www/TDAA_reminder/TDAA_reminder/__init__.py", line 37, in &lt;module&gt; [Sat Sep 03 01:57:16.917384 2016] [:error] [pid 17688] [client 54.165.223.88:40658] flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) [Sat Sep 03 01:57:16.917400 2016] [:error] [pid 17688] [client 54.165.223.88:40658] AttributeError: 'TwilioRestClient' object has no attribute 'flow_from_clientsecrets' </code></pre> <p>Excerpt related to debugging:</p> <pre><code>SCOPES = ('https://www.googleapis.com/auth/calendar') store = file.Storage('cal_auth.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store, flags) \ if flags else tools.run(flow, store) CAL = build('calendar', 'v3', http=creds.authorize(Http())) </code></pre>
0
2016-09-03T00:17:48Z
39,419,555
<p>Answered in comments via following discussion: </p> <blockquote> <p>what was the error from the Apache error log file? If the guide says to have it twice, the guide is technically wrong. It has to be /var/www/TDAA_reminder as that is the directory the WSGI script file is in. Without it, Apache shouldn't be serving up your WSGI application as it would be forbidden. If it works regardless of that, you have lax security elsewhere in your Apache configuration which is putting your server at a bit of risk as allowing access to anything in the file system.</p> </blockquote> <p>if I read it right, <code>'TwilioRestClient' object has no attribute 'flow_from_clientsecrets'</code> but when I do <code>python __init__.py</code> it works and and I get no errors when using ngrok to tunnel in so I am confused why that is the error?</p> <blockquote> <p>changed the paths in my file to absolute and it worked!</p> </blockquote>
0
2016-09-09T20:54:03Z
[ "python", "apache", "ubuntu", "flask", "mod-wsgi" ]
Python: Ignore case sensitivity for MYSQL column names
39,302,170
<p>I am querying my MySQL DB with following code. </p> <pre><code>import MySQLdb db = MySQLdb.connect("localhost","user","password","test" ) cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = "select * from student" try: cursor.execute(sql) results = cursor.fetchall() for row in results: print row['firstname'] except: print "Error: unable to fecth data" db.close() </code></pre> <p>Problem is that the column name specified in <code>row['firstName']</code> does not match and is case sensitive. Is there any way to ignore case sensitivity?</p>
0
2016-09-03T00:26:08Z
39,302,305
<p>you can use this:</p> <pre><code>sequence = cursor.column_names </code></pre> <p><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html</a></p> <p>Then compare your string to the actual name with .lower() and act accordingly</p>
1
2016-09-03T00:51:57Z
[ "python", "mysql" ]
Django ORM query for empty FileFields
39,302,175
<p>It's not clear to me whether this is possible through the ORM - it doesn't appear so, but maybe I'm missing something?</p> <pre><code> class ApplicationInstitution(models.Model): ... transcript_file = FileField(upload_to=...) </code></pre> <p>Some of those <code>ApplicationInstitution</code> objects may already have had a <code>transcript_file</code> uploaded into them, while others have not. I want to query for instances with an empty FileField. At first I thought I could so something like</p> <p><code>ApplicationInstitution.objects.filter(transcript_file__isnull=False)</code></p> <p>or similar, but this gives unexpected results (either all records or zero, depending on whether you use <code>filter</code> or <code>exclude</code>). And if you try to access the actual file object, you get a Raise, not an empty:</p> <pre><code>&gt;&gt;&gt; a.institutions.last().transcript_file.file Traceback (most recent call last): ... ValueError: The 'transcript_file' attribute has no file associated with it. </code></pre> <p>I've written a model method using try/except that gets me the answer, but ORM would be cleaner. Is a query for empty or non-empty FileFields even possible? </p>
0
2016-09-03T00:26:46Z
39,302,287
<pre><code>transcript_file = FileField(upload_to=..., null=True) </code></pre> <p>and try this for <code>ApplicationInstitution</code> without file:</p> <pre><code>ApplicationInstitution.objects.filter(transcript_file__isnull=True) </code></pre> <p>for <code>ApplicationInstitution</code> with file:</p> <pre><code>ApplicationInstitution.objects.exclude(transcript_file__isnull=True) </code></pre>
-1
2016-09-03T00:48:56Z
[ "python", "django", "orm" ]
Django ORM query for empty FileFields
39,302,175
<p>It's not clear to me whether this is possible through the ORM - it doesn't appear so, but maybe I'm missing something?</p> <pre><code> class ApplicationInstitution(models.Model): ... transcript_file = FileField(upload_to=...) </code></pre> <p>Some of those <code>ApplicationInstitution</code> objects may already have had a <code>transcript_file</code> uploaded into them, while others have not. I want to query for instances with an empty FileField. At first I thought I could so something like</p> <p><code>ApplicationInstitution.objects.filter(transcript_file__isnull=False)</code></p> <p>or similar, but this gives unexpected results (either all records or zero, depending on whether you use <code>filter</code> or <code>exclude</code>). And if you try to access the actual file object, you get a Raise, not an empty:</p> <pre><code>&gt;&gt;&gt; a.institutions.last().transcript_file.file Traceback (most recent call last): ... ValueError: The 'transcript_file' attribute has no file associated with it. </code></pre> <p>I've written a model method using try/except that gets me the answer, but ORM would be cleaner. Is a query for empty or non-empty FileFields even possible? </p>
0
2016-09-03T00:26:46Z
39,307,388
<p>You can query for empty strings:</p> <pre><code># instances with empty FileField ApplicationInstitution.objects.filter(transcript_file='') # and with a file already uploaded ApplicationInstitution.objects.exclude(transcript_file='') </code></pre>
1
2016-09-03T13:22:25Z
[ "python", "django", "orm" ]
Python background shell script communication
39,302,190
<p>I have 2 python scripts, <code>foo.py</code> and <code>bar.py</code>. I am running foo.py in the background using</p> <pre><code>python foo.py &amp; </code></pre> <p>Now I want to run <code>bar.py</code> and use the stdout from this file to trigger script inside foo.py. Is this possible? I'm using Ubuntu 16.04 LTS.</p>
1
2016-09-03T00:28:53Z
39,302,263
<p>There is a system that actually comes from UNIX world that creates <code>pipes</code> between processes. A pipe is basically a pair of file descriptors, each program having access to one of them. One program writes to the pipe, while the other reads:</p> <p><a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">https://docs.python.org/2/library/subprocess.html</a></p> <p>However, this requires an aditional script where you start foo and bar as subprocesses and connect their outputs/inputs.</p>
0
2016-09-03T00:43:15Z
[ "python", "shell", "background-process" ]
Python background shell script communication
39,302,190
<p>I have 2 python scripts, <code>foo.py</code> and <code>bar.py</code>. I am running foo.py in the background using</p> <pre><code>python foo.py &amp; </code></pre> <p>Now I want to run <code>bar.py</code> and use the stdout from this file to trigger script inside foo.py. Is this possible? I'm using Ubuntu 16.04 LTS.</p>
1
2016-09-03T00:28:53Z
39,302,292
<p>You could use <a href="https://en.wikipedia.org/wiki/Named_pipe" rel="nofollow">UNIX named pipe</a> for that.</p> <p>First, you create named pipe object by executing <code>mkfifo named_pipe</code> in the same directory, where you have your python files.</p> <p>Your <code>foo.py</code> then could look like this:</p> <pre><code>while True: for line in open('named_pipe'): print 'Got: [' + line.rstrip('\n') + ']' </code></pre> <p>And your <code>bar.py</code> could look like this:</p> <pre><code>import sys print &gt;&gt;open('named_pipe', 'wt'), sys.argv[-1] </code></pre> <p>So, you run your consumer process like this: <code>python foo.py &amp;</code>. And finally, each time you execute <code>python bar.py Hello</code>, you will see the message <code>Got: [Hello]</code> in your console.</p> <p>UPD: unlike Paul's answer, if you use <em>named</em> pipe, you don't have to start one of the processes from inside the other.</p>
1
2016-09-03T00:49:50Z
[ "python", "shell", "background-process" ]
Getting a cropped combination of 9 2D numpy arrays (only want boundaries of middle array)
39,302,252
<p>I have 9 individual 2D numpy arrays that are each 3x3, I want to join at the edges like example:</p> <p><code> 111222333 111222333 111222333 444555666 444555666 444555666 777888999 777888999 777888999 </code></p> <p>Except I only want the nearby boundaries of any array that isn't the middle one, like example:</p> <p><code> 12223 45556 45556 45556 78889 </code></p> <p><a href="http://pastebin.com/raw/QuKDfjCN" rel="nofollow">Here is the code I used to generate the first example.</a> I have been considering using another function to crop the combined array (9x9 down to 5x5 in terms of the example) but I'm concerned about performance and I don't know how to achieve that either.</p>
0
2016-09-03T00:41:01Z
39,302,304
<p>Since you know you want to drop the first and last two columns of your 9x9 array, I would just use NumPy's indexing:</p> <pre><code>&gt;&gt;&gt; x = np.arange(81).reshape((9,9)) &gt;&gt;&gt; x array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24, 25, 26], [27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44], [45, 46, 47, 48, 49, 50, 51, 52, 53], [54, 55, 56, 57, 58, 59, 60, 61, 62], [63, 64, 65, 66, 67, 68, 69, 70, 71], [72, 73, 74, 75, 76, 77, 78, 79, 80]]) &gt;&gt;&gt; x[:,2:-2] array([[ 2, 3, 4, 5, 6], [11, 12, 13, 14, 15], [20, 21, 22, 23, 24], [29, 30, 31, 32, 33], [38, 39, 40, 41, 42], [47, 48, 49, 50, 51], [56, 57, 58, 59, 60], [65, 66, 67, 68, 69], [74, 75, 76, 77, 78]]) </code></pre> <p><code>x[:,2:-2]</code> means all rows (<code>:</code>), drop first two and last two columns (<code>2:-2</code>).</p>
1
2016-09-03T00:51:41Z
[ "python", "arrays", "numpy" ]
Reducing the brightness of an LED Strip (Adafruit Dotstar RGB Strip) using Python
39,302,267
<p>I have this code below piping data to a strip of RGB LEDs. The code works fine. The Adafruit Dotstar libray (<a href="https://github.com/adafruit/Adafruit_DotStar" rel="nofollow">https://github.com/adafruit/Adafruit_DotStar</a>) also has a strandtest.py example in addition to the code below. In the test example it is possible to reduce the brightness of the LEDs using <em>strip.setBrightnes(2)</em>. I have duplicated that code in the same general location in the code below but it does not change the LED brightness. I suspect a bug with in the library but I would still like to find a solution to reduce the LED brightness. I am at wits end (read NOOB). Any help reducing the LED brightness is appreciated.</p> <pre><code>#!/usr/bin/python import PIL from PIL import Image from dotstar import Adafruit_DotStar filename = "/home/pi/Adafruit_DotStar_Pi/marilynlowerres.jpg" datapin = 10 clockpin = 11 strip = Adafruit_DotStar(0, datapin, clockpin) rOffset = 3 gOffset = 2 bOffset = 1 strip.begin() strip.setBrightness(2) print "Loading..." img = Image.open(filename).convert("RGB") pixels = img.load() width = img.size[0] height = img.size[1] print "%dx%d pixels" % img.size gamma = bytearray(256) for i in range(256): gamma[i] = int(pow(float(i) / 255.0, 2.7) * 255.0 + 0.5) print "Allocating..." column = [0 for x in range(width)] for x in range(width): column[x] = bytearray(height * 4) print "Converting..." for x in range(width): for y in range(height): value= pixels[x, y] y4= y * 4 column[x][y4]= 0xFF column[x][y4 + rOffset] = gamma[value[0]] column[x][y4 + gOffset] = gamma[value[1]] column[x][y4 + bOffset] = gamma[value[2]] print "Displaying..." while True: for x in range(width): strip.show(column[x]) </code></pre>
0
2016-09-03T00:44:18Z
39,309,152
<p>Here is a solution to reducing pixel brightness provided by Adafruit Industries. Thanks Adafruit!</p> <pre><code> column[x][y4 + rOffset] = gamma[value[0]/2] # Gamma-corrected R column[x][y4 + gOffset] = gamma[value[1]/2] # Gamma-corrected G column[x][y4 + bOffset] = gamma[value[2]/2] # Gamma-corrected B </code></pre>
0
2016-09-03T16:39:16Z
[ "python", "debugging", "raspberry-pi", "led" ]
concatinate pandas dataframe to multiindex
39,302,275
<p>I have a pandas dataframe like this </p> <pre><code>df1=pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns=list('ABC')) df1.index.name="ID1" df2=pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns=list('ABC')) df2.index.name="ID2" </code></pre> <p>so,How can I concatinate like below,this dataframe have multiindex.</p> <pre><code> A B C ID1 0 7 5 7 1 6 3 8 2 6 5 4 ID2 0 3 9 7 1 8 7 5 2 3 9 9 </code></pre> <p>I have tried 'pd.concat([df1,df2])' but multiindex hasnt created.</p>
2
2016-09-03T00:46:25Z
39,302,293
<p>Concat is correct</p> <pre><code>pd.concat([df1,df2], keys=['id1', 'id2']) </code></pre>
2
2016-09-03T00:50:03Z
[ "python", "pandas" ]
Datetime object with timezone
39,302,385
<p>How do I get an aware datetime object using the modified timestamp from a file? I've done it this way:</p> <pre><code>modified = datetime.datetime.fromtimestamp(os.path.getmtime(myfile)) isotime = modified.strftime('%Y-%m-%d %H:%M:%S %z') </code></pre> <p>but this just gets me a naive time, so %z is a blank string like: 2016-09-03 10:35:24</p> <p>I've been using this documentation, but I can't understand how to make a tzinfo object for the system timezone: <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">https://docs.python.org/2/library/datetime.html</a></p>
1
2016-09-03T01:10:16Z
39,302,542
<p>It is pain in the ass to get the current time zone using python standart library.</p> <p>Just install <a href="https://dateutil.readthedocs.io/en/stable/tz.html" rel="nofollow"><code>dateutil</code></a> package:</p> <pre><code>$ sudo pip install python-dateutil </code></pre> <p>and you can do the following:</p> <p>--</p> <pre><code>&gt;&gt;&gt; from dateutil.tz import tzlocal &gt;&gt;&gt; datetime.datetime.fromtimestamp(os.path.getmtime("file"), tz=tzlocal()) </code></pre>
1
2016-09-03T01:51:15Z
[ "python", "datetime" ]
String not in string
39,302,405
<p>So I have two strings</p> <p><code>a = "abc"</code> and <code>b = "ab"</code></p> <p>Now I am trying to find the characters in a which are not present in b</p> <p>The code that I have is : </p> <pre><code>for element in t: if element not in s: print element </code></pre> <p>This is giving some error for large strings. I have not looked into that error yet but I was wondering that another way to do the same thing would be something similar to : </p> <pre><code>if a not in b: //further code to identify the element that is not in string b </code></pre> <p>The piece of code above gives me <code>False</code> when I run it, I don't know how to identify the element which is not present in the second string.</p> <p>How do I go about this?</p>
-1
2016-09-03T01:15:24Z
39,302,410
<p>This is the sort of thing that a <code>set</code> is really good for:</p> <pre><code>&gt;&gt;&gt; a = "abc" &gt;&gt;&gt; b = "abd" &gt;&gt;&gt; set(a).difference(b) set(['c']) </code></pre> <p>This gives you items in <code>a</code> that aren't in <code>b</code>. If you want the items that only appear in one or the other, you can use <code>symmetric_difference</code>:</p> <pre><code>&gt;&gt;&gt; a = "abc" &gt;&gt;&gt; b = "abd" &gt;&gt;&gt; set(a).symmetric_difference(b) set(['c', 'd']) </code></pre> <hr> <p>Note that your code <em>should</em> work too given proper inputs:</p> <pre><code>&gt;&gt;&gt; for element in a: ... if element not in b: ... print element ... c </code></pre> <p>However, if you're dealing with large sequences, this is much less efficient and it's a bunch more code to write so I don't really recommend it.</p>
3
2016-09-03T01:17:07Z
[ "python", "string", "python-2.7" ]
How do I get a datetime object out of a YYYY-Q string?
39,302,412
<p>The <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">datetime.strptime</a> reference does not provide an option for the YYYY-Qx (with x = {1,...,4}) date format. Do I need the <a href="http://dateutil.readthedocs.io/en/stable/parser.html" rel="nofollow">dateutil.parser</a> for that?</p> <p>For my implementation, I chose the 15th of the second month as the representative date. That means, if this function receives "2016-Q3" as date, it will be resolved to "2016-08-15".</p> <pre><code>def df_quarter(self, date): ypart = datetime.datetime.strptime(date.split('-')[0], '%Y') qpart = re.sub('Q', '', date.split('-')[1]) qmid = 2+3*(int(qpart)-1) if qmid &lt; 10: qmid = "0" + str(qmid) date = str(ypart.year) + '-' + qmid + '-15' </code></pre>
0
2016-09-03T01:19:08Z
39,302,458
<p>You could simply hard-code the relationship between quarters and dates, and use <code>re.sub</code> to replace <code>Q(\d)</code> with the appropriate value:</p> <pre><code>import re def df_quarter(date): q = {'1':'02-15', '2':'05-15', '3':'08-15', '4':'11-15'} return re.sub('Q(\d)', lambda match, q=q: q[match.group(1)], date) </code></pre> <hr> <pre><code>In [36]: df_quarter('2016-Q1') Out[36]: '2016-02-15' In [35]: df_quarter('2016-Q2') Out[35]: '2016-05-15' In [34]: df_quarter('2016-Q3') Out[34]: '2016-08-15' In [37]: df_quarter('2016-Q4') Out[37]: '2016-11-15' </code></pre> <hr> <p>Or, if you want <code>df_quarter</code> to return a <code>datetime.datetime</code> object:</p> <pre><code>import re import datetime as DT def df_quarter(date): q = {'1':'02-15', '2':'05-15', '3':'08-15', '4':'11-15'} date = re.sub('Q(\d)', lambda match, q=q: q[match.group(1)], date) return DT.datetime.strptime(date, '%Y-%m-%d') </code></pre> <hr> <p>If you would rather compute the month based on a formula, you could instead use</p> <pre><code>def df_quarter(date): date = re.sub('Q(\d)', lambda match: '{:02d}-15'.format(int(match.group(1))*3-1), date) return DT.datetime.strptime(date, '%Y-%m-%d') </code></pre> <p>Notice that the format specifier <code>02d</code> replaces the integer, <code>int(match.group(1))*3-1</code> with a 2-digit string padded with a zero on the left if necessary.</p>
0
2016-09-03T01:29:16Z
[ "python", "date", "datetime" ]
Invalid Syntax Error - Average Calculator "IF" and "WHILE"
39,302,442
<p>I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.</p> <p><a href="http://i.stack.imgur.com/umYUV.png" rel="nofollow"><img src="http://i.stack.imgur.com/umYUV.png" alt="enter image description here"></a> Here's the sample output my professor defined:</p> <pre><code>SAMPLE RUN Enter test score 80 Enter test score 70 Enter test score 90 Enter test score 88 Enter test score 0 The average is 82.000% </code></pre>
-3
2016-09-03T01:26:19Z
39,302,470
<p>I've fixed your code for you. For future questions, please post your code directly in your question and indent it all by 4 spaces to properly format it. </p> <pre><code>addition_integer = 0 divison_integer = 0 while True: test = int(input("Enter test score: ")) if test == 0: break else: addition_integer += test divison_integer += 1 print("The average is {}%".format(addition_integer/divison_integer)) </code></pre> <p>Here's an explanation of what I did to fix this:</p> <p>You were looping <code>while True</code>, which is correct, however you had no way to break out of the while loop. Your line saying <code>if test == '0'</code> would never resolve to true because you're taking the input as an <code>int</code> from the user, not to mention it was out of place and didn't have proper syntax.. What I am doing in the code above is continuing to loop until the input from the user is equal to <code>0</code> (an integer, not a string). If the user inputs <code>0</code>, then we simply break out of the loop and print the average. Until then, we continue to add the input to <code>addition_integer</code> and increment <code>division_integer</code> by 1.</p> <p>All in all, you were pretty close to the solution, you just needed a few syntax changes and to be steered in the right direction as to how you can break out of an infinite loop.</p> <p>Finally, here is a test using the numbers that you've provided in your question:</p> <pre><code>Enter test score: 80 Enter test score: 70 Enter test score: 90 Enter test score: 88 Enter test score: 0 The average is 82% </code></pre>
1
2016-09-03T01:34:31Z
[ "python", "if-statement", "while-loop", "syntax-error", "average" ]
Invalid Syntax Error - Average Calculator "IF" and "WHILE"
39,302,442
<p>I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.</p> <p><a href="http://i.stack.imgur.com/umYUV.png" rel="nofollow"><img src="http://i.stack.imgur.com/umYUV.png" alt="enter image description here"></a> Here's the sample output my professor defined:</p> <pre><code>SAMPLE RUN Enter test score 80 Enter test score 70 Enter test score 90 Enter test score 88 Enter test score 0 The average is 82.000% </code></pre>
-3
2016-09-03T01:26:19Z
39,302,482
<p>The <code>if</code> statement in the image (please post the actual code in your question) is invalid. It needs a colon, i.e. <code>if test == '0':</code>. It also needs a body.</p> <p>The sample output suggests that <code>0</code> is to terminate the loop. Check for that first, before you modify <code>division_integer</code> otherwise the average will be affected. Then, when you get a <code>0</code> <em>break</em> out of the while loop with <code>break</code>, i.e.</p> <pre><code>while True: test = int(input('Enter test score:')) if test == 0: break addition_integer += test division_integer += 1 </code></pre> <p>Note that you are converting the input into an integer, but your test was for the <em>string</em> <code>"0"</code>. You need to test for the integer <code>0</code> as I show above.</p> <p>Another point, you should use a <code>try/except</code> block when converting the input into an integer so that you can catch invalid input:</p> <pre><code>while True: try: test = int(input('Enter test score:')) except ValueError: print('Invalid number entered, try again.') continue # etc. </code></pre>
2
2016-09-03T01:37:53Z
[ "python", "if-statement", "while-loop", "syntax-error", "average" ]
Invalid Syntax Error - Average Calculator "IF" and "WHILE"
39,302,442
<p>I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.</p> <p><a href="http://i.stack.imgur.com/umYUV.png" rel="nofollow"><img src="http://i.stack.imgur.com/umYUV.png" alt="enter image description here"></a> Here's the sample output my professor defined:</p> <pre><code>SAMPLE RUN Enter test score 80 Enter test score 70 Enter test score 90 Enter test score 88 Enter test score 0 The average is 82.000% </code></pre>
-3
2016-09-03T01:26:19Z
39,302,531
<p>Alternative answer </p> <p>Use a list, sum and divide. Same concept, compare test inside the while loop in order to break out of it. Also check if you get valid input that can be made an integer with a try/except. </p> <p>Additionally, beware of the division by zero </p> <pre><code>values = [] while True: try: test = int(input('Enter test score:')) if test == 0: break values.append(test) except: break total = len(values) avg = 0 if total == 0 else 1.0 * sum(values) / total print("The average is", avg) </code></pre>
0
2016-09-03T01:50:00Z
[ "python", "if-statement", "while-loop", "syntax-error", "average" ]
How to redirect a Django template and use the 'Next' variable?
39,302,467
<p>I am using Django's built in login view as can be seen in the following snippets:</p> <p><strong>urls.py</strong></p> <pre><code> url(r'^login$',login,{'template_name': 'login.html'},name="login"), </code></pre> <p><strong>template.html</strong></p> <pre><code>&lt;form method="post" action="{% url 'login' %}"&gt; {% csrf_token %} &lt;table&gt; &lt;tr&gt; &lt;td&gt;{{ form.username.label_tag }}&lt;/td&gt; &lt;td&gt;{{ form.username }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{{ form.password.label_tag }}&lt;/td&gt; &lt;td&gt;{{ form.password }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type="submit" value="login" /&gt; &lt;input type="hidden" name="next" value="{{ next }}" /&gt; &lt;/form&gt; </code></pre> <p>How can I use the next variable to redirect to a URL different than the default <em>/accounts/profile/</em> that django redirects to? I know of people referring to the settings.py file but I am wondering how I can utilize the next variable to do this?</p> <p>(I'm not really sure of how the next variable works even after referring to documentation, an explanation of this would be much appreciated)</p>
0
2016-09-03T01:34:07Z
39,341,203
<p>if you are using django login view ie,</p> <pre><code>from django.contrib.auth.views import login </code></pre> <p>you just need to pass the next url to the template. so when the request is sent to the login view , the code is in place to redirect to that url. is no next url is found</p> <pre><code>settings.LOGIN_REDIRECT_URL is used </code></pre> <p>you can simple pass the next url just like, </p> <pre><code>&lt;form method="post" action="{% url 'login' %}?next={{next_url}}"&gt; </code></pre> <p>Pass the "next_url" value via context. </p> <p>The next case, if you need the next url redirection for any of you custom views, simple write a code inside the view to get next url and after doing the job inside the view you can redirect to the next url.</p> <pre><code>from django.utils.http import is_safe_url def your_view(request): # do your codes redirect_to = request.GET.get(next, '') # use get or Post as per your requirement if is_safe_url(url=redirect_to, host=request.get_host()): HttpResponseRedirect(redirect_to) else: # your response </code></pre> <p>To clear your doubt how the next variable works: In the above view we get a get a http request and if we have passed the next url as query params. we will be getting it in the view. "request.GET.get(next, '')" will get you the next url you sent from view. from view level you can do the functionalities you need and then if the next url is present and valid you can use HttpResponseRedirect to redirect to the next url. </p> <p>For login ref: <a href="http://stackoverflow.com/questions/806835/django-redirect-to-previous-page-after-login">Django: Redirect to previous page after login</a> </p>
0
2016-09-06T05:26:40Z
[ "python", "django", "django-forms", "django-templates", "django-views" ]
How to access DataFrame column created with DataFrame.groupby
39,302,498
<p>After creating a DataFrame with a column 'a' having the duplicated cell values:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [1,2,2,3,3,3,3], 'b':[1,2,3,4,5,6,7], 'c':[8,9,10,11,12,13,14]}) </code></pre> <p><a href="http://i.stack.imgur.com/OlBbV.png" rel="nofollow"><img src="http://i.stack.imgur.com/OlBbV.png" alt="enter image description here"></a></p> <p>I proceed by creating a copy of it where I consolidate the duplicated cells in column 'a' while summing the values of other cells. I am using <code>groupby</code> method to achieve this, like so:</p> <pre><code>groupDf = df.groupby('a', axis=0).sum() </code></pre> <p><a href="http://i.stack.imgur.com/Pullb.png" rel="nofollow"><img src="http://i.stack.imgur.com/Pullb.png" alt="enter image description here"></a></p> <p>After the consolidated version of the DataFrame is created I want to access its columns ['a']:</p> <pre><code>print(groupDf['a]) </code></pre> <p>and I am getting the <code>KeyError</code> notifying me that ['a'] column does not exist. Printing the column names with <code>groupDf.columns</code> returns only the column 'b' and the column 'c': <code>Index(['b', 'c'], dtype='object')</code></p> <p>How should I access the column 'a? </p>
1
2016-09-03T01:41:21Z
39,302,552
<p>After the <code>groupby</code>, the grouped column turns into an index, you can access it either by call <code>.index</code> or <code>reset_index</code> and then access it as a normal column, i.e the following two methods:</p> <pre><code>df.groupby('a', axis=0).sum().reset_index() # a b c # 0 1 1 8 # 1 2 5 19 # 2 3 22 50 df.groupby('a', axis=0).sum().index # Int64Index([1, 2, 3], dtype='int64') </code></pre>
4
2016-09-03T01:53:15Z
[ "python", "pandas" ]
Adding URL parameters to form action in flask
39,302,500
<p>Is there a way to pass an additional list of parameters outside of a form when the form is submit? </p> <p>I know I can create a new hidden input field in the form for each parameter I want to pass through the form, but is there another way? I tried to add parameters directly to the form action but that doesn't work. The code in its entirety can be found here:</p> <pre><code>from flask import Flask, request import os app = Flask(__name__) @app.route('/') def index(): print request.args return "&lt;form action='/?foo=bar'&gt;&lt;input name='variable' type='text' /&gt;&lt;/form&gt;" if __name__ == '__main__': port = int(os.environ.get('PORT', 8080)) app.run('0.0.0.0', debug=True, port=port) </code></pre> <p>Clarifying question based on feedback from comments:</p> <p>Using this code, when I type "123" into the textbox and hit enter, I see that the url is <code>http://wardrobe-plus-jeffhou.c9users.io/?variable=123</code>.</p> <p>What I want is <code>http://wardrobe-plus-jeffhou.c9users.io/?foo=bar&amp;variable=12‌​3</code>.</p>
1
2016-09-03T01:41:40Z
39,302,846
<p>I think you should show what you input and what you want output.</p> <p>In your code, the <code>index()</code> function default accept the <code>GET</code> method, so if you want to post data from form add the <code>methods</code> to the <code>@app.route()</code>.</p> <pre><code>@app.route('/', methods=['GET', 'POST']) </code></pre> <p>and, the form also should add post method.</p> <pre><code>&lt;form method='post', action='/'&gt;&lt;/form&gt; </code></pre>
0
2016-09-03T03:00:53Z
[ "python", "forms", "flask" ]
Time formats match but still getting error. ValueError: time data 'Time' does match format specified pd.to_datetime
39,302,508
<p>my data column looks like this:</p> <pre><code>0 Time 1 2014-07-28 00:17:35 2 2014-07-28 00:18:05 3 2014-07-28 01:50:54 4 2014-07-28 01:51:24 5 2014-07-28 01:53:57 6 2014-07-28 01:54:56 </code></pre> <p>my code looks like this:</p> <pre><code>df['Epoch'] = pd.to_datetime(df['Time'], format = "%Y-%m-%d %H:%M:%S") </code></pre> <p>and my error looks like this:</p> <blockquote> <p>ValueError: time data 'Time' does match format specified</p> </blockquote> <p>really not sure if I'm missing something here. Please help.</p>
-1
2016-09-03T01:44:37Z
39,302,807
<p>Your dataframe is wrongly loaded: your header is interpreted as a row and is the first row of your dataframe. <code>pd.to_datetime</code> tries to transform the string 'Time' found row 0.</p> <p>Load correctly your dataframe by getting the row 0 loaded as a header instead.</p> <p>Something like this can move the firs row as colum titles and delete it as a row:</p> <pre><code>df.columns = df.ix[0] df = df.drop(0) </code></pre>
0
2016-09-03T02:53:35Z
[ "python", "pandas", "time", "python-datetime" ]
Django, send dictionary to template
39,302,512
<p>Is it possible to send a dictionary to a template. And use the django/python magic to work on it client side?</p> <p>The view function</p> <pre><code>def index(request): context = { 'users' : users, 'investments' : { 'one' : 1, 'two' : 2 }, } return render(request, 'index.html', context) </code></pre> <p>And the html</p> <pre><code>{% if investments %} &lt;h1&gt;{{ investments['one'] }}&lt;/h1&gt; #&lt;---- something like that. {% endif %} </code></pre>
1
2016-09-03T01:46:19Z
39,302,536
<p>The code below works in Flask-Jinja, and I believe should work in Django:</p> <pre><code>{% if investments %} &lt;h1&gt;{{ investments.one }}&lt;/h1&gt; {% endif %} </code></pre>
3
2016-09-03T01:50:36Z
[ "python", "django" ]
Decode a hex string into Chinese characters
39,302,515
<p>I have a hex code: %E7%B5%99. I want to convert it into Chinese characters.</p> <pre><code>print ("%E7%B5%99".decode('utf-8')) </code></pre> <p>This doesn't seem to work.</p> <p>It should give the answer: 絙</p>
0
2016-09-03T01:46:47Z
39,302,533
<p>You need to "unquote" the percent encoded string first. Then decode from UTF8:</p> <pre><code>&gt;&gt;&gt; s = "%E7%B5%99" &gt;&gt;&gt; print urllib.unquote(s).decode('utf8') 絙 </code></pre>
3
2016-09-03T01:50:10Z
[ "python", "python-2.7" ]
Time-based sliding window and measuring (change of) data arrival rate
39,302,567
<p>I'm trying to implement a time-based sliding window (in Python), i.e., a data sources inserts new data items, and items older than, say, 1h are automatically removed. On top of that, I need to measures the rate, or rather the change of rate the data sources inserts items.</p> <p>My question is kind of two-fold. First, how is the best way to implement a time-based window. In my currently, probably naive solution, I simply use a Python list <code>window = []</code>. In case of a new data <code>item</code>, I append the item with the current timestamp: <code>window.append((current_time, item))</code>. Then, using a timer, every 1sec I <code>pop</code> all first elements with a timestamp older than the current (timestamp-1h):</p> <pre><code>threshold = int(time.time()*1000) - self.WINDOW_SIZE_IN_MS while True: try: if window[0][0] &lt; threshold: del self.word_lists[0] else: break except: break </code></pre> <p>While this works, I wonder if there are more clever solutions to this. </p> <p>More importantly, what would be a good way to measure the change of rate data items enter the window. Here, I have no good idea how to approach this, at least none that sounds also efficient. Something very naive I had in mind: I split the 1h-window in 20 intervals each 5min and count the number of items. If the most recent 5min-interval conains significantly more items than the average of the 20 intervals, I say there is a burst. But I would have to do this every, say, 1min. This sounds not efficient and there are a lot of parameters. </p> <p>In short, I need to measure the acceleration in which new items enter my window. Are there best-practices approaches for this?</p>
0
2016-09-03T01:57:31Z
39,304,218
<p>For the first part, it is more efficient to check for expired items and remove them when you receive a new item to add. That is, don't bother with a timer which wakes up the process for no reason once a second--just piggyback the maintenance work when real work is happening.</p> <p>For the second part, the entire 1 hour has a known length. Store an integer which is the index in the list of five minutes ago. You can maintain this when doing an insert, and you know you only have to move it forward.</p> <p>Putting it all together, pseudo-code:</p> <pre><code>window = [] recent_index = 0 def insert(time, item): while window and window[0][0] &lt; time - timedelta(hours=1): window.pop() recent_index -= 1 while window[recent_index][0] &lt; time - timedelta(minutes=5): recent_index += 1 window.append((time, item)) return float(len(window) - recent_index) / len(window) </code></pre> <p>The above function returns what fraction of items from the past hour arrived in the past five minutes. Over 20 or 50%, say, and you have a burst.</p>
0
2016-09-03T07:04:53Z
[ "python", "list", "queue", "sliding-window" ]
python - Mount EBS volume using boto3
39,302,594
<p>I want to use AWS Spot instances to train Neural Networks. To prevent loss of the model when the spot instance is terminated, I plan to create a snapshot of the EBS volume, make a new volume and attach it to a reserved instance. How can I mount, or make the EBS volume available using python &amp; boto3. </p> <p>These are the steps used to <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html" rel="nofollow">make the volume available</a> on Linux, but I want to automate the process so that I don't need to SSH into the instance every time. Here is the code I use to attach the volume - </p> <pre><code>import boto3 ec2 = boto3.resource('ec2') spot = ec2.Instance('i-9a8f5082') res = ec2.Instance('i-86e65a13') snapshot = ec2.create_snapshot(VolumeId="vol-5315f7db", Description="testing spot instances") volume = ec2.create_volume(SnapshotId=snapshot.id, AvailabilityZone='us-west-2a') res.attach_volume(VolumeId="vol-5315f7db", Device='/dev/sdy') snapshot.delete() </code></pre>
1
2016-09-03T02:04:10Z
39,302,706
<p>You have to perform those steps in the operating system. You can't perform those steps via the AWS API (Boto3). Your best bet is to script those steps and then kick off the script somehow via Boto3, possibly using the AWS SSM service.</p>
1
2016-09-03T02:28:17Z
[ "python", "linux", "amazon-web-services", "boto3" ]
python - Mount EBS volume using boto3
39,302,594
<p>I want to use AWS Spot instances to train Neural Networks. To prevent loss of the model when the spot instance is terminated, I plan to create a snapshot of the EBS volume, make a new volume and attach it to a reserved instance. How can I mount, or make the EBS volume available using python &amp; boto3. </p> <p>These are the steps used to <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html" rel="nofollow">make the volume available</a> on Linux, but I want to automate the process so that I don't need to SSH into the instance every time. Here is the code I use to attach the volume - </p> <pre><code>import boto3 ec2 = boto3.resource('ec2') spot = ec2.Instance('i-9a8f5082') res = ec2.Instance('i-86e65a13') snapshot = ec2.create_snapshot(VolumeId="vol-5315f7db", Description="testing spot instances") volume = ec2.create_volume(SnapshotId=snapshot.id, AvailabilityZone='us-west-2a') res.attach_volume(VolumeId="vol-5315f7db", Device='/dev/sdy') snapshot.delete() </code></pre>
1
2016-09-03T02:04:10Z
39,326,511
<p>What's wrong with sending and execute ssh script remotely? Assume you are using ubuntu , i.e. </p> <pre><code>ssh -i your.pem ubuntu@ec2_name_or_ip 'sudo bash -s' &lt; mount_script.sh </code></pre> <p>If you attach tag to those resources, you can later use boto3 to inquired the resources by universal tag name, instead tied to the specific static id. </p>
0
2016-09-05T08:26:43Z
[ "python", "linux", "amazon-web-services", "boto3" ]
How to decode a text file
39,302,602
<p>I have this code here and it work perfectly.</p> <pre><code># encoding=utf8 #Import the necessary methods from tweepy library import sys from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener reload(sys) sys.setdefaultencoding('utf8') #Variables that contains the user credentials to access Twitter API access_token = "" access_token_secret = "" consumer_key = "" consumer_secret = "" #This is a basic listener that just prints received tweets to stdout. class StdOutListener(StreamListener): def on_data(self, data): #save data with open('debate_data.txt', 'a') as tf: tf.write((data).decode('unicode-escape').encode('utf-8')) return True def on_error(self, status): print status if __name__ == '__main__': #This handles Twitter authetification and the connection to Twitter Streaming API l = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, l) #This line filter Twitter Streams to capture data by the keywords: 'Bernier', 'Rossello', 'Bernabe' stream.filter(track=['Bernier', 'Rosselló', 'Rossello', 'Bernabe', 'Lúgaro', 'Lugaro', 'María de Lourdes', 'Maria de Lourdes', 'Cidre']) </code></pre> <p>But when I run this other piece of code I get the wrong answer.</p> <pre><code>import json import io #save the tweets to this path tweets_data_path = 'debate_data.txt' tweets_data = [] with io.open(tweets_data_path, 'r') as tweets_file: for line in tweets_file: try: tweet = json.loads(line) tweets_data.append(tweet) except: continue print len(tweets_data) </code></pre> <p>There are 42,188 Tweets on that file, but when I run the code Im only getting 291. I think is something with the encoding/decoding but I cant figure out what. Any help would be greatly appreciate.</p> <p>I ran this example without any of the encoding/decoding and it worked perfectly. </p> <p><a href="http://adilmoujahid.com/posts/2014/07/twitter-analytics/" rel="nofollow">http://adilmoujahid.com/posts/2014/07/twitter-analytics/</a></p>
0
2016-09-03T02:06:09Z
39,302,755
<p>The reason of only getting 291 is the <code>json.loads()</code> throw some errors and <code>except</code> continue it.</p> <p>I suggest you print the error just like:</p> <pre><code>except Exception as err: print err continue </code></pre> <p>now you know the error reason, and solve it.</p> <p>Are you sure the format of data inside <code>debate_data.txt</code> are <code>json</code> ? </p>
2
2016-09-03T02:40:00Z
[ "python", "twitter", "encoding", "tweepy" ]
How to decode a text file
39,302,602
<p>I have this code here and it work perfectly.</p> <pre><code># encoding=utf8 #Import the necessary methods from tweepy library import sys from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener reload(sys) sys.setdefaultencoding('utf8') #Variables that contains the user credentials to access Twitter API access_token = "" access_token_secret = "" consumer_key = "" consumer_secret = "" #This is a basic listener that just prints received tweets to stdout. class StdOutListener(StreamListener): def on_data(self, data): #save data with open('debate_data.txt', 'a') as tf: tf.write((data).decode('unicode-escape').encode('utf-8')) return True def on_error(self, status): print status if __name__ == '__main__': #This handles Twitter authetification and the connection to Twitter Streaming API l = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, l) #This line filter Twitter Streams to capture data by the keywords: 'Bernier', 'Rossello', 'Bernabe' stream.filter(track=['Bernier', 'Rosselló', 'Rossello', 'Bernabe', 'Lúgaro', 'Lugaro', 'María de Lourdes', 'Maria de Lourdes', 'Cidre']) </code></pre> <p>But when I run this other piece of code I get the wrong answer.</p> <pre><code>import json import io #save the tweets to this path tweets_data_path = 'debate_data.txt' tweets_data = [] with io.open(tweets_data_path, 'r') as tweets_file: for line in tweets_file: try: tweet = json.loads(line) tweets_data.append(tweet) except: continue print len(tweets_data) </code></pre> <p>There are 42,188 Tweets on that file, but when I run the code Im only getting 291. I think is something with the encoding/decoding but I cant figure out what. Any help would be greatly appreciate.</p> <p>I ran this example without any of the encoding/decoding and it worked perfectly. </p> <p><a href="http://adilmoujahid.com/posts/2014/07/twitter-analytics/" rel="nofollow">http://adilmoujahid.com/posts/2014/07/twitter-analytics/</a></p>
0
2016-09-03T02:06:09Z
39,302,895
<p>As agnewee said, I also recommend:</p> <pre><code>try: tweet = json.loads(line) except Exception as err: print err # or use log to see what happen else: tweets_data.append(tweet) </code></pre>
2
2016-09-03T03:14:45Z
[ "python", "twitter", "encoding", "tweepy" ]
how to add column by using other column's conditions
39,302,666
<p>I have a dataframe.</p> <pre><code>df=pd.DataFrame({'month':np.arange(1,8)}) </code></pre> <p>So,I would like to add column by using 'month' columns</p> <pre><code>if 'month'=1,2,3 the elements = 'term1' 'month'=4,5 the elements = 'term2' 'month'=6,7 the elements = 'term3' </code></pre> <p>I would like to get the result below</p> <pre><code> month term 0 1 term1 1 2 term1 2 3 term1 3 4 term2 4 5 term2 5 6 term3 6 7 term3 </code></pre> <p>How can I get this result? maybe we could get this result easy and simple way....</p>
0
2016-09-03T02:19:52Z
39,302,722
<p>Use <code>numpy.where</code> and <code>Series.isin()</code> method could be one of the options to do it:</p> <pre><code>import numpy as np import pandas as pd df["term"] = np.where(df.month.isin([1,2,3]), "term1", \ np.where(df.month.isin([4,5]), "term2", "term3")) df # month term #0 1 term1 #1 2 term1 #2 3 term1 #3 4 term2 #4 5 term2 #5 6 term3 #6 7 term3 </code></pre>
1
2016-09-03T02:32:25Z
[ "python", "pandas" ]
how to add column by using other column's conditions
39,302,666
<p>I have a dataframe.</p> <pre><code>df=pd.DataFrame({'month':np.arange(1,8)}) </code></pre> <p>So,I would like to add column by using 'month' columns</p> <pre><code>if 'month'=1,2,3 the elements = 'term1' 'month'=4,5 the elements = 'term2' 'month'=6,7 the elements = 'term3' </code></pre> <p>I would like to get the result below</p> <pre><code> month term 0 1 term1 1 2 term1 2 3 term1 3 4 term2 4 5 term2 5 6 term3 6 7 term3 </code></pre> <p>How can I get this result? maybe we could get this result easy and simple way....</p>
0
2016-09-03T02:19:52Z
39,302,910
<p>I would go for a declarative way through a dict, simple to read and easy to apply. You can generate your replace condition dictionary programmatically if the replacement conditions become large or depends on other inputs:</p> <pre><code>conditions = {1:'term1', 2:'term1', 3:'term1', 4:'term2', 5:'term2', 6:'term3', 7:'term3'} df['term'] = df.replace(conditions) df month term 0 1 term1 1 2 term1 2 3 term1 3 4 term2 4 5 term2 5 6 term3 6 7 term3 </code></pre>
1
2016-09-03T03:18:31Z
[ "python", "pandas" ]
How to copy one DataFrame column in to another Dataframe if their indexes values are the same
39,302,670
<p>After creating a DataFrame with some duplicated cell values in column with the name 'keys':</p> <pre><code>import pandas as pd df = pd.DataFrame({'keys': [1,2,2,3,3,3,3],'values':[1,2,3,4,5,6,7]}) </code></pre> <p><a href="http://i.stack.imgur.com/M9c0P.png" rel="nofollow"><img src="http://i.stack.imgur.com/M9c0P.png" alt="enter image description here"></a></p> <p>I go ahead and create two more DataFrames which are the consolidated versions of the original DataFrame <code>df</code>. Those newly created DataFrames will have no duplicated cell values under the 'keys' column:</p> <pre><code>df_sum = df_a.groupby('keys', axis=0).sum().reset_index() df_mean = df_b.groupby('keys', axis=0).mean().reset_index() </code></pre> <p>As you can see <code>df_sum['values']</code> cells values were all summed together. While <code>df_mean['values']</code> cell values were averaged with <code>mean()</code> method. Lastly I rename the 'values' column in both dataframes with:</p> <pre><code>df_sum.columns = ['keys', 'sums'] df_mean.columns = ['keys', 'means'] </code></pre> <p><a href="http://i.stack.imgur.com/oKmxV.png" rel="nofollow"><img src="http://i.stack.imgur.com/oKmxV.png" alt="enter image description here"></a></p> <p>Now I would like to copy the <code>df_mean['means']</code> column into the dataframe <code>df_sum</code>.</p> <p>How to achieve this?</p> <p>The Photoshoped image below illustrates the dataframe I would like to create. Both 'sums' and 'means' columns are merged into a single DataFrame:</p> <p><a href="http://i.stack.imgur.com/Ws6n9.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ws6n9.png" alt="enter image description here"></a></p>
2
2016-09-03T02:20:23Z
39,302,752
<p>There are several ways to do this. Using the <code>merge</code> function off the dataframe is the most efficient.</p> <pre><code>df_both = df_sum.merge(df_mean, how='left', on='keys') df_both Out[1]: keys sums means 0 1 1 1.0 1 2 5 2.5 2 3 22 5.5 </code></pre>
3
2016-09-03T02:38:43Z
[ "python", "pandas" ]
How to copy one DataFrame column in to another Dataframe if their indexes values are the same
39,302,670
<p>After creating a DataFrame with some duplicated cell values in column with the name 'keys':</p> <pre><code>import pandas as pd df = pd.DataFrame({'keys': [1,2,2,3,3,3,3],'values':[1,2,3,4,5,6,7]}) </code></pre> <p><a href="http://i.stack.imgur.com/M9c0P.png" rel="nofollow"><img src="http://i.stack.imgur.com/M9c0P.png" alt="enter image description here"></a></p> <p>I go ahead and create two more DataFrames which are the consolidated versions of the original DataFrame <code>df</code>. Those newly created DataFrames will have no duplicated cell values under the 'keys' column:</p> <pre><code>df_sum = df_a.groupby('keys', axis=0).sum().reset_index() df_mean = df_b.groupby('keys', axis=0).mean().reset_index() </code></pre> <p>As you can see <code>df_sum['values']</code> cells values were all summed together. While <code>df_mean['values']</code> cell values were averaged with <code>mean()</code> method. Lastly I rename the 'values' column in both dataframes with:</p> <pre><code>df_sum.columns = ['keys', 'sums'] df_mean.columns = ['keys', 'means'] </code></pre> <p><a href="http://i.stack.imgur.com/oKmxV.png" rel="nofollow"><img src="http://i.stack.imgur.com/oKmxV.png" alt="enter image description here"></a></p> <p>Now I would like to copy the <code>df_mean['means']</code> column into the dataframe <code>df_sum</code>.</p> <p>How to achieve this?</p> <p>The Photoshoped image below illustrates the dataframe I would like to create. Both 'sums' and 'means' columns are merged into a single DataFrame:</p> <p><a href="http://i.stack.imgur.com/Ws6n9.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ws6n9.png" alt="enter image description here"></a></p>
2
2016-09-03T02:20:23Z
39,302,777
<p>I think <code>pandas.merge()</code> is the function you are looking for. Like <code>pd.merge(df_sum, df_mean, on = "keys")</code>. Besides, this result can also be summarized on one <code>agg</code> function as following:</p> <pre><code>df.groupby('keys')['values'].agg(['sum', 'mean']).reset_index() # keys sum mean #0 1 1 1.0 #1 2 5 2.5 #2 3 22 5.5 </code></pre>
2
2016-09-03T02:45:51Z
[ "python", "pandas" ]
SyntaxError: non-keyword arg after keyword arg, with no apparent reason
39,302,705
<p>I have a .dat file which I first want to convert into a .csv file and then plot some of the rows against time, my scripts is as follows :</p> <pre><code>import pandas as pd import numpy as np from sys import argv from pylab import * import csv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() # read flash.dat to a list of lists datContent = [i.strip().split() for i in open("./flash.dat").readlines()] # write it as a new CSV file with open("./flash.csv", "wb") as f: writer = csv.writer(f) writer.writerows(datContent) def your_func(row): return (row['global_beta']) columns_to_keep = ['#time', 'global_beta', 'max_dens', 'max_temp', 'dens@max_temp'] dataframe = pd.read_csv("./flash.csv", usecols=columns_to_keep) dataframe['Nuclear_Burning'] = dataframe.apply(your_func, axis=1) pd.set_option('display.height', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) dataframe.plot(x='#time', 'Nuclear_Burning', style='r') print dataframe show() </code></pre> <p>I executed the script with <code>python csv_flash_dat_file.py flash.dat</code> and got the following error :</p> <pre><code>File "csv_flash_dat_file.py", line 46 dataframe.plot(x='#time', 'Nuclear_Burning', style='r') SyntaxError: non-keyword arg after keyword arg </code></pre> <p>I don't see the apparent reason to find the error, please help me fix this.</p>
2
2016-09-03T02:28:16Z
39,302,727
<p>It's just what it says. You can't pass non-keyword arguments after keyword arguments. If you have something like x='#time', that's a keyword argument, and all of those have to come at the end of the argument list.</p>
4
2016-09-03T02:34:04Z
[ "python", "csv", "pandas" ]
SyntaxError: non-keyword arg after keyword arg, with no apparent reason
39,302,705
<p>I have a .dat file which I first want to convert into a .csv file and then plot some of the rows against time, my scripts is as follows :</p> <pre><code>import pandas as pd import numpy as np from sys import argv from pylab import * import csv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() # read flash.dat to a list of lists datContent = [i.strip().split() for i in open("./flash.dat").readlines()] # write it as a new CSV file with open("./flash.csv", "wb") as f: writer = csv.writer(f) writer.writerows(datContent) def your_func(row): return (row['global_beta']) columns_to_keep = ['#time', 'global_beta', 'max_dens', 'max_temp', 'dens@max_temp'] dataframe = pd.read_csv("./flash.csv", usecols=columns_to_keep) dataframe['Nuclear_Burning'] = dataframe.apply(your_func, axis=1) pd.set_option('display.height', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) dataframe.plot(x='#time', 'Nuclear_Burning', style='r') print dataframe show() </code></pre> <p>I executed the script with <code>python csv_flash_dat_file.py flash.dat</code> and got the following error :</p> <pre><code>File "csv_flash_dat_file.py", line 46 dataframe.plot(x='#time', 'Nuclear_Burning', style='r') SyntaxError: non-keyword arg after keyword arg </code></pre> <p>I don't see the apparent reason to find the error, please help me fix this.</p>
2
2016-09-03T02:28:16Z
39,302,729
<p>The argument 'Nuclear_Burning' follows a keyword argument <code>x</code>. Once you start using keywords in an argument list, you have to keep on using keyword arguments.</p>
3
2016-09-03T02:34:09Z
[ "python", "csv", "pandas" ]
Tkinter TypeError: setvar() takes exactly 1 argument (2 given)
39,302,813
<p>I am writing a GUI program with Tkinter. Everything runs smoothly except for the key bindings. When I test themI get</p> <blockquote> <p>"TypeError: setvar() takes exactly 1 argument (2 given)"</p> </blockquote> <p>The problem is that I am passing no arguments in these instances so I don't understand where the issue lies. I jury rigged it by adding an extra argument to the function in question. This makes the binding work, but causes the buttons that share the command to kick back the inverse type error</p> <blockquote> <p>"TypeError: setvar() takes exactly 2 arguments (1 given)"</p> </blockquote> <p>The code is below. </p> <p>The bindings in question are in lines: 18, 27, 186, 187, 212, 230.</p> <p>They call the methods: manipulate.setvar(), manipulate.searching(), manipulate.stuff() and manipulate.newent()</p> <pre><code>#!/usr/bin/python2.7 from Tkinter import * import ttk import os import json global inventory global where where = False class widgets: def partnumber(self, parent, mode): global PN do = manipulate() PN_in = ttk.Entry(parent, width=11, textvariable=PN) if mode == 1: PN_in.bind('&lt;1&gt;', do.setvar) PN_in.grid(column=1, row=1, sticky=(W, E, S)) ttk.Label(parent, text='Part#').grid(column=1, row=2, sticky=(N, W)) def description(self, parent, mode): global DESC do = manipulate() DESC_in = ttk.Entry(parent, width=20, textvariable=DESC) if mode == 1: DESC_in.bind('&lt;1&gt;', do.setvar) DESC_in.grid(column=2, row=1, sticky=(E, S)) ttk.Label(parent, text='Description').grid(column=2, row=2, sticky=(N, W)) def quantity(self, parent): global QTY QTY_in = ttk.Entry(parent, width=3, textvariable=QTY) QTY_in.grid(column=3, row=1, sticky=(S)) ttk.Label(parent, text='Qty.').grid(column=3, row=2, sticky=(N)) def cost(self, parent): global COST COST_in = ttk.Entry(parent, width=6, textvariable=COST) COST_in.grid(column=4, row=1, sticky=(S)) ttk.Label(parent, text='Cost').grid(column=4, row=2, sticky=(N)) def quanchangebox(self, parent): global MANQUAN MANQUAN_in = Spinbox(parent, from_=1, to=10, textvariable=MANQUAN) MANQUAN_in.pack() class manipulate: global name name = str('BNEIDATA.txt') def searching(self): do = manipulate() do.search(0) def changevar(self, PN): item = inventory[PN.get()] DESC.set(item[0]) QTY.set(item[1]) COST.set(item[2]) def getresults(self): global result, RESULT, inventory, PN, DESC, QTY, COST hit = inventory[PN.get()] do = manipulate() do.changevar(PN) bit = str(PN.get()) result.insert(0, bit) bit = str(hit[0]) RESULT.insert(0, bit) result.activate(1) def search(self, mode): global inventory, PN, DESC do = manipulate() do.load() popup = boxes() if inventory.get(PN.get(), False) != False: do.getresults() if mode == 1: popup.howmany(mode) if mode == 2: popup.howmany(mode) if inventory.get(PN.get(), False) == False: ghostdict = {} for key in iter(inventory): entry = inventory[key] ghostdict[entry[0].encode()] = key if ghostdict.get(DESC.get(), False) != False: PN.set(ghostdict[DESC.get()]) do.search(mode) if ghostdict.get(DESC.get(), False) == False: popup = boxes() popup.additem() def newent(self): do = manipulate() global addbox, PN, DESC, QTY, COST temp = [DESC.get(), QTY.get(), COST.get()] inventory[PN.get()] = temp do.writ() addbox.destroy() def writ(self): global inventory os.remove(name) with open(name, 'a') as datafile: datafile.write(json.dumps(inventory)) reset = manipulate() reset.setvar() def create(self): with open(name, 'a') as datafile: bogusfirstentry = {'049007042':['Nylon Bushing', '75', '.47']} datafile.write(json.dumps(bogusfirstentry)) def find(self, name, breed, path): global where if breed == 1: for root, dirs, files in os.walk(path): if name in files: where = root if breed == 2: for root, dirs, files in os.walk(path): if name in dirs: where = os.path.join(root, name) def load(self): with open(name, 'r') as datafile: temp = datafile.read() global inventory inventory = json.loads(temp) ghostdict = {} for key in iter(inventory): entry=inventory[key] ghostdict[key] = [entry[0].encode(), entry[1], entry[2]] inventory = ghostdict def setvar(self): global PN, DESC, QTY, COST PN.set('') DESC.set('') QTY.set(0) COST.set(0) def recieve(self): do = manipulate() do.search(1) def use(self): do = manipulate() do.search(2) def quan_up(self): global MANQUAN, PN, inventory, quanbox do = manipulate() quan = inventory[PN.get()] temp = [quan[0], (quan[1]+MANQUAN.get()), quan[2]] inventory[PN.get()] = temp do.writ() quanbox.destroy() do.setvar() def quan_dn(self): global MANQUAN, PN, inventory, quanbox do = manipulate() quan = inventory[PN.get()] temp = [quan[0], (quan[1]-MANQUAN.get()), quan[2]] inventory[PN.get()] = temp do.writ() quanbox.destroy() do.setvar() def stuff(self): global result, RESULT, PN do = manipulate() PN.set(result.get(result.curselection()[0])) do.changevar(PN) class boxes: def main(self): do = manipulate() root = Tk() root.title('BNE Inventory Database') root.bind('&lt;Return&gt;', do.searching) root.bind('&lt;BackSpace&gt;', do.setvar) mainframe = ttk.Frame(root, padding='3 3 3 3') mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) global result, RESULT, PN, DESC, QTY, COST PN, DESC, QTY, COST = StringVar(), StringVar(), IntVar(), DoubleVar() field = widgets() field.partnumber(mainframe, 1) field.description(mainframe, 1) field.quantity(mainframe) field.cost(mainframe) ttk.Button(mainframe, text='Search', command=do.searching).grid(column=3, row=6, sticky=(W, E, N)) ttk.Button(mainframe, text='Recieved', command=do.recieve).grid(column=3, row=6, sticky=(W, E, S)) ttk.Button(mainframe, text='Adj Cost', command=root.destroy).grid(column=4, row=6, sticky=(W, E, N)) ttk.Button(mainframe, text='Used', command=do.use).grid(column=3, row=6, sticky=(W, E)) ttk.Button(mainframe, text='Clear Fields', command=do.setvar).grid(column=4, row=6, sticky=(W, E, S)) ttk.Button(mainframe, text='Reports', command=root.destroy).grid(column=4, row=6, sticky=(W, E)) RESULT = Listbox(mainframe, height=5) RESULT.grid(column=2, row=6, sticky=(W, E, S)) result = Listbox(mainframe, height=5, width=11) result.grid(column=1, row=6, sticky=(W, E, S,)) result.bind('&lt;&lt;ListboxSelect&gt;&gt;', do.stuff) root.mainloop() def additem(self): global PN, DESC, QTY, COST, addbox addbox = Toplevel() addbox.title('Add New Item') addboxframe = ttk.Frame(addbox, padding='3 3 3 3') addboxframe.grid(column=0, row=0, sticky=(N, W, E, S)) addboxframe.columnconfigure(0, weight=1) addboxframe.rowconfigure(0, weight=1) field = widgets() field.partnumber(addboxframe, 0) field.description(addboxframe, 0) field.quantity(addboxframe) field.cost(addboxframe) do = manipulate() addbox.bind('&lt;Return&gt;', do.newent) ttk.Button(addboxframe, text='Add New Item', command=do.newent).grid(columnspan=5, row=3, sticky=(W, E)) def howmany(self, mode): global MANQUAN, quanbox field = widgets() do = manipulate() MANQUAN = IntVar() quanbox = Toplevel() quanboxframe = ttk.Frame(quanbox, padding='3 3 3 3') quanboxframe.grid(column=0, row=0, sticky=(N, W, E, S)) quanboxframe.columnconfigure(0, weight=1) quanboxframe.rowconfigure(0, weight=1) field.quanchangebox(quanboxframe) if mode == 1: quanbox.title('Item(s) Recieved') ttk.Button(quanboxframe, text=' + Parts', command=do.quan_up).pack() if mode == 2: quanbox.title('Item(s) Used') ttk.Button(quanboxframe, text=' - Parts', command=do.quan_dn).pack() if __name__ == '__main__': check = manipulate() gui = boxes() check.find('BNEIDATA.txt', 1, '/') if where == False: check.create() check.load() if where != False: check.load() gui.main() </code></pre>
0
2016-09-03T02:54:22Z
39,302,909
<p>When you bind an event to an object-oriented handler:</p> <pre><code>PN_in.bind('&lt;1&gt;', do.setvar) </code></pre> <p>it will call the handler with two arguments <code>(self, event)</code></p> <p>But you've only defined the hander to take one:</p> <pre><code>def setvar(self): </code></pre> <p>If you don't need the information contained in the <code>event</code> argument, you could possibly just define it as an argument with a default value but not use it:</p> <pre><code>def setvar(self, event=None): </code></pre> <p>By defaulting the value to <code>None</code>, you should still be able to call it as a method with no arguments (implied <code>self</code> argument) in your code:</p> <pre><code>do.setvar() </code></pre> <p>An alternate way to do this is split it into two methods, a two argument one, for binding, that simply calls the one argument version that everthing else uses.</p>
1
2016-09-03T03:17:56Z
[ "python", "tkinter" ]
Bash script running python scripts
39,302,842
<p>I new to bash script, and found one of the code from stackoverflow. I merge it with my script, it doesn't run python. When I try to echo, it is always going to "Good". When I tried to run <code>ps -ef | grep runserver*</code> this always came out and causing the python script not running. </p> <pre><code>root 1133 0.0 0.4 11988 2112 pts/0 S+ 02:58 0:00 grep --color=auto runserver.py </code></pre> <p>Here is my code:-</p> <pre><code>#!/bin/sh SERVICE='runserver*' if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null then python /var/www/html/rest/runserver.py python /var/www/html/rest2/runserver.py else echo "Good" fi </code></pre>
0
2016-09-03T02:59:56Z
39,303,159
<p>If you are more familiar with python, try this instead:</p> <pre><code>#!/usr/bin/python import os import sys process = os.popen("ps aux | grep -v grep | grep WHATEVER").read().splitlines() if len(process) == 2: print "WHATEVER is running - nothing to do" else: os.system("WHATEVER &amp;") </code></pre>
0
2016-09-03T04:12:58Z
[ "python", "linux", "bash", "shell" ]
Bash script running python scripts
39,302,842
<p>I new to bash script, and found one of the code from stackoverflow. I merge it with my script, it doesn't run python. When I try to echo, it is always going to "Good". When I tried to run <code>ps -ef | grep runserver*</code> this always came out and causing the python script not running. </p> <pre><code>root 1133 0.0 0.4 11988 2112 pts/0 S+ 02:58 0:00 grep --color=auto runserver.py </code></pre> <p>Here is my code:-</p> <pre><code>#!/bin/sh SERVICE='runserver*' if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null then python /var/www/html/rest/runserver.py python /var/www/html/rest2/runserver.py else echo "Good" fi </code></pre>
0
2016-09-03T02:59:56Z
39,303,357
<p>Is the following code what you want?</p> <pre><code>#!/bin/sh SERVER='runserver*' CC=`ps ax|grep -v grep|grep "$SERVER"` if [ "$CC" = "" ]; then python /var/www/html/rest/runserver.py python /var/www/html/rest2/runserver.py else echo "good" fi </code></pre>
0
2016-09-03T04:51:25Z
[ "python", "linux", "bash", "shell" ]
Bash script running python scripts
39,302,842
<p>I new to bash script, and found one of the code from stackoverflow. I merge it with my script, it doesn't run python. When I try to echo, it is always going to "Good". When I tried to run <code>ps -ef | grep runserver*</code> this always came out and causing the python script not running. </p> <pre><code>root 1133 0.0 0.4 11988 2112 pts/0 S+ 02:58 0:00 grep --color=auto runserver.py </code></pre> <p>Here is my code:-</p> <pre><code>#!/bin/sh SERVICE='runserver*' if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null then python /var/www/html/rest/runserver.py python /var/www/html/rest2/runserver.py else echo "Good" fi </code></pre>
0
2016-09-03T02:59:56Z
39,307,720
<p>@NickyMan, the problem is related to the logic in the shell script. Your program don't find <em>runserver</em> and always says "Good". In this code, if you don't find the server, then exec <em>runserver</em>.</p> <pre><code>#!/bin/sh SERVICE='runserver*' if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null then echo "Good" else python /var/www/html/rest/runserver.py python /var/www/html/rest2/runserver.py fi </code></pre>
0
2016-09-03T13:57:56Z
[ "python", "linux", "bash", "shell" ]
Getting the root word using the Wordnet Lemmatizer
39,302,880
<p>I need to find a common root word matched for all related words for a keyword extractor.</p> <p>How to convert words into the same root using the python nltk lemmatizer? </p> <ul> <li>Eg: <ol> <li>generalized, generalization -> general </li> <li>optimal, optimized -> optimize (maybe) </li> <li>configure, configuration, configured -> configure</li> </ol></li> </ul> <p>The python nltk lemmatizer gives 'generalize', for 'generalized' and 'generalizing' when part of speech(pos) tag parameter is used but not for 'generalization'.</p> <p>Is there a way to do this?</p>
0
2016-09-03T03:10:45Z
39,303,494
<p>Use SnowballStemmer:</p> <pre><code>&gt;&gt;&gt; from nltk.stem.snowball import SnowballStemmer &gt;&gt;&gt; stemmer = SnowballStemmer("english") &gt;&gt;&gt; print(stemmer.stem("generalized")) general &gt;&gt;&gt; print(stemmer.stem("generalization")) general </code></pre> <blockquote> <p>Note: Lemmatisation is closely related to stemming. The difference is that a stemmer operates on a single word without knowledge of the context, and therefore cannot discriminate between words which have different meanings depending on part of speech.</p> </blockquote> <p>A general issue I have seen with lemmatizers is that it identifies even bigger words as <em>lemma</em>s.</p> <p>Example: In WordNet Lemmatizer(checked in NLTK), </p> <ul> <li>Genralized => Generalize</li> <li>Generalization => Generalization </li> <li>Generalizations => Generalization</li> </ul> <p>POS tag was not given as input in the above cases, so it was always considered <em>noun</em>.</p>
2
2016-09-03T05:15:46Z
[ "python", "nlp", "nltk", "wordnet", "lemmatization" ]
Pandas plot series with series names in one row
39,302,945
<p>I have a csv file like this</p> <pre><code>date, name, value 2016-09-01, alice, 10 2016-09-02, alice, 11 2016-09-01, bob, 8 2016-09-02, bob, 14 </code></pre> <p>With pandas can I plot as a line chart? Or must I change the structure of the file to something similar to </p> <pre><code>date, alice, bob 2016-09-01, 10, 8 2016-09-02, 11, 14 </code></pre>
0
2016-09-03T03:24:30Z
39,303,169
<p>Pivot your dataframe to plot one curve per column:</p> <pre><code>df.pivot(index='date', columns='name').plot() </code></pre>
1
2016-09-03T04:15:30Z
[ "python", "pandas", "plot", "time-series" ]
Load an opencv video frame by frame using PyQT
39,303,008
<p>I am trying to load a mat file ( has position coordinates of object whichis tracked) and load a video file. To load a video file I am using opencv. I made a GUI to load both of them. As soon as someone presses start button the video starts playing and Pause stops it. </p> <p>Here is the gui for that:</p> <p><a href="http://i.stack.imgur.com/gA1jH.png" rel="nofollow"><img src="http://i.stack.imgur.com/gA1jH.png" alt="enter image description here"></a></p> <p>Here are the two issues I am encountering:</p> <ol> <li>the video gets loaded in a different window. I want it to appear the main window which has Start and Pause button</li> <li>I want to add 2 buttons ('Next Frame' and 'Previous Frame') which allow me to go through the video frame by frame. Next Frame Button moves to the next frame and Previous Frame moves the video to previous frame.</li> </ol> <p>Here is the code :</p> <pre><code>import sys import scipy.io as sio from PyQt4 import QtGui, QtCore import cv2 class QtCapture(QtGui.QWidget): def __init__(self, filename): super(QtGui.QWidget, self).__init__() self.cap = cv2.VideoCapture(str(filename)) self.video_frame = QtGui.QLabel() lay = QtGui.QVBoxLayout() lay.setMargin(0) lay.addWidget(self.video_frame) self.setLayout(lay) def nextFrameSlot(self): ret, frame = self.cap.read() # My webcam yields frames in BGR format frame = cv2.cvtColor(frame, cv2.cv.CV_BGR2RGB) img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888) pix = QtGui.QPixmap.fromImage(img) self.video_frame.setPixmap(pix) def start(self): self.timer = QtCore.QTimer() self.timer.timeout.connect(self.nextFrameSlot) self.timer.start(1000./30) def pause(self): self.timer.stop() def deleteLater(self): self.cap.release() super(QtGui.QWidget, self).deleteLater() class ControlWindow(QtGui.QMainWindow): def __init__(self): super(ControlWindow, self).__init__() self.setGeometry(50, 50, 800, 600) self.setWindowTitle("PyTrack") self.capture = None self.matPosFileName = None self.videoFileName = None self.positionData = None self.updatedPositionData = {'red_x':[], 'red_y':[], 'green_x':[], 'green_y': [], 'distance': []} self.updatedMatPosFileName = None self.isVideoFileLoaded = False self.isPositionFileLoaded = False self.quitAction = QtGui.QAction("&amp;Exit", self) self.quitAction.setShortcut("Ctrl+Q") self.quitAction.setStatusTip('Close The App') self.quitAction.triggered.connect(self.closeApplication) self.openMatFile = QtGui.QAction("&amp;Open Position File", self) self.openMatFile.setShortcut("Ctrl+Shift+T") self.openMatFile.setStatusTip('Open .mat File') self.openMatFile.triggered.connect(self.loadPosMatFile) self.openVideoFile = QtGui.QAction("&amp;Open Video File", self) self.openVideoFile.setShortcut("Ctrl+Shift+V") self.openVideoFile.setStatusTip('Open .h264 File') self.openVideoFile.triggered.connect(self.loadVideoFile) self.mainMenu = self.menuBar() self.fileMenu = self.mainMenu.addMenu('&amp;File') self.fileMenu.addAction(self.openMatFile) self.fileMenu.addAction(self.openVideoFile) self.fileMenu.addAction(self.quitAction) self.imageCaptureWindow = QtGui.QWidget(self) self.start_button = QtGui.QPushButton('Start', self.imageCaptureWindow) self.start_button.clicked.connect(self.startCapture) self.start_button.setGeometry(0,10,40,30) self.pause_button = QtGui.QPushButton('Pause', self.imageCaptureWindow) self.pause_button.setGeometry(50,10,40,30) self.setCentralWidget(self.imageCaptureWindow) self.show() def startCapture(self): if not self.capture and self.isPositionFileLoaded and self.isVideoFileLoaded: self.capture = QtCapture(self.videoFileName) self.pause_button.clicked.connect(self.capture.pause) self.capture.setParent(self) self.capture.setWindowFlags(QtCore.Qt.Tool) self.capture.start() self.capture.show() def endCapture(self): self.capture.deleteLater() self.capture = None def loadPosMatFile(self): try: self.matPosFileName = str(QtGui.QFileDialog.getOpenFileName(self, 'Select .mat position File')) self.positionData = sio.loadmat(self.matPosFileName) self.isPositionFileLoaded = True except: print "Please select a .mat file" def loadVideoFile(self): try: self.videoFileName = QtGui.QFileDialog.getOpenFileName(self, 'Select .h264 Video File') self.isVideoFileLoaded = True except: print "Please select a .h264 file" def closeApplication(self): choice = QtGui.QMessageBox.question(self, 'Message','Do you really want to exit?',QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) if choice == QtGui.QMessageBox.Yes: print("Closing....") sys.exit() else: pass if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = ControlWindow() sys.exit(app.exec_()) </code></pre> <p>How should I go about doing that? Thanks for the help!</p>
0
2016-09-03T03:39:12Z
39,434,210
<p>Here is the link for the solved answer to the above asked question:</p> <p><a href="https://github.com/rajatsaxena/IISc_Neuroscience/blob/master/Miscellaneous/pyqt_opencv.py" rel="nofollow">https://github.com/rajatsaxena/IISc_Neuroscience/blob/master/Miscellaneous/pyqt_opencv.py</a></p>
0
2016-09-11T08:24:32Z
[ "python", "opencv", "pyqt", "pyqt4" ]
python sqlite3 unrecognized token
39,303,010
<p>I am trying to do some simple operations in sqlite with python. I have the test database created and have created a table but when I try to insert my data into it I get an 'unrecognized token' error. </p> <blockquote> <p>c.execute("create table node(changeset int, uid int, timestamp text, lon real, visible int, version int, user text, lat real, id int)")</p> </blockquote> <p>Creates the table. but when I try to insert the first line of data: </p> <blockquote> <p>c.execute("insert into node values(8581395,451048,2011-0629T14:14:14Z,-87.6939548,true,5,bbmiller,41.9729565,261114299)")</p> </blockquote> <p>I get the error: </p> <p>OperationalError: unrecognized token: "29T14"</p> <p>What is wrong with it? </p>
-1
2016-09-03T03:39:38Z
39,303,631
<p>The line</p> <pre><code>c.execute("insert into node values(8581395,451048,2011-0629T14:14:14Z,-87.6939548,true,5,bbmiller,41.9729565,261114299)") </code></pre> <p>should be</p> <pre><code>c.execute("insert into node values(8581395, 451048, '2011-0629T14:14:14Z', -87.6939548, 1, 5, 'bbmiller', 41.9729565, 261114299)") </code></pre> <p>Notice two relevant changes:</p> <ol> <li><p>I've changed all the text fields to be nested into quote marks</p></li> <li><p>True becomes an Integer as SQLite do not store booleans as an specific type.</p></li> </ol> <p>From <a href="https://www.sqlite.org/datatype3.html" rel="nofollow">https://www.sqlite.org/datatype3.html</a>:</p> <blockquote> <p>SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).</p> </blockquote> <p>Thus the boolean values comming from python must be translated into 0 or 1.</p>
0
2016-09-03T05:40:26Z
[ "python", "sqlite3" ]
How do I evaluate xe^x/(e^x-1) with numerical stability in Python?
39,303,052
<p>How do I evaluate xe^x/(e^x-1) with numerical stability around zero and when x is very positive or negative? I have access to all the usual mathematical functions in <code>numpy</code> and <code>scipy</code>.</p>
1
2016-09-03T03:48:11Z
39,303,428
<pre><code>def f(x): if abs(x) &gt; 0.1: return x*exp(x)/(exp(x)-1) else: return 1/(1.-x/2.+x**2/6.-x**3/24.) </code></pre> <p>The expansion in the last line can be extended in the obvious fashion if more precision is required, and can be made faster by re-phrasing. As it stands, it errs by as much as 1e-6.</p>
2
2016-09-03T05:03:40Z
[ "python", "numerical-stability" ]
Creating a python calculator using for loop
39,303,056
<p>so I have been asked to write a Python assignment for a basic calculator. It needs to include the operation I want to use (e.g. 1+1=, 2*2=). I am not so shabby at the keywords but when it comes to the construction from below the for i in range(1, 12, 1) statement I kinda falter. Im a bit fuzzy about how the data from the bottom reads from top. This is basically my code starts</p> <pre><code>print ("Welcome to my Calculator") x = input('Please enter first number: ') y = input('Please enter a second number: ') equation = x + y print input("Choose an equation: (a) Add, (m) Multiplaction, (s) Subtract, (/) Divide") for equation in range(1, 12, 1): </code></pre>
-4
2016-09-03T03:49:11Z
39,303,100
<pre><code>print ("Welcome to my Calculator") x = int(input('Please enter first number: ')) y = int(input('Please enter a second number: ')) equation = x + y s = input("Choose an equation: (+) Add, (*) Multiplaction, (-) Subtract, (/) Divide") if s == '+': print x + y if s == '*': print x * y if s == '-': print x - y if s == '/': print x / y </code></pre> <p>First, I made the input of x and y int because before it was being taken as a string and that will not work.</p> <p>Second, I made s = input (s is a random letter in my mind) and I had it equal different things ( add, multiply, subtract, divide).</p> <p>Then, I set 4 if statements. I will explain one of them because they are all similar.</p> <pre><code>if s == '+' print x + y </code></pre> <p>This is saying if the user inputed + then it will print the first number (x) added to the second number (y). </p> <p>Hope that helps :)</p> <p>Edit: This new code will only allow you to enter numbers 1-12 for both x and y that is line 9: if x in range(1,12,1) and y in range(1,12,1): It is simply saying if the first number you enter (X) is not in range 1-12 it will not display the answer. Same goes with y.</p> <pre><code>print ("Welcome to my Calculator") x = int(input('Please enter first number: ')) y = int(input('Please enter a second number: ')) s = input("Choose an equation: (+) Add, (*) Multiplaction, (-) Subtract, (/) Divide ") if x in range(1,12,1) and y in range(1,12,1): if s == '+': print x + y if s == '*': print x * y if s == '-': print x - y if s == '/': print x / y </code></pre>
-1
2016-09-03T04:00:52Z
[ "python", "for-loop", "range" ]
Creating a python calculator using for loop
39,303,056
<p>so I have been asked to write a Python assignment for a basic calculator. It needs to include the operation I want to use (e.g. 1+1=, 2*2=). I am not so shabby at the keywords but when it comes to the construction from below the for i in range(1, 12, 1) statement I kinda falter. Im a bit fuzzy about how the data from the bottom reads from top. This is basically my code starts</p> <pre><code>print ("Welcome to my Calculator") x = input('Please enter first number: ') y = input('Please enter a second number: ') equation = x + y print input("Choose an equation: (a) Add, (m) Multiplaction, (s) Subtract, (/) Divide") for equation in range(1, 12, 1): </code></pre>
-4
2016-09-03T03:49:11Z
39,303,120
<p>I feel like the other answer lacks indicators to what you do wrong. You will need to look further into Python's grammar before going further. Basically you have some things problematic :</p> <p><code>equation = x + y</code> computes the sum of x + y. To create an equation to which you can send x and y, you could create a function like this:</p> <pre><code>def my_sum(argument1, argument2): return argument1 + argument2 </code></pre> <p>Look into Python's dock to functions you are calling like <code>input</code>. <a href="https://docs.python.org/" rel="nofollow">Python Doc</a> There is no need to print input as it's will print the message itself. There is no handling regarding the answer given by the user to the "Choose an equation". The for loop you are trying to accomplish has no meaning; obviously you would want the input from the user (which could be a, m, s or /) to lead to some equation. To realize this, save the value of the input into a variable:</p> <p><code>user_answer = input("Choose an equation: ")</code></p> <p>Then use this variable for redirecting towards the correct equation function:</p> <pre><code>if user_answer == 'a': my_sum() # This is the function defined above </code></pre>
0
2016-09-03T04:05:38Z
[ "python", "for-loop", "range" ]
Paramiko won't install with Pip
39,303,095
<p>Trying to use <code>paramiko</code> and Python tells me it's not found, so I try to install with <code>sudo pip install paramiko</code> and get this awful error: <a href="http://pastebin.com/GFpgXB07" rel="nofollow">http://pastebin.com/GFpgXB07</a></p> <p>On OS X. Thanks!</p>
0
2016-09-03T04:00:09Z
39,303,172
<p>The system Python in OSX is used for various tasks by the operating system, so modifying its packages is generally a very bad idea. This error looks like the operating system preventing you from doing something potentially very harmful – in general, doing <code>sudo pip install</code> <em>anything</em> within your system Python is a bad idea, unless you know <em>exactly</em> what you're doing.</p> <p>So how do you install and use a new package safely? Use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenvs</a>. This lets you create an independent set of Python packages that you can modify and update as much as you like, without risk of breaking your operating system.</p>
1
2016-09-03T04:15:58Z
[ "python", "pip", "paramiko" ]
Paramiko won't install with Pip
39,303,095
<p>Trying to use <code>paramiko</code> and Python tells me it's not found, so I try to install with <code>sudo pip install paramiko</code> and get this awful error: <a href="http://pastebin.com/GFpgXB07" rel="nofollow">http://pastebin.com/GFpgXB07</a></p> <p>On OS X. Thanks!</p>
0
2016-09-03T04:00:09Z
39,303,318
<p>It seems that you have permissions problem. I agree with jakevdp but in that case virtualenv is nut your solution. Try the install with --user option. Doc says (<a href="https://pip.pypa.io/en/stable/reference/pip_install/" rel="nofollow">https://pip.pypa.io/en/stable/reference/pip_install/</a>): </p> <pre><code>--user Install to the Python user install directory for your platform. Typically ~/.local/. </code></pre> <p>Moreover, if you take this habit you will be safe of not screwing your system with sudo.</p>
1
2016-09-03T04:45:34Z
[ "python", "pip", "paramiko" ]
ValueError: too many values to unpack Multiprocessing Pool
39,303,117
<p>I have the following 'worker' that initially returned a single JSON object, but I would like it to return multiple JSON objects:</p> <pre><code>def data_worker(data): _cats, index, total = data _breeds = {} try: url = _channels['feedUrl'] r = get(url, timeout=5) rss = etree.XML(r.content) tags = rss.xpath('//cats/item') _cats['breeds'] = {} for t in tags: _cats['breeds']["".join(t.xpath('breed/@url'))] = True _breeds['url'] = "".join(t.xpath('breed/@url')) return [_cats, _breeds] except: return [_cats, _breeds] </code></pre> <p>This worker is a parameter for a multiprocessing pool:</p> <pre><code>cats, breeds = pool.map(data_worker, data, chunksize=1) </code></pre> <p>When I run the pool and the worker with just one output (i.e. _cats), it works just fine, but when I try to return multiple JSON "schemas," I get the error:</p> <pre><code> File "crawl.py", line 111, in addFeedData [cats, breeds] = pool.map(data_worker, data, chunksize=1) ValueError: too many values to unpack </code></pre> <p><strong>How can I return 2 separate JSON objects in data_worker?</strong> I need them to be separate JSON objects. Note, I have already tried the following, which did not work:</p> <pre><code>[cats, breeds] = pool.map(data_worker, data, chunksize=1) (cats, breeds) = pool.map(data_worker, data, chunksize=1) return (_cats, _breeds) </code></pre>
0
2016-09-03T04:05:05Z
39,303,154
<p>First of all I think you meant to write this:</p> <pre><code>cats, breeds = pool.map(data_worker, data, chunksize=1) </code></pre> <p>But anyway this won't work, because <code>data_worker</code> returns a pair, but <code>map()</code> returns a list of whatever the worker returns. So you should do this:</p> <pre><code>cats = [] breeds = [] for cat, breed in pool.map(data_worker, data, chunksize=1): cats.append(cat) breeds.append(breed) </code></pre> <p>This will give you the two lists you seek.</p> <p>In other words, you expected a pair of lists, but you got a list of pairs.</p>
1
2016-09-03T04:12:38Z
[ "python", "json", "multiprocessing" ]
How to install flaskext.mysql with yum/centos?
39,303,157
<p>While running a program, I get the error <code>ImportError: No module named flaskext.mysql</code>. How can I fix this with yum?</p>
-1
2016-09-03T04:12:50Z
39,303,207
<p>You can install <code>flaskext.mysql</code> using <code>pip</code></p> <p><code>pip install flask-mysql</code></p> <p>If you don't have <code>pip</code> you can install that using the instructions here: <a href="https://packaging.python.org/install_requirements_linux/#centos-rhel" rel="nofollow">https://packaging.python.org/install_requirements_linux/#centos-rhel</a></p> <p>Flask-MySQL Documentation: <a href="http://flask-mysql.readthedocs.io/en/latest/" rel="nofollow">http://flask-mysql.readthedocs.io/en/latest/</a></p>
1
2016-09-03T04:23:12Z
[ "python", "mysql", "flask", "centos", "yum" ]
Correct way of writing two floats into a regular txt
39,303,218
<p>I am running a big job, in cluster mode. However, I am only interested in two floats numbers, which I want to read somehow, when the job succeeds.</p> <p>Here what I am trying:</p> <pre><code>from pyspark.context import SparkContext if __name__ == "__main__": sc = SparkContext(appName='foo') f = open('foo.txt', 'w') pi = 3.14 not_pi = 2.79 f.write(str(pi) + "\n") f.write(str(not_pi) + "\n") f.close() sc.stop() </code></pre> <p>However, 'foo.txt' doesn't appear to be written anywhere (probably it gets written in an executor, or something). I tried '/homes/gsamaras/foo.txt', which would be the <code>pwd</code> of the gateway. However, it says: <code>No such file or directory: '/homes/gsamaras/myfile.txt'</code>.</p> <p>How to do that?</p> <hr> <pre><code>import os, sys import socket print "Current working dir : %s" % os.getcwd() print(socket.gethostname()) </code></pre> <p>suggest that the driver is actually a node of the cluster, that's why I don't see the file in my gateway.</p> <p>Maybe write the file in the HDFS somehow?</p> <p>This won't work either:</p> <pre><code>Traceback (most recent call last): File "computeCostAndUnbalancedFactorkMeans.py", line 15, in &lt;module&gt; f = open('hdfs://myfile.txt','w') IOError: [Errno 2] No such file or directory: 'hdfs://myfile.txt' </code></pre>
1
2016-09-03T04:25:00Z
39,370,817
<p>At the first glance there is nothing particularly (you should context manager in case like this instead of manually closing but it is not the point) wrong with your code. If this script is passed to <code>spark-submit</code> file will be written to the directory local to the driver code. </p> <p>If you submit your code in the cluster mode it will be an arbitrary worker node in your cluster. If you're in doubt you can always log <code>os.getcwd()</code> and <code>socket.gethostname()</code> to figure out which machine is used and what is the working directory.</p> <p>Finally you cannot use standard Python IO tools to write to HDFS. There a few tools which can achieve that including native <a href="https://github.com/dask/hdfs3" rel="nofollow">dask/hdfs3</a>.</p>
1
2016-09-07T13:09:14Z
[ "python", "apache-spark", "io", "bigdata", "distributed-computing" ]
Pandas 'read_csv' giving an error, in one specific directory only.
39,303,287
<p>I was attempting to follow a <a href="http://ahmedbesbes.com/how-to-score-08134-in-titanic-kaggle-challenge.html" rel="nofollow">pandas/sklearn/kaggle tutorial</a>, and barely got a dozen lines when I stumbled over over one of the simplest commands in python:</p> <p>Code:</p> <pre><code>import warnings warnings.filterwarnings('ignore') import pandas as pd pd.options.display.max_columns = 100 pd.options.display.max_rows = 100 import matplotlib as mpl import matplotlib.pyplot as pd import numpy as np #Cell 3 data = pd.read_csv('./Data/train.csv') data.head() </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "KaggleTitanic00.py", line 15, in &lt;module&gt; data = pd.read_csv('./Data/train.csv') AttributeError: 'module' object has no attribute 'read_csv' </code></pre> <p>A command that only gives an error in <em>that directory</em>:</p> <pre><code>~/Python/Tutorials/SKlearn$ python Chapter4--Test-12.py Number of spam messages: 747 Number of ham messages: 4825 ['spam' 'spam' 'ham' ..., 'ham' 'ham' 'ham'] Prediction: spam. Message: Ur cash-balance is currently 500 pounds - to maximize ur cash-in now send GO to 86688 only 150p/msg. CC 08718720201 HG/Suite342/2Lands Row/W1J6HL Prediction: spam. Message: December only! Had your mobile 11mths+? You are entitled to update to the latest colour camera mobile for Free! Call The Mobile Update Co FREE on 08002986906 Prediction: ham. Message: Just normal only here :) Prediction: ham. Message: How would my ip address test that considering my computer isn't a minecraft server Prediction: ham. Message: Ü collecting ur laptop then going to configure da settings izzit? </code></pre> <p>I have absolutely no idea what's wrong. The code is identical to the tutorial.</p>
1
2016-09-03T04:40:18Z
39,303,394
<p>Write:</p> <pre><code>import matplotlib.pyplot as plt </code></pre> <p>By reimporting as <code>pd</code> you overwrite <code>import pandas as pd</code></p>
2
2016-09-03T04:58:41Z
[ "python", "csv", "pandas", "module", "attributeerror" ]
OpenCV Python Feature detection examples extension
39,303,315
<p>I'm chasing a little assistance with an idea I'm playing with. I want to take the features located in an image with code similar to the example on</p> <p><a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html" rel="nofollow">See sample image at bottom of page here</a> Last section/Example is the one I'm talking about</p> <p>in particular for my issue I wanted to use the matches indicated in the image to find the target in the scene image like illustrated with a seemingly simple addition. I want to draw a bounding box around the target when located in the scene frame</p> <p><a href="http://i.imgur.com/lpE7khN.jpg" rel="nofollow">Example of output I'm after</a></p> <p>Rather than just putting a bounding box around the features, I would rather have a list of the four contour points that represent the transformed target on the scene frame if that makes sense.</p> <p>Big picture, I want to take the subsection of the scene image containing my target and crop it out of the scene image, mask the non-target areas out of the image remaining and then use this as my source for a further process.</p> <p>At this point I've managed to do all it need to with a hard coded set of points to represent the corners of the target image as rotated and transformed in the scene image so everything works I just need an example of how to determine the x,y co-ords of each corner of the target in that scene</p> <p>I didn't want to post the code as its a bit clunky and its the concept I'm after, not a complete 'do it for me please' fix</p> <p>Any advice much appreciated, If you could show me using the example code attached how to do this I'd be very grateful, Cheers.</p> <pre><code>import numpy as np import cv2 from matplotlib import pyplot as plt img1 = cv2.imread('box.png',0) # queryImage img2 = cv2.imread('box_in_scene.png',0) # trainImage # Initiate SIFT detector sift = cv2.SIFT() # find the keypoints and descriptors with SIFT kp1, des1 = sift.detectAndCompute(img1,None) kp2, des2 = sift.detectAndCompute(img2,None) # FLANN parameters FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) search_params = dict(checks=50) # or pass empty dictionary flann = cv2.FlannBasedMatcher(index_params,search_params) matches = flann.knnMatch(des1,des2,k=2) # Need to draw only good matches, so create a mask matchesMask = [[0,0] for i in xrange(len(matches))] # ratio test as per Lowe's paper for i,(m,n) in enumerate(matches): if m.distance &lt; 0.7*n.distance: matchesMask[i]=[1,0] draw_params = dict(matchColor = (0,255,0), singlePointColor = (255,0,0), matchesMask = matchesMask, flags = 0) img3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,**draw_params) plt.imshow(img3,),plt.show() </code></pre>
1
2016-09-03T04:44:23Z
39,311,462
<p>You need to find the prescriptive transform between the two images.</p> <p>Create a set of corresponding coordinates according to the matched features. </p> <p>For example you find that the feature FtI1 in image 1 corresponds to FtJ1 in image 2 so you know that coordinate of FtI1 (xi,yi) corresponds to the coordinate of FtJ1 (xj,yj) and you have this for all the corresponding features. After you have a list of corresponding coordinates between the two images you can calculate the prescriptive transform using opecv getPerspectiveTransform.</p> <p>Finally use the transformation you found on the 4 coordinates of the enclosing shape in the first image to get the coordinates of the enclosing shape in the second image. The opencv function for that is warpPerspective.</p> <p>An example of how to do that in opecv is in: <a href="http://docs.opencv.org/3.1.0/da/d6e/tutorial_py_geometric_transformations.html" rel="nofollow">http://docs.opencv.org/3.1.0/da/d6e/tutorial_py_geometric_transformations.html</a></p>
0
2016-09-03T21:21:47Z
[ "python", "image-processing", "opencv3.0" ]
Problems extending python array declared outside of scope
39,303,338
<p>This is a very basic question, but I can't seem to extend an array with a new item that is added within a function. I haven't gotten push to work either, so I think my array is just not being addressed by the other functions. </p> <p>The array is declared as a global because otherwise function(s) do not appear to be able to see it. There is probably a much better way, but this is working in a few ways.</p> <p>this is one set of things I've tried:</p> <pre><code> # addTo.insert(0, theItem) # weeklytasks.append(theItem) # print(addTo) # def askForItem(theItem): # addTo.push(theItem) # print(addTo) # </code></pre> <p>but no luck.</p> <pre><code> def initializer(): print("hello!") print("do you want to view the current list, or add a new item?") </code></pre> <p>setting up some arrays</p> <pre><code> global weeklyTasks = ['no items']; global monthlyTasks = ['no items'] global quarterlyTasks = ['no items']; </code></pre> <p>trying to extend</p> <pre><code> quarterlyTasks.extend('the item') print(quarterlyTasks); </code></pre> <p>Neither of these work</p> <pre><code> #monthlyTasks.push(0,"task1") #monthlyTasks.append("item") </code></pre> <p>set a var for user's input</p> <pre><code> global theItem addTo = "" theItem = "" import string print('addTo in globals, ' 'addTo' in globals()) </code></pre> <p>takes an item and checks its timeframe</p> <pre><code> def evaluateInput(timeframe): global addTo; global theItem; if timeframe == "Weekly": addTo = "weeklyTasks"; printDestination(); weeklyTasks.extend(theItem); # why does [].extend not work here? if timeframe == "Monthly": addTo = "monthlyTasks" monthlyTasks.insert(0,theItem) printDestination() if timeframe == "Quarterly": addTo = "quarterlyTasks" quarterlyTasks.insert(0,theItem) printDestination() </code></pre> <p>follow up with a request for the timeframe</p> <pre><code> def getTimeframe(text): if "add" in text: timeframe = input("Where does this entry go? \n Weekly, Monthly or Quarterly?: ") evaluateInput(timeframe) # sends the timeframe to evaluateInput # next, ask for the item theItem = input('what is the item?') </code></pre> <p>print a confirmation of what is being added where</p> <pre><code> def printDestination(): print("The item (" + theItem+") will be added to " + addTo) # prints where something is going print("the "+addTo+" list now contains:") # good, this worked print(weeklyTasks) #good, this worked (but the method to push doesn't work) </code></pre>
1
2016-09-03T04:48:01Z
39,304,546
<p>A working example of all mentioned functions. <code>global</code> is not required, because the <code>tasklist</code> is not re-assigned in the function, only its methods are called.</p> <pre><code>tasklist = ['one'] def testfunc(): # no global required tasklist.append('two') tasklist.extend(['three', 'four']) tasklist.insert(0, 'zero') testfunc() print(tasklist) # ['zero', 'one', 'two', 'three', 'four'] </code></pre> <p>Hope it helps.</p>
3
2016-09-03T07:45:05Z
[ "python", "arrays", "python-3.x" ]
Problems extending python array declared outside of scope
39,303,338
<p>This is a very basic question, but I can't seem to extend an array with a new item that is added within a function. I haven't gotten push to work either, so I think my array is just not being addressed by the other functions. </p> <p>The array is declared as a global because otherwise function(s) do not appear to be able to see it. There is probably a much better way, but this is working in a few ways.</p> <p>this is one set of things I've tried:</p> <pre><code> # addTo.insert(0, theItem) # weeklytasks.append(theItem) # print(addTo) # def askForItem(theItem): # addTo.push(theItem) # print(addTo) # </code></pre> <p>but no luck.</p> <pre><code> def initializer(): print("hello!") print("do you want to view the current list, or add a new item?") </code></pre> <p>setting up some arrays</p> <pre><code> global weeklyTasks = ['no items']; global monthlyTasks = ['no items'] global quarterlyTasks = ['no items']; </code></pre> <p>trying to extend</p> <pre><code> quarterlyTasks.extend('the item') print(quarterlyTasks); </code></pre> <p>Neither of these work</p> <pre><code> #monthlyTasks.push(0,"task1") #monthlyTasks.append("item") </code></pre> <p>set a var for user's input</p> <pre><code> global theItem addTo = "" theItem = "" import string print('addTo in globals, ' 'addTo' in globals()) </code></pre> <p>takes an item and checks its timeframe</p> <pre><code> def evaluateInput(timeframe): global addTo; global theItem; if timeframe == "Weekly": addTo = "weeklyTasks"; printDestination(); weeklyTasks.extend(theItem); # why does [].extend not work here? if timeframe == "Monthly": addTo = "monthlyTasks" monthlyTasks.insert(0,theItem) printDestination() if timeframe == "Quarterly": addTo = "quarterlyTasks" quarterlyTasks.insert(0,theItem) printDestination() </code></pre> <p>follow up with a request for the timeframe</p> <pre><code> def getTimeframe(text): if "add" in text: timeframe = input("Where does this entry go? \n Weekly, Monthly or Quarterly?: ") evaluateInput(timeframe) # sends the timeframe to evaluateInput # next, ask for the item theItem = input('what is the item?') </code></pre> <p>print a confirmation of what is being added where</p> <pre><code> def printDestination(): print("The item (" + theItem+") will be added to " + addTo) # prints where something is going print("the "+addTo+" list now contains:") # good, this worked print(weeklyTasks) #good, this worked (but the method to push doesn't work) </code></pre>
1
2016-09-03T04:48:01Z
39,304,828
<p>Here's the working solution in python 3.2 to add items to list in function:</p> <pre><code>weeklyTasks = ['No work Sunday'] def AddWeeklyTask(): weeklyTasks.extend(['Work On']) weeklyTasks.append('Do not work on weekends') weeklyTasks.insert(2,'Friday') print(weeklyTasks) AddWeeklyTask() print(weeklyTasks) </code></pre> <p>Output:</p> <pre><code>['No work Sunday'] ['No work Sunday', 'Work On', 'Friday', 'Do not work on weekends'] </code></pre> <p>There is no need to declare <code>list</code> as <code>global</code> </p>
1
2016-09-03T08:22:58Z
[ "python", "arrays", "python-3.x" ]
How to detect own files name
39,303,375
<p>I have some code, which I will rather not share but this a portion</p> <pre><code>try_again = input ("Try again?") if answer == "Y" or answer == "y": clear() file_path = os.path.dirname(os.path.realpath(__file__)) open file_path + "maze_game.exe" exit() else: exit() </code></pre> <p>I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:</p> <pre><code>file_name = how ever I get the name try_again = input ("Try again?") if answer == "Y" or answer == "y": clear() file_path = os.path.dirname(os.path.realpath(__file__)) open file_path + file_name exit() else: exit() </code></pre> <p>so how might I get the file name?</p> <p>EDIT: here is my whole code:</p> <pre><code>import os import time clear = lambda: os.system('cls') name = input ("What is your name? ") friend = "Charels" if name == "Charels" or name == "charels" or name == "Charles" or name == "charles": friend = "Chuck" print ("Welcome to the Maze Game Dr. " + name) time.sleep(1.5) clear() print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend) time.sleep(1.5) clear() print ("Are you sure you want to continue?") answer = input ("Y or N? ") if answer == "Y" or answer == "y": ("") else: friend = friend + " for dead. R.I.P." print ("Shame on you, you left " + friend) time.sleep(1.5) clear() print ("YOU LOSE") time.sleep(1.5) clear() file_name = how ever I get the name try_again = input ("Try again?") if answer == "Y" or answer == "y": clear() file_path = os.path.dirname(os.path.realpath(__file__)) open file_path + file_name exit() else: exit() input ("...") </code></pre> <p>no, the program is not completed and ignore the last line</p>
2
2016-09-03T04:55:09Z
39,303,522
<p>Maybe I am misunderstanding what you want, but I think <code>os.path.basename(__file__)</code> will do the trick. </p> <p>This will give you just the file part of your path, so if you have a file<code>foo/bar/baz.py</code> and pass that path like <code>os.path.basename('foo/bar/baz.py')</code>, it will return the string <code>'baz.py'</code>.</p> <p>So try:</p> <pre><code>file_name = os.path.basename(__file__) </code></pre> <p>That being said, your approach seems a little atypical as @Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for. </p>
2
2016-09-03T05:21:16Z
[ "python" ]
Fastest way to process a python list of tuples
39,303,484
<p>In a Django project, I have a python list of tuples like so:</p> <pre><code>users_and_values = [(user_id,value),(user_id,value),......] </code></pre> <p>where <code>value</code> can either be 0.0 or 1.0 (float). Given this list, I need to create a new one, which is like so:</p> <pre><code>[(user_object,value),(user_object,value),......] </code></pre> <p>where <code>user_object</code> is the object associated with each <code>user_id</code> (containing user attributes and such).</p> <p><strong>What is the most efficient way to achieve this (performance and correctness both matter)?</strong> Currently, I'm trying to achieve that as follows in a Django view:</p> <pre><code> user_ids = [user_id for user_id, value in users_and_values] user_objs = User.objects.filter(id__in=user_ids) context["votes"] = [(user_objs(user_id),value) for user_id, value in users_and_votes] </code></pre> <p>This gives me the error: </p> <blockquote> <p>'QuerySet' object is not callable</p> </blockquote> <p>I could also have tried <code>[(User.object.get(id=user_id),value) for user_id, value in users_and_values]</code>, but that would be too many DB calls. So can anyone chime in with what I'm doing wrong, and the correct solution? Thanks in advance. </p>
0
2016-09-03T05:13:33Z
39,303,545
<p><code>user_objs</code> is an unordered collection of users. You have to manually map the user ids to the corresponding values by iterating over it:</p> <pre><code>user_ids = [user_id for user_id, value in users_and_values] user_objs = User.objects.filter(id__in=user_ids) ids_to_values = dict(users_and_values) # {id1: value1, ...} context["votes"] = [(user, ids_to_values[user.id]) for user in user_objs] </code></pre>
2
2016-09-03T05:25:30Z
[ "python", "django" ]
Django upload only csv file
39,303,488
<p>I am trying to import csv file i am able to import without any problem but the present functionality accepts all file types, i want the functionality to accept only csv file. below is the view.py and template file.</p> <p>myapp/views.py</p> <pre><code>def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): importing_file(request.FILES['docfile']) </code></pre> <p>myapp/templates/myapp/index.html</p> <pre><code> &lt;form action="{% url 'ml:list' %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;p&gt;{{ form.non_field_errors }}&lt;/p&gt; &lt;p&gt;{{ form.docfile.label_tag }} {{ form.docfile.help_text }}&lt;/p&gt; &lt;p&gt; {{ form.docfile.errors }} {{ form.docfile }} &lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Upload"/&gt;&lt;/p&gt; &lt;/form&gt; </code></pre> <blockquote> <p>EDIT</p> <p>I could find a workaround by adding validate_file_extension as per the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-a-specific-field-attribute" rel="nofollow">django documentation</a></p> <p>myapp/forms.py</p> </blockquote> <pre><code>def validate_file_extension(value): if not value.name.endswith('.csv'): raise forms.ValidationError("Only CSV file is accepted") class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file',validators=[validate_file_extension]) </code></pre>
0
2016-09-03T05:14:42Z
39,304,039
<p>added code snippet to the forms.py file to validate file extension and now it is working fine.</p> <pre><code>def validate_file_extension(value): if not value.name.endswith('.csv'): raise forms.ValidationError("Only CSV file is accepted") class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file',validators=[validate_file_extension]) </code></pre>
0
2016-09-03T06:43:08Z
[ "python", "django", "csv" ]
Web2py DAL find the record with the latest date
39,303,554
<p>Hi I have a table with the following structure.</p> <p>Table Name: DOCUMENTS</p> <p>Sample Table Structure:</p> <pre><code>ID | UIN | COMPANY_ID | DOCUMENT_NAME | MODIFIED_ON | ---|----------|------------|---------------|---------------------| 1 | UIN_TX_1 | 1 | txn_summary | 2016-09-02 16:02:42 | 2 | UIN_TX_2 | 1 | txn_summary | 2016-09-02 16:16:56 | 3 | UIN_AD_3 | 2 | some other doc| 2016-09-02 17:15:43 | </code></pre> <p>I want to fetch the latest modified record UIN for the company whose id is 1 and document_name is "txn_summary".</p> <p>This is the postgresql query that works:</p> <pre><code>select distinct on (company_id) uin from documents where comapny_id = 1 and document_name = 'txn_summary' order by company_id, "modified_on" DESC; </code></pre> <p>This query fetches me UIN_TX_2 which is correct.</p> <p>I am using web2py DAL to get this value. After some research I have been successful to do this:</p> <pre><code>fmax = db.documents.modified_on.max() query = (db.documents.company_id==1) &amp; (db.documents.document_name=='txn_summary') rows = db(query).select(fmax) </code></pre> <p>Now "rows" contains only the value of the modified_on date which has maximum value. I want to fetch the record which has the maximum date inside "rows". Please suggest a way. Help is much appreciated.</p> <p><strong>And my requirement extends to find each such records for each company_id for each document_name.</strong></p>
0
2016-09-03T05:26:49Z
39,335,401
<p>Your approach will not return complete row, it will only return last modified_on value.</p> <p>To fetch last modified record for the company whose id is 1 and document_name "txn_summary", query will be</p> <pre><code>query = (db.documents.company_id==1) &amp; (db.documents.document_name=='txn_summary') row = db(query).select(db.documents.ALL, orderby=~db.documents.modified_on, limitby=(0, 1)).first() </code></pre> <p><code>orderby=~db.documents.modified_on</code> will return records arranged in descending order of <code>modified_on</code> (last modified record will be first) and <code>first()</code> will select the first record. i.e. complete query will return last modified record having company 1 and document_name = "txn_summary".</p> <p>There can be other/better way to achieve this. Hope this helps!</p>
0
2016-09-05T17:37:44Z
[ "python", "postgresql", "web2py", "data-access-layer" ]
Cannot install Keras on Pycharm on Macbook
39,303,623
<p>Macbook.</p> <p>I can perform "pip install Keras==1.0.8" successfully on terminal though.</p> <p><strong>Problem: Installing Keras to Pycharm, cannot make it.</strong></p> <p>Error as shown by screenshots below: <a href="http://i.stack.imgur.com/7ORA6.png" rel="nofollow"><img src="http://i.stack.imgur.com/7ORA6.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/LtGsy.png" rel="nofollow"><img src="http://i.stack.imgur.com/LtGsy.png" alt="enter image description here"></a></p>
0
2016-09-03T05:38:55Z
39,303,904
<p>There are some non-python dependencies for Keras, so pip won't install them and fails if they are not found. The error here is related to fortran compiler and can be resolved by installing for example <code>gfortran</code>. But there would be probably other packages that you miss.</p> <p>I recommend taking steps in <a href="http://deeplearning.net/software/theano/install.html#mac-os" rel="nofollow">installation guide of theano on OS X</a> because for now keras depends on theano. If you take the steps to have a working installation of theano there shouldn't be any problem installing Keras with pip.</p>
1
2016-09-03T06:25:31Z
[ "python", "pycharm", "keras" ]
python 3.5 for loop defined functions placed in the loop
39,303,685
<p>Ok I have been trying to use a input Int function to set how many questions are asked at the start however the input doesn't seem to want to go through. It can be done right? I all I want is to be be able to alter the start_test() value. While when the user enter a inter correct answer I want the error message to display the correct answer after the Wrong. </p> <pre><code>import random import string import sys # Used to refer to the what constinutes a vowel vowels = ['a', 'e', 'i', 'o', 'u'] # Used to refer to the what constinutes consonant consonants = [x for x in string.ascii_lowercase if x not in vowels] #List of words used for candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] word_map = {x:{'consonants':len([y for y in x.lower() if y in consonants]), 'vowels':len([y for y in x.lower() if y in vowels]), 'letters':len(x)} for x in candidateWords} ordinal_map = {1:'st', 2:'nd', 3:'rd', 4:'th', 5:'th', 6:'th', 7:'th', 8:'th', 9:'th', 10:'th'} def start_test(number_questions): current_question = 0 correct_questions = 0 if number_questions &gt; len(candidateWords): number_questions = len(candidateWords) sample_questions = random.sample(candidateWords, number_questions) print(' Welcome to Samuel Mays English Test') print ('---------------------') for x in sample_questions: print ("Question {}/{}:".format(current_question+1, number_questions)) print ('---------------------') # current_question += 1 #q_type or question type uses a random inter between one and 4 elif is then used to set up # what occurrs on an instance of each number in the set range q_type = random.randint(1, 4) if q_type == 1: # if one is rolled the how many letter question is asked # it refers to the word map and looks at the letters entry. correct = word_map[x]['letters'] #Input that is presented to the user ans = input('How many letters does "{}" contain?'.format(x)) elif q_type == 2: # if two is rolled the how many vowel question is asked # it refers to the word map. correct = word_map[x]['vowels'] #Input that is presented to the user ans = input('How many vowels does "{}" contain?'.format(x)) elif q_type == 3: # if three is rolled the how many vowels question is asked correct = word_map[x]['consonants'] ans = input('How many consonants does "{}" contain?'.format(x)) else: n = random.randint(1, len(x)) correct = x[n-1] if sys.version.startswith('3'): ans = str(input('What is the {}{} letter of "{}"?'.format(n, ordinal_map[int(n)], x))) else: ans = str(raw_input('What is the {}{} letter of "{}"?'.format(n, ordinal_map[int(n)], x))) if str(ans).lower() == str(correct).lower(): print('Well done correct! :)') correct_questions += 1 else: print('Wrong') print ('You have completed your test!') print (" Score {}/{}:".format(correct_questions , number_questions)) try_again = input('Would you like to try again? (y/n)').lower() if try_again == 'y' or try_again == 'yes': start_test(number_questions) start_test(5) </code></pre> <p>tring to figure out how how to the results of a defined function into the loop</p> <pre><code>def prompt_vowel_count(word): correct = word_map[word]['vowels'] ans = input('How many vowels does "{}" contain?'.format(word)) return check(int(ans), correct) </code></pre>
-2
2016-09-03T05:49:06Z
39,303,860
<pre><code>import random import string import sys vowels = ['a', 'e', 'i', 'o', 'u'] consonants = [x for x in string.ascii_lowercase if x not in vowels] candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] word_map = {x:{'consonants':len([y for y in x.lower() if y in consonants]), 'vowels':len([y for y in x.lower() if y in vowels]), 'letters':len(x)} for x in candidateWords} ordinal_map = {1:'st', 2:'nd', 3:'rd', 4:'th', 5:'th', 6:'th', 7:'th', 8:'th', 9:'th', 10:'th'} def prompt_vowel_count(word): correct = word_map[word]['vowels'] ans = input('How many vowels does "{}" contain?'.format(word)) return correct, ans def start_test(number_questions): current_question = 0 correct_questions = 0 if number_questions &gt; len(candidateWords): number_questions = len(candidateWords) sample_questions = random.sample(candidateWords, number_questions) print(' Welcome to Year One Greens English Test') print ('---------------------') for x in sample_questions: print ("Question {}/{}:".format(current_question+1, number_questions)) print ('---------------------') current_question += 1 #q_type or question type uses a random inter between one and 4 elif is then used to set up q_type = random.randint(1, 4) if q_type == 1: correct = word_map[x]['letters'] ans = input('How many letters does "{}" contain?'.format(x)) elif q_type == 2: correct, ans = prompt_vowel_count(x) elif q_type == 3: correct = word_map[x]['consonants'] ans = input('How many consonants does "{}" contain?'.format(x)) else: n = random.randint(1, len(x)) correct = x[n-1] if sys.version.startswith('3'): ans = str(input('What is the {}{} letter of "{}"?'.format(n, ordinal_map[int(n)], x))) else: ans = str(raw_input('What is the {}{} letter of "{}"?'.format(n, ordinal_map[int(n)], x))) if str(ans).lower() == str(correct).lower(): print('Well done correct! :)') correct_questions += 1 else: print('Wrong') print ('You have completed your test!') print (" Score {}/{}:".format(correct_questions , number_questions)) try_again = input('Would you like to try again? (y/n)').lower() if try_again == 'y' or try_again == 'yes': start_test(number_questions) start_test(5) </code></pre>
2
2016-09-03T06:17:57Z
[ "python", "python-3.x", "python-3.5" ]
How do i work out this date time issue in python
39,303,710
<p>I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.</p> <pre><code>last_date = df.iloc[1,0] last_unix = pd.to_datetime('2015-01-31 00:00:00') +pd.Timedelta(13148730) five_months = 13148730 next_unix = last_unix + five_months for i in forecast_set: next_date = Timestamp('2015-06-30 00:00:00') next_unix += 13148730 df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i] </code></pre> <p>Error: Traceback (most recent call last):</p> <p>File "", line 1, in runfile('C:/Users/HP/Documents/machine learning.py', wdir='C:/Users/HP/Documents')</p> <p>File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile execfile(filename, namespace)</p> <p>File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile exec(compile(f.read(), filename, 'exec'), namespace)</p> <p>File "C:/Users/HP/Documents/machine learning.py", line 74, in next_unix = last_unix + five_months</p> <p>File "pandas\tslib.pyx", line 1025, in pandas.tslib._Timestamp.<strong>add</strong> (pandas\tslib.c:20118)</p> <p>ValueError: Cannot add integral value to Timestamp without offset.</p>
-1
2016-09-03T05:54:11Z
39,304,571
<p>If <code>pd.to_datetime</code> returns a python <code>datetime</code> object, then you should look at using a <code>timedelta</code> object for your 5 month interval:</p> <p><a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow">https://docs.python.org/2/library/datetime.html#timedelta-objects</a></p>
0
2016-09-03T07:47:50Z
[ "python", "pandas" ]
How do i work out this date time issue in python
39,303,710
<p>I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.</p> <pre><code>last_date = df.iloc[1,0] last_unix = pd.to_datetime('2015-01-31 00:00:00') +pd.Timedelta(13148730) five_months = 13148730 next_unix = last_unix + five_months for i in forecast_set: next_date = Timestamp('2015-06-30 00:00:00') next_unix += 13148730 df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i] </code></pre> <p>Error: Traceback (most recent call last):</p> <p>File "", line 1, in runfile('C:/Users/HP/Documents/machine learning.py', wdir='C:/Users/HP/Documents')</p> <p>File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile execfile(filename, namespace)</p> <p>File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile exec(compile(f.read(), filename, 'exec'), namespace)</p> <p>File "C:/Users/HP/Documents/machine learning.py", line 74, in next_unix = last_unix + five_months</p> <p>File "pandas\tslib.pyx", line 1025, in pandas.tslib._Timestamp.<strong>add</strong> (pandas\tslib.c:20118)</p> <p>ValueError: Cannot add integral value to Timestamp without offset.</p>
-1
2016-09-03T05:54:11Z
39,304,713
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow">pd.Timedelta()</a> method:</p> <pre><code>In [20]: pd.to_datetime('2015-01-31 00:00:00') + pd.Timedelta(seconds=13148730) Out[20]: Timestamp('2015-07-02 04:25:30') </code></pre> <p>if we try to add number of seconds to Pandas DateTime:</p> <pre><code>In [22]: pd.to_datetime('2015-01-31 00:00:00') + 13148730 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-22-c252fc51ec14&gt; in &lt;module&gt;() ----&gt; 1 pd.to_datetime('2015-01-31 00:00:00') + 13148730 pandas\tslib.pyx in pandas.tslib._Timestamp.__add__ (pandas\tslib.c:20225)() ValueError: Cannot add integral value to Timestamp without offset. </code></pre>
0
2016-09-03T08:08:30Z
[ "python", "pandas" ]
Flask testing keeps failing
39,303,754
<p>So I have web app where if the user is logged in, he cannot sign up. Instead he is redirected and a message saying he cannot sign up is flashed.</p> <p>The problem is I can't test it for some reason.</p> <p>Here is the view</p> <pre><code>@users_template.route('/signup', methods=['GET', 'POST']) def signup(): form = RegisterationForm() if current_user.is_authenticated and current_user.is_active: # prevent the user from seeing the register page if he's already logged in flash('You cannot sign up while you\'re logged in') return redirect(url_for('main.home')) if request.method == 'POST' and form.validate_on_submit(): username = form.username.data password = form.password.data user = User(username=username, password=password) if db.session.query(User).filter(User.username == username).first() is None: current_app.logger.info('&lt;{}&gt; did not register before. Registering him/her now'.format(username)) db.session.add(user) db.session.commit() flash('Thank you for registering. Please login now') return redirect(url_for('users.login')) else: # the user name has been registered before flash('You already registered') return render_template('signup.html', form=form) </code></pre> <p>Now in my test module I have this method</p> <pre><code>def test_signup_page_requires_logout(self): data_to_signup = {'username': 'mustafa1', 'password': 'mustafa1', 'confirm_password': 'mustafa1'} data_to_login = {'username': 'mustafa1', 'password': 'mustafa1'} # with statement preserves the request context for the current_user with self.client: self.client.post('/signup', data=data_to_signup) self.client.post('/login', data=data_to_login) response = self.client.get('/signup', follow_redirects=True) assert b'You cannot sign up while you\'re logged in' in response.data </code></pre> <p>What's even more confusing is that this structure works for other methods</p> <pre><code>def test_headquarter_after_login(self): data_to_signup = {'username': 'mustafa1', 'password': 'mustafa1', 'confirm_password': 'mustafa1'} data_to_login = {'username': 'mustafa1', 'password': 'mustafa1'} with self.client: self.client.post('/signup', data=data_to_signup) self.client.post('/login', data=data_to_login) response = self.client.get('/headquarter') assert b'Headquarter page' in response.data </code></pre> <p>EDIT: here is the login view</p> <pre><code>from .. import bcrypt @users_template.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm(request.form) if form.validate_on_submit() and request.method == 'POST': username = form.username.data password = form.password.data user = User.query.filter(User.username == username).first() if user is not None and bcrypt.check_password_hash(user.password, password): # authenticate login_user(user) # then log the user in flash('You are logged in') return redirect(url_for('main.home')) else: flash('Incorrect username or password') # if username is wrong, it will be caught by the error handling above return render_template('login.html', form=form) # for a GET request </code></pre> <p>This is the error (I'm using py.test fyi)</p> <pre><code> assert current_user.is_active() == True assert current_user.is_authenticated() == True &gt; assert b'You cannot sign up while you\'re logged in' in response.data E AssertionError: assert b"You cannot sign up while you're logged in" in b'&lt;!DOCTYPE html&gt;\n&lt;html lang="en"&gt;\n &lt;head&gt;\n &lt;meta charset="utf-8"&gt;\n &lt;meta http-equiv="X-UA-Compatible" cont...jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt;\n &lt;script src="/static/js/bootstrap.min.js"&gt; &lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n' E + where b'&lt;!DOCTYPE html&gt;\n&lt;html lang="en"&gt;\n &lt;head&gt;\n &lt;meta charset="utf-8"&gt;\n &lt;meta http-equiv="X-UA-Compatible" cont...jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt;\n &lt;script src="/static/js/bootstrap.min.js"&gt; &lt;/script&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n' = &lt;TestResponse 3874 bytes [200 OK]&gt;. </code></pre> <p>This is to display the flashed messages in all my templates(It's in my "base.html" which I inherit from)</p> <pre><code> {% if get_flashed_messages() %} {% for message in get_flashed_messages() %} &lt;div class='container'&gt; &lt;span class='alert alert-info'&gt; &lt;small&gt;{{ message }}&lt;/small&gt; &lt;/span&gt; &lt;/div&gt; {% endfor %} {% endif %} </code></pre> <p>I've made more tests using the flashed messages and it worked fine. Like this one for testing the user signup</p> <pre><code>assert b'Thank you for registering. Please login now' in response.data </code></pre>
0
2016-09-03T06:00:27Z
39,303,916
<p>Suggestion no:</p> <ol> <li><p>Because of this line:</p> <pre><code>if current_user.is_authenticated and current_user.is_active: </code></pre> <p>current_user has his <code>is_active</code> flag set as <code>False</code>. If I'm not right, then please paste test error.</p></li> <li><p>Another clue could be lack of flash messages in home template. Put this code below in for example <code>flashMessages.html</code>:</p> <pre><code>{% macro render_flashMessages() %} {% with messages = get_flashed_messages() %} {% if messages %} &lt;ul class="list-unstyled"&gt; {% for message in messages %} &lt;li&gt;&lt;div class="alert alert-info"&gt;{{ message|safe }}&lt;/div&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} {% endwith %} {% endmacro %} </code></pre> <p>then you can use it in this way in <code>home.html</code>:</p> <pre><code>{% from "flashMessages.html" import render_flashMessages %} {{ render_flashMessages() }} </code></pre></li> <li><p>Next thing to check is to use assert with something else than response.data, if you're using <a href="https://flask-webtest.readthedocs.io/en/latest/" rel="nofollow">Flask-WebTest</a> you can try:</p> <pre><code>assert b'You cannot sign up while you\'re logged in' in response.flashes[0][1] </code></pre> <p>Where <code>flashes</code> is:</p> <blockquote> <p>List of tuples (category, message) containing messages that were flashed during request.</p> </blockquote></li> <li><p>But if you're not using FlaskWebTest, you can check session:</p> <pre><code>from flask import session session['_flashes'][0][1] </code></pre></li> </ol>
1
2016-09-03T06:26:50Z
[ "python", "flask", "flask-testing" ]
How to count the number of vowels in a string without a function wrapper
39,303,789
<p>I've currently solving a MIT undergrad problem in Python 3.5. The goal is to write a Python script counting and printing the number of vowels in a string containing only lower-case letters without using a function wrapper or even a function definition (stated in the assignment, weird ?).</p> <pre><code>def vowels_count(s): i=0 counter = 0 while(s[i] != " "): if s[i] == "a" or s[i] == "e" or s[i] == "i" or s[i] == "o" or s[i] == "u": counter += 1 i = i + 1 return(counter) </code></pre> <p>I have two problems: 1/ first of, my own code using a while do structure meets a problem with the use of the index navigating from the first character to the last one. The debugger says: index out of range 2/ finally, if I have to comply with the MIT instructions, I would not be able to do anything in a single-line code without defining a function. </p> <p>Thanks for your support</p> <p>Why is this version not correct on the string index i ?</p> <pre><code>def vowels_count_1(s): i = 0 counter = 0 while(s[i] != ""): if s[i] == "a" or s[i] == "e" or s[i] == "i" or s[i] == "o" or s[i] == "u": counter += 1 i += 1 print("Number of vowels: " + str(counter)) </code></pre>
-1
2016-09-03T06:06:09Z
39,303,880
<p>You can use the condition of <code>i</code> being less than the length of your string to break out of the while loop. I also recommend the easier approach of just checking if the letter at <code>s[i]</code> is in a string composed of vowels:</p> <pre><code>def vowels_count(s): i = 0 counter = 0 while i &lt; len(s): if s[i] in 'aeiou': counter += 1 i += 1 return counter </code></pre> <p>If you wanted to do this in one line, you could use the length of a list comprehension:</p> <pre><code>counter = len([c for c in s if c in 'aeiou']) </code></pre>
5
2016-09-03T06:22:05Z
[ "python", "string" ]
How to count the number of vowels in a string without a function wrapper
39,303,789
<p>I've currently solving a MIT undergrad problem in Python 3.5. The goal is to write a Python script counting and printing the number of vowels in a string containing only lower-case letters without using a function wrapper or even a function definition (stated in the assignment, weird ?).</p> <pre><code>def vowels_count(s): i=0 counter = 0 while(s[i] != " "): if s[i] == "a" or s[i] == "e" or s[i] == "i" or s[i] == "o" or s[i] == "u": counter += 1 i = i + 1 return(counter) </code></pre> <p>I have two problems: 1/ first of, my own code using a while do structure meets a problem with the use of the index navigating from the first character to the last one. The debugger says: index out of range 2/ finally, if I have to comply with the MIT instructions, I would not be able to do anything in a single-line code without defining a function. </p> <p>Thanks for your support</p> <p>Why is this version not correct on the string index i ?</p> <pre><code>def vowels_count_1(s): i = 0 counter = 0 while(s[i] != ""): if s[i] == "a" or s[i] == "e" or s[i] == "i" or s[i] == "o" or s[i] == "u": counter += 1 i += 1 print("Number of vowels: " + str(counter)) </code></pre>
-1
2016-09-03T06:06:09Z
39,303,946
<p>As you learn more and more you'll be able to count the vowels in one line using <code>sum</code> and a generation expression.</p> <p>You could fix your loop <code>while i &lt; len(s)</code>, i.e. up to the length of the string, but much better is just to <em>iterate</em> over the sequence of characters we call "string".</p> <pre><code>for ch in s: if ch == 'a' or ... </code></pre> <p>No indices needed. No <code>i</code>.</p> <p>If you have learned the <code>in</code> operator already, you could simplify the test.</p> <hr> <p>Without a function probably means this:</p> <pre><code>s = "the string" # your code here print("vowel count:", counter) </code></pre> <p>But I'm not sure ...</p>
1
2016-09-03T06:30:38Z
[ "python", "string" ]
How to count the number of vowels in a string without a function wrapper
39,303,789
<p>I've currently solving a MIT undergrad problem in Python 3.5. The goal is to write a Python script counting and printing the number of vowels in a string containing only lower-case letters without using a function wrapper or even a function definition (stated in the assignment, weird ?).</p> <pre><code>def vowels_count(s): i=0 counter = 0 while(s[i] != " "): if s[i] == "a" or s[i] == "e" or s[i] == "i" or s[i] == "o" or s[i] == "u": counter += 1 i = i + 1 return(counter) </code></pre> <p>I have two problems: 1/ first of, my own code using a while do structure meets a problem with the use of the index navigating from the first character to the last one. The debugger says: index out of range 2/ finally, if I have to comply with the MIT instructions, I would not be able to do anything in a single-line code without defining a function. </p> <p>Thanks for your support</p> <p>Why is this version not correct on the string index i ?</p> <pre><code>def vowels_count_1(s): i = 0 counter = 0 while(s[i] != ""): if s[i] == "a" or s[i] == "e" or s[i] == "i" or s[i] == "o" or s[i] == "u": counter += 1 i += 1 print("Number of vowels: " + str(counter)) </code></pre>
-1
2016-09-03T06:06:09Z
39,307,132
<p>Here is an one line solution:</p> <pre><code>reduce(lambda t, c : (t + 1) if c in 'aeiou' else t, s.lower(), 0) </code></pre>
0
2016-09-03T12:55:26Z
[ "python", "string" ]
TfidfVectorizer in scikit-learn : ValueError: np.nan is an invalid document
39,303,912
<p>I'm using TfidfVectorizer from scikit-learn to do some feature extraction from text data. I have a CSV file with a Score (can be +1 or -1) and a Review (text). I pulled this data into a DataFrame so I can run the Vectorizer.</p> <p>This is my code: </p> <pre><code>import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer df = pd.read_csv("train_new.csv", names = ['Score', 'Review'], sep=',') # x = df['Review'] == np.nan # # print x.to_csv(path='FindNaN.csv', sep=',', na_rep = 'string', index=True) # # print df.isnull().values.any() v = TfidfVectorizer(decode_error='replace', encoding='utf-8') x = v.fit_transform(df['Review']) </code></pre> <p>This is the traceback for the error I get: </p> <pre><code>Traceback (most recent call last): File "/home/PycharmProjects/Review/src/feature_extraction.py", line 16, in &lt;module&gt; x = v.fit_transform(df['Review']) File "/home/b/hw1/local/lib/python2.7/site- packages/sklearn/feature_extraction/text.py", line 1305, in fit_transform X = super(TfidfVectorizer, self).fit_transform(raw_documents) File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform self.fixed_vocabulary_) File "/home/b/work/local/lib/python2.7/site- packages/sklearn/feature_extraction/text.py", line 752, in _count_vocab for feature in analyze(doc): File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 238, in &lt;lambda&gt; tokenize(preprocess(self.decode(doc))), stop_words) File "/home/b/work/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 118, in decode raise ValueError("np.nan is an invalid document, expected byte or " ValueError: np.nan is an invalid document, expected byte or unicode string. </code></pre> <p>I checked the CSV file and DataFrame for anything that's being read as NaN but I can't find anything. There are 18000 rows, none of which return <code>isnan</code> as True. </p> <p>This is what <code>df['Review'].head()</code> looks like: </p> <pre><code> 0 This book is such a life saver. It has been s... 1 I bought this a few times for my older son and... 2 This is great for basics, but I wish the space... 3 This book is perfect! I'm a first time new mo... 4 During your postpartum stay at the hospital th... Name: Review, dtype: object </code></pre>
1
2016-09-03T06:26:03Z
39,308,809
<p>You need to convert the dtype <code>object</code> to <code>unicode</code> string as is clearly mentioned in the traceback.</p> <pre><code>x = v.fit_transform(df['Review'].values.astype('U')) ## Even astype(str) would work </code></pre> <p>From the Doc page of TFIDF Vectorizer:</p> <blockquote> <p>fit_transform(raw_documents, y=None) <br></p> <p>Parameters: raw_documents : iterable <br> an iterable which yields either <em>str</em>, <em>unicode</em> or <em>file objects</em></p> </blockquote>
2
2016-09-03T16:01:07Z
[ "python", "machine-learning", "scikit-learn", "tf-idf", "text-classification" ]
Convert time decimal to datetime object python
39,304,024
<p>I am trying to convert a decimal time to a datetime object to look for the months in order to later divide the time into seasons. I did some research and stumbled upon datetime.datetime.fromtimestamp but everything I have tried produces the following error:</p> <pre><code> TypeError: 'datetime.datetime' object is not iterable </code></pre> <p>In the past, I have used pandas to create a new time array, but do not feel that is best for my given situation. Currently I have the following in my code and tried doing it without the for loop as well, in hopes that I can get fromtimestamp() to work correctly.</p> <pre><code>raw_time = (data.variables['time'].getValue()/float(365*24))+1800 #hours since 1800 time = n.where((raw_time&gt;=2006)&amp;(time&lt;=2016)) #our specific time interval annual_time = [] for i in raw_time[time]: annual_time.extend(datetime.datetime.fromtimestamp(i)) </code></pre> <p>My time was read in from as netCDF file and currently appears as follows:</p> <pre><code>print raw_time[time] array([ 2006.05205479, 2006.1369863 , 2006.22191781, 2006.29863014, 2006.38356164, 2006.46575342, 2006.55068493, 2006.63287671, 2006.71780822, 2006.80273973, 2006.88493151, 2006.96986301, 2007.05205479, 2007.1369863 , 2007.22191781, 2007.29863014, 2007.38356164, 2007.46575342, 2007.55068493, 2007.63287671, 2007.71780822, 2007.80273973, 2007.88493151, 2007.96986301, 2008.05205479, 2008.1369863 , 2008.22191781, 2008.30136986, 2008.38630137, 2008.46849315, 2008.55342466, 2008.63561644, 2008.72054795, 2008.80547945, 2008.88767123, 2008.97260274, ...]) </code></pre>
1
2016-09-03T06:41:16Z
39,304,528
<p>The error message is because of your use of <code>extend</code>:</p> <pre><code>annual_time = [] for i in raw_time[time]: annual_time.extend(datetime.datetime.fromtimestamp(i)) </code></pre> <p><em>list</em><code>.extend()</code> is used to take another list or iterable and add its contents to the end of the list. <code>datetime</code> does not return a list or iterable; it returns a datetime instance. For scalar values, you need to use <code>append</code>:</p> <pre><code>annual_time = [] for i in raw_time[time]: annual_time.append(datetime.datetime.fromtimestamp(i)) </code></pre> <p>Having said that, I think you will need to manipulate the time values before using this function, because the values you are giving do not look like timestamps (which are a number of seconds past January 1, 1970, 00:00:00 UTC) - unless those times really are supposed to be about half an hour after midnight January 1, 1970...</p>
1
2016-09-03T07:43:49Z
[ "python", "datetime" ]
Convert time decimal to datetime object python
39,304,024
<p>I am trying to convert a decimal time to a datetime object to look for the months in order to later divide the time into seasons. I did some research and stumbled upon datetime.datetime.fromtimestamp but everything I have tried produces the following error:</p> <pre><code> TypeError: 'datetime.datetime' object is not iterable </code></pre> <p>In the past, I have used pandas to create a new time array, but do not feel that is best for my given situation. Currently I have the following in my code and tried doing it without the for loop as well, in hopes that I can get fromtimestamp() to work correctly.</p> <pre><code>raw_time = (data.variables['time'].getValue()/float(365*24))+1800 #hours since 1800 time = n.where((raw_time&gt;=2006)&amp;(time&lt;=2016)) #our specific time interval annual_time = [] for i in raw_time[time]: annual_time.extend(datetime.datetime.fromtimestamp(i)) </code></pre> <p>My time was read in from as netCDF file and currently appears as follows:</p> <pre><code>print raw_time[time] array([ 2006.05205479, 2006.1369863 , 2006.22191781, 2006.29863014, 2006.38356164, 2006.46575342, 2006.55068493, 2006.63287671, 2006.71780822, 2006.80273973, 2006.88493151, 2006.96986301, 2007.05205479, 2007.1369863 , 2007.22191781, 2007.29863014, 2007.38356164, 2007.46575342, 2007.55068493, 2007.63287671, 2007.71780822, 2007.80273973, 2007.88493151, 2007.96986301, 2008.05205479, 2008.1369863 , 2008.22191781, 2008.30136986, 2008.38630137, 2008.46849315, 2008.55342466, 2008.63561644, 2008.72054795, 2008.80547945, 2008.88767123, 2008.97260274, ...]) </code></pre>
1
2016-09-03T06:41:16Z
39,332,582
<p>You should use <a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF4 num2date</a> to convert <code>time</code> from numeric values to datetime objects. </p> <pre><code>import netCDF4 ncfile = netCDF4.Dataset('./foo.nc', 'r') time = ncfile.variables['time'] # do not cast to numpy array yet time_convert = netCDF4.num2date(time[:], time.units, time.calendar) </code></pre> <p>This will create a <code>time_convert</code> array of datetime objects that you can then work with to generate seasons, for example. </p>
0
2016-09-05T14:18:30Z
[ "python", "datetime" ]
Code debugging, why leds won't turn off after operation?
39,304,052
<p>I wroted a code, whitch turns on leds by the date and color from the txt file. If the date is correct leds turns on, but when correct time passes leds wont turn off, they still glowing until next date. So, why leds won't turn off, where is the problem? Please help, I have tried almost everything. </p> <pre><code>import sys import time import datetime import RPi.GPIO as GPIO import SDL_DS1307 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) LED_R = 17 LED_G = 27 LED_B = 22 GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt" starttime = datetime.datetime.utcnow() ds1307 = SDL_DS1307.SDL_DS1307(1, 0x68) ds1307.write_now() while True: currenttime = datetime.datetime.utcnow() deltatime = currenttime - starttime data=time.strftime("%Y"+"%m"+"%d"+"%H"+"%M") with open('data.txt') as f: for line in f: parts=line.split() if parts[0]&lt;=(data)&lt;=parts[1]: if parts[2]=='raudona': GPIO.putput(LED_R, False) GPIO.putput(LED_G, True) GPIO.putput(LED_B, True) elif parts[2]=='zalia': GPIO.putput(LED_R, True) GPIO.putput(LED_G, False) GPIO.putput(LED_B, True) elif parts[2]=='melyna': GPIO.putput(LED_R, True) GPIO.putput(LED_G, True) GPIO.putput(LED_B, False) elif parts[2]=='geltona': GPIO.putput(LED_R, False) GPIO.putput(LED_G, True) GPIO.putput(LED_B, False) elif parts[2]=='zydra': GPIO.putput(LED_R, True) GPIO.putput(LED_G, False) GPIO.putput(LED_B, False) elif parts[2]=='violetine': GPIO.putput(LED_R, False) GPIO.putput(LED_G, False) GPIO.putput(LED_B, True) elif parts[2]=='balta': GPIO.putput(LED_R, False) GPIO.putput(LED_G, False) GPIO.putput(LED_B, False) time.sleep(10.0) </code></pre>
1
2016-09-03T06:45:15Z
39,304,248
<p>Hey brother I believe I have found the answer to your problem. Okay here is what you will do. <a href="https://learn.adafruit.com/debugging-with-the-raspberry-pi-webide/debug-a-blinking-led" rel="nofollow">THIS IS A THOROUGH GUIDE ON DEBUGGING A BLINKING LED</a></p> <p>Endeavour to go through the guide as it contains useful information on solving the issue that you are experiencing.</p> <p>You see Raspberry Pi is a very interesting and unique piece of device</p>
0
2016-09-03T07:07:55Z
[ "python", "raspberry-pi", "raspbian", "led", "raspberry-pi3" ]
Code debugging, why leds won't turn off after operation?
39,304,052
<p>I wroted a code, whitch turns on leds by the date and color from the txt file. If the date is correct leds turns on, but when correct time passes leds wont turn off, they still glowing until next date. So, why leds won't turn off, where is the problem? Please help, I have tried almost everything. </p> <pre><code>import sys import time import datetime import RPi.GPIO as GPIO import SDL_DS1307 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) LED_R = 17 LED_G = 27 LED_B = 22 GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt" starttime = datetime.datetime.utcnow() ds1307 = SDL_DS1307.SDL_DS1307(1, 0x68) ds1307.write_now() while True: currenttime = datetime.datetime.utcnow() deltatime = currenttime - starttime data=time.strftime("%Y"+"%m"+"%d"+"%H"+"%M") with open('data.txt') as f: for line in f: parts=line.split() if parts[0]&lt;=(data)&lt;=parts[1]: if parts[2]=='raudona': GPIO.putput(LED_R, False) GPIO.putput(LED_G, True) GPIO.putput(LED_B, True) elif parts[2]=='zalia': GPIO.putput(LED_R, True) GPIO.putput(LED_G, False) GPIO.putput(LED_B, True) elif parts[2]=='melyna': GPIO.putput(LED_R, True) GPIO.putput(LED_G, True) GPIO.putput(LED_B, False) elif parts[2]=='geltona': GPIO.putput(LED_R, False) GPIO.putput(LED_G, True) GPIO.putput(LED_B, False) elif parts[2]=='zydra': GPIO.putput(LED_R, True) GPIO.putput(LED_G, False) GPIO.putput(LED_B, False) elif parts[2]=='violetine': GPIO.putput(LED_R, False) GPIO.putput(LED_G, False) GPIO.putput(LED_B, True) elif parts[2]=='balta': GPIO.putput(LED_R, False) GPIO.putput(LED_G, False) GPIO.putput(LED_B, False) time.sleep(10.0) </code></pre>
1
2016-09-03T06:45:15Z
39,306,026
<p>What a nice opportunity to use the <a href="https://docs.python.org/3.5/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">for-else construct</a>.</p> <p>If an instruction to turn LED lights on is found, turn the LEDs on and then break from the loop, because the task is completed.</p> <p>For the case, no instruction was found, i.e. no <code>break</code> was executed, add the <code>else</code> suite to the loop and turn off all LEDs there.</p> <pre><code> for line in f: parts=line.split() if parts[0]&lt;=(data)&lt;=parts[1]: if parts[2]=='raudona': GPIO.putput(LED_R, False) GPIO.putput(LED_G, True) GPIO.putput(LED_B, True) break elif parts[2]=='zalia': GPIO.putput(LED_R, True) GPIO.putput(LED_G, False) GPIO.putput(LED_B, True) break # elif ..... else: GPIO.putput(LED_R, False) GPIO.putput(LED_G, False) GPIO.putput(LED_B, False) </code></pre> <p>(code not tested, all my raspberries are in the garden)</p>
2
2016-09-03T10:44:26Z
[ "python", "raspberry-pi", "raspbian", "led", "raspberry-pi3" ]
how to call a member function in python by its function instance?
39,304,103
<p>Suppose we have the following code:</p> <pre><code>class T(object): def m1(self, a): ... f=T.m1 </code></pre> <p>How to call f on an instance of T?</p> <pre><code>x=T() x.f(..)? f(x, ..)? </code></pre>
1
2016-09-03T06:51:05Z
39,304,145
<p>Hopefully this explains it!</p> <pre><code>class T(object): def m1(self, a): return a f=T().m1 #must initialize the class using '()' before calling a method of that class f(1) f = T() f.m1(1) f = T().m1(1) f = T f().m1(1) f = T.m1 f(T(), 1) #can call the method without first initializing the class because we pass a reference of the methods class f = T.m1 f2 = T() f(f2, 1) </code></pre>
0
2016-09-03T06:55:33Z
[ "python" ]
how to call a member function in python by its function instance?
39,304,103
<p>Suppose we have the following code:</p> <pre><code>class T(object): def m1(self, a): ... f=T.m1 </code></pre> <p>How to call f on an instance of T?</p> <pre><code>x=T() x.f(..)? f(x, ..)? </code></pre>
1
2016-09-03T06:51:05Z
39,304,574
<p>A member function is just like any other function, except it takes <code>self</code> as the first argument and there is a mechanism which passes that argument automatically.</p> <p>So, the short answer is, use it ths way:</p> <pre><code>class T(object): def m1(self, a): pass f=T.m1 x = T() f(x, 1234) </code></pre> <h2>Unbound Method</h2> <p>This is because you are using T.m1, which is an <em>"unbound method"</em>. Unbound here means that its <code>self</code> argument is not bound to an instance.</p> <pre><code>&gt;&gt;&gt; T.m1 &lt;unbound method T.m1&gt; </code></pre> <h2>Bound Method</h2> <p>Unlike <code>T.m1</code>, <code>x.m1</code> gives you a bound method:</p> <pre><code>&gt;&gt;&gt; x.m1 &lt;bound method T.m1 of &lt;__main__.T object at 0x0000000002483080&gt;&gt; </code></pre> <p>You can reference a bound method and use it without passing <code>self</code> explicitly:</p> <pre><code>f2 = x.m1 f2(1234) </code></pre> <h2>Bind using <code>partial</code></h2> <p>You can also do the equivalent "binding" <code>self</code> yourself, with this code:</p> <pre><code>import functools unbound_f = T.m1 bound_f = functools.partial(unbound_f, x) bound_f(1234) </code></pre>
0
2016-09-03T07:48:10Z
[ "python" ]
python pdf (PyPDF2 module) - How to split/merge this?
39,304,167
<p>I was trying to split &amp; merge pdf files so that i can remove the first page of each pdf files.. Here's the code.</p> <pre><code> #python3 #split and merge pdf files! import os, PyPDF2 pdfFiles = [] os.chdir('C:\\Users\\Cyber\\Downloads\\5-111-fall-2008\\5-111-fall-2008\\contents\\readings-and-lecture-notes') for filename in os.listdir('.'): if filename.endswith('pdf'): pdfFiles.append(filename) pdfWriter = PyPDF2.PdfFileWriter() for filename in pdfFiles: pdfFileObj = open(filename, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) for pageNum in range(1, pdfReader.numPages): pageObj = pdfReader.getPage(pageNum) pdfWriter.addPage(pageObj) pdfOutput = open('Merged.pdf', 'wb') pdfWriter.write(pdfOutput) pdfOutput.close() </code></pre> <p>And then i get the following error...</p> <p>: PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]</p> <p>I searched for that error and found out that it indicates there may have been an issue with the creation of the PDF itself.</p> <p>Though i get my merged.pdf file as i wanted, i want to know what that exactly means &amp; how to avoid getting them.</p>
0
2016-09-03T06:58:01Z
39,305,139
<p>This warning means that the first section of the xref table does not begin with object zero. There may have been an error in writing the PDF. If strict = False, PyPDF2 will try to correct the object ID numbers. If strict = True, they will not be corrected.The default is True. Try <code>PyPDF2.PdfFileReader(pdfFileObj,False)</code></p>
1
2016-09-03T09:01:32Z
[ "python", "pypdf2" ]
How do I deal with Pandas Series data type that has NaN?
39,304,173
<p>What happens when using max() and min() on pandas.core.series.Series type that has NaN in it? Is this a bug? See below,</p> <hr> <pre><code>%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt mydata = pd.DataFrame(np.random.standard_normal((100,1)), columns=['No NaN']) mydata['Has NaN'] = mydata['No NaN'] / mydata['No NaN'].shift(1) # Both return NaN! print(min(mydata['Has NaN']), max(mydata['Has NaN'])) # Still why False? Isn't float('nan') a singleton like None? print(min(mydata['Has NaN']) == max(mydata['Has NaN'])) # But this time works well! print(min([1, 2, 3, float('nan')])) print('\n') # When Series data type that has NaN bumps into min() and max(), what should # I do? E.g., try: n, bins, patches = plt.hist(mydata['Has NaN'], 10) except ValueError as e: print(e, '\nSeems "range" argument in hist() has problem!') </code></pre>
2
2016-09-03T06:58:16Z
39,304,634
<p>you should use Pandas or NumPy functions instead of vanilla Python ones:</p> <pre><code>In [7]: mydata['Has NaN'].min(), mydata['Has NaN'].max() Out[7]: (-46.00309057827485, 62.430829637766671) In [8]: min(mydata['Has NaN']), max(mydata['Has NaN']) Out[8]: (nan, nan) In [125]: mydata.plot.hist(alpha=0.5) Out[125]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x1a784588&gt; </code></pre> <p><a href="http://i.stack.imgur.com/4XDwJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/4XDwJ.png" alt="enter image description here"></a></p>
3
2016-09-03T07:57:19Z
[ "python", "pandas", "matplotlib", "dataframe" ]
How do I deal with Pandas Series data type that has NaN?
39,304,173
<p>What happens when using max() and min() on pandas.core.series.Series type that has NaN in it? Is this a bug? See below,</p> <hr> <pre><code>%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt mydata = pd.DataFrame(np.random.standard_normal((100,1)), columns=['No NaN']) mydata['Has NaN'] = mydata['No NaN'] / mydata['No NaN'].shift(1) # Both return NaN! print(min(mydata['Has NaN']), max(mydata['Has NaN'])) # Still why False? Isn't float('nan') a singleton like None? print(min(mydata['Has NaN']) == max(mydata['Has NaN'])) # But this time works well! print(min([1, 2, 3, float('nan')])) print('\n') # When Series data type that has NaN bumps into min() and max(), what should # I do? E.g., try: n, bins, patches = plt.hist(mydata['Has NaN'], 10) except ValueError as e: print(e, '\nSeems "range" argument in hist() has problem!') </code></pre>
2
2016-09-03T06:58:16Z
39,304,658
<p>First, you shouldn't use the Python built-in <code>max</code> or <code>min</code> when dealing with <code>pandas</code> or <code>numpy</code>, especially when you are working with <code>nan</code>.</p> <p>Since 'nan' is the first item of <code>mydata['Has NaN']</code>, it is never replaced in either <code>max</code> or <code>min</code> because (as stated in the <a href="https://docs.python.org/3/reference/expressions.html#value-comparisons" rel="nofollow">docs</a>):</p> <blockquote> <p>The not-a-number values float('NaN') and Decimal('NaN') are special. They are identical to themselves (x is x is true) but are not equal to themselves (x == x is false). Additionally, comparing any number to a not-a-number value will return False. For example, both 3 &lt; float('NaN') and float('NaN') &lt; 3 will return False.</p> </blockquote> <p>Instead, use the <code>pandas</code> <code>max</code> and <code>min</code> methods:</p> <pre><code>In [4]: mydata['Has NaN'].min() Out[4]: -176.9844930355774 In [5]: mydata['Has NaN'].max() Out[5]: 12.684033138603787 </code></pre> <p>With regards to the histogram, it seems this is a known issue with <code>plt.hist</code>, see <a href="https://github.com/matplotlib/matplotlib/issues/6483" rel="nofollow">here</a> and <a href="https://github.com/matplotlib/matplotlib/issues/6992" rel="nofollow">here</a>.</p> <p>It should be fairly straightforward to deal with for now, though:</p> <pre><code>n, bins, patches = plt.hist(mydata['Has NaN'][~mydata['Has NaN'].isnull()], 10) </code></pre> <p><a href="http://i.stack.imgur.com/ytxEV.png" rel="nofollow"><img src="http://i.stack.imgur.com/ytxEV.png" alt="enter image description here"></a></p>
3
2016-09-03T08:00:55Z
[ "python", "pandas", "matplotlib", "dataframe" ]
Why is there a difference in format of encrypted passwords in Django
39,304,190
<p>I am using Django 1.97. The encrypted passwords are significantly different (in terms of the format).</p> <p>Some passwords are of format $$$: </p> <pre><code>pbkdf2_sha256$24000$61Rm3LxOPsCA$5kV2bzD32bpXoF6OO5YuyOlr5UHKUPlpNKwcNVn4Bt0= </code></pre> <p>While others are of format :</p> <pre><code>!9rPYViI1oqrSMfkDCZSDeJxme4juD2niKcyvKdpB </code></pre> <p>Passwords are set either using <code>User.objects.create_user()</code> or <code>user.set_password()</code>. Is this difference an expected one ?</p>
0
2016-09-03T07:00:51Z
39,304,294
<p>There is no significant difference between <code>User.objects.create_user()</code> and <code>user.set_password()</code> since first uses second.</p> <p>Basically, passwords are in string with format <code>&lt;algorithm&gt;$&lt;iterations&gt;$&lt;salt&gt;$&lt;hash&gt;</code> according to <a href="https://docs.djangoproject.com/en/1.9/topics/auth/passwords/" rel="nofollow">docs</a>. The differences might come from <code>PASSWORD_HASHERS</code> settings variable. May be one password was created with one hasher and other password with another. But if you'll keep those hashers in variable mentioned above all should be fine, users will able to change it etc. You can read about it in little notice after <a href="https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#using-bcrypt-with-django" rel="nofollow">bcrypt</a> section.</p> <p>Also docs for <code>django.contrib.auth</code> package might be helpful too. <a href="https://docs.djangoproject.com/en/1.9/topics/auth/" rel="nofollow">Link</a>.</p> <p><strong>UPDATE</strong>:</p> <p>If you find documentation of an old django versions <a href="https://django.readthedocs.io/en/1.3.X/topics/auth.html#passwords" rel="nofollow">(1.3</a> for example), you will see that</p> <blockquote> <p>Previous Django versions, such as 0.90, used simple MD5 hashes without password salts. For backwards compatibility, those are still supported; they'll be converted automatically to the new style the first time check_password() works correctly for a given user.</p> </blockquote> <p>So I think that the answer might be somewhere here. But it really depends on how legacy your project is, so you can decide if it's normal or what. Anyway you can issue <code>check_password()</code> to be sure. Or you can just email your user with "change password please" notification. There are many factors involved really.</p>
0
2016-09-03T07:14:20Z
[ "python", "django" ]
Why is there a difference in format of encrypted passwords in Django
39,304,190
<p>I am using Django 1.97. The encrypted passwords are significantly different (in terms of the format).</p> <p>Some passwords are of format $$$: </p> <pre><code>pbkdf2_sha256$24000$61Rm3LxOPsCA$5kV2bzD32bpXoF6OO5YuyOlr5UHKUPlpNKwcNVn4Bt0= </code></pre> <p>While others are of format :</p> <pre><code>!9rPYViI1oqrSMfkDCZSDeJxme4juD2niKcyvKdpB </code></pre> <p>Passwords are set either using <code>User.objects.create_user()</code> or <code>user.set_password()</code>. Is this difference an expected one ?</p>
0
2016-09-03T07:00:51Z
39,306,071
<p>You'll be fine. You just have some blank passwords in your database. </p> <p>Going back as far as <a href="https://github.com/django/django/blob/stable/0.95.x/django/contrib/auth/models.py#L13" rel="nofollow">V0.95</a>, django used the <code>$</code> separators for delimiting algorithm/salt/hash. These days, django <a href="https://github.com/django/django/blob/master/django/contrib/auth/hashers.py#L136" rel="nofollow">pulls out the algorithm first</a> by looking at what is in front of the first <code>$</code> and then passes the whole lot to the hasher to decode. This allows for a wider set of formats, including the one for PBKDF2 which adds an extra iterations parameter in this list (as per your first example).</p> <p>However, it also recognises that some users may not be allowed to login and/or have no password. This is encoded using the second format you've seen. As you can see <a href="https://github.com/django/django/blob/master/django/contrib/auth/hashers.py#L71" rel="nofollow">here</a>:</p> <blockquote> <p>If password is None then a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string will be returned which disallows logins.</p> </blockquote> <p>You can also see that the random string is exactly 40 characters long - just like your second example.</p> <p>In short, then, this is all as expected.</p>
1
2016-09-03T10:48:51Z
[ "python", "django" ]
QObject::startTimer: QTimer can only be used with threads started with QThread?
39,304,366
<p>I have given the model a parent, but it still shows error message when exiting, what was wrong in the following code</p> <pre><code>#!/usr/bin/env python2 import os import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4 import uic import re CODE = 'xxx' class MyWindow(QDialog): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) layout = QVBoxLayout(self) textedit = QTextEdit(self) textedit.setPlainText(CODE) layout.addWidget(textedit) self.setLayout(layout) self.resize(640, 280) self.lineedit = QLineEdit(self) self.lineedit.setGeometry(200, 12, 200, 32) self.completer = QCompleter(self) model = QStringListModel(self) model.setStringList(['1','2','3','4']) self.completer.setModel(model) self.lineedit.setCompleter(self.completer) def main(): app = QApplication(sys.argv) win = MyWindow() win.show() sys.exit(app.exec_()) if __name__ == "__main__": main() </code></pre> <p>The above code errors out when exiting.</p> <pre><code>$ python2.7 ./ask_keep_completer0.py QObject::startTimer: QTimer can only be used with threads started with QThread Segmentation fault (core dumped) </code></pre> <p><img src="http://i.imgur.com/WfevhJ3.gif" alt="img"></p>
0
2016-09-03T07:22:29Z
39,311,662
<p>after adding this call, it doesn't error out anymore</p> <pre><code>self.setAttribute(Qt.WA_DeleteOnClose) </code></pre>
0
2016-09-03T21:53:50Z
[ "python", "qt", "pyqt", "qcompleter" ]
execute time period in python
39,304,472
<p>I want to run the script in shell by sending time period like</p> <pre><code>./test.py 20160830000 201608311100 </code></pre> <p>How can I do this for the following python script? <code>s</code> and <code>t</code> are UNIX timestamp.</p> <pre><code>#!/usr/bin/python import requests from pprint import pprint import json import os import commands i = commands.getstatusoutput('date -d "2016-08-30" "+%s"') j = commands.getstatusoutput('date -d "2016-08-31" "+%s"') s = int(i[1]) t = int(j[1]) url = 'http://192.168.1.96/zabbix/api_jsonrpc.php' payload = { "jsonrpc": "2.0", "method": "history.get", "params": { "output": "extend", "history": 0, "time_from": s, "time_till": t, "hostsids": "10105", "itemids": "23688", "sortfield": "clock", "sortorder": "DESC" }, "auth": "b5f1f71d91146fcc2980e83e8aacd637", "id": 1 } header = { 'content-type': 'application/json-rpc', } res = requests.post(url, data=json.dumps(payload, indent=True), headers=header) res = res.json() pprint(res) </code></pre>
0
2016-09-03T07:36:21Z
39,304,635
<p>Take a look at the <a href="https://docs.python.org/2/library/time.html" rel="nofollow">time</a> python module, specifically the <a href="https://docs.python.org/2/library/time.html#time.strptime" rel="nofollow">time.strptime</a> function for parsing human-readable time strings into a time structure and the <a href="https://docs.python.org/2/library/time.html#time.mktime" rel="nofollow">time.mktime</a> function for converting a time structure into a unix timestamp.</p>
0
2016-09-03T07:57:31Z
[ "python", "json", "linux" ]
execute time period in python
39,304,472
<p>I want to run the script in shell by sending time period like</p> <pre><code>./test.py 20160830000 201608311100 </code></pre> <p>How can I do this for the following python script? <code>s</code> and <code>t</code> are UNIX timestamp.</p> <pre><code>#!/usr/bin/python import requests from pprint import pprint import json import os import commands i = commands.getstatusoutput('date -d "2016-08-30" "+%s"') j = commands.getstatusoutput('date -d "2016-08-31" "+%s"') s = int(i[1]) t = int(j[1]) url = 'http://192.168.1.96/zabbix/api_jsonrpc.php' payload = { "jsonrpc": "2.0", "method": "history.get", "params": { "output": "extend", "history": 0, "time_from": s, "time_till": t, "hostsids": "10105", "itemids": "23688", "sortfield": "clock", "sortorder": "DESC" }, "auth": "b5f1f71d91146fcc2980e83e8aacd637", "id": 1 } header = { 'content-type': 'application/json-rpc', } res = requests.post(url, data=json.dumps(payload, indent=True), headers=header) res = res.json() pprint(res) </code></pre>
0
2016-09-03T07:36:21Z
39,304,743
<p>If I understand correctly, you want to get the timestamps to use in your jsonrpc call from the command line arguments, rather than using hardcoded dates (which for some reason you're processing through the command line too <code>date</code> using the deprecated <code>commands</code> module, rather than using Python's builtin <code>time</code> or <code>datetime</code> modules, which can handle timestamps and dates natively).</p> <p>This is quite easy. The command line arguments to a Python script are stored in the list <code>sys.argv</code>. The first value in the list is the filename of the script, the rest are the arguments. You may need to check that there are the expected number of them!</p> <p>Try something like this:</p> <pre><code># your other imports here import sys USAGE_MSG = "Usage: test.py START_TIMESTAMP END_TIMESTAMP" if len(sys.argv) != 3: print(USAGE_MSG) sys.exit(1) try: s = int(sys.argv[1]) t = int(sys.argv[2]) except TypeError: # couldn't convert one of the timestamps to int print("Invalid timestamp") print(USAGE_MSG) sys.exit(1) # the rest of your code can go here </code></pre> <p>There are a lot of alternative ways you could handle the error checking, I just made something up for this example. You should of course use whatever works best for your needs.</p>
1
2016-09-03T08:11:34Z
[ "python", "json", "linux" ]
Python coding exercise
39,304,512
<p>I have a function named orderInt passed three integers and returns true if the three int are in ascending order, otherwise false. Here's my code so far:</p> <pre><code>def orderInt(a, b, c): print "Enter 3 integers: " a = input() b = input() c = input() </code></pre> <p>How do I compare the variables? </p>
-7
2016-09-03T07:41:29Z
39,304,637
<p>First of all, your indentation is wrong.</p> <pre><code>def orderInt(): print "Enter 3 integers: " a = input() b = input() c = input() if a&lt;b&lt;c: return True else: return False print orderInt() </code></pre> <p>Second, your function is taking three arguments and also taking inputs. The arguments passed will be overwritten by your <code>input</code>s.</p> <pre><code>def orderInt(): print "Enter 3 integers: " if a&lt;b&lt;c: return True else: return False a = input() b = input() c = input() print orderInt(a,b,c) </code></pre> <p>Hope this helps.</p>
0
2016-09-03T07:58:23Z
[ "python", "python-2.7" ]
Python Cryptography: Cannot sign with RSA private key using PKCS1v15 padding
39,304,533
<p>I'm trying to implement a functionally equivalent signing with Python and the Cryptography library to PHP's <code>openssl_pkey_get_private</code> and <code>openssl_sign</code> using a SHA1 hash. I've read that PHP uses PKCS1v15 padding, so that's what I'm trying to use as well. My code is:</p> <pre><code>from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_private_key from cryptography.hazmat.backends import default_backend pk = open('key.pem', 'rb') key = load_pem_private_key(pk.read(), password=None, backend=default_backend()) message = b'hello world' signature = key.sign( message, padding.PKCS1v15, hashes.SHA1() ) </code></pre> <p>Executing this results in:</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-21-ef3db8a6f4a8&gt; in &lt;module&gt;() 3 message, 4 padding.PKCS1v15, ----&gt; 5 hashes.SHA1() 6 ) /home/vagrant/virtualenvs/test/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py in sign(self, data, padding, algorithm) 613 614 def sign(self, data, padding, algorithm): --&gt; 615 signer = self.signer(padding, algorithm) 616 signer.update(data) 617 signature = signer.finalize() /home/vagrant/virtualenvs/test/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py in signer(self, padding, algorithm) 550 551 def signer(self, padding, algorithm): --&gt; 552 return _RSASignatureContext(self._backend, self, padding, algorithm) 553 554 def decrypt(self, ciphertext, padding): /home/vagrant/virtualenvs/test/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py in __init__(self, backend, private_key, padding, algorithm) 170 171 if not isinstance(padding, AsymmetricPadding): --&gt; 172 raise TypeError("Expected provider of AsymmetricPadding.") 173 174 self._pkey_size = self._backend._lib.EVP_PKEY_size( TypeError: Expected provider of AsymmetricPadding. </code></pre>
3
2016-09-03T07:44:13Z
39,305,312
<p>The operator <code>isinstance</code> indicates that <code>padding.PKCS1v15</code> needs to be an instance instead of the type (class) itself. That means that the object instance should be created by calling the constructor.</p> <p>To do this add parentheses, i.e. <code>padding.PKCS1v15()</code>.</p>
2
2016-09-03T09:22:02Z
[ "php", "python", "cryptography", "pkcs#1" ]
should I store all encrypted password to database using generate_password_hash()
39,304,650
<p>When I use <code>generate_password_hash()</code> function, I get a encrypted password string which contains a random salt.</p> <pre><code>&gt;&gt;&gt; from werkzeug.security import generate_password_hash, check_password_hash &gt;&gt;&gt; generate_password_hash('password') &gt;&gt;&gt; 'pbkdf2:sha1:1000$3j8Brovx$9acddcd67da9e4c913817231c882a0f757e2d095' </code></pre> <p>If I store this string to database, someone else hacked into my database and get this string, it's easy to get the origin password using brute force cracking becasue the encrypted password contains the salt. </p> <pre><code>check_password_hash('pbkdf2:sha1:1000$9HycZ0Qa$94f08a91fba1c040c5bffb6c7e1ab5a6ad4818de', 'password') </code></pre> <p>Should I encrypt the origin password using my own salt first before using <code>generate_password_hash()</code> or is there a better solution?</p> <p>Thanks.</p>
0
2016-09-03T08:00:10Z
39,304,969
<blockquote> <p>it's easy to get the origin password using brute force cracking because the encrypted password contains the salt.</p> </blockquote> <p>No, it's "easy" to brute force, because you're having a low iteration count of 1000.</p> <blockquote> <p>Should I encrypt the origin password using my own salt first before using <code>generate_password_hash()</code> or is there a better solution?</p> </blockquote> <p>No, encryption is reversible and since a lost database also means that the encryption key is probably lost too, this would mean that the additional encryption is useless.</p> <p>An easy fix would be to increase the number of iterations to a million or 10 million depending on what you can afford on your server that your users don't run away because of a slow authentication procedure.</p> <pre><code>generate_password_hash('password', method='pbkdf2:sha256:1000000') </code></pre> <p>The problem with PBKDF2 is that it can be easily parallelized, because it doesn't need much memory. There are alternatives such as scrypt and Argon2 which can be configured to require much memory. Memory is currently the main limitation of dedicated password brute forcing machines based on ASICs.</p> <p>Ultimately, nothing you do, will lead to a secure authentication system if your users are using "password1" as their password. You should require your users to use complicated passwords with at least 12 characters including uppercase letters, lowercase letter and numbers (optionally including special characters). Those should also not be part of a dictionary.</p> <p>See more: <a href="http://security.stackexchange.com/q/211/45523">How to securely hash passwords?</a></p>
2
2016-09-03T08:41:25Z
[ "python", "encryption", "flask" ]
should I store all encrypted password to database using generate_password_hash()
39,304,650
<p>When I use <code>generate_password_hash()</code> function, I get a encrypted password string which contains a random salt.</p> <pre><code>&gt;&gt;&gt; from werkzeug.security import generate_password_hash, check_password_hash &gt;&gt;&gt; generate_password_hash('password') &gt;&gt;&gt; 'pbkdf2:sha1:1000$3j8Brovx$9acddcd67da9e4c913817231c882a0f757e2d095' </code></pre> <p>If I store this string to database, someone else hacked into my database and get this string, it's easy to get the origin password using brute force cracking becasue the encrypted password contains the salt. </p> <pre><code>check_password_hash('pbkdf2:sha1:1000$9HycZ0Qa$94f08a91fba1c040c5bffb6c7e1ab5a6ad4818de', 'password') </code></pre> <p>Should I encrypt the origin password using my own salt first before using <code>generate_password_hash()</code> or is there a better solution?</p> <p>Thanks.</p>
0
2016-09-03T08:00:10Z
39,306,671
<p>When you store password hashes, the main assumption is that it is too difficult to retrieve the password using brute force. If you want it to be safer, go for slower hash algorithims and longer passwords.</p> <p>Encryption is worse than a hash because hash is irreversible and brute force is the only way to retrieve the password. With encryption, brute force is just one of the options.</p> <p>Once that is clear, you have the option to have a "secret" salt in the code or salt can be saved with the hash. <strong>Saving the salt with the password is safer!</strong> Why? Because you have a different salt for each password, so the intruder has to brute force each password separately. If you have one global salt value, brute force can be done for all passwords in the datbase in one go.</p>
2
2016-09-03T12:02:33Z
[ "python", "encryption", "flask" ]
Why is Django reporting inconsistent values for this instance attribute?
39,304,819
<p>I have the following simple Django model class:</p> <pre><code>from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=254) parent_a = models.IntegerField() def update_names(self, name, other_a_list): a_set = set([self] + other_a_list) for curr_a in a_set: curr_a.name = name curr_a.save() print "Updated MyClassA #%s's name to %s" % (curr_a.pk, curr_a.name) def related_a_instances(self): family_list = MyClassA.objects.filter(parent_a=self.parent_a) return [curr_a for curr_a in family_list if curr_a.name == "CREATED"] </code></pre> <p>When I run the following code it, the last assertion fails:</p> <pre><code> m1 = MyClassA.objects.create(parent_a=99, name="OPEN",) m2 = MyClassA.objects.create(parent_a=99, name="CREATED",) assert m2.name == "CREATED" m3 = MyClassA.objects.create(parent_a=99, name="CREATED",) assert m3.name == "CREATED" related_a_instances = m2.related_a_instances() assert related_a_instances == [m2, m3] m2.update_names(name="OPEN", other_a_list=related_a_instances) print "Checking that MyClassA m1 (%s) is OPEN. My Code says its %s. DB says %s" % (m1.pk, m1.name, MyClassA.objects.get(pk=m1.pk).name) assert m1.name == "OPEN" print "Checking that MyClassA m2 (%s) is OPEN. My Code says its %s. DB says %s" % (m2.pk, m2.name, MyClassA.objects.get(pk=m2.pk).name) assert m2.name == "OPEN" print "Checking that MyClassA m3 (%s) is OPEN. My Code says its %s. DB says %s" % (m3.pk, m3.name, MyClassA.objects.get(pk=m3.pk).name) assert m3.name == "OPEN" </code></pre> <p>Here is the console output when the failure happens:</p> <pre><code>Updated MyClassA #2's name to OPEN Updated MyClassA #3's name to OPEN Checking that MyClassA m1 (1) is OPEN. My Code says its OPEN. DB says OPEN Checking that MyClassA m2 (2) is OPEN. My Code says its OPEN. DB says OPEN Checking that MyClassA m3 (3) is OPEN. My Code says its CREATED. DB says OPEN </code></pre> <p>Why does the calling function think <code>m3.status</code> is <code>'CREATED'</code> when clearly it was updated to <code>'OPEN'</code> in the <code>update_names()</code>? </p> <p>Weirdly, if I replace <code>m2.update_names(name='OPEN', other_a_list=related_a_instances)</code> with <code>m2.update_names(name='OPEN', other_a_list=[m2,m3])</code>, all assertions pass. What's going on here? I'm stumped!</p>
0
2016-09-03T08:21:39Z
39,304,879
<p>Because you haven't refreshed m3 from the database. <code>related_a_instances</code> fetches brand new objects from the database; even though those items refer to the same db rows as m1 to m3, they are not the same objects and updates to one do not affect the other.</p> <p>If you did <code>m3 = MyClassA.objects.get(pk=m3)</code> before your assertion, you would see the change.</p> <p>The reason your alternative method passes is that then you <em>are</em> sending the same object, m3, to the update method.</p>
2
2016-09-03T08:29:58Z
[ "python", "django", "django-models", "django-queryset" ]
Python list to sqlite
39,304,872
<pre><code>from bs4 import BeautifulSoup import requests import sqlite3 conn = sqlite3.connect('stadiumsDB.db') c = conn.cursor() c.executescript(''' DROP TABLE IF EXISTS Stadium; CREATE TABLE Stadium ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, Stadium TEXT UNIQUE, Club Text UNIQUE, Location Text UNIQUE ) ''') main_site = requests.get('https://en.wikipedia.org/wiki/List_of_Premier_League_stadiums').text soup = BeautifulSoup(main_site) column_names = [th.getText() for th in soup.findAll('th')[:9]] print column_names stadium_rows = soup.findAll('tr')[1:] stadium_data = [[td.getText() for td in stadium_rows[i].findAll('td')] for i in range(len(stadium_rows))] print stadium_data </code></pre> <p>I want to build a sqlite database. First row of the table will be the column name and i want them import from my column_names variable. Next rows i want them import from stadium_data variable. Any guidance please !!!!</p>
0
2016-09-03T08:29:22Z
39,316,118
<p>For your table definition you can insert <code>stadium_data</code> best with <a href="https://docs.python.org/2.7/library/sqlite3.html#sqlite3.Cursor.executemany" rel="nofollow">executemany</a> like</p> <pre><code>cn=column_names stadium=cn.index("Stadium") club=cn.index("Club") location=cn.index("Location") # this is for making sure that column order is correct c.executemany("insert into stadium(stadium, club, location) values (?,?,?)", ((row[stadium], row[club],row[location]) for row in stadium_data)) </code></pre> <p>This does not put <code>column_names</code> first in the table as this is doesnt seem like a good idea to me but you can do so with (insert this before the executemany)</p> <pre><code>c.execute("insert into stadium(id,stadium, club, location) values (?,?,?,?)", (0,cn[stadium], cn[club],cn[location])) </code></pre>
0
2016-09-04T10:50:15Z
[ "python", "sqlite" ]
Python threading with PyQt as decorator
39,304,951
<p>Hello fellow Overflowers, here's another code I've stuck in. I am using decorator to run some functions asycronously.</p> <p>file: async.py</p> <pre><code>from threading import Thread from functools import wraps def run(func): @wraps(func) def async_func(*args, **kwargs): func_hl = Thread(target=func, args=args, kwargs=kwargs) func_hl.daemon = False func_hl.start() return func_hl return async_func </code></pre> <p>And then:</p> <pre><code>import async [...] @async.run def foo(): while condition: do_something() </code></pre> <p>But now I make a project with QT and those QThreads.</p> <p>So,the question is: how should I improve my decorator to be QT-friendly? My effort so far was like that:</p> <pre><code>def better_thread(to_wrap): class MyThread(QtCore.QThread): def run(self, *args, **kwargs): _res = to_wrap(*args, **kwargs) return _res @wraps(to_wrap) def async_func(*args, **kwargs): def finish(): pass mythread = MyThread() mythread.start() result = mythread.run(*args, **kwargs) return result return async_func </code></pre> <p>Which I beleive is ugly and wrong. Could you help me?</p>
0
2016-09-03T08:38:59Z
39,386,669
<p>First here: <a href="http://stackoverflow.com/questions/1595649/threading-in-a-pyqt-application-use-qt-threads-or-python-threads">Threading in a PyQt application: Use Qt threads or Python threads?</a>, for some usufull advise.</p> <p>A simple "refactoring" of your code, to make it cleaner:</p> <pre><code>class Runner(QtCore.QThread): def __init__(self, target, *args, **kwargs): super().__init__() self._target = target self._args = args self._kwargs = kwargs def run(self): self._target(*self._args, **self._kwargs) def run(func): @wraps(func) def async_func(*args, **kwargs): runner = Runner(func, *args, **kwargs) # Keep the runner somewhere or it will be destroyed func.__runner = runner runner.start() return async_func </code></pre> <p><strong>EDIT</strong></p> <p>A simple test:</p> <pre><code>@run def test(): sleep(1) print('TEST') test() sleep(2) print('END') </code></pre>
1
2016-09-08T08:58:29Z
[ "python", "multithreading", "qt", "pyqt", "qthread" ]
Element-wise comparison of vector and scalar fails in rpy2 with Python 3
39,304,977
<p>It looks like rpy2 doesn't behave exactly the same in Python3 and Python2. In particular, in Python 2.7.x, I am able to compare a <a href="http://rpy2.readthedocs.io/en/version_2.8.x/vector.html" rel="nofollow">Vector</a> with a scalar, whereas in Python 3.5.x, if I try to do that, the following error is raised: </p> <pre><code>TypeError: unorderable types: IntVector() &gt; int() </code></pre> <p>Here is a snippet of my code:</p> <pre><code>&gt;&gt;&gt; from rpy2 import robjects &gt;&gt;&gt; x = robjects.IntVector([5, -1]) &gt;&gt;&gt; x &gt; 0 </code></pre> <p>And here is an extract of my <code>pip freeze</code> (same in both environments):</p> <pre><code>rpy2==2.8.2 numpy==1.11.1 </code></pre> <p>I would like to understand if it's a bug in rpy2 or simply a different behaviour of some library that rpy2 relies on (numpy for example).</p>
1
2016-09-03T08:41:58Z
39,310,160
<p>If a bug, I would think that it was with Python 2.</p> <p>An R vector is a sequence and the default Python behavior does not make such comparisons possible. For example:</p> <pre><code>&gt;&gt;&gt; [1,2,3] &lt; 2 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-5-f7a2f4fe21e0&gt; in &lt;module&gt;() ----&gt; 1 [1,2,3] &lt; 2 TypeError: unorderable types: list() &lt; int() </code></pre> <p>On the other hand, R's vectorized counterpart can be called throught the delegator <code>.ro</code> (as in "R Operator"). See <a href="https://rpy2.readthedocs.io/en/version_2.8.x/vector.html#operators" rel="nofollow">https://rpy2.readthedocs.io/en/version_2.8.x/vector.html#operators</a></p> <pre><code>&gt;&gt;&gt; v = IntVector([1,2,3]) &gt;&gt;&gt; v.ro &lt; 2 R object with classes: ('logical',) mapped to: &lt;BoolVector - Python:0x7fc7789a5a08 / R:0x22d25f8&gt; [ 1, 0, 0] </code></pre>
1
2016-09-03T18:33:39Z
[ "python", "python-3.x", "numpy", "rpy2" ]
Reuse large dequeued variable in Tensorflow
39,304,995
<p>I have a large tensor (some hundreds of megabytes) that is dequeued.</p> <pre><code>small_queue = tf.FIFOQueue(10, [tf.float64, tf.float64, tf.float64]) big_queue = tf.FIFOQueue(10, [tf.float64]) .... small1, small2, small3 = small_queue.dequeue() large = big_queue.dequeue() result = process(small1, small2, small3, large) ... with tf.Session() as S: R = S.run(result) </code></pre> <p>I'd like to reuse the <code>large</code> variable on subsequent calls to <code>S.run</code>, but I'm not sure how to do with the existing tensorflow <a href="https://www.tensorflow.org/versions/r0.10/how_tos/variable_scope/index.html" rel="nofollow" title="variable sharing">variable sharing</a> paradigm. <code>tf.get_variable</code> requires an initializer, so this is the wrong way to do it but illustrates what I'm trying to do:</p> <pre><code>with tf.variable_scope("cache"): large = tf.get_variable("large", initializer=big_queue.dequeue()) </code></pre> <p><strong>EDIT 1</strong>: Here is the a more complete example -- I'd like to cache <code>result1</code> and <code>result2</code> in <code>get_expr()</code></p> <pre><code>import time import numpy as np import threading import tensorflow as tf capacity=10 data_shape1 = [10, 3000, 128, 4] data_shape2 = [20, 500, 100] dtype1 = np.float64 dtype2 = np.int32 data_input1 = tf.placeholder(dtype1, shape=data_shape1) data_input2 = tf.placeholder(dtype2, shape=data_shape2) queue = tf.FIFOQueue(capacity=capacity, dtypes=[dtype1, dtype2], shapes=[data_shape1, data_shape2], name="FIFOQueue") def load_and_enqueue(session): enqueue_op = queue.enqueue([data_input1, data_input2]) for i in xrange(1, capacity+1): # Just feed random stuff to the queue random_data1 = np.full(data_shape1, i, dtype=dtype1) random_data2 = np.full(data_shape2, i, dtype=dtype2) # Feed example to Tensorflow placeholder feed_dict = { data_input1: random_data1, data_input2: random_data2 } print ("Enqueueing {i} with shape {s} " "and size {b} MB").format( i=i, s=random_data1.shape, b=random_data1.nbytes/(1024**2)) # Push all the training examples to the queue session.run(enqueue_op, feed_dict=feed_dict) def get_expr(): result1, result2 = queue.dequeue() # Would like to cache result1, result2 # at this point return result1 with tf.Session() as S: # Start enqueue thread t = threading.Thread(target=load_and_enqueue, args=(S,)) t.setDaemon(True) t.start() # Wait for all data to be enqueued t.join() expr1 = get_expr() expr2 = get_expr() S.run(tf.initialize_all_variables()) print S.run(expr1).ravel()[0] print S.run(expr2).ravel()[0] </code></pre>
1
2016-09-03T08:43:48Z
39,312,666
<p>I don't sure that I understand your question. </p> <p>If you just want to get <code>Tensor</code> variable you need <code>tf.get_variable</code> after <code>scope.reuse_variables()</code>:</p> <pre><code>with tf.scope('my_scope') as scope: scope.reuse_variables() large_var = tf.get_variable('my_large_var') #do something </code></pre> <p>If you need to evaluate multiple variables I suppose you need <code>sess.run([var1, var2])</code> (I'm not sure but in cifair10 example there is string <code>_, loss_value = sess.run([train_op, loss])</code>).</p>
0
2016-09-04T01:02:55Z
[ "python", "tensorflow" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1(5).func2() </code></pre> <p>how can i call func2 inside func1 or func3 inside func1 ? and yes, i do need func1, func2 and func3, i don't want to use class</p>
-1
2016-09-03T08:44:26Z
39,305,045
<p>Have You tried to call it ? And TIPs : Remember about indent </p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c funct2() #function called , WORKS ! </code></pre> <h1> </h1>
1
2016-09-03T08:49:26Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1(5).func2() </code></pre> <p>how can i call func2 inside func1 or func3 inside func1 ? and yes, i do need func1, func2 and func3, i don't want to use class</p>
-1
2016-09-03T08:44:26Z
39,305,072
<pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c return func2,func3 </code></pre> <p><strong>Closure may works</strong></p>
0
2016-09-03T08:51:58Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1(5).func2() </code></pre> <p>how can i call func2 inside func1 or func3 inside func1 ? and yes, i do need func1, func2 and func3, i don't want to use class</p>
-1
2016-09-03T08:44:26Z
39,305,077
<p>Although you don't really need new functions to do such simple tasks, calling functions in another function would be something like this:</p> <pre><code>def func2(b): return b*3 def func3(b): return b/5 def func1(a): b = a + 1 c = func2(b) print c c = func3(b) print c </code></pre> <p>and finally call your function with an input, 5 for example:</p> <pre><code>func1(5) </code></pre>
0
2016-09-03T08:52:32Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1(5).func2() </code></pre> <p>how can i call func2 inside func1 or func3 inside func1 ? and yes, i do need func1, func2 and func3, i don't want to use class</p>
-1
2016-09-03T08:44:26Z
39,305,345
<p>There is a way to achieve the syntax you want but it is <strong>highly irregular</strong> and I would <strong>strongly</strong> advise against using it. It is hacky.</p> <pre><code>def func1(a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1.func2 = func2 func1.func3 = func3 return func1 </code></pre> <p>Now, inside the interpreter shell:</p> <pre><code>&gt;&gt;&gt; def func1(a): ... b = a + 1 ... def func2(): ... c = b*3 ... print c ... def func3(): ... c = b/5 ... print c ... func1.func2 = func2 ... func1.func3 = func3 ... return func1 ... &gt;&gt;&gt; func1(5).func2() 18 &gt;&gt;&gt; </code></pre> <p>Please, for Guido, do not do this.</p>
0
2016-09-03T09:25:54Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1(5).func2() </code></pre> <p>how can i call func2 inside func1 or func3 inside func1 ? and yes, i do need func1, func2 and func3, i don't want to use class</p>
-1
2016-09-03T08:44:26Z
39,305,368
<p>The function objects <code>func2</code> and <code>func3</code> are local to the function <code>func1</code>, which means they do not exist outside of <code>func1</code> unless <code>func1</code> explicitly returns them to the calling environment. </p> <p>So if you want to call those functions <em>outside</em> of <code>func1</code> (as your posted code attempts to do) you need to do something like this:</p> <pre><code>def func1(a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c return func2, func3 f2, f3 = func1(5.0) f2() f3() </code></pre> <p><strong>output</strong></p> <pre><code>18.0 1.2 </code></pre> <p><code>f2</code> and <code>f3</code> will use the value of the <code>a</code> parameter that was given to <code>func1</code> when they were created. If you want to use a different <code>a</code> then simply call <code>func1</code> again; each time you call it new instances of the <code>func2</code> and <code>func3</code> function objects are created.</p> <p><hr> <em>Aside</em></p> <p>Note that I passed an argument of <code>5.0</code> rather than <code>5</code> to <code>func1</code>. That's to ensure that <code>b/5</code> in <code>func3</code> uses float division. That's not necessary in Python 3, and to get the Python 3 behaviour in Python 2 you can put</p> <pre><code>from __future__ import division </code></pre> <p>at the top of your script.</p>
0
2016-09-03T09:29:00Z
[ "python", "function", "nested" ]
django rest framework multiple url arguments
39,305,135
<p>In rest api view I need to have 2 objects. For example:</p> <pre><code>class Foo(models.Model): .... class Bar(models.Model): .... </code></pre> <p>What is correct way to get them? I mean how should I configure urls? I think this is not really good practice: <code>url(r'^foo/(?P&lt;pk&gt;\d+)/bar/(?P&lt;pk&gt;\d+)/$', FooBarView.as_view())</code> Or: <code>url(r'^foobar/$', FooBarView.as_view())</code> and then pass parameters: <code>?foo=1&amp;bar=2</code>.</p>
1
2016-09-03T09:00:22Z
39,305,548
<p>For django >= 1.5 You could pass parameters to class view doing somethin like this:</p> <pre><code>class Foo(TemplateView): template_name = "yourtemplatesdir/template.html" # Set any other attributes here # dispatch is called when the class instance loads def dispatch(self, request, *args, **kwargs): self.id = kwargs.get('foo_id', "other_def_id") self.barid = kwargs.get('bar_id', "other_def_id") # depending on your definition, this class might be different class Bar(TemplateView): template_name = "yourtemplatesdir/template.html" # Set any other attributes here # this method might not be necessary # dispatch is called when the class instance loads def dispatch(self, request, *args, **kwargs): self.id = kwargs.get('bar_id', "other_def_id") </code></pre> <p>In your url conf something like:</p> <pre><code>from .views import FooBar urlpatterns = patterns('', url( regex=r'^(?P&lt;foo_id&gt;\d+)/(?P&lt;bar_id&gt;\d+)/$' view=FooBar.as_view(), name='viewname' ), ) </code></pre> <p>Then, in your template view for FooBar, you could do:</p> <pre><code>{{ view.id }} {{ view.barid }} </code></pre> <p>I hope it helps, it could be more detailed if you provide further information about the object information needed in your '<em>action</em>'.</p>
0
2016-09-03T09:49:02Z
[ "python", "django", "django-rest-framework" ]
django rest framework multiple url arguments
39,305,135
<p>In rest api view I need to have 2 objects. For example:</p> <pre><code>class Foo(models.Model): .... class Bar(models.Model): .... </code></pre> <p>What is correct way to get them? I mean how should I configure urls? I think this is not really good practice: <code>url(r'^foo/(?P&lt;pk&gt;\d+)/bar/(?P&lt;pk&gt;\d+)/$', FooBarView.as_view())</code> Or: <code>url(r'^foobar/$', FooBarView.as_view())</code> and then pass parameters: <code>?foo=1&amp;bar=2</code>.</p>
1
2016-09-03T09:00:22Z
39,306,929
<p>I think it is more like a design problem.</p> <p>Which one is better? I will say it depends on what is the relationship between model foo and model bar.</p> <p>If you get model <strong>Class</strong> and model <strong>student</strong>, and you want to get student info and base on which class and relative student_number, like each class will have a student no.1. </p> <p>you can go:</p> <pre><code>url(r'^class/(?P&lt;class_pk&gt;\d+)/student/(?P&lt;student_pk&gt;\d+)/$') </code></pre> <p>If you want to get both model information, but you want put them into a statistic table,</p> <p>you can go:</p> <pre><code>url(r'^statistic/$') </code></pre> <p>then pass parameters like:</p> <pre><code> ?class=1&amp;student=2 </code></pre> <p>These are just simple examples, there should be other cases, and you should use other way to design your URL API.</p>
0
2016-09-03T12:33:38Z
[ "python", "django", "django-rest-framework" ]
multiclass classification with double values and scikit
39,305,189
<p>I would like to train a programm to give dicts various tags depending on the numeric values they contain - with scikit. My problem is, that I only seem to understand how to classify text (sentences) or just number variables (and not variables that contain mulitple numbers).</p> <p>Here is what I am trying to do:</p> <pre><code># available classes: # hot, cold, wet, sticky first_sample = {} first_sample["temp"] = 30 first_sample["airpressure"] = 104 first_sample["airmoisture"] = 70 second_sample = {} second_sample["temp"] = 2 second_sample["airpressure"] = 100 second_sample["airmoisture"] = 40 # do this manually X times train(first_sample, ['sticky', 'hot']) train(second_sample, ['wet', 'cold']) train(...) # then do it on a bunch of data by programme classify(bunch_of_data) </code></pre>
1
2016-09-03T09:07:26Z
39,311,420
<p>You need to train two classifiers and fit them to your data twice. Suppose your data is (you can convert your dicts to a dataframe using <code>Pandas</code>):</p> <pre><code>| "temp" | "airpressure" | "airmoisture"| "target1" | "target2" | |:------:|:-------------:|:------------:|:---------:|:---------:| | 30 | 104 | 70 | 'sticky' | 'hot' | | 2 | 100 | 40 | 'wet' | 'cold' | | . | . | . | . | . | | . | . | . | . | . | | . | . | . | . | . | </code></pre> <p>First, you fit the first classifier (clf1) to all your samples (lets call them X) and first column of your targets <code>target1</code> (lets call it y1)</p> <pre><code>clf1.fit(X,y1) </code></pre> <p>and then the second classifier (clf2) on X and second column of your target <code>target2</code> (or y2).</p> <pre><code>clf2.fit(X,y2) </code></pre>
0
2016-09-03T21:17:20Z
[ "python", "scikit-learn", "classification" ]