title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Django - Parsing URL in any order?
38,470,092
<p>I am setting up a Django/Django Rest Framework API and most of the queries are generated using parameters inside the url. The pattern follows <code>{param name}/{param value}</code>.</p> <p>For example:</p> <pre><code>users/ users/id/{id}/ users/name/{name}/ users/group/{group}/name/{name}/ users/group/{group}/ema...
-1
2016-07-19T23:25:13Z
38,470,218
<p>I would suggest to use query string instead.</p> <p>query: /users/?email=user@example.com&amp;name=Doge</p> <p>Then in your views:</p> <pre><code>email = self.request.query_params.get('email', None) name = self.request.query_params.get('name', None) </code></pre> <p>Your url pattern would just look like:</p> <p...
1
2016-07-19T23:41:24Z
[ "python", "regex", "django", "django-rest-framework" ]
How to connect HBase and Spark using Python?
38,470,114
<p>I have an embarrassingly parallel task for which I use Spark to distribute the computations. These computations are in Python, and I use PySpark to read and preprocess the data. The input data to my task is stored in HBase. Unfortunately, I've yet to find a satisfactory (i.e., easy to use and scalable) way to read/w...
3
2016-07-19T23:27:48Z
38,575,095
<p>I found <a href="https://issues.apache.org/jira/browse/HBASE-15225?focusedCommentId=15135626&amp;page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-15135626" rel="nofollow">this comment</a> by one of the makers of <code>hbase-spark</code>, which seems to suggest there is a way to use PySpa...
3
2016-07-25T18:34:31Z
[ "python", "apache-spark", "hbase", "pyspark", "apache-spark-sql" ]
Python not freeing RAM while processing large file in parallel
38,470,123
<p>I have a 25Gb plaintext file with ~10 million lines, several hundred words per line. Each line needs to be individually processed and I'm trying to split off chunks to a dozen workers to be processed in parallel. Currently loading in a million lines at a time (this for some reason takes up ~10Gb in RAM even though i...
4
2016-07-19T23:29:17Z
38,470,891
<p>You are not joining sub processes. After <code>list_of_values</code> done processes created by <code>Pool</code> still alive (kinda, more like zombie, but with alive parent process). They still hold all their values. You can't see their data in main because it in another processes (for same reason <code>gc.collect</...
4
2016-07-20T01:25:50Z
[ "python", "python-3.x", "memory-management", "parallel-processing" ]
I can't find a way to evade a Value Error using data from dataframe in sklearn pandas
38,470,124
<p>I am trying to run some basic machine learning algorithms on numerical data (floats) and am having issues getting the data to be read in. I using python 2.7, sklearn, pandas, and working through jupyter (ipython notebook). As a first pass I was trying to use a basic random forest search, however when using the funct...
2
2016-07-19T23:29:22Z
38,472,783
<p>In scikit-learn, a Classifier predicts a discrete variable, i.e. the data type of the target variable must be either integer or string. If you are trying to model a continuous variable, you must use a "regressor" model, in your case the equivalent model is <code>RandomForestRegresser</code>.</p>
1
2016-07-20T05:12:40Z
[ "python", "pandas", "machine-learning", "scikit-learn", "random-forest" ]
Summing values in a Dictionary of Lists
38,470,125
<p>I have a dictionary <code>dictData</code> that has been created from 3 columns (0, 3 and 4) of a csv file where each key is a datetime object and each value is a list, containing two numbers (let's call them a and b, so the list is [a,b]) stored as strings:</p> <pre><code>import csv import datetime as dt with open(...
6
2016-07-19T23:29:32Z
38,470,263
<h3>Setup</h3> <pre><code>dictData = {'2010': ['1', '2'], '2011': ['4', '3'], '2012': ['0', '45'], '2013': ['8', '7'], '2014': ['9', '0'], '2015': ['22', '1'], '2016': ['3', '4'], '2017': ['0', '5'], '2018': ['7', '8'], ...
8
2016-07-19T23:47:30Z
[ "python", "list", "pandas", "dictionary" ]
Summing values in a Dictionary of Lists
38,470,125
<p>I have a dictionary <code>dictData</code> that has been created from 3 columns (0, 3 and 4) of a csv file where each key is a datetime object and each value is a list, containing two numbers (let's call them a and b, so the list is [a,b]) stored as strings:</p> <pre><code>import csv import datetime as dt with open(...
6
2016-07-19T23:29:32Z
38,470,313
<pre><code>values = [(0,1), (2,3), (4,5)] values = np.array(values) print values[:, 0].sum() print values[:, 1].sum() print len([item for item in values[:, 0] if item == 0]) </code></pre>
0
2016-07-19T23:53:38Z
[ "python", "list", "pandas", "dictionary" ]
python sending sms with twilio
38,470,229
<pre><code>import os from flask import Flask from flask import request from flask import url_for from flask import render_template from twilio.rest import TwilioRestClient from twilio import twiml </code></pre> <h1>Declare and configure application</h1> <pre><code>app = Flask(__name__, static_url_path='/static') ...
0
2016-07-19T23:43:18Z
38,512,825
<p>Ok I resolved it, so if you are using python on twilio, this is the code to have your phone system that answers the call, puts the caller on hold playing music and then sends you an sms then you can call the number to help the caller.</p> <p>Here it is:</p> <pre><code>import os from flask import Flask from flask ...
0
2016-07-21T19:30:18Z
[ "python", "sms", "twilio" ]
Telegram timed response
38,470,246
<p>I am currently working on a Telegram Bot using the python api. I am using this example here <a href="https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py" rel="nofollow">https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py</a...
0
2016-07-19T23:45:33Z
38,497,228
<p>You can use the <code>JobQueue</code> for that.</p> <p>You can see an example here: <a href="https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/timerbot.py" rel="nofollow">https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/timerbot.py</a></p> <p>Make sure t...
0
2016-07-21T07:05:22Z
[ "python", "telegram", "python-telegram-bot" ]
Scrapy: extract JSON from within HTML script
38,470,261
<p>I'm trying to extract (what appears to be) JSON data from within an HTML script. The HTML script looks like this on the site:</p> <pre><code>&lt;script&gt; $(document).ready(function(){ var terms = new Verba.Compare.Collections.Terms([{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6...
0
2016-07-19T23:47:18Z
38,470,432
<p>You can't go "deeper" because that element's contents are just text. It's not too hard to read out the JSON from the JavaScript:</p> <pre><code>line = javascript.strip().splitlines()[1] the_json = line.split('(', 1)[1].split(')', 1)[0] </code></pre>
-1
2016-07-20T00:10:28Z
[ "python", "html", "json", "xpath", "scrapy" ]
Scrapy: extract JSON from within HTML script
38,470,261
<p>I'm trying to extract (what appears to be) JSON data from within an HTML script. The HTML script looks like this on the site:</p> <pre><code>&lt;script&gt; $(document).ready(function(){ var terms = new Verba.Compare.Collections.Terms([{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6...
0
2016-07-19T23:47:18Z
38,471,784
<p>I would extract it using a regex, something like:</p> <pre><code>response.xpath('/html/body/script[2]').re_first('\((\[.*\])\)') </code></pre>
0
2016-07-20T03:23:11Z
[ "python", "html", "json", "xpath", "scrapy" ]
Scrapy: extract JSON from within HTML script
38,470,261
<p>I'm trying to extract (what appears to be) JSON data from within an HTML script. The HTML script looks like this on the site:</p> <pre><code>&lt;script&gt; $(document).ready(function(){ var terms = new Verba.Compare.Collections.Terms([{"id":"6436","name":"SUMMER 16","inquiry":true,"ordering":true},{"id":"6...
0
2016-07-19T23:47:18Z
38,477,184
<p>You can use <a href="https://github.com/scrapinghub/js2xml" rel="nofollow">js2xml</a> for this.</p> <p>To illustrate, first, let's create a Scrapy selector with your sample HTML, and grab the JavaScript statements:</p> <pre><code>&gt;&gt;&gt; import scrapy &gt;&gt;&gt; sample = '''&lt;script&gt; ... $(document)....
1
2016-07-20T09:17:37Z
[ "python", "html", "json", "xpath", "scrapy" ]
IOError: [Errno Invalid output device (no default output device)] -9996
38,470,321
<p>I've copied and pasted some example code to play a wav file using pyaudio, but I get the error: <code>IOError: [Errno Invalid output device (no default output device)] -9996</code>.</p> <p>Here's the code:</p> <pre><code>import pyaudio import wave import sys CHUNK = 1024 if len(sys.argv) &lt; 2: print("Plays...
0
2016-07-19T23:54:50Z
38,914,636
<p>It seems PyAudio can't find your default device. One solution would be to add the parameter <code>output_device_index</code> to the initialization of your <code>stream</code> variable.</p> <p>For example, with a device index of 0</p> <pre><code>stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), ...
0
2016-08-12T09:33:02Z
[ "python", "pyaudio" ]
changing ylim with plot_date python
38,470,358
<p>I cannot figure out how to change the ylim on my yaxis with plot_date and have tried several options including ax.yaxis.set_ticks , plt.gca().set_ylim([start,end]). The lines being plotted are being cut off and extend over the scale of the y-axis. I am trying to increase the y-axis scale to show 7-09, or at least e...
0
2016-07-20T00:00:08Z
38,472,706
<p>The problem is with <code>ax.axis('tight')</code> this is overriding the rescaling of yaxis. Try using <code>plt.tight_layout()</code>. Here is the code you should have at the end</p> <pre><code>start = datetime.date(1953,5,23) end = datetime.date(1953,7,9) ax.set_ylim([start,end]) plt.tight_layout() plt.savefig(f...
0
2016-07-20T05:06:10Z
[ "python", "matplotlib" ]
Why do only certain lines in this if statement execute?
38,470,528
<pre><code>import sys import re import SocketServer from sys import stdin class MyTCPHandler(SocketServer.BaseRequestHandler): """ The RequestHandler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def hand...
-2
2016-07-20T00:24:42Z
38,470,906
<p>Are you sure that the server received this string - "The client has decided to close this connection. Good day."?</p> <p>The problem with your if statement is the "is" comparison, which compares whether the two variables point to the same object, as opposed to their values. </p> <p>Replacing it as follows works:</...
0
2016-07-20T01:28:09Z
[ "python", "sockets" ]
Python 2.7 Socket connection on 2 different networks?
38,470,537
<p>Title says all. I have a client and a server setup, but they only work with localhost. How can I connect to the socket from a different network?</p> <p>Client</p> <pre><code># Echo client program import socket print "Client" HOST = "localhost" # Symbolic name meaning all available interfaces PORT = 5...
0
2016-07-20T00:25:50Z
38,471,090
<ol> <li>Check your public ip address using online tools like <a href="http://whatismyipaddress.com/" rel="nofollow">http://whatismyipaddress.com/</a> </li> <li>Check your local ip address using ipconfig -a in windows ifconfig in linux. </li> </ol> <p>Now if you are behind a dsl router (generally, you are) these add...
0
2016-07-20T01:52:52Z
[ "python", "sockets", "networking" ]
why is a sum of strings converted to floats
38,470,550
<h3>Setup</h3> <p>consider the following dataframe (note the strings):</p> <pre><code>df = pd.DataFrame([['3', '11'], ['0', '2']], columns=list('AB')) df </code></pre> <p><a href="http://i.stack.imgur.com/iEQcv.png"><img src="http://i.stack.imgur.com/iEQcv.png" alt="enter image description here"></a></p> <pre><code...
14
2016-07-20T00:27:31Z
38,470,963
<p>Went with the good old stack trace. Learned a bit about pdb through Pycharm as well. Turns out what happens is the following:</p> <p>1) </p> <pre><code>cls.sum = _make_stat_function( 'sum', name, name2, axis_descr, 'Return the sum of the values for the requested axis', nanops.na...
15
2016-07-20T01:36:39Z
[ "python", "pandas" ]
Django - 'function' object is not iterable - Error during template rendering
38,470,553
<p>So, I've been trying to create a user login. When I click submit on my login form, I get this error:</p> <pre><code>Exception Type: TypeError Exception Value: 'function' object is not iterable </code></pre> <p>Here's the full Traceback: <a href="http://dpaste.com/3D1B7MG" rel="nofollow">http://dpaste.com/3D1B7MG<...
0
2016-07-20T00:27:50Z
38,517,560
<p>Alright, I was able to solve it. </p> <p>The problem was apparently in my base.html where I had:</p> <pre><code>&lt;li&gt;&lt;a href="{% url 'profile' %}"&gt;{{ user.username }}&lt;/a&gt;&lt;/li&gt; </code></pre> <p>and</p> <pre><code>&lt;li&gt;&lt;a href="{% url 'logout' %}"&gt;Log Out&lt;/a&gt;&lt;/li&gt; </co...
0
2016-07-22T03:13:31Z
[ "python", "html", "django" ]
What is a right method to apply relations between database?
38,470,554
<p>I want to create simple app to tracking people in rooms. I want have 2 table person and room. Something like this </p> <pre><code>class Person(models.Model): name = models.CharField() class Room(models.Model): number = models.IntegerField() max_occupancy = models.IntegerField() //set up max person in room </code><...
1
2016-07-20T00:27:51Z
38,470,996
<p>This might work:</p> <pre><code>from django.core.exceptions import ValidationError class Room(models.Model): number = models.IntegerField() max_occupancy = models.IntegerField() #set up max person in room class Person(models.Model): name = models.CharField(max_length=16) room = models.ForeignKey(R...
1
2016-07-20T01:41:32Z
[ "python", "django", "django-models", "django-database" ]
Django override behavior of double underscore relationship lookup in queries
38,470,569
<p>My main ask: Is there any way to change the behavior of a related lookup such as <code>MyModel.objects.filter(relationship__field="value")</code>?</p> <p>Consider this setup. I've got a one-to-many relationship with a custom Manager that filters out Books with <code>active=False</code></p> <pre><code>from django.d...
4
2016-07-20T00:30:11Z
38,470,774
<p>To quote the <a href="https://docs.djangoproject.com/en/1.9/topics/db/managers/#using-managers-for-related-object-access" rel="nofollow">documentation</a>:</p> <blockquote> <p>By default, Django uses an instance of a “plain” manager class when accessing related objects (i.e. choice.poll), not the default mana...
1
2016-07-20T01:07:32Z
[ "python", "sql", "django", "django-models", "django-orm" ]
Django override behavior of double underscore relationship lookup in queries
38,470,569
<p>My main ask: Is there any way to change the behavior of a related lookup such as <code>MyModel.objects.filter(relationship__field="value")</code>?</p> <p>Consider this setup. I've got a one-to-many relationship with a custom Manager that filters out Books with <code>active=False</code></p> <pre><code>from django.d...
4
2016-07-20T00:30:11Z
38,491,133
<p><em>Edit:</em> I'm not sure if you can override the QuerySet class somewhere to get this feature, my only suggestion would be to add <code>books__active=True</code> to your queries. </p> <p>I've added the code to a github repo with a test illustrating the issue if someone wants to take it for a spin. <a href="https...
0
2016-07-20T21:26:24Z
[ "python", "sql", "django", "django-models", "django-orm" ]
Django override behavior of double underscore relationship lookup in queries
38,470,569
<p>My main ask: Is there any way to change the behavior of a related lookup such as <code>MyModel.objects.filter(relationship__field="value")</code>?</p> <p>Consider this setup. I've got a one-to-many relationship with a custom Manager that filters out Books with <code>active=False</code></p> <pre><code>from django.d...
4
2016-07-20T00:30:11Z
38,802,183
<p>In <a href="https://docs.djangoproject.com/en/1.10/releases/1.10/#manager-use-for-related-fields-and-inheritance-changes" rel="nofollow">Django 1.10</a> the <code>Manager.use_for_related_fields</code> is deprecated in favor of setting <code>Meta.base_manager_name</code> on the model. See the updated documentation fo...
0
2016-08-06T08:26:37Z
[ "python", "sql", "django", "django-models", "django-orm" ]
Parsing specific values in multiple pages
38,470,596
<p>I have the following code with a purpose to parse specific information from each of multiple pages. The http of each of the multiple pages is structured and therefore I use this structure to collect all links at the same time for further parsing.</p> <pre><code>import urllib import urlparse import re from bs4 impor...
0
2016-07-20T00:34:42Z
38,470,643
<p>This should work : </p> <pre><code>As = [soup.find_all(href=True) for soup in soups] </code></pre> <p>This should give you all href tags</p> <p>If you only want hrefs with name 'a', then the following would work :</p> <pre><code>As = [soup.find_all('a',href=True) for soup in soups] </code></pre>
0
2016-07-20T00:42:41Z
[ "python", "web-scraping", "beautifulsoup" ]
Parsing specific values in multiple pages
38,470,596
<p>I have the following code with a purpose to parse specific information from each of multiple pages. The http of each of the multiple pages is structured and therefore I use this structure to collect all links at the same time for further parsing.</p> <pre><code>import urllib import urlparse import re from bs4 impor...
0
2016-07-20T00:34:42Z
38,470,754
<blockquote> <p>I am specifically interested in obtaining things like this: '/party-pictures/2007/something-for-everyone'. </p> <p>The next would be going for regular expression!!</p> </blockquote> <p>You don't necessarily need to use regular expressions, and, from what I understand, you can filter out the desi...
1
2016-07-20T01:03:40Z
[ "python", "web-scraping", "beautifulsoup" ]
How to append last row from 2D array in Python
38,470,678
<p>How can I append the last row of an array to itself ?</p> <p>something like:</p> <pre><code>x= np.array([(1,2,3,4,5)]) x= np.append(x, x[0], 1) </code></pre> <p>Also, Could you explain why this way of working with vectors yields an error?</p> <pre><code>for i in range(3): x.append(0) x [0, 0, 0] x= np.appe...
1
2016-07-20T00:48:04Z
38,470,771
<p>How about this:</p> <pre><code>np.append(arr=x, values=x[-1,None], axis=0) #array([[1, 2, 3, 4, 5], # [1, 2, 3, 4, 5]]) </code></pre>
0
2016-07-20T01:07:13Z
[ "python", "numpy" ]
How to append last row from 2D array in Python
38,470,678
<p>How can I append the last row of an array to itself ?</p> <p>something like:</p> <pre><code>x= np.array([(1,2,3,4,5)]) x= np.append(x, x[0], 1) </code></pre> <p>Also, Could you explain why this way of working with vectors yields an error?</p> <pre><code>for i in range(3): x.append(0) x [0, 0, 0] x= np.appe...
1
2016-07-20T00:48:04Z
38,470,788
<pre><code>&gt;&gt;&gt; np.append(x,x[-1:],0) array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]) </code></pre>
1
2016-07-20T01:09:16Z
[ "python", "numpy" ]
How to append last row from 2D array in Python
38,470,678
<p>How can I append the last row of an array to itself ?</p> <p>something like:</p> <pre><code>x= np.array([(1,2,3,4,5)]) x= np.append(x, x[0], 1) </code></pre> <p>Also, Could you explain why this way of working with vectors yields an error?</p> <pre><code>for i in range(3): x.append(0) x [0, 0, 0] x= np.appe...
1
2016-07-20T00:48:04Z
38,473,499
<pre><code>In [3]: x=np.array([(1,2,3,4,5)]) In [4]: x Out[4]: array([[1, 2, 3, 4, 5]]) In [5]: x=np.append(x,x[0],1) ... ValueError: all the input arrays must have same number of dimensions </code></pre> <p><code>x</code> is (1,5), <code>x[0]</code> is (5,) - one is 2d, the other 1d.</p> <pre><code>In [11]: x=np.vst...
2
2016-07-20T06:08:35Z
[ "python", "numpy" ]
What do the decimals mean before the Z in datetime?
38,470,691
<p>If I have the datetime string <code>2016-07-19T21:55:48.298Z</code>, what does the <code>.298</code> stand for?</p>
0
2016-07-20T00:50:55Z
38,621,225
<p>Milliseconds. You'd be down to micro if you had six decimals. <a href="https://en.wikipedia.org/wiki/ISO_8601#Times" rel="nofollow">https://en.wikipedia.org/wiki/ISO_8601#Times</a></p> <p>As answered in the comments by @yann-vernier</p>
1
2016-07-27T19:05:18Z
[ "python", "datetime" ]
Why are the subject and content empty when using python to send Email?
38,470,740
<p>I tried to run the following python script (copied from <a href="http://www.tutorialspoint.com/python/python_sending_email.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_sending_email.htm</a>) on a remote server to send an Email. I successfully received the Email in my mailbox, but unfortunately the...
0
2016-07-20T01:00:38Z
38,470,945
<p>Have you tried like below:</p> <pre><code>message['Subject'] = 'SMTP e-mail test' message['From'] = 'username@company.com' message['To'] = 'receivername@company.com' </code></pre>
-1
2016-07-20T01:32:51Z
[ "python", "email" ]
Finding Eulerian Tour in Python
38,470,753
<p>Going through the Udacity course on algorithms and created following functions to determine the Eulerian path of a given graph. While i pass the sample tests, the answer isn't accepted. Anyone got an idea why? Thanks for any pointers!</p> <pre><code># Find Eulerian Tour # # Write a function that takes in a graph # ...
0
2016-07-20T01:03:36Z
38,498,169
<p>I was going through the same course on Udacity. I have found a solution. Check the solution <a href="http://stackoverflow.com/questions/12447880/finding-a-eulerian-tour">here</a></p>
0
2016-07-21T07:50:39Z
[ "python", "algorithm" ]
How to get timezone from datetime string in python?
38,470,781
<p>I have a date string that looks like this <code>Tue Jul 19 2016 14:00:00 GMT-0700 (PDT)</code>. Is there a library or function that could do something like this?</p> <pre><code>print get_tz('Tue Jul 19 2016 14:00:00 GMT-0700 (PDT)') 'US/Pacific' </code></pre>
1
2016-07-20T01:08:05Z
38,485,535
<p>In general, you'll have to be careful about mapping time zone abbreviations to time zone identifiers. There's not a one-to-one mapping. For example, <code>CST</code> could be Central Standard Time, China Standard Time, or Cuba Standard Time.</p> <p>Since you have both an offset and an abbreviation, you might be a...
2
2016-07-20T16:05:37Z
[ "python", "datetime", "timezone" ]
How to get timezone from datetime string in python?
38,470,781
<p>I have a date string that looks like this <code>Tue Jul 19 2016 14:00:00 GMT-0700 (PDT)</code>. Is there a library or function that could do something like this?</p> <pre><code>print get_tz('Tue Jul 19 2016 14:00:00 GMT-0700 (PDT)') 'US/Pacific' </code></pre>
1
2016-07-20T01:08:05Z
38,554,391
<p>I agree with @MattJohnson that you need to be very careful when parsing short timezone names to <code>tzinfo</code> objects. However, if you have a specific context where only one reading makes sense (e.g. you are parsing timestamps generated in the United States), you can use the <code>tzinfos</code> argument to <c...
1
2016-07-24T16:45:22Z
[ "python", "datetime", "timezone" ]
Why won't KeyboardInterrupt work in Python when using Wing IDE 101?
38,470,812
<p>I'm trying to do something in a loop (in this example print to 100) and cancel the count at any time by pressing 'Ctrl+C'.</p> <p>The test code I'm using is below, however this doesn't work (EDIT: it works in a script launched from terminal but does not work when run in the python shell of my IDE - Wing 101). Keybo...
1
2016-07-20T01:14:30Z
38,486,869
<p>This is a limitation of Wing IDE 101. The only way to stop a loop like this is to restart the shell.</p>
0
2016-07-20T17:16:42Z
[ "python", "python-2.7", "keyboardinterrupt", "wing-ide" ]
500 Internal Server Error when connecting to MySQL with Flask
38,470,821
<p>I am starting off with Flask by following this tutorial: <a href="http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972" rel="nofollow">http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972</a></p> <p>The sourc...
1
2016-07-20T01:15:48Z
38,471,371
<p>if you are using apache server, Check error log of apache to see the actual error</p>
0
2016-07-20T02:32:25Z
[ "python", "mysql" ]
Click button, then scrape data on seemingly static webpage?
38,470,838
<p>I'm trying to scrape the player statistics in the <code>Totals</code> table at this link: <a href="http://www.basketball-reference.com/players/j/jordami01.html" rel="nofollow">http://www.basketball-reference.com/players/j/jordami01.html</a>. It's much more difficult to scrape the data as-is when you first appear on ...
1
2016-07-20T01:18:38Z
38,470,932
<p><em>You don't need <code>BeautifulSoup</code> here</em>. Click the <code>CSV</code> button with selenium, extract the contents of the appeared <code>pre</code> element with CSV data and parse it with <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">built-in <code>csv</code> module:</a></p> <pre><...
2
2016-07-20T01:31:16Z
[ "python", "selenium" ]
print dataframe without losing format
38,470,875
<p>How can I print a df without losing the format?</p> <p>Lets say I have a df like this:</p> <pre><code>In: df Out: TFs No Esenciales Genes regulados Genes Regulados Positivamente Genes Regulados Negativamente No Tentativo de genes a silenciar No Real de genes a silenciar No Tentativo de genes a inducir 1...
0
2016-07-20T01:23:55Z
38,471,079
<p>Per the <a href="http://pandas.pydata.org/pandas-docs/stable/options.html" rel="nofollow">docs</a>, you can use the <code>display.width</code> option in Pandas.</p> <p>Something like the following should work (although you may have to increase the <code>1000</code> width value if it's still getting cut-off).</p> <...
1
2016-07-20T01:51:49Z
[ "python", "pandas", "printing", "dataframe" ]
Python: global name 'maximum' is not defined
38,470,886
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'A':[100,300,500,600], 'B':[100,200,300,400], 'C':[1000,2000,3000,4000], 'D':[1,4,5,6], 'E':[2,5,2,7]}) </code></pre> <p>and when applying the pairwise maximum t...
1
2016-07-20T01:25:23Z
38,470,940
<p>Did you miss "np." by any chance after importing numpy as np . Here is my output from my MacBook : </p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.maximum(df.A,df.B) 0 100 1 300 2 500 3 600 Name: A, dtype: int64 </code></pre>
4
2016-07-20T01:32:31Z
[ "python", "numpy", "pandas" ]
Python: global name 'maximum' is not defined
38,470,886
<p>I have a dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'A':[100,300,500,600], 'B':[100,200,300,400], 'C':[1000,2000,3000,4000], 'D':[1,4,5,6], 'E':[2,5,2,7]}) </code></pre> <p>and when applying the pairwise maximum t...
1
2016-07-20T01:25:23Z
38,471,604
<p>pandas alternative:</p> <pre><code>In [32]: df[['A','B']].max().max() Out[32]: 600 </code></pre> <p>step-by-step:</p> <pre><code>In [31]: df[['A','B']].max() Out[31]: A 600 B 400 dtype: int64 </code></pre> <p>if you need a maximum per row:</p> <pre><code>In [35]: df[['A','B']].max(axis=1) Out[35]: 0 10...
1
2016-07-20T02:59:11Z
[ "python", "numpy", "pandas" ]
Using .format() to print a string that does not exceed a defined number of spaces and is centered?
38,470,930
<p>So Im trying to do three things here. 1. Get the print statement below to be 16 spaces long 2. Cut off the extra = signs on eiter side of the name that cause it to be longer than 16. 3. Center the text so an equal amount of = signs are either side of the name</p> <p>This is my attempt...</p> <pre><code>import ran...
1
2016-07-20T01:30:51Z
38,471,007
<p>You can define a function that will return your desired output:</p> <pre><code>def heading(text): return '{0:=^16}'.format(text) heading(name_choice) </code></pre> <p>Please note that if one of the names in the list is longer than 16 characters, this function will return the entire name, without <code>=</code>...
0
2016-07-20T01:42:59Z
[ "python", "string.format" ]
Using .format() to print a string that does not exceed a defined number of spaces and is centered?
38,470,930
<p>So Im trying to do three things here. 1. Get the print statement below to be 16 spaces long 2. Cut off the extra = signs on eiter side of the name that cause it to be longer than 16. 3. Center the text so an equal amount of = signs are either side of the name</p> <p>This is my attempt...</p> <pre><code>import ran...
1
2016-07-20T01:30:51Z
38,471,021
<p>You should change<code>print('{0:.16}'.format(name_string))</code> to <code>print('{0:16}'.format(name_string))</code>,then it will work.</p>
0
2016-07-20T01:45:30Z
[ "python", "string.format" ]
Using .format() to print a string that does not exceed a defined number of spaces and is centered?
38,470,930
<p>So Im trying to do three things here. 1. Get the print statement below to be 16 spaces long 2. Cut off the extra = signs on eiter side of the name that cause it to be longer than 16. 3. Center the text so an equal amount of = signs are either side of the name</p> <p>This is my attempt...</p> <pre><code>import ran...
1
2016-07-20T01:30:51Z
38,472,730
<p>Adding <code>| {0} |</code> to the formatting in <a href="http://stackoverflow.com/a/38471007/1248974">simon.sim's answer</a> produces the OP's desired ouput shown in the question:</p> <pre><code>import random def extra_format(text): return '{0:=^16}'.format(text) name_list = ['Joe','Phil','Frank','Daniel'] n...
0
2016-07-20T05:07:41Z
[ "python", "string.format" ]
How to control the LED on an xbox 360 gamepad using pyusb
38,470,946
<p>I'm looking to use pyusb to interact with a wired xbox 360 gamepad. So far I can read just fine but I'd also like to write so I can make the LED stop blinking. </p> <p>Looking <a href="http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/UsbInfo" rel="nofollow">here</a>, I should be able to do it, but no ...
0
2016-07-20T01:32:53Z
38,484,561
<p>Solved it; just had to try more variants of the string being written. Here's what eventually worked:</p> <pre><code>dev.write(writeEP,"\x01\x03\x06",0) </code></pre>
0
2016-07-20T15:21:50Z
[ "python", "usb", "pyusb", "gamepad" ]
Illegal instruction: 4 when importing python plugins
38,470,975
<p>I tried to install a <code>hoomd</code>_script molecular dynamics software on my imac (it's imac pro before 2009, the system is <code>OS X El captain v10.11.3</code>). I have successfully compiled this to iMac, but when I import this hoomd_script in <code>Python 2.7.12</code>, Python crashes completely and I get the...
1
2016-07-20T01:38:31Z
39,104,758
<p>As stated on the <a href="http://glotzerlab.engin.umich.edu/hoomd-blue/download.html" rel="nofollow">HOOMD-blue web page</a>, the conda builds require a CPU capable of AVX instructions (2011 or newer). The illegal instruction results because you are trying to execute an instruction that your processor does not suppo...
0
2016-08-23T15:06:20Z
[ "python", "c++", "operating-system" ]
avoid outer element wrap in lxml
38,471,001
<pre><code>&gt;&gt;&gt; from lxml import html &gt;&gt;&gt; html.tostring(html.fromstring('&lt;div&gt;1&lt;/div&gt;&lt;div&gt;2&lt;/div&gt;')) '&lt;div&gt;&lt;div&gt;1&lt;/div&gt;&lt;div&gt;2&lt;/div&gt;&lt;/div&gt;' # I dont want to outer &lt;div&gt; &gt;&gt;&gt; html.tostring(html.fromstring('I am pure text')) '&lt;...
0
2016-07-20T01:42:01Z
38,475,366
<p>By default, <a href="http://lxml.de/lxmlhtml.html#parsing-html-fragments" rel="nofollow"><code>lxml</code> will create a parent <code>div</code> when the string contains multiple elements</a>.</p> <p>You can work with individual fragments instead:</p> <pre><code>from lxml import html test_cases = ['&lt;div&gt;1&lt...
1
2016-07-20T07:49:18Z
[ "python", "html", "parsing", "lxml" ]
Zapier and Pythoneverywhere smtp issues
38,471,039
<p>I've been using Zapier and Pythoneverywhere for some backend stuff using Python, and recently I've been getting a 534 error as follows:</p> <p><code>File "/usr/lib64/python2.7/smtplib.py", line 622, in login raise SMTPAuthenticationError(code, resp) SMTPAuthenticationError: (534, '5.7.14 &lt;https://accounts.google...
0
2016-07-20T01:48:00Z
38,471,134
<p>I'm not sure why this fixed it, but I made one change to this section of the code:</p> <pre><code> server.ehlo() server.starttls() </code></pre> <p>And changed it to be:</p> <pre><code> server.ehlo() server.starttls() server.ehlo() </code></pre> <p>As per this (<a href="http://stackoverflow.com...
1
2016-07-20T01:59:13Z
[ "python", "smtp", "smtplib", "pythonanywhere", "zapier" ]
How to read file sent from curl to Flask?
38,471,062
<p>Flask code - </p> <pre><code> @app.route('/messages', methods = ['POST']) def api_message(): if request.headers['Content-Type'] == 'text/plain': return "Text Message: " + request.data elif request.headers['Content-Type'] == 'application/json': f = open(filename,'r') l = f.readlines...
0
2016-07-20T01:50:23Z
38,471,187
<p>What your <code>curl</code> command code is doing is reading the file <code>hello.json</code> and putting it in the body of the request. (This feature is actually very useful if you have a large chunk of JSON you need to send to the server).</p> <p>Normally in <code>application/json</code> requests you send the JSO...
2
2016-07-20T02:06:25Z
[ "python", "curl", "flask" ]
Python super() in nested multiple-inheritance
38,471,087
<p>I recently had a problem understanding the code below: </p> <pre><code>class A(object): def __init__(self): print("go A go!") class B(A): def __init__(self): super(B, self).__init__() print("go B go!") class C(A): def __init__(self): super(C, self).__init__() ...
0
2016-07-20T01:52:30Z
38,471,200
<p>Python uses <a href="https://en.wikipedia.org/wiki/C3_linearization" rel="nofollow">C3 linearlization</a> to define the order (Method Resolution Order ). It produced the following order:</p> <pre><code>D.__mro__ (__main__.D, __main__.B, __main__.C, __main__.A, builtins.object) </code></pre> <p>Since you are callin...
3
2016-07-20T02:08:58Z
[ "python", "python-2.7" ]
How to stack (per iteration) dataframes in column side by side in one csv file in python pandas?
38,471,128
<p>If I could generate two columns of data per iteration in a for-loop and I want to save it in a csv file, how will it be done if the next iteration that I would generate two columns it will be stacked side by side on the same csv file(no overwriting)? same goes for the next iterations. I have searched for <code>panda...
1
2016-07-20T01:58:44Z
38,471,284
<p>A file is a one dimensional object that only grows in length. The rows are only separated by a \n character. So, it is impossible to add rows without rewriting the file.</p> <p>You can load the file in memory and concatenate using dataframe and then write it back to (some other file). Here:</p> <pre><code>import n...
1
2016-07-20T02:20:43Z
[ "python", "pandas" ]
How to stack (per iteration) dataframes in column side by side in one csv file in python pandas?
38,471,128
<p>If I could generate two columns of data per iteration in a for-loop and I want to save it in a csv file, how will it be done if the next iteration that I would generate two columns it will be stacked side by side on the same csv file(no overwriting)? same goes for the next iterations. I have searched for <code>panda...
1
2016-07-20T01:58:44Z
38,472,142
<p>is that what you want?</p> <pre><code>In [84]: %paste df = pd.DataFrame(np.arange(10).reshape((5,2))) for i in range (0, 4): new = pd.DataFrame(np.random.randint(0, 100, (5,2))) df = pd.concat([df, new], axis=1) ## -- End pasted text -- In [85]: df Out[85]: 0 1 0 1 0 1 0 1 0 1 0 0 1 ...
1
2016-07-20T04:07:05Z
[ "python", "pandas" ]
How to stack (per iteration) dataframes in column side by side in one csv file in python pandas?
38,471,128
<p>If I could generate two columns of data per iteration in a for-loop and I want to save it in a csv file, how will it be done if the next iteration that I would generate two columns it will be stacked side by side on the same csv file(no overwriting)? same goes for the next iterations. I have searched for <code>panda...
1
2016-07-20T01:58:44Z
38,474,086
<p>An alternative:</p> <pre><code>def iter_stack(n, shape): df = pd.DataFrame(np.random.choice(range(10), shape)).T for _ in range(n-1): df = df.append(pd.DataFrame(np.random.choice(range(10), shape)).T) return df.T iterstacking(5, (5, 2)) </code></pre> <p><a href="http://i.stack.imgur.com/39Stn....
0
2016-07-20T06:44:24Z
[ "python", "pandas" ]
TypeError: 'NoneType' object is not callable , how can i solve it?
38,471,138
<p>i`m trying to make a game , but this error happens with my collision def</p> <p>thats the code:</p> <pre><code>def colisao(espeto): for b in range(len(espeto)) : if player.collided(espeto[b]): if b == 0 : espeto [0].x = janela.width / 2 espeto [0].y = janela.height - espeto ...
0
2016-07-20T01:59:52Z
38,471,224
<p>It is very likely that <code>player.collided</code> is None, instead of a function/method. Please check that. This is the only thing I can guess with the details given.</p>
0
2016-07-20T02:12:21Z
[ "python", "pygame" ]
Bash is waiting for a python subprocess
38,471,203
<p>I have three scripts which call each other. They are the followings:</p> <p>script1.sh:</p> <p></p> <pre><code>s=`./script2.py`; echo "DONE"; </code></pre> <p>script2.py:</p> <p></p> <pre><code>#!/usr/bin/env python3 import subprocess subprocess.Popen(["./script3.py"]) print ("Exit script2") </code></pre> <p...
2
2016-07-20T02:09:13Z
38,471,529
<p>The problem is that <code>script1.sh</code> is capturing stdout and python has not finished writing to stdout until <code>script3.py</code> finishes.</p> <p>One solution is to send the stdout of <code>script3.py</code> somewhere else. For example, this allows <code>script1.sh</code> to complete quickly:</p> <pre>...
3
2016-07-20T02:50:47Z
[ "python", "bash", "python-3.x", "subprocess" ]
Python: Too many values to unpack
38,471,258
<p>I am working on a program in Python however I am getting the following error when I run it through the terminal:</p> <pre><code>Traceback (most recent call last): File "packetSniffer.py", line 120, in &lt;module&gt; main() File "packetSniffer.py", line 27, in main (version, headerLength, timeToLive, pro...
-2
2016-07-20T02:17:10Z
38,471,326
<p>This seems to be ip(data) returns a seq with more than 7 elems. Try this:</p> <pre><code>(version, headerLength, timeToLive, protocol, source, target, data) = ip(data)[:7] </code></pre>
0
2016-07-20T02:26:51Z
[ "python", "python-3.x" ]
Python: Too many values to unpack
38,471,258
<p>I am working on a program in Python however I am getting the following error when I run it through the terminal:</p> <pre><code>Traceback (most recent call last): File "packetSniffer.py", line 120, in &lt;module&gt; main() File "packetSniffer.py", line 27, in main (version, headerLength, timeToLive, pro...
-2
2016-07-20T02:17:10Z
38,471,363
<p>Right before the errant line:</p> <pre><code>(version, headerLength, timeToLive, protocol, source, target, data) = ip(data) </code></pre> <p>you should place the following:</p> <pre><code>print(data) print(ip(data)) </code></pre> <p>The output of that should then show you <em>exactly</em> what the problem is - t...
0
2016-07-20T02:31:03Z
[ "python", "python-3.x" ]
Python: Too many values to unpack
38,471,258
<p>I am working on a program in Python however I am getting the following error when I run it through the terminal:</p> <pre><code>Traceback (most recent call last): File "packetSniffer.py", line 120, in &lt;module&gt; main() File "packetSniffer.py", line 27, in main (version, headerLength, timeToLive, pro...
-2
2016-07-20T02:17:10Z
38,471,585
<p>the problem here is yours <code>ip</code> function only return a string, but you want to extract a bunch of stuff that it simple can't be extracted by just unpacking, you need to redefine the <code>ip</code> function to return all that stuff or change how you use it.</p> <p>By the way, there is a way to in case of ...
0
2016-07-20T02:56:37Z
[ "python", "python-3.x" ]
Python call by reference issue
38,471,306
<p>As what I have understand on python, when you pass a variable on a function parameter it is already reference to the original variable. On my implementation when I try to equate a variable that I pass on the function it resulted empty list.</p> <p>This is my code:</p> <pre><code>#on the main ------------- temp_obj...
1
2016-07-20T02:24:15Z
38,471,425
<p><strong>Python is not pass-by-reference. It is pass-by-object.</strong></p> <p>Consider the following two functions:</p> <pre><code>def f(mylist): mylist = [] def g(mylist): mylist.append(1) </code></pre> <p>Now let's say I call them.</p> <pre><code>mylist = [1] f(mylist) print(mylist) mylist = [1] # r...
1
2016-07-20T02:40:04Z
[ "python", "python-3.x" ]
Python call by reference issue
38,471,306
<p>As what I have understand on python, when you pass a variable on a function parameter it is already reference to the original variable. On my implementation when I try to equate a variable that I pass on the function it resulted empty list.</p> <p>This is my code:</p> <pre><code>#on the main ------------- temp_obj...
1
2016-07-20T02:24:15Z
38,471,436
<pre><code>new_temp_obj = obj[:] #copying the remaining element </code></pre> <p>This would make <code>new_temp_obj</code> reference to another new list object. You could use <code>id</code> to see that its <code>id</code> changes with this assignment.</p> <p>Change it to:</p> <pre><code>new_temp_obj[:] = obj[:] </...
1
2016-07-20T02:41:26Z
[ "python", "python-3.x" ]
Python video processing libraries?
38,471,369
<p>Are there python libraries for processing video? In particular:</p> <ul> <li>identify codec used</li> <li>create a lower-quality preview of a video</li> <li>add a watermark to a video</li> </ul> <p>Thanks!</p>
0
2016-07-20T02:32:18Z
38,471,616
<p>See <a href="http://hachoir3.readthedocs.io/" rel="nofollow">Hachoir</a> and <a href="http://zulko.github.io/moviepy/index.html" rel="nofollow">MoviePy</a>.</p> <ol> <li><p>identify codec used</p> <ul> <li><strong>Hachoir</strong>: <a href="http://hachoir3.readthedocs.io/metadata.html#example" rel="nofollow">extra...
0
2016-07-20T03:01:18Z
[ "python", "video" ]
instantiating optional arguments in python class?
38,471,377
<p>So in the event that you have several optional arguments in a class, how would you loop over the optional arguments to set their values after the base instantiation is done? Also looking for any recommendations of more pythonic ways to handle this code overall. Thanks!</p> <p>required args:</p> <pre><code>p = argp...
0
2016-07-20T02:33:34Z
38,473,002
<p><a href="https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists" rel="nofollow">This</a> is what you might be looking for. You can use <code>*args</code> when you're not sure in the problem how many arguments might pass to your function. It allows you pass an arbitrary number of arguments to yo...
1
2016-07-20T05:32:37Z
[ "python", "class", "oop" ]
Create list of sequential numbers until next rounded number past x
38,471,421
<p>I'm trying to create a list of sequential numbers in python from 1 to a specified number, but need to round the numbers off to one that's divisible by 10.</p> <p>e.g. if my specificed number is <code>7</code> my list would be <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code></p> <p>I've written the following code, whic...
0
2016-07-20T02:39:41Z
38,471,479
<p>Why not use a simple range?</p> <pre><code>&gt;&gt;&gt; def makeList(n): return list(range(1,1+n if n % 10 == 0 else 1+ 10*(1+n//10))) &gt;&gt;&gt; makeList(7) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] &gt;&gt;&gt; makeList(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] &gt;&gt;&gt; makeList(11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,...
2
2016-07-20T02:46:13Z
[ "python", "list", "python-2.7" ]
Create list of sequential numbers until next rounded number past x
38,471,421
<p>I'm trying to create a list of sequential numbers in python from 1 to a specified number, but need to round the numbers off to one that's divisible by 10.</p> <p>e.g. if my specificed number is <code>7</code> my list would be <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code></p> <p>I've written the following code, whic...
0
2016-07-20T02:39:41Z
38,471,515
<pre><code>def makeList(n): return range(1, n + 11 - (n % 10)) </code></pre> <h1>EDIT</h1> <p>Noticed that when n is multiple of 10 no need to add 10.</p> <pre><code>def makeList(n): return range(1, n + 1 - (n % 10) + 10 * (n % 10 != 0)) </code></pre>
1
2016-07-20T02:49:37Z
[ "python", "list", "python-2.7" ]
Python File Close on Program Exit
38,471,560
<p>If I wanted to close a file in a program with an infinite loop, I could do the following:</p> <pre><code>file = open('abc', 'w') while True: try: file.write('a\n') except KeyboardInterrupt: break file.close() </code></pre> <p>But if I just left it like this:</p> <pre><code>file = open('a...
1
2016-07-20T02:54:04Z
38,471,608
<p>Python has <a href="https://www.quora.com/How-does-garbage-collection-in-Python-work" rel="nofollow" title="automatic garbage collection">automatic garbage collection</a>. Garbage collection is the automatic clearing away of unused file handles or data in memory. As a python program halts, if it has halted cleanly...
0
2016-07-20T02:59:36Z
[ "python", "file", "keyboardinterrupt" ]
Python File Close on Program Exit
38,471,560
<p>If I wanted to close a file in a program with an infinite loop, I could do the following:</p> <pre><code>file = open('abc', 'w') while True: try: file.write('a\n') except KeyboardInterrupt: break file.close() </code></pre> <p>But if I just left it like this:</p> <pre><code>file = open('a...
1
2016-07-20T02:54:04Z
38,471,792
<p>As mentioned above by @Mitch Jackson, if a python program halts cleanly, it will free up the memory. In your case, since you are just opening a file in a while loop. The program won't be able to close already opened file when it halts unless you explicitly include exception handling like a <code>try-catch block</cod...
0
2016-07-20T03:24:25Z
[ "python", "file", "keyboardinterrupt" ]
python csv.reader misses first line
38,471,611
<p>I am using csv.reader in python to read a csv file into a dictionary. The first column of the csv is a date (in one of 2 possible formats) which is readn as a datetime object and becomes the key of the dict, and I also read columns 3 and 4:</p> <pre><code>import datetime as dt import csv with open(fileInput,'r') as...
0
2016-07-20T03:00:18Z
38,473,059
<p>When you run your <code>try</code>, <code>except</code> statement, it is easy to believe that python will first <code>try</code> something, and if that fails, revert your environment back to the state it was in before the <code>try</code> statement was executed. It does not do this. As such, you have to be aware of ...
1
2016-07-20T05:37:27Z
[ "python", "csv" ]
Trying to install Scrapy on Mac
38,471,638
<p>When I try to install Scrapy on OS X using the terminal I get an error.</p> <p>The command I use: </p> <pre><code>sudo pip install -U scrapy </code></pre> <p>The error I get:</p> <pre><code>Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/basecommand...
0
2016-07-20T03:03:50Z
38,471,927
<p>Do it without the -U switch.</p> <pre><code>sudo pip install scrapy </code></pre>
-1
2016-07-20T03:40:53Z
[ "python", "scrapy", "pip" ]
Trying to install Scrapy on Mac
38,471,638
<p>When I try to install Scrapy on OS X using the terminal I get an error.</p> <p>The command I use: </p> <pre><code>sudo pip install -U scrapy </code></pre> <p>The error I get:</p> <pre><code>Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg/pip/basecommand...
0
2016-07-20T03:03:50Z
38,550,878
<p>This is because Mac OS was shipped with six 1.4.1 installed already and when it attempts to uninstall it.it doesn't have permission to do so because System Integrity Protection doesn't allow even root to modify those directories.</p> <p>This will do it. </p> <pre><code>sudo pip install scrapy --upgrade --ignore-in...
3
2016-07-24T10:09:11Z
[ "python", "scrapy", "pip" ]
ImportError : cannot import name urlopen
38,471,736
<p>I am trying to open up an URL for my project and here is my code:</p> <pre><code>from urllib2 import urlopen page = urlopen("https://docs.python.org/3/howto/urllib2.html") contents = page.read() </code></pre> <p>It's just a simple code for a demo however, when I run the codes, I got the following error <strong>"Im...
2
2016-07-20T03:18:02Z
38,472,004
<p>The answer to this question breaks down into two sections. The solution differs based on if you are using python 2 or python 3.</p> <p>In python 3 urllib2 is no longer used. Try using urllib.request.</p> <p>In python 2 you may just have a bad install or old version of urllib2. Try pip install urllib2.</p>
0
2016-07-20T03:49:22Z
[ "python", "python-import", "importerror", "urlopen" ]
ImportError : cannot import name urlopen
38,471,736
<p>I am trying to open up an URL for my project and here is my code:</p> <pre><code>from urllib2 import urlopen page = urlopen("https://docs.python.org/3/howto/urllib2.html") contents = page.read() </code></pre> <p>It's just a simple code for a demo however, when I run the codes, I got the following error <strong>"Im...
2
2016-07-20T03:18:02Z
38,472,008
<p>I'm going to take an educated guess and assume you are using python3. In python3, urllib2 has been split into <a href="https://docs.python.org/3/library/urllib.request.html" rel="nofollow"><code>urllib.request</code></a> and <a href="https://docs.python.org/3/library/urllib.error.html" rel="nofollow"><code>urllib.er...
3
2016-07-20T03:49:45Z
[ "python", "python-import", "importerror", "urlopen" ]
Django how to get data in post that was sent with get?
38,471,739
<p>I have a CBV that call some model methods (which run some processes on the machine, and connect to other websites to retrieve data)</p> <pre><code>class Edit(View: def get(self, request): object = Model.objects.get() object.foo() return object def post(self, request): ...how...
0
2016-07-20T03:18:32Z
38,471,882
<p>It will be an attribute of request (<a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpRequest.POST" rel="nofollow">reference</a>). </p> <pre><code>data = request.POST # python dictionary-like </code></pre> <p>The view gets the argument in this order: request, positional url argum...
1
2016-07-20T03:35:21Z
[ "python", "django", "post" ]
PY QT using QTableWidget
38,471,793
<p>I am using PY QT for making GUI. There is multiple tabs , in one of tab it has tablewidget of 3 rows and 3 column. I am trying than when ever user click any row of column 2, it gives pop up check box window. I don't know how to tract the clicking of perticular cell and then activate the related def.</p>
0
2016-07-20T03:24:31Z
38,471,840
<p>QTalbeWidget have a signal named "cellClicked".</p> <p>You can use it like this below.</p> <pre><code>myTableWidget.cellClicked.connect(self.OnCellClicked) def OnCellClicked(self, row, col): pass </code></pre>
1
2016-07-20T03:30:25Z
[ "python", "pyqt", "qtablewidget" ]
Python / Kivy - UrlRequest results
38,471,829
<p>i'm strugling with this for some time now and couldn't find a solution.</p> <p>So i was studying Python and Kivy with the "Creating Apps in Kivy" from Dusty Phillips. It's a simple weather app and when i try to get data from openweathermap.com, the UrlRequest function doesn't work as it should. I'm pretty new to k...
2
2016-07-20T03:29:11Z
38,477,301
<p>The problem here is that you print the result before its downloaded successfully.</p> <p>Also remember to put "http://" infront of the link string.</p> <p>Remember, that the url is loaded asyncronically. As it says in the docs on <a href="https://kivy.org/docs/api-kivy.network.urlrequest.html" rel="nofollow">UrlRe...
0
2016-07-20T09:22:41Z
[ "python", "kivy" ]
How to use a queryset result to filter other queryset in DJango ORM?
38,471,856
<p>I am trying to call a view using AJAX, but I have a problem. I have a token for the submit, the function that calls to Django view is working, I followed all the instructions of this link: <a href="https://realpython.com/blog/python/django-and-ajax-form-submissions/" rel="nofollow">https://realpython.com/blog/python...
0
2016-07-20T03:32:18Z
38,472,578
<p>I've moved the SOLVED text to an answer:</p> <p>I changed this:</p> <pre><code>resp_inventario=InventarioProducto.objects.get(producto_codigo_producto__in=resp_producto) </code></pre> <p>To this: </p> <pre><code>resp_inventario=InventarioProducto.objects.filter(producto_codigo_producto__in=resp_producto) </code>...
0
2016-07-20T04:53:22Z
[ "python", "ajax", "django" ]
Pygame - Menu Screen Buttons not working properly
38,471,858
<p>I am trying to create a menu screen for my game. At the moment im using sprites for buttons and everything works well, and I can create an infinite amount of buttons (currently I just have Start and Options), but only the first button I call appears on the screen. I think it has something to do with the while loop i...
0
2016-07-20T03:32:26Z
38,475,996
<p>In the constructor of your Button class, you have an infinite loop. This means you never get to the code part where you make your second Button.</p> <pre><code>def gameIntro(): button_start = Button(img_button_start, 27, 0) #stuck in infinite loop print('This print statement is never reac...
0
2016-07-20T08:21:04Z
[ "python", "button", "menu", "pygame" ]
How to print out a hierarchy tree of the employees
38,471,872
<p>Given a list of employees and their bosses as a csv file , write a function that will print out a hierarchy tree of the employees.</p> <p>Sample input from csv file</p> <pre><code>Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/ Fred, Sam,developer, 2010 </code></pre> <p>The format is name, supervisor, desig...
0
2016-07-20T03:34:29Z
38,472,423
<p>Fixing the indentation like this should work. Indentation is extremely important in python. </p> <pre><code>strq = "Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/Fred, Sam, developer, 2010" def treeEmployee(infoStr): str1 = infoStr.split("/") s2 = [] for i in str1: s2.append(i.split(","))...
0
2016-07-20T04:37:49Z
[ "python" ]
How to print out a hierarchy tree of the employees
38,471,872
<p>Given a list of employees and their bosses as a csv file , write a function that will print out a hierarchy tree of the employees.</p> <p>Sample input from csv file</p> <pre><code>Sam, Ian, technical lead, 2009 / Ian, NULL, CEO,2007/ Fred, Sam,developer, 2010 </code></pre> <p>The format is name, supervisor, desig...
0
2016-07-20T03:34:29Z
38,472,485
<p>This generates a hierarchy tree from your inputs in JS.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function wrapper(str) { var elem; str = str.split('/'); ...
0
2016-07-20T04:43:55Z
[ "python" ]
When I use Chinese.UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)
38,471,909
<pre><code>def google_search(key_word): query = "https://www.google.com.hk/search?q=" + key_word +"%20site:detail.zol.com.cn" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(query,headers=headers) page = urllib.request.ur...
0
2016-07-20T03:38:33Z
38,472,136
<p>Are you from shenzhen?</p> <p>In fact, chinese string needs to be "urlencode" in url.</p> <p>It seems you use python3, i am not familiar with python3, let me use python2 to explain it, what you can do is to replace the api i have used in the example.</p> <pre><code>#coding:utf-8 import urllib key = urllib.quote("...
1
2016-07-20T04:06:11Z
[ "python", "http", "url", "encoding" ]
When I use Chinese.UnicodeEncodeError: 'ascii' codec can't encode characters in position 14-15: ordinal not in range(128)
38,471,909
<pre><code>def google_search(key_word): query = "https://www.google.com.hk/search?q=" + key_word +"%20site:detail.zol.com.cn" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.request.Request(query,headers=headers) page = urllib.request.ur...
0
2016-07-20T03:38:33Z
38,472,364
<pre><code>import urllib.request from urllib.parse import quote def google_search(key_word): query = "https://www.google.com.hk/search?q=" + quote(key_word) +"%20site:detail.zol.com.cn" headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = urllib.reques...
0
2016-07-20T04:32:03Z
[ "python", "http", "url", "encoding" ]
Value counts for all combinations of groups
38,471,946
<p>I have a dataframe with multiple group columns and a value column. </p> <pre><code> a b val 0 A C 1 1 A D 1 2 A D 1 3 A D 2 4 B E 0 </code></pre> <p>For any one group, for eg <code>a==A</code>, <code>b==C</code>I can do <code>value_counts</code> on the series slice. How can I get the value count...
0
2016-07-20T03:43:06Z
38,471,994
<p>is that what you want?</p> <pre><code>In [47]: df.groupby(['a','b','val']).size().reset_index() Out[47]: a b val 0 0 A C 1 1 1 A D 1 2 2 A D 2 1 3 B E 0 1 </code></pre> <p>or this?</p> <pre><code>In [43]: df['counts'] = df.groupby(['a','b'])['val'].transform('size') In [44]: df Out[...
1
2016-07-20T03:47:47Z
[ "python", "pandas", "counter" ]
Save data using ajax in Django wont work
38,472,015
<p>I am trying to save data from <code>javascript</code> to <code>django-views</code> using <code>jquery $.ajax</code> but the browser console will give me this error:</p> <p>Here is my <code>javascript</code> content with <code>$.ajax</code>:</p> <pre><code>var url = $(this).attr('action'); $.ajax({ type:...
-1
2016-07-20T03:50:10Z
38,473,526
<p>First thing is you have to pass csrf token in Ajax request call see <a href="https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax." rel="nofollow">this</a></p> <p>Otherwise it will not allow you for POST request it will request as GET and your whole data will be coming in <code>request.GET</code> instead of...
0
2016-07-20T06:10:24Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Save data using ajax in Django wont work
38,472,015
<p>I am trying to save data from <code>javascript</code> to <code>django-views</code> using <code>jquery $.ajax</code> but the browser console will give me this error:</p> <p>Here is my <code>javascript</code> content with <code>$.ajax</code>:</p> <pre><code>var url = $(this).attr('action'); $.ajax({ type:...
-1
2016-07-20T03:50:10Z
38,473,918
<p>As based to @solarissmoke suggestion i changed the <code>request.POST['bdate']</code> to <code>request.POST['birthdate']</code> since in the js file, the variable is <code>birthdate</code> not <code>bdate</code></p> <p>Then as i started to work for date parsing the Django trace give me this error:</p> <blockquote>...
0
2016-07-20T06:35:11Z
[ "javascript", "jquery", "python", "ajax", "django" ]
creating a new adb logcat text file in a python script
38,472,064
<p>How do I execute this logcat command via python? </p> <pre><code>adb logcat -d &gt; log1.txt </code></pre> <p>I tried this but there is no file being created in the output folder. I did do a workaround and it worked.</p> <p>I have another issue: The log1.txt file is populated. I am expected to copy lines with t...
-3
2016-07-20T03:56:11Z
38,472,360
<p>Try this </p> <pre><code>with open('out-file.txt', 'w') as f: subprocess.call(['adb','logcat', '-d'], stdout=f) </code></pre>
0
2016-07-20T04:31:34Z
[ "android", "python", "file", "adb", "logcat" ]
Assign output of subprocess to variable
38,472,254
<p>The purpose of this script is to read a file, extract the audio, and print out a transcript by running it through IBM Watson speech to text API. My problem is when I try to save the output from the subprocess into a variable and pass it into the open function, it reads as binary. What am I doing wrong? Any help woul...
0
2016-07-20T04:20:28Z
38,472,489
<p>1.Run 'ffmpeg -i ' + fullVideo + ' -vn -ab 128k ' + title + '.flac' for ensure it is right.</p> <p>2.If it is right, see the converted file existed.</p> <p>3.stdin is standard input, stdout is standard output. So use stdout argument in Popen.</p> <pre><code> output = subprocess.Popen('ffmpeg -i ' + fullVideo +...
0
2016-07-20T04:44:50Z
[ "python", "ffmpeg", "subprocess" ]
Pandas sum multiple dataframes
38,472,276
<p>I have multiple dataframes each with a multi-level-index and a value column. I want to add up all the dataframes on the value columns. </p> <p><code>df1 + df2</code></p> <p>Not all the indexes are complete in each dataframe, hence I am getting <code>nan</code> on a row which is not present in all the dataframes. <...
3
2016-07-20T04:23:36Z
38,472,352
<p>use the <code>add</code> method with <code>fill_value=0</code> parameter.</p> <pre><code>df1 = pd.DataFrame({'val':{'a': 1, 'b':2, 'c':3}}) df2 = pd.DataFrame({'val':{'a': 1, 'b':2, 'd':3}}) df1.add(df2, fill_value=0) </code></pre> <p><a href="http://i.stack.imgur.com/Dzvek.png" rel="nofollow"><img src="http://i....
3
2016-07-20T04:30:28Z
[ "python", "pandas", "dataframe", "merge" ]
Linking pointer arguments from a C function with a ctype argument in python script
38,472,284
<p>The following is a simple code showing division of a number: </p> <pre><code>//pointer.h #include&lt;stdio.h&gt; int divide(int , int , int *); //pointer.c #include&lt;stdio.h&gt; __declspec(dllexport) int divide(int a, int b, int *remainder) { int quot = a / b; remainder = a % b; return quot; } ...
2
2016-07-20T04:24:00Z
38,472,690
<p><strong>Edit</strong></p> <p>It looks like you're calling your wrapped divide function with three integer arguments (<code>mydll.divide(4,32,3)</code>). That won't work. See the below code for how you probably want to specify the third argument. The rest of my post may be unnecessary, but I'm leaving it anyway f...
0
2016-07-20T05:04:25Z
[ "python", "c", "pointers", "ctypes" ]
pandas - Resampling datetime index and extending to end of the month
38,472,382
<p>I am trying to resample a datetime index into hourly data. I also want the resampling until the end of the month.</p> <p>So given the following <code>df</code>:</p> <pre><code>data = np.arange(6).reshape(3,2) rng = ['Jan-2016', 'Feb-2016', 'Mar-2016'] df = pd.DataFrame(data, index=rng) df.index = pd.to_datetime(df...
4
2016-07-20T04:33:39Z
38,472,404
<p><strong>UPDATE:</strong></p> <pre><code>In [37]: (df.set_index(df.index[:-1].union([df.index[-1] + pd.offsets.MonthEnd(0)])) ....: .resample('H') ....: .ffill() ....: .head() ....: ) Out[37]: 0 1 2016-01-01 00:00:00 0 1 2016-01-01 01:00:00 0 1 2016-01-01 02:00:00 0 1...
4
2016-07-20T04:35:52Z
[ "python", "pandas", "dataframe" ]
How to import a gzip file larger than RAM limit into a Pandas DataFrame? "Kill 9" Use HDF5?
38,472,387
<p>I have a <code>gzip</code> which is approximately 90 GB. This is well within disk space, but far larger than RAM. </p> <p>How can I import this into a pandas dataframe? I tried the following in the command line:</p> <pre><code># start with Python 3.4.5 import pandas as pd filename = 'filename.gzip' # size 90 GB ...
4
2016-07-20T04:34:18Z
38,472,574
<p>I'd do it this way:</p> <pre><code>filename = 'filename.gzip' # size 90 GB hdf_fn = 'result.h5' hdf_key = 'my_huge_df' cols = ['colA','colB','colC','ColZ'] # put here a list of all your columns cols_to_index = ['colA','colZ'] # put here the list of YOUR columns, that you want to index chunksize = 10**6 ...
8
2016-07-20T04:52:59Z
[ "python", "pandas", "dataframe", "gzip", "hdf5" ]
Python strange behavior with for loop
38,472,503
<p>I am a beginner learning python. I have a problem with this for loop.</p> <p>I am trying to a search loop for pc to track the move made by the player (human) and to anticipate the next move in a tic tac toe game. </p> <p>As a result, I create a for loop to append the moves made by the player(human) but somethin...
0
2016-07-20T04:46:04Z
38,472,602
<p>In the outer loop, on the last iteration, you are testing for the index of the literal array: <code>[[],["X"],[]]</code>. So Python finds the first one by equality: which is the same as the second item. </p>
1
2016-07-20T04:56:07Z
[ "python", "for-loop", "iteration" ]
Python strange behavior with for loop
38,472,503
<p>I am a beginner learning python. I have a problem with this for loop.</p> <p>I am trying to a search loop for pc to track the move made by the player (human) and to anticipate the next move in a tic tac toe game. </p> <p>As a result, I create a for loop to append the moves made by the player(human) but somethin...
0
2016-07-20T04:46:04Z
38,472,832
<p>As Jeff Meatball Yang said index works so that it find first occurance in list. I would do something like that</p> <pre><code>lst = [["X", [], []], [[], "X", []], [[], "X", []]] temp_lst = [] for i in range(len(lst)): lst_1 = [] for j in range(len(lst[i])): if lst[i][j] == "X": ls...
0
2016-07-20T05:16:51Z
[ "python", "for-loop", "iteration" ]
Why does my first if statement always return true even if it doesn't match the if criteria?
38,472,679
<p>I tried printing the Score to ensure it was receiving the value I entered and it was which was even more baffling. Ex. I tried entering in 0.85 and it printed A. Why is that?</p> <pre><code>try: Score = raw_input("What is the Score? ") if Score &gt;= 0.90 &lt; 1.01: print Score print "A" ...
0
2016-07-20T05:03:11Z
38,472,705
<h3>Problem 1: <code>raw_input</code></h3> <p><a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow">From the docs</a>: <code>raw_input</code> "reads a line from input, converts it to a string (stripping a trailing newline), and returns that".</p> <p>You need to cast it to a <code>float</...
1
2016-07-20T05:06:06Z
[ "python" ]
Why does my first if statement always return true even if it doesn't match the if criteria?
38,472,679
<p>I tried printing the Score to ensure it was receiving the value I entered and it was which was even more baffling. Ex. I tried entering in 0.85 and it printed A. Why is that?</p> <pre><code>try: Score = raw_input("What is the Score? ") if Score &gt;= 0.90 &lt; 1.01: print Score print "A" ...
0
2016-07-20T05:03:11Z
38,472,715
<p><strong>UPDATE</strong></p> <p>(I had this wrong in my first answer.)</p> <p>In addition to @Alex's point that you need <code>float(raw_input(...))</code> to get a numeric type... this <code>if</code> statement:</p> <pre><code>if Score &gt;= 0.90 &lt; 1.01: </code></pre> <p>is equivalent to:</p> <pre><code>if S...
4
2016-07-20T05:06:31Z
[ "python" ]
pyodbc to Sage ERP MAS 200 Driver Error
38,473,004
<p>I'm trying to use pyodbc to connect to an ERP database (Sage ERP MAS 200).</p> <pre><code>import pyodbc cnxn = pyodbc.connect('DRIVER={MAS 90 4.0 ODBC Driver};DSN=SOTAMAS90;autocommit=True;UID=myID;PWD=myPWD;Company=myCompany') </code></pre> <p>However I am getting the following error:</p> <pre><code>pyodbc.Erro...
0
2016-07-20T05:32:46Z
38,481,727
<p>It seems that "autocommit=True" must be placed outside of the connection string:</p> <pre><code>cnxn = pyodbc.connect('DRIVER={MAS 90 4.0 ODBC Driver};DSN=SOTAMAS90;UID=myID;PWD=myPWD;Company=myCompany',autocommit=True) </code></pre>
0
2016-07-20T12:45:16Z
[ "python", "odbc", "pyodbc" ]
Storing Python Program Execution Flow (Function call Flow)
38,473,063
<p>I am developing a project in which I have to store all the function that were called in each request-response cycle and store them. I do not need to store values of the variable, all I need to store is function that we were called with their parameters and their order in execution. I am using mongodb to store this t...
0
2016-07-20T05:37:41Z
38,473,267
<p>You could use a function decorator for convenience.</p> <pre><code>import functools import logging def log_me(func): @functools.wraps(func) def inner(*args, **kwargs): logging.debug('name: %s, args: %s, kwargs: %s', func.__name__, args, kwargs) return...
0
2016-07-20T05:53:38Z
[ "python", "mongodb", "program-flow" ]
Storing Python Program Execution Flow (Function call Flow)
38,473,063
<p>I am developing a project in which I have to store all the function that were called in each request-response cycle and store them. I do not need to store values of the variable, all I need to store is function that we were called with their parameters and their order in execution. I am using mongodb to store this t...
0
2016-07-20T05:37:41Z
38,473,442
<p><a href="https://docs.python.org/2/library/sys.html#sys.settrace" rel="nofollow">sys.settrace</a> traces a function for debugging but can be modified for this problem. Maybe something like <a href="https://pymotw.com/2/sys/tracing.html" rel="nofollow">this</a> - </p> <pre><code>import sys def trace_calls(frame, ev...
0
2016-07-20T06:05:14Z
[ "python", "mongodb", "program-flow" ]
Make return of a method/instance become an attribute
38,473,175
<p>I have a class A() include some method:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): X3 = self.x1 + self.x2 return X3 </code></pre> <p>How can I make X3 become an attribute which I can access by "self.X3" to use it for ...
0
2016-07-20T05:47:45Z
38,473,220
<p>One way would be to simply make <code>X3</code> an attribute by prepending <code>self.</code>. For example:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): self.X3 = self.x1 + self.x2 return self.X3 </code></pre> <p>I'm n...
2
2016-07-20T05:50:36Z
[ "python", "class", "methods", "attributes" ]
Make return of a method/instance become an attribute
38,473,175
<p>I have a class A() include some method:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): X3 = self.x1 + self.x2 return X3 </code></pre> <p>How can I make X3 become an attribute which I can access by "self.X3" to use it for ...
0
2016-07-20T05:47:45Z
38,473,224
<p>simply Change <code>X3 =</code> to: <code>self.X3=</code></p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): self.X3 = self.x1 + self.x2 return self.X3 </code></pre>
1
2016-07-20T05:50:43Z
[ "python", "class", "methods", "attributes" ]
Make return of a method/instance become an attribute
38,473,175
<p>I have a class A() include some method:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): X3 = self.x1 + self.x2 return X3 </code></pre> <p>How can I make X3 become an attribute which I can access by "self.X3" to use it for ...
0
2016-07-20T05:47:45Z
38,473,273
<pre><code>class A: def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): self.X3 = self.x1 + self.x2 return self.X3 if __name__ == '__main__': a = A(1, 2) print a.plus() </code></pre> <p>Give this a try. I got some issues compiling when I tried adding...
0
2016-07-20T05:54:07Z
[ "python", "class", "methods", "attributes" ]
Make return of a method/instance become an attribute
38,473,175
<p>I have a class A() include some method:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): X3 = self.x1 + self.x2 return X3 </code></pre> <p>How can I make X3 become an attribute which I can access by "self.X3" to use it for ...
0
2016-07-20T05:47:45Z
38,473,558
<p>For this example, using a <a href="https://docs.python.org/3.5/library/functions.html#property" rel="nofollow">property</a> is probably most appropriate. You can read more about the descriptor protocol (for which properties are syntactic sugar) <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow"...
0
2016-07-20T06:12:11Z
[ "python", "class", "methods", "attributes" ]
Pandas rolling computations for printing elements in the window
38,473,205
<p>I want to make a series out of the values in a column of pandas dataframe in a sliding window fashion. For instance, if this is my dataframe</p> <pre><code> state 0 1 1 1 2 1 3 1 4 0 5 0 6 0 7 1 8 4 9 1 </code></pre> <p>for a window size of say 3, I want to get a list as [111, 111,...
8
2016-07-20T05:49:32Z
38,473,356
<pre><code>a = np.array([100, 10, 1]) s.rolling(3).apply(a.dot).apply('{:03.0f}'.format) 0 nan 1 nan 2 111 3 111 4 110 5 100 6 000 7 001 8 014 9 141 Name: state, dtype: object </code></pre> <p>thx @Alex for reminding me to use <code>dot</code></p>
9
2016-07-20T05:58:59Z
[ "python", "pandas", "dataframe" ]
python27 extracting only specific columns from a csv file
38,473,252
<p>Pls excuse Im fairly new to programming trying to do something simple but cant seem to figure it out. Probably something obvious.</p> <p><strong>I need to take a huge csv file populated with about 6 columns, parse it and extract only 2 columns into a dictionary</strong> which later I will use to build and API call ...
0
2016-07-20T05:52:34Z
38,473,359
<p>You can store the keys you need to a list and then every row you read from csv file use dict comprehension to pick the keys you need:</p> <pre><code>import csv import pprint KEYS = [ 'column1', 'column5' ] def parseSourceFile(filename): with open(filename) as f: reader = csv.DictReader(f) ...
0
2016-07-20T05:59:01Z
[ "python", "json", "csv" ]
python27 extracting only specific columns from a csv file
38,473,252
<p>Pls excuse Im fairly new to programming trying to do something simple but cant seem to figure it out. Probably something obvious.</p> <p><strong>I need to take a huge csv file populated with about 6 columns, parse it and extract only 2 columns into a dictionary</strong> which later I will use to build and API call ...
0
2016-07-20T05:52:34Z
38,473,422
<p>What about something like</p> <pre><code>import csv def parseSourceFile(filename): reader = csv.DictReader(open(filename, "r")) result = [] for row in reader: result.append({k:v for (k,v) in row.items() if k in ['column1', 'column5']}) return result def main(): result = parseSourceFi...
0
2016-07-20T06:03:16Z
[ "python", "json", "csv" ]
how to create pdf in django using pypdf
38,473,441
<p>this is my views</p> <pre><code>def pdf_datakar(request): from fpdf import FPDF pdf = FPDF(format='letter') pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt="Welcome to Python!", align="C") pdf.output("Somefilename.pdf") </code></pre> <p>I want to create pdf file using py...
0
2016-07-20T06:05:02Z
38,473,909
<p>In your view there is no return statement so at the end add return statement.</p> <p>like this</p> <pre><code>from django.http import HttpResponse def pdf_datakar(request): from fpdf import FPDF pdf = FPDF(format='letter') pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt="We...
0
2016-07-20T06:34:40Z
[ "python", "django" ]