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 |
|---|---|---|---|---|---|---|---|---|---|
Filter values inside Python generator expressions | 37,772,551 | <p>I have a dictionary <code>dct</code> for which I want each of its values to be summed provided their corresponding keys exist in a specified list <code>lst</code>.</p>
<p>The code I am using so far is:</p>
<pre><code>sum(dct[k] for k in lst)
</code></pre>
<p>In the above generator expression I would like to handl... | 4 | 2016-06-12T09:14:27Z | 37,772,627 | <p>You have two options:</p>
<p>Checking if the key exists</p>
<pre><code>sum(dct[k] for k in lst if k in dct)
</code></pre>
<p>or using <code>get</code></p>
<pre><code>sum(dct.get(k, 0) for k in lst)
</code></pre>
<p>where <code>dct.get(k, 0)</code> returns <code>dct[k]</code> if <code>k</code> is a key in <code>... | 5 | 2016-06-12T09:21:55Z | [
"python",
"dictionary",
"keyerror"
] |
Filter values inside Python generator expressions | 37,772,551 | <p>I have a dictionary <code>dct</code> for which I want each of its values to be summed provided their corresponding keys exist in a specified list <code>lst</code>.</p>
<p>The code I am using so far is:</p>
<pre><code>sum(dct[k] for k in lst)
</code></pre>
<p>In the above generator expression I would like to handl... | 4 | 2016-06-12T09:14:27Z | 37,772,634 | <p>You can use the <code>get</code>-method of dictionaries, to provide a default value if not found:</p>
<pre><code>sum(dct.get(k, 0) for k in lst)
</code></pre>
| 1 | 2016-06-12T09:22:20Z | [
"python",
"dictionary",
"keyerror"
] |
Filter values inside Python generator expressions | 37,772,551 | <p>I have a dictionary <code>dct</code> for which I want each of its values to be summed provided their corresponding keys exist in a specified list <code>lst</code>.</p>
<p>The code I am using so far is:</p>
<pre><code>sum(dct[k] for k in lst)
</code></pre>
<p>In the above generator expression I would like to handl... | 4 | 2016-06-12T09:14:27Z | 37,772,746 | <p>Well, there are few options, preferred one is to use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>dict.get()</code></a>:</p>
<pre><code># 1
sum(dct.get(k, 0) for k in lst)
# 2
sum(dct[k] for k in lst if k in dct)
</code></pre>
<p>Also one of the option is to filter <code>... | 1 | 2016-06-12T09:36:18Z | [
"python",
"dictionary",
"keyerror"
] |
Python: fast subsetting and looping dataframe | 37,772,591 | <p>I have the folowing minimal code which is too slow. For the 1000 rows I need, it takes about 2 min. I need it to run faster.</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,1000,size=(1000, 4)), columns=list('ABCD'))
start_algorithm = time.time()
myunique = df['D'].uniqu... | 2 | 2016-06-12T09:18:24Z | 37,772,857 | <p>Avoid computing the sub-DataFrame <code>df[df['D'] == i]</code> more than once. The original code computes this <code>len(myunique)**2</code> times. Instead you can compute this once for each <code>i</code> (that is, <code>len(myunique)</code> times in total), store the results, and then pair them together later. Fo... | 3 | 2016-06-12T09:51:10Z | [
"python",
"python-2.7",
"loops",
"numpy",
"pandas"
] |
Python: fast subsetting and looping dataframe | 37,772,591 | <p>I have the folowing minimal code which is too slow. For the 1000 rows I need, it takes about 2 min. I need it to run faster.</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,1000,size=(1000, 4)), columns=list('ABCD'))
start_algorithm = time.time()
myunique = df['D'].uniqu... | 2 | 2016-06-12T09:18:24Z | 37,773,044 | <p>Here's a vectorized approach to form the groups based on unique elements from <code>"D"</code> column -</p>
<pre><code># Sort the dataframe based on the sorted indices of column 'D'
df_sorted = df.iloc[df['D'].argsort()]
# In the sorted dataframe's 'D' column find the shift/cut indces
# (places where elements cha... | 0 | 2016-06-12T10:12:28Z | [
"python",
"python-2.7",
"loops",
"numpy",
"pandas"
] |
How to "walk" this tree consisting of lists, tuples and strings? | 37,772,704 | <p>The tree structure:</p>
<pre><code>T
|__A1
| |__B1
| |__B2
| |__D1
|__A2
|__C1
|__C2
|__C3
|__E1
|__F1
E2
|__G1
|__G2
</code></pre>
<p>is parsed to:</p>
<pre><code>[('T',
[('A1', ['B1', ('B2', ['D1'])]),
('A2', ['C1', 'C2', ('C3', [... | 0 | 2016-06-12T09:30:41Z | 37,773,429 | <p>This code shall work</p>
<pre><code>tree = [('T',
[('A1', ['B1', ('B2', ['D1'])]),
('A2', ['C1', 'C2', ('C3', [('E1', ['F1']), ('E2', ['G1', 'G2'])])])])]
def print_node(header, tree):
if isinstance(tree,str):
return [header+' '+str(tree)]
else:
head, tail = tree
return reduce... | 1 | 2016-06-12T10:58:44Z | [
"python",
"python-2.7",
"tree"
] |
How to correct test for unicode strings with Django and Python 2 | 37,773,043 | <p>I need to test, whether the representation of my Django models are working with Unicode as it might be that users insert th9ings like ü or ¼ into it. To do so, I have this Django tests.py</p>
<pre><code># -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from djang... | 1 | 2016-06-12T10:12:25Z | 37,853,873 | <p>According to error message test tries to compare <code>str</code> and <code>unicode</code> objects. That's not good generally.</p>
<pre><code>AssertionError: 'Category 1->Category \xc3\xbc' != u'Category 1->Category \xfc'
</code></pre>
<p>Try to:</p>
<ul>
<li>compare unicode objects: <code>self.assertEqual(... | 0 | 2016-06-16T08:31:00Z | [
"python",
"django",
"testing",
"unicode"
] |
How to correct test for unicode strings with Django and Python 2 | 37,773,043 | <p>I need to test, whether the representation of my Django models are working with Unicode as it might be that users insert th9ings like ü or ¼ into it. To do so, I have this Django tests.py</p>
<pre><code># -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from djang... | 1 | 2016-06-12T10:12:25Z | 37,859,297 | <p>have you tried using <a href="http://pythonhosted.org/six/#six.text_type" rel="nofollow">six.text_type</a>? </p>
<blockquote>
<p><code>six.text_type</code></p>
<p>Type for representing (Unicode) textual data. This is <code>unicode()</code> in Python 2 and <code>str</code> in Python 3.</p>
</blockquote>
<p><... | 1 | 2016-06-16T12:30:24Z | [
"python",
"django",
"testing",
"unicode"
] |
How to correct test for unicode strings with Django and Python 2 | 37,773,043 | <p>I need to test, whether the representation of my Django models are working with Unicode as it might be that users insert th9ings like ü or ¼ into it. To do so, I have this Django tests.py</p>
<pre><code># -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from djang... | 1 | 2016-06-12T10:12:25Z | 37,908,051 | <p>tl; dr ) <strong>Use the same type on both sides of assertEqual</strong>.</p>
<p>The best code universal for Python 3 and 2 is possible without adding symbols like <code>u'', unicode, foo.__str__()</code> etc., and less should be written and more thought about both what type is expected where in Python 2/3.</p>
<p... | 1 | 2016-06-19T14:03:14Z | [
"python",
"django",
"testing",
"unicode"
] |
Map multiple WTForm fields to one attribute using Flask-WTForm | 37,773,049 | <p>I have a form that maps correctly to my model. What I want to do is have users input their date of birth using three <code>SelectField</code> (day, month, year) and write the combination of those three values to my <code>model.dateOfBirth</code>. I know of the existing <code>DateField</code> and <code>DateTimeField<... | 0 | 2016-06-12T10:12:56Z | 37,785,843 | <p>You can write a function for this.</p>
<pre><code>from datetime import datetime
def date_of_birth(**kwargs):
day = kwargs['day']
month = kwargs['month']
year = kwargs['year']
strip="-"
seq = (day,month,year)
date = datetime.strptime(strip.join(seq) , '%d-%m-%Y')
birthday = stringDate.str... | 0 | 2016-06-13T09:13:35Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] |
theano.scan output gradient is different if calculation is done inside or outside scan | 37,773,071 | <p>So I have the following code</p>
<pre><code>def step(i, rng, prev, A, B):
a = A*prev
b = B*a
return b, a, a+rng
rng = RandomStreams(lasagne.random.get_rng().randint(1,2147462579))
A = T.scalar("A")
B = T.scalar("B")
outputs, _ = theano.scan(step,
sequences=[T.arange(1,5),rng... | 0 | 2016-06-12T10:15:39Z | 37,794,557 | <p>How about using <a href="http://deeplearning.net/software/theano/library/gradient.html#theano.gradient.disconnected_grad" rel="nofollow"><code>theano.gradient.disconnected_grad</code></a></p>
<pre><code>from theano import gradient
def step(i, rng, prev, A, B):
a = A*prev
b = B*a
return b, a, a+rng
rng... | 0 | 2016-06-13T16:13:58Z | [
"python",
"theano"
] |
How to print string and list on same row without square brackets | 37,773,122 | <pre><code>l = [1, 2]
print "My numbers are:", l
</code></pre>
<p>This gives me </p>
<pre><code>My numbers are: [1, 2]
</code></pre>
<p>but I want </p>
<pre><code>My numbers are: 1, 2
</code></pre>
<p>I have seen <code>','.join(l)</code> but I don't know how to print out everything on the same line. </p>
| -4 | 2016-06-12T10:21:13Z | 37,773,226 | <p>For <code>.join</code> to work you will have to change every element to <code>str</code>:</p>
<p><code>print ', '.join(map(str, l))</code></p>
| 2 | 2016-06-12T10:32:55Z | [
"python"
] |
How to print string and list on same row without square brackets | 37,773,122 | <pre><code>l = [1, 2]
print "My numbers are:", l
</code></pre>
<p>This gives me </p>
<pre><code>My numbers are: [1, 2]
</code></pre>
<p>but I want </p>
<pre><code>My numbers are: 1, 2
</code></pre>
<p>I have seen <code>','.join(l)</code> but I don't know how to print out everything on the same line. </p>
| -4 | 2016-06-12T10:21:13Z | 37,773,265 | <p>Here I used a generator to generate a list of the string values and then I joined them together! I hope this helps!</p>
<pre><code>l = [1, 2]
print 'My numbers are: {}'.format(' and '.join(str(x) for x in l))
</code></pre>
| 0 | 2016-06-12T10:36:48Z | [
"python"
] |
How to print string and list on same row without square brackets | 37,773,122 | <pre><code>l = [1, 2]
print "My numbers are:", l
</code></pre>
<p>This gives me </p>
<pre><code>My numbers are: [1, 2]
</code></pre>
<p>but I want </p>
<pre><code>My numbers are: 1, 2
</code></pre>
<p>I have seen <code>','.join(l)</code> but I don't know how to print out everything on the same line. </p>
| -4 | 2016-06-12T10:21:13Z | 37,774,389 | <pre><code>print "My numbers are:", str(l).strip("[]")
</code></pre>
<p>Use strip. Convert the list in string and then remove the char that you want specifying them in the strip function.</p>
| 0 | 2016-06-12T12:43:32Z | [
"python"
] |
Python function doesn't seem to terminate after return | 37,773,361 | <p>At least that's the most that I can make sense of it, and I've been tracing over the flow of execution for hours. Here's the relevant snippet of the code:</p>
<pre><code>def check_list(inputList):
'''checks if list is composed of numbers, and, if so, returns a new list of purely integers'''
VerifiedDataSet ... | 1 | 2016-06-12T10:50:14Z | 37,773,401 | <p>If an exception is raised you are returning <code>'not approved'</code> from the function, </p>
<p>which makes <code>listStatus == 'n'</code>, therefore the <code>while</code> loop breaks.</p>
| 2 | 2016-06-12T10:55:55Z | [
"python",
"loops",
"debugging",
"iterator"
] |
Python function doesn't seem to terminate after return | 37,773,361 | <p>At least that's the most that I can make sense of it, and I've been tracing over the flow of execution for hours. Here's the relevant snippet of the code:</p>
<pre><code>def check_list(inputList):
'''checks if list is composed of numbers, and, if so, returns a new list of purely integers'''
VerifiedDataSet ... | 1 | 2016-06-12T10:50:14Z | 37,773,411 | <p>The value being returned from the function is a string. Hence result will have the value "not approved".</p>
<p><code>listStatus = result[0]</code></p>
<p>This will make <code>listStatus</code> = 'n' and not "not approved".</p>
| 0 | 2016-06-12T10:56:46Z | [
"python",
"loops",
"debugging",
"iterator"
] |
How can i get keys of SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS? | 37,773,364 | <p>I'm using django1.9 with python-social-auth.</p>
<p>And I want to implement a user's login with Facebook account.
Then I want to get information like their gender / age / location / job etc..</p>
<p>How can I get key names which I should set to SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS ?</p>
<p>thanks</p>
| 0 | 2016-06-12T10:50:26Z | 39,984,635 | <p>Here is the field list:</p>
<p><a href="https://developers.facebook.com/docs/graph-api/reference/user/" rel="nofollow">https://developers.facebook.com/docs/graph-api/reference/user/</a></p>
<p>I use some of them:</p>
<pre><code>SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
'fields': 'id,name,email,gender,abou... | 0 | 2016-10-11T18:53:27Z | [
"python",
"django",
"python-social-auth"
] |
How To make decorator get invoked on a recursive function call? | 37,773,483 | <p>So here's an extension to this question: <a href="https://stackoverflow.com/a/37568895/2290820">https://stackoverflow.com/a/37568895/2290820</a>
on how to optionally Enable or Disable Decorator on a Function.</p>
<p>On those lines, I came up with something like this to make decorator get invoked on a recursive cal... | 0 | 2016-06-12T11:04:12Z | 37,774,271 | <p>In your <code>deco</code> you have an assignment <code>f.attr = attr</code> that "eats" your argument after first recursive call. Your should modify your recursive call this way:</p>
<pre><code>def deco(f):
def fattr(attr):
f.attr = attr
def closure(*args):
f(*args)
f.unwrap ... | 1 | 2016-06-12T12:29:18Z | [
"python",
"recursion",
"python-decorators"
] |
python, tcpServer tcpClient, [WinError 10061] | 37,773,568 | <p>When I try to run tcpServer and tcpClient on the same local network, it works, but I can't run them on the external network. The OS refuses the connection.</p>
<blockquote>
<p>Main builtins.ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it</p>
</bl... | 0 | 2016-06-12T11:12:49Z | 37,773,623 | <p>There are most likely two reasons for that: </p>
<p>1.) Your server application is not listening on that particular ip/port</p>
<p>2.) A firewall is blocking that ip/port</p>
<p>I would recommend checking your firewall settings. You could start with turning your firewall off to determine if it really is a firewal... | 0 | 2016-06-12T11:19:33Z | [
"python",
"sockets",
"tcpclient",
"tcpserver"
] |
Path to files in kivy app not valid after building with buildozer | 37,773,586 | <p>I'm trying to build a kivy app using the buildozer virtual machine. It works fine as long as my main.py doesn't contain any specific paths to files.
For example, in my app I want to display an image. If I run on Windows, I would specifiy the source as</p>
<pre><code>C:\pathtoapp\img\image.png
</code></pre>
<p>In U... | 1 | 2016-06-12T11:14:47Z | 37,774,980 | <p>Of course it gives an error message. You don't have such a path on Android, nor on Windows. With Kivy you can use <a href="https://kivy.org/docs/api-kivy.resources.html#resource-lookup" rel="nofollow">relative paths</a>, which should work if you use something like:</p>
<pre><code>self.image = 'g3347.png'
</code></p... | 1 | 2016-06-12T13:48:24Z | [
"python",
"kivy",
"buildozer"
] |
Extracting values from nested list/tuple/dictionary | 37,773,598 | <p>Here's a list that was originally a dictionary that was converted due to sorting;</p>
<pre><code>list1 = [
('key1', {'count': 10, 'value1': Counter({'set1': 5, 'set2': 4, 'set3': 1})}),
('key2', {'count': 8, 'value2': Counter({'set1': 6, 'set2': 2})}),
('key3', {'count': 7, 'va... | -1 | 2016-06-12T11:16:34Z | 37,773,734 | <p>The following assumes that your order never changes.</p>
<pre><code>def get_stuff(list):
for i in list[:2]:
print i[0], i[1].values()[0]
print i[1].values()[1].keys()[0], i[1].values()[1].values()[0]
</code></pre>
| 0 | 2016-06-12T11:33:26Z | [
"python",
"list",
"dictionary",
"nested"
] |
Recursively generating all the possible calculations between set elements in Python | 37,773,706 | <p>I've a trouble understanding why the following recursive code (function count()) gives the wrong count of calculations, but the one based on manually written nested for loops (function count2()) gives the right count, which is n! * 4 ^ (n-1)?</p>
<p>(Never mind the output variable at this point. I'll use it later, ... | 0 | 2016-06-12T11:30:24Z | 37,774,737 | <p>You are appending too many reuslts in your recursive function. Let me elaborate with your example. Let us just consider counting for the original permutation. The call</p>
<pre><code>count([4, 1, 2, 3])
</code></pre>
<p>should result in the following recursive calls:</p>
<pre><code>count([5, 2, 3]) # +
count([3,... | 0 | 2016-06-12T13:20:29Z | [
"python",
"recursion",
"permutation"
] |
Django db in visual studio 2015 | 37,773,719 | <p>I try to django sync db inv visual studio 2015.</p>
<p>See screenshot:</p>
<p><a href="http://i.stack.imgur.com/SsJh4.png" rel="nofollow"><img src="http://i.stack.imgur.com/SsJh4.png" alt="enter image description here"></a></p>
<p>but then I get this errors:</p>
<pre><code>Python interactive window. Type $help ... | 0 | 2016-06-12T11:32:01Z | 37,774,688 | <p>It looks like you are running the commands from an interactive python window. You should run them from the Windows command (cmd)</p>
| 0 | 2016-06-12T13:15:34Z | [
"python",
"django",
"visual-studio",
"visual-studio-2015"
] |
Django db in visual studio 2015 | 37,773,719 | <p>I try to django sync db inv visual studio 2015.</p>
<p>See screenshot:</p>
<p><a href="http://i.stack.imgur.com/SsJh4.png" rel="nofollow"><img src="http://i.stack.imgur.com/SsJh4.png" alt="enter image description here"></a></p>
<p>but then I get this errors:</p>
<pre><code>Python interactive window. Type $help ... | 0 | 2016-06-12T11:32:01Z | 39,375,154 | <p>I ran into this. You need to open the Windows command line in the project's folder. The easiest way to do this is to open File Explorer and navigate to the folder containing the project (contains the "manage.py" file). Once there, click on the "File" menu option in the header bar and choose "Open Command Prompt". Th... | 0 | 2016-09-07T16:30:25Z | [
"python",
"django",
"visual-studio",
"visual-studio-2015"
] |
Using raw string properly to send commands over SSH in Python | 37,773,856 | <p>I have a long long command to send over SSH using Paramiko and I need to wrap the string using "r" parameter but the IDE still tells me it's not written fine.
The string is something like that:</p>
<pre><code>somecommand get -n somestuff sa/management --template='{{range .secrets}}{{printf "%s\n" .name}}{{end}}'
</... | 0 | 2016-06-12T11:47:28Z | 37,774,137 | <p>First, you are missing a quote at the end of your string.
The second problem is that you can't use quotes inside a string like that.</p>
<pre><code>r'some'thing'
</code></pre>
<p>won't work while</p>
<pre><code>r'some"thing'
</code></pre>
<p>will work.
Since you have quotes in quotes inside the string use a trip... | 2 | 2016-06-12T12:15:39Z | [
"python",
"ssh",
"paramiko"
] |
Write a python regular expression for matching dot and array indices | 37,773,858 | <p>I need to match the proper variable access strings ex. </p>
<pre><code>employeeobj.empid
employeeobj.grades[0].grade
employee[0]
employee.dept.location.room[0]
</code></pre>
<p>Few examples -</p>
<pre><code>employeeobj.[] Invalid
.employeeobj Invalid
[]employeeobj Invalid
employeeobj.dept. Invalid
employeeobj.de... | 0 | 2016-06-12T11:47:52Z | 37,774,578 | <h3>Not an answer</h3>
<p>This is how this might be done with <code>pyparsing</code></p>
<pre><code>from pyparsing import *
#see https://stackoverflow.com/questions/36428652/pyparsing-is-it-possible-to-globally-suppress-all-literals
ParserElement.inlineLiteralsUsing(Suppress)
#the grammar
ident = Word(alphas, alphanu... | 0 | 2016-06-12T13:05:13Z | [
"python",
"regex"
] |
Insertion_Sort() implementation (Error), Python | 37,773,862 | <p>I have two version of the implementation of INSERTION SORT; I think <strong>that are equivalent</strong>, but <strong>the second one returns a sorted list wrong.</strong>
This is the first one:</p>
<pre><code>def insertionSort(A):
for j in range(1,len(A)):
key = A[j]
i = j
while i>0 and A[i-1]>k... | -1 | 2016-06-12T11:47:57Z | 37,773,935 | <p>Here's a correction of your second code: </p>
<pre><code>def insertionSort(A):
for j in range(1,len(A)):
key = A[j]
i = j-1
while i>=0 and A[i]>key:
A[i+1] = A[i]
i -= 1
A[i+1] = key
</code></pre>
<p>The difference lies in the <code>>=</code> ... | 1 | 2016-06-12T11:54:34Z | [
"python",
"indexing",
"implementation",
"insertion-sort"
] |
What is the most pythonic way to filter list of strings with a list of regular expressions in the order of the regex? | 37,773,891 | <p>If I have a list of strings <code>strlst</code> and a list of regular expressions <code>rexlst</code>, what is the most pythonic way to filter out every element of <code>strlst</code> for which <strong>none</strong> of the regular expressions in <code>rexlst</code> matches? So, as soon as one of the regular erpressi... | 1 | 2016-06-12T11:50:23Z | 37,773,919 | <p>Convert your list of strings to a <code>set</code> for easy element removal, then continuously loop over the remaining strings to see if a regex matches. You need to be careful with removing elements from sets while iterating, so make a copy each time:</p>
<pre><code>tomatch = set(strlst)
outlist = []
for regex in ... | 2 | 2016-06-12T11:53:00Z | [
"python",
"regex",
"list",
"filter"
] |
How do I show a constantly changing variable in python? | 37,773,896 | <p>New to python. I have a variable called 'score' which changes constantly throughout the running of the program. Is there a way to show the variable at all times in a window/place so that the user can see their score changing? Thanks!</p>
| -2 | 2016-06-12T11:50:53Z | 37,773,966 | <p>You could run a different process that actually displays the value of the variable.
Another approach is to save the result of the variable and show it in a file.
Maybe this could help.
<a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.ht... | 0 | 2016-06-12T11:58:37Z | [
"python"
] |
error happens when install xgboost4.0 in windows7, python2.7 | 37,773,939 | <p>Here is the process I tried to install xgboost:</p>
<pre><code>git clone --recursive https://github.com/dmlc/xgboost
git submodule init
git submodule update
cp make/mingw64.mk config.mk
</code></pre>
<p>It was good until I ran the code in my git bash</p>
<pre><code> make -j4
</code></pre>
<p>It goes wrong:</p>
... | 0 | 2016-06-12T11:55:01Z | 37,779,352 | <p>There was an issue raised on the <a href="https://github.com/dmlc/xgboost/issues/1267" rel="nofollow">github page</a>.</p>
<p>After cloning, checkout to version <code>9a48a40</code> then repeat the steps you performed above. I was having the same issue, and this worked for me.</p>
<p>Quoting from the link:</p>
<b... | 2 | 2016-06-12T21:41:55Z | [
"python",
"git",
"install",
"windows-7-x64",
"xgboost"
] |
Is there an easier way of transforming these python objects | 37,774,012 | <p>I`d like to transform the following python input:</p>
<pre><code>[{'paramA': ['valA1','valA2','valA3','valA4']},
{'paramB': ['valB1','valB2','valB3','valB4']},
{'paramC': ['valC1','valC2','valC3','valC4']},
# ...........................................,
{'paramN': ['valN1', 'valN2','valN3','valN4']}]
</code></p... | 1 | 2016-06-12T12:04:03Z | 37,774,144 | <p>First join everything in the input list into <em>one</em> dictionary; that way you can use <code>zip()</code> to transform all values into rows, and re-combine that with the keys:</p>
<pre><code>try:
# use efficient Python 3 version in Python 2
from future_builtins import zip
except ImportError:
# Python 3... | 4 | 2016-06-12T12:16:08Z | [
"python",
"list",
"dictionary",
"transform",
"list-comprehension"
] |
Is there an easier way of transforming these python objects | 37,774,012 | <p>I`d like to transform the following python input:</p>
<pre><code>[{'paramA': ['valA1','valA2','valA3','valA4']},
{'paramB': ['valB1','valB2','valB3','valB4']},
{'paramC': ['valC1','valC2','valC3','valC4']},
# ...........................................,
{'paramN': ['valN1', 'valN2','valN3','valN4']}]
</code></p... | 1 | 2016-06-12T12:04:03Z | 37,774,331 | <pre><code>l = [
{"paramA": ["valA1","valA2","valA3","valA4"]},
{"paramB": ["valB1","valB2","valB3","valB4"]},
{"paramC": ["valC1","valC2","valC3","valC4"]},
]
output = [dict([(line.keys()[0], line.values()[0][index]) for line in l]) for index in range(len(l[0].values()[0]))]
print(output)
</code></pre>
... | 1 | 2016-06-12T12:35:24Z | [
"python",
"list",
"dictionary",
"transform",
"list-comprehension"
] |
How do you get third link from BeautifulSoup result | 37,774,056 | <p>I am using the following code to retrieve a bunch of links using BeautifulSoup. It returns all the links, but I would like to get the third link, parse through that one, and then get the third from that one and so on. How can I modify the below code to accomplish that?</p>
<pre><code>import urllib
from BeautifulSou... | 2 | 2016-06-12T12:08:50Z | 37,774,159 | <p>First of all, you should stop using <code>BeautifulSoup</code> version 3 - it is quite old and no longer maintained. Switch to <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code> version 4</a>. Install it via:</p>
<pre><code>pip install beautifulsoup4
</code></... | 2 | 2016-06-12T12:17:30Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
How do you get third link from BeautifulSoup result | 37,774,056 | <p>I am using the following code to retrieve a bunch of links using BeautifulSoup. It returns all the links, but I would like to get the third link, parse through that one, and then get the third from that one and so on. How can I modify the below code to accomplish that?</p>
<pre><code>import urllib
from BeautifulSou... | 2 | 2016-06-12T12:08:50Z | 37,777,228 | <p>Another option would be to use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow"><em>css selector</em></a>,<a href="http://www.w3schools.com/cssref/sel_nth-of-type.asp" rel="nofollow"><em>nth-of-type</em></a> to get the third anchor looping until the css select returns N... | 0 | 2016-06-12T17:40:28Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
Range of IP pinging | 37,774,189 | <p>Okay so, I want to be able to input a starting and ending IP and ping all the IP addresses inbetween them including the ones listed and then display their results into a .txt document. I can get it to work for a single IP, but I don't know how to make it so the user has to input 2 IP's and it successfully pings all ... | 0 | 2016-06-12T12:20:56Z | 37,774,670 | <pre><code>import struct
import socket
def findIPs(start, end):
ipstruct = struct.Struct('>I')
start, = ipstruct.unpack(socket.inet_aton(start))
end, = ipstruct.unpack(socket.inet_aton(end))
return [socket.inet_ntoa(ipstruct.pack(i)) for i in range(start, end+1)]
def pingNetwork(range_ips):
for... | 0 | 2016-06-12T13:13:38Z | [
"python"
] |
Django - Restructured queryset is not iterable | 37,774,264 | <p>I have a Django queryset. I'm using <code>groupby</code> to restructure the queryset:</p>
<pre><code>content_items = ContentItem.objects.filter(content_group__row__page=page)
</code></pre>
<p><code>content_items</code> looks like this:</p>
<pre><code>[<Faq: Faq object>, <Text: Text object>, <Faq: F... | 0 | 2016-06-12T12:28:54Z | 37,774,344 | <p><code>content_groups</code> is a <em>dictionary</em>, when you iterate it over via:</p>
<pre><code>for content_group in content_groups:
</code></pre>
<p><code>content_group</code> would correspond to each <em>key</em> - a <code>ContentGroup</code> instance. And, you get an error when you try to loop over it - a Dj... | 1 | 2016-06-12T12:38:05Z | [
"python",
"django",
"iteration"
] |
Can't bring cassandra and celery together | 37,774,330 | <p>I'm trying the the example to use celery and cassandra together:
<a href="http://datastax.github.io/python-driver/cqlengine/third_party.html" rel="nofollow">http://datastax.github.io/python-driver/cqlengine/third_party.html</a>
But without luck.</p>
<p>I get this exception the I'm starting the worker with:
$ celery... | 0 | 2016-06-12T12:35:08Z | 37,819,775 | <p>Your <code>cassandra_init</code> signal handler function needs to accept arbitrary keyword arguments.</p>
<p>Simply change the line:</p>
<pre><code>def cassandra_init():
</code></pre>
<p>into:</p>
<pre><code>def cassandra_init(**kwargs):
</code></pre>
<p>For more information about Celery signals, see the user g... | 1 | 2016-06-14T18:42:22Z | [
"python",
"cassandra",
"celery",
"python-3.5"
] |
OpenCV & Python - Real time image (frame) processing | 37,774,354 | <p>We're doing a project in school where we need to do basic image processing. Our goal is to use every video frame for the Raspberry Pi and do real time image processing.</p>
<p>We've tried to include raspistill in our python-program but so far nothing has worked. The goal of our project is to design a RC-car which f... | 0 | 2016-06-12T12:39:10Z | 37,774,410 | <p>You <strong>can use picamera to acquire images</strong>. </p>
<p>To make it "real time", you can acquire data each X milliseconds. You need to set X depending on the power of your hardware (and the complexity of the openCV algorithm). </p>
<p>Here's an example (from <a href="http://picamera.readthedocs.io/en/rele... | 0 | 2016-06-12T12:46:32Z | [
"python",
"opencv",
"raspberry-pi3"
] |
OpenCV & Python - Real time image (frame) processing | 37,774,354 | <p>We're doing a project in school where we need to do basic image processing. Our goal is to use every video frame for the Raspberry Pi and do real time image processing.</p>
<p>We've tried to include raspistill in our python-program but so far nothing has worked. The goal of our project is to design a RC-car which f... | 0 | 2016-06-12T12:39:10Z | 37,774,423 | <p>OpenCV already contains functions to process live camera data.</p>
<p><a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow">This OpenCV documentation</a> provides a simple example:</p>
<pre><code>import numpy as np
import cv2
cap... | 2 | 2016-06-12T12:48:00Z | [
"python",
"opencv",
"raspberry-pi3"
] |
Executing same Python program with different arguments in parallel | 37,774,469 | <p>How can i execute the same python program in parallel (I am thinking of x10) with the only difference being two input arguments representing a time-range? I need it for some data-processing, which otherwise will take too long to finish</p>
<p>I know i can do it manually in shell by starting 10 scripts one by one, ... | 1 | 2016-06-12T12:52:48Z | 37,774,507 | <p>Enclose your script in a main method, like so:</p>
<pre><code>def main(args):
a, b = args
# do something
if __name__ == '__main__':
args = parse_arguments()
main(args)
</code></pre>
<p>Then you can use a second script together with <code>multiprocessing.Pool</code>, to run the main method with di... | 0 | 2016-06-12T12:57:33Z | [
"python",
"python-3.x"
] |
python libclang bindings on Windows fail to initialize a translation unit from sublime text | 37,774,599 | <p><em>Short description</em>: using <code>libclang</code> to autocomplete code does not work with python that comes bundled with Sublime Text 3.</p>
<p><em>Details</em>: A small verifiable example is in the repo on <a href="https://github.com/niosus/test-complete-plugin" rel="nofollow">Github</a></p>
<p>In essence, ... | 4 | 2016-06-12T13:06:59Z | 38,394,502 | <p>Unfortunately for now the answer to this question is that it is due to a bug in Python 3.3 that is bundled with Sublime Text 3. See <a href="https://forum.sublimetext.com/t/ctypes-from-sublime-text-3-python-broken-on-windows/21490/15" rel="nofollow">discussion</a> on Sublime Text forum.</p>
<p>This means that we wo... | 0 | 2016-07-15T11:01:11Z | [
"python",
"windows",
"python-3.x",
"sublimetext3",
"libclang"
] |
Matplotlib: plotting of nan elements in an array | 37,774,617 | <p>I'm attempting to mask a data array, whereby for every value in the array less than 9 I wish to set this to 0. Every value greater than 9 I wish to set to 1. Such that when I multiply this array by the array I wish to mask, any value will either be multiplied by 0 (thus masking that data) or (1) i..e, that data will... | 2 | 2016-06-12T13:08:33Z | 37,774,815 | <p>You can build the mask matrix so simple:</p>
<pre><code>numpy.array((yourarray > 9), dtype=int)
</code></pre>
<p>You can change the > to >= if you want. The relation you wrote was not clear, you did not define what to do if the values equals to 9.</p>
<p>In case of None, NaN, inf values matplotlib will not plo... | 2 | 2016-06-12T13:27:47Z | [
"python",
"arrays",
"matplotlib"
] |
Matplotlib: plotting of nan elements in an array | 37,774,617 | <p>I'm attempting to mask a data array, whereby for every value in the array less than 9 I wish to set this to 0. Every value greater than 9 I wish to set to 1. Such that when I multiply this array by the array I wish to mask, any value will either be multiplied by 0 (thus masking that data) or (1) i..e, that data will... | 2 | 2016-06-12T13:08:33Z | 37,774,878 | <p>If you mask the arrays, you can plot them normally. If you add two masked arrays, the masks are combined properly as you can see in the example below. I have generated random data between 0 and 20 and mask all the values less than 9 in both arrays.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as pl
#... | 2 | 2016-06-12T13:35:15Z | [
"python",
"arrays",
"matplotlib"
] |
Image in label does not immideately change after function call | 37,774,635 | <p>Im currently trying to change an image in a tkinter label widget by using a binding to the return key. After pressing the return key I would like the image to change to "im2", then wait for 2 seconds and change again to "im3".
The code I use so far is: </p>
<pre><code>window = tk.Tk()
window.title("Testwindow")
wi... | 0 | 2016-06-12T13:10:14Z | 37,774,800 | <p>time.sleep() won't work here as it stops the execution of the program, you'll have to use <code>after</code>...and its also a bad practice to use <code>sleep</code> in GUI programming.</p>
<p><code>root.after(time_delay, function_to_run, args_of_fun_to_run)</code></p>
<p>So in your case it'll like </p>
<pre><code... | 4 | 2016-06-12T13:25:55Z | [
"python",
"tkinter"
] |
Assertion Error during Pip installation | 37,774,654 | <p>I use Python 2.7 on Ubuntu 14p.</p>
<p>I'm giving as input <code>pip list</code>, but the process fails. In the following picture you can see where and how it fails:</p>
<p><a href="http://i.stack.imgur.com/pFmKS.png" rel="nofollow"><img src="http://i.stack.imgur.com/pFmKS.png" alt="enter image description here"><... | -1 | 2016-06-12T13:12:31Z | 37,774,848 | <p>Upgrading your pip version should remove the error.</p>
<p><code>sudo pip install -U pip</code></p>
| 2 | 2016-06-12T13:31:45Z | [
"python",
"python-2.7",
"pip",
"assertion"
] |
Compiling C++ code with g++ from Python script on Windows | 37,774,886 | <p>I'm trying to write a Python script that calls g++.exe via subprocess.Popen() and uses it to compile a .cpp file into an .exe. The problem is that no matter how I try to pass the path to the source file, I get the following error:</p>
<blockquote>
<p>g++.exe: error: CreateProcess: No such file or directory</p>
</... | 1 | 2016-06-12T13:35:48Z | 37,775,127 | <p>It is not the <code>client.cpp</code> file that is not found, but the <code>g++.exe</code>. You can know that because it is <code>CreateProcess</code> that generates the error. If it was the cpp file, <code>CreateProcess</code> would succeed, and only then would the compiler return with an error.</p>
<pre><code>os.... | 0 | 2016-06-12T14:04:35Z | [
"python",
"c++",
"g++",
"popen"
] |
Compiling C++ code with g++ from Python script on Windows | 37,774,886 | <p>I'm trying to write a Python script that calls g++.exe via subprocess.Popen() and uses it to compile a .cpp file into an .exe. The problem is that no matter how I try to pass the path to the source file, I get the following error:</p>
<blockquote>
<p>g++.exe: error: CreateProcess: No such file or directory</p>
</... | 1 | 2016-06-12T13:35:48Z | 37,797,266 | <p>I was able to solve my own problem and get a working .exe with the following code:</p>
<pre><code>import os, subprocess, json, glob
class client():
def __init__(self):
self.gccDir = os.path.abspath("external/mingw64")
self.sourceDir = "c/client"
self.fileName = "client.cpp"
self... | 0 | 2016-06-13T19:01:07Z | [
"python",
"c++",
"g++",
"popen"
] |
are elements of an array in a set? | 37,774,990 | <pre><code>import numpy
data = numpy.random.randint(0, 10, (6,8))
test = set(numpy.random.randint(0, 10, 5))
</code></pre>
<p>I want an expression whose value is a Boolean array, with the same shape of <code>data</code> (or, at least, can be reshaped to the same shape), that tells me if the corresponding term in <code... | 5 | 2016-06-12T13:48:44Z | 37,775,103 | <p>I am assuming you are looking to find a boolean array to detect the presence of the <code>set</code> elements in <code>data</code> array. To do so, you can extract the elements from <code>set</code> with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.hstack.html" rel="nofollow"><code>np.hs... | 5 | 2016-06-12T14:00:53Z | [
"python",
"numpy"
] |
are elements of an array in a set? | 37,774,990 | <pre><code>import numpy
data = numpy.random.randint(0, 10, (6,8))
test = set(numpy.random.randint(0, 10, 5))
</code></pre>
<p>I want an expression whose value is a Boolean array, with the same shape of <code>data</code> (or, at least, can be reshaped to the same shape), that tells me if the corresponding term in <code... | 5 | 2016-06-12T13:48:44Z | 37,775,575 | <p>The expression <code>a = data < 6</code> returns a new array because <code><</code> is a value comparison operator.</p>
<blockquote>
<h3><a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.ndarray.html#arithmetic-matrix-multiplication-and-comparison-operations" rel="nofollow">Arithmetic, matrix... | 1 | 2016-06-12T14:48:37Z | [
"python",
"numpy"
] |
How to keep a Python TCP listener application running? | 37,775,062 | <p>I'm trying to make a Python program that will run on AWS (deployed via Elastic Beanstalk) that listens to a <a href="https://stomp.github.io" rel="nofollow">STOMP</a> queue (a simple text based protocol over TCP). I'm using the <a href="https://github.com/jasonrbriggs/stomp.py" rel="nofollow">stomp.py</a> library, <... | 1 | 2016-06-12T13:55:45Z | 37,775,219 | <p>You can use an infinite while loop</p>
<pre><code>def main():
'''Starts the STOMP listener.'''
print('Running main function')
# See the following example for the template this file was based on:
# http://jasonrbriggs.github.io/stomp.py/quickstart.html
conn = stomp.Connection([('example.com', 6... | 0 | 2016-06-12T14:13:41Z | [
"python",
"pycharm",
"elastic-beanstalk",
"stomp"
] |
How to create a GSM-7 encoding in Python? | 37,775,209 | <p>The GSM-7 character set is defined as a basic mapping table + an extension character mapping table (<a href="https://en.wikipedia.org/wiki/GSM_03.38#GSM_7-bit_default_alphabet_and_extension_table_of_3GPP_TS_23.038_.2F_GSM_03.38" rel="nofollow">https://en.wikipedia.org/wiki/GSM_03.38#GSM_7-bit_default_alphabet_and_ex... | 1 | 2016-06-12T14:12:31Z | 37,775,729 | <p>Based on @Martijn Pieters comment, I've changed the code to:</p>
<pre><code>def decode_gsm7(txt, errors):
ext_table = {
'\x40': u'|',
'\x14': u'^',
'\x65': u'â¬',
'\x28': u'{',
'\x29': u'}',
'\x3C': u'[',
'\x3D': u'~',
'\x3E': u']',
'\x2F'... | 0 | 2016-06-12T15:06:04Z | [
"python",
"encoding",
"gsm"
] |
Saving a histogram after removing a bin in numpy | 37,775,232 | <p>I have a large array of data, for which I need to get the histogram without the bin with the highest frequency. I use <a href="http://stackoverflow.com/questions/36341774/histogram-manipulation-to-remove-unwanted-data">this</a>, to remove such bin, but then I need to save the changed histogram, since I have to compa... | 1 | 2016-06-12T14:14:41Z | 37,776,489 | <p>I think I figured out how to do it. Basically, I find the range of bin for which the histogram has the highest frequency and then remove it from the original data. Here is the sample code for those who are interested: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
gaussian_numbers = np.random.r... | 0 | 2016-06-12T16:19:18Z | [
"python",
"numpy",
"histogram"
] |
Pandas: Drop() int64 based on value returns object | 37,775,308 | <p>I need to drop all rows where a one column are below a certain value. I used the command below, but this returns the column as an object. I need to keep it as <code>int64</code>:</p>
<pre><code>df["customer_id"] = df.drop(df["customer_id"][df["customer_id"] < 9999999].index)
df = df.dropna()
</code></pre>
<p>I ... | 3 | 2016-06-12T14:22:07Z | 37,776,033 | <p>What's wrong with slicing the whole frame (and reindexing if necessary)?</p>
<pre><code>df = df[df["customer_id"] < 9999999]
df.index = range(0,len(df))
</code></pre>
| 0 | 2016-06-12T15:34:36Z | [
"python",
"pandas"
] |
Pandas: Drop() int64 based on value returns object | 37,775,308 | <p>I need to drop all rows where a one column are below a certain value. I used the command below, but this returns the column as an object. I need to keep it as <code>int64</code>:</p>
<pre><code>df["customer_id"] = df.drop(df["customer_id"][df["customer_id"] < 9999999].index)
df = df.dropna()
</code></pre>
<p>I ... | 3 | 2016-06-12T14:22:07Z | 37,776,622 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p>
<pre><code>i... | 1 | 2016-06-12T16:32:36Z | [
"python",
"pandas"
] |
iterating through a list consisting of nested tuples/dictionaries | 37,775,328 | <p>I have the following list which has nested tuples/dicts.</p>
<pre><code>list1 = [
('key1', {'count': 10, 'value1': Counter({'set1': 5, 'set2': 4, 'set3': 1})}),
('key2', {'count': 8, 'value1': Counter({'set1': 6, 'set2': 2})}),
('key3', {'count': 7, 'value1': Counter({'set1': 5... | -1 | 2016-06-12T14:24:41Z | 37,775,355 | <p><code>Counter</code> objects are just dictionaries with extra behaviour, so you can also use <code>dict.items()</code>. However, I'd use a different method here unique to <code>Counter</code> objects.</p>
<p>Loop over the <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" r... | 2 | 2016-06-12T14:27:14Z | [
"python",
"list",
"dictionary",
"tuples"
] |
Copy complete sentences from text file and add to list | 37,775,356 | <p>I am trying to extract <strong>complete sentences</strong> from a long text file and adding them as strings to a list in Python 2.7. I want to automate this and not just cut and paste in the list.</p>
<p>Here is what I have:</p>
<pre><code>from sys import argv
script, filename = argv # script = alien.py; filename... | 1 | 2016-06-12T14:27:25Z | 37,775,549 | <p>You can do it with a while loop:</p>
<pre><code>listed = []
with open(filename,"r") as text:
Line = text.readline()
while Line!='':
listed.append(Line)
Line = text.readline()
print listed
</code></pre>
<p>In the previous example, I assumed that each sentence is written on a different lin... | 1 | 2016-06-12T14:45:54Z | [
"python",
"string",
"list",
"text"
] |
Copy complete sentences from text file and add to list | 37,775,356 | <p>I am trying to extract <strong>complete sentences</strong> from a long text file and adding them as strings to a list in Python 2.7. I want to automate this and not just cut and paste in the list.</p>
<p>Here is what I have:</p>
<pre><code>from sys import argv
script, filename = argv # script = alien.py; filename... | 1 | 2016-06-12T14:27:25Z | 37,776,641 | <p>Normally sentences are separated by <code>'. '</code>, not <code>'\n'</code>. Under this condition, use split with <code>period+space</code>(without <code>return-enter</code>):</p>
<pre><code>listed = []
fd = open(filename,"r")
try:
data = fd.read()
sentences = data.split(". ")
for sentence in sentenc... | 0 | 2016-06-12T16:34:56Z | [
"python",
"string",
"list",
"text"
] |
Can scipy.stats to calculate pmf automatically? | 37,775,377 | <p>I have two questions.</p>
<p>1) I have an array like <code>[1,2,3,4,5,5,3,1]</code>. and I don't know which distributions it is. Can I use <code>scipy.stats</code> to calculate pmf,cdf automatically?</p>
<p>2)<code>scipy.stats</code> is just like a library of distributions? If I want to analysis data, I have to fi... | 0 | 2016-06-12T14:29:29Z | 37,775,495 | <p>Well, scipy.stats is not a library for telling you the distribution of data and calculating pmf and cdf automatically. Its a library for easing your tasks <strong>while estimating</strong> the probabily distribution. You have to explore your data and find which distribution which fits your data with least error ,whi... | 0 | 2016-06-12T14:40:26Z | [
"python",
"scipy"
] |
Pygame-OpenGL cannot fill the surface | 37,775,538 | <p>I have started to code a person body with Python - OpenGL to learn the library, however when I use <code>glColor3fv((1.000, 0.498, 0.314))</code> it only fills the part of the surface and not the all surface.</p>
<p>All my imports:</p>
<pre><code>import pygame
from pygame.locals import *
from OpenGL.GL import *
f... | -1 | 2016-06-12T14:44:59Z | 37,778,012 | <p>It seems like some indices are wrong. I cannot help you really because this would be a tedious task to check all the indices and vertices.</p>
<p><a href="http://i.stack.imgur.com/xdjsP.png" rel="nofollow"><img src="http://i.stack.imgur.com/xdjsP.png" alt="enter image description here"></a></p>
<p>As you can see p... | 1 | 2016-06-12T19:00:46Z | [
"python",
"opengl"
] |
Python: Calculate difference between all elements in a set of integers | 37,775,578 | <p>I want to calculate absolute difference between all elements in a set of integers. I am trying to do <code>abs(x-y)</code> where <code>x</code> and <code>y</code> are two elements in the set. I want to do that for all combinations and save the resulting list in a new set.</p>
| 3 | 2016-06-12T14:48:54Z | 37,775,720 | <p>As sets do not maintain order, you may use something like an <a href="https://pypi.python.org/pypi/ordered-set/" rel="nofollow">ordered-set</a> and iterate till last but one.</p>
| 0 | 2016-06-12T15:04:26Z | [
"python",
"set"
] |
Python: Calculate difference between all elements in a set of integers | 37,775,578 | <p>I want to calculate absolute difference between all elements in a set of integers. I am trying to do <code>abs(x-y)</code> where <code>x</code> and <code>y</code> are two elements in the set. I want to do that for all combinations and save the resulting list in a new set.</p>
| 3 | 2016-06-12T14:48:54Z | 37,775,746 | <blockquote>
<p>I want to calculate absolute difference between all elements in a set of integers (...) and save the resulting list in a new set.</p>
</blockquote>
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow">itertools.combinations</a>:</p>
<pre><co... | 2 | 2016-06-12T15:07:38Z | [
"python",
"set"
] |
Python: Calculate difference between all elements in a set of integers | 37,775,578 | <p>I want to calculate absolute difference between all elements in a set of integers. I am trying to do <code>abs(x-y)</code> where <code>x</code> and <code>y</code> are two elements in the set. I want to do that for all combinations and save the resulting list in a new set.</p>
| 3 | 2016-06-12T14:48:54Z | 37,776,621 | <p>For completeness, here's a solution based on Numpy <code>ndarray</code>'s and <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist" rel="nofollow">pdist()</a>:</p>
<pre><code>In [69]: import numpy as np
In [70]: from scipy.spatial.distance impo... | 0 | 2016-06-12T16:32:36Z | [
"python",
"set"
] |
Where is the origin coding of sparse_softmax_cross_entropy_with_logits function in tensorflow | 37,775,596 | <p>I want to know what the tensorflow function <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py#L424" rel="nofollow">sparse_softmax_cross_entropy_with_logits</a> mathematically is exactly doing. But I can't find the origin of the coding.
Can you help me?</p>
| 1 | 2016-06-12T14:50:43Z | 37,778,879 | <p>In the head version (as of today), you can find the function in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py</a> line #424.</p>
<p>The comment says:</p>
<blockquote>... | 0 | 2016-06-12T20:40:44Z | [
"python",
"tensorflow",
"softmax",
"cross-entropy"
] |
Where is the origin coding of sparse_softmax_cross_entropy_with_logits function in tensorflow | 37,775,596 | <p>I want to know what the tensorflow function <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn_ops.py#L424" rel="nofollow">sparse_softmax_cross_entropy_with_logits</a> mathematically is exactly doing. But I can't find the origin of the coding.
Can you help me?</p>
| 1 | 2016-06-12T14:50:43Z | 37,781,767 | <p>The most important part of the implementation is <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_xent_op.h" rel="nofollow">here</a> starting at line 132.</p>
<p>This functor is called by the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ke... | 0 | 2016-06-13T04:19:26Z | [
"python",
"tensorflow",
"softmax",
"cross-entropy"
] |
Overwrite valueChanged pyqt5 adding Qt.QueuedConnection | 37,775,603 | <p>I want to create my own class of QSpinBox and overwriting the valueChanged method to behaviour as I need adding the <code>Qt.QueuedConnection</code> type instead of <code>Qt.AutoConnection</code></p>
<p>here is the code I use :</p>
<pre><code>class AbstractSpinBox(QtWidgets.QSpinBox):
def __init__(self, paren... | 0 | 2016-06-12T14:51:12Z | 37,783,292 | <p>Why do you need to extend <code>QSpinBox</code> for that? It's a signal, and you'll select the connection type when <em>connecting</em> it, not when defining it.</p>
| 1 | 2016-06-13T06:44:45Z | [
"python",
"pyqt5"
] |
Steam WebAPI AuthenticateUser | 37,775,604 | <p>How to auth user via <a href="https://api.steampowered.com/ISteamUserAuth/AuthenticateUser/v0001" rel="nofollow">https://api.steampowered.com/ISteamUserAuth/AuthenticateUser/v0001</a> api method?</p>
<p>For example, I will get steam public key data from <a href="https://steamcommunity.com/login/getrsakey/" rel="nof... | 0 | 2016-06-12T14:51:13Z | 37,775,660 | <p>As far as I am concerned, you are not allowed to do this operation, hence the "403 forbidden" So, you simply are not "authorized" to perform this with the credentials you have.</p>
<p><a href="https://en.wikipedia.org/wiki/HTTP_403" rel="nofollow">https://en.wikipedia.org/wiki/HTTP_403</a></p>
<blockquote>
<p>A... | 0 | 2016-06-12T14:57:44Z | [
"python",
"authentication",
"encryption",
"steam-web-api"
] |
Steam WebAPI AuthenticateUser | 37,775,604 | <p>How to auth user via <a href="https://api.steampowered.com/ISteamUserAuth/AuthenticateUser/v0001" rel="nofollow">https://api.steampowered.com/ISteamUserAuth/AuthenticateUser/v0001</a> api method?</p>
<p>For example, I will get steam public key data from <a href="https://steamcommunity.com/login/getrsakey/" rel="nof... | 0 | 2016-06-12T14:51:13Z | 37,901,625 | <p>AuthenticateUser doesn't do what you think it does. It's used by the Steam client to get web session logon cookies for the user who is currently logged into the client. The loginkey that AuthenticateUser asks for comes from the CM (the server which the client connects to).</p>
<p>If you want to log a user into the ... | 0 | 2016-06-18T21:06:17Z | [
"python",
"authentication",
"encryption",
"steam-web-api"
] |
Python type variables wrong message | 37,775,621 | <p>Why do I keep getting the message wrong when I run this code in the python console? For a I enter 5.</p>
<pre><code>a = raw_input("type a number here: ")
if type(a) != int == False:
print ("Input verified!")
elif type(a) != float == False:
print ("Input verified!")
else:
print ("Wrong!")
</code></... | -5 | 2016-06-12T14:53:32Z | 37,775,669 | <p><code>type(a) != int == False</code> is a <em>chained comparison</em>, and evaluates as:</p>
<pre><code>(type(a) != int) and (int == False)
</code></pre>
<p><code>int == False</code> is always going to be false.</p>
<p>Don't use <code>== False</code> or <code>== True</code> in boolean tests; just test directly or... | 4 | 2016-06-12T14:58:48Z | [
"python",
"python-2.7"
] |
Pygame.movie missing | 37,775,635 | <p><strong><em>EDIT:</em></strong>
I am having another issue now:</p>
<pre><code>film_app.py:8: RuntimeWarning: use movie: No module named movie
(ImportError: No module named movie)
movie = pygame.movie.Movie('Countdown.mpg')
Traceback (most recent call last):
File "film_app.py", line 8, in <module>
movi... | 1 | 2016-06-12T14:54:55Z | 37,775,703 | <p><code>movie</code> is not a sub package of <code>pygame</code></p>
<p>Use it like this:</p>
<pre><code>movie = pygame.movie.Movie("file.mpg")
</code></pre>
<p>Note however:</p>
<p>The movie api is deprecated and your pygame will most likely not contain any code for this api.</p>
<p>The code will just throw a No... | 2 | 2016-06-12T15:02:50Z | [
"python",
"raspberry-pi",
"pygame",
"raspbian",
"movie"
] |
Calling a function before declaring its body in python 3.x | 37,775,737 | <p>I know that in python, all functions must be defined before any are used. So this code will result in an error:</p>
<pre><code>hello()
def hello():
print('Hi!')
</code></pre>
<p>But in a code like the one bellow:</p>
<pre><code>def func():
hello()
def hello():
print('Hi!')
func()
</code></pre>
<p>... | 1 | 2016-06-12T15:06:59Z | 37,775,784 | <p>Python is an interpreted language, therefore it is interpreted line by line, </p>
<p>Both your examples follow the same logic, </p>
<p>in the second one,</p>
<p><code>func</code> and <code>hello</code> have already been interpreted, so when you call <code>func()</code> they both are known and for that executed.</... | 3 | 2016-06-12T15:10:33Z | [
"python",
"function"
] |
Calling a function before declaring its body in python 3.x | 37,775,737 | <p>I know that in python, all functions must be defined before any are used. So this code will result in an error:</p>
<pre><code>hello()
def hello():
print('Hi!')
</code></pre>
<p>But in a code like the one bellow:</p>
<pre><code>def func():
hello()
def hello():
print('Hi!')
func()
</code></pre>
<p>... | 1 | 2016-06-12T15:06:59Z | 37,775,785 | <p>Defining a new function does not execute it. Hence the <code>hello()</code> function is only called when you call <code>func()</code>, which is done after defining <code>hello()</code>.</p>
| 3 | 2016-06-12T15:10:35Z | [
"python",
"function"
] |
Calling a function before declaring its body in python 3.x | 37,775,737 | <p>I know that in python, all functions must be defined before any are used. So this code will result in an error:</p>
<pre><code>hello()
def hello():
print('Hi!')
</code></pre>
<p>But in a code like the one bellow:</p>
<pre><code>def func():
hello()
def hello():
print('Hi!')
func()
</code></pre>
<p>... | 1 | 2016-06-12T15:06:59Z | 37,775,801 | <p>I think this is because Python code is parsed top-down, and whenever the interpreter sees a function call, <em>it has to execute it right away</em>, so if it's not defined (yet), this will be an error.</p>
<p>On the other hand, if this function isn't being called now, but the call appears in a definition of another... | 0 | 2016-06-12T15:12:57Z | [
"python",
"function"
] |
Find command in python catches only first line | 37,775,741 | <p>Trying to grab the magnet link from the following code </p>
<pre><code>rawdata = ''' <div class="iaconbox center floatright">
<a rel="12624681,0" class="icommentjs kaButton smallButton rightButton" href="https://kat.cr/zootopia-2016-1080p-hdrip-x264-ac3-jyk-t12624681.html#comment">209 <i ... | 0 | 2016-06-12T15:07:20Z | 37,775,781 | <p>try <code>rawdata[rawdata.find('href="magnet:?')+1:rawdata.find('"')]</code></p>
| 1 | 2016-06-12T15:10:14Z | [
"python",
"find",
"text-manipulation"
] |
Find command in python catches only first line | 37,775,741 | <p>Trying to grab the magnet link from the following code </p>
<pre><code>rawdata = ''' <div class="iaconbox center floatright">
<a rel="12624681,0" class="icommentjs kaButton smallButton rightButton" href="https://kat.cr/zootopia-2016-1080p-hdrip-x264-ac3-jyk-t12624681.html#comment">209 <i ... | 0 | 2016-06-12T15:07:20Z | 37,775,956 | <p>It's better to use regular expression.</p>
<pre><code>import re
rawdata = '''your rawdata......'''
regex = re.compile('href="(.+)" class="icon16')
magnet_href = regex.search(rawdata).group(1)
</code></pre>
| 1 | 2016-06-12T15:26:58Z | [
"python",
"find",
"text-manipulation"
] |
Find command in python catches only first line | 37,775,741 | <p>Trying to grab the magnet link from the following code </p>
<pre><code>rawdata = ''' <div class="iaconbox center floatright">
<a rel="12624681,0" class="icommentjs kaButton smallButton rightButton" href="https://kat.cr/zootopia-2016-1080p-hdrip-x264-ac3-jyk-t12624681.html#comment">209 <i ... | 0 | 2016-06-12T15:07:20Z | 37,775,964 | <p>First of all, as pointed out by HenryM, you need to use single quotes or escape the <code>"</code> to make the strings valid. </p>
<p>Second, <code>find()</code> always returns the first index of the character found. So you will find the first <code>"</code> and not the one ending the link. To fix this use the <cod... | 1 | 2016-06-12T15:27:34Z | [
"python",
"find",
"text-manipulation"
] |
Find command in python catches only first line | 37,775,741 | <p>Trying to grab the magnet link from the following code </p>
<pre><code>rawdata = ''' <div class="iaconbox center floatright">
<a rel="12624681,0" class="icommentjs kaButton smallButton rightButton" href="https://kat.cr/zootopia-2016-1080p-hdrip-x264-ac3-jyk-t12624681.html#comment">209 <i ... | 0 | 2016-06-12T15:07:20Z | 37,776,200 | <p>The input data is an HTML fragment. <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">You should not be using regular expressions to parse it</a>.</p>
<p>Use a parser instead. Here is a working sample using <a href="https://www.crummy.com/software/BeautifulS... | 1 | 2016-06-12T15:51:50Z | [
"python",
"find",
"text-manipulation"
] |
string (file1.txt) search from file2.txt | 37,775,790 | <p><code>file1.txt</code> contains usernames, i.e. </p>
<pre><code>tony
peter
john
...
</code></pre>
<p><code>file2.txt</code> contains user details, just one line for each user details, i.e. </p>
<pre><code>alice 20160102 1101 abc
john 20120212 1110 zjc9
mary 20140405 0100 few3
peter 20140405 0001 io9... | -2 | 2016-06-12T15:11:14Z | 37,776,128 | <pre><code>import pandas as pd
df1 = pd.read_csv('df1.txt', header=None)
df2 = pd.read_csv('df2.txt', header=None)
df1[0] = df1[0].str.strip() # remove the 2 whitespace followed by the feild
df2 = df2[0].str[0:-2].str.split(' ').apply(pd.Series) # split the word and remove whitespace
df = df1.merge(df2)
Out[26]:
... | 0 | 2016-06-12T15:43:38Z | [
"python",
"string",
"search",
"fromfile"
] |
string (file1.txt) search from file2.txt | 37,775,790 | <p><code>file1.txt</code> contains usernames, i.e. </p>
<pre><code>tony
peter
john
...
</code></pre>
<p><code>file2.txt</code> contains user details, just one line for each user details, i.e. </p>
<pre><code>alice 20160102 1101 abc
john 20120212 1110 zjc9
mary 20140405 0100 few3
peter 20140405 0001 io9... | -2 | 2016-06-12T15:11:14Z | 37,776,132 | <p>You can use <code>pandas</code>:</p>
<pre><code>import pandas as pd
file1 = pd.read_csv('file1.txt', sep =' ', header=None)
file2 = pd.read_csv('file2.txt', sep=' ', header=None)
shortlist = file2.loc[file2[0].isin(file1.values.T[0])]
</code></pre>
<p>it will give you the following result:</p>
<pre><code> ... | 0 | 2016-06-12T15:43:49Z | [
"python",
"string",
"search",
"fromfile"
] |
string (file1.txt) search from file2.txt | 37,775,790 | <p><code>file1.txt</code> contains usernames, i.e. </p>
<pre><code>tony
peter
john
...
</code></pre>
<p><code>file2.txt</code> contains user details, just one line for each user details, i.e. </p>
<pre><code>alice 20160102 1101 abc
john 20120212 1110 zjc9
mary 20140405 0100 few3
peter 20140405 0001 io9... | -2 | 2016-06-12T15:11:14Z | 37,776,141 | <p>You can use <code>.split(' ')</code>, assuming that there will always be a space between the name and the other information in the <code>file2.txt</code></p>
<p>Here's an example:</p>
<pre><code>UserList = []
with open("file1.txt","r") as fuser:
UserLine = fuser.readline()
while UserLine!='':
... | 0 | 2016-06-12T15:44:51Z | [
"python",
"string",
"search",
"fromfile"
] |
Creating a function inside a class with self variables as arguments (Python) | 37,775,984 | <p>Inside a class I want to create a method that would have as arguments some <code>self.</code> variables.</p>
<p>For example (some code taken from <a href="http://stackoverflow.com/questions/37772551/filter-values-inside-python-generator-expressions#37772746">here</a>), say that I have</p>
<pre><code>class Summatio... | -1 | 2016-06-12T15:29:21Z | 37,776,041 | <p>You can use <code>getattr()</code> to access attributes dynamically; give the object to look the attribute on (<code>self</code> here) and a string with the name of the attribute:</p>
<pre><code>def do_sums(self, d, l):
return sum(getattr(self, d).get(k, 0) for k in getattr(self, l))
</code></pre>
<p>and pass ... | 2 | 2016-06-12T15:35:05Z | [
"python",
"class",
"python-3.x",
"self"
] |
Find and extract curr_id number from Investing | 37,775,998 | <p>I need to know the <code>curr_id</code> to submit using python to investing.com and extract historic data for a number of currencies/commodities. To do this I need the <code>curr_id</code> number. As in the example bellow. I'm able to extract all scripts. But then I cannot figure out how to find the correct script i... | 2 | 2016-06-12T15:30:42Z | 37,776,127 | <p>You can use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="nofollow">regular expression pattern</a> as a <code>text</code> argument to find a specific <code>script</code> element. Then, search inside the text of the <code>script</code> using the same regular expression:<... | 2 | 2016-06-12T15:43:26Z | [
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
Find and extract curr_id number from Investing | 37,775,998 | <p>I need to know the <code>curr_id</code> to submit using python to investing.com and extract historic data for a number of currencies/commodities. To do this I need the <code>curr_id</code> number. As in the example bellow. I'm able to extract all scripts. But then I cannot figure out how to find the correct script i... | 2 | 2016-06-12T15:30:42Z | 37,777,397 | <p>You don't actually need a regex, you can get the id from by extracting the value attribute from the input tag with the <code>name=item_ID</code></p>
<pre><code>In [6]: from bs4 import BeautifulSoup
In [7]: import requests
In [8]: r = requests.get("http://www.investing.com/currencies/usd-brl-historical-data").con... | 1 | 2016-06-12T17:56:32Z | [
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
Saving gzipped JSON causes connection resets | 37,776,093 | <p>I have a <a href="http://auction-api-us.worldofwarcraft.com/auction-data/4923213e5eb3ec3b7e03d22b632bda36/auctions.json" rel="nofollow">gzipped JSON file</a> that I'm trying to download, but when I try and read the response content with the requests library, it resets the connection.</p>
<pre><code>data = requests.... | 0 | 2016-06-12T15:39:54Z | 37,776,221 | <p>requests already decompress the data.</p>
<p>You do not need to use gzip:</p>
<pre><code>import requests
req = requests.get("http://auction-api-us.worldofwarcraft.com/auction-data/4923213e5eb3ec3b7e03d22b632bda36/auctions.json", stream=True)
with open("out.json", "wb") as f:
for chunk in req.iter_content(chu... | 0 | 2016-06-12T15:53:47Z | [
"python",
"json",
"gzip"
] |
Saving gzipped JSON causes connection resets | 37,776,093 | <p>I have a <a href="http://auction-api-us.worldofwarcraft.com/auction-data/4923213e5eb3ec3b7e03d22b632bda36/auctions.json" rel="nofollow">gzipped JSON file</a> that I'm trying to download, but when I try and read the response content with the requests library, it resets the connection.</p>
<pre><code>data = requests.... | 0 | 2016-06-12T15:39:54Z | 37,793,157 | <p>So the issue isn't actually with the API I'm using, it's either a bug with the requests library for Windows or an issue with Python 3.5.1 on Windows 10.</p>
<p>When I ran this exact code on Ubuntu 16.04 using Python 3.5.1, it worked just fine.</p>
| 0 | 2016-06-13T15:03:35Z | [
"python",
"json",
"gzip"
] |
How to make tkinter show multiple warnings in python, and how to make a python script uncloseable? | 37,776,158 | <p>I want to prank my friends, by making a script, that keeps displaying a warning, and is completely un-closeable. My code so far is:</p>
<pre><code>import tkinter as tk
from tkinter import messagebox
import random
root = tk.Tk()
messages=["Anodr settlument neds yer hulp!","Another settlement needs your help!",
... | -2 | 2016-06-12T15:46:53Z | 37,776,323 | <p>Turn the message into a question, then just keep asking stupid questions...not recommended though, they might not be your friend anymore.</p>
<pre><code>yn = tkMessageBox.askyesno("Text", "Ask a question...")
if yn == True:
yn = tkMessageBox.askyesno("Text", "Ask another question...")
if yn == True:
... | -2 | 2016-06-12T16:03:48Z | [
"python",
"tkinter",
"malware"
] |
Pycharm/Python OpenCV and CV2 install error | 37,776,228 | <p>I've been trying to install both OpenCV and cv2 from both Pycharm and from the terminal as suggested using:</p>
<pre><code>pip install --user opencv
pip install --user cv2
</code></pre>
<p>but I'm getting the following error for them:</p>
<pre><code>Collecting opencv
Could not find a version that satisfies the ... | 3 | 2016-06-12T15:54:16Z | 39,308,557 | <p>I ran into the same problem. One issue might be OpenCV is created for Python 2.7, not 3 (not all python 2.7 libraries will work in python 3 or greater). I also don't believe you can download OpenCV directly through PyCharm's package installer. I have found luck following the instructions: <a href="https://opencv-pyt... | 0 | 2016-09-03T15:31:57Z | [
"python",
"opencv",
"pycharm"
] |
Conda says conflict over installing dateutil in Python 3.5.1 | 37,776,256 | <p>I have a Python 3.5.1 environment managed by conda. I'm trying to create a new Python 3.5.1 environment with <code>conda create</code> and listing several of the modules I want in the new environment.</p>
<p>One such module is <a href="https://anaconda.org/anaconda/dateutil" rel="nofollow"><code>dateutil</code></a>... | 2 | 2016-06-12T15:57:07Z | 38,065,266 | <p>The URL <a href="http://repo.continuum.io/pkgs/free/linux-64/dateutil-2.4.2-py35_0.tar.bz2" rel="nofollow">http://repo.continuum.io/pkgs/free/linux-64/dateutil-2.4.2-py35_0.tar.bz2</a> no longer exists, and I'm not sure why. I'm filing an issue for you on anaconda-issues.</p>
<p><a href="https://github.com/Continu... | 1 | 2016-06-28T00:31:36Z | [
"python",
"python-3.x",
"conda",
"python-dateutil"
] |
Covariance in Python with iminuit | 37,776,275 | <p>I have to calculate the covariance between 2 parameters from a fit function. I found this package in Python called iminuit that did a good fit and also calculate the covariance matrix of the parameters. I tested the package on a simple function. This is the code:</p>
<pre><code>from iminuit import Minuit, describe,... | 0 | 2016-06-12T15:58:47Z | 37,776,331 | <p>You are confusing covariance with correlation. Correlation is the normalised version of the covariance, which is indeed always between -1 and 1.</p>
<p>To obtain the corellation from the covariance matrix, calculate:</p>
<pre><code>correlation = cov[0, 1] / np.sqrt(cov[0, 0] * cov[1, 1])
</code></pre>
| 0 | 2016-06-12T16:04:27Z | [
"python",
"iminuit"
] |
Scalar multiplication not working with image vector | 37,776,506 | <p>I've imported an image and converted it to a vector, now I want to multiply it by a scalar. I'm getting very odd behavior.</p>
<pre><code>import numpy
import Image
image = Image.open("./yalefaces/subject01.gif").convert("L")
vector = numpy.asarray(image).flatten()
print vector
print vector * 2
</code></pre>
<p>Th... | 0 | 2016-06-12T16:20:39Z | 37,776,571 | <p>This should give you what you need:</p>
<pre><code>numpy.multiply(vector,2)
</code></pre>
| -1 | 2016-06-12T16:26:30Z | [
"python",
"numpy",
"python-imaging-library"
] |
Scalar multiplication not working with image vector | 37,776,506 | <p>I've imported an image and converted it to a vector, now I want to multiply it by a scalar. I'm getting very odd behavior.</p>
<pre><code>import numpy
import Image
image = Image.open("./yalefaces/subject01.gif").convert("L")
vector = numpy.asarray(image).flatten()
print vector
print vector * 2
</code></pre>
<p>Th... | 0 | 2016-06-12T16:20:39Z | 37,787,197 | <p>The problem is that when I call <code>numpy.asarray</code> on the image, I get a vector of <code>uint8</code>-s. The reason I get 4 where I expect 2*130 = 260 is because 4 is 260 modulo 256. The solution is to cast to, say, floats:</p>
<pre><code> vector = vector.astype(numpy.float32)
vector = vector * 2
</code></... | 0 | 2016-06-13T10:19:26Z | [
"python",
"numpy",
"python-imaging-library"
] |
Selenium: How to click on all DIVs with same class name | 37,776,723 | <p>I've been working on scraping a site which has usually 10 to 12 DIVs with the same class name. When clicked on any one of these DIVs, it goes to a new page. I want to scrape data from that page and then navigate back to previous page and then click on the next div and so on.</p>
<p>But I can't figure out that when ... | 1 | 2016-06-12T16:44:50Z | 37,776,745 | <p>The problem with that is that you cannot simply find all the <code>div</code>s and click them one by one because when you get back to the previous page the elements you've previously found already became "stale" and you need to "re-find" them.</p>
<p>I'd maintain an <em>index</em> of a current <code>div</code> elem... | 1 | 2016-06-12T16:47:01Z | [
"python",
"selenium"
] |
Build a Pypet (Tatiana Tylosky) Double "For" Loop | 37,776,724 | <p>I've just completed <a href="https://www.thinkful.com/learn/intro-to-python-tutorial/#Creating-Your-Pypet" rel="nofollow">Tatiana Tylosky's tutorial for Python</a> and created my own Python pypet.</p>
<p>In her tutorial, she shows how to do a "for" loop consisting of:</p>
<pre><code>cat = {
'name': 'Fluffy',
... | 1 | 2016-06-12T16:44:52Z | 37,776,768 | <p>I would enclose your feed <code>for</code> loop in a <code>for</code> loop that iterates three times. I would use something like:</p>
<pre><code>for _ in range(3):
for pet in pets:
feed(pet)
print pet
</code></pre>
<p><code>for _ in range(3)</code> iterates three times. Note that I used <code... | 1 | 2016-06-12T16:49:27Z | [
"python"
] |
Build a Pypet (Tatiana Tylosky) Double "For" Loop | 37,776,724 | <p>I've just completed <a href="https://www.thinkful.com/learn/intro-to-python-tutorial/#Creating-Your-Pypet" rel="nofollow">Tatiana Tylosky's tutorial for Python</a> and created my own Python pypet.</p>
<p>In her tutorial, she shows how to do a "for" loop consisting of:</p>
<pre><code>cat = {
'name': 'Fluffy',
... | 1 | 2016-06-12T16:44:52Z | 37,776,865 | <p>Programming languages let you embed one structure in another. Put your current loop under a for loop that runs three times, as @intboolstring's answer already showed. Here are two more things you should do now:</p>
<ol>
<li><p>Don't compare against <code>True</code>. <code>if pet["Hungry"] == True:</code> is better... | 0 | 2016-06-12T17:00:51Z | [
"python"
] |
Build a Pypet (Tatiana Tylosky) Double "For" Loop | 37,776,724 | <p>I've just completed <a href="https://www.thinkful.com/learn/intro-to-python-tutorial/#Creating-Your-Pypet" rel="nofollow">Tatiana Tylosky's tutorial for Python</a> and created my own Python pypet.</p>
<p>In her tutorial, she shows how to do a "for" loop consisting of:</p>
<pre><code>cat = {
'name': 'Fluffy',
... | 1 | 2016-06-12T16:44:52Z | 37,776,921 | <p>If you don't want to use nested for loops you could also extend the pet list temporarily like this:</p>
<pre><code>for pet in pets * 3:
feed(pet)
</code></pre>
<p>that works because <code>pet * 3</code> creates the following list: <code>[cat, mouse, cat, mouse, cat, mouse]</code></p>
<p>If you need more contr... | 0 | 2016-06-12T17:07:06Z | [
"python"
] |
F2PY cannot find intel fortran compiler on windows 7 | 37,776,876 | <p>I am struggling to get F2PY working with Intel Fortran on Windows 7. This appears to be a common issue and I have attempted a number of suggestions found in other posts (described below). </p>
<p>A bit of information about my system:</p>
<ul>
<li>Windows 7 64-bit </li>
<li>Python 2.7.11 via Enthought Canopy 32-b... | 0 | 2016-06-12T17:02:00Z | 37,802,600 | <p>After some further experimentation, I was able to resolve the issue and am posting the steps that worked in case it may help others with similar problems.</p>
<ol>
<li>f2py can now find Intel Fortran after setting the path to C:\Program Files (x86)\Intel\Composer XE 2013 SP1\bin\ia32 and rebooting</li>
<li><p>Howev... | 0 | 2016-06-14T03:42:34Z | [
"python",
"intel-fortran",
"f2py"
] |
Remove different type of characters form DataFrame column | 37,776,901 | <p>I have the following column in a DataFrame</p>
<pre><code>0 EUR/USD
1 GBP/USD
2 USD/JPY
3 USD/CHF
4 AUD/USD
5 USD/CAD
6 NZD/USD
7 USD/ZAR
8 USD/TRY
9 BTC/USD
10 USD/MXN
11 USD/PLN
12 USD/SEK
13 USD/SGD
14 USD/DKK
</code></pre>
<p>I need to remov... | 0 | 2016-06-12T17:04:51Z | 37,776,953 | <p>You could use <code>str.replace</code> with the regex pattern <code>/USD|USD/</code>:</p>
<pre><code>In [180]: df['col'].str.replace(r'/USD|USD/', '')
Out[180]:
0 EUR
1 GBP
2 JPY
3 CHF
4 AUD
5 CAD
6 NZD
7 ZAR
8 TRY
9 BTC
10 MXN
11 PLN
12 SEK
13 SGD
14 DKK
Name... | 1 | 2016-06-12T17:10:18Z | [
"python",
"regex",
"dataframe"
] |
python re.sub - alternative replacement patterns | 37,776,934 | <p>I want to provide alternative replacement patterns to re.sub.</p>
<p>Let's say i've got two search patterns as alternatives, like this:</p>
<pre><code>re.sub(r"[A-Z]+|[a-z]+", replacementpattern, string)
</code></pre>
<p>and instead of providing one replacement pattern I would like to somehow catch which search p... | 1 | 2016-06-12T17:07:59Z | 37,777,711 | <p>You can pass a function to <code>re.sub()</code>. In the function you can return the value needed based on the captured group. A simple code for illustration:</p>
<pre><code>>>> def fun(m):
... if m:
... if m.group(1):
... return 'x'
... else:
... return 'y'
>>>print re.s... | 0 | 2016-06-12T18:29:43Z | [
"python",
"regex",
"python-3.x"
] |
python re.sub - alternative replacement patterns | 37,776,934 | <p>I want to provide alternative replacement patterns to re.sub.</p>
<p>Let's say i've got two search patterns as alternatives, like this:</p>
<pre><code>re.sub(r"[A-Z]+|[a-z]+", replacementpattern, string)
</code></pre>
<p>and instead of providing one replacement pattern I would like to somehow catch which search p... | 1 | 2016-06-12T17:07:59Z | 37,778,545 | <p>Usually, you would just use two replacements:</p>
<pre><code>re.sub(r"[A-Z]+", replacement1, string)
re.sub(r"[a-z]+", replacement2, string)
</code></pre>
<p>Anticlimactic, right?</p>
<p>It's actually less code than the alternatives usually, and it's far clearer what you're doing.</p>
| 0 | 2016-06-12T20:01:52Z | [
"python",
"regex",
"python-3.x"
] |
Scipy optimize.minimize function | 37,777,025 | <p>I try to solve nonlinear programming task using scipy.optimize.minimize</p>
<pre><code>max r
x1**2 + y1**2 <= (1-r)**2
(x1-x2)**2 + (y1-y2)**2 >= 4*r**2
0 <= r <= 1
</code></pre>
<p>So I've wrote next code:</p>
<pre><code>r = np.linspace(0, 1, 100)
x1 = np.linspace(0, 1, 100)
y1 = np.linspace(0, 1, 10... | 0 | 2016-06-12T17:18:04Z | 37,777,190 | <p>Your parameter space appears to be 5-dimensional. A point in your parameter
space would be <code>z = (r, x1, y1, x2, y2)</code>. Therefore the function to be minimized
-- and also the constraint functions -- should accept a point <code>z</code> and
return a scalar value.</p>
<p>Thus instead of</p>
<pre><code>fun... | 2 | 2016-06-12T17:36:40Z | [
"python",
"scipy",
"nonlinear-optimization"
] |
Create valid .mp3 file with python | 37,777,108 | <p>I saw this piece of perl code, which creates an MP3 object and writes some tags to it. I don't write code in perl but i assume it creates a valid mp3 file with tags.</p>
<pre><code>$mp3 = MP3::Tag->new('1.mp3');
$mp3->title_set('Some_title');
$mp3->artist_set('Some_artist');
$mp3->update_tags();
$mp3-... | 0 | 2016-06-12T17:29:18Z | 37,777,264 | <p>You are incorrect about Perl's <a href="https://metacpan.org/pod/MP3::Tag" rel="nofollow">MP3::Tag</a> module. Its constructor expects an existing valid MP3 file, whose tags you may read and modify. It will not create an MP3 file from scratch</p>
<p><a href="http://www.xamuel.com/blank-mp3s/" rel="nofollow">This si... | 3 | 2016-06-12T17:43:04Z | [
"python",
"perl",
"tags",
"mp3",
"id3"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.