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 |
|---|---|---|---|---|---|---|---|---|---|
Visualising a numpy array/matrix | 38,669,230 | <p>I have a function that returns a list. I think I use np.append to add this list as a new line in an array, my intention is as follow:</p>
<pre><code>list = 4 5 6
b = 1 2 3
b = np.append(b, list)
</code></pre>
<p>output;</p>
<pre><code>1 2 3
4 5 6
</code></pre>
<p>This isn't the code I use (there's a lot of mess... | 2 | 2016-07-30T00:29:36Z | 38,669,384 | <p>True list append:</p>
<pre><code>In [701]: alist = [4,5,6]
In [702]: b=[1,2,3]
In [703]: b.append(alist)
In [704]: b
Out[704]: [1, 2, 3, [4, 5, 6]]
</code></pre>
<p>bad array operation:</p>
<pre><code>In [705]: anArray=np.array([4,5,6])
In [706]: b=np.array([1,2,3])
In [707]: b=np.append(b,anArray)
In [708]: b
Ou... | 3 | 2016-07-30T01:00:57Z | [
"python",
"arrays",
"numpy"
] |
Visualising a numpy array/matrix | 38,669,230 | <p>I have a function that returns a list. I think I use np.append to add this list as a new line in an array, my intention is as follow:</p>
<pre><code>list = 4 5 6
b = 1 2 3
b = np.append(b, list)
</code></pre>
<p>output;</p>
<pre><code>1 2 3
4 5 6
</code></pre>
<p>This isn't the code I use (there's a lot of mess... | 2 | 2016-07-30T00:29:36Z | 38,669,481 | <p>you should use hstack or vstack</p>
<pre><code>import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
np.vstack((a,b))
</code></pre>
<p>gives</p>
<pre><code>array([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>or </p>
<pre><code>np.hstack((a,b))
</code></pre>
<p>gives</p>
<pre><code>array([1, 2,... | 1 | 2016-07-30T01:19:00Z | [
"python",
"arrays",
"numpy"
] |
Why Do I need Range(Len)) for a nested if? | 38,669,242 | <p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p>
<pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4]
mostFrq = 0
mostFrqAmount = 0
for i in range(len(arr)):
... | 0 | 2016-07-30T00:31:13Z | 38,669,266 | <p>When you're iterating over a list, you get its elements. Since you're then accessing list elements at the index of that element, it won't work when it's out of bounds (and wouldn't do what you expected anyways).</p>
<p>Instead, just use the items you're provided by the loop:</p>
<pre><code>mostFrq = 0
mostFrqAmoun... | 0 | 2016-07-30T00:38:11Z | [
"python"
] |
Why Do I need Range(Len)) for a nested if? | 38,669,242 | <p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p>
<pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4]
mostFrq = 0
mostFrqAmount = 0
for i in range(len(arr)):
... | 0 | 2016-07-30T00:31:13Z | 38,669,268 | <p>Not sure what you've tried. This should work the same way:</p>
<pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4]
mostFrq = 0
mostFrqAmount = 0
for i in arr:
amountOfCurrent = 0
# now look at temp element
for j in arr:
if (j == i):
amountOfCurrent = amountO... | 0 | 2016-07-30T00:38:28Z | [
"python"
] |
Why Do I need Range(Len)) for a nested if? | 38,669,242 | <p>This works as is but when I didn't have range(len..)) in and do <code>for i in arr</code> and <code>for j in arr</code>, I get <code>IndexError: list index out of range</code> on the if statement. Why is this?</p>
<pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4]
mostFrq = 0
mostFrqAmount = 0
for i in range(len(arr)):
... | 0 | 2016-07-30T00:31:13Z | 38,669,298 | <p>If you analyze what is going on with your code in the failing form, you have:</p>
<pre><code>arr = [2,2,2,2,4,5,2,45,3,4,4]
mostFrq = 0
mostFrqAmount = 0
for i in arr:
amountOfCurrent = 0
# now look at temp element
for j in arr:
if (arr[j] == arr[i]):
... | 0 | 2016-07-30T00:44:41Z | [
"python"
] |
Django Model Field from OneToOneField | 38,669,253 | <p>I have two models:</p>
<pre><code>class FirstModel(models.Model):
foo = models.IntegerField(default=0)
class SecondModel(models.Model):
bar = models.OneToOneField(FirstModel, on_delete=models.CASCADE, primary_key=True)
</code></pre>
<p>How do I make a variable <code>baz</code> that is from <code>FirstMod... | 0 | 2016-07-30T00:34:08Z | 38,669,426 | <p>You can use <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.related_name" rel="nofollow"><code>related_name</code></a> in the linking model for backward reference: </p>
<pre><code>class FirstModel(models.Model):
foo = models.IntegerField(default=0)
class SecondMo... | 3 | 2016-07-30T01:09:11Z | [
"python",
"django",
"model"
] |
Find if an item is in a lower dimension in a Python multidimensional array | 38,669,300 | <p>I have a three dimensional array, called grid. I now want to find whether an item is in the list of second dimensions containing the third dimension. For example, if I have this array:</p>
<pre><code>grid = [ [ [ "0" , "1" ] , [ "2" , "1" ] ] , [ [ "3" , "0" ] ] ]
</code></pre>
<p>I want to find whether in all of... | 0 | 2016-07-30T00:45:17Z | 38,669,334 | <p>Where you say <code>[all]</code>, you can use a for-loop to iterate through the elements.</p>
<p>For example, <code>([0][all][0])</code></p>
<pre><code>for y in grid[0]:
if y[0] == "Your Value To Look For":
print("I found the value")
</code></pre>
| 1 | 2016-07-30T00:50:52Z | [
"python",
"python-3.x"
] |
group elements in an array and sum | 38,669,307 | <p>I have the following array</p>
<pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
</code></pre>
<p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p>
<pre><code>b = [1,0,2,0,3,0,1]
</code></pre>
<p>Any suggestions... | -2 | 2016-07-30T00:46:00Z | 38,669,372 | <p>Maybe something like this:</p>
<pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
b = []
for i in range(0,len(a),3):
b.append(sum(a[i:i+3]))
print b
</code></pre>
<p>Output: </p>
<pre><code>[1, 0, 2, 0, 3, 0, 1]
</code></pre>
| 2 | 2016-07-30T00:59:26Z | [
"python",
"arrays"
] |
group elements in an array and sum | 38,669,307 | <p>I have the following array</p>
<pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
</code></pre>
<p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p>
<pre><code>b = [1,0,2,0,3,0,1]
</code></pre>
<p>Any suggestions... | -2 | 2016-07-30T00:46:00Z | 38,669,382 | <p>Simply, most pythonicly would be the following</p>
<pre><code>b = [sum(a[i:i+3]) for i in range(0, len(a), 3)]
</code></pre>
<p>where your input array is <code>a</code>.</p>
<pre><code>>>> a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
>>> b = [sum(a[i:i+3]) for i in range(0, len(a), 3)]
>&g... | 3 | 2016-07-30T01:00:42Z | [
"python",
"arrays"
] |
group elements in an array and sum | 38,669,307 | <p>I have the following array</p>
<pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
</code></pre>
<p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p>
<pre><code>b = [1,0,2,0,3,0,1]
</code></pre>
<p>Any suggestions... | -2 | 2016-07-30T00:46:00Z | 38,669,390 | <p>You can split in chunk and sum:</p>
<pre><code>step = 3
[sum(a[i:i+step]) for i in range(0, len(a),step)]
[1, 0, 2, 0, 3, 0, 1]
</code></pre>
<p>If the length is not the multiple of step, last chunk might be smaller.</p>
| 2 | 2016-07-30T01:02:11Z | [
"python",
"arrays"
] |
group elements in an array and sum | 38,669,307 | <p>I have the following array</p>
<pre><code>a = [0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1]
</code></pre>
<p>I want to group every 3rd element and sum all of the elements within each group. So I can get a new array with a new size showing this sum</p>
<pre><code>b = [1,0,2,0,3,0,1]
</code></pre>
<p>Any suggestions... | -2 | 2016-07-30T00:46:00Z | 38,669,471 | <p>Another option using <code>groupby</code> from <code>itertools</code>:</p>
<pre><code>from itertools import groupby
[sum(v for _, v in g) for _, g in groupby(enumerate(a), key = lambda x: x[0]/3)]
# [1, 0, 2, 0, 3, 0, 1]
</code></pre>
<p>Or another way to use <code>zip</code>:</p>
<pre><code>[sum(v) for v in zip(... | 1 | 2016-07-30T01:17:06Z | [
"python",
"arrays"
] |
Python thread is not threading | 38,669,374 | <p>I've been looking all over google and can't seem to get this working.
I'm trying to thread 2 functions, both of which are infinite loops.</p>
<p>Looking at the extract below, it only starts the 1st thread and does not proceed to the next one in line.</p>
<p>PS: When I swap the 2 threads around, then I have the sam... | -2 | 2016-07-30T00:59:58Z | 38,669,529 | <p>The reason why only the first thread is executed is that you actually have ONLY one thread in your program. When you write <code>thread1 = cleanup_old_logs_service()</code> and <code>thread2 = syslog_service()</code>you are not creating new threads, but just assigning the return values of your functions to 2 differe... | 1 | 2016-07-30T01:27:27Z | [
"python",
"multithreading"
] |
Python thread is not threading | 38,669,374 | <p>I've been looking all over google and can't seem to get this working.
I'm trying to thread 2 functions, both of which are infinite loops.</p>
<p>Looking at the extract below, it only starts the 1st thread and does not proceed to the next one in line.</p>
<p>PS: When I swap the 2 threads around, then I have the sam... | -2 | 2016-07-30T00:59:58Z | 38,669,532 | <p>By saying <code>thread1 = cleanup_old_logs_service()</code> you are actually executing the function <code>cleanup_old_logs_service</code> not saving a reference to a thread. You would have to say</p>
<pre><code>import threading # If you have not already
thread1 = threading.Thread(target=cleanup_old_logs_service)
t... | 0 | 2016-07-30T01:27:38Z | [
"python",
"multithreading"
] |
How to choose only consecutive numbers from a list using python | 38,669,527 | <p>I did research and tried the code below. It almost works but I only want the consecutive numbers in the result. That would be [100,101,102]. I do not want the [75], [78], [109] in the result.</p>
<pre><code>from operator import itemgetter
from itertools import groupby
data = [75, 78, 100, 101, 102, 109]
for k, g in... | 1 | 2016-07-30T01:26:47Z | 38,669,554 | <p><code>g</code> in your example is the iterable of elements (e.g., [75], or [100, 101, 102]). If you only want consecutive number<strong>s</strong>, it sounds like you're looking to print all <code>g</code>s where there are greater than one elements in <code>g</code> [Note, <code>g</code> is actually an iterable, bu... | 2 | 2016-07-30T01:35:29Z | [
"python"
] |
django 1.8.13 'User' object has no attribute 'user' | 38,669,568 | <p>I have a problem with the method Login(), the variable 'user' if it contains the user but that method fails. could help detect the problem.</p>
<pre><code>from django.contrib.auth import authenticate, login
def login(request):
if request.user.is_authenticated():
return render(request, 'Default.html')
mensaje ... | 1 | 2016-07-30T01:39:00Z | 38,669,579 | <p>Also, according to the documentation, <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.login" rel="nofollow"><code>login()</code></a> function <em>expects 2 arguments</em> to be passed in - a request instance and a user model instance:</p>
<pre><code>login(request, User)
</cod... | 0 | 2016-07-30T01:40:12Z | [
"python",
"django",
"user"
] |
django 1.8.13 'User' object has no attribute 'user' | 38,669,568 | <p>I have a problem with the method Login(), the variable 'user' if it contains the user but that method fails. could help detect the problem.</p>
<pre><code>from django.contrib.auth import authenticate, login
def login(request):
if request.user.is_authenticated():
return render(request, 'Default.html')
mensaje ... | 1 | 2016-07-30T01:39:00Z | 38,669,625 | <p>You are importing login from django.contrib.auth but look at your very next line of code.</p>
<pre><code>from django.contrib.auth import authenticate, login
def login(request):
if request.user.is_authenticated():
return render(request, 'Default.html')
</code></pre>
<p>Yep, you are shadowing that login... | 0 | 2016-07-30T01:49:13Z | [
"python",
"django",
"user"
] |
Video Stream in GTK Window? | 38,669,627 | <p>Is there any way to embed a video stream (ffmpeg) in a GTK Window? Right now I am using Glade along with the Python GTK3 bindings, and I don't see any obvious methods provided by Glade.</p>
<p>Perhaps a library or something part of GTK3 not exposed in Glade?</p>
| 0 | 2016-07-30T01:50:05Z | 38,678,374 | <p>The easiest way is by using GStreamer. They have a few docs over it: <a href="http://docs.gstreamer.com/display/GstSDK/Basic+tutorial+5%3A+GUI+toolkit+integration" rel="nofollow">http://docs.gstreamer.com/display/GstSDK/Basic+tutorial+5%3A+GUI+toolkit+integration</a></p>
<p>Setting it in Glade directly probably won... | 0 | 2016-07-30T20:50:45Z | [
"python",
"user-interface",
"video",
"gtk3",
"glade"
] |
Tastypie using custom detail_uri_name, mismatched type error | 38,669,717 | <p>I am trying to override <code>get_bundle_detail_data</code></p>
<pre><code>class MyResourse(ModelResource):
foo = fields.CharField( attribute = 'modelA__variableOnModelA' )
def get_bundle_detail_data(self, bundle):
return bundle.obj.foo
class Meta:
resource_name='resource'
</code></... | 4 | 2016-07-30T02:08:36Z | 38,793,845 | <p>It looks like you need to override <code>detail_uri_kwargs</code> for your resource.</p>
<p>I wound up with something like this:</p>
<pre><code>from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.bundle import Bundle
from .models import AgoraUser
class AgoraUserResourse(ModelR... | 1 | 2016-08-05T16:24:48Z | [
"python",
"django",
"model",
"tastypie"
] |
How do I pass variables between two different python scripts I have | 38,669,746 | <p>I'm trying to pass information between two different python scripts. They're quite long, so for simplification purposes, here are two other scripts where I encounter the same issue: </p>
<p>a.py</p>
<pre><code>f = open('test.txt', 'w+')
num = int(raw_input('How many are there: '))
tipe = raw_input('What kind are t... | 1 | 2016-07-30T02:14:10Z | 38,669,849 | <p>When passing variables between Python scripts, remember that when you call a script, the calling script can access the namespace of the called script. </p>
<p>That being said, you could give this a try: Start the called script with the code</p>
<pre><code>from __main__ import *
</code></pre>
<p>This grants access... | 0 | 2016-07-30T02:35:13Z | [
"python",
"variables",
"import",
"module"
] |
How do I pass variables between two different python scripts I have | 38,669,746 | <p>I'm trying to pass information between two different python scripts. They're quite long, so for simplification purposes, here are two other scripts where I encounter the same issue: </p>
<p>a.py</p>
<pre><code>f = open('test.txt', 'w+')
num = int(raw_input('How many are there: '))
tipe = raw_input('What kind are t... | 1 | 2016-07-30T02:14:10Z | 38,672,297 | <p>you can pass them through functions</p>
<p><strong>a.py</strong></p>
<pre><code>f = open('test.txt', 'w+')
num = int(raw_input('How many are there: '))
tipe = raw_input('What kind are they: ')
if __name__ == '__main__':
from b import fxn
for x in xrange(num, num+11):
fxn(num, tipe, f) # Pass para... | 0 | 2016-07-30T09:14:15Z | [
"python",
"variables",
"import",
"module"
] |
excel converts a string of format "MM/DD/YYYY HH:MM:SS" to a date of format "MM/DD/YYYY HH:MM" | 38,669,754 | <p>I am using python's csv module to write a list to a csv file. One of the entries in the list is a string of format <code>"MM/DD/YYYY HH:MM:SS AM/PM"</code>. When i open the csv file using excel, the format of this entry is showing up as
<code>"MM/DD/YYYY HH:MM"</code>. On highlighting the cell I can see the formula... | -1 | 2016-07-30T02:16:05Z | 38,678,787 | <ul>
<li>select your cell(s)</li>
<li>right click</li>
<li>format cells </li>
<li>custom</li>
<li>type in [$-409]mm/dd/yyyy hh:mm:ss AM/PM;@</li>
<li>press ok</li>
</ul>
<p>Some items may be named slightly different as I translated this from a German Excel version.</p>
| 0 | 2016-07-30T21:47:15Z | [
"python",
"excel",
"csv"
] |
How to remove elements in a list based on another list in python, without loops? | 38,669,859 | <p>I have two lists of equal length:</p>
<pre><code>list_a = ['a','b','c','d']
list_b = [-6.3, 3.1, 0.5, 4.1]
</code></pre>
<p>I want to remove the elements < 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p>
<pre><code>list_a_2 = ['b','d']
list_b_2 = [3.1, 4.1]
</code></pr... | 2 | 2016-07-30T02:38:22Z | 38,669,913 | <p>One way is to use <code>zip</code>:</p>
<pre><code>list_a_2, list_b_2 = zip(*[(a, b) for a, b in zip(list_a, list_b) if b > 0.7])
list_a_2
# ('b', 'd')
list_b_2
# (3.1, 4.1)
</code></pre>
<p>If a for loop is better suited, you can create two empty lists and conditionally append the values to them:</p>
<pr... | 6 | 2016-07-30T02:48:14Z | [
"python"
] |
How to remove elements in a list based on another list in python, without loops? | 38,669,859 | <p>I have two lists of equal length:</p>
<pre><code>list_a = ['a','b','c','d']
list_b = [-6.3, 3.1, 0.5, 4.1]
</code></pre>
<p>I want to remove the elements < 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p>
<pre><code>list_a_2 = ['b','d']
list_b_2 = [3.1, 4.1]
</code></pr... | 2 | 2016-07-30T02:38:22Z | 38,669,940 | <p>Without explicit loops, create both? Sure, if we use a temporary object:</p>
<pre><code>list_a = ['a','b','c','d']
list_b = [-6.3, 3.1, 0.5, 4.1]
tmp = zip(a, b)
list_a_2 = [x[0] for x in tmp if x[1] > 0.7]
list_b_2 = [x[1] for x in tmp if x[1] > 0.7]
del tmp
</code></pre>
<p>But using an actual for-loop wil... | 1 | 2016-07-30T02:55:17Z | [
"python"
] |
How to remove elements in a list based on another list in python, without loops? | 38,669,859 | <p>I have two lists of equal length:</p>
<pre><code>list_a = ['a','b','c','d']
list_b = [-6.3, 3.1, 0.5, 4.1]
</code></pre>
<p>I want to remove the elements < 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p>
<pre><code>list_a_2 = ['b','d']
list_b_2 = [3.1, 4.1]
</code></pr... | 2 | 2016-07-30T02:38:22Z | 38,670,098 | <p>If you really want to avoid loops you can use a recursive function:</p>
<pre><code>def unnecessarily_recursive_function(list_a,list_b):
try:
a = list_a.pop(0)
b = list_b.pop(0)
tmp_a, tmp_b = unnecessarily_recursive_function(list_a,list_b)
if b < 0.7:
return [a] + ... | 0 | 2016-07-30T03:32:23Z | [
"python"
] |
How to remove elements in a list based on another list in python, without loops? | 38,669,859 | <p>I have two lists of equal length:</p>
<pre><code>list_a = ['a','b','c','d']
list_b = [-6.3, 3.1, 0.5, 4.1]
</code></pre>
<p>I want to remove the elements < 0.7 in list_b, and simultaneously remove the corresponding elements from list_a, i.e.</p>
<pre><code>list_a_2 = ['b','d']
list_b_2 = [3.1, 4.1]
</code></pr... | 2 | 2016-07-30T02:38:22Z | 38,680,355 | <p>Thanks a lot! For other people having a same problem:</p>
<p>I end up with the following code:</p>
<pre><code>list_a = ['a','b','c','d']
list_b = [-6.3, 3.1, 0.5, 4.1]
tmp = zip(a, b)
list_a_2 = [x[0] for x in tmp if x[1] > 0.7]
list_b_2 = [x[1] for x in tmp if x[1] > 0.7]
del tmp
</code></pre>
<p>And a bet... | 0 | 2016-07-31T02:59:41Z | [
"python"
] |
Excel add-in removed without consent | 38,669,887 | <p>I have programmed an excel add-in in VBA that makes calls to a MySQL server using python. My problem is the following : </p>
<p>every once in a while, for no apparent reason, the add-in gets removed from the developer tab, and I can't access its code anymore. The way around this problem is to uninstall and reinstal... | 2 | 2016-07-30T02:44:02Z | 38,670,601 | <p>Here is how I would do it IF I am facing the same issue as yours</p>
<ol>
<li>Close all open workbooks in Excel</li>
<li>Create a new subroutine called <code>Auto_Open</code> in a Blank Excel File</li>
<li>Add the code which is mentioned at the bottom of this post</li>
<li>Save it to <code>C:\Users\<your usernam... | 3 | 2016-07-30T05:21:32Z | [
"python",
"excel",
"vba",
"excel-vba",
"xlwings"
] |
Retain ordering of text data when vectorizing | 38,669,905 | <p>I am attempting to write a machine learning algorithm with <code>scikit-learn</code> that parses text and classifies it based on training data.</p>
<p>The example for using text data, taken directly from the <code>scikit-learn</code> documentation, uses a <code>CountVectorizer</code> to generate a sparse array for ... | 4 | 2016-07-30T02:47:22Z | 38,670,377 | <p>What about <a href="https://www.tensorflow.org/versions/r0.10/tutorials/word2vec/index.html" rel="nofollow">word2vec embedding?</a> It is a neural network based embedding of words into vectors, and takes context into account. This could provide a more sophisticated set of features for your classifier.</p>
<p>One po... | 1 | 2016-07-30T04:37:00Z | [
"python",
"python-3.x",
"order",
"scikit-learn",
"nltk"
] |
TensorFlow/TFLearn -Architecture Err - 'ValueError: Cannot feed value of shape (64,) for Tensor u'TargetsData/Y:0', which has shape '(?, 1)' | 38,670,055 | <p>I tried tflearn Quickstart titanic tutorial successfully and made some tests further.
I was predicting a float target by 8 float inputs, and I modified some of the tutorial then
'ValueError: Cannot feed value of shape (64,) for Tensor u'TargetsData/Y:0', which has shape '(?, 1)''</p>
<h1>Build neural network</h1>
... | 0 | 2016-07-30T03:22:15Z | 38,670,172 | <p>I have never used TensorFlow but I bet this is just a broadcasting issue. Try to change the shape of your problematic array which currently has shape (64,) into (64,1), that is from a row vector to a column vector:</p>
<pre><code>my_array.shape = (64, 1)
</code></pre>
<p>or more generally for any length:</p>
<pre... | 1 | 2016-07-30T03:49:14Z | [
"python",
"neural-network",
"deep-learning"
] |
Saving wxPython scrolledcanvas contents to image | 38,670,168 | <p>I've been trying this for a bit and haven't found a solution that works for me</p>
<p>I have a <code>wx.scrolledcanvas</code> that I'm trying to save to an image, however when i use the answers I've found they all save only the visible portion of the canvas, and not the full canvas. Is there any way to save the ent... | 0 | 2016-07-30T03:48:30Z | 38,679,469 | <p>Refactor your code such that what you are drawing in your <code>EVT_PAINT</code> handler can be called passing it the <code>wx.DC</code> to be drawn upon, and then call that from your paint handler with the <code>wx.PaintDC</code> or whatever you are currently using. When you want to save it to an image call the sa... | 1 | 2016-07-30T23:35:55Z | [
"python",
"wxpython"
] |
Different results from BeautifulSoup each time | 38,670,187 | <p>I'm doing a web scrape of a website with 122 different pages with 10 entries per page. The code breaks on random pages, on random entries each time it is ran. I can run the code on a url one time and it works while other times it does not.</p>
<pre><code>def get_soup(url):
soup = BeautifulSoup(requests.get(url)... | 3 | 2016-07-30T03:53:41Z | 38,673,300 | <p>There are slight discrepancies in the html for various elements as you progress through the site pages, the best way to get the name is actually to select the outer div and extract the text from the anchor.</p>
<p>This will get all the info from each product and put it into dicts where the keys are <em>'Tissue', '... | 2 | 2016-07-30T11:15:19Z | [
"python",
"beautifulsoup"
] |
curl https://pypi.python.org/simple/pip returns nothing | 38,670,217 | <p>I have run into a very strange error on my MacBook. I've seen some similar posts but none of them solved my issue.</p>
<p>I've been trying to install some Python libraries, and I tried to use curl to view this link: <a href="https://pypi.python.org/simple/pip/" rel="nofollow">https://pypi.python.org/simple/pip/</a>... | 0 | 2016-07-30T04:00:24Z | 38,670,227 | <p>Try using curl in verbose mode to see why:</p>
<pre><code>curl -v https://pypi.python.org/simple/pip
</code></pre>
<p>The response is a permanent redirect. It works if you append a trailing slash as follows:</p>
<pre><code>curl https://pypi.python.org/simple/pip/
</code></pre>
| 2 | 2016-07-30T04:03:29Z | [
"python",
"osx",
"curl"
] |
Fastest way to xor all integers in a string | 38,670,246 | <p>I am trying to find the fastest way of xor'ing all integers(numerals actually) in a string consecutively. The problem makes me feel that there is an simple and a fast answer I just can't think of. But here what I came up with so far.</p>
<p><strong>Setup:</strong></p>
<pre><code>from operator import xor
a = "123"
... | 0 | 2016-07-30T04:07:16Z | 38,670,540 | <p>On my (Python 3) system, this rework of the solution runs measureably faster than those shown:</p>
<pre><code>from operator import xor
from functools import reduce
print(15 & reduce(xor, map(ord, a)))
</code></pre>
<p>If we know they are all digits, <code>15 & ord('5')</code> pulls out the bits we need wi... | 1 | 2016-07-30T05:07:22Z | [
"python",
"performance",
"complexity-theory",
"xor"
] |
python get time stamp on file in mm/dd/yyyy-HH:MM format | 38,670,267 | <p>I'm trying to get the datestamp on the file in mm-dd-yyyy-hh:mm format.</p>
<pre><code>time.ctime(os.path.getmtime(file))
</code></pre>
<p>gives me detailed time stamp:</p>
<pre><code>Fri Jun 07 16:54:31 2013
</code></pre>
<p>How can I display the output as:</p>
<pre><code>06-07-2013-16:54
</code></pre>
<p>Thi... | 0 | 2016-07-30T04:11:16Z | 38,670,284 | <p>Just found it, I needed to add %H:%M like below:</p>
<pre><code>time.strftime('%m-%d-%Y-%H:%M', time.gmtime(os.path.getmtime())
</code></pre>
| 0 | 2016-07-30T04:15:47Z | [
"python",
"date",
"unix-timestamp"
] |
Raspberry pi:sudo is not working | 38,670,270 | <p>I have logged into raspberry pi via SSH. I m getting error while run any command with sudo in raspberry pi3. Eroor is like sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set.So i dont know how to set it and this error is about what? If root user require than plz tell me what is root user and how ... | 0 | 2016-07-30T04:11:37Z | 38,724,812 | <p>Login with root </p>
<pre><code>su -
</code></pre>
<p>and </p>
<pre><code>chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
</code></pre>
| 0 | 2016-08-02T15:33:54Z | [
"python",
"windows",
"putty",
"raspberry-pi3"
] |
Are Boto3 Resources and Clients Equivalent? When Use One or Other? | 38,670,372 | <p>Boto3 Mavens,</p>
<p>What is the functional difference, if any, between Clients and Resources?</p>
<p>Are they functionally equivalent?</p>
<p>Under what conditions would you elect to invoke a Boto3 Resource vs. a Client (and vice-versa)?</p>
<p>Although I've endeavored to answer this question by RTM...regrets, ... | 4 | 2016-07-30T04:36:28Z | 38,707,084 | <p>Resources are just a resource-based abstraction over the clients. They can't do anything the clients can't do, but in many cases they are nicer to use. They actually have an embedded client that they use to make requests. The downside is that they don't always support 100% of the features of a service.</p>
| 2 | 2016-08-01T19:55:55Z | [
"python",
"amazon-web-services",
"boto3"
] |
Unsuccessful attempts to post request for form submission | 38,670,424 | <p>I am working on my first project using python to submit a form and retrieve weather data from <a href="http://www.weather.gov" rel="nofollow">http://www.weather.gov</a></p>
<p>I am brand new to HTTP form submission and as such it is highly possible I am going about this all wrong. I've read that mechanize and/or se... | 1 | 2016-07-30T04:47:41Z | 38,670,513 | <p>Post to the URL <a href="http://forecast.weather.gov/zipcity.php" rel="nofollow">http://forecast.weather.gov/zipcity.php</a>
That is where the php script lies for receiving post data from the form.</p>
| 0 | 2016-07-30T05:02:36Z | [
"python",
"forms",
"python-requests",
"urllib2",
"urllib"
] |
How to set angularjs input value using selenium(python) | 38,670,502 | <p>In the target webpage, there is an angularjs input element:</p>
<pre><code><input type="text" class="form-control ng-pristine ng-valid ng-valid-maxlength ng-touched" placeholder="Role name" ng-model="selectedRole.roleName" maxlength="50">
</code></pre>
<p><a href="http://i.stack.imgur.com/3RcFa.jpg" rel="nof... | 1 | 2016-07-30T05:00:58Z | 38,670,571 | <p>Once you've located the <code>input</code> element, just <em>send the keys</em> to it:</p>
<pre><code>role_name = driver.find_element_by_css_selector('input[ng-model="selectedRole.roleName"]')
role_name.send_keys("test")
</code></pre>
| 0 | 2016-07-30T05:14:12Z | [
"python",
"angularjs",
"selenium"
] |
How to set angularjs input value using selenium(python) | 38,670,502 | <p>In the target webpage, there is an angularjs input element:</p>
<pre><code><input type="text" class="form-control ng-pristine ng-valid ng-valid-maxlength ng-touched" placeholder="Role name" ng-model="selectedRole.roleName" maxlength="50">
</code></pre>
<p><a href="http://i.stack.imgur.com/3RcFa.jpg" rel="nof... | 1 | 2016-07-30T05:00:58Z | 38,671,308 | <p>I think you need to wait before send_keys using <code>WebDriverWait</code> until element to be visible as below :</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDr... | 0 | 2016-07-30T07:05:42Z | [
"python",
"angularjs",
"selenium"
] |
How to set angularjs input value using selenium(python) | 38,670,502 | <p>In the target webpage, there is an angularjs input element:</p>
<pre><code><input type="text" class="form-control ng-pristine ng-valid ng-valid-maxlength ng-touched" placeholder="Role name" ng-model="selectedRole.roleName" maxlength="50">
</code></pre>
<p><a href="http://i.stack.imgur.com/3RcFa.jpg" rel="nof... | 1 | 2016-07-30T05:00:58Z | 39,207,980 | <p>You can simply access and set value using the below code.</p>
<pre><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver.find_element_by_xpath("//input[@ng-model = 'selectedRole.roleName']")
... | 0 | 2016-08-29T13:51:00Z | [
"python",
"angularjs",
"selenium"
] |
How to add comment box and post form to django rest framework | 38,670,510 | <p>I created a site by following a django rest framework tutorial(<a href="http://192.241.153.25:8000" rel="nofollow">http://192.241.153.25:8000</a>)</p>
<p>and i finished hooking up login part and posts,
but i have no clue in what way how i can put a posting form and comment box for the individual post.</p>
<p>here... | 0 | 2016-07-30T05:02:26Z | 38,670,928 | <p>This may work for you:
views.py :-</p>
<pre><code>def adComment(request):
print request
if request.method == 'POST':
form = CommentForm(request.POST) #Validate your data with form.
if form.is_valid():
instance = form.save(commit=False)
instance.title = form.cleaned_d... | 0 | 2016-07-30T06:13:25Z | [
"jquery",
"python",
"angularjs",
"django"
] |
How to add comment box and post form to django rest framework | 38,670,510 | <p>I created a site by following a django rest framework tutorial(<a href="http://192.241.153.25:8000" rel="nofollow">http://192.241.153.25:8000</a>)</p>
<p>and i finished hooking up login part and posts,
but i have no clue in what way how i can put a posting form and comment box for the individual post.</p>
<p>here... | 0 | 2016-07-30T05:02:26Z | 38,672,202 | <p>Look at this exapmle:</p>
<p>models.py</p>
<pre><code>class Post(models.Model):
title = models.CharField(max_length=500)
body = models.TextField()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post)
text = models.TextField()
author = m... | 0 | 2016-07-30T09:04:59Z | [
"jquery",
"python",
"angularjs",
"django"
] |
Python: how to save the output to a text file? | 38,670,522 | <p>1.
I tried with -o
werwe wer wer wer we
2.and >>text.txtrr
rrrrrrrrrrrrrrrrrrrrrrrr</p>
<pre><code> # -*- coding: iso-8859-15
import sys
import requests
import os
if len(sys.argv) >= 2:
os.system('clear')
print "Please wait.."`enter code here`
P1 = st... | -2 | 2016-07-30T05:04:15Z | 38,671,178 | <p>First, this isn't a well-put question. You don't state what your error is, or what you expected to happen. But, there are some obvious things in your code that we can fix. </p>
<p>You seem to be mixing up shell commands and python code, after you've taken in sys.argv. </p>
<pre><code>r = requests.get(url,params=... | 0 | 2016-07-30T06:47:59Z | [
"python",
"save",
"output"
] |
Split a pandas column of dictionaries into multiple columns | 38,670,535 | <p>I have the following csv with first row as header:</p>
<pre><code>id,data
a,"{'1': 0.7778, '3': 0.5882, '2': 0.9524, '4': 0.5556}"
b,"{'1': 0.7778, '3': 0.5, '2': 0.7059, '4': 0.2222}"
c,"{'1': 0.8182, '3': 0.2609, '2': 0.5882}"
</code></pre>
<p>I need to get to something like this</p>
<pre><code>id 1 ... | 5 | 2016-07-30T05:06:05Z | 38,670,637 | <p>You can do this with Python's <a href="https://docs.python.org/2/library/ast.html"><code>ast</code></a> module:</p>
<pre><code>import ast
import pandas as pd
df = pd.read_csv('/path/to/your.csv')
dict_df = pd.DataFrame([ast.literal_eval(i) for i in df.data.values])
>>> dict_df
1 2 3 ... | 5 | 2016-07-30T05:27:29Z | [
"python",
"pandas"
] |
i want to write python file out put to xls or xlxs file | 38,670,621 | <p>I want to write username and output (taksh) in xls file. i want to do it for 1000 to 5000 users. i am new to Python and work as PBX engineer.</p>
<p>my code and out put is below:</p>
<pre><code>import requests
import xml.etree.ElementTree as ET
# this statement performs a GET on the specified url
response = reque... | -4 | 2016-07-30T05:24:12Z | 38,670,663 | <p>you could check python pandas library</p>
<p>you dataframe will looks something simillar to this:</p>
<pre><code>df1 = pd.DataFrame( data={ "user":data1,"name":data2} )
</code></pre>
<p>where data1,data2 are the list containing the result after parsing.
create a data frame by parsing the file .</p>
<pre><code>&g... | 0 | 2016-07-30T05:33:25Z | [
"python"
] |
Regex uppercase certain letters | 38,670,704 | <p>I would like to use regex to uppercase the letter c in certain circumstances (e.g.) if the C is for Celsius. My regex so far:</p>
<pre><code>((?!\s)[c](?=\s)|(?!\d)[c](?=\d)|[c](?=-))
</code></pre>
<p>Example text:</p>
<pre><code>Some plastic insert c lids were cracked, temperature was between 8c and 8.8c.
</code... | -2 | 2016-07-30T05:40:14Z | 38,670,811 | <p>You need <code>(?<=...)</code> instead of <code>(?!...)</code>, the former stands for <em>look behind</em> while the latter stands for <em>negative look ahead</em>, if you want to replace <code>c</code> after space or digits, then you need to use <em>look behind</em> constraint:</p>
<pre><code>str1 = "Some plast... | 0 | 2016-07-30T05:54:04Z | [
"python",
"regex"
] |
Looping through user input and adding it to a list of unknown length | 38,670,710 | <p>The code ask the user 5 questions and they will answer it and then those 5 answers will be one element of a new list of unknown length as
<p>What I mean is I don't know how many horses the user will bet on one day. If the user bets 6 horses in one day then the new list will have have 6 elements with each element b... | 0 | 2016-07-30T05:41:09Z | 38,670,771 | <p>You add it all to some final list?</p>
<pre><code>final_list = []
while True:
add_selection =raw_input("Would you like to add a selection?").lower()
if add_selection == "yes":
selection = raw_input('Horse: ')
print selection
stake = float(raw_input('Stake: '))
... | 0 | 2016-07-30T05:49:21Z | [
"python",
"list",
"loops"
] |
Looping through user input and adding it to a list of unknown length | 38,670,710 | <p>The code ask the user 5 questions and they will answer it and then those 5 answers will be one element of a new list of unknown length as
<p>What I mean is I don't know how many horses the user will bet on one day. If the user bets 6 horses in one day then the new list will have have 6 elements with each element b... | 0 | 2016-07-30T05:41:09Z | 38,670,875 | <p>Create a list outside the scope of the loop then append to it based on user input. When they enter "No", leave the loop with <code>break</code> if you want to stay in the function, <code>return</code> if you want to leave the function.</p>
<p>You need to declare <code>inputs</code> before the loop in order to acce... | 0 | 2016-07-30T06:04:55Z | [
"python",
"list",
"loops"
] |
Python dictionary.get() default return not working | 38,670,755 | <p>I'm trying to create a dictionary from string to list of strings. So I thought I would use dict.get()'s default value keyword argument as such:</p>
<pre><code>read_failures = {}
for filename in files:
try:
// open file
except Exception as e:
error = type(e).__name__
read_failures[err... | 0 | 2016-07-30T05:47:35Z | 38,670,837 | <p>So this</p>
<pre><code>read_failures[error] = read_failures.get(error, []).append(filename)
</code></pre>
<p>sets the value of read_failures[error] to None because the .append method returns a None. Simple fix is to change this to:</p>
<pre><code>read_failures[error] = read_failures.get(error, []) + [filename]
</... | 0 | 2016-07-30T05:58:17Z | [
"python"
] |
Python dictionary.get() default return not working | 38,670,755 | <p>I'm trying to create a dictionary from string to list of strings. So I thought I would use dict.get()'s default value keyword argument as such:</p>
<pre><code>read_failures = {}
for filename in files:
try:
// open file
except Exception as e:
error = type(e).__name__
read_failures[err... | 0 | 2016-07-30T05:47:35Z | 38,670,949 | <p>As other comments and answers have pointed out, your issue is that <code>list.append</code> returns <code>None</code>, and so you can't assign the result of your call back to the dictionary. However, if the list is already in the dictionary, you don't need to reassign it, since <code>append</code> will modify it in ... | 2 | 2016-07-30T06:15:57Z | [
"python"
] |
python call function in get method of dictionary instead default value | 38,670,816 | <p>Need some help in order to understand some things in Python and <code>get</code> dictionary method. </p>
<p>Let's suppose that we have some list of dictionaries and we need to make some data transformation (e.g. get all names from all dictionaries by key <code>'name'</code>). Also I what to call some specific funct... | 0 | 2016-07-30T05:54:36Z | 38,670,847 | <p>If you want to avoid calling <code>func</code> if the dictionary contains the value, you can use this:</p>
<pre><code>def retrieve_data(value):
return ', '.join([v['name'] if 'name' in v else func(v) for v in value])
</code></pre>
<p>The reason <code>func</code> is called each time in your example is because i... | 2 | 2016-07-30T06:00:33Z | [
"python",
"dictionary"
] |
Make numpy matrix with insufficient length of data | 38,670,880 | <p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p>
<p>Eg:</p>
<pre><code>data = [0,4,1,3,2,5,9,6,7,8]
>>&g... | 3 | 2016-07-30T06:06:26Z | 38,670,965 | <p>I'm sure there are various ways of doing this. My first inclination is to make a <code>output</code> array filled with the 'fill', and copy the <code>data</code> to it. Since the fill is 'ragged', not a full column or row, I'd start out 1d and reshape to the final shape.</p>
<pre><code>In [730]: row,col = 3,4
In ... | 3 | 2016-07-30T06:18:41Z | [
"python",
"python-3.x",
"numpy"
] |
Make numpy matrix with insufficient length of data | 38,670,880 | <p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p>
<p>Eg:</p>
<pre><code>data = [0,4,1,3,2,5,9,6,7,8]
>>&g... | 3 | 2016-07-30T06:06:26Z | 38,670,966 | <p>Here is one option using <code>numpy.pad</code>, pad the data with -1 at the end of array and then reshape it:</p>
<pre><code>import numpy as np
data = [0,4,1,3,2,5,9,6,7,8]
row, col = 3, 4
np.pad(data, (0, row * col - len(data)), 'constant', constant_values = -1).reshape(row, col)
# array([[ 0, 4, 1, 3],
# ... | 1 | 2016-07-30T06:18:47Z | [
"python",
"python-3.x",
"numpy"
] |
Make numpy matrix with insufficient length of data | 38,670,880 | <p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p>
<p>Eg:</p>
<pre><code>data = [0,4,1,3,2,5,9,6,7,8]
>>&g... | 3 | 2016-07-30T06:06:26Z | 38,670,981 | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html" rel="nofollow"><code>np.ndarray.flat</code></a> to index into the flattened version of the array.</p>
<pre><code>data = [0, 4, 1, 3, 2, 5, 9, 6, 7, 8]
default_value = -1
desired_shape = (3, 4)
output = default_value * np.ones(... | 3 | 2016-07-30T06:20:12Z | [
"python",
"python-3.x",
"numpy"
] |
Make numpy matrix with insufficient length of data | 38,670,880 | <p>I have some data, say a list of 10 numbers and I have to convert that list to a matrix of shape (3,4). What would be the best way to do so, if I say I wanted the data to fill by columns/rows and the unfilled spots to have some default value like -1.</p>
<p>Eg:</p>
<pre><code>data = [0,4,1,3,2,5,9,6,7,8]
>>&g... | 3 | 2016-07-30T06:06:26Z | 38,671,684 | <p>I checked the solutions given based on speed. The tests was done using IPython 4.2.0 with Python 3.5.2|Anaconda 4.1.1 (64-bit).
The data array starts with 100,000 elements. The new dimentions are 150,000 x 150,000.</p>
<h3>M. Klugerford's solution (icreasing the data and reshaping):</h3>
<pre><code>%timeit data = ... | 3 | 2016-07-30T07:55:04Z | [
"python",
"python-3.x",
"numpy"
] |
Datetime picker and modal conflict angular ui bootstrap | 38,670,916 | <p>I have a problem, in one form, I have to create an angular pop up form so I use this tutorial <a href="https://angular-ui.github.io/bootstrap/#/modal" rel="nofollow">modal</a> and it worked well however my other field which is the date time picker got affected.</p>
<p>this is my code where I use modal:</p>
<pre><c... | 0 | 2016-07-30T06:11:57Z | 38,671,244 | <p>I see 2 problems with your approach:</p>
<ol>
<li><p>Using the multiple versions of a library will not work if it uses the same namespacing, which is the case. So either check, if the date-picker works with the latest ui-boostrap version es well. Or downgrade your code to the ui-bootstrap version that is required b... | 0 | 2016-07-30T06:55:57Z | [
"python",
"angularjs",
"django"
] |
How to test if a class had explicietly defined a __gt__? | 38,671,212 | <p>Is there a way to test whether a costume class had explicitly defined an attribute like <code>__gt__</code>? To put things in context consider these two classes:</p>
<pre><code>class myclass1:
def __init__(self, val):
self.val = val
def __gt__(self, other):
if type(other) is int:
... | 1 | 2016-07-30T06:51:53Z | 38,671,258 | <p>You can check inside the <code>__dict__</code> for each class:</p>
<pre><code>'__gt__' in x2.__class__.__dict__
Out[23]: False
'__gt__' in x1.__class__.__dict__
Out[24]: True
</code></pre>
<p>Or, using built-ins in order to not rely on dunders:</p>
<pre><code>'__gt__' in vars(type(x1))
Out[31]: True
'__gt__' in... | 2 | 2016-07-30T06:57:30Z | [
"python",
"python-3.x"
] |
Send email from python webapp2 Google App Engine | 38,671,257 | <p>i am trying to send an email from my application. The code run successfully with out error. But it do not send the email. It show this message on Console. </p>
<pre><code>You are not currently sending out real email.
If you have sendmail installed you can use it by using the
server with --enable_sendmail
</code><... | 2 | 2016-07-30T06:57:27Z | 38,674,023 | <p>That's because the dev_appserver by default doesn't send out real mails.</p>
<p>Email sending <strong>will work when you push to a live server</strong>, for eg:</p>
<pre><code>appcfg update /path/to/app/
</code></pre>
<p>But like the error message points out, you'll have to use the <code>--enable_sendmail</code> ... | 0 | 2016-07-30T12:34:02Z | [
"python",
"email",
"google-app-engine",
"webapp2"
] |
How to write a python script to print names of all folders and subfolders in a directory? | 38,671,269 | <p>im fairly new to python.i know how to list directories etc
but how to i get only the name of folder and its subfolders?</p>
<p>Thanks</p>
| -8 | 2016-07-30T06:59:04Z | 38,671,473 | <pre><code>import os
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
</code></pre>
| 1 | 2016-07-30T07:25:47Z | [
"python",
"folders"
] |
Does PyMySQL support Prepared Statements? | 38,671,286 | <p>Does PyMySQL support prepared statements?
I am trying to connect to MySQL from a python module.</p>
<p>I have checked documentation at <a href="http://pymysql.readthedocs.io" rel="nofollow" title="PyMySQL Documentation">http://pymysql.readthedocs.io</a> and didn't find anything useful.</p>
<p>No luck on skimming t... | 0 | 2016-07-30T07:02:27Z | 38,671,547 | <p>Yes it does. Please check the example below.
<pre><code>// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT IN... | 0 | 2016-07-30T07:36:35Z | [
"python",
"pymysql"
] |
Pandas dataframe: Getting row indices from criteria 1, sorted by criteria 2 | 38,671,386 | <p>I have data frames with the following structure:</p>
<pre><code>import pandas as pd
import numpy as np
data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']}
df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4'])
Col1 Col2 Col3 Col4
R1 ... | 2 | 2016-07-30T07:15:32Z | 38,671,561 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>:</p>
<pre><code>df[indeces].sort_values(['Col4'])
Col1 Col2 Col3 Col4
R3 6 30 -30 AAA
R2 5 20 50 BBB
</code></pre>
| 2 | 2016-07-30T07:39:26Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
TutorialsPoint - Flask â SQLAlchemy not working | 38,671,408 | <p>I did all that was stated on tutorial point (<strong>just copied and pasted</strong>), but when I tried to add a student entry,i.e. âAdd Studentâ it gives</p>
<p>Bad Request
The browser (or proxy) sent a request that this server could not understand.</p>
<p>Please advise if there is anything wrong with the tut... | -2 | 2016-07-30T07:17:49Z | 38,671,583 | <p>The tutorial has an indentation problem in the student class.
The constructor code should be indented one level so it becomes a method of the student class.</p>
<p>Corrected code: (note the indent of "def <strong>init</strong>(self, name, city, addr,pin):" and the code below)</p>
<pre><code>class students(db.Mode... | 3 | 2016-07-30T07:41:54Z | [
"python",
"sqlite",
"flask",
"sqlalchemy"
] |
TutorialsPoint - Flask â SQLAlchemy not working | 38,671,408 | <p>I did all that was stated on tutorial point (<strong>just copied and pasted</strong>), but when I tried to add a student entry,i.e. âAdd Studentâ it gives</p>
<p>Bad Request
The browser (or proxy) sent a request that this server could not understand.</p>
<p>Please advise if there is anything wrong with the tut... | -2 | 2016-07-30T07:17:49Z | 38,671,942 | <p>It's not following the <a href="https://www.python.org/dev/peps/pep-0008/#class-names" rel="nofollow">class naming</a> convention. The student class should use <a href="https://en.wikipedia.org/wiki/CamelCase" rel="nofollow">Camel case</a>. Try this:</p>
<pre><code>student = Students(request.form['name'], request.f... | 0 | 2016-07-30T08:26:01Z | [
"python",
"sqlite",
"flask",
"sqlalchemy"
] |
Pandas idxmax() not working as expected | 38,671,448 | <p>Suppose I have the following DataFrame <code>Q_df</code>:</p>
<pre><code> (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2)
(0, 0) 0.000 0.00 0.0 0.64 0.000 0.0 0.512 0.000 0.0
(0, 1) 0.000 0.00 0.8 0.00 0.512 0.0 0.000 0.512 0.0
(0, 2)... | 0 | 2016-07-30T07:22:20Z | 38,671,506 | <p>IIUC, you can use <code>axis=1</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a>:</p>
<pre><code>policy = Q_df.idxmax(axis=1)
(0, 0) (1, 0)
(0, 1) (0, 2)
(0, 2) (2, 2)
(1, 0) (1, 2)
(1, 1) (0, 1)
(1, 2) (2... | 1 | 2016-07-30T07:29:07Z | [
"python",
"pandas"
] |
How to install NS-3 simulator correctly using cygwin on windows 7 | 38,671,465 | <p>I need to run NS-3 simulator on my windows 7 so I installed cygwin and with devel, python and utils packages. I got a problem when I run <code>./build.py</code> command as the following : </p>
<pre><code>Traceback (most recent call last):
File "./build.py", line 10, in <module>
from util import run_comm... | 0 | 2016-07-30T07:24:43Z | 38,678,867 | <p>Following
<a href="https://www.nsnam.org/docs/release/3.25/tutorial/singlehtml/index.html#building-ns3" rel="nofollow">https://www.nsnam.org/docs/release/3.25/tutorial/singlehtml/index.html#building-ns3</a></p>
<p>seems to work. (first step 2357 files compiled, so a bit long)</p>
<p>To debug your problem and save... | 0 | 2016-07-30T21:59:30Z | [
"python",
"bash",
"python-2.7",
"cygwin",
"ns-3"
] |
How to split a statement based on dots ('.'), while excluding dots inside angular brackets(< . >) using regular expressions in python? | 38,671,627 | <p>I want to split statements by dots using regex in python, while excluding certain dots inside the angular brackets.
eg:
Original Statement :</p>
<pre><code>'my name 54. is <not23.> worth mentioning. ok?'
</code></pre>
<p>I want to split it into following sentences:</p>
<pre><code>Statement 1 : 'my name 54'
... | -1 | 2016-07-30T07:47:32Z | 38,671,662 | <p>Easy if you can user the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong><code>regex</code> module</strong></a> (it provides the <code>(*SKIP)(*FAIL)</code> functionality):</p>
<pre><code>import regex as re
string = 'my name 54. is <not23.> worth mentioning. ok?'
rx = re.compile(r"&... | 1 | 2016-07-30T07:51:51Z | [
"python",
"regex"
] |
How to split a statement based on dots ('.'), while excluding dots inside angular brackets(< . >) using regular expressions in python? | 38,671,627 | <p>I want to split statements by dots using regex in python, while excluding certain dots inside the angular brackets.
eg:
Original Statement :</p>
<pre><code>'my name 54. is <not23.> worth mentioning. ok?'
</code></pre>
<p>I want to split it into following sentences:</p>
<pre><code>Statement 1 : 'my name 54'
... | -1 | 2016-07-30T07:47:32Z | 38,671,813 | <p>Split on the following regex:</p>
<pre><code>\.(?![^<]*>)
</code></pre>
<p><a href="https://regex101.com/r/uL1uI5/1" rel="nofollow">Live demo</a></p>
<pre><code>import re
str = 'my name 54. is <not23.> worth mentioning. ok?'
regex = re.compile(r"\.(?![^<]*>)")
arr = regex.split(str)
print(arr)... | 1 | 2016-07-30T08:09:35Z | [
"python",
"regex"
] |
initialization of multiarray raised unreported exception python | 38,671,630 | <p>I am a new programmer who is picking up python. I recently am trying to learn about importing csv files using numpy.
Here is my code:</p>
<pre><code>import numpy as np
x = np.loadtxt("abcd.py", delimiter = True, unpack = True)
print(x)
</code></pre>
<p>The idle returns me with:</p>
<pre><code>>> True
>&... | 1 | 2016-07-30T07:48:01Z | 38,671,893 | <p>As there is an error at the import line, your installation of numpy is broken in some way. My guess is that you have installed numpy for python2 but are using python3. You should remove numpy and attempt a complete re-install, taking care to pick the correct version.</p>
<p>There are a few oddities in the code:
You... | 1 | 2016-07-30T08:20:11Z | [
"python",
"numpy"
] |
Early stopping and the sklearn neural_network.MLPClassifier | 38,671,718 | <p>I am using <a href="http://scikit-learn.org/dev/modules/generated/sklearn.neural_network.MLPClassifier.html" rel="nofollow"><code>sklearn.neural_network.MLPClassifier</code></a>. I am using the <code>early_stopping</code> feature, which evaluates performance for each iteration using a validation split (10% of the tr... | 0 | 2016-07-30T07:58:15Z | 38,732,224 | <p>The solution is to use sknn rather than the sklearn implementation of MLP. That allows use to add our own valid_set and specify the loss function. Details <a href="http://scikit-neuralnetwork.readthedocs.io/en/latest/module_mlp.html#classifier" rel="nofollow">here</a>. </p>
| 0 | 2016-08-02T23:50:06Z | [
"python",
"scikit-learn",
"neural-network",
"perceptron"
] |
Get right data from dict inside list | 38,671,722 | <p>I'm trying to get a video URL from tweet, <code>A</code> was taken from tweepy. Because twitter doesn't tell which one is the highest quality video I assume that I have to compare highest 'bitrate' and store the 'url' that corresponds with it. This is what I have. </p>
<p>Please bear with me, I'm new to this. </p>
... | -1 | 2016-07-30T07:58:50Z | 38,671,764 | <p>If you want to get dictionary (or url) with the highest bitrate:</p>
<p>This compares the items of the list of dictionaries using <code>bitrate</code> key and returns dictionary with the highest <code>bitrate</code>. </p>
<pre><code>max(A, key=lambda x:x['bitrate'])['url']
</code></pre>
<p><strong>EDIT:</strong> ... | 1 | 2016-07-30T08:04:09Z | [
"python",
"data-structures",
"data-dictionary"
] |
Python Selenium:: Element is Currently Invisible | 38,671,761 | <p>So I am accessing <a href="https://steemit.com/steem/@ozchartart/usdsteem-btc-technical-analysis-2-the-only-way-for-me-to-move-on-is-to-chart-it-in-the-dawn" rel="nofollow">this</a> link and with help of <a href="http://stackoverflow.com/a/38632255/275002">this</a> friend, I am able to progress a bit. Now I am stuck... | 1 | 2016-07-30T08:03:19Z | 38,673,200 | <p>Seems that you're trying to interract with another button. Try more specific selector:</p>
<pre><code>driver.find_element_by_xpath('//button[text()="Post"]').click()
</code></pre>
<p>This works for me</p>
| 1 | 2016-07-30T11:05:55Z | [
"python",
"selenium"
] |
Sort python dictionary for keys, split it and create a JSON Array from it | 38,671,766 | <p>I have this huge JSON file, which contains more than 80000 lines, looking like that:</p>
<pre><code>{u'hero_name': u'bristleback', u'gold_total': 17937, tick:24098}
{u'hero_name': u'silencer', u'gold_total': 10847, tick:24198}
{u'hero_name': u'silencer', u'gold_total': 11789, tick:25098}
{u'hero_name': u'weaver', u... | -2 | 2016-07-30T08:04:20Z | 38,672,645 | <p>You need to use the <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json</a> - there are other packages, but this one should do it.</p>
<ol>
<li>Load the JSON to a veriable using <code>open()</code></li>
<li>Convert to <code>dict</code> using <code>json.loads()</code></li>
</ol>
<p>For example... | 0 | 2016-07-30T10:01:08Z | [
"python",
"json",
"sorting",
"dictionary"
] |
MultiIndex from irregular tuple of tuples | 38,671,810 | <p>I have the following tuples</p>
<pre><code>tups = zip(list('AAAABBBB'), zip(list('aabbaabb'), list('cdcdcdcd')))
tups
[('A', ('a', 'c')),
('A', ('a', 'd')),
('A', ('b', 'c')),
('A', ('b', 'd')),
('B', ('a', 'c')),
('B', ('a', 'd')),
('B', ('b', 'c')),
('B', ('b', 'd'))]
</code></pre>
<p>I'd like to create... | 2 | 2016-07-30T08:09:21Z | 38,671,820 | <p>You'll have to flatten your tuples. I did it as follows</p>
<pre><code>new_tups = [(a, b, c) for a, (b, c) in tups]
df = pd.DataFrame(np.arange(32).reshape(4, 8),
columns=pd.MultiIndex.from_tuples(new_tups))
</code></pre>
<p><a href="http://i.stack.imgur.com/7DM6m.png" rel="nofollow"><img src="... | 2 | 2016-07-30T08:10:18Z | [
"python",
"pandas",
"multi-index"
] |
Python manual call to descriptor ignored | 38,671,838 | <pre><code>class B(object):
def meth(self):
pass
class C(B):
pass
b = B()
c = C()
print c.meth.__get__(b, B)
</code></pre>
<p>gives me:</p>
<pre><code><bound method C.meth of <__main__.C object at 0x10a892910>>
</code></pre>
<p>but I expect something like:</p>
<pre><code><bound met... | 0 | 2016-07-30T08:12:10Z | 38,672,210 | <p>The object you get when you lookup <code>c.meth</code> is a descriptor, but perhaps not the descriptor you were expecting. Rather, it's the <em>result</em> of a descriptor call (which just happens to be another kind of descriptor). Specifically, <code>c.meth</code> is an <code>instancemethod</code> object. It's what... | 1 | 2016-07-30T09:06:00Z | [
"python",
"python-2.7",
"inheritance",
"methods",
"descriptor"
] |
How to apply loop to extract contents from "DIV" tag while using Beautiful soup? | 38,671,845 | <p>i have recently found a very neat way of web scrapping using bs4 that has a really nice organized structure to it. let us say this is our html code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-ht... | 0 | 2016-07-30T08:13:27Z | 38,672,452 | <p>You code works fine for me, except for the syntax error: <code>find_hi-again</code> is not a valid variable name.</p>
<pre><code>divs = soup.find_all('div',{'class':'a'})
for i in divs:
find_hi = i.div.text.strip()
find_hi_again = i.find_all('div')[1].p.text.strip()
find_final = i.find('div',{'class':'... | 0 | 2016-07-30T09:34:33Z | [
"python",
"loops",
"tags",
"beautifulsoup",
"textwrangler"
] |
Pandas: slicing a dataframe into multiple sheets of the same spreadsheet | 38,672,018 | <p>Say I have 3 dictionaries of the same length, which I combine into a unique <code>pandas</code> dataframe. Then I dump said dataframe into an Excel file. Example:</p>
<pre><code>import pandas as pd
from itertools import izip_longest
d1={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
d2={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
... | 3 | 2016-07-30T08:40:53Z | 38,672,135 | <p>First prep your dataframe for writing like this:</p>
<pre><code>prepdf = mydf.groupby(mydf.index // 2).apply(lambda df: df.reset_index(drop=True))
prepdf
</code></pre>
<p><a href="http://i.stack.imgur.com/eGDyZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/eGDyZ.png" alt="enter image description here"></a... | 3 | 2016-07-30T08:56:07Z | [
"python",
"excel",
"pandas",
"dataframe",
"slice"
] |
Python super: calling a base class method which contains another base class method that is overriden by derived class | 38,672,395 | <pre class="lang-py prettyprint-override"><code>class A(object):
def foo(self):
print "A - foo"
def foo2(self):
print "foo2"
self.foo()
class B(A):
def foo(self):
print "B - foo"
def foo2(self):
super(B, self).foo2()
B().foo2()
</code></pre>
<p>I was trying to ... | 2 | 2016-07-30T09:27:35Z | 38,672,477 | <p>One way to do this is to call <code>foo</code> on <code>A</code> and pass <code>self</code> to it by hand:
</p>
<pre><code>class A(object):
def foo(self):
print("A - foo")
def foo2(self):
print("foo2")
A.foo(self)
class B(A):
def foo(self):
print("B - foo")
def foo2(... | 2 | 2016-07-30T09:38:34Z | [
"python"
] |
Python super: calling a base class method which contains another base class method that is overriden by derived class | 38,672,395 | <pre class="lang-py prettyprint-override"><code>class A(object):
def foo(self):
print "A - foo"
def foo2(self):
print "foo2"
self.foo()
class B(A):
def foo(self):
print "B - foo"
def foo2(self):
super(B, self).foo2()
B().foo2()
</code></pre>
<p>I was trying to ... | 2 | 2016-07-30T09:27:35Z | 38,672,625 | <p>As Leon pointed out you could simply access the <code>foo</code> method inside the <code>A</code> class by hardcoding the explicit call via <code>A.foo</code> and passing instance object as argument, however as Rawing has stated it's not good solution. Actually it's example of wrong class design. Why?</p>
<ol>
<li>... | 1 | 2016-07-30T09:58:51Z | [
"python"
] |
django rest framework how to define required fields per ViewSet action | 38,672,401 | <p>I am trying the tutorial from DRF and I found something confused.
I have a User model which simply extends auth.User like this</p>
<pre><code>class User(DefaultUser):
"""
Represents a registered User
"""
EMAIL_VALIDATOR_LENGTH = 6
email_validated = models.BooleanField(default=False)
# using a 6-digit numbers for ... | 0 | 2016-07-30T09:28:34Z | 38,674,465 | <p>Try to override serializer constructor to modify fields based on extra arguments. Didn't test that but it should work:</p>
<pre><code>class UserSerializer(ModelSerializer):
def __init__(self, *args, **kwargs):
super(UserSerializer, self).__init__(*args, **kwargs)
require_password = kwargs.get('... | 0 | 2016-07-30T13:29:08Z | [
"python",
"django",
"django-rest-framework"
] |
django rest framework how to define required fields per ViewSet action | 38,672,401 | <p>I am trying the tutorial from DRF and I found something confused.
I have a User model which simply extends auth.User like this</p>
<pre><code>class User(DefaultUser):
"""
Represents a registered User
"""
EMAIL_VALIDATOR_LENGTH = 6
email_validated = models.BooleanField(default=False)
# using a 6-digit numbers for ... | 0 | 2016-07-30T09:28:34Z | 38,681,955 | <p>I turned out to implement it myself, so I basically make all fields option but in actions, I added a decorator to ensure the request body has those specified keys in it. </p>
<p>decorator:</p>
<pre><code>class AssertInRequest(object):
"""
A decorator to decorate ViewSet actions, this decorator assumes the first
po... | 0 | 2016-07-31T07:59:19Z | [
"python",
"django",
"django-rest-framework"
] |
Code works in Java but not Python? | 38,672,495 | <p>This code seems to work in Java, but when I convert it to Python, it exceeds the maximum recursion depth and exits.. Not sure what the difference is. They look like they function identically to me.</p>
<p><strong>Java version:</strong></p>
<pre><code>public String addCommas(String number)
{
if(number.length <... | 1 | 2016-07-30T09:42:38Z | 38,672,538 | <p>The difference is in the last line.</p>
<pre><code> return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length);
</code></pre>
<p>This calls <code>addCommas</code> on the first substring only (which reduces the length of the string parameter for the next call... | 1 | 2016-07-30T09:48:01Z | [
"python",
"recursion"
] |
Code works in Java but not Python? | 38,672,495 | <p>This code seems to work in Java, but when I convert it to Python, it exceeds the maximum recursion depth and exits.. Not sure what the difference is. They look like they function identically to me.</p>
<p><strong>Java version:</strong></p>
<pre><code>public String addCommas(String number)
{
if(number.length <... | 1 | 2016-07-30T09:42:38Z | 38,672,702 | <p>The difference is in the last line </p>
<p>Java :
return addCommas(number.subString(0, number.length - 3)) + "," + number.subString(number.length - 3, number.length);</p>
<p>Python :
return addCommas(number[:len(number) - 3] + ',' + number[len(number) - 3:])</p>
<p>are not same. If you observe in java you are cal... | 0 | 2016-07-30T10:08:44Z | [
"python",
"recursion"
] |
Why can't pdb access a variable containing an exception? | 38,672,560 | <p>Sometime, I can't identify when or what's causing it, pdb will not help you with code like:</p>
<pre><code>try:
foo()
except Exception as e:
import pdb; pdb.set_trace()
</code></pre>
<p>You end up with the usual prompt, but trying to access <code>e</code> will lead to:</p>
<pre><code>(pdb) e
*** NameError:... | 1 | 2016-07-30T09:50:39Z | 38,672,659 | <p>In Python 3, the target of an <code>except .. as target</code> statement is cleared when the suite exits. From the <a href="https://docs.python.org/3/reference/compound_stmts.html#the-try-statement" rel="nofollow"><code>try</code> statement documentation</a>:</p>
<blockquote>
<p>When an exception has been assigne... | 3 | 2016-07-30T10:04:00Z | [
"python",
"python-3.x",
"debugging",
"exception",
"pdb"
] |
Select all checkboxes in django template | 38,672,675 | <p>I am using the following code to 'select all' and 'clear' the checkboxes of my django form in the django template. </p>
<pre><code> <form id="inv_form" method="post" action="{% url 'inventory:create_inventory' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Cr... | 0 | 2016-07-30T10:06:11Z | 38,672,846 | <p>You probably hate to unbind submit, then you can submit the form. </p>
<pre><code>$('some_form').unbind('submit').submit()
</code></pre>
<p>This approach should cancel <code>prevenDefault</code> so you can submit the form.</p>
| 0 | 2016-07-30T10:25:19Z | [
"javascript",
"python",
"django",
"django-forms",
"django-templates"
] |
Deploying django app with nginx and uwsgi, client can not connect to server | 38,672,691 | <p>I have been trying to solve this problem three entire days without solution. Now, I am under pressure at my work and I really need your help.</p>
<p>I know that nginx is listen to correct port '20154' using netstat, also I have run the command nginx -t and its ok. The logs have no error because client can not reach... | 1 | 2016-07-30T10:07:50Z | 38,673,406 | <p>This is the new configuration that worked for me, you can see the changes, also the command that I had to use, thanks.</p>
<p><strong>The new sites-enabled file:</strong></p>
<pre><code>upstream django {
server unix:///home/ctag/env_Compass4D/Compass4D/Compass4D.sock; # for a file socket
}
server {
lis... | 0 | 2016-07-30T11:26:21Z | [
"python",
"django",
"nginx",
"uwsgi"
] |
NaN in mapper - name 'nan' is not defined | 38,672,695 | <p>I do as below</p>
<pre><code>mapper = {'a': 'b', 'c': nan, 'd': 'e', nan : nan}
df['b'] = [ mapper[x] for x in df['a'] ]
df['b'].value_counts()
</code></pre>
<p>and</p>
<pre><code>NameError Traceback (most recent call last)
<ipython-input-48-3862b2347ce7> in <module>()... | -3 | 2016-07-30T10:08:19Z | 38,672,710 | <p>You didn't define what the variable <code>nan</code> is, so Python raises a <code>NameError</code>. If you want to check whether a number is <code>NaN</code> (not a number), use <code>math.isnan(x)</code>, where <code>x</code> is a float.</p>
| 0 | 2016-07-30T10:09:45Z | [
"python",
null
] |
NaN in mapper - name 'nan' is not defined | 38,672,695 | <p>I do as below</p>
<pre><code>mapper = {'a': 'b', 'c': nan, 'd': 'e', nan : nan}
df['b'] = [ mapper[x] for x in df['a'] ]
df['b'].value_counts()
</code></pre>
<p>and</p>
<pre><code>NameError Traceback (most recent call last)
<ipython-input-48-3862b2347ce7> in <module>()... | -3 | 2016-07-30T10:08:19Z | 38,672,715 | <p>Python does not have a built-in name <code>nan</code>, nor is there a keyword.</p>
<p>It looks as if you forgot to import it; <code>numpy</code> defines such a name:</p>
<pre><code>from numpy import nan
</code></pre>
<p>From the local name <code>df</code> I infer you are probably using pandas; pandas' documentati... | 2 | 2016-07-30T10:10:00Z | [
"python",
null
] |
Write specific data in one cell depending on contents of another cell in Pandas | 38,672,734 | <p>I am a Pandas newbie and I have a csv file with about 50 different columns. Some of them contain a "-1" value and the last column I have named "Holder" to store the results of some comparisons I make on the other columns.</p>
<p>Data is of the form</p>
<pre><code>Row 1:
Investments_Cash Holder
0 ... | 2 | 2016-07-30T10:11:52Z | 38,672,777 | <pre><code>df.loc[df.Investments_Cash == -1, 'Holder'] = 'Found'
</code></pre>
| 3 | 2016-07-30T10:17:20Z | [
"python",
"pandas"
] |
predict_proba(X) of RandomForestClassifier (sklearn) seems to be static? | 38,672,779 | <p>For all classes I want to retrieve the prediction-score/probability of a given sample. I'm using the RandomForestClassifier of sklearn. My code is running fine if I'm using <code>.predict()</code>. However to show the probabilites I'm using <code>.predict_proba(X)</code> and it returns always the same values, even t... | 1 | 2016-07-30T10:17:35Z | 38,675,888 | <p>I guess the problem is you are passing always the same argument to <code>predict_proba</code>. Here is my code to build a forest of trees from the iris dataset:</p>
<pre><code>from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
iris = datasets.load_iris()
X = iris.data
y = iris.target
r... | 1 | 2016-07-30T16:04:57Z | [
"python",
"scikit-learn",
"classification",
"probability",
"random-forest"
] |
pyspark saveAsSequenceFile with pyspark.ml.linalg.Vectors | 38,672,784 | <p>I try to save a (huge) list of sparse vectors as a sequence file and I get errors. Below is a dummy code:</p>
<pre class="lang-py prettyprint-override"><code>#used on pyspark shell
from pyspark.ml.linalg import Vectors
rdd = sc.parallelize([Vectors.sparse(5, {1:1,2:2}), Vectors.sparse(5, {3:3,4:4})])
rdd.zipWithInd... | 1 | 2016-07-30T10:18:26Z | 38,673,358 | <p>Native Hadoop libraries are not an issue here. The problem here is a <code>SparseVector</code> class itself. <code>ml</code> / <code>mllib</code> vectors heavily use native NumPy structures which cannot be handled by <code>Pyrolite</code> library.</p>
<p>Arguably using sequence files in PySpark to handle anything e... | 1 | 2016-07-30T11:20:31Z | [
"python",
"apache-spark",
"pyspark"
] |
keys of first data frame that appear in second one and flag that fact | 38,672,867 | <p>I have two Data Frames:</p>
<pre><code>data = {
'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'],
'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'],
'retailer_name': ['Walmart',... | 0 | 2016-07-30T10:27:51Z | 38,673,315 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.intersection.html" rel="nofollow">MultiIndex.intersection()</a> method if you make sure that both multiindexes have the same dtypes:</p>
<pre><code>In [74]: df2['flag'] = 0
In [75]: df2.ix[df2.index.intersection(df.index),... | 1 | 2016-07-30T11:16:27Z | [
"python",
"pandas",
"dataframe"
] |
Python 3.5 Windows cannot run Rodeo example? | 38,672,891 | <p>I just installed Python 3.5 on windows 10 and was trying to run the startup example from the IDE I choose (Rodeo). The example gives an error when trying to import ggplot. Specifically, at this call</p>
<pre><code>from ggplot import ggplot, aes, geom_bar
</code></pre>
<p>which gives me:</p>
<pre><code>ImportError... | 0 | 2016-07-30T10:31:17Z | 38,683,370 | <p>Well, I found a solution myself. <code>pip install ggplot --upgrade</code> failed for me, but
<code>conda install -c conda-forge ggplot</code> did the trick.</p>
| 0 | 2016-07-31T11:14:00Z | [
"python",
"python-ggplot",
"rodeo"
] |
Changing the value of range during iteration in Python | 38,672,963 | <pre><code>>>> k = 8
>>> for i in range(k):
print i
k -= 3
print k
</code></pre>
<p>Above the is the code which prints numbers from <code>0-7</code> if I use just <code>print i</code> in the for loop.</p>
<p>I want to understand the above code how it is working, and is there ... | 0 | 2016-07-30T10:40:06Z | 38,672,978 | <p>The expression <code>range(k)</code> is evaluated just <em>once</em>, not on every iteration. You can't set <code>k</code> and expect the <code>range(k)</code> result to change, no. From the <a href="https://docs.python.org/2/reference/compound_stmts.html#the-for-statement" rel="nofollow"><code>for</code> statement ... | 2 | 2016-07-30T10:42:14Z | [
"python",
"python-2.7",
"loops",
"range"
] |
Changing the value of range during iteration in Python | 38,672,963 | <pre><code>>>> k = 8
>>> for i in range(k):
print i
k -= 3
print k
</code></pre>
<p>Above the is the code which prints numbers from <code>0-7</code> if I use just <code>print i</code> in the for loop.</p>
<p>I want to understand the above code how it is working, and is there ... | 0 | 2016-07-30T10:40:06Z | 38,672,984 | <p>You can't change the range after it's been generated. In Python 2, <code>range(k)</code> will make a list of integers from 0 to k, like this: <code>[0, 1, 2, 3, 4, 5, 6, 7]</code>. Changing <code>k</code> after the list has been made will do nothing.</p>
<p>If you want to change the number to iterate to, you could ... | 1 | 2016-07-30T10:42:51Z | [
"python",
"python-2.7",
"loops",
"range"
] |
Changing the value of range during iteration in Python | 38,672,963 | <pre><code>>>> k = 8
>>> for i in range(k):
print i
k -= 3
print k
</code></pre>
<p>Above the is the code which prints numbers from <code>0-7</code> if I use just <code>print i</code> in the for loop.</p>
<p>I want to understand the above code how it is working, and is there ... | 0 | 2016-07-30T10:40:06Z | 38,673,138 | <p>If you do want to change k and affect the loop you need to make sure you are iterating over mutable object. For example:</p>
<pre><code>k = list(range(8))
for i in k:
print(i)
k.pop()
k.pop()
k.pop()
print(k)
</code></pre>
<p>Or alternatively:</p>
<pre><code>k = list(range(... | 0 | 2016-07-30T10:59:39Z | [
"python",
"python-2.7",
"loops",
"range"
] |
How to do POST/GET request in python? | 38,673,106 | <p>I have a python server which parses a HTML page, the script runs fine. However I have an android application which will call this server by sending an argument i.e. a URL. </p>
<p>I want the server to get the URL posted by the android application and parse the data of the HTML page.</p>
<p>My queries are :- Which ... | 0 | 2016-07-30T10:56:20Z | 38,673,294 | <p>GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource</p>
<p>So if you want to submit data, use POST</p>
<p>See: <a href="http://www.w3schools.com/tags/ref_httpmethods.asp" rel="nofollow">http://www.w3schools.com/tags/ref_httpmethods.asp</a></p>
| 0 | 2016-07-30T11:14:44Z | [
"android",
"python"
] |
How to do POST/GET request in python? | 38,673,106 | <p>I have a python server which parses a HTML page, the script runs fine. However I have an android application which will call this server by sending an argument i.e. a URL. </p>
<p>I want the server to get the URL posted by the android application and parse the data of the HTML page.</p>
<p>My queries are :- Which ... | 0 | 2016-07-30T10:56:20Z | 38,673,303 | <p>Based on conclusion that you just want to get some information without updating anything on server side I can tell that GET request will be enough and theoretically more idiomatically. </p>
<p>So you just should make request with URL like www.yourdomain.com/?q=domaintocrawl.com and get parsed data in response.</p>
| 0 | 2016-07-30T11:15:27Z | [
"android",
"python"
] |
Django - Form validation not happening | 38,673,171 | <p>The following is my code for creating a form:</p>
<pre><code>from django import forms
class Register(forms.Form):
username = forms.CharField(label='', max_length=64, required=True)
firstname = forms.CharField(label='', max_length=64, required=True)
surname = forms.CharField(label='sur name', max_length=... | 0 | 2016-07-30T11:02:48Z | 38,673,218 | <p>You're not passing post data into your form. It should look like this:</p>
<pre><code>from .forms import Register
def register(request):
form = Register(request.POST or None)
if request.method == 'POST' and form.is_valid():
# your action when form is valid
else:
return render(request, 'a... | 1 | 2016-07-30T11:08:01Z | [
"python",
"django"
] |
Django - Form validation not happening | 38,673,171 | <p>The following is my code for creating a form:</p>
<pre><code>from django import forms
class Register(forms.Form):
username = forms.CharField(label='', max_length=64, required=True)
firstname = forms.CharField(label='', max_length=64, required=True)
surname = forms.CharField(label='sur name', max_length=... | 0 | 2016-07-30T11:02:48Z | 38,673,364 | <p>To validate the form you need to populate it with data from the POST request and check if it's valid. Your view should look like this:</p>
<pre><code>from .forms import Register
def register(request):
if request.method == 'POST' # process form data
# create form instance, populate it with data
... | 3 | 2016-07-30T11:21:26Z | [
"python",
"django"
] |
django: How to avoid permission error on migration | 38,673,195 | <p>I am trying to deploy a django application on a virtual server running ubuntu 16.04.</p>
<pre><code>python manage.py makemigrations
</code></pre>
<p>leads to the following traceback, after some models and fields have been created:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 12, in &... | 1 | 2016-07-30T11:05:27Z | 38,673,366 | <p>You need grant access for user to migrations folder:</p>
<pre><code>sudo chown <your_username> <path_to_migrations_folder>
</code></pre>
| 1 | 2016-07-30T11:21:36Z | [
"python",
"django",
"virtualenv"
] |
How to rearrange a multidimensional array | 38,673,268 | <p>So for various reasons that go outside of this post, I am writing a file that transfers data from one place to another. I have some of the data held in a series of multidimensional arrays</p>
<p>lets pretend I have a 4 dimensional array with the following shape/dimensions:
[x, y, z, n]</p>
<p>How would I rearrange... | 0 | 2016-07-30T11:12:32Z | 38,673,348 | <p>Transpose:</p>
<pre><code>>>> a = [[1,2,3],[4,5,6]]
>>> b = zip(*a)
>>> b
[(1, 4), (2, 5), (3, 6)]
</code></pre>
| 0 | 2016-07-30T11:19:29Z | [
"python",
"arrays",
"multidimensional-array"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.