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 |
|---|---|---|---|---|---|---|---|---|---|
How do I get the dot product but without the summation | 38,981,194 | <p>consider array's <code>a</code> and <code>b</code></p>
<pre><code>a = np.array([
[-1, 1, 5],
[-2, 3, 0]
])
b = np.array([
[1, 1, 0],
[0, 2, 3],
])
</code></pre>
<p>Looking at</p>
<pre><code>d = a.T.dot(b)
d
array([[-1, -5, -6],
[ 1, 7, 9],
[ 5, 5, 0]])
</... | 4 | 2016-08-16T17:38:29Z | 38,981,653 | <pre><code>for r in a.T:
print(np.multiply(r,b.T))
[[-1 0]
[-1 -4]
[ 0 -6]]
[[1 0]
[1 6]
[0 9]]
[[5 0]
[5 0]
[0 0]]
</code></pre>
| 0 | 2016-08-16T18:06:11Z | [
"python",
"numpy"
] |
How do I get the dot product but without the summation | 38,981,194 | <p>consider array's <code>a</code> and <code>b</code></p>
<pre><code>a = np.array([
[-1, 1, 5],
[-2, 3, 0]
])
b = np.array([
[1, 1, 0],
[0, 2, 3],
])
</code></pre>
<p>Looking at</p>
<pre><code>d = a.T.dot(b)
d
array([[-1, -5, -6],
[ 1, 7, 9],
[ 5, 5, 0]])
</... | 4 | 2016-08-16T17:38:29Z | 38,982,932 | <p>Most efficient one would be with <code>broadcasting</code> as shown in <a href="http://stackoverflow.com/a/38981589/3293881"><code>@Warren Weckesser's post</code></a> as we are basically dealing with element-wise multiplication without any <code>sum-reduction</code>. </p>
<p>An alternative one with <a href="http://... | 2 | 2016-08-16T19:24:30Z | [
"python",
"numpy"
] |
Color 3D Surface Based on Categories that passes through scatter points | 38,981,257 | <p>I have the data in the following format: </p>
<h2>X,Y,Z,Category</h2>
<p>I used plotly to generate a scatter plot and then a fit a Curve through the scatter points using the following code.</p>
<pre><code>from scipy.interpolate import griddata
import numpy as np
import matplotlib.pyplot as plt
from matplotlib imp... | 0 | 2016-08-16T17:42:11Z | 38,981,929 | <p>Just as <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html" rel="nofollow"><code>griddata</code></a> can be used to interpolate the 1D <code>z</code> array to a 2D grid, you can use <code>griddata</code> to interpolate a 1D <code>color</code> array to the same 2D grid:</p>
... | 1 | 2016-08-16T18:21:42Z | [
"python",
"matlab",
"matplotlib",
"3d",
"plotly"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 38,981,316 | <p>When there are 1+ items in the list (if not, just use the first element):</p>
<pre><code>>>> "{} and {}".format(", ".join(listy[:-1]), listy[-1])
'item1, item2, item3, item4, item5, and item6'
</code></pre>
<p>Edit: If you need an <em>Oxford comma</em> (didn't know it even existed!) -- just use: <code>",... | 9 | 2016-08-16T17:46:31Z | [
"python",
"python-2.7"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 38,981,330 | <p>In python, many functions, that work with lists also works with iterators (like <code>join</code>, <code>sum</code>, <code>list</code>). To get the last item of a iterable is not that easy, because you cannot get the length, because it may be unknown in advance.</p>
<pre><code>def coma_iter(iterable):
sep = ''
... | 1 | 2016-08-16T17:47:34Z | [
"python",
"python-2.7"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 38,981,356 | <pre><code>def coma(lst):
return '{} and {}'.format(', '.join(lst[:-1]), lst[-1])
</code></pre>
| 3 | 2016-08-16T17:49:15Z | [
"python",
"python-2.7"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 38,981,360 | <pre><code>def oxford_comma_join(l):
if not l:
return ""
elif len(l) == 1:
return l[0]
else:
return ', '.join(l[:-1]) + ", and " + l[-1]
print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>item1,... | 3 | 2016-08-16T17:49:40Z | [
"python",
"python-2.7"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 38,982,008 | <p>It's generally bad practice to use <code>+</code> when combining strings, as it is generally slow. Instead, you can use</p>
<pre><code>def comma(items):
return "{}, and {}".format(", ".join(items[:-1]), items[-1])
</code></pre>
<p>You should note, however, that this will break if you only have one item:</p>
... | 1 | 2016-08-16T18:26:29Z | [
"python",
"python-2.7"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 38,982,233 | <p>Might as well round out the solutions with a recursive example.</p>
<pre><code>>>> listy = ['item1', 'item2','item3','item4','item5', 'item6']
>>> def foo(a):
if len(a) == 1:
return ', and ' + a[0]
return a[0] + ', ' + foo(a[1:])
>>> foo(listy)
'item1, item2, item3, item4... | 1 | 2016-08-16T18:40:24Z | [
"python",
"python-2.7"
] |
Converting a list into comma-separated string with "and" before the last item - Python 2.7 | 38,981,302 | <p>I have created this function to parse the list:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
def coma(abc):
for i in abc[0:-1]:
print i+',',
print "and " + abc[-1] + '.'
coma(listy)
#item1, item2, item3, item4, item5, and item6.
</code></pre>
<p>Is there a neater w... | 8 | 2016-08-16T17:44:46Z | 39,068,437 | <p>One more different way to do:</p>
<pre><code>listy = ['item1', 'item2','item3','item4','item5', 'item6']
</code></pre>
<p><strong>first way</strong>:</p>
<pre><code>print(', '.join('and, ' + listy[item] if item == len(listy)-1 else listy[item]
for item in xrange(len(listy))))
output >>> item1, item2, it... | 2 | 2016-08-21T20:12:34Z | [
"python",
"python-2.7"
] |
Alter existing text in etree Element object | 38,981,384 | <p>I have the following XML:</p>
<pre><code><root>
<element>
<subelement1>
subelement1 text
</subelement1>
<subelement2>
subelement2 text
</subelement2>
</element>
</root>
</code></pre>
<p>It's my goal to p... | -1 | 2016-08-16T17:50:50Z | 38,981,744 | <p>Simply assign to the <code>text</code> attribute of the relevant element:</p>
<pre><code>el = doc.find('.//subelement2')
el.text += ' + my new string of text'
</code></pre>
| 1 | 2016-08-16T18:10:58Z | [
"python",
"elementtree",
"xml.etree"
] |
How to prevent user registration form in Django from returning password field can not be null | 38,981,503 | <p>I have created a user registration form in Django but every time I test it, the user is not being saved to the database because when the password is entered it raises "this field can not be null. I do not understand why this is happening since the form was working before, and it follows the same procedures as other ... | 0 | 2016-08-16T17:57:51Z | 38,981,919 | <p>If you clean a django form field (using <code>def clean_myfield</code>) you need to return that field</p>
<pre><code>def clean_password(self):
password = self.cleaned_data.get('password')
if len(password) <= 8:
raise forms.ValidationError("Password must be longer than 8 characters")
else:
... | 2 | 2016-08-16T18:21:19Z | [
"python",
"django",
"forms"
] |
How to correctly override Django manage.py's command? | 38,981,700 | <p>I need to override <code>createsuperuser.py</code>'s <code>handle</code> method in Django <code>Command</code> class.</p>
<p>I created myapp\management\commands\createsuperuser.py:</p>
<pre><code>import getpass
import sys
import django.contrib.auth.management.commands.createsuperuser as makesuperuser
from django... | 0 | 2016-08-16T18:08:36Z | 38,982,236 | <p>Put your application name on top in the <code>INSTALLED_APPS</code> list. </p>
| 1 | 2016-08-16T18:40:28Z | [
"python",
"django"
] |
Pyinstaller won't open the external .txt files of the python script | 38,981,765 | <p>EDIT</p>
<p>This is my code:</p>
<pre><code>import pyperclip
text_file = open("dewey.txt", "rt") #Open the list containing the values
text = text_file.read().split('\n')
text_file.close()
num = []
with open ('dewey num.txt', 'rt') as in_file: #Open the list containing the keys
f... | 0 | 2016-08-16T18:12:24Z | 39,013,958 | <p>In the end I managed to import all the dependencies by using the command 'pyi-makespec' which then required an additional step to make the actual exe file. The documentation for pyinstaller is really extensive and accurate. Thanks @Repiklis for your inputs</p>
| 0 | 2016-08-18T08:59:51Z | [
"python",
"python-3.x",
"compilation",
"user-input",
"pyinstaller"
] |
Use Class in a loop- python | 38,981,814 | <p>I'm new to using Classes in Python, and could use some guidance on what resources to consult/how to use a class in a loop.</p>
<p>Sample data:</p>
<pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df2 = pd.DataFrame(np.random.randint(0, 1, size=(100, 1)), columns=list('E'))... | 0 | 2016-08-16T18:15:07Z | 38,981,970 | <p>You could just enumerate the files like so</p>
<pre><code>files = [self.model_file, self.model_file2, self.model_file3]
values = [1 ,5 ,7]
for n in range(len(value)):
pickle_model(self.model, files[n])
</code></pre>
<p>Does this answer the question?</p>
| 0 | 2016-08-16T18:23:48Z | [
"python",
"class",
"loops"
] |
Use Class in a loop- python | 38,981,814 | <p>I'm new to using Classes in Python, and could use some guidance on what resources to consult/how to use a class in a loop.</p>
<p>Sample data:</p>
<pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df2 = pd.DataFrame(np.random.randint(0, 1, size=(100, 1)), columns=list('E'))... | 0 | 2016-08-16T18:15:07Z | 38,982,181 | <p>An elegant way to do it is to iterate through both lists at the same time using <code>zip</code></p>
<pre><code>def run(self):
self.import_training_data()
for value,model_file in zip([1, 3, 7],[self.model_file, self.model_file2, self.model_file3]):
self.extract_variables(value)
self.train_mo... | 0 | 2016-08-16T18:36:56Z | [
"python",
"class",
"loops"
] |
How do Python distributable modules work with external libs | 38,981,847 | <p>I apologise in advance, as I am rather new to Python programming, but I was curious as to how this system works. My question is: if I write a Python script and make it distributable, but my program imports other external libraries such as numpy or scipy (which is what I am working on currently) how does it all work ... | 0 | 2016-08-16T18:17:10Z | 38,981,959 | <p>The easy way to ensure that dependent modules are installed is through <em>pip -r</em>.</p>
<p>Essentially, make a <em>requirements.txt</em> along with your script for users to install the correct modules and versions. </p>
<p>Inside the text file should look like this:</p>
<pre><code>Flask==0.11.1
</code></pre>
... | 0 | 2016-08-16T18:22:55Z | [
"python",
"numpy",
"makefile",
"import"
] |
How do Python distributable modules work with external libs | 38,981,847 | <p>I apologise in advance, as I am rather new to Python programming, but I was curious as to how this system works. My question is: if I write a Python script and make it distributable, but my program imports other external libraries such as numpy or scipy (which is what I am working on currently) how does it all work ... | 0 | 2016-08-16T18:17:10Z | 38,982,133 | <p><code>numpy</code>, <code>scipy</code> takes a long time to install in a virtualenv. For this reason I would not recommend virtualenv like others have. You could try <code>pyinstaller</code> to create an OS specific executable. Haven't tried it with numpy or scipy myself though.</p>
<p><a href="http://www.pyinst... | 0 | 2016-08-16T18:34:20Z | [
"python",
"numpy",
"makefile",
"import"
] |
Python Pandas : Pivot table : aggfunc concatenate instead of np.size or np.sum | 38,981,885 | <p>I have some entries in dataframe like :</p>
<pre><code>name, age, phonenumber
A,10, Phone1
A,10,Phone2
B,21,PhoneB1
B,21,PhoneB2
C,23,PhoneC
</code></pre>
<p>Here is what I am trying to achieve as result of pivot table:</p>
<pre><code> name, age, phonenumbers, phonenocount
A,10, "Phone1,Phone2" , 2
B,21, ... | 1 | 2016-08-16T18:19:07Z | 38,982,172 | <p>You can use <code>agg</code> function after the <code>groupby</code>:</p>
<pre><code>df.groupby(['name', 'age'])['phonenumber'].agg({'phonecount': pd.Series.nunique, 'phonenumber': lambda x: ','.join(x)})
# phonenumber phonecount
# name age
# A 10 Phone1,Phone2 2
# B 21 P... | 5 | 2016-08-16T18:36:30Z | [
"python",
"pandas",
"pivot-table"
] |
How to map pixels (R, G, B) in a collection of images to a distinct pixel-color-value indices? | 38,981,912 | <p>Lets say one has 600 annotated semantic segmentation mask images, which contain 10 different colors, each representing one entity. These images are in a numpy array of shape (600, 3, 72, 96), where n = 600, 3 = RGB channels, 72 = height, 96 = width. </p>
<p>How to map each RGB-pixel in the numpy array to a color-in... | 1 | 2016-08-16T18:21:07Z | 38,983,726 | <p>Here's a compact vectorized approach without those error checks -</p>
<pre><code>def unique_map_pixels_vectorized(imgs):
N,H,W = len(imgs), imgs.shape[2], imgs.shape[3]
img2D = imgs.transpose(0, 2, 3, 1).reshape(-1,3)
ID = np.ravel_multi_index(img2D.T,img2D.max(0)+1)
_, firstidx, tags = np.unique(ID... | 1 | 2016-08-16T20:17:00Z | [
"python",
"image",
"performance",
"numpy",
"image-processing"
] |
Change matplotlib backend in Python virtualenv | 38,981,915 | <p>I've installed a <code>virtualenv</code> with <a href="https://github.com/yyuu/pyenv-virtualenv" rel="nofollow">pyenv</a> using Python v2.7.12. Inside this virtualenv, I installed <code>matplotlib</code> v1.5.1 via:</p>
<pre><code>pip install matplotlib
</code></pre>
<p>with no issues. The problem is that a simple... | 2 | 2016-08-16T18:21:09Z | 38,988,308 | <p>You can consider changing your backend to <code>TkAgg</code> in the Python 2 virtualenv by running the following:</p>
<pre><code>sudo apt install python-tk # install Python 2 bindings for Tk
pip --no-cache-dir install -U --force-reinstall matplotlib # reinstall matplotlib
</code></pre>
<p>To confirm the backe... | 3 | 2016-08-17T04:48:41Z | [
"python",
"matplotlib",
"plot",
"virtualenv",
"backend"
] |
pandas shift date using values from another column | 38,981,977 | <p>code to make test data:</p>
<pre><code> import pandas as pd
df = pd.DataFrame({'A': pd.date_range(start='1-1-2016',periods=5, freq='M')})
df['B'] = df.A.dt.month
print(df)
</code></pre>
<p>data looks like</p>
<pre><code> B A
0 1 2016-01-31
1 2 2016-02-29
2 3 2016-03-31
3 4 2016-0... | 1 | 2016-08-16T18:24:10Z | 38,982,372 | <p>You can try:</p>
<pre><code>df['C'] = df[['A', 'B']].apply(lambda x: x['A'] - pd.DateOffset(months=x['B']), axis=1)
</code></pre>
| 1 | 2016-08-16T18:48:15Z | [
"python",
"date",
"datetime",
"pandas",
"time-series"
] |
pandas shift date using values from another column | 38,981,977 | <p>code to make test data:</p>
<pre><code> import pandas as pd
df = pd.DataFrame({'A': pd.date_range(start='1-1-2016',periods=5, freq='M')})
df['B'] = df.A.dt.month
print(df)
</code></pre>
<p>data looks like</p>
<pre><code> B A
0 1 2016-01-31
1 2 2016-02-29
2 3 2016-03-31
3 4 2016-0... | 1 | 2016-08-16T18:24:10Z | 38,983,098 | <p>Here is a vectorized way to compose arrays of dates (NumPy <code>datetime64</code>s) out of
date components (such as years, months, days):</p>
<pre><code>import numpy as np
import pandas as pd
def compose_date(years, months=1, days=1, weeks=None, hours=None, minutes=None,
seconds=None, millisecond... | 3 | 2016-08-16T19:36:08Z | [
"python",
"date",
"datetime",
"pandas",
"time-series"
] |
Using argparse or docopt for pdftk replacement | 38,982,002 | <p>I have am writing a program that accepts arguements in the following form.</p>
<pre><code>SYNOPSIS
pdf_form.py <input PDF file | - | PROMPT> [ <operation> <operation arguments> ]
[ output <output filename | - | PROMPT> ] [ flatten ]
Where:
<operation> may be empty, or: [generat... | 1 | 2016-08-16T18:26:15Z | 38,984,485 | <p>One argument could be</p>
<pre><code>parser.add_argument('-o','--output', default='-')
</code></pre>
<p>and later</p>
<pre><code>if args.output in ['PROMPT']:
... input...
</code></pre>
<p>others:</p>
<pre><code>parser.add_argument('--flatten', action='store_true')
parser.add_argument('--fill_form', dest='f... | 0 | 2016-08-16T21:05:42Z | [
"python",
"command-line-arguments",
"argparse",
"docopt"
] |
ImportError: No module named cv2 â WSGI + python + apache | 38,982,107 | <p>I'm trying to run a python app on my apache Amazon EC2 server through WSGI, and I keep getting this error:</p>
<pre><code>[Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] mod_wsgi (pid=28751): Target WSGI script '/var/www/html/lumos/wsgi.py' cannot be loaded as Python module.
[Tue Aug 16 18:22:57 2016] [err... | 0 | 2016-08-16T18:32:16Z | 38,984,977 | <p>Ok so it turns out, that according to <a href="https://code.google.com/archive/p/modwsgi/wikis/ConfigurationDirectives.wiki#WSGIPythonPath" rel="nofollow">the docs</a>, you cannot use WSGIPythonPath when using daemon mode. </p>
<p>So the python path I had specified wasn't even doing anything. To fix, I used the 'py... | 0 | 2016-08-16T21:46:08Z | [
"python",
"apache",
"opencv",
"amazon-web-services",
"amazon-ec2"
] |
ImportError: No module named cv2 â WSGI + python + apache | 38,982,107 | <p>I'm trying to run a python app on my apache Amazon EC2 server through WSGI, and I keep getting this error:</p>
<pre><code>[Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] mod_wsgi (pid=28751): Target WSGI script '/var/www/html/lumos/wsgi.py' cannot be loaded as Python module.
[Tue Aug 16 18:22:57 2016] [err... | 0 | 2016-08-16T18:32:16Z | 38,986,073 | <p>Your setup is broken because mod_wsgi is compiled for Python 2.6 and not specifically for the Python 2.7 installation you want to use. You should not force the <code>site-packages</code> and <code>dict-packages</code> from your Python 2.7 installation into the module search path for what is a Python 2.6 environment.... | 0 | 2016-08-16T23:39:13Z | [
"python",
"apache",
"opencv",
"amazon-web-services",
"amazon-ec2"
] |
Python Reportlab combine paragraph | 38,982,150 | <p>I hope you can help me trying to combine a paragraph, my style is called "cursiva" and works perfectly also I have other's but it's the same if I change cursiva to other one. the issue is that If I use this coude o get this.</p>
<p><a href="http://i.stack.imgur.com/OBlSY.png" rel="nofollow"><img src="http://i.stack... | 0 | 2016-08-16T18:35:28Z | 39,016,790 | <p>The question you are asking is actually caused by a workaround for a different problem, namely that you don't know how to register font families in Reportlab. Because that is what is needed to make <code><i></code> and <code><b></code> work.</p>
<p>So you probably already managed to add a custom font, s... | 0 | 2016-08-18T11:15:20Z | [
"python",
"python-2.7",
"reportlab"
] |
Hooking Django App to subdirectory using mod_wsgi and apache on Centos 5 | 38,982,218 | <h2>Background:</h2>
<p>I am working on bringing a Django App into production for my office. So far the app has been developed and works and all that needs to be done is to deploy said app. A task that is unfortunately more cumbersome than developing the app itself. I am working on a Centos 5.11 server with Apache 2.2... | 0 | 2016-08-16T18:39:12Z | 39,029,721 | <p>After searching around I discovered that the issues were in the django.wsgi file that provided an unnecessary extra layer. I changed my httpd.conf file to the code below, further specifying the path for my virtualenv and linking to the wsgi.py file.</p>
<pre><code>LoadModule wsgi_module extramodules/mod_wsgi.so
WS... | 0 | 2016-08-19T01:15:56Z | [
"python",
"django",
"apache",
"wsgi"
] |
Python/Tkinter - Identify object on click | 38,982,313 | <p>I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?</p>
<p>Here is my code:</p>
<pre><code>import tkinter as... | 1 | 2016-08-16T18:45:07Z | 38,982,460 | <p>What about this solution:</p>
<pre><code>import tkinter as tk
def onclick(event):
global rectangles
item = cv.find_closest(event.x, event.y)
if item[0] in rectangles:
current_color = cv.itemcget(item, 'fill')
if current_color == 'black':
cv.itemconfig(item, fill='white')
... | 1 | 2016-08-16T18:53:51Z | [
"python",
"canvas",
"tkinter",
"onclick"
] |
Python/Tkinter - Identify object on click | 38,982,313 | <p>I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?</p>
<p>Here is my code:</p>
<pre><code>import tkinter as... | 1 | 2016-08-16T18:45:07Z | 38,982,513 | <p>Based on <a href="http://stackoverflow.com/questions/2786877/how-do-i-attach-event-bindings-to-items-on-a-canvas-using-tkinter">this accepted answer</a> you need to tag_bind your rectangles. Also, you should be assigning IDs to each object you create. If you need to do this repeatedly, you can wrap the process in ... | 0 | 2016-08-16T18:57:36Z | [
"python",
"canvas",
"tkinter",
"onclick"
] |
Python/Tkinter - Identify object on click | 38,982,313 | <p>I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?</p>
<p>Here is my code:</p>
<pre><code>import tkinter as... | 1 | 2016-08-16T18:45:07Z | 38,982,754 | <p>Here are three common solutions to this problem:</p>
<h2>Using the item type</h2>
<p>You can ask the canvas for the type of the object:</p>
<pre><code>item_type = cv.type(item)
if item_type == "rectangle":
# this item is a rectangle
else:
# this item is NOT a rectangle
</code></pre>
<h2>Using tags</h2>
... | 2 | 2016-08-16T19:12:36Z | [
"python",
"canvas",
"tkinter",
"onclick"
] |
Python/Tkinter - Identify object on click | 38,982,313 | <p>I am trying to create a program that changes the object colour on click from white to black or from white to black depending of the previous colour. I would want the program change the colour only if the object is a rectangle. How can I make the this happen?</p>
<p>Here is my code:</p>
<pre><code>import tkinter as... | 1 | 2016-08-16T18:45:07Z | 38,982,757 | <p>The solution of BPL is fine. Here is another solution that doesn't require any global variable. There's a system of tags in Tkinter which could be compared with "class" from HTML/CSS. It enables us to associate a list of tags to a graphic object. See <a href="http://effbot.org/tkinterbook/canvas.htm#item-specifiers"... | 1 | 2016-08-16T19:12:43Z | [
"python",
"canvas",
"tkinter",
"onclick"
] |
"pygame.error: video system not initialized" | 38,982,337 | <p>Does anyone know why this error keeps coming up? I'm not sure what's wrong with the code. I've copied this from a video just to test mouse tracking and yet my version isn't working even though the two sets of code are identical (I believe). Here is the video I took the code from: <a href="https://www.youtube.com/wat... | -1 | 2016-08-16T18:46:37Z | 38,982,448 | <p>My guess would be a missing dependency or library mismatch.
How did you install pygame, and were there any errors.
I recommend you use pip or your distribution's package manager.
Also, you should make sure that any non-python APIs and modules that you might need are all installed.</p>
| 0 | 2016-08-16T18:53:11Z | [
"python",
"python-3.x",
"pygame",
"mouseevent"
] |
"pygame.error: video system not initialized" | 38,982,337 | <p>Does anyone know why this error keeps coming up? I'm not sure what's wrong with the code. I've copied this from a video just to test mouse tracking and yet my version isn't working even though the two sets of code are identical (I believe). Here is the video I took the code from: <a href="https://www.youtube.com/wat... | -1 | 2016-08-16T18:46:37Z | 38,982,492 | <p>The problem with your code is that your initialization method <code>__init__</code>, is missing a underscore. Since your class is never being initialized, your never creating a Pygame screen. Thus the error</p>
<p>Change this line: <code>def __init(self):</code>, To this: <code>def __init__(self):</code></p>
| 0 | 2016-08-16T18:56:26Z | [
"python",
"python-3.x",
"pygame",
"mouseevent"
] |
How to OR multiple filter calls in python | 38,982,419 | <p>I have the following code in Python that takes in several filters. Then I have a loop that calls .filter on each of them. However when you call multiple filters these are ANDed. How can I change it so that the multiple calls to filter are ORed. The problem is in the "else" part of my code.</p>
<pre><code>for filter... | 1 | 2016-08-16T18:51:02Z | 38,982,526 | <p>Just build up a list of filters and <code>or_</code> them at the end:</p>
<pre><code>exprs = []
for filter_ in filters:
exprs.append(field.ilike(...))
organizations_products = organizations_products.filter(or_(*exprs))
</code></pre>
<p>By the way, implementing search like this is a terrible way to go performan... | 0 | 2016-08-16T18:58:17Z | [
"python",
"sqlalchemy"
] |
How to OR multiple filter calls in python | 38,982,419 | <p>I have the following code in Python that takes in several filters. Then I have a loop that calls .filter on each of them. However when you call multiple filters these are ANDed. How can I change it so that the multiple calls to filter are ORed. The problem is in the "else" part of my code.</p>
<pre><code>for filter... | 1 | 2016-08-16T18:51:02Z | 38,983,732 | <p>There are two parts to the solution. First, we must construct the <code>from</code> clause, and then the <code>where</code> clause.</p>
<pre><code>def get_joined_stmt(filters, stmt):
if 'type' in filters.keys():
stmt = stmt.join(ProductType)
if 'category' in filters.keys():
stmt = stmt.join(... | 1 | 2016-08-16T20:17:27Z | [
"python",
"sqlalchemy"
] |
Python AIML error | 38,982,462 | <p>I'm starting a project with Python which uses AIML, when I run the script It gives me a 'Not match found' error. This is the Python code:</p>
<pre><code>import aiml
kernel = aiml.Kernel()
kernel.learn("bot.aiml")
while True:
print kernel.respond(raw_input("\n>>"))
</code></pre>
<p>Just a simple AIML kern... | 0 | 2016-08-16T18:53:52Z | 39,464,333 | <p>I have a better python script if you are interested</p>
<pre><code>import aiml
import sys <br>
brainLoaded = False
forceReload = False
while not brainLoaded:
if forceReload or (len(sys.argv) >= 2 and sys.argv[1] == "reload"):
kern.bootstrap(learnFiles="Database.xml", commands="load aiml b")
... | 0 | 2016-09-13T07:23:43Z | [
"python",
"aiml"
] |
Python AIML error | 38,982,462 | <p>I'm starting a project with Python which uses AIML, when I run the script It gives me a 'Not match found' error. This is the Python code:</p>
<pre><code>import aiml
kernel = aiml.Kernel()
kernel.learn("bot.aiml")
while True:
print kernel.respond(raw_input("\n>>"))
</code></pre>
<p>Just a simple AIML kern... | 0 | 2016-08-16T18:53:52Z | 39,709,368 | <p>"No match found for input" warning occurs because because "bot.aiml" does have a matching output for your input. Try to include a default response like the following:</p>
<pre><code><category>
<pattern>*</pattern>
<template>
Sorry. I didn't quite get that.
</template&g... | 0 | 2016-09-26T17:56:27Z | [
"python",
"aiml"
] |
Does calling Python Scikit classifier `.fit` method repeatedly effect anything? | 38,982,494 | <p>I'm using scikit SVM and I'd like to test an SVM with both the <code>sample_weights</code> customized and passed to the classifier and again with the usual implementation where <code>sample_weights</code> is the default value of <code>1</code> for each sample. (<code>sample_weight</code> allows the user to give some... | 0 | 2016-08-16T18:56:28Z | 38,984,992 | <p>This simply does not matter for SVM, as it always converges to global minima. It does not "start around good solution", SVM is not a neural network - it does not need a good initialization. In other words - you can call fit how many times you want and you do not have to reinitialize the classifier. In case of sklear... | 1 | 2016-08-16T21:46:46Z | [
"python",
"machine-learning",
"scikit-learn",
"svm",
"libsvm"
] |
argparse: make one argument default when no arguments are called | 38,982,570 | <p>What's the best way to set a group argument as the default when no arguments are called.</p>
<pre><code>parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("--a", action="store_true") #call when no arguments are provided
group.add_argument("--b", action="store_true")
... | 1 | 2016-08-16T19:01:17Z | 38,982,646 | <p>For the way you are trying to use a mutually exclusive group here, a simple option with three choices and a default may be a more pythonic CLI to consider. </p>
<p>i.e., you may structure this differently:</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument("--thing", choices=['a', 'b', 'c'], de... | 0 | 2016-08-16T19:05:56Z | [
"python",
"default",
"argparse"
] |
argparse: make one argument default when no arguments are called | 38,982,570 | <p>What's the best way to set a group argument as the default when no arguments are called.</p>
<pre><code>parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("--a", action="store_true") #call when no arguments are provided
group.add_argument("--b", action="store_true")
... | 1 | 2016-08-16T19:01:17Z | 38,983,370 | <p>I would just add a simple test after parsing</p>
<pre><code>if not any([args.a, args.b, args.c]):
args.a=True
</code></pre>
<p>This is simpler than any attempt to make <code>parse_args</code> to do this. The parser will parse all arguments independently - and in any order. So you really can't tell until the p... | 1 | 2016-08-16T19:53:58Z | [
"python",
"default",
"argparse"
] |
Custom fields in Django models | 38,982,578 | <p>Is it possible to have custom fields (non-model fields) in a django model. For instance, I have a the following model: </p>
<pre><code>class Patient(models.Model):
firstName = models.CharField(max_length=100, blank=True, default='')
lastName = models.CharField(max_length=100, blank=True, default='')
occ... | 0 | 2016-08-16T19:01:58Z | 38,984,094 | <p>Why not use the editable attribute of the field?
<a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#editable" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#editable</a></p>
<pre><code>class Patient(models.Model):
firstName = models.CharField(max_length=100, blank=True,... | 0 | 2016-08-16T20:40:36Z | [
"python",
"django"
] |
regex to match any character or none? | 38,982,637 | <p>I have the two following peices of strings;</p>
<pre><code>line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore
line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore
</code></pre>
<p>I'm trying to grab these two parts;</p>
<pre><code>"GET /file/ HTTP/1.1" 302
"" 400
</code... | 1 | 2016-08-16T19:05:24Z | 38,982,803 | <p>Use <code>.*?</code> instead of <code>.+?</code>.</p>
<p><code>+</code> means "1 or more"</p>
<p><code>*</code> means "0 or more"</p>
<p><a href="https://regex101.com/r/gU7oT6/2" rel="nofollow">Regex101 Demo</a></p>
<p>If you want a more efficient regex, use a negated character class <code>[^"]</code> instead of... | 2 | 2016-08-16T19:15:48Z | [
"python",
"regex"
] |
regex to match any character or none? | 38,982,637 | <p>I have the two following peices of strings;</p>
<pre><code>line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore
line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore
</code></pre>
<p>I'm trying to grab these two parts;</p>
<pre><code>"GET /file/ HTTP/1.1" 302
"" 400
</code... | 1 | 2016-08-16T19:05:24Z | 38,982,833 | <p>You can use:</p>
<pre><code>import re
lines = ['[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore', '[16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore']
rx = re.compile(r'''
"[^"]*" # ", followed by anything not a " and a "
\ # a space
\d+ # at leas... | 1 | 2016-08-16T19:17:21Z | [
"python",
"regex"
] |
regex to match any character or none? | 38,982,637 | <p>I have the two following peices of strings;</p>
<pre><code>line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore
line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore
</code></pre>
<p>I'm trying to grab these two parts;</p>
<pre><code>"GET /file/ HTTP/1.1" 302
"" 400
</code... | 1 | 2016-08-16T19:05:24Z | 38,984,717 | <p>Try this...
Using 'findall' in place of 'search' might give you a better control over how you want to process your output.</p>
<pre><code>import re
output = []
logs = '[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore \
[16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore'
re... | 0 | 2016-08-16T21:23:59Z | [
"python",
"regex"
] |
Set shell environment variable via python script | 38,982,640 | <p>I have some instrument which requires environment variable which I want to set automatically from python code. So I tried several ways to make it happen, but none of them were successful.
Here are some examples:</p>
<ol>
<li><p>I insert following code in my python script</p>
<pre><code>import os
os.system("export ... | 1 | 2016-08-16T19:05:30Z | 38,982,936 | <p>Setting an environment variable sets it only for the current process and any child processes it launches. So using <code>os.system</code> will set it only for the shell that is running to execute the command you provided. When that command finishes, the shell goes away, and so does the environment variable. Setting ... | 1 | 2016-08-16T19:24:49Z | [
"python",
"bash",
"shell"
] |
Set shell environment variable via python script | 38,982,640 | <p>I have some instrument which requires environment variable which I want to set automatically from python code. So I tried several ways to make it happen, but none of them were successful.
Here are some examples:</p>
<ol>
<li><p>I insert following code in my python script</p>
<pre><code>import os
os.system("export ... | 1 | 2016-08-16T19:05:30Z | 38,982,939 | <p>As long as you start the "instrument" (a script I supposed) from the very same process it should work:</p>
<pre><code>In [1]: os.putenv("VARIABLE", "123")
In [2]: os.system("echo $VARIABLE")
123
</code></pre>
<p>You can't change an environment variable of a different process or a parent process.</p>
| 0 | 2016-08-16T19:25:05Z | [
"python",
"bash",
"shell"
] |
Set shell environment variable via python script | 38,982,640 | <p>I have some instrument which requires environment variable which I want to set automatically from python code. So I tried several ways to make it happen, but none of them were successful.
Here are some examples:</p>
<ol>
<li><p>I insert following code in my python script</p>
<pre><code>import os
os.system("export ... | 1 | 2016-08-16T19:05:30Z | 38,984,815 | <p>Depending on how you execute your instrument, you might be able to change environment specifically for the child process without affecting the parent. See documentation for <code>os.spawn*e</code> or <code>subprocess.Popen</code> which accept separate argument denoting child environment. For example, <a href="https:... | 0 | 2016-08-16T21:31:25Z | [
"python",
"bash",
"shell"
] |
Simple, ugly function to produce an orientation from an angle. | 38,982,644 | <p>I wrote a function that takes a degree and returns the orientation as 'N', 'NE', ...etc. Very simple, but it's ugly - is there any way to rewrite this to make it...prettier?</p>
<pre><code>def orientation(tn):
if 23 <= tn <= 67:
o = 'NE'
elif 68 <= tn <= 113:
o = 'E'
elif... | 5 | 2016-08-16T19:05:51Z | 38,982,734 | <p>Use <a href="https://docs.python.org/2/library/bisect.html">bisection</a>:</p>
<pre><code>from bisect import bisect_left
directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']
boundaries = [22, 67, 113, 158, 203, 248, 293, 338, 360]
def orientation(tn):
return directions[bisect_left(boundaries, ... | 18 | 2016-08-16T19:11:48Z | [
"python"
] |
Simple, ugly function to produce an orientation from an angle. | 38,982,644 | <p>I wrote a function that takes a degree and returns the orientation as 'N', 'NE', ...etc. Very simple, but it's ugly - is there any way to rewrite this to make it...prettier?</p>
<pre><code>def orientation(tn):
if 23 <= tn <= 67:
o = 'NE'
elif 68 <= tn <= 113:
o = 'E'
elif... | 5 | 2016-08-16T19:05:51Z | 38,982,767 | <p>Try to make a whole number division by 45 and address an array member by this number (index). The array should contain directions.</p>
| 4 | 2016-08-16T19:13:50Z | [
"python"
] |
Simple, ugly function to produce an orientation from an angle. | 38,982,644 | <p>I wrote a function that takes a degree and returns the orientation as 'N', 'NE', ...etc. Very simple, but it's ugly - is there any way to rewrite this to make it...prettier?</p>
<pre><code>def orientation(tn):
if 23 <= tn <= 67:
o = 'NE'
elif 68 <= tn <= 113:
o = 'E'
elif... | 5 | 2016-08-16T19:05:51Z | 38,982,797 | <p>You can calculate the integer index into a list of compass directions:</p>
<pre><code>def compass(angle):
return ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'][int(8*(angle+22.)/360)]
</code></pre>
| 6 | 2016-08-16T19:15:36Z | [
"python"
] |
Simple, ugly function to produce an orientation from an angle. | 38,982,644 | <p>I wrote a function that takes a degree and returns the orientation as 'N', 'NE', ...etc. Very simple, but it's ugly - is there any way to rewrite this to make it...prettier?</p>
<pre><code>def orientation(tn):
if 23 <= tn <= 67:
o = 'NE'
elif 68 <= tn <= 113:
o = 'E'
elif... | 5 | 2016-08-16T19:05:51Z | 38,982,949 | <p>Same principle, but much clearer imo, making use of the <a href="https://docs.python.org/2/reference/expressions.html#conditional-expressions" rel="nofollow">ternary operator</a> instead: </p>
<pre><code>def orientation(tn):
tn = mod(tn, 360)
return "N" if tn < 23 else \
"NE" if tn < 68 else \... | 1 | 2016-08-16T19:25:43Z | [
"python"
] |
Which exception should I raise for a REST API error? | 38,982,668 | <p>I am writing a simple API client in Python and I am wondering what exception should I raise if the remote server is not happy.</p>
<p>The API itself is very poorly documented (I don't know all the possible error messages so I can't just define custom classes for all of them), I am letting Requests handle HTTP-level... | 2 | 2016-08-16T19:07:29Z | 38,982,742 | <p>Yes, just raising <code>Exception</code> is likely too broad. </p>
<p>Usually a module should define his own base exception class:</p>
<pre><code>MyAPIClientError(Exception):
pass
</code></pre>
<p>And then you can subclass that:</p>
<pre><code>RemoteServerNotHappyError(MyAPIClientError):
pass
</code></p... | 1 | 2016-08-16T19:12:04Z | [
"python",
"rest",
"exception-handling"
] |
Function not getting executed in python | 38,982,681 | <p>I have 2 functions<code>(recharge_list and sms_list)</code> in my below <code>Server()</code> class</p>
<pre><code>import os
import json
import requests
import cherrypy
import ConfigParser
from bs4 import BeautifulSoup
class Server():
@cherrypy.expose
def index(self):
return "Seems Like You're Lo... | 0 | 2016-08-16T19:08:07Z | 38,983,279 | <blockquote>
<p>By my understanding the object once created by <code>Server</code> class is able to execute only the first called function.</p>
</blockquote>
<p>This is not so. Each time an HTTP request is provided, the web server calls the function associated to the URL of that request.</p>
<blockquote>
<p>What ... | 1 | 2016-08-16T19:47:53Z | [
"python",
"cherrypy"
] |
I get python frameworks error while reading a csv file, when I try a different easier file it works fine | 38,982,712 | <pre><code>import csv
exampleFile = open('example.csv')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
print('Row #' + str(exampleReader.line_num) + ' ' + str(row))
Traceback (most recent call last):
File "/Users/jossan113/Documents/Python II/test.py", line 7, in <module>
... | 0 | 2016-08-16T19:10:09Z | 38,982,823 | <p>The file contains unicode characters, which was painful to deal with in old versions of python, since you are using 3.5 try opening the file as utf-8 and see if the issue goes away:</p>
<pre><code>exampleFile = open('example.csv', encoding="utf-8")
</code></pre>
<p><strong>From the docs:</strong></p>
<p>Since ope... | 0 | 2016-08-16T19:16:52Z | [
"python",
"file",
"csv",
"import",
"frameworks"
] |
Rows and columns restrictions on python | 38,982,776 | <p>I have a list of lists <code>m</code> which I need to modify</p>
<p>I need that the sum of each row to be greater than <code>A</code> and the sum of each column to be lesser than <code>B</code> </p>
<p>I have something like this</p>
<pre><code>x = 5 #or other number, not relevant
rows = len(m)
cols = len(m[0]... | 1 | 2016-08-16T19:14:19Z | 38,983,417 | <p>A NumPy solution:</p>
<pre><code>import numpy as np
val = B / len(m) # column sums <= B
assert val * len(m[0]) >= A # row sums >= A
# create array shaped like m, filled with val
arr = np.empty_like(m)
arr[:] = val
</code></pre>
<p>I chose to ignore the original content of <code>m</code> - it's all zero ... | 0 | 2016-08-16T19:57:20Z | [
"python",
"list",
"condition"
] |
Rows and columns restrictions on python | 38,982,776 | <p>I have a list of lists <code>m</code> which I need to modify</p>
<p>I need that the sum of each row to be greater than <code>A</code> and the sum of each column to be lesser than <code>B</code> </p>
<p>I have something like this</p>
<pre><code>x = 5 #or other number, not relevant
rows = len(m)
cols = len(m[0]... | 1 | 2016-08-16T19:14:19Z | 38,983,968 | <pre><code>from random import *
m = [[0,0,0],
[0,0,0]]
A = 20
B = 25
x = 1 #or other number, not relevant
rows = len(m)
cols = len(m[0])
def runner(list1, a1, b1, x1):
list1_backup = list(list1)
rows = len(list1)
cols = len(list1[0])
for r in range(rows):
while sum(list1[r]) <= a... | 0 | 2016-08-16T20:32:21Z | [
"python",
"list",
"condition"
] |
Rows and columns restrictions on python | 38,982,776 | <p>I have a list of lists <code>m</code> which I need to modify</p>
<p>I need that the sum of each row to be greater than <code>A</code> and the sum of each column to be lesser than <code>B</code> </p>
<p>I have something like this</p>
<pre><code>x = 5 #or other number, not relevant
rows = len(m)
cols = len(m[0]... | 1 | 2016-08-16T19:14:19Z | 38,983,999 | <p>Something like this should to the trick:</p>
<pre><code>import numpy
from scipy.optimize import linprog
A = 10
B = 20
m = 2
n = m * m
# the coefficients of a linear function to minimize.
# setting this to all ones minimizes the sum of all variable
# values in the matrix, which solves the problem, but see below.
c... | 1 | 2016-08-16T20:34:25Z | [
"python",
"list",
"condition"
] |
Python Mutli-chat socket errors | 38,982,784 | <p>I am writing a multi-chat which consists of the Client handler, the server and chat record. The Client should allow multiple chats. At the moment it doesn't allow for even one chat, I get an error message after the name has been entered. </p>
<p>This is the Client handler file</p>
<pre><code>from socket import*
fr... | 1 | 2016-08-16T19:14:48Z | 38,982,984 | <p>Edit: Also, your server isn't accepting/listing for connections</p>
<p>You should make the server multithreaded so that it can send and receive at the same time. Here's how it might look:</p>
<pre><code>import socket
import os
from threading import Thread
import thread
def main():
s = socket.socket(socket.AF_... | 0 | 2016-08-16T19:28:11Z | [
"python",
"multithreading",
"python-3.x"
] |
Are uWSGI and Nginx required to serve a Flask app? | 38,982,807 | <p>Setting up Flask with uWSGI and Nginx is quite difficult, and even with buildout scripts it takes quite some time, and has to be recorded to instructions to be reproduced later.</p>
<p>If I don't plan a big load on server (it's hidden from public), does it make sense to run it without uWSGI? (Flask can listen to a ... | 1 | 2016-08-16T19:15:54Z | 38,982,989 | <p>When you "run Flask" you are actually running Werkzeug's development WSGI server, and passing your Flask app as the WSGI callable.</p>
<p>The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.</p>
<p>Replace the Werkzeug dev server with a ... | 2 | 2016-08-16T19:28:55Z | [
"python",
"nginx",
"flask",
"uwsgi",
"buildout"
] |
Are uWSGI and Nginx required to serve a Flask app? | 38,982,807 | <p>Setting up Flask with uWSGI and Nginx is quite difficult, and even with buildout scripts it takes quite some time, and has to be recorded to instructions to be reproduced later.</p>
<p>If I don't plan a big load on server (it's hidden from public), does it make sense to run it without uWSGI? (Flask can listen to a ... | 1 | 2016-08-16T19:15:54Z | 38,984,367 | <p>Presumably you already have a Flask app object and routes set up, but if you create the app like this:</p>
<pre><code>import flask
app = flask.Flask(__name__)
</code></pre>
<p>then set up your <code>@app.route()</code>s, and then when you want to start the app:</p>
<pre><code>import gevent
app_server = gevent.w... | 1 | 2016-08-16T20:58:27Z | [
"python",
"nginx",
"flask",
"uwsgi",
"buildout"
] |
django-python: NoReverseMatch issue: what argument should I give it? | 38,982,944 | <p>I have the following views:</p>
<pre><code>def default_detail (request, equipment_id):
equipment = Equipment.objects.get(id = equipment_id)
context = {'equipment' : equipment}
return render(request, 'calbase/default_detail.html', context)
def default_add_cal (request, equipment_id):
equipment = ge... | 1 | 2016-08-16T19:25:22Z | 38,983,055 | <p>You should pass the arguments as a tuple. That would make <code>args</code> an iterable with <code>equipment_id</code> being one of the arguments:</p>
<pre><code>args=(equipment_id,ââ)
# ^
</code></pre>
<p>Those grouping parenthesis will not make the arguments a tuple:</p>
<pre><code>>>&... | 1 | 2016-08-16T19:33:22Z | [
"python",
"django",
"django-urls"
] |
Simple login function for XBMC (Python) issue | 38,983,104 | <p>I'm trying to scrape sections of a Javascript calendar page through python(xbmc/kodi).
So far I've been able to scrape static html variables but not the JavaScript generated sections. </p>
<p>The variables im trying to retrieve are <code><strong class="item-title">**this**</strong> , <span class="ite... | 1 | 2016-08-16T19:36:27Z | 38,983,617 | <p>Is your question about the steps to scrape the JavaScript, how to use Python on XBMC/Kodi, or how to install packages that come with a <strong>setup.py</strong> file?</p>
<p>Just based on your RegEx above, if your entries are always <em>like</em> <code><strong class="item-title">**this**</strong></code>... | 1 | 2016-08-16T20:10:30Z | [
"javascript",
"python",
"web-scraping",
"xbmc",
"kodi"
] |
Write xml with a path and value | 38,983,126 | <p>I have a list of paths and values, something like this:</p>
<pre><code>[
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'},
]
</code></pre>
<p>And I want to build out the full xml structure, which would be:</p>
<pre><code><Item>
<Info>
<... | 1 | 2016-08-16T19:38:19Z | 38,983,269 | <p>Yes, you can do that with <code>lxml</code>.</p>
<p>I suggest you to use a template XML and fill it.</p>
<p>Template:</p>
<pre><code><Item>
<Info>
<Name/>
</Info>
<Genres>
<Genre/>
</Genres>
</Item>
from lxml import etree
tree = etr... | 1 | 2016-08-16T19:47:13Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
Write xml with a path and value | 38,983,126 | <p>I have a list of paths and values, something like this:</p>
<pre><code>[
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'},
]
</code></pre>
<p>And I want to build out the full xml structure, which would be:</p>
<pre><code><Item>
<Info>
<... | 1 | 2016-08-16T19:38:19Z | 38,983,808 | <p>You could do something like:</p>
<pre><code>l = [
{'Path': 'Item/Info/Name', 'Value': 'Body HD'},
{'Path': 'Item/Genres/Genre', 'Value': 'Action'},
]
import lxml.etree as et
root_node = l[0]["Path"].split("/", 1)[0]
tree = et.fromstring("<{}></{}>".format(root_node, root_node))
for dct in l: ... | 1 | 2016-08-16T20:22:09Z | [
"python",
"xml",
"lxml",
"elementtree"
] |
xlwings UDFS: how to set PythonPath/ UDF_Modules correctly? | 38,983,144 | <p>Thank you for your time first!</p>
<p>Recently I have been trying to build my own excel functions by using Xlwings. Unlike using </p>
<pre><code>$ xlwings quickstart myproject
</code></pre>
<p>which would create a python script in the same directory as the excel xlsm file, I would love to put the python script a... | 1 | 2016-08-16T19:39:13Z | 38,985,158 | <p><code>PYTHONPATH</code>, as the name says, is a path, not a file, i.e. you should be using </p>
<pre><code>PYTHONPATH = "D:\"
</code></pre>
<p><code>xlwings quickstart myproject</code> is still useful because it sets up the Excel file with the VBA module, even if you want to move out the python file later on.</p>
| 3 | 2016-08-16T21:59:50Z | [
"python",
"excel-vba",
"xlwings"
] |
Positioning of multiple stacked bar plot with pandas | 38,983,145 | <p>I am trying to make a multiple stacked bar plot with pandas.</p>
<p>Here is a sample code:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'a':[10, 20], 'b': [15, 25], 'c': [35, 40], 'd':[45, 50]}, index=['john', 'bob'])
ax = df[['a', 'c']].plot.bar(position=0, width=0.1, stacked=True)
df[['b', 'd']].plot.... | 3 | 2016-08-16T19:39:17Z | 38,984,137 | <p>The position parameter in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow"><code>pd.Df.plot</code></a>controls the alignment of your bar plot layouts. It resembles similarity with the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar" re... | 2 | 2016-08-16T20:43:26Z | [
"python",
"pandas",
"matplotlib"
] |
Error in Spark while declaring a UDF | 38,983,244 | <p>I am trying to create a udf which takes a value(array) in a column and returns an array containing only unique elements . Please see the code below in Spark (version-1.6.1):</p>
<pre><code>def uniq_array(col_array):
x = np.unique(col_array)
return x
uniq_array_udf = udf(uniq_array,ArrayType())
</code></pre... | 0 | 2016-08-16T19:45:36Z | 38,983,377 | <p>For ArrayType, the type of the contents of the array also needs to be specified, eg</p>
<pre><code>def uniq_array(col_array):
x = np.unique(col_array)
return x
uniq_array_udf = udf(uniq_array,ArrayType(IntegerType()))
</code></pre>
| 2 | 2016-08-16T19:55:00Z | [
"python",
"apache-spark",
"bigdata",
"pyspark"
] |
Pandas dataframe plotting - issue when switching from two subplots to single plot w/ secondary axis | 38,983,254 | <p>I have two sets of data I want to plot together on a single figure. I have a set of flow data at 15 minute intervals I want to plot as a line plot, and a set of precipitation data at hourly intervals, which I am resampling to a daily time step and plotting as a bar plot. Here is what the format of the data looks lik... | 0 | 2016-08-16T19:46:22Z | 38,983,994 | <p>Here is an example:</p>
<h2>Setup</h2>
<pre><code>In [1]: from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
%matplotlib inline
df = pd.DataFrame({'x' : np.arange(10),
'y1' : np.random.rand(10,),
'y2' :... | 0 | 2016-08-16T20:34:06Z | [
"python",
"pandas",
"plot"
] |
difference between __all__ and from bar import * in __init__.py in package | 38,983,292 | <p>can someone please tell me what the differnce between using these two in my <code>__init__.py</code> in my package? And which is better to use?</p>
<pre><code>__all__ = ['functions']
from functions import *
</code></pre>
| -1 | 2016-08-16T19:48:41Z | 38,983,495 | <pre><code>print(len(globals()))
import sys
print(len(globals()))
from sys import *
print(len(globals()))
</code></pre>
<p>OUTPUT:</p>
<pre><code>8
9
67
</code></pre>
| -2 | 2016-08-16T20:02:45Z | [
"python",
"import",
"module",
"package",
"init"
] |
Issues downloading Graphlab dependencies get_dependencies() | 38,983,295 | <p>I am having trouble when I try to download the dependencies needed to run <code>graphlab</code>. I do <code>import graphlab</code> I get the following:</p>
<pre><code>ACTION REQUIRED: Dependencies libstdc++-6.dll and libgcc_s_seh-1.dll not found.
1. Ensure user account has write permission to C:\Users\DANISUAR\App... | 0 | 2016-08-16T19:49:08Z | 39,220,993 | <p>The first step is to install all the graph packages using the procedures listed in the link "<a href="https://turi.com/download/install-graphlab-create-command-line.html" rel="nofollow">https://turi.com/download/install-graphlab-create-command-line.html</a>" using pip installer.
Verify the successful installation of... | 0 | 2016-08-30T07:09:48Z | [
"python",
"data-science",
"graphlab"
] |
TCP handshake using python RAW sockets | 38,983,311 | <p>I am implementing a TCP handshake using python RAW sockets. The Linux kernel is however being quite annoying because it attempts to handle certain aspects of this protocol. </p>
<p>For example, when I send a SYN packet, the server responded with a SYN, ACK packet; to which the kernel automatically responds with a R... | 2 | 2016-08-16T19:50:15Z | 38,983,954 | <p>While I hope that someone comes up with a more convenient solution, one way to do it would be to use iptables to pass incoming TCP Syn packets to an <a href="https://www.netfilter.org/projects/libnetfilter_queue/doxygen/" rel="nofollow">nfqueue</a>. Nfqueue has existing python <a href="https://pypi.python.org/pypi/N... | 1 | 2016-08-16T20:31:46Z | [
"python",
"linux",
"tcp",
"network-programming",
"raw-sockets"
] |
TCP handshake using python RAW sockets | 38,983,311 | <p>I am implementing a TCP handshake using python RAW sockets. The Linux kernel is however being quite annoying because it attempts to handle certain aspects of this protocol. </p>
<p>For example, when I send a SYN packet, the server responded with a SYN, ACK packet; to which the kernel automatically responds with a R... | 2 | 2016-08-16T19:50:15Z | 38,986,064 | <p>You can use libpcap, in Python it seems this module: <a href="http://pylibpcap.sourceforge.net/" rel="nofollow">http://pylibpcap.sourceforge.net/</a> or this one: <a href="https://pypi.python.org/pypi/pypcap" rel="nofollow">https://pypi.python.org/pypi/pypcap</a></p>
<p>With pcap you can register to receive message... | 1 | 2016-08-16T23:38:15Z | [
"python",
"linux",
"tcp",
"network-programming",
"raw-sockets"
] |
TCP handshake using python RAW sockets | 38,983,311 | <p>I am implementing a TCP handshake using python RAW sockets. The Linux kernel is however being quite annoying because it attempts to handle certain aspects of this protocol. </p>
<p>For example, when I send a SYN packet, the server responded with a SYN, ACK packet; to which the kernel automatically responds with a R... | 2 | 2016-08-16T19:50:15Z | 39,000,770 | <p>Since you are doing this all yourself with raw packets, why not just create your own MAC address and IP address? You would need to put the adapter into promiscuous mode to receive packets, but if you do this, the kernel shouldn't send any responses to your incoming packets as they will appear to be addressed to "som... | 1 | 2016-08-17T15:30:47Z | [
"python",
"linux",
"tcp",
"network-programming",
"raw-sockets"
] |
Can't figure out for k list.remove(k) | 38,983,333 | <p>Im new at python and also at programming. My code is:</p>
<pre><code>xxx = ['cc','bb','aa','qq','zz']
for k in xxx:
if k[0] != 'a':
xxx.remove(k)
print xxx
</code></pre>
<p>I'm expecting to get output xxx to be = <code>aa</code> or <code>['aa']</code>.</p>
<p>But instead my output <code>['bb', 'aa', '... | 0 | 2016-08-16T19:51:55Z | 38,983,494 | <p>You're trying to modify a list in place as you're trying to remove items while iterating, which can lead to an assortment of strange unwanted behaviour. Here are some solutions:</p>
<pre><code>>>> [i for i in ['cc','bb','aa','qq','zz'] if i[0] == 'a'] # Returns new list.
['aa']
</code></pre>
<p>or</p>
<... | 1 | 2016-08-16T20:02:36Z | [
"python",
"list",
"for-loop"
] |
Can't figure out for k list.remove(k) | 38,983,333 | <p>Im new at python and also at programming. My code is:</p>
<pre><code>xxx = ['cc','bb','aa','qq','zz']
for k in xxx:
if k[0] != 'a':
xxx.remove(k)
print xxx
</code></pre>
<p>I'm expecting to get output xxx to be = <code>aa</code> or <code>['aa']</code>.</p>
<p>But instead my output <code>['bb', 'aa', '... | 0 | 2016-08-16T19:51:55Z | 38,983,587 | <p>Removing elements from a list while iterating through it (at least the way you are doing it) can be tricky.
Let's go through it step-by-step:</p>
<pre><code>xxx = ['cc','bb','aa','qq','zz']
for k in xxx:
</code></pre>
<p>You're going to go through each element in the list. The first element is 'cc', which doesn't ... | 0 | 2016-08-16T20:08:41Z | [
"python",
"list",
"for-loop"
] |
syntax error for If and Else statements | 38,983,359 | <p>enter image description hereOk, I am just starting to learn python, and I can't figure out why my IF/Else statement keeps getting this error after I enter Else: "SyntaxError: unindent does not match any outer indentation level". Here is my code
if x>1000:
print('3')
else:</p>
<p>SyntaxError:SyntaxE... | -1 | 2016-08-16T19:53:22Z | 38,983,390 | <p>Each indentation level should have four spaces.</p>
<pre><code>if x > 1000:
print('3')
else:
pass # Must match indentation level of `print('3')` above.
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help... | 1 | 2016-08-16T19:55:46Z | [
"python",
"if-statement"
] |
syntax error for If and Else statements | 38,983,359 | <p>enter image description hereOk, I am just starting to learn python, and I can't figure out why my IF/Else statement keeps getting this error after I enter Else: "SyntaxError: unindent does not match any outer indentation level". Here is my code
if x>1000:
print('3')
else:</p>
<p>SyntaxError:SyntaxE... | -1 | 2016-08-16T19:53:22Z | 38,983,400 | <p>You are probably mixing up spaces and tabs. Only use one of those. If you are using spaces, make sure you are using the same amount of spaces. Also else must have something in it, like pass or return</p>
| 0 | 2016-08-16T19:56:22Z | [
"python",
"if-statement"
] |
syntax error for If and Else statements | 38,983,359 | <p>enter image description hereOk, I am just starting to learn python, and I can't figure out why my IF/Else statement keeps getting this error after I enter Else: "SyntaxError: unindent does not match any outer indentation level". Here is my code
if x>1000:
print('3')
else:</p>
<p>SyntaxError:SyntaxE... | -1 | 2016-08-16T19:53:22Z | 38,983,492 | <p>Be careful with spaces and tabs, even if lines look visually indented, from python perspective they maybe are not indented</p>
<p><a href="http://i.stack.imgur.com/SWwRG.png" rel="nofollow"><img src="http://i.stack.imgur.com/SWwRG.png" alt="enter image description here"></a></p>
<p>For example, look at the image, ... | 1 | 2016-08-16T20:02:30Z | [
"python",
"if-statement"
] |
syntax error for If and Else statements | 38,983,359 | <p>enter image description hereOk, I am just starting to learn python, and I can't figure out why my IF/Else statement keeps getting this error after I enter Else: "SyntaxError: unindent does not match any outer indentation level". Here is my code
if x>1000:
print('3')
else:</p>
<p>SyntaxError:SyntaxE... | -1 | 2016-08-16T19:53:22Z | 38,983,528 | <p>Ah, IDLE. You have tried to enter this into shell, right? So the thing looks like</p>
<pre><code>>>> if x > 1000:
print(3)
else:
</code></pre>
<p>right? The point is, <code>>>></code> doesn't count when calculating indents. So in fact if and else are <em>not</em> in the same column... | 2 | 2016-08-16T20:04:31Z | [
"python",
"if-statement"
] |
How do I avoid running the setup method for a skipped Python unit test | 38,983,401 | <p>I have a set of test cases with a few skipped tests, but the setUp method is being run for the skipped tests. According to the documentation at <a href="https://docs.python.org/2/library/unittest.html" rel="nofollow">https://docs.python.org/2/library/unittest.html</a>, Skipped tests will not have setUp() or tearDown... | -1 | 2016-08-16T19:56:27Z | 38,983,558 | <p>Rather than calling <code>TestCase.skipTest</code>, you can decorate the method with <a href="https://docs.python.org/2/library/unittest.html#unittest.skip" rel="nofollow"><code>unittest.skip</code></a>:</p>
<pre><code>import unittest
def fun(x):
return x + 1
class MyTest(unittest.TestCase):
def setUp(sel... | 0 | 2016-08-16T20:06:11Z | [
"python",
"unit-testing",
"python-unittest"
] |
how to pivot a Dataframe groupby results | 38,983,427 | <p>I have following dataframe:</p>
<pre><code>test=pd.DataFrame({'MKV':[50,1000,80,20],
'Rating':['A','Z','A','A'],
'Sec':['I','I','I','F']})
test.groupby(['Rating','Sec'])['MKV'].apply(lambda x: x/x.sum())
gives results:
0 0.38
1 1.00
2 0.62
3 1.00
</code></pre>
<p>How ca... | 1 | 2016-08-16T19:58:04Z | 38,983,937 | <p>I don't think you need to do a <code>groupby</code>. You can pivot by using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel=... | 2 | 2016-08-16T20:30:38Z | [
"python",
"pandas",
"group-by",
"pivot"
] |
Query instances related to other instance with SQLAlchemy | 38,983,450 | <p>I have <code>User</code> and <code>Property</code> models for my application. I was originally using the Peewee ORM, but am switching to SQLAlchemy. I want to select all properties listed by the current user and display them in a template. In Peewee, iterating over the following query worked, but I get a <code>Pr... | 0 | 2016-08-16T19:59:38Z | 38,983,901 | <p>In Peewee, a foreign key field does not separate the actual key from the thing it represents. In SQLAlchemy, a foreign key column is only the key, a relationship is used to represent the thing it points to.</p>
<p><code>listed_by</code> is an integer. <code>current_user</code> is a proxy to a <code>User</code> ob... | 1 | 2016-08-16T20:28:11Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
Saving data from a modelform Django | 38,983,483 | <p>Now heads up! I am fresh noob off the NOOB-BUS from NOOBSVILLE!</p>
<p>So i am workin on a form to load up information and edit that form information and im in a headache. so i am using:</p>
<p>Django: 1.8
Pyhton: 3.5.1
backend is sqlite </p>
<p>I am using a form.ModelForm to load information into but when it com... | 0 | 2016-08-16T20:01:58Z | 38,985,071 | <p>I think you're wanting info/answers on a couple of things here, looking at your code comments. Hopefully this helps:</p>
<p>1) You only need to use the clean_FIELDNAME functions if you need to handle something custom specifically for that field. The <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validati... | 1 | 2016-08-16T21:53:08Z | [
"python",
"django",
"validation",
"modelform"
] |
unbound method fit() must be called with DecisionTreeClassifier instance as first argument (got Stock instance instead) | 38,983,597 | <p>I'm trying to access the <code>fit</code> method on the <code>clf</code> object in my <code>Stock</code> class, I get this error: </p>
<p><code>unbound method fit() must be called with DecisionTreeClassifier instance as first argument (got Stock instance instead)</code></p>
<p>Stock class:</p>
<pre><code>class St... | 0 | 2016-08-16T20:09:17Z | 38,983,687 | <p>You need to instantiate your <code>DecisionTreeClassifier</code></p>
<p><code>self.clf = tree.DecisionTreeClassifier()</code></p>
| 1 | 2016-08-16T20:15:06Z | [
"python",
"scikit-learn"
] |
unbound method fit() must be called with DecisionTreeClassifier instance as first argument (got Stock instance instead) | 38,983,597 | <p>I'm trying to access the <code>fit</code> method on the <code>clf</code> object in my <code>Stock</code> class, I get this error: </p>
<p><code>unbound method fit() must be called with DecisionTreeClassifier instance as first argument (got Stock instance instead)</code></p>
<p>Stock class:</p>
<pre><code>class St... | 0 | 2016-08-16T20:09:17Z | 38,983,738 | <p>You're not instantiating <code>tree.DecisionTreeClassifier</code>. Therefore, you're calling the <code>fit()</code> method <em>on the class</em> and need to tell it what instance you want to use, just as it says.</p>
<p>Presumably you want to instantiate <code>tree.DecisionTreeClassifier</code>:</p>
<pre><code>sel... | 1 | 2016-08-16T20:17:50Z | [
"python",
"scikit-learn"
] |
unbound method fit() must be called with DecisionTreeClassifier instance as first argument (got Stock instance instead) | 38,983,597 | <p>I'm trying to access the <code>fit</code> method on the <code>clf</code> object in my <code>Stock</code> class, I get this error: </p>
<p><code>unbound method fit() must be called with DecisionTreeClassifier instance as first argument (got Stock instance instead)</code></p>
<p>Stock class:</p>
<pre><code>class St... | 0 | 2016-08-16T20:09:17Z | 38,983,773 | <p>To complete the other correct answers, here's a little example which will help you to understand what your buggy line <code>self.clf = tree.DecisionTreeClassifier</code> means:</p>
<pre><code>class f(object):
def __init__(self):
pass
print(isinstance(f, f))
print(isinstance(f(), f))
</code></pre>
| 2 | 2016-08-16T20:20:20Z | [
"python",
"scikit-learn"
] |
string to wstring in python | 38,983,603 | <p>I have a udp socket which received datagram of different length.
The first of the datagram specifies what type of data it is going to receive say for example 64-means bool false, 65-means bool true, 66-means sint, 67-means int and so on. As most of datatypes have known length, but when it comes to string and wstrin... | 0 | 2016-08-16T20:09:38Z | 38,989,201 | <p>A complete answer depends on exactly what you intend to do with the resulting data. Splitting the string with <code>'\x00'</code> (assuming that's what you meant to do? not sure I understand why there are two backslashes there) doesn't really make sense. The reason for using a <code>wstring</code> type in the first ... | 1 | 2016-08-17T06:08:23Z | [
"python",
"string",
"sockets",
"wstring"
] |
kivy android share image | 38,983,649 | <p>I want to create share button that will use android ACTION_SEND intent for sharing image. It's my code:</p>
<pre><code>from kivy.setupconfig import USE_SDL2
def share(path):
if platform == 'android':
from jnius import cast
from jnius import autoclass
if USE_SDL2:
PythonActi... | 1 | 2016-08-16T20:12:12Z | 39,054,869 | <p>I found solution. You must cast uri to parcelable and then pass it to intent:</p>
<pre><code>parcelable = cast('android.os.Parcelable', uri)
shareIntent.putExtra(Intent.EXTRA_STREAM, parcelable)
</code></pre>
| 0 | 2016-08-20T13:51:15Z | [
"android",
"python",
"kivy",
"pyjnius"
] |
How to tackle this Inverse Relation homework? | 38,983,767 | <p>Here is my assignment:</p>
<blockquote>
<p>Write a function <strong>inverse(rel)</strong> that takes a relation rel and returns the inverse relation of the relation rel. The inverse relation InvsetR of the relation R is dened as InvsetR =
{(x, y) â S Ã S |(y, x) â R)}. Example:</p>
<blockquote>
<p... | -1 | 2016-08-16T20:20:00Z | 38,983,842 | <p>For this particular example, you don't need any custom function of yours, just use the builtins python already provides, a couple of examples:</p>
<pre><code>foo = set([(1, 1), (1, 2), (2, 3), (4, 2)])
inv_foo1 = map(lambda (a, b): (b, a), foo)
inv_foo2 = {(b, a) for (a, b) in foo}
print(foo)
print(inv_foo1)
print(... | 0 | 2016-08-16T20:24:14Z | [
"python",
"set",
"add",
"relation",
"inverse"
] |
How to tackle this Inverse Relation homework? | 38,983,767 | <p>Here is my assignment:</p>
<blockquote>
<p>Write a function <strong>inverse(rel)</strong> that takes a relation rel and returns the inverse relation of the relation rel. The inverse relation InvsetR of the relation R is dened as InvsetR =
{(x, y) â S Ã S |(y, x) â R)}. Example:</p>
<blockquote>
<p... | -1 | 2016-08-16T20:20:00Z | 38,983,848 | <p>If a "relation" is a set of (x, y) couples:</p>
<pre><code>>>> relation = {(1,1), (1,2), (2,3), (4,2)}
</code></pre>
<p>The inverted relation is:</p>
<pre><code>>>> inverted = {(y, x) for x, y in relation}
>>> inverted
{(3, 2), (1, 1), (2, 4), (2, 1)}
</code></pre>
<p>The <code>inRelat... | 0 | 2016-08-16T20:24:34Z | [
"python",
"set",
"add",
"relation",
"inverse"
] |
How to properly use str.replace() with Pandas DataFrame | 38,983,922 | <p>I have a DataFrame like so </p>
<pre><code> Year Player
46 Jan. 17, 1971 Chuck Howley
47 Jan. 11, 1970 Len Dawson
48 Jan. 12, 1969 Joe Namath
49 Jan. 14, 1968 Bart Starr
50 Jan. 15, 1967 Bart Starr
</code></pre>
<p>and I only want the year to populate <code>df_MVPs['Year']</cod... | 2 | 2016-08-16T20:29:46Z | 38,984,042 | <p>I'd use <code>.str.extract()</code> method instead:</p>
<pre><code>In [10]: df
Out[10]:
Year Player
46 Jan. 17, 1971 Chuck Howley
47 Jan. 11, 1970 Len Dawson
48 Jan. 12, 1969 Joe Namath
49 Jan. 14, 1968 Bart Starr
50 Jan. 15, 1967 Bart Starr
In [11]: df.Year.str.extract('.*(\d... | 1 | 2016-08-16T20:37:52Z | [
"python",
"pandas"
] |
How to properly use str.replace() with Pandas DataFrame | 38,983,922 | <p>I have a DataFrame like so </p>
<pre><code> Year Player
46 Jan. 17, 1971 Chuck Howley
47 Jan. 11, 1970 Len Dawson
48 Jan. 12, 1969 Joe Namath
49 Jan. 14, 1968 Bart Starr
50 Jan. 15, 1967 Bart Starr
</code></pre>
<p>and I only want the year to populate <code>df_MVPs['Year']</cod... | 2 | 2016-08-16T20:29:46Z | 38,984,059 | <p>Aw man, convert to a datetime then get the year:</p>
<pre><code>df_MVPs['Year'] = pd.to_datetime(df_MVPs['Year'], format='%b. %d, %Y').dt.year
</code></pre>
| 5 | 2016-08-16T20:38:41Z | [
"python",
"pandas"
] |
How to properly use str.replace() with Pandas DataFrame | 38,983,922 | <p>I have a DataFrame like so </p>
<pre><code> Year Player
46 Jan. 17, 1971 Chuck Howley
47 Jan. 11, 1970 Len Dawson
48 Jan. 12, 1969 Joe Namath
49 Jan. 14, 1968 Bart Starr
50 Jan. 15, 1967 Bart Starr
</code></pre>
<p>and I only want the year to populate <code>df_MVPs['Year']</cod... | 2 | 2016-08-16T20:29:46Z | 38,984,074 | <p>You could take the last four characters of the string:</p>
<pre><code>df_MVPs['Year'] = df_MVPs['Year'].str[-4:]
>>> df_MVPs
Year Player
46 1971 Chuck Howley
47 1970 Len Dawson
48 1969 Joe Namath
49 1968 Bart Starr
50 1967 Bart Starr
</code></pre>
| 2 | 2016-08-16T20:39:45Z | [
"python",
"pandas"
] |
Iterating variable when if statement comes up false | 38,983,982 | <p>I wrote this program in python:</p>
<pre><code>num=51
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
else:
print "not right number, try again - error 1"
else:
print "not right number, try again -... | 0 | 2016-08-16T20:33:31Z | 38,984,056 | <p>You can use the <code>break</code> statement to terminate the loop</p>
<pre><code>num=1
while True:
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
break
else:
print "n... | 2 | 2016-08-16T20:38:33Z | [
"python"
] |
Iterating variable when if statement comes up false | 38,983,982 | <p>I wrote this program in python:</p>
<pre><code>num=51
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
else:
print "not right number, try again - error 1"
else:
print "not right number, try again -... | 0 | 2016-08-16T20:33:31Z | 38,984,139 | <p>What about this one?</p>
<pre><code>def f(n):
for (a, b) in [(3, 1), (4, 2), (5, 3), (6, 4)]:
if(num % a) != b:
return (False, b)
return (True, n)
for num in range(100):
print '-' * 80
v = f(num)
if not v[0]:
print "{0} is not the right number, try again - error {1... | 1 | 2016-08-16T20:43:31Z | [
"python"
] |
Iterating variable when if statement comes up false | 38,983,982 | <p>I wrote this program in python:</p>
<pre><code>num=51
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
else:
print "not right number, try again - error 1"
else:
print "not right number, try again -... | 0 | 2016-08-16T20:33:31Z | 38,984,191 | <p>I think that the code's structure is wrong, you could try this instead:</p>
<pre><code>num=51
def test(num):
# keep all the tests in a list
# same as tests = [num % 3 == 1, num % 4 == 2, ...]
tests = [num % x == y for x,y in zip(range(3,7), range(1,5))]
if all(tests): # if all the tests are Tru... | 1 | 2016-08-16T20:46:56Z | [
"python"
] |
Iterating variable when if statement comes up false | 38,983,982 | <p>I wrote this program in python:</p>
<pre><code>num=51
if (num % 3 == 1):
if (num%4 == 2):
if (num%5 == 3):
if (num%6 ==4):
print num
else:
print "not right number, try again - error 1"
else:
print "not right number, try again -... | 0 | 2016-08-16T20:33:31Z | 38,984,275 | <p>You could clean it up by putting your checks in a function:</p>
<pre><code>def good_number(num):
if num % 3 == 1:
if num % 4 == 2:
if num % 5 == 3:
if num % 6 == 4:
return True
# Put your elses/prints here
# Replace 100 with your max
for num in range(... | 0 | 2016-08-16T20:52:30Z | [
"python"
] |
Machine-Learning classification results too good to be true? | 38,984,004 | <p>Sorry about all the text, but I think the background of this project would help:</p>
<p>I've been working on a binary classification project. The original dataset consisted of about 28,000 of class 0 and 650 of class 1, so it was very highly imbalanced. I was given an under- and over-sampled dataset to work with th... | 0 | 2016-08-16T20:34:45Z | 38,985,480 | <p>Accuracy may not be the best performance metric in your case, maybe you can think of using precision,recall and F1 score, and perform some debugging via learning curves, over fitting detection, etc.</p>
| 0 | 2016-08-16T22:28:46Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"classification"
] |
Conditional Iteration over a dataframe | 38,984,043 | <p>I have a dataframe <code>df</code> which looks like:</p>
<pre><code> id location grain
0 BBG.XETR.AD.S XETR 16.545
1 BBG.XLON.VB.S XLON 6.2154
2 BBG.XLON.HF.S XLON NaN
3 BBG.XLON.RE.S XLON NaN
4 BBG.XLON.LL.S XLON NaN
5 BBG.XLON.AN.S ... | 1 | 2016-08-16T20:37:52Z | 38,984,193 | <p>You can specify a list of columns in <code>dropna</code> on which to subset the data:</p>
<blockquote>
<p>subset : array-like
Labels along other axis to consider, e.g. if you are dropping rows
these would be a list of columns to include</p>
</blockquote>
<pre><code>>>> df.dropna(subset=['gra... | 1 | 2016-08-16T20:47:04Z | [
"python",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.