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]]) </code></pre> <p><code>d[0, 0]</code> is <code>-1</code>. and is the sum of <code>a[:, 0] * b[:, 0]</code>. I'd like a 2x2 array of vectors where the <code>[0, 0]</code> position would be <code>a[:, 0] * b[:, 0]</code>.</p> <p>with the above <code>a</code> and <code>b</code>, I'd expect</p> <pre><code>d = np.array([[a[:, i] * b[:, j] for j in range(a.shape[1])] for i in range(b.shape[1])]) d array([[[-1, 0], [-1, -4], [ 0, -6]], [[ 1, 0], [ 1, 6], [ 0, 9]], [[ 5, 0], [ 5, 0], [ 0, 0]]]) </code></pre> <p>The sum of <code>d</code> along <code>axis==2</code> should be the dot product <code>a.T.dot(b)</code></p> <pre><code>d.sum(2) array([[-1, -5, -6], [ 1, 7, 9], [ 5, 5, 0]]) </code></pre> <h3>Question</h3> <p>What is the most efficient way of getting <code>d</code>?</p>
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]]) </code></pre> <p><code>d[0, 0]</code> is <code>-1</code>. and is the sum of <code>a[:, 0] * b[:, 0]</code>. I'd like a 2x2 array of vectors where the <code>[0, 0]</code> position would be <code>a[:, 0] * b[:, 0]</code>.</p> <p>with the above <code>a</code> and <code>b</code>, I'd expect</p> <pre><code>d = np.array([[a[:, i] * b[:, j] for j in range(a.shape[1])] for i in range(b.shape[1])]) d array([[[-1, 0], [-1, -4], [ 0, -6]], [[ 1, 0], [ 1, 6], [ 0, 9]], [[ 5, 0], [ 5, 0], [ 0, 0]]]) </code></pre> <p>The sum of <code>d</code> along <code>axis==2</code> should be the dot product <code>a.T.dot(b)</code></p> <pre><code>d.sum(2) array([[-1, -5, -6], [ 1, 7, 9], [ 5, 5, 0]]) </code></pre> <h3>Question</h3> <p>What is the most efficient way of getting <code>d</code>?</p>
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://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> would be like so -</p> <pre><code>np.einsum('ij,ik-&gt;jki',a,b) </code></pre>
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 import cm from mpl_toolkits.mplot3d import Axes3D x=np.asarray([3,5,9,3,3,7,6,9,1,9]); y=np.asarray([4,3,3,10,8,2,4,10,9,3]); z=np.asarray([1,2,4,10,1,7,10,3,1,7]); # x = np.random.random(100) xi=np.linspace(min(x), max(x),50) #print xi yi=np.linspace(min(y),max(y),50) X,Y= np.meshgrid(xi,yi) Z = np.nan_to_num(griddata((x,y), z, (X, Y), method='cubic')) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x, y, z) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False,alpha=0.4) plt.show() </code></pre> <p>What i am looking to do is to color the plot according to categories something like this : <a href="http://i.stack.imgur.com/AtV0f.png" rel="nofollow"><img src="http://i.stack.imgur.com/AtV0f.png" alt="enter image description here"></a> Where red represents the category 1 and Blue represents category 2. So inorder to get something like this I need to generate a 2D Array and then use a colormap/colorscale to color the categories accordingly.</p> <p>The above output have been created using <strong>XLSTAT</strong> where it took category as the 4th col as the category.</p> <p>Can someone explain me how do i generate the Z data which will help me color the categories differently? </p> <p>I have tried to something like dividing the 2D matrix into halves 0's and half 1's and got output something like this.</p> <p><a href="http://i.stack.imgur.com/ghYSF.png" rel="nofollow"><img src="http://i.stack.imgur.com/ghYSF.png" alt="enter image description here"></a></p> <p>Considering the following sample data : </p> <pre><code>x y z Category 3 4 1 Cat 1 5 3 2 cat2 9 3 4 cat2 3 10 10 cat3 3 8 1 cat3 7 2 7 cat2 6 4 10 Cat 1 9 10 3 Cat 4 1 9 1 Cat 1 9 3 7 cat2 </code></pre> <p><strong>I need to generate 2D Data that will represent the surface color and color the different categories with custom color</strong></p>
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> <pre><code>color = [colormap[cat] for cat in category] C = np.nan_to_num(griddata((x, y), color, (X, Y), method='cubic')) </code></pre> <p>Then you can use the colormap <code>cm.coolwarm</code> to map values in <code>C</code> to RGBA <code>facecolors</code>:</p> <pre><code>ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cmap, linewidth=0, antialiased=False, alpha=0.4, facecolors=cmap(C)) </code></pre> <hr> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import scipy.interpolate as interpolate x = np.asarray([3, 5, 9, 3, 3, 7, 6, 9, 1, 9]) y = np.asarray([4, 3, 3, 10, 8, 2, 4, 10, 9, 3]) z = np.asarray([1, 2, 4, 10, 1, 7, 10, 3, 1, 7]) category = np.array(['Cat 1', 'cat2', 'cat2', 'cat3', 'cat3', 'cat2', 'Cat 1', 'Cat 4', 'Cat 1', 'cat2']) # coolwarm: 0 --&gt; blue, 1 --&gt; red # want: 'Cat 1' --&gt; blue, 'cat2' --&gt; red, 'cat3' --&gt; ?, 'Cat 4' --&gt; ? colormap = {'Cat 1': 0, 'cat2': 1, 'cat3': 0.333, 'Cat 4': 0.666} color = np.array([colormap[cat] for cat in category]) xi = np.linspace(min(x), max(x), 50) yi = np.linspace(min(y), max(y), 50) X, Y = np.meshgrid(xi, yi) Z = np.nan_to_num(interpolate.griddata((x, y), z, (X, Y), method='cubic')) C = interpolate.griddata((x, y), color, (X, Y), method='cubic') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') cmap = cm.coolwarm ax.scatter(x, y, z, c=color, cmap=cmap) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cmap, linewidth=0, antialiased=False, alpha=0.4, facecolors=cmap(C)) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/MhdM6.png" rel="nofollow"><img src="http://i.stack.imgur.com/MhdM6.png" alt="enter image description here"></a></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 way to achieve this? This should be applicable to lists with any length.</p>
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>&gt;&gt;&gt; "{} 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>", and"</code> isntead.</p>
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 way to achieve this? This should be applicable to lists with any length.</p>
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 = '' last = None for next in iterable: if last is not None: yield sep yield last sep = ', ' last = next if sep: yield ', and ' if last is not None: yield last print ''.join(coma_iter(listy)) </code></pre>
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 way to achieve this? This should be applicable to lists with any length.</p>
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 way to achieve this? This should be applicable to lists with any length.</p>
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, item2, item3, item4, item5, and item6 </code></pre> <p>Also as an aside the Pythonic way to write </p> <pre><code>for i in abc[0:-1]: </code></pre> <p>is</p> <pre><code>for i in abc[:-1]: </code></pre>
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 way to achieve this? This should be applicable to lists with any length.</p>
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> <pre><code>&gt;&gt;&gt; comma(["spam"]) ', and spam' </code></pre> <p>To solve that, you can either test the length of the list (<code>if len(items) &gt;= 2:</code>), or do this, which (imho) is slightly more pythonic:</p> <pre><code>def comma(items): start, last = items[:-1], items[-1] if start: return "{}, and {}".format(", ".join(start), last) else: return last </code></pre> <p>As we saw above, a single item list will result in an empty value for <code>items[:-1]</code>. <code>if last:</code> is just a pythonic way of checking if <code>last</code> is empty.</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 way to achieve this? This should be applicable to lists with any length.</p>
8
2016-08-16T17:44:46Z
38,982,233
<p>Might as well round out the solutions with a recursive example.</p> <pre><code>&gt;&gt;&gt; listy = ['item1', 'item2','item3','item4','item5', 'item6'] &gt;&gt;&gt; def foo(a): if len(a) == 1: return ', and ' + a[0] return a[0] + ', ' + foo(a[1:]) &gt;&gt;&gt; foo(listy) 'item1, item2, item3, item4, item5, , and item6' &gt;&gt;&gt; </code></pre>
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 way to achieve this? This should be applicable to lists with any length.</p>
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 &gt;&gt;&gt; item1, item2, item3, item4, item5, and, item6 </code></pre> <p><strong>second way</strong>:</p> <pre><code>print(', '.join(item for item in listy[:-1]), 'and', listy[-1]) output &gt;&gt;&gt; (item1, item2, item3, item4, item5, 'and', 'item6') </code></pre>
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>&lt;root&gt; &lt;element&gt; &lt;subelement1&gt; subelement1 text &lt;/subelement1&gt; &lt;subelement2&gt; subelement2 text &lt;/subelement2&gt; &lt;/element&gt; &lt;/root&gt; </code></pre> <p>It's my goal to parse the tree, and alter <em>only</em> the data in a particular subelement, in this case <code>&lt;subelement2&gt;</code>.So, where currently there exists the string <code>subelement2 text</code>, I want to be able to append data to that so that the resulting XML is as follows:</p> <pre><code>&lt;root&gt; &lt;element&gt; &lt;subelement1&gt; subelement1 text &lt;/subelement1&gt; &lt;subelement2&gt; subelement2 text + my new string of text &lt;/subelement2&gt; &lt;/element&gt; &lt;/root&gt; </code></pre> <p>Noting, that <code>subelement2 text</code> has now become <code>subelement2 text + my new string of text</code></p> <hr> <p>I already can find parse the text and find <code>subelement2</code>, like so:</p> <pre><code>import xml.etree.ElementTree as ET doc = ET.fromstring(''' &lt;root&gt; &lt;element&gt; &lt;subelement1&gt; subelement1 text &lt;/subelement1&gt; &lt;subelement2&gt; subelement2 text &lt;/subelement2&gt; &lt;/element&gt; &lt;/root&gt; ''') el = doc.find('.//subelement2') </code></pre> <p>...but once I have the Element object assigned to <code>el</code>, how do I alter its text?</p> <p>What I am looking for help in understanding, is the general function or approach used to alter existing text within a subelement, as in the example above.</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 registration forms. I have been trying to figure out the cause of the issue for days and I am still not understanding how the field can be null and still wont work. However in the terminal I am not getting any error messages, and the login form is working because users are created via the admin. Thanks for the help and here is the code I am using.</p> <h1>the user form</h1> <pre><code>class UserForm(forms.ModelForm): email = forms.EmailField(label="Email Address") password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def clean_email(self): email = self.cleaned_data.get('email') email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("This email already exists.") return email def clean_username(self): username = self.cleaned_data.get('username') username_qs = User.objects.filter(username=username) if username_qs.exists(): raise forms.ValidationError("This username already exists.") return username def clean_password(self): password = self.cleaned_data.get('password') if len(password) &lt;= 8: raise forms.ValidationError("Password must be longer than 8 characters") else: print("password saved") </code></pre> <h1>My view registration function</h1> <pre><code>def register_view(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() new_user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, new_user) return redirect('/appname/account/') return render(request, "appname/index.html", {"form": form}) </code></pre> <h1>My html</h1> <pre><code>% block signup %} &lt;div clss="container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6" style="background-color:yellow;"&gt; &lt;h1&gt;appname&lt;/h1&gt; &lt;p&gt;x and x&lt;/p&gt; &lt;/div&gt; &lt;div&gt; &lt;div class="col-sm-6"&gt; &lt;h3&gt;Sign Up&lt;/h1&gt; &lt;form method="POST" action="{% url 'appname:index' %}"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" class="btn" value="Sign Up"/&gt; &lt;/form&gt; &lt;h5&gt;Have an Account? &lt;a href="{% url 'appname:login' %}"&gt;Login&lt;/a&gt;&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endblock %} </code></pre>
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) &lt;= 8: raise forms.ValidationError("Password must be longer than 8 characters") else: print("password saved") return password # &lt;-- add this line </code></pre>
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.contrib.auth.management import get_default_username from django.contrib.auth.password_validation import validate_password from django.core import exceptions from django.core.management.base import CommandError from django.utils.encoding import force_str from django.utils.text import capfirst class Command(makesuperuser.Command): def handle(self, *args, **options): # the rest of code is copied from Django source and is almost # standart except few changes related to how info of # REQUIRED_FIELDS is shown </code></pre> <p>When I do in terminal <code>./manage.py createsuperuser</code> I do not see any changes. If I change the name of my file to lets say <code>mycmd.py</code> and do <code>./manage.py mycmd</code> everything starts to work as I expect.</p> <p>How to get changes I need using <code>./manage.py createsuperuser</code>?</p>
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 for line in in_file: num.append(line[:3]) intenum = [] for i in num: intenum.append(int(i)) #Make the keys as integers dict1= dict(zip(intenum,text)) #Merge the 2 lists in a dictionary print ('This software will give you the subjects for each stack.') #Instructions for the user print ('I need to know the range first, please only use the first three numbers of the classmark.') #Instructions for the user x=input('Please key in the starting number for this stack: ') #Input for start y=input('Please key in the last number for this stack: ') #Input for stop start = int(x) stop = int(y) values = [dict1[k] for k in range(start, stop + 1) if k in dict1] #Call the values in range print('The subject(s) for this section: ') for i in values: #Print the values in range print (i) output = '\n'.join (values) pyperclip.copy(output) </code></pre> <p>It's working as it should within python, so I compiled it to .exe using Pyinstaller.</p> <p>I managed to have an exe file now but I'm struggling with the import of pyperclip.</p> <p>the exe works except for that last command. I tried -p dir and also --hidden-import pyperclip.</p> <p>I ran it with -d and the debug I get is:</p> <pre><code>PyInstaller Bootloader 3.x LOADER: executable is C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck\deweycheck.exe LOADER: homepath is C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck LOADER: _MEIPASS2 is NULL LOADER: archivename is C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck\deweycheck.exe LOADER: No need to extract files to run; setting extractionpath to homepath LOADER: SetDllDirectory(C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck) LOADER: Already in the child - running user's code. LOADER: Python library: C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck\python35.dll LOADER: Loaded functions from Python library. LOADER: Manipulating environment (sys.path, sys.prefix) LOADER: Pre-init sys.path is C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck\base_library.zip;C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck LOADER: sys.prefix is C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck LOADER: Setting runtime options LOADER: Initializing python LOADER: Overriding Python's sys.path LOADER: Post-init sys.path is C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck\base_library.zip;C:\Users\aless\AppData\Local\Programs\Python\Python35\dist\deweycheck LOADER: Setting sys.argv LOADER: setting sys._MEIPASS LOADER: importing modules from CArchive LOADER: extracted struct LOADER: callfunction returned... LOADER: extracted pyimod01_os_path LOADER: callfunction returned... LOADER: extracted pyimod02_archive LOADER: callfunction returned... LOADER: extracted pyimod03_importers LOADER: callfunction returned... LOADER: Installing PYZ archive with Python modules. LOADER: PYZ archive: out00-PYZ.pyz LOADER: Running pyiboot01_bootstrap.py LOADER: Running dewey.py </code></pre> <p>I'm not sure how to proceed right now :\ any input?</p>
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')) df['E']= df2 </code></pre> <p>here's the code outside of a class:</p> <pre><code>styles = [1, 3, 7] def train_model(X, y): clf = LogisticRegression(random_state=0, C=1, penalty='l1') clf.fit(X, y) for value in styles: X = df[['A', 'B', 'C']][df['D']==value] y = df['E'][df['D']==value] train_model(X, y) </code></pre> <p>I need to translate this into a class, like so:</p> <pre><code>class BaseTrainer(object): """ Abstract class to define run order """ def run(self): self.import_training_data() for value in [1, 3, 7]: self.extract_variables(value) self.train_model() # I think there's a better way to do this if value = 1: pickle_model(self.model, self.model_file) if value = 3: pickle_model(self.model, self.model_file2) if value = 7: pickle_model(self.model, self.model_file3) class ModelTrainer(BaseTrainer): """ Class to train model for predicting Traits of Customers """ def __init__(self): self.model_file = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_modern.pkl' self.model_file2 = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_traditional.pkl' self.model_file3 = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_rustic.pkl' def import_training_data(self): _execute_vertica_query('get_training_data') self.df = _read_data('training_data.csv') self.df.columns = [['CuID', 'StyID', 'StyName', 'Filter', 'PropItemsViewed', 'PropItemsOrdered', 'DaysSinceView']] def extract_variables(self, value): # Take subset of columns for training purposes (remove CuID, Segment) self.X = self.df[['PropItemsViewed', 'PropItemsOrdered', 'DaysSinceView']][df['StyID']==value] y = self.df[['Filter']][df['StyID']==value] self.y = y.flatten() def train_model(self): self.model = LogisticRegression(C=1, penalty='l1') self.model.fit(self.X, self.y) </code></pre> <p>I think there must be a better way to structure it or run through the three different values in the styles list. But I don't even know what to search for to improve this. Any suggestions, pointers, etc. would be appreciated! </p>
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')) df['E']= df2 </code></pre> <p>here's the code outside of a class:</p> <pre><code>styles = [1, 3, 7] def train_model(X, y): clf = LogisticRegression(random_state=0, C=1, penalty='l1') clf.fit(X, y) for value in styles: X = df[['A', 'B', 'C']][df['D']==value] y = df['E'][df['D']==value] train_model(X, y) </code></pre> <p>I need to translate this into a class, like so:</p> <pre><code>class BaseTrainer(object): """ Abstract class to define run order """ def run(self): self.import_training_data() for value in [1, 3, 7]: self.extract_variables(value) self.train_model() # I think there's a better way to do this if value = 1: pickle_model(self.model, self.model_file) if value = 3: pickle_model(self.model, self.model_file2) if value = 7: pickle_model(self.model, self.model_file3) class ModelTrainer(BaseTrainer): """ Class to train model for predicting Traits of Customers """ def __init__(self): self.model_file = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_modern.pkl' self.model_file2 = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_traditional.pkl' self.model_file3 = '/wayfair/mnt/crunch_buckets/central/data_science/customer_style/train_rustic.pkl' def import_training_data(self): _execute_vertica_query('get_training_data') self.df = _read_data('training_data.csv') self.df.columns = [['CuID', 'StyID', 'StyName', 'Filter', 'PropItemsViewed', 'PropItemsOrdered', 'DaysSinceView']] def extract_variables(self, value): # Take subset of columns for training purposes (remove CuID, Segment) self.X = self.df[['PropItemsViewed', 'PropItemsOrdered', 'DaysSinceView']][df['StyID']==value] y = self.df[['Filter']][df['StyID']==value] self.y = y.flatten() def train_model(self): self.model = LogisticRegression(C=1, penalty='l1') self.model.fit(self.X, self.y) </code></pre> <p>I think there must be a better way to structure it or run through the three different values in the styles list. But I don't even know what to search for to improve this. Any suggestions, pointers, etc. would be appreciated! </p>
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_model() pickle_model(self.model, model_file) </code></pre> <p>As for the design it could be improved</p> <p>For instance, define your model files as a list directly:</p> <pre><code>self.model_list = map(lambda x : os.path.join('/wayfair/mnt/crunch_buckets/central/data_science/customer_style',x),['train_modern.pkl','train_traditional','train_rustic.pkl']) </code></pre> <p>Which gives:</p> <pre><code>def run(self): self.import_training_data() for value,model_file in zip([1, 3, 7],self.model_file_list): self.extract_variables(value) self.train_model() </code></pre>
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 together? It is my understanding that the user would still have to install the libraries separately or I need to write a separate makefile that runs a script to install it while my distributable is being installed. Am I right in this opinion? Advice would be greatly appreciated. Also a explanation how it works internally given your answer. Thanks a lot! Appreciate your time! </p>
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> <p>You can use:</p> <pre><code>pip freeze </code></pre> <p>To find which modules you have installed</p> <p>EDIT: This is implied your script is small and not packaged inside a .dmg or .exe file. </p>
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 together? It is my understanding that the user would still have to install the libraries separately or I need to write a separate makefile that runs a script to install it while my distributable is being installed. Am I right in this opinion? Advice would be greatly appreciated. Also a explanation how it works internally given your answer. Thanks a lot! Appreciate your time! </p>
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.pyinstaller.org" rel="nofollow">http://www.pyinstaller.org</a></p>
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, "PhoneB1,PhoneB2", 2 C,23, "PhoneC" , 1 </code></pre> <p>I was trying something like :</p> <pre><code>pd.pivot_table(phonedf, index=['name','age','phonenumbers'], values=['phonenumbers'], aggfunc=np.size) </code></pre> <p>however I want the phone numbers to be concatenated as part of aggfunc. Any Suggestions ?</p>
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 PhoneB1,PhoneB2 2 # C 23 PhoneC 1 </code></pre> <p>Or a shorter version according to @root and @Jon Clements:</p> <pre><code>df.groupby(['name', 'age'])['phonenumber'].agg({'phonecount': 'nunique', 'phonenumber': ','.join}) </code></pre>
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-index-value? For example, a color list would be [(128, 128, 0), (240, 128, 0), ...n], and all (240, 128, 0) pixels in the numpy array would be converted to index value in unique mapping (= 1).</p> <p>How to do this efficiently and with less code? Here's one solution I came up with, but it's quite slow.</p> <pre><code># Input imgs.shape = (N, 3, H, W), where (N = count, W = width, H = height) def unique_map_pixels(imgs): original_shape = imgs.shape # imgs.shape = (N, H, W, 3) imgs = imgs.transpose(0, 2, 3, 1) # tupleview.shape = (N, H, W, 1); contains tuples [(R, G, B), (R, G, B)] tupleview = imgs.reshape(-1, 3).view(imgs.dtype.descr * imgs.shape[3]) # get unique pixel values in images, [(R, G, B), ...] uniques = list(np.unique(tupleview)) # map uniques into hashed list ({"RXBXG": 0, "RXBXG": 1}, ...) uniqmap = {} idx = 0 for x in uniques: uniqmap["%sX%sX%s" % (x[0], x[1], x[2])] = idx idx = idx + 1 if idx &gt;= np.iinfo(np.uint16).max: raise Exception("Can handle only %s distinct colors" % np.iinfo(np.uint16).max) # imgs1d.shape = (N), contains RGB tuples imgs1d = tupleview.reshape(np.prod(tupleview.shape)) # imgsmapped.shape = (N), contains uniques-index values imgsmapped = np.empty((len(imgs1d))).astype(np.uint16) # map each pixel into unique-pixel-ID idx = 0 for x in imgs1d: str = ("%sX%sX%s" % (x[0], x[1] ,x[2])) imgsmapped[idx] = uniqmap[str] idx = idx + 1 imgsmapped.shape = (original_shape[0], original_shape[2], original_shape[3]) # (N, H, W) return (imgsmapped, uniques) </code></pre> <p>Testing it:</p> <pre><code>import numpy as np n = 30 pixelvalues = (np.random.rand(10)*255).astype(np.uint8) images = np.random.choice(pixelvalues, (n, 3, 72, 96)) (mapped, pixelmap) = unique_map_pixels(images) assert len(pixelmap) == mapped.max()+1 assert mapped.shape == (len(images), images.shape[2], images.shape[3]) assert pixelmap[mapped[int(n*0.5)][60][81]][0] == images[int(n*0.5)][0][60][81] print("Done: %s" % list(mapped.shape)) </code></pre>
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,return_index=True,return_inverse=True) return tags.reshape(N,H,W), img2D[firstidx] </code></pre> <p>Runtime test and verification -</p> <pre><code>In [24]: # Setup inputs (3x smaller than original ones) ...: N,H,W = 200,24,32 ...: imgs = np.random.randint(0,10,(N,3,H,W)) ...: In [25]: %timeit unique_map_pixels(imgs) 1 loop, best of 3: 2.21 s per loop In [26]: %timeit unique_map_pixels_vectorized(imgs) 10 loops, best of 3: 37 ms per loop ## 60x speedup! In [27]: map1,unq1 = unique_map_pixels(imgs) ...: map2,unq2 = unique_map_pixels_vectorized(imgs) ...: In [28]: np.allclose(map1,map2) Out[28]: True In [29]: np.allclose(np.array(map(list,unq1)),unq2) Out[29]: True </code></pre>
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</p> <pre><code>import matplotlib.pyplot as plt plt.scatter([], []) plt.show() </code></pre> <p>script fails to produce a plot window. The backend that I see in the virtualenv using:</p> <pre><code>import matplotlib print matplotlib.rcParams['backend'] </code></pre> <p>is <code>agg</code>, which is apparently the root cause of the issue. If I check the backend in my system-wide installation, I get <code>Qt4Agg</code> (and the above script when run shows a plot window just fine).</p> <p>There are already several similar questions in SO, and I've tried the solutions given in all of them.</p> <ol> <li><p><a href="http://stackoverflow.com/questions/21688409/matplotlib-plt-show-isnt-showing-graph">Matplotlib plt.show() isn&#39;t showing graph</a></p> <p>Tried to create the virtualenv with the <a href="https://virtualenv.pypa.io/en/latest/reference/?highlight=system%20site#cmdoption--system-site-packages" rel="nofollow">--system-site-packages</a> option. No go.</p></li> <li><p><a href="http://askubuntu.com/questions/785505/how-to-ensure-matplotlib-in-a-python-3-virtualenv-uses-the-tkagg-backend">How to ensure matplotlib in a Python 3 virtualenv uses the TkAgg backend?</a></p> <p>Installed <code>sudo apt install tk-dev</code>, then re-installed using <code>pip --no-cache-dir install -U --force-reinstall matplotlib</code>. The backend still shows as <code>agg</code>.</p></li> <li><p><a href="http://stackoverflow.com/questions/9054718/matplotlib-doesnt-display-graph-in-virtualenv">Matplotlib doesn&#39;t display graph in virtualenv</a></p> <p>Followed install instructions given in <a href="http://stackoverflow.com/a/16856545/1391441">this answer</a>, did nothing (the other answer involves using <code>easy_install</code>, which <a href="http://stackoverflow.com/q/3220404/1391441">I will not do</a>)</p></li> <li><p><a href="http://stackoverflow.com/questions/13151514/matplotlib-plot-window-wont-appear">matplotlib plot window won&#39;t appear</a></p> <p>The solution given here is to <em>"install a GUI library (one of Tkinter, GTK, QT4, PySide, Wx)"</em>. I don't know how to do this. Furthermore, if I use:</p> <pre><code>import matplotlib.rcsetup as rcsetup print(rcsetup.all_backends) </code></pre> <p>I get:</p> <pre><code>[u'GTK', u'GTKAgg', u'GTKCairo', u'MacOSX', u'Qt4Agg', u'Qt5Agg', u'TkAgg', u'WX', u'WXAgg', u'CocoaAgg', u'GTK3Cairo', u'GTK3Agg', u'WebAgg', u'nbAgg', u'agg', u'cairo', u'emf', u'gdk', u'pdf', u'pgf', u'ps', u'svg', u'template'] </code></pre> <p>meaning that all those backends <em>are</em> available in my system (?).</p></li> <li><p><a href="http://stackoverflow.com/questions/7534453/matplotlib-does-not-show-my-drawings-although-i-call-pyplot-show">matplotlib does not show my drawings although I call pyplot.show()</a></p> <p>My <code>matplotlibrc</code> file shows the line:</p> <pre><code>backend : Qt4Agg </code></pre> <p>I don't know how to make the virtualenv aware of this?</p></li> </ol> <p>Some of the solutions involve creating links to the system version of <code>matplotlib</code> (<a href="http://stackoverflow.com/a/32439941/1391441">here</a> and <a href="http://stackoverflow.com/a/35780169/1391441">here</a>), which I don't want to do. I want to use the version of <code>matplotlib</code> installed in the <code>virtualenv</code>. </p> <p>If I try to set the backend with:</p> <pre><code>import matplotlib matplotlib.use('GTKAgg') </code></pre> <p>I get <code>ImportError: Gtk* backend requires pygtk to be installed</code> (same with <code>GTK</code>). But if I do <code>sudo apt-get install python-gtk2 python-gtk2-dev</code>, I see that they are both installed.</p> <p>Using:</p> <pre><code>import matplotlib matplotlib.use('Qt4Agg') </code></pre> <p>(or <code>Qt5Agg</code>) results in <code>ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5, or PySide package to be installed, but it was not found.</code> Not sure if I should install some package?</p> <p>Using:</p> <pre><code>import matplotlib matplotlib.use('TkAgg') </code></pre> <p>results in <code>ImportError: No module named _tkinter</code>, but <code>sudo apt-get install python-tk</code> says that it is installed.</p> <p>Using:</p> <pre><code>import matplotlib matplotlib.use('GTKCairo') </code></pre> <p>results in <code>ImportError: No module named gtk</code>. So I try <code>sudo apt-get install libgtk-3-dev</code> but it says that it already installed.</p> <p>How can I make the virtualenv use the same backend that my system is using?</p>
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 backend is indeed <code>TkAgg</code>, run</p> <pre><code>python -c 'import matplotlib as mpl; print(mpl.get_backend())' </code></pre> <p>and you should see <code>TkAgg</code>.</p>
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-04-30 4 5 2016-05-31 </code></pre> <p>how to shift column A backwards by number of months as value from column B</p> <p>to the effect of </p> <pre><code> df['A'] - pd.DateOffset(months=value_from_column_B) </code></pre>
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-04-30 4 5 2016-05-31 </code></pre> <p>how to shift column A backwards by number of months as value from column B</p> <p>to the effect of </p> <pre><code> df['A'] - pd.DateOffset(months=value_from_column_B) </code></pre>
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, milliseconds=None, microseconds=None, nanoseconds=None): years = np.asarray(years) - 1970 months = np.asarray(months) - 1 days = np.asarray(days) - 1 types = ('&lt;M8[Y]', '&lt;m8[M]', '&lt;m8[D]', '&lt;m8[W]', '&lt;m8[h]', '&lt;m8[m]', '&lt;m8[s]', '&lt;m8[ms]', '&lt;m8[us]', '&lt;m8[ns]') vals = (years, months, days, weeks, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) return sum(np.asarray(v, dtype=t) for t, v in zip(types, vals) if v is not None) df = pd.DataFrame({'A': pd.date_range(start='1-1-2016',periods=5, freq='M')}) df['B'] = df['A'].dt.month df['C'] = compose_date(years=df['A'].dt.year, months=df['A'].dt.month-df['B'], days=df['A'].dt.day) print(df) # A B C # 0 2016-01-31 1 2015-12-31 # 1 2016-02-29 2 2015-12-29 # 2 2016-03-31 3 2015-12-31 # 3 2016-04-30 4 2015-12-30 # 4 2016-05-31 5 2015-12-31 </code></pre> <hr> <pre><code>In [135]: df = pd.DataFrame({'A': pd.date_range(start='1-1-2016', periods=10**3, freq='M')}) In [136]: df['B'] = df['A'].dt.month In [137]: %timeit compose_date(years=df['A'].dt.year, months=df['A'].dt.month-df['B'], days=df['A'].dt.day) 10 loops, best of 3: 41.2 ms per loop In [138]: %timeit df[['A', 'B']].apply(lambda x: x['A'] - pd.DateOffset(months=x['B']), axis=1) 10 loops, best of 3: 169 ms per loop </code></pre>
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 &lt;input PDF file | - | PROMPT&gt; [ &lt;operation&gt; &lt;operation arguments&gt; ] [ output &lt;output filename | - | PROMPT&gt; ] [ flatten ] Where: &lt;operation&gt; may be empty, or: [generate_fdf | fill_form |dump_data | dump_data_fields ] OPTIONS --help, -h show summary of options. &lt;input PDF files | - | PROMPT&gt; An input PDF file. Use - to pass a single PDF into pdftk via stdin. [&lt;operation&gt; &lt;operation arguments&gt;] Available operations are: generate_fdf,fill_form, dump_data,dump_data_fields Some operations takes additional arguments, described below. generate_fdf Reads a single, input PDF file and generates an FDF file suitable for fill_form out of it to the given output filename or (if no output is given) to stdout. Does not create a new PDF. fill_form &lt;FDF data filename | - | PROMPT&gt; Fills the input PDF's form fields with the data from an FDF file, or stdin. Enter the data filename after fill_form, or use - to pass the data via stdin, like so: ./pdf_form.py form.pdf fill_form data.fdf output form.filled.pdf After filling a form, the form fields remain interactive unless flatten is used. flatten merges the form fields with the PDF pages. You can also use flatten alone, as shown: ./pdf_form.py form.pdf fill_form data.fdf output out.pdf flatten or: ./pdf_form.py form.filled.pdf output out.pdf flatten dump_data Reads a single, input PDF file and reports various statistics, to the given output filename or (if no output is given). dump_data_fields Reads a single, input PDF file and reports form field statistics to the given output filename [flatten] Use this option to merge an input PDF's interactive form fields and their data with the PDF's pages. </code></pre> <p> I am currently parsing these options using the following (messy) code</p> <pre><code>def parse(arg): """ Parses commandline arguments. """ #checking that request is valid if len(arg) == 1: raise ValueError(info()) if arg[1] in ('-h', '--help'): print(info(verbose=True)) return if len(arg) == 2: raise ValueError(info()) path = arg[1] if path == 'PROMPT': path = input('Please enter a filename for an input document:') func = arg[2] if func == 'fill_form': fdf = arg[3] if len(arg) &gt; 5 and arg[4] == 'output': out = arg[5] else: out = '-' else: fdf = None if len(arg) &gt; 4 and arg[3] == 'output': out = arg[4] else: out = '-' if out == 'PROMPT': out = input('Output file: ') flatten = 'flatten' in arg return path, func, fdf, out, flatten </code></pre> <p>Is there a better way to do this with either argparse or docopt?</p>
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='ftd') parser.add_argument('--path') if args.path in ['PROMPT']: args.path = input... </code></pre>
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] [error] [client 72.219.147.5] mod_wsgi (pid=28751): Exception occurred processing WSGI script '/var/www/html/lumos/wsgi.py'. [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] Traceback (most recent call last): [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/wsgi.py", line 11, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import app [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/app.py", line 2, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import main [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/main.py", line 1, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import mod_one [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/mod_one.py", line 1, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import cv2 [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] ImportError: No module named cv2 </code></pre> <p>This is where the cv2.so file is located (<code>sudo find / -name "cv2.so"</code>):</p> <pre><code>/var/www/html/lumos/opencv/build/lib/cv2.so /usr/local/lib/python2.7/dist-packages/cv2.so </code></pre> <p>And I have set the WSGI Python Path to be where that file is located:</p> <pre><code>WSGIPythonPath /usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ </code></pre> <p>I know opencv is installed correctly because when I do the following, there's no error:</p> <pre><code>$ python &gt;&gt;&gt;import cv2 #no import error &gt;&gt;&gt; </code></pre> <p>When I installed mod_wsgi, this was used:</p> <pre><code>mod_wsgi-python26-3.2-6.11.amzn1.x86_64 </code></pre> <p>Here is my wsgi.py file</p> <pre><code>import os, sys sys.path.insert(0, "/var/www/html/lumos") import bottle import app application = bottle.default_app() #using bottle.py web-framework </code></pre> <p>Here is my httpd.conf:</p> <pre><code>WSGISocketPrefix /var/run/wsgi WSGIPythonPath /usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ &lt;VirtualHost *&gt; ServerName lumos.website.me DocumentRoot /var/www/html/lumos WSGIDaemonProcess lumos threads=5 WSGIScriptAlias / /var/www/html/lumos/app.wsgi &lt;Directory "/var/www/html/lumos"&gt; WSGIProcessGroup lumos WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>When I run <code>python -V</code>, I get <code>Python 2.7.10.</code></p> <p>How can I make mod_wsgi work with opencv? Any help is appreciated.</p>
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 'python-path' option to the <a href="https://code.google.com/archive/p/modwsgi/wikis/ConfigurationDirectives.wiki#WSGIDaemonProcess" rel="nofollow">WSGIDaemonProcess directive</a> instead.</p> <p>In my <code>httpd.conf</code> file, I deleted this:</p> <pre><code>WSGIPythonPath /usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ </code></pre> <p>And changed this:</p> <pre><code>WSGIDaemonProcess lumos threads=5 </code></pre> <p>To this:</p> <pre><code>WSGIDaemonProcess lumos threads=5 python-path=/usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ </code></pre> <p>So my final <code>httpd.conf</code> looks like this:</p> <pre><code>&lt;VirtualHost *&gt; ServerName lumos.website.me DocumentRoot /var/www/html/lumos WSGIDaemonProcess lumos threads=5 python-path=/usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ WSGIScriptAlias / /var/www/html/lumos/wsgi.py &lt;Directory "/var/www/html/lumos"&gt; WSGIProcessGroup lumos WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>And now cv2 works.</p>
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] [error] [client 72.219.147.5] mod_wsgi (pid=28751): Exception occurred processing WSGI script '/var/www/html/lumos/wsgi.py'. [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] Traceback (most recent call last): [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/wsgi.py", line 11, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import app [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/app.py", line 2, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import main [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/main.py", line 1, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import mod_one [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] File "/var/www/html/lumos/mod_one.py", line 1, in &lt;module&gt; [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] import cv2 [Tue Aug 16 18:22:57 2016] [error] [client 72.219.147.5] ImportError: No module named cv2 </code></pre> <p>This is where the cv2.so file is located (<code>sudo find / -name "cv2.so"</code>):</p> <pre><code>/var/www/html/lumos/opencv/build/lib/cv2.so /usr/local/lib/python2.7/dist-packages/cv2.so </code></pre> <p>And I have set the WSGI Python Path to be where that file is located:</p> <pre><code>WSGIPythonPath /usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ </code></pre> <p>I know opencv is installed correctly because when I do the following, there's no error:</p> <pre><code>$ python &gt;&gt;&gt;import cv2 #no import error &gt;&gt;&gt; </code></pre> <p>When I installed mod_wsgi, this was used:</p> <pre><code>mod_wsgi-python26-3.2-6.11.amzn1.x86_64 </code></pre> <p>Here is my wsgi.py file</p> <pre><code>import os, sys sys.path.insert(0, "/var/www/html/lumos") import bottle import app application = bottle.default_app() #using bottle.py web-framework </code></pre> <p>Here is my httpd.conf:</p> <pre><code>WSGISocketPrefix /var/run/wsgi WSGIPythonPath /usr/local/lib/python2.7/site-packages/:/usr/local/lib/python2.7/dist-packages/ &lt;VirtualHost *&gt; ServerName lumos.website.me DocumentRoot /var/www/html/lumos WSGIDaemonProcess lumos threads=5 WSGIScriptAlias / /var/www/html/lumos/app.wsgi &lt;Directory "/var/www/html/lumos"&gt; WSGIProcessGroup lumos WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>When I run <code>python -V</code>, I get <code>Python 2.7.10.</code></p> <p>How can I make mod_wsgi work with opencv? Any help is appreciated.</p>
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. First up you are still running the wrong Python version and second, any extension modules in those directories will likely fail and possibly crash the processes.</p> <p>You must uninstall the mod_wsgi you are using from system packages and install a version compiled for Python 2.7. Because you are using a non standard Python installation you likely will need to build mod_wsgi from source code.</p>
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.imgur.com/OBlSY.png" alt="enter image description here"></a></p> <p>As you can see guys it shows with a line break and I need it shows togetter.</p> <p>The problem is that i need to make it like this (one, one) togetter because I need to use two styles, the issue here is that I'm using arial narrrow so if I use italic or bold I need to use each one by separate because the typography does not alow me to use "&lt; i >italic text&lt; /i > ", so I need to use two different styles that actually works fine by separate.</p> <p>how can I achive this?</p> <pre><code>cursiva = ParagraphStyle('cursiva') cursiva.fontSize = 8 cursiva.fontName= "Arialni" incertidumbre=[] incertidumbre.extend([Paragraph("one", cursiva), Paragraph("one", cursiva)]) </code></pre> <p>Thank you guys</p>
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>&lt;i&gt;</code> and <code>&lt;b&gt;</code> work.</p> <p>So you probably already managed to add a custom font, so the first part should look familiar, the final line is probably the missing link. It is registering the combination of these fonts a family. </p> <pre><code>from reportlab.pdfbase.pdfmetrics import registerFontFamily pdfmetrics.registerFont(TTFont('Arialn', 'Arialn.ttf')) pdfmetrics.registerFont(TTFont('Arialnb', 'Arialnb.ttf')) pdfmetrics.registerFont(TTFont('Arialni', 'Arialni.ttf')) pdfmetrics.registerFont(TTFont('Arialnbi', 'Arialnbi.ttf')) registerFontFamily('Arialn',normal='Arialn',bold='Arialnb',italic='Arialni',boldItalic='Arialnbi') </code></pre>
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, mod_wsgi 3.3 and both Python 2.7 and Django 1.9 in virtualenv.</p> <h2>The problem</h2> <p>The issue I am running into is hooking the Django App to my domain's subdirectory (www.abc.example.com/FR/) but I am running into problems when configuring apache's httpd.conf where my added settings do not seem to be saved. I have run the following commands as per the httpd.conf's comments on making sure changes are saved upon restart:</p> <pre><code>/usr/local/cpanel/bin/apache_conf_distiller --update /usr/local/cpanel/bin/build_apache_conf </code></pre> <p>The guides that I have used have lead me to the following code: * note that '~' is representative of /home/[username]</p> <p><strong>httpd.conf</strong></p> <pre><code>LoadModule wsgi_module extramodules/mod_wsgi.so </code></pre> <p>...</p> <pre><code>WSGIScriptAlias /FR ~/public_html/FR/django.wsgi WSGIPythonPath ~/public_html/FR &lt;Directory ~/mydjango/IFTP&gt; &lt;Files wsgi.py&gt; Order deny,allow Allow from all &lt;/Files&gt; &lt;/Directory&gt; </code></pre> <p><strong>django.wsgi</strong> at ~/public_html/FR/django.wsgi</p> <pre><code>import os import sys sys.path.append('~/mydjango') sys.path.append('~/mydjango/IFTP') os.environ['DJANGO_SETTINGS_MODULE'] = 'IFTP.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p><strong>wsgi.py</strong> at ~/mydjango/IFTP/wsgi.py</p> <pre><code>import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "IFTP.settings") application = get_wsgi_application() </code></pre> <h2>Edit 1:</h2> <p>My apologies, I should have further specified that the problem is that these settings are not taking effect. When I go to www.abc.example.com/FR/ I encounter a 404 not found so the wsgi script is either misconfigured or not setup properly, which is where I need assistance.</p>
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 WSGIScriptAlias /FR ~/mydjango/IFTP/wsgi.py WSGIPythonPath "~/mydjango/lib/python2.7/site-packages:~/mydjango" WSGIPythonHome ~/mydjango &lt;Directory ~/mydjango/IFTP&gt; &lt;Files wsgi.py&gt; Order deny,allow Allow from all &lt;/Files&gt; &lt;/Directory&gt; </code></pre>
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 tk root = tk.Tk() cv = tk.Canvas(root, height=800, width=800) cv.pack() def onclick(event): item = cv.find_closest(event.x, event.y) current_color = cv.itemcget(item, 'fill') if current_color == 'black': cv.itemconfig(item, fill='white') else: cv.itemconfig(item, fill='black') cv.bind('&lt;Button-1&gt;', onclick) cv.create_line(50, 50, 60, 60, width=2) cv. create_rectangle(80, 80, 100, 100) root.mainloop() </code></pre> <p>In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.</p> <p>Thanks for the help.</p>
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') else: cv.itemconfig(item, fill='black') rectangles = [] root = tk.Tk() cv = tk.Canvas(root, height=800, width=800) cv.pack() cv.bind('&lt;Button-1&gt;', onclick) id_a = cv.create_line(50, 50, 60, 60, width=2) id_b = cv.create_rectangle(80, 80, 100, 100) rectangles.append(id_b) root.mainloop() </code></pre> <p>The main idea of this is you add the items id you want to change color to a global array (global variables are discouraged though). Then when you click with the mouse, the itemcget function will give you the id from the closest item, so you need to check whether this id is inside of the array of your rectangle items.</p>
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 tk root = tk.Tk() cv = tk.Canvas(root, height=800, width=800) cv.pack() def onclick(event): item = cv.find_closest(event.x, event.y) current_color = cv.itemcget(item, 'fill') if current_color == 'black': cv.itemconfig(item, fill='white') else: cv.itemconfig(item, fill='black') cv.bind('&lt;Button-1&gt;', onclick) cv.create_line(50, 50, 60, 60, width=2) cv. create_rectangle(80, 80, 100, 100) root.mainloop() </code></pre> <p>In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.</p> <p>Thanks for the help.</p>
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 a loop or functions, but the base theory won't change. GL with tkinter!</p>
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 tk root = tk.Tk() cv = tk.Canvas(root, height=800, width=800) cv.pack() def onclick(event): item = cv.find_closest(event.x, event.y) current_color = cv.itemcget(item, 'fill') if current_color == 'black': cv.itemconfig(item, fill='white') else: cv.itemconfig(item, fill='black') cv.bind('&lt;Button-1&gt;', onclick) cv.create_line(50, 50, 60, 60, width=2) cv. create_rectangle(80, 80, 100, 100) root.mainloop() </code></pre> <p>In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.</p> <p>Thanks for the help.</p>
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> <p>Another solution is to give each item one or more tags. You can then query the tags for the current item. </p> <p>First, include one or more tags on the items you want to be clickable:</p> <pre><code>cv. create_rectangle(80, 80, 100, 100, tags=("clickable",)) </code></pre> <p>Next, check for the tags on the item you're curious about, and check to see if your tag is in the set of tags for that item:</p> <pre><code>tags = cv.itemcget(item, "tags") if "clickable" in tags: # this item has the "clickable" tag else: # this item does NOT have the "clickable" tag </code></pre> <h2>Create bindings on tags</h2> <p>A third option is to attach the bindings to the tags rather than the canvas as a whole. When you do this, your function will only be called when you click on item with the given tag, eliminating the need to do any sort of runtime check:</p> <pre><code>cv.tag_bind("clickable", "&lt;1&gt;", onclick) </code></pre>
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 tk root = tk.Tk() cv = tk.Canvas(root, height=800, width=800) cv.pack() def onclick(event): item = cv.find_closest(event.x, event.y) current_color = cv.itemcget(item, 'fill') if current_color == 'black': cv.itemconfig(item, fill='white') else: cv.itemconfig(item, fill='black') cv.bind('&lt;Button-1&gt;', onclick) cv.create_line(50, 50, 60, 60, width=2) cv. create_rectangle(80, 80, 100, 100) root.mainloop() </code></pre> <p>In this code the program changes the fill colour for any object. I would want it to change it only for rectangles.</p> <p>Thanks for the help.</p>
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" rel="nofollow">item specifiers</a>.</p> <p>Here is how it would be:</p> <pre><code>import tkinter as tk def onclick(event): global rectangles item = cv.find_closest(event.x, event.y) if 'rect' in cv.gettags(item): current_color = cv.itemcget(item, 'fill') if current_color == 'black': cv.itemconfig(item, fill='white') else: cv.itemconfig(item, fill='black') rectangles = [] root = tk.Tk() cv = tk.Canvas(root, height=800, width=800) cv.pack() cv.bind('&lt;Button-1&gt;', onclick) id_a = cv.create_line(50, 50, 60, 60, width=2) id_b = cv.create_rectangle(80, 80, 100, 100, tags=('rect')) root.mainloop() </code></pre> <p>I think it's a bit more object oriented in some way. ;)</p>
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/watch?v=dxhNcQ-FDaY" rel="nofollow">https://www.youtube.com/watch?v=dxhNcQ-FDaY</a></p> <pre><code>import pygame from pygame.locals import * import sys class MousePos(object): def __init(self): pygame.init() self.myFont = pygame.font.SysFont("Arial", 24) pygame.display.set_caption("Mouse Events") self.myScreen = pygame.display.set_mode((400, 400), 0 ,32) self.myScreen.fill((255, 255, 255)) pygame.display.update() def coords(self): text = self.myFont.render(str(pygame.mouse.get_pos()), True, (0, 0, 0)) pygame.draw.rect(self.myScreen, (255, 255, 255), (200, 200, 100, 100), 0) self.myScreen.blit(text, (200, 200)) pygame.display.update() if __name__ == "__main__": newMouse = MousePos() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: newMouse.coords() </code></pre>
-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/watch?v=dxhNcQ-FDaY" rel="nofollow">https://www.youtube.com/watch?v=dxhNcQ-FDaY</a></p> <pre><code>import pygame from pygame.locals import * import sys class MousePos(object): def __init(self): pygame.init() self.myFont = pygame.font.SysFont("Arial", 24) pygame.display.set_caption("Mouse Events") self.myScreen = pygame.display.set_mode((400, 400), 0 ,32) self.myScreen.fill((255, 255, 255)) pygame.display.update() def coords(self): text = self.myFont.render(str(pygame.mouse.get_pos()), True, (0, 0, 0)) pygame.draw.rect(self.myScreen, (255, 255, 255), (200, 200, 100, 100), 0) self.myScreen.blit(text, (200, 200)) pygame.display.update() if __name__ == "__main__": newMouse = MousePos() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: newMouse.coords() </code></pre>
-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_ in filters: field_models = {'type': ProductType, 'category': ProductCategory} if filter_['field'] in field_models: model = field_models[filter_['field']] organizations_products = organizations_products.join(model).filter(or_( model.code.ilike('%{}%'.format(escape_like(filter_['value']))), model.description.ilike('%{}%'.format(escape_like(filter_['value']))) )) else: field = getattr(Product, filter_['field']) organizations_products = organizations_products.filter( field.ilike('%{}%'.format(escape_like(filter_['value'])))) </code></pre>
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 performance-wise (unless you're on PostgreSQL and have a trigram index, in which case ignore this). You're much better served by using the fulltext search features of your DB.</p>
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_ in filters: field_models = {'type': ProductType, 'category': ProductCategory} if filter_['field'] in field_models: model = field_models[filter_['field']] organizations_products = organizations_products.join(model).filter(or_( model.code.ilike('%{}%'.format(escape_like(filter_['value']))), model.description.ilike('%{}%'.format(escape_like(filter_['value']))) )) else: field = getattr(Product, filter_['field']) organizations_products = organizations_products.filter( field.ilike('%{}%'.format(escape_like(filter_['value'])))) </code></pre>
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(ProductCategory) return stmt def get_exprs(field, value): def _ilike_expr(x): return '%{}%'.format(escape_like(x)) model_dict = {'type': ProductType, 'category': ProductCategory} model = model_dict[field] stmt = organizations_products.join(model) try: return [model.code.ilike(_ilike_expr(value)), model.description.ilike(_ilike_expr(value))] except KeyError: return [getattr(Product, field).ilike(_ilike_expr(value))] organizations_products = get_joined_stmt(filters, organizations_products) where_exprs = [] for filter_ in filters.items(): where_exprs.extend(get_exprs(**filter_)) organizations_products = organizations_products.filter(or_(*where_exprs)) </code></pre>
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&gt;&gt;")) </code></pre> <p>Just a simple AIML kernel. Is it something wrong with it?</p>
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 &lt;br&gt; brainLoaded = False forceReload = False while not brainLoaded: if forceReload or (len(sys.argv) &gt;= 2 and sys.argv[1] == "reload"): kern.bootstrap(learnFiles="Database.xml", commands="load aiml b") brainLoaded = True kern.saveBrain("Cache.brn") else: # Attempt to load the brain file. If it fails, fall back on the Reload try: # It is our cache file. kern.bootstrap(brainFile = "Cache.brn") brainLoaded = True except: forceReload = True # Enter the main input/output loop. print "Enter your message for the chatbot" while(True): print kern.respond(raw_input("&gt; ")) </code></pre> <p>Note: You need to create a folder Database where you place your AIML files and a file Database.xml</p>
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&gt;&gt;")) </code></pre> <p>Just a simple AIML kernel. Is it something wrong with it?</p>
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>&lt;category&gt; &lt;pattern&gt;*&lt;/pattern&gt; &lt;template&gt; Sorry. I didn't quite get that. &lt;/template&gt; &lt;/category&gt; </code></pre>
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 samples greater influence than others.) So the workflow is standard-- fit each model to a training subset, test each model on a heldout development set to see if I should use the weights or not. My code is this: </p> <pre><code>clf = svm.SVC( kernel = 'rbf', gamma = .001) ## initialize the model- i only do this once! clf.fit(X_train, y_train) ## fit the model/do the optimization accuracy[name + "_no_weights"] = clf.score(X_test, y_test) ## store results clf.fit(X_train, y_train, sample_weight = sample_weight_test) ## fit the model/do the optimization w/ different regularization accuracy[name + "_w_weights"] = clf.score(X_test, y_test) ## store results </code></pre> <p>Notice if I were to test which kernel to use I would have to re-initialize the classifier by redefining <code>clf</code>. The point is, above I'm training the same classifier in both cases but I don't re-initialize the classifier. So it could be that on the second time I call <code>.fit</code> its parameters are already initialized (not randomly, but from previously training). This would mean the results after the second <code>.fit</code> method could have an unfair advantage-- their starting point for the optimization was very close to a good decision boundary. </p> <p>Anybody know how this works or have suggestions? </p>
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 sklearn it is even more obvious, as its .fit method does not even pass a current lagrange multipliers, it simply calls external, low-level implementation of SVM solver.</p>
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") group.add_argument("--c", action="store_true") </code></pre> <p>Let's call my program argparse_ex.py. I want <code>argparse.py</code> (with no arguments) and <code>argparse.py --a</code> to return the same output.</p>
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'], default='a') </code></pre> <p>If you need it to be a positional argument [which I don't recommend, optional arguments should be <em>options</em>] then you can achieve it like this instead:</p> <pre><code>parser.add_argument("thing", choices=['a', 'b', 'c'], nargs='?', default='a') </code></pre> <p>By the way, it will be a bad idea to call your script <code>argparse.py</code> because then you may not be able to <code>import argparse</code> properly. </p>
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") group.add_argument("--c", action="store_true") </code></pre> <p>Let's call my program argparse_ex.py. I want <code>argparse.py</code> (with no arguments) and <code>argparse.py --a</code> to return the same output.</p>
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 parsing is all done whether any of the options has been selected or not.</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='') occupation = models.CharField(max_length=100, blank=True, default='') gender = models.CharField(max_length=50, blank=True, default='') dateOfBirth = models.DateField(blank=True, default=date.today) address = AddressField(blank=True, null=True) </code></pre> <p>Address is a non-model field. I also have this serializer: </p> <pre><code>class PatientSerializer(serializers.Serializer): firstName = serializers.CharField() lastName = serializers.CharField() occupation = serializers.CharField() gender = serializers.CharField() dateOfBirth = serializers.DateField() address = serializers.SerializerMethodField() def create(self, validated_data): """ Create and return a new patient """ return Patient.objects.create(**validated_data) def get_address(self, obj): return obj.address </code></pre> <p>I tried to set it as a SerializerMethodField in my serializer, but this is not working correctly, address is always null. Just for information, I'm using Django-nonrel since I'm using a mongodb database. </p>
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, default='') lastName = models.CharField(max_length=100, blank=True, default='') occupation = models.CharField(max_length=100, blank=True, default='') gender = models.CharField(max_length=50, blank=True, default='') dateOfBirth = models.DateField(blank=True, default=date.today) address = AddressField(blank=True, null=True, editable=False) </code></pre> <p>Hope this helps.</p>
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></pre> <p>Basically any character in between the two "" or nothing in between "". So far I've tried this;</p> <pre><code>regex_example = re.search("\".+?\" [0-9]{3}", line1) print regex_example.group() </code></pre> <p>This will work with line1, but give an error for line2. This is due to the '.' matching any character, but giving an error if no character exists. </p> <p>Is there any way for it to match any character or nothing in between the two ""?</p>
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 a lazy quantifier <code>?</code>. You should also use the raw string flag <code>r</code> and <code>\d</code> for digits. </p> <pre><code>r'"[^"]*" \d{3}' </code></pre>
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></pre> <p>Basically any character in between the two "" or nothing in between "". So far I've tried this;</p> <pre><code>regex_example = re.search("\".+?\" [0-9]{3}", line1) print regex_example.group() </code></pre> <p>This will work with line1, but give an error for line2. This is due to the '.' matching any character, but giving an error if no character exists. </p> <p>Is there any way for it to match any character or nothing in between the two ""?</p>
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 least one digit ''', re.VERBOSE) matches = [m.group(0) \ for line in lines \ for m in rx.finditer(line)] print(matches) # ['"GET /file/ HTTP/1.1" 302', '"" 400'] </code></pre> <p><hr> See <a href="http://ideone.com/1Zjvok" rel="nofollow"><strong>a demo on ideone.com</strong></a>.</p>
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></pre> <p>Basically any character in between the two "" or nothing in between "". So far I've tried this;</p> <pre><code>regex_example = re.search("\".+?\" [0-9]{3}", line1) print regex_example.group() </code></pre> <p>This will work with line1, but give an error for line2. This is due to the '.' matching any character, but giving an error if no character exists. </p> <p>Is there any way for it to match any character or nothing in between the two ""?</p>
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' regex = r'"(.*?)"\s(\d{3})' value = re.findall(regex, logs) output.append(value) print(output) </code></pre>
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 ENV_VAR=/some_path") </code></pre></li> <li><p>I created bash script(env.sh) and run it from python:</p> <pre><code>#!/bin/bash export ENV_VAR=some_path #call it from python os.system("source env.sh") </code></pre></li> <li>I also tried <em>os.putenv()</em> and <em>os.environ</em>["ENV_VAR"] = "some_path"</li> </ol> <blockquote> <p>Is it possible to set(export) environment variable using python, i.e without directly exporting it to shell?</p> </blockquote>
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 it using <code>os.putenv</code> or <code>os.environ</code> has a similar effect; the environment variables are set for the Python process and any children of it.</p> <p>I assume you are trying to have those variables set for the shell that you launch the script from, or globally. That can't work because the shell (or other process) is not a child of the Python script in which you are setting the variable.</p>
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 ENV_VAR=/some_path") </code></pre></li> <li><p>I created bash script(env.sh) and run it from python:</p> <pre><code>#!/bin/bash export ENV_VAR=some_path #call it from python os.system("source env.sh") </code></pre></li> <li>I also tried <em>os.putenv()</em> and <em>os.environ</em>["ENV_VAR"] = "some_path"</li> </ol> <blockquote> <p>Is it possible to set(export) environment variable using python, i.e without directly exporting it to shell?</p> </blockquote>
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 ENV_VAR=/some_path") </code></pre></li> <li><p>I created bash script(env.sh) and run it from python:</p> <pre><code>#!/bin/bash export ENV_VAR=some_path #call it from python os.system("source env.sh") </code></pre></li> <li>I also tried <em>os.putenv()</em> and <em>os.environ</em>["ENV_VAR"] = "some_path"</li> </ol> <blockquote> <p>Is it possible to set(export) environment variable using python, i.e without directly exporting it to shell?</p> </blockquote>
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://docs.python.org/3.5/library/subprocess.html#replacing-the-os-spawn-family" rel="nofollow">Replacing the os.spawn family</a> in <code>subprocess</code> module documentation which provides both usages:</p> <blockquote> <p>Environment example:</p> <pre><code>os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==&gt; Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) </code></pre> </blockquote>
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 &lt;= tn &lt;= 67: o = 'NE' elif 68 &lt;= tn &lt;= 113: o = 'E' elif 114 &lt;= tn &lt;= 158: o = 'SE' elif 159 &lt;= tn &lt;= 203: o = 'S' elif 204 &lt;= tn &lt;= 248: o = 'SW' elif 249 &lt;= tn &lt;= 293: o = 'W' elif 294 &lt;= tn &lt;= 338: o = 'NW' else: o = 'N' return o </code></pre>
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, tn)] </code></pre> <p><code>bisect_left()</code> (very efficiently) finds the index into which you'd insert <code>tn</code> into the <code>boundaries</code> list; that index is then mapped into the <code>directions</code> list to translate to a string.</p> <p>Bisection only takes up to 4 steps to find the right boundary (<code>log2(len(boundaries))</code>).</p> <p>You could also add 22 and divide the value modulo 360 by 45:</p> <pre><code>directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'] def orientation(tn): index = ((tn + 22) % 360) // 45 return directions[index] </code></pre> <p>However, your original boundaries were not evenly distributed at 45 degrees each, so this gives a slightly different result (your <code>N</code> boundaries span 44 degrees, while <code>E</code> is allotted 46 degrees). Bisection doesn't care about such exceptions; you can shift the boundaries all you like.</p>
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 &lt;= tn &lt;= 67: o = 'NE' elif 68 &lt;= tn &lt;= 113: o = 'E' elif 114 &lt;= tn &lt;= 158: o = 'SE' elif 159 &lt;= tn &lt;= 203: o = 'S' elif 204 &lt;= tn &lt;= 248: o = 'SW' elif 249 &lt;= tn &lt;= 293: o = 'W' elif 294 &lt;= tn &lt;= 338: o = 'NW' else: o = 'N' return o </code></pre>
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 &lt;= tn &lt;= 67: o = 'NE' elif 68 &lt;= tn &lt;= 113: o = 'E' elif 114 &lt;= tn &lt;= 158: o = 'SE' elif 159 &lt;= tn &lt;= 203: o = 'S' elif 204 &lt;= tn &lt;= 248: o = 'SW' elif 249 &lt;= tn &lt;= 293: o = 'W' elif 294 &lt;= tn &lt;= 338: o = 'NW' else: o = 'N' return o </code></pre>
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 &lt;= tn &lt;= 67: o = 'NE' elif 68 &lt;= tn &lt;= 113: o = 'E' elif 114 &lt;= tn &lt;= 158: o = 'SE' elif 159 &lt;= tn &lt;= 203: o = 'S' elif 204 &lt;= tn &lt;= 248: o = 'SW' elif 249 &lt;= tn &lt;= 293: o = 'W' elif 294 &lt;= tn &lt;= 338: o = 'NW' else: o = 'N' return o </code></pre>
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 &lt; 23 else \ "NE" if tn &lt; 68 else \ "E" if tn &lt; 114 else \ "SE" if tn &lt; 159 else \ "S" if tn &lt; 204 else \ "SW" if tn &lt; 249 else \ "W" if tn &lt; 294 else \ "NW" if tn &lt; 339 else \ "N" </code></pre> <p>Obviously this method doesn't generalise to other scenarios, but personally, for your particular problem I would actually prefer this over a more generalisable alternative as it is simple, clear, readable, straightforward code: anyone landing on this definition would know exactly what it does at the blink of an eye, regardless of programming skill. :p</p>
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 errors which raises <code>HTTPError</code> in those cases, but what should I raise if the server just supplies an <code>error</code> key in the JSON response?</p> <p>I am currently using <code>Exception</code> but that feels quite broad, I'd like to know whether there's a better alternative.</p> <p>Regards.</p>
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></pre> <p><code>RemoteServerNotHappyError</code> should probably mention something about what the server's json returned that was not expected by your API client class. Add in the relevant error messages as you see fit. </p> <p>This means users of your library can catch these specific exceptions (which they might know how to handle), without having to catch every exception (they surely don't know how to handle every possible failure mode). </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 Lost :D" @cherrypy.expose def recharge_list(self,carrier, state): details_array=[] small_details_array=[] price_cell_array=[] lst = [] url = "link{}/{}".format(carrier,state) try: if self.t_arr.get(url) is not None: return json.dumps({'data': self.t_arr[url]}) except AttributeError: self.t_arr = {} r = requests.get(url) data = r.text soup = BeautifulSoup(data,"html.parser") table = soup.find('table',{'class':'table'}) s="" detailtext = table.findAll('div',{'class':'detailtext'}) for det in detailtext: details_array.append(det.text) smalldetails = table.findAll('div',{'style':'padding-top:5px'}) for smallDet in smalldetails: small_details_array.append(smallDet.text); price_cells = table.findAll('td', {'class': 'pricecell'}) for price_cell in price_cells: price_cell_array.append(price_cell.text) for i in range(len(details_array)): d_arr = {} d_arr['detail']=details_array[i] temp = small_details_array[i].split('\n') d_arr['talktime'] = temp[1] d_arr['keyword']=temp[3] tempnew = price_cell_array[i].split('\n') d_arr['price'] = tempnew[1] d_arr['validity'] = tempnew[3] # global list lst.append(d_arr) self.t_arr[url] = lst return json.dumps({'data': self.t_arr[url]}) @cherrypy.expose def sms_list(self,carrier, state): details_array=[] price_cell_array=[] lst = [] url = "link/{}/{}".format(carrier,state) try: if self.t_arr.get(url) is not None: return json.dumps({'data': self.t_arr[url]}) except AttributeError: self.t_arr = {} r = requests.get(url) data = r.text soup = BeautifulSoup(data,"html.parser") table = soup.find('div',{'id':'SMS'}) table2 = table.find('table',{'class':'table'}) print(table2) s="" detailtext = table2.findAll('div',{'class':'detailtext'}) for det in detailtext: details_array.append(det.text) smalldetails = table2.findAll('div',{'style':'padding-top:5px'}) price_cells = table.findAll('td', {'class': 'pricecell'}) for price_cell in price_cells: price_cell_array.append(price_cell.text) for i in range(len(details_array)): d_arr = {} d_arr['detail']=details_array[i] tempnew = price_cell_array[i].split('\n') d_arr['price'] = tempnew[1] d_arr['validity'] = tempnew[3] # global list lst.append(d_arr) self.t_arr[url] = lst return json.dumps({'data': self.t_arr[url]}) if __name__ == '__main__': ''' Setting up the Server with Specified Configuration''' cherrypy.config.update({'server.socket_host': '0.0.0.0',}) cherrypy.config.update({'server.socket_port': int(os.environ.get('PORT', '5000')),}) cherrypy.quickstart(Server()) </code></pre> <p>The problem is, when I run my server with <code>recharge_list</code> it works, but then I have to terminate my server from terminal and re-start the server to execute the <code>sms_list</code> function.</p> <p>By my understanding the object once created by <code>Server</code> class is able to execute only the first called function.</p> <p>What should I edit in my code such that I can execute the functions without terminating the server.</p>
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 should I edit in my code such that I can execute the functions without terminating the server.</p> </blockquote> <p>In <code>sms_list</code> (and <strong>not</strong> in <code>recharge_list</code>), replace every instance of <code>t_arr</code> with <code>t_sms_arr</code>.</p>
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 &lt;module&gt; for row in exampleReader: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 4627: ordinal not in range(128) </code></pre> <p>Do anyone have any idea why I get this error? I tried an very easy cvs file from the internet and it worked just fine, but when I try the bigger file it doesn't</p>
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 open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:</p> <pre><code>import csv with open('some.csv', newline='', encoding='utf-8') as f: reader = csv.reader(f) for row in reader: print(row) </code></pre> <p><a href="https://docs.python.org/3/library/csv.html" rel="nofollow">csv modeule docs</a></p>
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]) for r in range(rows): while sum(m[r]) &lt; A: c = randint(0, cols-1) m[r][c] += x for c in range(cols): cant = sum([m[r][c] for r in range(rows)]) while cant &gt; B: r = randint(0, rows-1) if m[r][c] &gt;= x: #I don't want negatives m[r][c] -= x </code></pre> <p>My problem is: I need to satisfy both conditions and, this way, after the second <code>for</code> I won't be sure if the first condition is still met.</p> <p>Any suggestions on how to satisfy both conditions and, of course, with the best execution? I could definitely consider the use of <code>numpy</code></p> <p><strong>Edit (an example)</strong></p> <pre><code>#input m = [[0,0,0], [0,0,0]] A = 20 B = 25 # one desired output (since it chooses random positions) m = [[10,0,15], [15,0,5]] </code></pre> <p><strong>I may need to add</strong> </p> <p>This is for the generation of the random initial population of a genetic algorithm, the restrictions are to make them a possible solution, and I would need to run this like 80 times to get different possible solutions</p>
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 &lt;= B assert val * len(m[0]) &gt;= A # row sums &gt;= 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 in your example anyway.</p>
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]) for r in range(rows): while sum(m[r]) &lt; A: c = randint(0, cols-1) m[r][c] += x for c in range(cols): cant = sum([m[r][c] for r in range(rows)]) while cant &gt; B: r = randint(0, rows-1) if m[r][c] &gt;= x: #I don't want negatives m[r][c] -= x </code></pre> <p>My problem is: I need to satisfy both conditions and, this way, after the second <code>for</code> I won't be sure if the first condition is still met.</p> <p>Any suggestions on how to satisfy both conditions and, of course, with the best execution? I could definitely consider the use of <code>numpy</code></p> <p><strong>Edit (an example)</strong></p> <pre><code>#input m = [[0,0,0], [0,0,0]] A = 20 B = 25 # one desired output (since it chooses random positions) m = [[10,0,15], [15,0,5]] </code></pre> <p><strong>I may need to add</strong> </p> <p>This is for the generation of the random initial population of a genetic algorithm, the restrictions are to make them a possible solution, and I would need to run this like 80 times to get different possible solutions</p>
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]) &lt;= a1: c = randint(0, cols-1) list1[r][c] += x1 for c in range(cols): cant = sum([list1[r][c] for r in range(rows)]) while cant &gt;= b1: r = randint(0, rows-1) if list1[r][c] &gt;= x1: #I don't want negatives list1[r][c] -= x1 good_a_int = 0 for r in range(rows): test1 = sum(list1[r]) &gt; a1 good_a_int += 0 if test1 else 1 if good_a_int == 0: return list1 else: return runner(list1=list1_backup, a1=a1, b1=b1, x1=x1) m2 = runner(m, A, B, x) for row in m: print ','.join(map(lambda x: "{:&gt;3}".format(x), row)) </code></pre>
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]) for r in range(rows): while sum(m[r]) &lt; A: c = randint(0, cols-1) m[r][c] += x for c in range(cols): cant = sum([m[r][c] for r in range(rows)]) while cant &gt; B: r = randint(0, rows-1) if m[r][c] &gt;= x: #I don't want negatives m[r][c] -= x </code></pre> <p>My problem is: I need to satisfy both conditions and, this way, after the second <code>for</code> I won't be sure if the first condition is still met.</p> <p>Any suggestions on how to satisfy both conditions and, of course, with the best execution? I could definitely consider the use of <code>numpy</code></p> <p><strong>Edit (an example)</strong></p> <pre><code>#input m = [[0,0,0], [0,0,0]] A = 20 B = 25 # one desired output (since it chooses random positions) m = [[10,0,15], [15,0,5]] </code></pre> <p><strong>I may need to add</strong> </p> <p>This is for the generation of the random initial population of a genetic algorithm, the restrictions are to make them a possible solution, and I would need to run this like 80 times to get different possible solutions</p>
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 = numpy.ones(n) # the constraint matrix. # This is matrix-multiplied with the current solution candidate # to form the left hand side of a set of normalized # linear inequality constraint equations, i.e. # # x_0 * A_ub[0][0] + x_1 * A_ub[0][1] &lt;= b_0 # x_1 * A_ub[1][0] + x_1 * A_ub[1][1] &lt;= b_1 # ... A_ub = numpy.zeros((2 * m, n)) # row sums. Since the &lt;= inequality is a fixed component, # we just multiply everthing by (-1), i.e. we demand that # the negative sums are smaller than the negative limit -A. # # Assign row ranges all at once, because numpy can do this. for r in xrange(0, m): A_ub[r][r * m:(r + 1) * m] = -1 # We want that the sum of the x in each (flattened) # column is smaller than B # # The manual stepping for the column sums in row-major encoding # is a little bit annoying here. for r in xrange(0, m): for j in xrange(0, m): A_ub[r + m][r + m * j] = 1 # the actual upper limits for the normalized inequalities. b_ub = [-A] * m + [B] * m # hand the linear program to scipy solution = linprog(c, A_ub=A_ub, b_ub=b_ub) # bring the solution into the desired matrix form print numpy.reshape(solution.x, (m, m)) </code></pre> <p><strong>Caveats</strong></p> <ul> <li>I use <code>&lt;=</code>, not <code>&lt;</code> as indicated in your question, because that's what numpy supports.</li> <li>This minimizes the total sum of all values in the target vector. For your use case, you probably want to minimize the distance to the original sample, which the linear program cannot handle, since neither the squared error nor the absolute difference can be expressed using a linear combination (which is what c stands for). For that, you will probably need to go to full <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize" rel="nofollow"><code>minimize()</code></a>. </li> </ul> <p>Still, this should get you rough idea.</p>
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* from codecs import decode from chatrecord import ChatRecord from threading import Thread from time import ctime class ClientHandler (Thread): def __init__(self, client, record): Thread.__init__(self) self._client = client self._record = record def run(self): self._client.send(str('Welcome to the chatroom!')) self._name = decode(self._client.recv(BUFSIZE),CODE) self._client.send(str(self._record),CODE) while True: message = decode(self._client.recv(BUFSIZE),CODE) if not message: print('Client disconnected') self._client.close() break else: message=self._name +'' + \ ctime()+'\n'+message self._record.add(message) self._client.send(str(self._record),CODE) HOST ='localhost' PORT = 5000 ADDRESS = (HOST,PORT) BUFSIZE = 1024 CODE = 'ascii' record = ChatRecord() server = socket(AF_INET,SOCK_STREAM) server.bind(ADDRESS) server.listen(5) while True: print ('Waiting for connection...') client,address = server.accept() print ('...connected from:',address) handler = ClientHandler(client,record) handler.start() </code></pre> <p>This is the server file</p> <pre><code>from socket import * from codecs import decode HOST ='localhost' PORT = 5000 BUFSIZE = 1024 ADDRESS = (HOST,PORT) CODE = 'ascii' server = socket(AF_INET,SOCK_STREAM) server.connect(ADDRESS) print (decode(server.recv(BUFSIZE), CODE)) name = raw_input('Enter your name:') server.send(name) while True: record = server.recv(BUFSIZE) if not record: print ('Server disconnected') break print (record) message = raw_input('&gt;') if not message: print ('Server disconnected') break server.send(message, CODE) server.close() </code></pre> <p>This is the Chartrecord</p> <pre><code>class ChatRecord(object): def __init__(self): self.data=[] def add(self,s): self.data.append(s) def __str__(self): if len(self.data)==0: return 'No messages yet!' else: return'\n'.join(self.data) </code></pre> <p>This is the error message I get when running the chat record. I can enter a name then after that I get the error message below</p> <pre><code>Waiting for connection... ('...connected from:', ('127.0.0.1', 51774)) Waiting for connection... Exception in thread Thread-1: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threadin g.py", line 532, in __bootstrap_inner self.run() File "/Users/basetsanamanele/Documents/workspace/HAAAAAAAFF/ClientHandler", line 17, in run self._client.send(str(self._record),CODE) TypeError: an integer is required </code></pre> <p>Please assist</p>
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_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host,port)) s.listen(10) serverThreads = [] while True: print "Server is listening for connections..." client, address = s.accept() serverThreads.append(Thread(target=runserver, args=(client,address)).start()) s.close() def runserver(client, address): clients = set() lockClients = threading.Lock() print ("Connection from: " + address) with lockClients: clients.add(client) try: while True: data = client.recv(1024) if data: print data.decode() with lockClients: for c in clients: c.sendall(data) else: break finally: with lockClients: clients.remove(client) client.close() </code></pre> <p>When you send a string over TCP you need to encode it to bytes. So your client file should look like this instead:</p> <pre><code>def run(self): self._client.send(('Welcome to the chatroom!').encode()) self._name = self._client.recv(BUFSIZE).decode() self._client.send(str(self._record),CODE) while True: message = self._client.recv(BUFSIZE).decode() if not message: print('Client disconnected') self._client.close() break else: message=self._name +'' + \ ctime()+'\n'+message self._record.add(message) self._client.send(self._record.encode()) </code></pre> <p>I much prefer the <code>.encode()</code> and <code>.decode()</code> syntax as it makes the code a little more readable IMO.</p>
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 port. Can Nginx just forward requests?)</p> <p>Does it make sense to not use even Nginx, just running bare flask app on a port?</p>
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 production-ready WSGI server such as Gunicorn or uWSGI when moving to production, no matter where the app will be available.</p> <hr> <p>The answer is similar for "should I use a web server". WSGI servers happen to have HTTP servers but they will not be as good as a dedicated production HTTP server (Nginx, Apache, etc.).</p>
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 port. Can Nginx just forward requests?)</p> <p>Does it make sense to not use even Nginx, just running bare flask app on a port?</p>
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.wsgi.WSGIServer((host, port), app) app_server.serve_forever() </code></pre> <p>Then you can just run your application directly rather than having to tell gunicorn or uWSGI or anything else to run it for you.</p> <p>I had a case where I wanted the utility of flask to build a web application (a REST API service) and found the inability to compose flask with other non-flask, non-web-service elements a problem. I eventually found <code>gevent.wsgi.WSGIServer</code> and it was just what I needed. After the call to <code>app_server.serve_forever()</code>, you can call <code>app_server.stop()</code> when your application wants to exit.</p> <p>In my deployment, my application is listening on localhost: using flask and gevent, and then I have nginx reverse-proxying HTTPS requests on another port and forwarding them to my flask service on localhost.</p>
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 = get_object_or_404(Equipment, id = equipment_id) EquipmentInlineFormSet = inlineformset_factory(Equipment, Calibration, fields = ('cal_by', 'cal_date', 'notes'), extra = 1, ) if request.method == "POST": if 'calibration' in request.POST: formset = EquipmentInlineFormSet(request.POST, request.FILES, instance=equipment) if formset.is_valid(): return HttpResponseRedirect(reverse('calbase:default_detail', args=(equipment_id))) else: formset = EquipmentInlineFormSet(instance=equipment) return render(request, 'calbase/default_detail_cal.html', {'formset' : formset, 'equipment' : equipment}) </code></pre> <p>And urls are like this:</p> <pre><code>urlpatterns = [ url(r'^$', views.default, name = 'default'), url(r'^default/(?P&lt;equipment_id&gt;[0-9]+)/$', views.default_detail, name = 'default_detail'), url(r'^default/new/$', views.default_new, name = 'default_new'), url(r'^default/(?P&lt;equipment_id&gt;[0-9]+)/cal/$', views.default_add_cal, name = 'default_add_cal'), ] </code></pre> <p>and the template for default_add_cal, default_detail_cal.html is like :</p> <pre><code>{% block content %} &lt;form method="POST" action = "{% url 'calbase:default_add_cal' equipment.id %}"&gt;{% csrf_token %} {{ formset }} &lt;button type="submit" class="save btn btn-default" name = "calibration"&gt;Save&lt;/button&gt; &lt;/form&gt; &lt;a href="{% url 'calbase:default' %}"&gt;Back?&lt;/a&gt; {% endblock %} </code></pre> <p>So Calibration is a foreign key to Equipment: a equipment can have several calibrations, and here I am trying to use a inlineformset to let user add calibrations to a equipment. Problem is that I got this:</p> <blockquote> <p>NoReverseMatch at /calbase/default/41/cal/ Reverse for 'default_detail' with arguments '('4', '1')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['calbase/default/(?P[0-9]+)/$']</p> </blockquote> <p>It confuses me that for example, for equipment id =41, when I do </p> <pre><code>return HttpResponseRedirect(reverse('calbase:default_detail', args=(equipment_id))) </code></pre> <p>the argument that is actually passed is '('4', '1')' instead of 41. How could this be? How should I possibly fix this? thanks</p>
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>&gt;&gt;&gt; args = (42) &gt;&gt;&gt; type(args) &lt;class 'int'&gt; &gt;&gt;&gt; &gt;&gt;&gt; args = (42,) &gt;&gt;&gt; type(args) &lt;class 'tuple'&gt; </code></pre> <p>Works even without the parens:</p> <pre><code>&gt;&gt;&gt; args = 42, &gt;&gt;&gt; type(args) &lt;class 'tuple'&gt; </code></pre>
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>&lt;strong class="item-title"&gt;**this**&lt;/strong&gt; , &lt;span class="item-daterange"&gt;**this**&lt;/span&gt; and &lt;div class="item-location"&gt;**this**&lt;/div&gt;</code> , note that they are in separate sections of the html source , and rendered through JavaScript. All of them scraped variables should be appended into one String and displayed. </p> <pre><code>response = net.http_GET('my URL') link = response.content match=re.compile('&lt;strong class="gcf-item-title"&gt;(.+?)&lt;/strong&gt;').findall(link) for name in match: name = name print name </code></pre> <p>From the above with regex i can scrape just one of those variables and since i need a String list to be displayed of all the variables together , How can that be done? </p> <p>I get that the page has to be pre rendered for the javascript variables to be scraped But since I'm using xbmc , I am not sure on how i can import additional python libraries such as dryscrape to get this done. Downloading Dryscrape gives me a setup.py , <strong>init</strong>.py file along with some others but how can i use all of them together? </p> <p>Thanks. </p>
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>&lt;strong class="item-title"&gt;**this**&lt;/strong&gt;</code> you won't get a match since your <strong>re</strong> pattern is for <strong> elements with class="gcf-item-title</strong>.</p> <p>Are you using or able to use BeautifulSoup? If you're not using it, but can, you should--it's life changing in terms of scraping websites.</p>
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>&lt;Item&gt; &lt;Info&gt; &lt;Name&gt;Body HD&lt;/Name&gt; &lt;/Info&gt; &lt;Genres&gt; &lt;Genre&gt;Action&lt;/Genre&gt; &lt;/Genres&gt; &lt;/Item&gt; </code></pre> <p>Is there a way to do this with <code>lxml</code>? Or how could I build a function to fill in the inferred paths?</p>
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>&lt;Item&gt; &lt;Info&gt; &lt;Name/&gt; &lt;/Info&gt; &lt;Genres&gt; &lt;Genre/&gt; &lt;/Genres&gt; &lt;/Item&gt; from lxml import etree tree = etree.parse("template.xml") </code></pre> <p>Then, fill it:</p> <pre><code>entries = [ {'Path': 'Item/Info/Name', 'Value': 'Body HD'}, {'Path': 'Item/Genres/Genre', 'Value': 'Action'}] for entry in entries: xpath = entry["Path"] node = tree.xpath(xpath)[0] node.text = entry['Value'] </code></pre> <p><em>Note: instead of "Path", I would prefer "XPath"</em></p> <p>If you dont want template, you can generate the whole tree structure like this:</p> <pre><code>from lxml import etree entries = [ {'Path': 'Item/Info/Name', 'Value': 'Body HD'}, {'Path': 'Item/Genres/Genre', 'Value': 'Action'}] root = None for entry in entries: path = entry["Path"] parts = path.split("/") xpath_list = ["/" + parts[0]] + parts[1:] curr = root for xpath in xpath_list: name = xpath.strip("/") if curr is None: root = curr = etree.Element(name) else: nodes = curr.xpath(xpath) if nodes: curr = nodes[0] else: curr = etree.SubElement(curr, name) curr.text = entry["Value"] print(etree.tostring(root, pretty_print=True)) </code></pre> <p>The result is:</p> <pre><code>&lt;Item&gt; &lt;Info&gt; &lt;Name&gt;Body HD&lt;/Name&gt; &lt;/Info&gt; &lt;Genres&gt; &lt;Genre&gt;Action&lt;/Genre&gt; &lt;/Genres&gt; &lt;/Item&gt; </code></pre> <p>Of course, there are limitations.</p>
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>&lt;Item&gt; &lt;Info&gt; &lt;Name&gt;Body HD&lt;/Name&gt; &lt;/Info&gt; &lt;Genres&gt; &lt;Genre&gt;Action&lt;/Genre&gt; &lt;/Genres&gt; &lt;/Item&gt; </code></pre> <p>Is there a way to do this with <code>lxml</code>? Or how could I build a function to fill in the inferred paths?</p>
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("&lt;{}&gt;&lt;/{}&gt;".format(root_node, root_node)) for dct in l: nodes = iter(dct["Path"].split("/")[1:]) # catch path like Item/Foo where there is only one child. nxt_child = child = et.Element(next(nodes)) for node in nodes: # keep adding nodes nxt_child = et.Element(node) child.append(nxt_child) # set value to last node. nxt_child.text = dct["Value"] # append it to the tree. tree.append(child) print(et.tostring(tree)) </code></pre> <p>Which would give you:</p> <pre><code>&lt;Item&gt; &lt;Info&gt; &lt;Name&gt;Body HD&lt;/Name&gt; &lt;/Info&gt; &lt;Genres&gt; &lt;Genre&gt;Action&lt;/Genre&gt; &lt;/Genres&gt; &lt;/Item&gt; </code></pre> <p>You know <code>Item</code> is the root node and the first in every Path, so first create a tree using that node and then just add to the tree as you go.</p>
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 anywhere I want, like "D:\test0.py", so I did this on VBA Function Settings:</p> <pre><code>PYTHONPATH = "D:\test0.py" UDF_MODULES = "test0" </code></pre> <p>Except the two lines above, I didn't change anything in Function Settings. However, what I got is only: <a href="http://i.stack.imgur.com/ZAH7m.png" rel="nofollow">errors, No module named 'test0'</a></p> <p>I am now fully confused, what should I do if I want to import module from "D:\test0.py" correctly? I know this might be a stupid question, but I really need help now.</p> <p>Thanks again!</p>
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.bar(position=1, width=0.1, stacked=True, ax=ax) </code></pre> <p>Which, in a notebook, give the following output: <a href="http://i.stack.imgur.com/WTnEC.png" rel="nofollow"><img src="http://i.stack.imgur.com/WTnEC.png" alt="stacked bar plot"></a></p> <p>The problem I'm facing is that, for each group, the bars are not in the order I want them to be. The doc says that the "position" argument for a bar plot specifies the relative position of the bar, with 0 being left and 1 being right. But it seems to do the complete opposite. What am I misunderstanding?</p>
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" rel="nofollow"><code>align</code></a> parameter of a matplotlib bar plot.</p> <p>Illustrations: <br><br> 1. when <code>position=0.5</code>: [Default : center alignment]</p> <pre><code>df[['a', 'c']].plot.bar(position=0.5, width=0.1, stacked=True, ax=ax) df[['b', 'd']].plot.bar(position=0.5, width=0.1, stacked=True, ax=ax) </code></pre> <p>The bars are coinciding with the X-axis labels as shown: <a href="http://i.stack.imgur.com/AdtvZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/AdtvZ.png" alt="enter image description here"></a> 2. when <code>position=0</code>:[left/bottom edge alignment]</p> <pre><code>df[['a', 'c']].plot.bar(position=0, width=0.1, stacked=True, ax=ax) df[['b', 'd']].plot.bar(position=0, width=0.1, stacked=True, ax=ax) </code></pre> <p>The left most portion of the bars are coinciding with the X-axis labels as shown: <a href="http://i.stack.imgur.com/8ndzI.png" rel="nofollow"><img src="http://i.stack.imgur.com/8ndzI.png" alt="enter image description here"></a></p> <p>Now, you can clearly distinguish the difference between the above 2 figures.</p>
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> <p>However, I am continuously running into the error: <code>TypeError: __init__() takes at least 2 arguments (1 given)</code></p> <p>Can anyone please help me resolve the error as soon as possible?</p> <p>Thanks!</p>
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 like:</p> <pre><code>2016-06-01 00:00:00 56.8 2016-06-01 00:15:00 52.1 2016-06-01 00:30:00 44.0 2016-06-01 00:45:00 43.6 2016-06-01 01:00:00 34.3 </code></pre> <p>At first I set this up as two subplots, with precipitation and flow rate on different axis. This works totally fine. Here's my code:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd from datetime import datetime filename = 'manhole_B.csv' plotname = 'SSMH-2A B' plt.style.use('bmh') # Read csv with precipitation data, change index to datetime object pdf = pd.read_csv('precip.csv', delimiter=',', header=None, index_col=0) pdf.columns = ['Precipitation[in]'] pdf.index.name = '' pdf.index = pd.to_datetime(pdf.index) pdf = pdf.resample('D').sum() print(pdf.head()) # Read csv with flow data, change index to datetime object qdf = pd.read_csv(filename, delimiter=',', header=None, index_col=0) qdf.columns = ['Flow rate [gpm]'] qdf.index.name = '' qdf.index = pd.to_datetime(qdf.index) # Plot f, ax = plt.subplots(2) qdf.plot(ax=ax[1], rot=30) pdf.plot(ax=ax[0], kind='bar', color='r', rot=30, width=1) ax[0].get_xaxis().set_ticks([]) ax[1].set_ylabel('Flow Rate [gpm]') ax[0].set_ylabel('Precipitation [in]') ax[0].set_title(plotname) f.set_facecolor('white') f.tight_layout() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/qun10.png" rel="nofollow">2 Axis Plot</a></p> <p>However, I decided I want to show everything on a single axis, so I modified my code to put precipitation on a secondary axis. Now my flow data data has disppeared from the plot, and even when I set the axis ticks to an empty set, I get these 00:15 00:30 and 00:45 tick marks along the x-axis.</p> <p><a href="http://i.stack.imgur.com/dl3dP.png" rel="nofollow">Secondary-y axis plots</a></p> <p>Any ideas why this might be occuring?</p> <p>Here is my code for the single axis plot:</p> <pre><code>f, ax = plt.subplots() qdf.plot(ax=ax, rot=30) pdf.plot(ax=ax, kind='bar', color='r', rot=30, secondary_y=True) ax.get_xaxis().set_ticks([]) </code></pre>
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' : np.square(np.arange(10))}) df Out[1]: x y1 y2 0 0 0.451314 0 1 1 0.321124 1 2 2 0.050852 4 3 3 0.731084 9 4 4 0.689950 16 5 5 0.581768 25 6 6 0.962147 36 7 7 0.743512 49 8 8 0.993304 64 9 9 0.666703 81 </code></pre> <h2>Plot</h2> <pre><code>In [2]: fig, ax1 = plt.subplots() ax1.plot(df['x'], df['y1'], 'b-') ax1.set_xlabel('Series') ax1.set_ylabel('Random', color='b') for tl in ax1.get_yticklabels(): tl.set_color('b') ax2 = ax1.twinx() # Note twinx, not twiny. I was wrong when I commented on your question. ax2.plot(df['x'], df['y2'], 'ro') ax2.set_ylabel('Square', color='r') for tl in ax2.get_yticklabels(): tl.set_color('r') Out[2]: </code></pre> <p><a href="http://i.stack.imgur.com/g9Cav.png" rel="nofollow"><img src="http://i.stack.imgur.com/g9Cav.png" alt="Plot"></a></p>
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\AppData\Local\Continuum\Miniconda2\envs\gl-env\lib\site-packages\graphlab 2. Run graphlab.get_dependencies() to download and install them. 3. Restart Python and import graphlab again. By running the above function, you agree to the following licenses. * libstdc++: https://gcc.gnu.org/onlinedocs/libstdc++/manual/license.html * xz: http://git.tukaani.org/?p=xz.git;a=blob;f=COPYING </code></pre> <p>So I try to run <code>graphlab.get_dependencies()</code> and I get the following error:</p> <pre><code>In [2]: gl.get_dependencies() By running this function, you agree to the following licenses. * libstdc++: https://gcc.gnu.org/onlinedocs/libstdc++/manual/license.html * xz: http://git.tukaani.org/?p=xz.git;a=blob;f=COPYING Downloading xz. Extracting xz. Downloading gcc-libs. Extracting gcc-libs. xz: c:\users\danisuar\appdata\local\temp\tmpcdpyzp.xz: File format not recognized --------------------------------------------------------------------------- CalledProcessError Traceback (most recent call last) &lt;ipython-input-2-5349b2d86a08&gt; in &lt;module&gt;() ----&gt; 1 gl.get_dependencies() C:\Users\DANISUAR\AppData\Local\Continuum\Miniconda2\envs\gl-env\lib\site-packag es\graphlab\dependencies.pyc in get_dependencies() 45 prev_cwd = os.getcwd() 46 os.chdir(dllarchive_dir) ---&gt; 47 subprocess.check_call([xz, '-d', dllarchive_file]) 48 dllarchive_tar = tarfile.open(os.path.splitext(dllarchive_file)[0]) 49 dllarchive_tar.extractall() C:\Users\DANISUAR\AppData\Local\Continuum\Miniconda2\envs\gl-env\lib\subprocess.pyc in check_call(*popenargs, **kwargs) 539 if cmd is None: 540 cmd = popenargs[0] --&gt; 541 raise CalledProcessError(retcode, cmd) 542 return 0 543 CalledProcessError: Command '['c:\\users\\danisuar\\appdata\\local\\temp\\tmpf1habd\\bin_x86-64\\xz.exe', '-d', 'c:\\users\\danisuar\\appdata\\local\\temp\\tmpcdpyzp.xz']' returned non-zero exit status 1 </code></pre> <p>I am using an Anaconda environment with Python 2.7 and Windows 7.</p>
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 graphlab by typing </p> <blockquote> <p>import graphlab </p> </blockquote> <p>The following errors may appear as given in the image description below. <a href="http://i.stack.imgur.com/haGAa.png" rel="nofollow">enter image description here</a></p> <p>Then, you can run the graphlab.get_dependencies() in python terminal.</p> <p>Verify the installation again in python terminal using</p> <blockquote> <p>import graplab</p> </blockquote>
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 RST packet resetting the connection. I overcame this my dropping all such reset packets using the following iptable rule: </p> <pre><code>-A OUTPUT -p tcp -m tcp --sport 999 --tcp-flags RST RST -j DROP </code></pre> <p>Now I want to receive the SYN, ACK packet sent by the server and print it out. But I receive nothing when I do the following: </p> <pre><code>a = self.s.recvfrom(4096) </code></pre> <p>I suspect that the kernel is dropping the SYN, ACK before I can recv it using my socket. Does anyone know a reasonable workaround? </p>
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/NetfilterQueue" rel="nofollow">bindings</a>, so using it shouldn't be an issue.</p> <p>The idea is to catch all incoming TCP Syns before they reach the kernel's TCP implementation. Then pass these packets to the nfqueue which your userland app can monitor. For each packet your app will get from the nfqueue, it will have to decide (<a href="https://www.netfilter.org/projects/libnetfilter_queue/doxygen/group__Queue.html#gae36aee5b74d0c88d2f8530e356f68b79" rel="nofollow">return a verdict</a>) of whether to handle the packet itself (i.e. drop the packet as far as the OS is concerned) or pass it along to the regular TCP implementation.</p> <p>I know for a fact that this approach works, but it's cumbersome. </p>
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 RST packet resetting the connection. I overcame this my dropping all such reset packets using the following iptable rule: </p> <pre><code>-A OUTPUT -p tcp -m tcp --sport 999 --tcp-flags RST RST -j DROP </code></pre> <p>Now I want to receive the SYN, ACK packet sent by the server and print it out. But I receive nothing when I do the following: </p> <pre><code>a = self.s.recvfrom(4096) </code></pre> <p>I suspect that the kernel is dropping the SYN, ACK before I can recv it using my socket. Does anyone know a reasonable workaround? </p>
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 messages from the kernel. By providing the correct filter from your application, you can receive TCP segments from the Kernel. I have used libpcap in C and I suppose you can use the indicated modules in the same way. For me this is the best solution as you can handle it from the application in a pretty standard way.</p> <p>To avoid the kernel responding with a RST, your solution with iptables looks the best one for me.</p>
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 RST packet resetting the connection. I overcame this my dropping all such reset packets using the following iptable rule: </p> <pre><code>-A OUTPUT -p tcp -m tcp --sport 999 --tcp-flags RST RST -j DROP </code></pre> <p>Now I want to receive the SYN, ACK packet sent by the server and print it out. But I receive nothing when I do the following: </p> <pre><code>a = self.s.recvfrom(4096) </code></pre> <p>I suspect that the kernel is dropping the SYN, ACK before I can recv it using my socket. Does anyone know a reasonable workaround? </p>
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 "some other system". This makes it trivial to filter the packets you care about from others. </p> <p>You will also need to respond to ARPs appropriately in order for the other system to find your MAC address. And if you need DHCP for obtaining an IP address, you would need to handle those interactions as well.</p>
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', 'zz']</code></p>
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>&gt;&gt;&gt; [i for i in ['cc','bb','aa','qq','zz'] if i[0] == 'a'] # Returns new list. ['aa'] </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; filter(lambda x: x[0] == 'a', ['cc','bb','aa','qq','zz']) # New list. ['aa'] </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; x = ['cc', 'bb', 'aa', 'qq', 'zz'] &gt;&gt;&gt; l = [] # New List &gt;&gt;&gt; for e in x: &gt;&gt;&gt; if e[0] == 'a': &gt;&gt;&gt; l.append(e) &gt;&gt;&gt; print l ['aa'] </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; x = ['cc', 'bb', 'aa', 'qq', 'zz'] # In place. &gt;&gt;&gt; for e in x[:]: &gt;&gt;&gt; if e[0] != 'a': x.remove(e) &gt;&gt;&gt; print x ['aa'] </code></pre>
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', 'zz']</code></p>
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 start with an 'a' so it is removed. Now 'bb' is the first element and 'aa' is the second. In other words:</p> <pre><code>xxx = ['bb','aa','qq','zz'] </code></pre> <p>BUT the for loop, which only knows it has looked at <strong>one</strong> element, just moves on to the <strong>second</strong> element without realizing things have shifted! The second element is now 'aa', which is left alone. Then the loop moves to the third element, 'qq', and removes it, leaving:</p> <pre><code>xxx = ['bb','aa','zz'] </code></pre> <p>The for loop sees a list with three elements and knows it has looked at three elements and believes it is done, even though it skipped 'bb' and 'zz' completely.</p> <p>As others have suggested, you can use a list comprehension instead, though you should definitely google and read up on how they work before applying them.</p> <pre><code>[i for i in ['cc','bb','aa','qq','zz'] if i[0] == 'a'] </code></pre> <p>In the future, I recommend putting print statements inside the for loop while debugging, just to see what's going on. For example, you probably would have figured this out on your own if you had:</p> <pre><code>for k in xxx: print k if k[0] != 'a': xxx.remove(k) </code></pre>
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:SyntaxError: unindent does not match any outer indentation level</p> <h1>the if and else are on the same column, so I am not sure whats happening?</h1> <p>Here is the error (link below) <a href="http://i.stack.imgur.com/oPeh6.png" rel="nofollow">Error</a> Here was the solution: kind-af funny looking, but even though If was initially on column 4 python registered it as column 0, so I had to put my else: on column 0 (even though it didn't look aligned. THANKS EVERYBODY FOR THE HELP!! <a href="http://i.stack.imgur.com/lwnp5.png" rel="nofollow">Solution</a></p>
-1
2016-08-16T19:53:22Z
38,983,390
<p>Each indentation level should have four spaces.</p> <pre><code>if x &gt; 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", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; x = 50 &gt;&gt;&gt; if x &gt; 100: ... print('3') ... else: ... pass ... &gt;&gt;&gt; x = 150 &gt;&gt;&gt; if x &gt; 100: ... print('3') ... else: ... pass ... 3 </code></pre> <p>Thanks to the pointer from @Vekyn regarding IDLE indentation quirks:</p> <p><a href="http://i.stack.imgur.com/6wcuw.gif" rel="nofollow"><img src="http://i.stack.imgur.com/6wcuw.gif" alt="enter image description here"></a></p>
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:SyntaxError: unindent does not match any outer indentation level</p> <h1>the if and else are on the same column, so I am not sure whats happening?</h1> <p>Here is the error (link below) <a href="http://i.stack.imgur.com/oPeh6.png" rel="nofollow">Error</a> Here was the solution: kind-af funny looking, but even though If was initially on column 4 python registered it as column 0, so I had to put my else: on column 0 (even though it didn't look aligned. THANKS EVERYBODY FOR THE HELP!! <a href="http://i.stack.imgur.com/lwnp5.png" rel="nofollow">Solution</a></p>
-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:SyntaxError: unindent does not match any outer indentation level</p> <h1>the if and else are on the same column, so I am not sure whats happening?</h1> <p>Here is the error (link below) <a href="http://i.stack.imgur.com/oPeh6.png" rel="nofollow">Error</a> Here was the solution: kind-af funny looking, but even though If was initially on column 4 python registered it as column 0, so I had to put my else: on column 0 (even though it didn't look aligned. THANKS EVERYBODY FOR THE HELP!! <a href="http://i.stack.imgur.com/lwnp5.png" rel="nofollow">Solution</a></p>
-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, line 2 contains 4 spaces and line 6 contains one tab. It's really useful when your text editor allows you to notice these differences somehow.</p>
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:SyntaxError: unindent does not match any outer indentation level</p> <h1>the if and else are on the same column, so I am not sure whats happening?</h1> <p>Here is the error (link below) <a href="http://i.stack.imgur.com/oPeh6.png" rel="nofollow">Error</a> Here was the solution: kind-af funny looking, but even though If was initially on column 4 python registered it as column 0, so I had to put my else: on column 0 (even though it didn't look aligned. THANKS EVERYBODY FOR THE HELP!! <a href="http://i.stack.imgur.com/lwnp5.png" rel="nofollow">Solution</a></p>
-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>&gt;&gt;&gt; if x &gt; 1000: print(3) else: </code></pre> <p>right? The point is, <code>&gt;&gt;&gt;</code> doesn't count when calculating indents. So in fact if and else are <em>not</em> in the same column as far as IDLE is concerned. :-( [The indents it sees are 0, 8, 4.] You have to start the <code>else:</code> flush completely to the left margin.</p>
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() run around them, but its not true when I try it. What am I missing?</p> <pre><code>import unittest def fun(x): return x + 1 class MyTest(unittest.TestCase): def setUp(self): print "** in Setup" def test_02(self): self.skipTest("** skipping, but dont want to run setUp") self.assertEqual(fun(4), 5) </code></pre> <p>output when I run the above Test</p> <pre><code>Testing started at 3:48 PM ... ** in Setup ** skipping, but dont want to run setUp Process finished with exit code 0 </code></pre>
-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(self): print "** in Setup" @unittest.skip('skip please...') def test_02(self): self.skipTest("** skipping, but dont want to run setUp") self.assertEqual(fun(4), 5) unittest.main() </code></pre> <p>In this case, unittest marks the method so that it knows not to bother running <code>setUp</code> or <code>tearDown</code>. With the version where you (directly or indirectly) raise <code>unittest.SkipTest</code> <em>inside</em> the test function, it's too late -- <code>setUp</code> has already been run by the time there is <em>any</em> indication that the test should be skipped.</p>
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 can I pivot this groupby results, to put results from each group into a separate column? <a href="http://i.stack.imgur.com/v6oIU.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/v6oIU.jpg" alt="enter image description here"></a></p>
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="nofollow"><code>unstack</code></a>, and then normalize the columns:</p> <pre><code># Perform the pivot. test = test.set_index(['Rating','Sec'], append=True).unstack(['Rating','Sec']) # Normalize the columns. test = test/test.sum() # Rename columns as appropriate. test.columns = [','.join(c[1:]) for c in test.columns] </code></pre> <p>The resulting output:</p> <pre><code> A,I Z,I A,F 0 0.384615 NaN NaN 1 NaN 1.0 NaN 2 0.615385 NaN NaN 3 NaN NaN 1.0 </code></pre>
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>ProgrammingError</code> in SQLAlchemy. How do I get the instances related to another instance in SQLAlchemy?</p> <pre><code>my_properties = Property.query.filter_by(listed_by=current_user) </code></pre> <pre><code>{% for property in my_properties %} {{ property.listing_no }} </code></pre> <pre><code>class Property(db.Model): id = db.Column(db.Integer, primary_key=True) listed_by = db.Column(db.Integer, db.ForeignKey('users.id')) </code></pre>
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> object. SQLAlchemy doesn't know what <code>integer == User</code> means.</p> <p>Create a relationship to the User object and filter on that.</p> <pre><code>class Property(db.Model): id = db.Column(db.Integer, primary_key=True listed_by_id = db.Column(db.ForeignKey(User.id)) listed_by = db.relationship(User, foreign_keys=[listed_by_id]) </code></pre> <pre><code>Property.query.filter_by(listed_by=current_user) </code></pre> <hr> <p>Technically, you can also filter on the id field by passing the user's id, although it's usually more useful to define the relationship.</p> <pre><code>Property.query.filter_by(listed_by_id=current_user.id) </code></pre>
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 comes to saving this is where i am stuck. the documentation is very confusing should i use all or just one clean.</p> <p>this is the forms.py</p> <pre><code> class EditContact(forms.ModelForm): class Meta: model = Contact #the list of all fields exclude = ['date_modified'] def clean(self): if self.date_of_entry is None: print("looking to see what works") self.date_of_entry = datetime.date.today() return def clean_ContactID(self): #see this line below this comment i dunno what it does ContactID= self.cleaned_data.get('ContactID') print ("cleaning it") # i also dont know what validation code suppose to look like # i cant find any working examples of how to clean data return ContactID </code></pre> <p>now there are mainly more def clean_methods but i think what i want to use is clean which should use all but in my view.</p> <p>this is in view.py</p> <pre><code>def saveContactInfo (request): #this part i get if request.user.is_authenticated(): ContactID= request.POST['ContactID'] a = ListofContacts.objects.get(ContactID=ContactID) f = EditContact(request.POST,instance=a) print("plz work!") if f.is_valid(): f.save() return render (request,"Contactmanager/editContact.html", {'contactID': contactID}) else: return HttpResponse("something isnt savin") else: return HttpResponse("Hello, you shouldnt ") </code></pre> <p>and this is model.py</p> <pre><code> def clean(self): if self.ConactID is None: raise ValidationError(_('ContactID cant be NULL!')) if self.date_of_entry is None: print("think it might call here first?") self.date_of_entry = datetime.date.today() print ( self.date_of_entry ) if self.modified_by is not None: self.modified_by="darnellefornow" print(self.modified_by ) if self.entered_by is not None: self.entered_by = "darnellefornow" print(self.entered_by ) ContactID = self.cleaned_data.get('ContactID') return </code></pre> <p>now above the model has the fields and the types which all have blank = true and null = true except for the excluded field date_of_entry</p> <p>and ive gotten to find out that when calling is_valid() in views it calls the models.clean() but it fails to save!!! and i dont know why! i dont know how to do the validation. i would like to know the process and what is required and even an example of form validation a field.</p>
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/validation/#cleaning-a-specific-field-attribute" rel="nofollow">Django docs show this as an example</a>:</p> <pre><code>def clean_recipients(self): data = self.cleaned_data['recipients'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!") # Always return the cleaned data, whether you have changed it or # not. return data </code></pre> <p>So in that block, they are checking to see if the email list provided contains a particular email. </p> <p>2) That also shows another question you asked in your comments about how to handle the validation. You'll see in that snippet above, you could raise a forms.ValidationError. This is discussed more here: <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/forms/validation/</a></p> <p>So, if an error is raised in any of those clean_ methods or in the main clean method, the form.is_valid() will be false.</p> <p>Does that help?</p>
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 Stock(): def __init__(self,equity, history): self.equity = equity self.history = history self.clf = tree.DecisionTreeClassifier # Couldn't use built-in comparable method # This method is a workaround. def exists(self, allCompanies): exists = False; for other in allCompanies: if self.equity.sid == other.equity.sid: exists = True return exists </code></pre> <p>Where I'm instantiating the class:</p> <pre><code>.... arr.append(Stock(equity, history)) </code></pre> <p>Where the error is thrown:</p> <pre><code>... if current &gt; prev: Stock.clf.fit(Stock, 1) else: Stock.clf.fit(Stock, 0) ... </code></pre>
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 Stock(): def __init__(self,equity, history): self.equity = equity self.history = history self.clf = tree.DecisionTreeClassifier # Couldn't use built-in comparable method # This method is a workaround. def exists(self, allCompanies): exists = False; for other in allCompanies: if self.equity.sid == other.equity.sid: exists = True return exists </code></pre> <p>Where I'm instantiating the class:</p> <pre><code>.... arr.append(Stock(equity, history)) </code></pre> <p>Where the error is thrown:</p> <pre><code>... if current &gt; prev: Stock.clf.fit(Stock, 1) else: Stock.clf.fit(Stock, 0) ... </code></pre>
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>self.clf = tree.DecisionTreeClassifier() </code></pre>
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 Stock(): def __init__(self,equity, history): self.equity = equity self.history = history self.clf = tree.DecisionTreeClassifier # Couldn't use built-in comparable method # This method is a workaround. def exists(self, allCompanies): exists = False; for other in allCompanies: if self.equity.sid == other.equity.sid: exists = True return exists </code></pre> <p>Where I'm instantiating the class:</p> <pre><code>.... arr.append(Stock(equity, history)) </code></pre> <p>Where the error is thrown:</p> <pre><code>... if current &gt; prev: Stock.clf.fit(Stock, 1) else: Stock.clf.fit(Stock, 0) ... </code></pre>
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 wstring, the first byte says 85-means string, next 2 bytes says string length followed by actual string. For wstring 85, next 2 bytes says wstring length, followed by actual wstring.</p> <p>To parse the above kind off wstring format <code>b'U\x00\x07\x00C\x00o\x00u\x00p\x00o\x00n\x001'</code> I used the following code</p> <pre><code>data = str(rawdata[3:]).split("\\x00") data = "".join(data[1:]) data = "".join(data[:-1]) </code></pre> <p>Is this correct or any other simple way?</p> <p>As I received the datagram, I need to send the datagram also. But I donot know how to create the datagrams as the socket.sendto requires <code>bytes</code>. If I try to convert string to <code>utf-16</code> format will it covert to wstring. If so how would I add the rest of the information into <code>bytes</code> </p> <p>From the above datagram information <code>U</code>-85 which is wstring, <code>\x00\x07</code> - 7 length of the wstring data, <code>\x00C\x00o\x00u\x00p\x00o\x00n\x001</code> - is the actual string <code>Coupon1</code></p>
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 place is to be able to represent characters that aren't plain old 8-bit (really 7-bit) ascii. If you have any characters that aren't standard Roman characters, they may well have something other than a zero byte separating the characters in which case your <code>split</code> result will make no sense.</p> <p>Caveat: Since you mentioned <code>sendto</code> requiring bytes, I assume you're using python3. Details will be slightly different under python2.</p> <p>Anyway if I understand what it is you're meaning to do, the "utf-16-be" codec may be what you're looking for. (The "utf-16" codec puts a "byte order marker" at the beginning of the encoded string which you probably don't want; "utf-16-be" just puts the big-endian 16-bit chars into the byte string.) Decoding could be performed something like this:</p> <pre><code>rawdata = b'U\x00\x07\x00C\x00o\x00u\x00p\x00o\x00n\x001' dtype = rawdata[0] if dtype == 85: # wstring dlen = ord(rawdata[1:3].decode('utf-16-be')) data = rawdata[3: (dlen * 2) + 3] dstring = data.decode('utf-16-be') </code></pre> <p>This will leave <code>dstring</code> as a python unicode string. In python3, all strings are unicode. So you're done.</p> <p>Encoding it could be done something like this:</p> <pre><code>tosend = 'Coupon1' snd_data = bytearray([85]) # wstring indicator snd_data += bytearray([(len(tosend) &gt;&gt; 8), (len(tosend) &amp; 0xff)]) snd_data += tosend.encode('utf-16-be') </code></pre>
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: PythonActivity = autoclass('org.kivy.android.PythonActivity') else: PythonActivity = autoclass('org.renpy.android.PythonActivity') Intent = autoclass('android.content.Intent') String = autoclass('java.lang.String') Uri = autoclass('android.net.Uri') File = autoclass('java.io.File') shareIntent = Intent(Intent.ACTION_SEND) shareIntent.setType('"image/*"') imageFile = File(path) uri = Uri.fromFile(imageFile) shareIntent.putExtra(Intent.EXTRA_STREAM, uri) currentActivity = cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(shareIntent) </code></pre> <p>But it doesn't work) It throws this error <code>jnius.jnius.JavaException: Invalid instance of u'android/net/Uri' passed for a u'java/lang/String'</code> in this line <code>shareIntent.putExtra(Intent.EXTRA_STREAM, uri)</code>. How can i fix this?</p>
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>inRelation({(1,1), (1,2), (2,3), (4,2)}) should return</p> <p>{(1,1), (2,1), (3,2), (2,4)}</p> </blockquote> </blockquote> <p>Here is my code:</p> <pre><code>def inverse(rel): m=set() for (x,y) in rel: m.add(y,x) return m </code></pre> <p>It says that I can add only one element. What can I do?</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(inv_foo2) </code></pre>
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>inRelation({(1,1), (1,2), (2,3), (4,2)}) should return</p> <p>{(1,1), (2,1), (3,2), (2,4)}</p> </blockquote> </blockquote> <p>Here is my code:</p> <pre><code>def inverse(rel): m=set() for (x,y) in rel: m.add(y,x) return m </code></pre> <p>It says that I can add only one element. What can I do?</p>
-1
2016-08-16T20:20:00Z
38,983,848
<p>If a "relation" is a set of (x, y) couples:</p> <pre><code>&gt;&gt;&gt; relation = {(1,1), (1,2), (2,3), (4,2)} </code></pre> <p>The inverted relation is:</p> <pre><code>&gt;&gt;&gt; inverted = {(y, x) for x, y in relation} &gt;&gt;&gt; inverted {(3, 2), (1, 1), (2, 4), (2, 1)} </code></pre> <p>The <code>inRelation</code> can be:</p> <pre><code>def inRelation(relation): return {(y, x) for x, y in relation} </code></pre> <p><em>note: I prefer snake case: <code>inv_relation</code></em></p>
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']</code>. My current method is </p> <pre><code>df_MVPs['Year'] = df_MVPs['Year'].str.replace(df_MVPs['Year'][:7], '') </code></pre> <p>but this causes an error to occur. Is there a way to do this more simply?</p> <p><strong>EDIT:</strong> I want my DataFrame to look like: </p> <pre><code> 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: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{4})$', expand=True) Out[11]: 0 46 1971 47 1970 48 1969 49 1968 50 1967 </code></pre> <p>but you can also use <code>.str.replace()</code>:</p> <pre><code>In [13]: df.Year.str.replace('.*(\d{4})$', r'\1') Out[13]: 46 1971 47 1970 48 1969 49 1968 50 1967 Name: Year, dtype: object </code></pre> <p><a href="https://regex101.com/r/mJ8dF3/1" rel="nofollow">Here is a link</a> which explains the <code>.*(\d{4})$</code> RegEx (Regular Expresiion) </p>
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']</code>. My current method is </p> <pre><code>df_MVPs['Year'] = df_MVPs['Year'].str.replace(df_MVPs['Year'][:7], '') </code></pre> <p>but this causes an error to occur. Is there a way to do this more simply?</p> <p><strong>EDIT:</strong> I want my DataFrame to look like: </p> <pre><code> 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: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']</code>. My current method is </p> <pre><code>df_MVPs['Year'] = df_MVPs['Year'].str.replace(df_MVPs['Year'][:7], '') </code></pre> <p>but this causes an error to occur. Is there a way to do this more simply?</p> <p><strong>EDIT:</strong> I want my DataFrame to look like: </p> <pre><code> 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: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:] &gt;&gt;&gt; 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 - error 2" else: print "not right number, try again - error 3" else: print "not right number, try again - error 4" </code></pre> <p>Which works well, except I really don't want to have to hand iterate <code>num</code> until I get the answer I want (I wrote this to solve a mathematics problem I wanted to solve - this is not homework, though). If anyone could detail to change all of the <code>else</code> statements to add a statement incrementing <code>num</code> by one and return to the beginning of the for loop, that'd be great.</p> <p>Thanks!</p>
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 "not right number, try again - error 1" else: print "not right number, try again - error 2" else: print "not right number, try again - error 3" else: print "not right number, try again - error 4" num += 1 </code></pre>
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 - error 2" else: print "not right number, try again - error 3" else: print "not right number, try again - error 4" </code></pre> <p>Which works well, except I really don't want to have to hand iterate <code>num</code> until I get the answer I want (I wrote this to solve a mathematics problem I wanted to solve - this is not homework, though). If anyone could detail to change all of the <code>else</code> statements to add a statement incrementing <code>num</code> by one and return to the beginning of the for loop, that'd be great.</p> <p>Thanks!</p>
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}".format(num, v[1]) else: print "The first number found is --&gt; {0}".format(v[1]) break N = 1000000 numbers = [num for num in range(N) if f(num)[0]] print "There are {0} numbers satisfying the condition below {1}".format( len(numbers), N) </code></pre>
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 - error 2" else: print "not right number, try again - error 3" else: print "not right number, try again - error 4" </code></pre> <p>Which works well, except I really don't want to have to hand iterate <code>num</code> until I get the answer I want (I wrote this to solve a mathematics problem I wanted to solve - this is not homework, though). If anyone could detail to change all of the <code>else</code> statements to add a statement incrementing <code>num</code> by one and return to the beginning of the for loop, that'd be great.</p> <p>Thanks!</p>
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 True return False # this while exit the loop else: # message to be formatted msg = "{n} is not the right number, try again - error {err}" # I tried to keep your error numbers err = len(tests) - tests.count(False) + 1 # format the message with the number and the error print msg.format(n=num, err=err) return True while test(num): num += 1 # increment the number print num, "is the right number" </code></pre> <p>The while loop tests the number on each iteration and it will exit when the number is right</p>
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 - error 2" else: print "not right number, try again - error 3" else: print "not right number, try again - error 4" </code></pre> <p>Which works well, except I really don't want to have to hand iterate <code>num</code> until I get the answer I want (I wrote this to solve a mathematics problem I wanted to solve - this is not homework, though). If anyone could detail to change all of the <code>else</code> statements to add a statement incrementing <code>num</code> by one and return to the beginning of the for loop, that'd be great.</p> <p>Thanks!</p>
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(100): if good_number(num): print('{} is a good number'.format(num)) # Or use a while loop: num = 0 while not good_num(num): num += 1 print('{} is a good number'.format(num)) </code></pre>
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 that was 5,000 of each class (class 1 instances were simply duplicated 9 times). After training models on this and getting sub-par results (an AUC of about .85, but it needed to be better) I started wondering if these sampling techniques were actually a good idea, so I took the original highly imbalanced dataset out again. I plugged it right into a default GradientBoostClassifier, trained it on 80% of the data and I immediately got something like this:</p> <pre><code>Accuracy: 0.997367035282 AUC: .9998 Confusion Matrix: [[5562 7] [ 8 120]] </code></pre> <p>Now, I know a high accuracy can be an artefact of the imbalanced classes, but I did not expect an AUC like this or that kind of performance! So I am very confused and feel there must be something an error in my technique somewhere...but I have no idea what it is. I've tried a couple different classifiers too and gotten similar levels of ridiculously good performance. I didn't leave the class labels in the data array and the training data is COMPLETELY different than the testing data. Each observation has about 130 features too, so this isn't a simple classification. It very much seems like something is wrong, I'm sure the classifier cannot be this good. Could there be anything else I am overlooking? Any other common pitfalls people run into like this with unbalanced data? </p> <p>I can provide the code, probability plots,example datapoints etc. if they would be helpful, but I didn't want this to get too long for now. Thanks to anybody who can help!</p>
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 XLON 3.215 6 BBG.XLON.TR.S XLON NaN 7 BBG.XLON.VO.S XLON NaN </code></pre> <p>In reality this dataframe will be much larger. I would like to iterate over this dataframe returning the <code>'grain'</code> value but I am only interested in the rows that have a value (not NaN) in the 'grain' column. So only returning as I iterate over the dataframe the following values:</p> <pre><code>16.545 6.2154 3.215 </code></pre> <p>I can iterate over the dataframe using:</p> <pre><code>for staticidx, row in df.iterrows(): value= row['grain'] </code></pre> <p>But this returns a value for all rows including those with a NaN value. Is there a way to either remove the NaN rows from the dataframe or skip the rows in the dataframe where grain equals NaN?</p> <p>Many thanks</p>
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>&gt;&gt;&gt; df.dropna(subset=['grain']) id location grain 0 BBG.XETR.AD.S XETR 16.5450 1 BBG.XLON.VB.S XLON 6.2154 5 BBG.XLON.AN.S XLON 3.2150 </code></pre>
1
2016-08-16T20:47:04Z
[ "python", "pandas" ]