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 |
|---|---|---|---|---|---|---|---|---|---|
Zapier: E164 GB/UK Mobile Number Parsing, Can it be done using Python/Javascript? | 37,617,311 | <p><em>Hello,</em></p>
<p>Currently trying to parse a UK mobile number from a web form into E164 format using Zapier. This is so in turn I can trigger a text using a Twilio and Zapier integration.</p>
<p>Twilio only takes the <a href="https://www.twilio.com/docs/api/rest/response#phone-numbers" rel="nofollow">E164</a... | 0 | 2016-06-03T14:41:49Z | 37,656,420 | <p>Twilio developer evangelist here.</p>
<p>As you've tagged this Python you could use the <a href="https://github.com/daviddrysdale/python-phonenumbers" rel="nofollow">Python phonenumbers library</a>. It's a port of Google's <a href="https://github.com/googlei18n/libphonenumber" rel="nofollow">libphonenumber</a>, whi... | 0 | 2016-06-06T11:36:46Z | [
"javascript",
"python",
"parsing",
"twilio",
"zapier"
] |
Perform basic math operations upon loading variables with h5py | 37,617,407 | <p>I'm performing data analysis on a large number of variables contained in an hdf5 file. The code I've written loops over a list of variables and then performs analyses and outputs some graphs. It would be nice to be able to use the code for combinations of variables (like <code>A+B</code> or <code>sqrt((A**2)+(B**2)<... | 1 | 2016-06-03T14:46:10Z | 37,844,937 | <p>First you have to ask yourself: Do I know the arithmetic operations only at runtime or already at programming time?</p>
<p>If you know it already now, just write a function in Python for it.</p>
<p>If you know it only at runtime, you will need a parser. While there are libraries specialized on this out there (<a h... | 0 | 2016-06-15T20:15:00Z | [
"python",
"parsing",
"h5py"
] |
Python POST encoding and formatting | 37,617,462 | <p>I'm sending a POST request using urllib with Python.</p>
<p>I used Charles to see the POST that usually gets sent and now i'm trying to send the same thing using urllib.</p>
<p><strong>This is what should be sent according to charles:</strong></p>
<p>{"stuff_values":{"description":"This is description","somestuff... | 0 | 2016-06-03T14:48:09Z | 37,617,618 | <p>Try:</p>
<pre><code>data = str(values)
</code></pre>
<p>instead. <code>urlencode</code> is converting certain characters to %xx escapes.</p>
| 1 | 2016-06-03T14:57:24Z | [
"python",
"post",
"character-encoding",
"urllib"
] |
Prime number generator crashes from memory error if there are too many numbers in array | 37,617,615 | <p>I have a prime number generator, I was curious to see how small and how fast I could get a prime number generator to be based on optimizations and such:</p>
<pre><code>from math import sqrt
def p(n):
if n < 2: return []
s = [True]*(((n/2)-1+n%2)+1)
for i in range(int(sqrt(n)) >> 1):
if no... | 0 | 2016-06-03T14:57:09Z | 37,618,021 | <p>The Problem is in line 7.</p>
<pre><code>for j in range( (i**i+(3*i) << 1) + 3, ((n/2)-1+n%2), (i<<1)+3): s[j] = False
</code></pre>
<p>especially this part: <code>i**i</code></p>
<p>1000000000^1000000000 is a 9 * 10^9 digit long number. Storing it takes multiple Gb if not Tb (WolframAlpha couldn't ca... | 5 | 2016-06-03T15:17:46Z | [
"python",
"python-2.7",
"generator",
"primes"
] |
Prime number generator crashes from memory error if there are too many numbers in array | 37,617,615 | <p>I have a prime number generator, I was curious to see how small and how fast I could get a prime number generator to be based on optimizations and such:</p>
<pre><code>from math import sqrt
def p(n):
if n < 2: return []
s = [True]*(((n/2)-1+n%2)+1)
for i in range(int(sqrt(n)) >> 1):
if no... | 0 | 2016-06-03T14:57:09Z | 37,618,536 | <p>First of all, there is a problem since the generator says that numbers like 33, 35 and 45 are prime.</p>
<p>Other than that, there are several structures taking up memory here:</p>
<ul>
<li><code>s = [True]*(((n/2)-1+n%2)+1)</code></li>
</ul>
<p>A list element takes up several bytes per element. For n = 1 billion... | 1 | 2016-06-03T15:43:05Z | [
"python",
"python-2.7",
"generator",
"primes"
] |
Python : How to export a contourf to a 2D array? | 37,617,623 | <p>From a complex 3D shape, I have obtained by tricontourf the equivalent <a href="http://i.stack.imgur.com/iXDmP.png" rel="nofollow">top view</a> of my shape.</p>
<p>I wish now to export this result on a 2D array.
I have tried this :</p>
<pre><code>import numpy as np
from shapely.geometry import Polygon
import skima... | 0 | 2016-06-03T14:57:48Z | 37,698,964 | <p>Considering a inner loop with <strong>for path in ...get_paths()</strong> as suggested by Andreas, things are better ... but <strong>not completely fixed</strong>.
My code is now :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import cv2
x = [...]
y = [...]
z = [...]
levels = [....]
...
cs = p... | 0 | 2016-06-08T09:46:52Z | [
"python",
"matplotlib",
"contourf"
] |
Integrate Jupyter notebook with data fetched from Django application | 37,617,629 | <p>I have a Django application that integrates data from a SQL database and displays that as a downloadable HTML table. Now I would also like to add analysis functionality, but instead of painstakingly adding only a few functionalities using JavaScript, I want to redirect the user to a Jupyter notebook, so the user has... | 2 | 2016-06-03T14:58:03Z | 37,620,756 | <blockquote>
<p>Am I right that Jupyter needs to be run on a different server than the Django app since it uses the Tornado server?</p>
</blockquote>
<p>No. They can run on the same server. </p>
<blockquote>
<p>How would I transfer the data produced with Django to Jupyter? I store the data in a new MySQL table, b... | 1 | 2016-06-03T17:58:48Z | [
"python",
"django",
"jupyter-notebook"
] |
Flask Restless CSRF exempt authentication URL | 37,617,691 | <p>I am using Flask Restless 0.17 and Flask JWT for the API portion of an application. In the front-end of the application I am using Flask WTF and its CSRF protection. </p>
<p>This is creating issues with Flask Restless as WTF expects a CSRF token on every view. I am able to get around this on endpoints that I create... | 0 | 2016-06-03T15:01:21Z | 37,764,124 | <p>I couldn't figure out how to do it like the above, so I instead turned off WTF CSRF protection and then enable it when we're not on an API endpoint.</p>
<p>settings.py</p>
<pre><code>WTF_CSRF_CHECK_DEFAULT = False
</code></pre>
<p>app.py</p>
<pre><code>def register_csrf(app):
"""
Only enable CSRF protect... | 0 | 2016-06-11T13:10:08Z | [
"python",
"flask",
"flask-wtforms",
"flask-restless"
] |
Sphinx getting stuck on reading sources index | 37,617,719 | <p>When I input <code>make html</code>, Sphinx gets stuck on the reading segment.</p>
<p>By changing a name in of "asp" changes the percentage it gets stuck on. I had it range from 100% to 25%.
Here is an example of what I see in the terminal when I run <code>make html</code>:</p>
<pre><code>make html
sphinx-build -b... | 2 | 2016-06-03T15:02:47Z | 37,618,789 | <p>Add one line <code>.. _asp:</code> at the beginning of <code>asp.rst</code></p>
<pre><code>.. _asp:
TEST123
=======
.. automodule:: rcegui
.. module:: RCEController
.. autoclass:: RCE_Control_MainWindow
:members:
</code></pre>
<p>for index.rst</p>
<pre><code>Welcome to GUI's documentation!
==================... | 1 | 2016-06-03T15:56:39Z | [
"python",
"python-sphinx",
"autodoc"
] |
Sphinx getting stuck on reading sources index | 37,617,719 | <p>When I input <code>make html</code>, Sphinx gets stuck on the reading segment.</p>
<p>By changing a name in of "asp" changes the percentage it gets stuck on. I had it range from 100% to 25%.
Here is an example of what I see in the terminal when I run <code>make html</code>:</p>
<pre><code>make html
sphinx-build -b... | 2 | 2016-06-03T15:02:47Z | 37,623,689 | <p>So I ended up checking the --init--.py and it didn't have all the files that the program I was calling needed. So after adding the missing files and restarting it. Sphinx was able to run with no errors. I am not sure what fixed it, but I feel like it was adding the missing files to the --init--.py file.</p>
| 0 | 2016-06-03T21:26:48Z | [
"python",
"python-sphinx",
"autodoc"
] |
value error: too many values to unpack , email validation | 37,617,753 | <p>I am trying to give validation to email through forms.py, but it gives me an error of "too many values to unpack" though I am new to django and python programming.</p>
<p>Here is my code:</p>
<pre><code>def clean_email(self):
email = self.cleaned_data.get('email')
email_base, provider = email.split("@")
... | 1 | 2016-06-03T15:04:10Z | 37,617,917 | <p>The exception, <code>ValueError: too many values to unpack</code>, is caused by unpacking a list to unmatchable target variables in terms of the size. For instance,</p>
<pre><code>>>> a, b, c = 'xxx.yyy.edu'.split('.') # ['xxx', 'yyy', 'edu']
# too few target variables
>>> a, b = 'xxx.yyy.ed... | 0 | 2016-06-03T15:12:23Z | [
"python",
"django"
] |
value error: too many values to unpack , email validation | 37,617,753 | <p>I am trying to give validation to email through forms.py, but it gives me an error of "too many values to unpack" though I am new to django and python programming.</p>
<p>Here is my code:</p>
<pre><code>def clean_email(self):
email = self.cleaned_data.get('email')
email_base, provider = email.split("@")
... | 1 | 2016-06-03T15:04:10Z | 37,618,001 | <p>Try something like this </p>
<pre><code> extension = provider[::-1].split('.')[0]
# if not domain == 'USC':
# raise forms.ValidationError("Please make sure you use your USC email.")
if not extension == "ude":
raise forms.ValidationError("Please use a valid .EDU email address")
return em... | 1 | 2016-06-03T15:16:46Z | [
"python",
"django"
] |
Display tkMessageBox above all other running applications | 37,617,787 | <p>I have a python program that, at a certain point when conditions are met, displays a tkMessageBox. </p>
<p>The intended use of this program is to start it, minimize it and then after a certain time get the alert. But when I use tkMessageBox, the message stays 'hidden' behind all the other applications that I have o... | 1 | 2016-06-03T15:06:03Z | 37,623,380 | <p>Well, you can make tkMessageBox raise above all other windows only along side with root:</p>
<pre><code>from Tkinter import Tk # For this example we only need Tk
from tkMessageBox import showinfo
root = Tk() # We need a main window
def showMessage():
root.attributes('-topmost', 1) ... | 0 | 2016-06-03T21:05:01Z | [
"python",
"python-2.7",
"tkinter"
] |
Bigrquery cannot coerce integers | 37,617,867 | <p>I've recently started using "bigrquery" package in R to get some data from Google Bigquery, however most of the integer columns in the data frame I receive has NAs.</p>
<p>The same SQL query in Google's own BigQuery dashboard returns valid results. I also tried in python and the same query returns valid results the... | 1 | 2016-06-03T15:09:49Z | 37,623,565 | <p>I'm not familiar with R or "bigrquery" specifically, but it sounds like your integer values are being coerced into a 32-bit integer and are out-of-range (BigQuery integers are 64-bit).</p>
<p>Workaround: if you just want to treat the number as an opaque ID, can you cast it to a string in your query?</p>
<p>It isn'... | 2 | 2016-06-03T21:18:30Z | [
"python",
"google-bigquery"
] |
Python: Script won't find word in text file | 37,617,963 | <p>I am trying to find specific words from a text file, however my script doesn't seem to be able to match the word to what's written on a line in the text file, even though I know it matches. I've noticed there are spaces but since I am saying <code>entry in line</code>, shouldn't it work?</p>
<p>I have also tried:</... | 0 | 2016-06-03T15:14:41Z | 37,618,100 | <p>You should strip all blanks/newlines from both the entry and lines in file. So, prefix everything with </p>
<pre><code>entry = entry.strip()
</code></pre>
<p>and change the </p>
<pre><code>if entry in line:
</code></pre>
<p>to</p>
<pre><code>if entry in line.strip():
</code></pre>
<p>EDIT:
also, what Moses Kol... | 0 | 2016-06-03T15:21:35Z | [
"python",
"file"
] |
Python: Script won't find word in text file | 37,617,963 | <p>I am trying to find specific words from a text file, however my script doesn't seem to be able to match the word to what's written on a line in the text file, even though I know it matches. I've noticed there are spaces but since I am saying <code>entry in line</code>, shouldn't it work?</p>
<p>I have also tried:</... | 0 | 2016-06-03T15:14:41Z | 37,618,109 | <p>You read to the end of the file the after the first loop. Swap the loops instead, so each <code>entry</code> in <code>System_data</code> gets checked at each line of the file:</p>
<pre><code>for line in f:
print "Start of line %s" % line
print "End of line"
for entry in System_data:
print "Entr... | 1 | 2016-06-03T15:22:01Z | [
"python",
"file"
] |
Python: Script won't find word in text file | 37,617,963 | <p>I am trying to find specific words from a text file, however my script doesn't seem to be able to match the word to what's written on a line in the text file, even though I know it matches. I've noticed there are spaces but since I am saying <code>entry in line</code>, shouldn't it work?</p>
<p>I have also tried:</... | 0 | 2016-06-03T15:14:41Z | 37,674,700 | <p>Ok so it seems the issue was that the string was actually in hexadecimal form.
But it only appeared in hexadecimal form to me when I used <code>print repr(line)</code> it appeared like:
<code>'\x00m\x00a\x00n\x00u\x00f\x00a\x00c\x00t\x00u\x00r\x00e\x00r\x00_\x00d\x00a\x0ââ0t\x00a\x00'</code></p>
<p>So I changed... | 0 | 2016-06-07T08:50:50Z | [
"python",
"file"
] |
Combine multi-dimentional data in numpy | 37,617,996 | <p>I have 1-d <code>NumPy</code> arrays which represent the points on an n-d grid. Each <code>NumPy</code> array represents points in a dimension. I want to generate a merged <code>NumPy</code> array that will have the n-d grid with a shape <code>(n , m)</code> where <code>n</code> would <code>len(dim-1) * len(dim-2) *... | 1 | 2016-06-03T15:16:27Z | 37,618,103 | <p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> to create the <em>extended</em> versions and then use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.column_stack.html" rel="nofollow"><code>np.c... | 1 | 2016-06-03T15:21:44Z | [
"python",
"arrays",
"numpy"
] |
Combine multi-dimentional data in numpy | 37,617,996 | <p>I have 1-d <code>NumPy</code> arrays which represent the points on an n-d grid. Each <code>NumPy</code> array represents points in a dimension. I want to generate a merged <code>NumPy</code> array that will have the n-d grid with a shape <code>(n , m)</code> where <code>n</code> would <code>len(dim-1) * len(dim-2) *... | 1 | 2016-06-03T15:16:27Z | 37,618,137 | <p>You can do this simply with <code>itertools.product</code>
For instance:</p>
<pre><code>x = [1,2]
y = [3,4,5]
list(itertools.product(x, y))
# [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
</code></pre>
<p>This also works for more than two inputs:</p>
<pre><code>a = [1]
b = [2,3]
c = [4,5,6]
list(itertools.prod... | 0 | 2016-06-03T15:23:12Z | [
"python",
"arrays",
"numpy"
] |
Combine multi-dimentional data in numpy | 37,617,996 | <p>I have 1-d <code>NumPy</code> arrays which represent the points on an n-d grid. Each <code>NumPy</code> array represents points in a dimension. I want to generate a merged <code>NumPy</code> array that will have the n-d grid with a shape <code>(n , m)</code> where <code>n</code> would <code>len(dim-1) * len(dim-2) *... | 1 | 2016-06-03T15:16:27Z | 37,618,145 | <p>This isn't a very elegant solution but it will get it done:</p>
<pre><code>import pandas as pd
import numpy as np
x = np.array([1, 2])
y = np.array([3, 4, 5])
pd.MultiIndex.from_product([x, y]).to_series().apply(pd.Series).values
array([[1, 3],
[1, 4],
[1, 5],
[2, 3],
[2, 4],
[... | 0 | 2016-06-03T15:23:38Z | [
"python",
"arrays",
"numpy"
] |
How to mix two numpy arrays using a boolean mask to create one of the same size efficiently? | 37,618,013 | <p>I use two arrays of the same size like :</p>
<pre><code>>>> a = [range(10)]
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = -a
>>> b
array([ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9])
</code></pre>
<p>I want to create another array using a boolean "mask", for example :</p>
<pr... | 0 | 2016-06-03T15:17:20Z | 37,618,344 | <p>You are looking for <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>c = numpy.where(m, a, b)
</code></pre>
<p>Good luck. </p>
| 7 | 2016-06-03T15:33:31Z | [
"python",
"arrays",
"performance",
"numpy",
"mask"
] |
How to mix two numpy arrays using a boolean mask to create one of the same size efficiently? | 37,618,013 | <p>I use two arrays of the same size like :</p>
<pre><code>>>> a = [range(10)]
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = -a
>>> b
array([ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9])
</code></pre>
<p>I want to create another array using a boolean "mask", for example :</p>
<pr... | 0 | 2016-06-03T15:17:20Z | 37,618,431 | <p>Using list comprehension you could create some conditionals that determine what list to pick form?</p>
<pre><code>result = [ a[i] if bol else b[i] for i, bol in enumerate(mask)]
</code></pre>
<p>And then you could apply some functions to a[i] or b[i] depending on how you want to alter them.</p>
| 0 | 2016-06-03T15:37:43Z | [
"python",
"arrays",
"performance",
"numpy",
"mask"
] |
How do I create a superuser account in Django 1.9.6 | 37,618,059 | <p>I am reading a book ("Learning Django Web Development" by Sanjeev Jaiswal and Ratan Kumar) on Django, but the book is based on an earlier version of Django (prior to version 1.9). In order to populate the database with tables, the book uses the syncdb command:</p>
<pre><code>$ python manage.py syncdb
</code></pre>... | 4 | 2016-06-03T15:19:21Z | 37,618,138 | <pre><code>$ python manage.py migrate
$ python manage.py createsuperuser
</code></pre>
<p><a href="https://docs.djangoproject.com/en/1.9/ref/django-admin/" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/django-admin/</a></p>
| 0 | 2016-06-03T15:23:22Z | [
"python",
"django",
"web-deployment"
] |
How do I create a superuser account in Django 1.9.6 | 37,618,059 | <p>I am reading a book ("Learning Django Web Development" by Sanjeev Jaiswal and Ratan Kumar) on Django, but the book is based on an earlier version of Django (prior to version 1.9). In order to populate the database with tables, the book uses the syncdb command:</p>
<pre><code>$ python manage.py syncdb
</code></pre>... | 4 | 2016-06-03T15:19:21Z | 37,618,142 | <p>I think you want to run these commands:</p>
<p><code>python manage.py makemigrations</code> creates migration files based on your models</p>
<p><code>python manage.py migrate</code> will create the tables in your db based on the migration files created</p>
<p>(see <a href="https://docs.djangoproject.com/en/1.9/to... | 3 | 2016-06-03T15:23:24Z | [
"python",
"django",
"web-deployment"
] |
Get derivative of data in python | 37,618,216 | <p>I write a program to get derivative. InterpolatedUnivariateSpline is used for calculating f(x+h). The red line is derivative of cosine, the green line is cosine consine, the blue line is -sine function. The red and blue line are matched. It works well in the following. </p>
<p><img src="http://i.stack.imgur.com/CpK... | 0 | 2016-06-03T15:27:24Z | 37,622,006 | <p>You have a <a href="https://en.wikipedia.org/wiki/Loss_of_significance" rel="nofollow">loss of significance</a> problem. It means that when adding a large floating point number to a small one, the precision of the small one is partially lost as a numpy double can only hold 64 bits of information.</p>
<p>To solve t... | 0 | 2016-06-03T19:25:35Z | [
"python",
"numpy",
"scipy",
"derivative"
] |
Unnecessary output in my text to binary code in Python | 37,618,253 | <p>I'm trying to make a code that will convert text to binary. I know I can make this program easily work by simply using the <code>encode()</code> and <code>decode()</code> functions, but I wanted to see if I can make it on my own. </p>
<p>This is my program:</p>
<pre><code>message=input("Word to translate: ")
rema... | 0 | 2016-06-03T15:29:07Z | 37,618,287 | <p>De-indent the <code>print</code> so it appears outside of the loop.</p>
<pre><code>message=input("Word to translate: ")
remains=""
for value in message:
number = ord (value)
while number > 0:
remain = number % 2
number = int ( number / 2 )
remains+=str(remain)
print(remain... | 1 | 2016-06-03T15:30:42Z | [
"python",
"binary"
] |
Just learned to scrape data and store it in my DB but it only scrapes one object | 37,618,263 | <p>First I am a novice, I'm still new to python and Django and I've just recently experimented with scraping my data and storing it in My database. I've got it to work kind of. It only scrapes one object and stores it. not multiple objects. Right now I am developing locally and trying to figure it out. I have it in a v... | 1 | 2016-06-03T15:29:29Z | 37,618,467 | <p>It only goes through the loop once because of this line:</p>
<p><code>return render(request, template, context)</code></p>
<p><code>return</code> returns out of the whole function altogether the first time it gets ran (in the first loop). If you want to go through each loop then return, move the <code>return</code... | 1 | 2016-06-03T15:39:40Z | [
"python",
"django",
"heroku",
"web-scraping"
] |
Problems with colorbar range matplotlib python | 37,618,291 | <p>I want to set my colorbar so I can see difference between the small values with different colors. For exeample: two different colors between 0.4 and 0.6.
But my maximum value is 3, which makes hard to see this values.
How can I set different intervals for different colors in the colorbar so I can see this differenc... | 2 | 2016-06-03T15:30:47Z | 37,621,499 | <p>Try this:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
delta = 0.025
x = y = np.arange(0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10e1 * (Z1*Z2) # Random function creation
levels... | 0 | 2016-06-03T18:49:05Z | [
"python",
"matplotlib",
"colorbar"
] |
Download from MEDIA_ROOT does not work | 37,618,299 | <p>I'm trying to make one <code>User</code> to upload a file (in some language) and another <code>User</code> to download it so they can translate it.</p>
<p>I've set media root adn media url:</p>
<pre><code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code></pre>
<p>When someone uploads a fi... | 4 | 2016-06-03T15:31:02Z | 37,618,729 | <p>I am guessing you are on the development server? Add this to the <code>urls.py</code> config file to tell Django's development server to serve <code>static/</code> and <code>media/</code> files too.</p>
<pre><code>if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from dj... | 3 | 2016-06-03T15:53:04Z | [
"python",
"django",
"django-file-upload"
] |
How to find element by multiline text | 37,618,376 | <p>How do you find an element by text if the text you're passing contains a break?</p>
<pre><code><div>
"Hello"
<br>
"World"
</div>
</code></pre>
<p>The following works: </p>
<pre><code>text = 'Hello'
driver.find_element_by_xpath("//div[text()[contains(.,'%s')]]"%text)
</code></pre>
<p>This fai... | 2 | 2016-06-03T15:35:09Z | 37,618,948 | <p>Try to use normalize-space.</p>
<p>This works for me:</p>
<p>I ahve run the flask webserver:</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return """<div>
"Hello"
<br>
"World"
</div>"""
if __name__ == "__main__":
app.run()
</c... | 0 | 2016-06-03T16:05:25Z | [
"python",
"selenium-webdriver"
] |
How to find element by multiline text | 37,618,376 | <p>How do you find an element by text if the text you're passing contains a break?</p>
<pre><code><div>
"Hello"
<br>
"World"
</div>
</code></pre>
<p>The following works: </p>
<pre><code>text = 'Hello'
driver.find_element_by_xpath("//div[text()[contains(.,'%s')]]"%text)
</code></pre>
<p>This fai... | 2 | 2016-06-03T15:35:09Z | 37,657,879 | <p>You should try below <code>xPath</code> to find element:-</p>
<pre><code>text = 'Hello' or 'Hello World'
driver.find_element_by_xpath("//div[normalize-space(text() = '%s')]" %text)
</code></pre>
<p>In this way you can ignore <code><br></code></p>
<p>Hope it will help you..:)</p>
| 0 | 2016-06-06T12:46:28Z | [
"python",
"selenium-webdriver"
] |
How can I log both successful and failed login and logout attempts in Django? | 37,618,473 | <p>I want to record all user login and logout attempts in Django. This record should show a history of all users who logged in/out, IP address and time of login/logout.</p>
<p>The <code>django_admin_log</code> table seems to only record ADD/DELETE/CHANGE activities of other models, not a history of user access. I've a... | 3 | 2016-06-03T15:40:02Z | 37,620,866 | <p>You could hook up to the provided signals: <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/auth/#module-django.contrib.auth.signals" rel="nofollow">django.contrib.auth.signals</a></p>
<h2>Recording to log</h2>
<pre><code>import logging
from django.contrib.auth.signals import user_logged_in, user_logged_... | 4 | 2016-06-03T18:04:58Z | [
"python",
"django",
"logging"
] |
Error in URL configuration trying to set up django-contact-form | 37,618,477 | <p>I have installed the <code>django-contact-form</code> module and modified my <code>urls.py</code> file at the root level of my django app to contain:</p>
<pre><code>from django.conf.urls import include, url
urlpatterns = [
# ... other URL patterns for your site ...
url(r'^contact/', include('contact_form.... | 1 | 2016-06-03T15:40:12Z | 37,618,648 | <p>Have you tried adding <code>django.contrib.sites</code> to the <code>INSTALLED_APPS</code> list in your <code>settings.py</code>?</p>
| 1 | 2016-06-03T15:48:40Z | [
"python",
"django",
"forms",
"django-forms"
] |
math.floor(N) vs N // 1 | 37,618,590 | <p>I am wondering if anyone can give me any insight into how the following may be the same / different in <strong>Python3</strong>:</p>
<pre><code>N // 1
</code></pre>
<p>and</p>
<pre><code>from math import floor
floor(N)
</code></pre>
<p>I tried the following, which seems to indicate that they are equivalent:</p>
... | 1 | 2016-06-03T15:45:39Z | 37,618,684 | <p>You will spot a difference when using floats:</p>
<pre><code>>>> 1000.5//1
1000.0
>>> floor(1000.5)
1000
</code></pre>
<p><code>floor</code> returns an integer. For most cases <code>1000</code> and <code>1000.0</code> are equivalent, but not always.</p>
| 4 | 2016-06-03T15:50:12Z | [
"python",
"math",
"floor"
] |
math.floor(N) vs N // 1 | 37,618,590 | <p>I am wondering if anyone can give me any insight into how the following may be the same / different in <strong>Python3</strong>:</p>
<pre><code>N // 1
</code></pre>
<p>and</p>
<pre><code>from math import floor
floor(N)
</code></pre>
<p>I tried the following, which seems to indicate that they are equivalent:</p>
... | 1 | 2016-06-03T15:45:39Z | 37,618,712 | <ol>
<li><p><code>math.floor(N)</code> returns an int, and <code>N // 1</code> returns a float.</p>
<pre><code>>>> type(math.floor(-4.4))
<class 'int'>
>>> type((-4.4) // 1)
<class 'float'>
</code></pre></li>
<li><p>Because of this <code>floor(nan)</code> will raise ValueError while <code... | 3 | 2016-06-03T15:51:36Z | [
"python",
"math",
"floor"
] |
math.floor(N) vs N // 1 | 37,618,590 | <p>I am wondering if anyone can give me any insight into how the following may be the same / different in <strong>Python3</strong>:</p>
<pre><code>N // 1
</code></pre>
<p>and</p>
<pre><code>from math import floor
floor(N)
</code></pre>
<p>I tried the following, which seems to indicate that they are equivalent:</p>
... | 1 | 2016-06-03T15:45:39Z | 37,618,887 | <p><code>math.floor</code> first tries to use the <code>__floor__</code> magic method, if it does not exist it instead uses <code>__float__</code> and then floors that, so it will work when the object supports <code>__floor__</code> or can be cast to a <code>float</code>.</p>
<p><code>x//1</code> uses the <code>__floo... | 2 | 2016-06-03T16:02:00Z | [
"python",
"math",
"floor"
] |
Compare two different size matrices to make one large matrix - Speed Improvements? | 37,618,611 | <p>I have two matrices, that I need to use to create a larger matrix. Each matrix is simply a tab-delimited text file that is read. Each matrix has 48 cols with identical identifiers per matrix, with different numbers of rows. The first matrix is 108887x48, and the second is 55482x48. The entries at each position, for ... | 2 | 2016-06-03T15:46:36Z | 37,620,483 | <p>I don't quite understand what this code does (the single letter variable names doesn't help). </p>
<p>My suggestion: Try to reduce how many operations you do in the innermost loops. For instance, do you need to recalculate <code>pos</code> in the inner level?</p>
<pre><code>pos = header.index(k[0])
</code></pre>
... | 0 | 2016-06-03T17:40:08Z | [
"python",
"performance",
"matrix",
"large-data"
] |
Compare two different size matrices to make one large matrix - Speed Improvements? | 37,618,611 | <p>I have two matrices, that I need to use to create a larger matrix. Each matrix is simply a tab-delimited text file that is read. Each matrix has 48 cols with identical identifiers per matrix, with different numbers of rows. The first matrix is 108887x48, and the second is 55482x48. The entries at each position, for ... | 2 | 2016-06-03T15:46:36Z | 37,621,374 | <p>This is just a matrix multiplication. You want to multiply the first matrix by the transpose of the second. For efficient matrix operations, get <a href="http://www.numpy.org/" rel="nofollow">NumPy</a>.</p>
<p>If you read your two input matrices into NumPy arrays of dtype <code>numpy.int8</code>, then the computati... | 2 | 2016-06-03T18:41:01Z | [
"python",
"performance",
"matrix",
"large-data"
] |
Write a CSV without delimiters in Python | 37,618,674 | <p>I'm having a problem... </p>
<p>I have a list of a number of websites, like this example. </p>
<pre><code>[u'www.rosenzweigco.com', u'www.investopedia.com', u'www.bk.mufg.jp']
</code></pre>
<p>However, when I want to have a CSV file, I'm getting this:</p>
<pre><code>w,w,w,.,r,o,s,e,n,z,w,e,i,g,c,o,.,c,o,m,
w,w,w... | 1 | 2016-06-03T15:49:42Z | 37,618,778 | <p><code>.writerow</code> takes an iterable and writes each item in the iterable as a column in your csv. It looks like you are passing a single string as <code>row</code>. In this case, you'd want:</p>
<pre><code>for website in data:
mycsv.writerow([website])
</code></pre>
<p>However, I'm guessing this isn't <... | 0 | 2016-06-03T15:56:06Z | [
"python",
"list",
"csv",
"delimiter"
] |
Write a CSV without delimiters in Python | 37,618,674 | <p>I'm having a problem... </p>
<p>I have a list of a number of websites, like this example. </p>
<pre><code>[u'www.rosenzweigco.com', u'www.investopedia.com', u'www.bk.mufg.jp']
</code></pre>
<p>However, when I want to have a CSV file, I'm getting this:</p>
<pre><code>w,w,w,.,r,o,s,e,n,z,w,e,i,g,c,o,.,c,o,m,
w,w,w... | 1 | 2016-06-03T15:49:42Z | 37,618,858 | <p>The first idea struck me is the same as mgilson's answer.
Also, if you are using python 3 , you need to open file with 'w' parameter, without binary mode unlike the python 2.7 </p>
<p>Python 3.5</p>
<pre><code>with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
... | 0 | 2016-06-03T15:59:47Z | [
"python",
"list",
"csv",
"delimiter"
] |
Problems with conditional dictionary lookup via if statement | 37,618,675 | <p>I have a dictionary which I am populating with values. The values are served to the dictionary through a for-loop.</p>
<pre><code>storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
i... | 1 | 2016-06-03T15:49:44Z | 37,619,047 | <p><strong>RESPONSE INACCURATE</strong></p>
<p>Ok. With the help of @spectras and @wwii (thank you for pointing me in the right direction) I was able to come up with a solution. The issue was in the way I set up my logical check in combination with not using the some_dict.get(item) method. </p>
<p>Here the solution:<... | 0 | 2016-06-03T16:11:49Z | [
"python",
"if-statement",
"dictionary"
] |
Problems with conditional dictionary lookup via if statement | 37,618,675 | <p>I have a dictionary which I am populating with values. The values are served to the dictionary through a for-loop.</p>
<pre><code>storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
i... | 1 | 2016-06-03T15:49:44Z | 37,619,176 | <p>Use <code>zip</code> on both list and check if a key-value pair has an alternate value-key pair in the dictionary:</p>
<pre><code>d = {}
for k, v in list(zip(listholder, values))[:-1]:
if v in d:
if d[v] == k:
continue
d[k] = v
print(d)
# {'word5': 'word6', 'word4': 'word5', 'word2': '... | 0 | 2016-06-03T16:19:00Z | [
"python",
"if-statement",
"dictionary"
] |
Problems with conditional dictionary lookup via if statement | 37,618,675 | <p>I have a dictionary which I am populating with values. The values are served to the dictionary through a for-loop.</p>
<pre><code>storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
i... | 1 | 2016-06-03T15:49:44Z | 37,619,413 | <p>Here is one way to do it. I basically <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">zip</a> them, filter the entries we don't need and then convert the filtered list into <a href="https://docs.python.org/2/library/functions.html#func-dict" rel="nofollow">dict</a>.</p>
<pre><code>list... | 1 | 2016-06-03T16:32:35Z | [
"python",
"if-statement",
"dictionary"
] |
Submitting jobs with numeric arguments to QSUB using Python | 37,618,695 | <p>I want to run a python function,say <code>my_fun(x1,x2)</code>, on different nodes of cluster with SGE (QSUB). I created a script <code>my_script.py</code> which takes in the numeric arguments from the command line, so when running locally, I'd call it as</p>
<pre><code>python my_script.py x1 x2
</code></pre>
<p>N... | 0 | 2016-06-03T15:51:01Z | 37,618,940 | <p>I suggest you divide the job into multiple independent jobs depending on the number of nodes you have. </p>
<p>For each node/core, create a folder with a file containing the a list of the parameters this subjob should treat. Then in python, write a script which reads the file and calls your script (maybe using the ... | 1 | 2016-06-03T16:04:58Z | [
"python",
"subprocess",
"cluster-computing",
"pbs",
"qsub"
] |
Submitting jobs with numeric arguments to QSUB using Python | 37,618,695 | <p>I want to run a python function,say <code>my_fun(x1,x2)</code>, on different nodes of cluster with SGE (QSUB). I created a script <code>my_script.py</code> which takes in the numeric arguments from the command line, so when running locally, I'd call it as</p>
<pre><code>python my_script.py x1 x2
</code></pre>
<p>N... | 0 | 2016-06-03T15:51:01Z | 37,619,578 | <p>This more or less does what I'm looking for:</p>
<p><a href="https://gist.github.com/timflutre/a9085660271bd059f71c" rel="nofollow">https://gist.github.com/timflutre/a9085660271bd059f71c</a></p>
<pre><code>import sys
import subprocess
job_param1 = 12.5
job_param2 = 5.0
jobName = "python my_script.py %f %f" % (job... | 0 | 2016-06-03T16:43:00Z | [
"python",
"subprocess",
"cluster-computing",
"pbs",
"qsub"
] |
add data to csv column wise using pandas | 37,618,732 | <p>I have some csv files and I want to copy a specific column from all of them and save it in a new csv file column wise.But the following code add them in a single column.</p>
<p>Also in total I have to go through almost 20M data so I don't want to store them in a single dataframe and save them in last.</p>
<p>Here ... | -1 | 2016-06-03T15:53:25Z | 37,621,530 | <p>you can do it this way:</p>
<pre><code>def get_merged_csv(flist, **kwargs):
return pd.concat([pd.read_csv(f, **kwargs) for f in flist], axis=1)
fmask = '*.csv'
# column numbers are starting from 0, so 9th column has index 8
df = get_merged_csv(glob.glob(fmask), usecols=[8])
df.to_csv(filename,mode="a",header=... | 1 | 2016-06-03T18:51:12Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
add data to csv column wise using pandas | 37,618,732 | <p>I have some csv files and I want to copy a specific column from all of them and save it in a new csv file column wise.But the following code add them in a single column.</p>
<p>Also in total I have to go through almost 20M data so I don't want to store them in a single dataframe and save them in last.</p>
<p>Here ... | -1 | 2016-06-03T15:53:25Z | 37,802,474 | <p>I'm not sure how to do this using Pythond, but in R, it is very easy.</p>
<p>Merge all columns in File1 and Column12 in File2.</p>
<pre><code>import pandas as pd
file1 = pd.read_table('C:\\Users\Users\\your_path_here\\Book1.csv', delimiter=',', header=None)
file2 = pd.read_table('C:\\Users\\Users\\your_path_here\\... | 0 | 2016-06-14T03:28:21Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
How to make a simple script in MYSQL Workbench to execute a query and export results into a CSV | 37,618,805 | <p>I'm really new at coding.</p>
<p>I'm just trying to figure out how to make a simple script for Mysql Workbench that it just runs a given query, and then exports the results into a CSV.</p>
<p>I know this works for executing the query:</p>
<pre><code>import grt
result = grt.root.wb.sqlEditors[0].executeScript("gi... | 1 | 2016-06-03T15:57:27Z | 37,619,059 | <p>Python 3.5</p>
<pre><code>import csv
import grt
result = grt.root.wb.sqlEditors[0].executeScript("givenquery")
with open('file.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for res in result:
... | 1 | 2016-06-03T16:12:30Z | [
"python",
"mysql-workbench",
"mysql-python"
] |
Socket: Reading UDP Packet | 37,618,851 | <p>I've been searching about this question, but i couldn't understand the question since it was not really general, I wouldn't find the solution to read UDP packets that contain UTF-8 text for example.</p>
<p>So i make a socket, that makes a UDP packet that contains UTF-8 text, and i send it like this:</p>
<pre><code... | 3 | 2016-06-03T15:59:27Z | 37,619,243 | <p>You'll want the receiver to do several things:</p>
<ol>
<li>Create a socket <code>sock</code> using <code>socket.socket</code>.</li>
<li>Bind to the socket using <code>sock.bind</code>.</li>
<li>In an infinite loop, execute: <code>data, addr = sock.recvfrom(1024)</code>.</li>
<li>Now the received data is available ... | 2 | 2016-06-03T16:22:05Z | [
"python",
"sockets",
"network-programming"
] |
Python crawler verification picture | 37,618,855 | <p>I want to crawl a verification picture, and I've achieve it by using curl like this.</p>
<pre><code>curl "https://www.ris.gov.tw/apply/captcha/image?CAPTCHA_KEY=71cc3b094e824446873038401ab8c303&time=1464968502855" -H "Referer: https://www.ris.gov.tw/id_card/" --insecure >> a.jpg
</code></pre>
<p>P.S (the... | 2 | 2016-06-03T15:59:40Z | 37,620,146 | <p>These changes gave me the JPEG file:</p>
<pre><code>res = rs.get(url, headers={'referer': 'https://www.ris.gov.tw/id_card/'})
with open('check.jpg', 'wb') as jpeg_file:
jpeg_file.write(res.content)
</code></pre>
<p>The <a href="http://docs.python-requests.org/en/master/api/#requests.Response.content" rel="nofo... | 1 | 2016-06-03T17:17:47Z | [
"python",
"curl",
"web-crawler"
] |
Pyspark computing correlation | 37,618,977 | <p>I want to use pyspark.mllib.stat.Statistics.corr function to compute correlation between two columns of pyspark.sql.dataframe.DataFrame object. corr function expects to take an rdd of Vectors objects. How do I translate a column of df['some_name'] to rdd of Vectors.dense object?</p>
| 0 | 2016-06-03T16:06:55Z | 37,619,189 | <p>There should be no need for that. For numerical you can compute correlation directly using <code>DataFrameStatFunctions.corr</code>:</p>
<pre><code>df1 = sc.parallelize([(0.0, 1.0), (1.0, 0.0)]).toDF(["x", "y"])
df1.stat.corr("x", "y")
# -1.0
</code></pre>
<p>otherwise you can use <code>VectorAssembler</code>:</p>... | 2 | 2016-06-03T16:19:35Z | [
"python",
"pyspark",
"pyspark-sql"
] |
Pyspark computing correlation | 37,618,977 | <p>I want to use pyspark.mllib.stat.Statistics.corr function to compute correlation between two columns of pyspark.sql.dataframe.DataFrame object. corr function expects to take an rdd of Vectors objects. How do I translate a column of df['some_name'] to rdd of Vectors.dense object?</p>
| 0 | 2016-06-03T16:06:55Z | 37,619,227 | <p>Ok I figured it out:</p>
<pre><code>v1 = df.flatMap(lambda x: Vectors.dense(x[col_idx_1]))
v2 = df.flatMap(lambda x: Vectors.dense(x[col_idx_2]))
</code></pre>
| 1 | 2016-06-03T16:21:22Z | [
"python",
"pyspark",
"pyspark-sql"
] |
Cant get ajax response to place nice with python code | 37,619,002 | <p><strong>Question:</strong> For some reason I can't seem to figure out why my ajax call will not return a value for success if my wo_data query comes up empty. What I want to happen is if I put a value into id_work_order and its not found in my db pop up an alert saying workorder was not found- otherwise if it is f... | 0 | 2016-06-03T16:08:40Z | 37,619,166 | <p>the code here is never reached:</p>
<pre><code> else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
</code></pre>
<p>because if <code>if wo_data.exists():</code> is not true, then <code>for x in wo_data:</code> would never have any iterations in the fi... | 1 | 2016-06-03T16:18:34Z | [
"javascript",
"python",
"django"
] |
python LDAP modify password | 37,619,024 | <p>I have a Windows 2012 R2 server and a LDAP server on it. I wrote a python script to modify the password of user (the user, who isn't admin, want to modify is own password. I have an other function which modify the password when you're admin, but I don't want to set a password, but modify it). This is a sample of my ... | 0 | 2016-06-03T16:10:08Z | 37,619,712 | <p>The error message part you want to focus on is <code>'info': '0000052D</code>. The hex value <code>0000052D</code> translates to a system error code of decimal 1325. That error code is documented <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385%28v=vs.85%29.aspx" rel="nofollow">here</a>:</p... | 0 | 2016-06-03T16:51:15Z | [
"python",
"passwords",
"ldap"
] |
Possible in Python to "import virus" | 37,619,138 | <p>I've searched the Google and on stackoverflow for this, so if it exists anywhere, my sincerest apologies. I'm (obviously) a newbie to Python, and one of my main concern with finding a new module that does whatever new programming project comes my way is this:</p>
<p>What's preventing a module (once imported) from d... | -5 | 2016-06-03T16:17:26Z | 37,619,271 | <p>Nothing prevents it. That's one of the benefits of open-source software (in the strictest sense of "source code that I can view"): you can, in theory, examine it to see exactly what it does before actually running it.</p>
<p>In practice, you usually just extend some level of trust to the source:</p>
<ol>
<li>Is th... | 5 | 2016-06-03T16:24:04Z | [
"python",
"virus"
] |
Alternative to "write to file" for transfering CSV data to PostgreSQL using COPY for better performance? | 37,619,208 | <p>I have a dataset in a CSV file consisting of 2500 lines. The file is structured that (simplified) way:</p>
<p><code>id_run; run_name; receptor1; receptor2; receptor3_value; [...]; receptor50_value</code></p>
<p>Each receptor of the file is already in a table and have a unique id.</p>
<p>I need to upload each line... | 2 | 2016-06-03T16:20:32Z | 37,619,975 | <blockquote>
<p>I'm writing all the data I need to upload in a .txt file and I'm using the COPY command from postgreSQL to transfer the file to the destination table.</p>
</blockquote>
<p>It is a heavy and unnecessary round-trip for all your data. Since you already have it in memory, you should just translate it int... | 1 | 2016-06-03T17:07:33Z | [
"python",
"sql",
"postgresql",
"csv",
"postgresql-copy"
] |
Alternative to "write to file" for transfering CSV data to PostgreSQL using COPY for better performance? | 37,619,208 | <p>I have a dataset in a CSV file consisting of 2500 lines. The file is structured that (simplified) way:</p>
<p><code>id_run; run_name; receptor1; receptor2; receptor3_value; [...]; receptor50_value</code></p>
<p>Each receptor of the file is already in a table and have a unique id.</p>
<p>I need to upload each line... | 2 | 2016-06-03T16:20:32Z | 37,629,062 | <p>Yes, there is something you can do to speed up writing the data to the file in advance: don't bother!</p>
<p>You already fit the data into memory, so that isn't an issue. So, instead of writing the lines to a list of strings, write them to a slightly different object - a <a href="https://docs.python.org/2/library/s... | 1 | 2016-06-04T10:23:46Z | [
"python",
"sql",
"postgresql",
"csv",
"postgresql-copy"
] |
Where is my syntax error? | 37,619,235 | <p>I'm trying to see where a Python syntax error would be hiding. Both Django and pylint claim a syntax error at custom.py:41. Lines 41-42 read:</p>
<pre><code> (reading_threshold =
int(request.POST['reading_threshold']))
</code></pre>
<p>I do not see anything that I can notice as wrong in th... | -4 | 2016-06-03T16:21:38Z | 37,619,361 | <p>You're looking right at the error. Python isn't C; assignment is a statement, rather than an expression, so you can't parenthesize it.</p>
| 2 | 2016-06-03T16:29:23Z | [
"python",
"django",
"syntax-error"
] |
Summing 2nd list items in a list of lists of lists | 37,619,348 | <p>My data is a list of lists of lists of varying size:</p>
<pre><code>data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]],.....]]]
</code></pre>
<p>What I want to do is return a list of lists with the values of the 2nd element of each list of lists summed - so, 3+5+7 is a list, so is 11+15, etc:</p>
<pre><code>newdata =... | 4 | 2016-06-03T16:28:34Z | 37,619,528 | <p>Something like this is pretty short and concise, using list comprehensions and <code>map</code> (I try not to use nested comprehensions if I can avoid it)</p>
<pre><code>import operator
f = operator.itemgetter(1)
[sum(map(f, x)) for x in data]
</code></pre>
| 3 | 2016-06-03T16:39:54Z | [
"python",
"list",
"list-comprehension"
] |
Summing 2nd list items in a list of lists of lists | 37,619,348 | <p>My data is a list of lists of lists of varying size:</p>
<pre><code>data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]],.....]]]
</code></pre>
<p>What I want to do is return a list of lists with the values of the 2nd element of each list of lists summed - so, 3+5+7 is a list, so is 11+15, etc:</p>
<pre><code>newdata =... | 4 | 2016-06-03T16:28:34Z | 37,619,560 | <p>Try this one-line approach using list comprehension:</p>
<pre><code>[sum([x[1] for x in i]) for i in data]
</code></pre>
<p>Output:</p>
<pre><code>data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]]]
[sum([x[1] for x in i]) for i in data]
Out[19]: [15, 26]
</code></pre>
<p>If you want the output to be a list of list,... | 7 | 2016-06-03T16:41:55Z | [
"python",
"list",
"list-comprehension"
] |
Summing 2nd list items in a list of lists of lists | 37,619,348 | <p>My data is a list of lists of lists of varying size:</p>
<pre><code>data = [[[1, 3],[2, 5],[3, 7]],[[1,11],[2,15]],.....]]]
</code></pre>
<p>What I want to do is return a list of lists with the values of the 2nd element of each list of lists summed - so, 3+5+7 is a list, so is 11+15, etc:</p>
<pre><code>newdata =... | 4 | 2016-06-03T16:28:34Z | 37,619,718 | <p>@mathmax and @BrendanAbel have offered Pythonic and performant solutions. However, I want to throw this transpositional approach into the ring for the sake of its brevity and trickyness:</p>
<pre><code>[sum(zip(*x)[1]) for x in data]
</code></pre>
| 4 | 2016-06-03T16:51:58Z | [
"python",
"list",
"list-comprehension"
] |
How do I plot wind speed and direction (U, V) on plot graph in Python? | 37,619,363 | <p>I'm trying to plot the wind speed and direction, but there is an error code that keeps telling me that "sequence too large; cannot be greater than 32." Here is the code that I am using:</p>
<pre><code>N = 500
ws = np.array(u)
wd = np.array(v)
df = pd.DataFrame({'direction': [ws], 'speed': [wd]})
df
direction sp... | 0 | 2016-06-03T16:29:28Z | 37,626,726 | <p>To plot wind U, V use <code>barbs</code> and <code>quiver</code>. Look at the code below:</p>
<pre><code>import matplotlib.pylab as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
d = np.arctan(Y ** 2. - .25 * Y - X)
U, V = 5 * np.cos(d), np.sin(d)
# barbs plot
ax1 = plt.subplot(1, 2, 1)
... | 0 | 2016-06-04T05:30:20Z | [
"python",
"matplotlib",
"jupyter-notebook"
] |
Python - Plotting a 3 dimensional array | 37,619,374 | <p>I've not yet worked with a 3 dimensional array and I'm a little confused on how to approach this plotting with its relative large size.</p>
<p>There is relative code to this, but it's not necessarily needed in this case.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d im... | 1 | 2016-06-03T16:30:01Z | 37,619,828 | <p>Unpack the values and plot</p>
<pre><code>x,y,z = zip(*MWpos1)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(x, y, z, '.')
ax.legend()
plt.show()
</code></pre>
<p><a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow">Read more at the tutorial</a></p>
| 3 | 2016-06-03T16:58:52Z | [
"python",
"arrays",
"numpy",
"matplotlib"
] |
What does this for loop with undefined terms inside brackets mean in python? | 37,619,440 | <p>I have a mathematics code in python and need to convert it to java. But I can't understand it:</p>
<pre><code>#python source
sum([d**2 for d in (x - y)])
</code></pre>
<p><code>d</code> is not defined before this line. <code>x,y</code> are arrays and defined and have value. I have trouble with the <code>for</code>... | -3 | 2016-06-03T16:34:03Z | 37,621,350 | <p>The actual for loop surrounded by brackets is a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>, which generates a list. This is expressed, in general, as follows:</p>
<pre><code>[ expression( <variables> ) for <variables> in <... | 1 | 2016-06-03T18:39:35Z | [
"python",
"arrays",
"for-loop",
"square-bracket"
] |
GIS SQL Query Logic Syntax | 37,619,476 | <p>I have a GIS layer that has thousands of Facility IDs. </p>
<ul>
<li>For each Facility ID there can be multiple Chemical ID's. </li>
<li>For each chemical ID there is a maximum of 3 zone types. Zone A, B, C. But there is not always 3 Zone types, it varies. </li>
<li>And the amount of chemical ID's for each Facility... | 0 | 2016-06-03T16:36:20Z | 37,620,085 | <p>Using this example in access. I prepare a demo on MySQL.</p>
<p><a href="http://stackoverflow.com/questions/21917637/achieving-row-number-partition-by-in-ms-access">Achieving ROW_NUMBER / PARTITION BY in MS Access</a></p>
<p><strong><a href="http://sqlfiddle.com/#!9/746b653/13" rel="nofollow">SQL Fiddle Demo</a></... | 0 | 2016-06-03T17:13:30Z | [
"python",
"sql",
"gis"
] |
GIS SQL Query Logic Syntax | 37,619,476 | <p>I have a GIS layer that has thousands of Facility IDs. </p>
<ul>
<li>For each Facility ID there can be multiple Chemical ID's. </li>
<li>For each chemical ID there is a maximum of 3 zone types. Zone A, B, C. But there is not always 3 Zone types, it varies. </li>
<li>And the amount of chemical ID's for each Facility... | 0 | 2016-06-03T16:36:20Z | 37,620,326 | <pre><code>Select f.FacilityID,
f.ZoneType,
m.MaxZoneDistance
from AllZones f
join (
SELECT max(ZoneDistance) MaxZoneDistance,
FacilityID
FROM AllZones
group by FacilityID
) m
on f.facilityID=m.facilityID
and MaxZoneDista... | 0 | 2016-06-03T17:28:20Z | [
"python",
"sql",
"gis"
] |
How to determine how many unique other items an integer has been with in a list of lists of lists? | 37,619,548 | <p>I've got a list of lists, with integers in it, like this: </p>
<pre><code>[[[1, 2, 3], [4, 5, 6, 7]], [[3, 7, 5], [1, 2, 4, 6]]]
</code></pre>
<p>Given the integer 1, I would like some way to make a function that will return </p>
<pre><code>[2, 3, 4, 6]
</code></pre>
<p>My current method is: </p>
<pre><code>big... | 2 | 2016-06-03T16:41:08Z | 37,619,665 | <pre><code>>>> set(integer for medList in bigList for smallList in medList for integer in smallList if 1 in smallList)
{1, 2, 3, 4, 6}
</code></pre>
<p>You can use a set comprehension to loop through all the lists and pick out the elements of the lists that contain 1. Notice that the <code>for</code> loops ar... | 4 | 2016-06-03T16:48:18Z | [
"python",
"algorithm"
] |
How to determine how many unique other items an integer has been with in a list of lists of lists? | 37,619,548 | <p>I've got a list of lists, with integers in it, like this: </p>
<pre><code>[[[1, 2, 3], [4, 5, 6, 7]], [[3, 7, 5], [1, 2, 4, 6]]]
</code></pre>
<p>Given the integer 1, I would like some way to make a function that will return </p>
<pre><code>[2, 3, 4, 6]
</code></pre>
<p>My current method is: </p>
<pre><code>big... | 2 | 2016-06-03T16:41:08Z | 37,619,802 | <p>This is a bit shorter, and still pretty readable. Since you only care about the bottom level lists, it would be more readable IMO if you had a function that flattened the nested list structure down to a single iterable of lists (basically what all the <code>chain</code>'s and list comprehensions are doing. Then yo... | 2 | 2016-06-03T16:57:35Z | [
"python",
"algorithm"
] |
how to make graph | 37,619,568 | <p>i want to make graph using matplotlib in python.</p>
<p>np.load(name.npy')</p>
<p>i searched many things and i tried
for example..just...</p>
<pre><code>x = [dt.datetime(2003, 05, 01), dt.datetime(2008, 06, 01)]
df = np.load(r'file')
y = df
</code></pre>
| 1 | 2016-06-03T16:42:29Z | 37,620,002 | <p>Replace the end date on the date-range to your desired graph, and the 'y' should be array loaded</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
start_date = '2003-05-01'
y = np.load(r'c:\python27\abnormal.npy')
x = pd.date_range(start=start_date, periods=len(y), freq='D')
p... | 1 | 2016-06-03T17:08:53Z | [
"python"
] |
how to make graph | 37,619,568 | <p>i want to make graph using matplotlib in python.</p>
<p>np.load(name.npy')</p>
<p>i searched many things and i tried
for example..just...</p>
<pre><code>x = [dt.datetime(2003, 05, 01), dt.datetime(2008, 06, 01)]
df = np.load(r'file')
y = df
</code></pre>
| 1 | 2016-06-03T16:42:29Z | 37,620,541 | <p>If your input array does not contain ordered pairs such as <code>[(0,1), (1,1), (2,2)]</code> and only contains one set of numbers '[1, 2, 3, 4]`, you neeed to create a set of x-coordinates. For a time series in days, you could try something like this:</p>
<pre><code>import datetime
import numpy as np
import matplo... | 1 | 2016-06-03T17:44:44Z | [
"python"
] |
Add python modules to Azure | 37,619,571 | <p>When I run a python script that I set up on WebJobs in Azure - I get the following error:</p>
<pre><code> import MySQLdb
ImportError: No module named MySQLdb
job failed due to exit code 1
</code></pre>
<p>I found some articles that seem to suggest to install python modules to a directory created on the weba... | 0 | 2016-06-03T16:42:40Z | 37,619,846 | <p>Have you tried this?</p>
<p><a href="http://nicholasjackson.github.io/azure/python/python-packages-and-azure-webjobs/" rel="nofollow">http://nicholasjackson.github.io/azure/python/python-packages-and-azure-webjobs/</a>
(from the site):</p>
<blockquote>
<p>Step 1.</p>
<p>If you are using OSX and the default ... | 1 | 2016-06-03T17:00:26Z | [
"python",
"mysql",
"python-2.7",
"azure",
"azure-webjobs"
] |
What is the proper way to write this with streams? | 37,619,707 | <p>The following code should accomplish what is desired if the exception handling worked as expected:</p>
<pre><code>XVector position = new XVector();
IntStream.range(0, desired_star_count).forEach(a -> {
// Try to find a position outside the margin of other stars.
try
{
IntStream.range(0, XStar... | 0 | 2016-06-03T16:50:54Z | 39,733,271 | <p>You can use the following code instead. It avoids both exceptions and breaks in its implementation. With the proper application of streams, the algorithm turns out to be easier to read and understand.</p>
<pre><code>XVector position = new XVector();
IntStream.range(0, DESIRED_STAR_COUNT).forEach(a -> {
// Tr... | 0 | 2016-09-27T19:57:51Z | [
"java",
"python",
"exception-handling",
"stream",
"porting"
] |
Check if one list matches a sublist inside of a list by index | 37,619,748 | <p>I have a data base that consist of about 800 16 number sequences. The sequences are a unique combination of ones and zeros. There is a process that outputs 15 of the numbers in the sequence and I want to look through the data base (historical data) and find all the matches excluding the last number. I started using ... | 0 | 2016-06-03T16:53:49Z | 37,621,069 | <p>If I understand your problem correctly, I would do the following:</p>
<pre><code>T = [0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
joined_T_Search = ''.join(map(str,T))
match_T = [] #empty list to append closest match to
#Match search algorithm
for text in data:
if joined_T_Search == text[:-1]:
matc... | 0 | 2016-06-03T18:19:03Z | [
"python",
"arrays",
"list",
"numpy"
] |
Django: Using a deleted/discarded field en lieu of deleting a database row - What to do with related models? | 37,619,749 | <p>Here's an example of what I'm trying to do:</p>
<pre><code>class Person( models.Model ):
name = models.CharField(max_length=140)
discarded = models.BooleanField( default=False )
class Thing( models.Model ):
name = models.CharField(max_length=140)
discarded = models.BooleanField( default=False )
... | 0 | 2016-06-03T16:53:50Z | 37,619,856 | <p>Write a custom manager for <code>Thing</code> and override its <code>get_queryset</code> method to exclude all discarded items:</p>
<pre><code>class ThingManager(models.Manager):
def get_queryset(self):
return super(ThingManager, self).get_queryset().exclude(discarded=True)
</code></pre>
<p>And update... | 1 | 2016-06-03T17:00:51Z | [
"python",
"django",
"django-models"
] |
retrieve value in a column corresponding to the first occurrence of an element in another column in pandas - python | 37,619,758 | <pre><code>df=pd.DataFrame({'a':['x','x','y','y','y','z','y','y'],'b':np.random.randn(8)})
a b
0 x -0.2414
1 x 1.2214
2 y 0.3442
3 y -2.9492
4 y 0.1214
5 z 2.8102
6 y -1.3844
7 y -0.7363
</code></pre>
<p>What is the most efficient way to select the value in column <code>b<... | 1 | 2016-06-03T16:54:33Z | 37,619,905 | <p>You want to use <code>groupby</code> with <code>a</code> the way I would do it is:</p>
<pre><code>g = df.groupby('a')
g.first()
</code></pre>
<p>Once you have your data grouped, <code>first</code> returns the initial occurrence of <code>a</code></p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.... | 1 | 2016-06-03T17:03:04Z | [
"python",
"pandas",
"dataframe"
] |
retrieve value in a column corresponding to the first occurrence of an element in another column in pandas - python | 37,619,758 | <pre><code>df=pd.DataFrame({'a':['x','x','y','y','y','z','y','y'],'b':np.random.randn(8)})
a b
0 x -0.2414
1 x 1.2214
2 y 0.3442
3 y -2.9492
4 y 0.1214
5 z 2.8102
6 y -1.3844
7 y -0.7363
</code></pre>
<p>What is the most efficient way to select the value in column <code>b<... | 1 | 2016-06-03T16:54:33Z | 37,619,910 | <pre><code>df[df['a'] != df['a'].shift(1)]
Out[22]:
a b
0 x 0.564161
2 y 1.498050
5 z 0.080116
6 y 0.255031
</code></pre>
<p>Original dataframe I used:</p>
<pre><code>df
Out[23]:
a b
0 x 0.564161
1 x -1.153969
2 y 1.498050
3 y 0.067259
4 y -0.345102
5 z 0.080116
6 y 0.25503... | 2 | 2016-06-03T17:03:32Z | [
"python",
"pandas",
"dataframe"
] |
Histogram from Pandas data and specify groupby time | 37,619,778 | <p>How do I make a histogram and find 90% and 95% values from the following output of bars: </p>
<pre><code>bars = ticks.Volume.resample('1s', how=sum)
bars = bars.dropna()
bars
Timestamp
2015-12-27 23:00:25 1.0
2015-12-27 23:01:11 10.0
2015-12-27 23:02:03 1.0
2015-12-27 23:02:14 2.0
2015-12-27 23:... | 1 | 2016-06-03T16:55:41Z | 37,625,749 | <p>These tasks can easily be done using Numpy's <code>histogram</code> and <code>percentile</code> methods.</p>
<p>But first we filter by time of day by first converting the index to datetime objects. In the following example I have changed the target times to include observations in your example dataframe.</p>
<pre>... | 2 | 2016-06-04T02:26:18Z | [
"python",
"pandas"
] |
Import 12000 files into one table | 37,619,803 | <p>I need to setup a streaming enviroment for my project.
The dataset is next: <a href="http://research.microsoft.com/pubs/152883/User_guide_T-drive.pdf" rel="nofollow">http://research.microsoft.com/pubs/152883/User_guide_T-drive.pdf</a></p>
<p>I'm planning to use PostgreSQL and Apache Kafka as a source and then conn... | 1 | 2016-06-03T16:57:37Z | 37,626,617 | <p>One simple solution would be to read the folder using spark and open an odbc connection per partition and iterate and write each row. </p>
| 0 | 2016-06-04T05:10:20Z | [
"java",
"python",
"apache-spark",
"apache-flink"
] |
Python Loop: List Index Out of Range | 37,619,848 | <p>Given the following list:</p>
<pre><code>a=[0,1,2,3]
</code></pre>
<p>I'd like to create a new list, b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.</p>
<p>Like this:
[1,3,5] </p>
<p>(from 0+1, 1+2, and 2+3)</p>
<p>Here's what I've tried... | 2 | 2016-06-03T17:00:29Z | 37,619,941 | <p>When you call <code>for i in a:</code>, you are getting the actual elements, not the indexes. When we reach the last element, that is <code>3</code>, <code>b.append(a[i+1]-a[i])</code> looks for <code>a[4]</code>, doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of... | 1 | 2016-06-03T17:05:50Z | [
"python",
"list",
"loops",
"python-3.x"
] |
Python Loop: List Index Out of Range | 37,619,848 | <p>Given the following list:</p>
<pre><code>a=[0,1,2,3]
</code></pre>
<p>I'd like to create a new list, b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.</p>
<p>Like this:
[1,3,5] </p>
<p>(from 0+1, 1+2, and 2+3)</p>
<p>Here's what I've tried... | 2 | 2016-06-03T17:00:29Z | 37,619,950 | <p>Try reducing the range of the for loop to <code>range(len(a)-1)</code>:</p>
<pre><code>a = [0,1,2,3]
b = []
for i in range(len(a)-1):
b.append(a[i]+a[i+1])
print(b)
</code></pre>
<p>This can also be written as a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollo... | 1 | 2016-06-03T17:06:23Z | [
"python",
"list",
"loops",
"python-3.x"
] |
Python Loop: List Index Out of Range | 37,619,848 | <p>Given the following list:</p>
<pre><code>a=[0,1,2,3]
</code></pre>
<p>I'd like to create a new list, b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.</p>
<p>Like this:
[1,3,5] </p>
<p>(from 0+1, 1+2, and 2+3)</p>
<p>Here's what I've tried... | 2 | 2016-06-03T17:00:29Z | 37,620,051 | <p>You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to <a href="https://docs.python.org/3.3/library/functions.html#zip" rel="nofollow"><code>zip<... | 1 | 2016-06-03T17:11:49Z | [
"python",
"list",
"loops",
"python-3.x"
] |
Python Loop: List Index Out of Range | 37,619,848 | <p>Given the following list:</p>
<pre><code>a=[0,1,2,3]
</code></pre>
<p>I'd like to create a new list, b, which consists of elements for which the current and next value of a are summed. It will contain 1 less element than a.</p>
<p>Like this:
[1,3,5] </p>
<p>(from 0+1, 1+2, and 2+3)</p>
<p>Here's what I've tried... | 2 | 2016-06-03T17:00:29Z | 37,620,170 | <ol>
<li>In your <code>for</code> loop, you're iterating through the elements of a list <code>a</code>. But in the body of the loop, you're using those items to index that list, when you actually want indexes.<br>
Imagine if the list <code>a</code> would contain 5 items, a number 100 would be among them and the for loo... | 3 | 2016-06-03T17:19:28Z | [
"python",
"list",
"loops",
"python-3.x"
] |
How to automatically scroll down in a Kivy ScrollView? | 37,619,893 | <p>I add widgets to a <code>GridLayout</code> in a <code>ScrollView</code>, so its content expands dynamically.<br>
By default, without user scrolling, the view stays at the top, no matter how many more widgets do you add. If the user scrolls, the view attach to this point, but it seems a little annoying for me to have... | 0 | 2016-06-03T17:02:32Z | 37,623,563 | <p>You can use <a href="https://kivy.org/docs/api-kivy.uix.scrollview.html#kivy.uix.scrollview.ScrollView.scroll_to" rel="nofollow">scroll_to</a> method after adding a new content.</p>
<pre><code>class TestApp(App):
def msg_in(self, btn):
msg = Message()
msg.size_hint = [None, None]
self.ms... | 1 | 2016-06-03T21:18:24Z | [
"python",
"python-3.x",
"kivy"
] |
Python How do i add/remove items in a RPG Inventory system | 37,619,930 | <p>I know how to make a simple inventory, but how do I add and remove items?
Here is my inventory:<code>inventory = ["Sword", "Shield", "Helmet", "Gloves"]</code>
I can print the inventory: <code>print inventory</code>
I use Python 2.7.10
I tried this but doesn't work: <code>inventory.add("Gun")</code></p>
| -2 | 2016-06-03T17:05:22Z | 37,620,024 | <p>Use <code>append()</code> to append to a list</p>
| 0 | 2016-06-03T17:10:09Z | [
"python"
] |
Python How do i add/remove items in a RPG Inventory system | 37,619,930 | <p>I know how to make a simple inventory, but how do I add and remove items?
Here is my inventory:<code>inventory = ["Sword", "Shield", "Helmet", "Gloves"]</code>
I can print the inventory: <code>print inventory</code>
I use Python 2.7.10
I tried this but doesn't work: <code>inventory.add("Gun")</code></p>
| -2 | 2016-06-03T17:05:22Z | 37,620,030 | <p>"inventory" is a list</p>
<p>The function for adding an item to a list is "append"</p>
<pre><code>inventory.append("Gun")
</code></pre>
<p>would do what you want.</p>
| 0 | 2016-06-03T17:10:30Z | [
"python"
] |
Python How do i add/remove items in a RPG Inventory system | 37,619,930 | <p>I know how to make a simple inventory, but how do I add and remove items?
Here is my inventory:<code>inventory = ["Sword", "Shield", "Helmet", "Gloves"]</code>
I can print the inventory: <code>print inventory</code>
I use Python 2.7.10
I tried this but doesn't work: <code>inventory.add("Gun")</code></p>
| -2 | 2016-06-03T17:05:22Z | 37,620,044 | <p>To add an item to an array use : <code>inventory.append("item")</code></p>
<p>To remove an item from an array use : <code>inventory.remove("item")</code></p>
| 0 | 2016-06-03T17:11:31Z | [
"python"
] |
Drawing points with with median lines in seaborn using stripplot | 37,619,952 | <p>I have the following plot in seaborn:</p>
<pre><code>df = pandas.DataFrame({"sample": ["X", "X", "X", "Y", "Y", "Y"],
"value": [0.2, 0.3, 0.4, 0.7, 0.75, 0.8],
"rep": ["a", "b", "c", "a", "b", "c"]})
plt.figure()
ax = sns.stripplot(x="sample", y="value", edgecolor="none... | 0 | 2016-06-03T17:06:30Z | 37,624,166 | <p>You may plot lines by using matplolib. Pandas may calculate medians value for your dataset. I use seaborn 0.7.0 in this example:</p>
<pre><code>from pandas import DataFrame
import matplotlib.pyplot as plt
import seaborn as sns
df = DataFrame({"sample": ["X", "X", "X", "Y", "Y", "Y"],
"value"... | 1 | 2016-06-03T22:09:07Z | [
"python",
"matplotlib",
"seaborn"
] |
Drawing points with with median lines in seaborn using stripplot | 37,619,952 | <p>I have the following plot in seaborn:</p>
<pre><code>df = pandas.DataFrame({"sample": ["X", "X", "X", "Y", "Y", "Y"],
"value": [0.2, 0.3, 0.4, 0.7, 0.75, 0.8],
"rep": ["a", "b", "c", "a", "b", "c"]})
plt.figure()
ax = sns.stripplot(x="sample", y="value", edgecolor="none... | 0 | 2016-06-03T17:06:30Z | 38,989,997 | <p>We can limit the width of each median line to its respective column by looping through the Axes ticks and ticklabels after generating the stripplot. This also enables the code to operate independent of the number of samples (columns) to be plotted.</p>
<pre>
<code>
import pandas as pd
import seaborn as sns
... | 0 | 2016-08-17T06:55:54Z | [
"python",
"matplotlib",
"seaborn"
] |
Read changes directly from an XML object using Python (lxml) | 37,619,973 | <p>I have an XML file. I <em>load it as an XML object like</em> <code>xmlDoc = etree.parse(filePath)</code>. Then I add some same-named nodes (tag is "object") using <code>append</code>. Then if I save this xmlDoc using <code>xmlDoc.write(savingPath)</code> and I open the saved file, everything is fine and I can see th... | 0 | 2016-06-03T17:07:29Z | 37,621,543 | <p>You have not shown how you create your initial <code>ElementTree</code>. The one created this way works:</p>
<pre><code>#!/usr/bin/env python
from lxml import etree
fname = 'b.xml'
objects = etree.Element("objects")
xmlDoc = etree.ElementTree(objects)
objects.append(etree.Element("object"))
objects.append(etree.... | 0 | 2016-06-03T18:52:19Z | [
"python",
"xml",
"python-2.7",
"xml-parsing",
"lxml"
] |
How Do You Make Python Turtle Stop Moving? | 37,619,994 | <p>I've tried to do <code>turtle.speed(0)</code>, and I've tried <code>turtle.goto(turtle.xcor(), turtle.ycor())</code> nothing is seeming to work.</p>
<p>This Is The Code:</p>
<pre><code>import turtle
def stopMovingTurtle():
## Here I Need To Stop The Turtle ##
turtle.listen()
turtle.onkey(stopMovingTurtle, 'R... | 0 | 2016-06-03T17:08:31Z | 37,620,542 | <p>The problem here isn't the order of <code>turtle.listen()</code> vs. <code>turtle.onkey()</code>, it's that the key event isn't being processed until the current operation completes. You can improve this by segmenting your long <code>turtle.goto(-200, 0)</code> motion into smaller motions, each of which allows a ch... | 1 | 2016-06-03T17:44:45Z | [
"python",
"turtle-graphics"
] |
Python os.system timeout with strings | 37,620,042 | <p>I'm unable to execute the following line:</p>
<pre><code>os.system("timeout 1s bash -c \"ffmpeg -i \""+path+\"+" | <some_<other_cmd>\"")
</code></pre>
<p>So the purpose of this command is to set a timeout for the whole command, i.e. pipelining some ffmpeg information from a path.</p>
<p>The problem is be... | 0 | 2016-06-03T17:11:13Z | 37,620,773 | <p>Triple sinqle quotes can do the trick (so that you do not have to escape doublequotes):</p>
<pre><code>os.system('''timeout 1s bash -c "ffmpeg -i "+path+"+" | cat''')
</code></pre>
<p>But in general.. Why not use <code>subprocess.call</code> that has saner syntax?</p>
| 0 | 2016-06-03T17:59:49Z | [
"python",
"linux",
"bash"
] |
Error message when trying to import installed python package | 37,620,171 | <p>I have python2.7 and python 2.6 installed in my VM and I pip install some libraries such as:</p>
<pre><code>sudo pip install gsconfig
</code></pre>
<p>The installation is successful and I can see that the package is installed by:</p>
<pre><code>pip list
</code></pre>
<p>My default system's python is 2.6. In the ... | 0 | 2016-06-03T17:19:32Z | 37,620,433 | <p>It looks like the package name is not <code>gsconfig</code>, but is something else.</p>
<p>Looking at the <a href="http://boundlessgeo.github.io/gsconfig/model.html" rel="nofollow">documentation</a>, I think it's <code>geoserver</code>.</p>
| 1 | 2016-06-03T17:36:10Z | [
"python",
"import",
"pip"
] |
Seaborn Stripplot with Min, Mid, Max lines | 37,620,190 | <p>I'm trying to create <code>strip plot</code> from seaborn and adding lines indicating the Min, Mid, and Max that I set. I would like to set the Min line at the 500 mark, the mid at 2000 and the max line at 3500. </p>
<p>My goal is to display which points are within the min and max and which ones are outside of the ... | 1 | 2016-06-03T17:20:37Z | 37,623,640 | <p>For your purpose you have to use standard matplotlib:</p>
<pre><code>import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
import seaborn as sns
data = DataFrame([1000,2000,3000,4000, 8000], columns=["Amount"], index=["EE1","EE2","EE3","EE4", "EE5"])
sns.stripplot(data=data, size=6, jitt... | 0 | 2016-06-03T21:23:14Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Python - Obtain a list of parenthetical tuples from string | 37,620,210 | <p>I have a string such as:
<code>(1,2,3,'4.1),(4.2)',5,6,7),(8,9,10)</code>. The output I need to obtain is the list:
<code>[ ((1,2,3,'4.1),(4.2)',5,6,7), (8,9,10) ]</code>
I believe I need a regex in order to perform this task. How can I do so?</p>
<p>Thank you.</p>
| 1 | 2016-06-03T17:21:53Z | 37,620,479 | <p>You might be able to evaluate the string directly (after putting it in a list).</p>
<pre><code>from ast import literal_eval
string = "(1,2,3,'4.1),(4.2)',5,6,7),(8,9,10)"
literal_eval('[{}]'.format(string))
# [(1, 2, 3, '4.1),(4.2)', 5, 6, 7), (8, 9, 10)]
</code></pre>
| 2 | 2016-06-03T17:39:52Z | [
"python",
"regex",
"python-2.7"
] |
Django upgrade from 1.2.5 to 1.3 error in admin | 37,620,215 | <p>I am attempting to upgrade a website running django 1.2.5 to 1.3
The only error I have encountered so far is in the admin part of the site:</p>
<pre><code>__init__() got an unexpected keyword argument 'field_path'
</code></pre>
<p>which I think is from somewhere in this code:</p>
<pre><code>class EventAdmin(admin... | 0 | 2016-06-03T17:22:14Z | 37,629,389 | <p>It's hard to tell exactly what is wrong here. </p>
<p>The error is triggered in a file called <code>filterspecs.py</code>. I suspect that it might be because you have a list filter <code>is_series</code> that is not included in the <code>self.list_display</code>. </p>
<p>Try to comment out the <code>list_filter</c... | 0 | 2016-06-04T11:00:52Z | [
"python",
"django",
"django-admin",
"upgrade",
"django-1.3"
] |
Django upgrade from 1.2.5 to 1.3 error in admin | 37,620,215 | <p>I am attempting to upgrade a website running django 1.2.5 to 1.3
The only error I have encountered so far is in the admin part of the site:</p>
<pre><code>__init__() got an unexpected keyword argument 'field_path'
</code></pre>
<p>which I think is from somewhere in this code:</p>
<pre><code>class EventAdmin(admin... | 0 | 2016-06-03T17:22:14Z | 37,633,213 | <p>It was actually the <code>start_date</code> field that was causing the problem and I tracked this down to a filter class in the models.py file, with a bit of help from this post:</p>
<p><a href="http://stackoverflow.com/questions/6740398/django-admin-custom-list-filter">django admin custom list_filter</a></p>
<p>t... | 1 | 2016-06-04T17:40:53Z | [
"python",
"django",
"django-admin",
"upgrade",
"django-1.3"
] |
How to remove the least frequent element from a Counter in Python the fastest way? | 37,620,222 | <p>I'd like to implement a Counter which drops the least frequent element when the counter's size going beyond some threshold. For that I need to remove the least frequent element.</p>
<p>What is the fastest way to do that in Python?</p>
<p>I know <code>counter.most_common()[-1]</code>, but it creates a whole list an... | 3 | 2016-06-03T17:22:28Z | 37,620,428 | <p>You may implement <code>least_common</code> by borrowing implementation of <code>most_common</code> and performing necessary changes.</p>
<p>Refer to <a href="https://hg.python.org/cpython/file/2.7/Lib/collections.py" rel="nofollow"><code>collections</code> source in Py2.7</a>:</p>
<pre><code>def most_common(self,... | 1 | 2016-06-03T17:35:57Z | [
"python",
"data-structures"
] |
How to remove the least frequent element from a Counter in Python the fastest way? | 37,620,222 | <p>I'd like to implement a Counter which drops the least frequent element when the counter's size going beyond some threshold. For that I need to remove the least frequent element.</p>
<p>What is the fastest way to do that in Python?</p>
<p>I know <code>counter.most_common()[-1]</code>, but it creates a whole list an... | 3 | 2016-06-03T17:22:28Z | 37,621,497 | <p>Since your stated goal is to remove items in the counter below a threshold, just reverse the counter (so the values becomes a list of keys with that value) and then remove the keys in the counter below the threshold.</p>
<p>Example:</p>
<pre><code>>>> c=Counter("aaaabccadddefeghizkdxxx")
>>> c
Co... | 0 | 2016-06-03T18:48:52Z | [
"python",
"data-structures"
] |
How to remove the least frequent element from a Counter in Python the fastest way? | 37,620,222 | <p>I'd like to implement a Counter which drops the least frequent element when the counter's size going beyond some threshold. For that I need to remove the least frequent element.</p>
<p>What is the fastest way to do that in Python?</p>
<p>I know <code>counter.most_common()[-1]</code>, but it creates a whole list an... | 3 | 2016-06-03T17:22:28Z | 37,621,647 | <p>If you only want to get the least common value, then the most efficient way to handle this is to simply get the minimum value from the counter (dictionary).</p>
<p>Since you can only say whether a value is the lowest, you actually need to look at all items, so a time complexity of O(n) is really the lowest we can g... | 0 | 2016-06-03T18:59:21Z | [
"python",
"data-structures"
] |
Displaying in Tkinter/python | 37,620,329 | <p>I'm trying to display the distance between my two circles in the Tkinter window. I found an algorithm, but I'm having problem with displaying it. Here's my program so far:</p>
<pre><code>from Tkinter import *
from math import *
def planetM(gd, hb):
global x1, y1
x1, y1 = x1+gd, y1+hb
can1.coords(oval1,... | 0 | 2016-06-03T17:28:35Z | 37,622,383 | <p>Use <code>after</code> method. Make it refresh the label every 0.1 seconds.</p>
<pre><code>win1.after(100, distance) # Number 100 represents time in milliseconds to wait before function distance is called
# This needs to be placed BEFORE mainloop.
</code></pre>
<p>Then make function... | 1 | 2016-06-03T19:53:54Z | [
"python",
"tkinter",
"label"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.