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 |
---|---|---|---|---|---|---|---|---|---|
Numeric output and dont echo repeating numbers for ex 1010101; 2020202, 1212121
| 39,433,142 |
<p>Looking for a script that can pipe or print to file and generate a random, non repeating output wordlist/numberlist [crunch for example can do that with the -d option but 10101 etc dont get sorted out]. </p>
<p>Example: a numeric list <code>000000-999999</code> and written to a file / pipe to program all numbers but no repeating sequences like <code>1010101; 2020202; 12121212, 13131313 ......</code> or repeating numbers <code>11 222 3333 44444 .....</code></p>
<p>EDIT:</p>
<p>Great answers so far, thank you.</p>
<p>Heres a little hack that does pretty much what is intented, but not perfectly.
Looking for a solution to have the result directly, going through the answers asap.</p>
<pre><code>sed -i -e '/1010/d' -e '/1212/d' file.txt
</code></pre>
<p>Source:
<a href="http://stackoverflow.com/questions/5410757/delete-lines-in-a-text-file-that-containing-a-specific-string">Delete lines in a text file that containing a specific string</a></p>
| 0 |
2016-09-11T05:22:58Z
| 39,433,384 |
<p>You are looking for a (pseudo-) random number generator, and there are many to choose from. Scale what your chosen one gives you (usually between 0 and 1) and fill your sequences by calling it repeatedly. Or use the scaled sequence to pull from ASCII tables if you want characters.</p>
<p>Perl comes with a builtin <a href="http://perldoc.perl.org/functions/rand.html" rel="nofollow"><code>rand</code></a>, which since Perl 5.20 is actually Perl's. Prior to that it used whatever was available on the system. This is a toy generator, not suitable for serious work. For reasons see for example <a href="https://www.nu42.com/2014/05/perl-5200-brings-better-prng-to-windows.html" rel="nofollow"><code>Sinan Unur's analysis</code></a> or older <a href="http://wellington.pm.org/archive/200704/randomness/#slide0" rel="nofollow"><code>Wellington's</code></a> thorough discussion. If you don't care for the period, correlations in higher dimensions, and such, it is probably OK.</p>
<p>There are modules in Perl which supply good alternatives. For example, <a href="http://search.cpan.org/~mkanat/Math-Random-Secure-0.06/lib/Math/Random/Secure.pm" rel="nofollow"><code>Math::Random::Secure</code></a> claims cryptographically secure quality and is probably more than adequate. If you need truly random numbers pooled from measurements of natural phenomena, and not pseudo-random sequences generated by a computer, the <a href="https://www.random.org/" rel="nofollow"><code>random.org</code></a> has them. The Perl module <a href="https://metacpan.org/pod/Net::Random" rel="nofollow"><code>Net::Random</code></a> provides interface to it, or to other sources of your choosing.</p>
<p>As for the code, once you try something let us know if there are problems.</p>
<hr>
<p>A toy example</p>
<pre><code>use warnings 'all';
use strict;
use feature 'say';
my $max = 999_999;
my @rand_ints;
for (1..$max) {
push @rand_ints, sprintf("%0*.0f", length($max), rand() * $max);
}
say for @rand_ints;
</code></pre>
<p>This prints reasonably random integers between <code>000000</code> and <code>999999</code>, one per line.</p>
<hr>
<p>It is possible that the requirement against "<em>repeating sequences</em>" means that no digits may repeat in a number (and that <code>010101</code> should be thrown out), thanks to <a href="http://stackoverflow.com/users/5771269/cdlane">cdlane</a> for a comment.</p>
<p>In that case I still recommend to pull from a good generator, but test each number. If it sports the offending repetitions discard and pull the next one. This will extend the needed sequence greatly, along with the processing time. For example</p>
<pre><code>while (1) {
my $rint = sprintf("%0*.0f", length($max), rand() * $max);
next if rep_digits_seqs($rint);
push @rand_ints, $rint;
last if @rand_ints == $max;
}
sub rep_digits_seqs {
return ($_[0] =~ /(\d)\1/ or $_[0] =~ /(\d\d)\1/);
}
</code></pre>
<p>The call to <a href="http://perldoc.perl.org/functions/sprintf.html" rel="nofollow"><code>sprintf</code></a> may seem wrong before the test for numbers that may fail anyway, but without it we would occasionally test un-rounded ones, resulting in errors. This excludes any repeated digits (<code>11</code>, <code>88</code>), and any repeated two-digit sequences like <code>1212</code> or <code>7575</code>. But it also excludes <code>0012...</code>. Adjust as needed.</p>
<p>Note that this particular requirement, of avoiding repetitions, results in repeated numbers. Consider the case where we have 10 digits to form a six-long number, without repetitions. This can be done in "<em>10 choose 6</em>" ways, which is <code>10!/(6!4!)</code> (factorials), ie. 210. So that's how many different numbers we'd have. Here we have more, since only some repetitions are excluded -- but it still seems to be a far cry from the needed million. So if we produce a million numbers some (many) will have to appear more than once. What also means that most numbers are likely to fail and we'd need a <em>very</em> long original sequence. I doubt that what comes out is a good pseudo-random sequence.</p>
| 2 |
2016-09-11T06:14:36Z
|
[
"python",
"bash",
"perl",
"random",
"sequence"
] |
Numeric output and dont echo repeating numbers for ex 1010101; 2020202, 1212121
| 39,433,142 |
<p>Looking for a script that can pipe or print to file and generate a random, non repeating output wordlist/numberlist [crunch for example can do that with the -d option but 10101 etc dont get sorted out]. </p>
<p>Example: a numeric list <code>000000-999999</code> and written to a file / pipe to program all numbers but no repeating sequences like <code>1010101; 2020202; 12121212, 13131313 ......</code> or repeating numbers <code>11 222 3333 44444 .....</code></p>
<p>EDIT:</p>
<p>Great answers so far, thank you.</p>
<p>Heres a little hack that does pretty much what is intented, but not perfectly.
Looking for a solution to have the result directly, going through the answers asap.</p>
<pre><code>sed -i -e '/1010/d' -e '/1212/d' file.txt
</code></pre>
<p>Source:
<a href="http://stackoverflow.com/questions/5410757/delete-lines-in-a-text-file-that-containing-a-specific-string">Delete lines in a text file that containing a specific string</a></p>
| 0 |
2016-09-11T05:22:58Z
| 39,433,487 |
<p>Here's a potential, simple solution for the specific six digit range, 000000-999999, you requested:</p>
<pre><code>from regex import match
from random import sample
DIGITS = 6
assert (DIGITS % 2 == 0), "Only works for even digit string lengths"
number_format = "{:0" + str(DIGITS) + "d}"
for number in sample(range(10**DIGITS), 10**DIGITS):
string = number_format.format(number)
if match(r"^(.+)\1+$", string) is None:
print(string)
</code></pre>
<p>The repetition examples you gave were for seven and eight digit numbers. In odd length numeric strings it would be tricker to detect the final one in <code>1010101</code> as a partial match. Only even length numeric strings can be done with the above thus the <code>assert</code>.</p>
| 1 |
2016-09-11T06:36:35Z
|
[
"python",
"bash",
"perl",
"random",
"sequence"
] |
Numeric output and dont echo repeating numbers for ex 1010101; 2020202, 1212121
| 39,433,142 |
<p>Looking for a script that can pipe or print to file and generate a random, non repeating output wordlist/numberlist [crunch for example can do that with the -d option but 10101 etc dont get sorted out]. </p>
<p>Example: a numeric list <code>000000-999999</code> and written to a file / pipe to program all numbers but no repeating sequences like <code>1010101; 2020202; 12121212, 13131313 ......</code> or repeating numbers <code>11 222 3333 44444 .....</code></p>
<p>EDIT:</p>
<p>Great answers so far, thank you.</p>
<p>Heres a little hack that does pretty much what is intented, but not perfectly.
Looking for a solution to have the result directly, going through the answers asap.</p>
<pre><code>sed -i -e '/1010/d' -e '/1212/d' file.txt
</code></pre>
<p>Source:
<a href="http://stackoverflow.com/questions/5410757/delete-lines-in-a-text-file-that-containing-a-specific-string">Delete lines in a text file that containing a specific string</a></p>
| 0 |
2016-09-11T05:22:58Z
| 39,435,515 |
<p>Your question is not completely clear. Is 123435 allowed, since the 3 is repeated?</p>
<p>Assuming absolutely no repetition is required, then put the ten digits [0..9] in an array, shuffle the array and pick off the first six digits. If you don't want a leading zero, then if necessary drop the leading zero and add the seventh digit from the shuffle at the end to get back to six digits.</p>
| 0 |
2016-09-11T11:17:35Z
|
[
"python",
"bash",
"perl",
"random",
"sequence"
] |
Numeric output and dont echo repeating numbers for ex 1010101; 2020202, 1212121
| 39,433,142 |
<p>Looking for a script that can pipe or print to file and generate a random, non repeating output wordlist/numberlist [crunch for example can do that with the -d option but 10101 etc dont get sorted out]. </p>
<p>Example: a numeric list <code>000000-999999</code> and written to a file / pipe to program all numbers but no repeating sequences like <code>1010101; 2020202; 12121212, 13131313 ......</code> or repeating numbers <code>11 222 3333 44444 .....</code></p>
<p>EDIT:</p>
<p>Great answers so far, thank you.</p>
<p>Heres a little hack that does pretty much what is intented, but not perfectly.
Looking for a solution to have the result directly, going through the answers asap.</p>
<pre><code>sed -i -e '/1010/d' -e '/1212/d' file.txt
</code></pre>
<p>Source:
<a href="http://stackoverflow.com/questions/5410757/delete-lines-in-a-text-file-that-containing-a-specific-string">Delete lines in a text file that containing a specific string</a></p>
| 0 |
2016-09-11T05:22:58Z
| 39,490,035 |
<p>OK, this is my definition of finding and eliminating repetitive strings. The idea is to:</p>
<ul>
<li>draw a random string of numbers and zeropad it (<code>str</code>)</li>
<li>store the first two characters (<code>replen</code> actually) of every substring to an array (<code>prefix</code>) and if there is a collision, there is a repetition in the string and another candidate is drawn, ie: <code>12312</code> -> <code>12</code>, <code>23</code>, <code>31</code>, <code>12</code> and the latter <code>12</code> is a collision and therefore the string is repetitive.</li>
<li>downside to current implementation is that 3 consecutive same numbers is considered a repetition: <code>666</code> -> <code>66</code>, <code>66</code> collision. This, however, is could be considered repetition but then again <code>66</code> is also and @rossum's solution should be used.</li>
</ul>
<p>awk:</p>
<pre><code>BEGIN {
# if(seed=="") { # note to self...
# print "-v seed=$RANDOM"
# exit
# }
replen=2 # minimum length of possible repetition
len=8 # set desired str length
srand(seed) # set the seed for rand
prefix[""]
while(length(prefix)<len-1) {
str=sprintf("%0"len"d",rand()*10^len-1) # get a random string of numbers, zeropad
for(i=1;i<=len-(replen-1);i++) { # create prefix array
key=substr(str,i,replen) # length(key) to array is 2
if(key in prefix) { # if duplicate found start over
delete prefix
break
}
else # if key candidate not a duplicate
prefix[key] # add it to array
}
}
print str # print str after while
}
</code></pre>
<p>Run it:</p>
<pre><code>$ awk -v seed=$RANDOM -f random.awk
34592181
</code></pre>
<p>No sanity checking is used for <code>len</code> or <code>replen</code>.</p>
| 0 |
2016-09-14T12:06:47Z
|
[
"python",
"bash",
"perl",
"random",
"sequence"
] |
Python metaclass for randomized quiz questions
| 39,433,159 |
<p>For teaching a large math class, it's helpful to write questions with some randomization built in, so that not all students get the exact same questions. My solution is to write a short Python script to generate a few questions -- identical except slight variations in the numbers. The result might be to give the class versions A/B/C/D of a quiz, and automatically give me solution sets A/B/C/D for quick grading.</p>
<p>I'd like to formalize this a bit, to allow others with <em>basic</em> Python skills to create randomized quizzes. Also, to organize my own work better. My first idea was to make a module with a Question class, which would have methods for initialization, for rendering (producing LaTeX code to include in a quiz document), for assessing a given response/answer, and various other attributes. </p>
<p>But alas, different instances of the Question class (different randomizable questions) would have different methods. For example, one question might randomly generate two three-digit numbers x,y, and render the question as "Find the GCD of (x,y)". At initialization, the question would also compute the answer, and reference it in the assessment method. Another question might randomly generate a single three-digit number p, and render the question as "Is p prime?". </p>
<p>A few solutions came to mind:</p>
<ol>
<li><p>Place code into string attributes, and call it via exec/eval. This is bad.</p></li>
<li><p>Override various methods each time I write a new question. When I investigated this, I learned the term "monkey-patching" which also seems bad.</p></li>
<li><p>Use a Question metaclass! Then, I guess that each randomizable question will end up being a class.</p></li>
</ol>
<p>I guess that solution 3 is the right one, so I'll have to learn metaclasses. But it would be a bit sad too. I would really like this to be usable by <em>beginner</em> programmers to write randomizable questions. I don't want a beginner to have to declare a class for every question.</p>
<p>Alternative ideas? My own skills are on the beginner side when it comes to object-oriented aspects of programming. </p>
<hr>
<h2>Edit: perhaps some more information would be helpful.</h2>
<p>I want to be able to easily reference questions later, e.g. for producing an exam or solution sheet. For example, I would want to pass a list of questions to a function, with a single command like "make_exam([q1,q2,q3], randomize=True)" where q1,q2,q3 are three questions. The command would return LaTeX code for an exam with the question text for q1,q2,q3, suitably randomizing each one. I could also turn on/off a solution sheet, etc.. For this, I think I need the question objects to come with various methods. </p>
| 0 |
2016-09-11T05:26:29Z
| 39,435,420 |
<p>There will be many questions and there will be randomization of some of the parameters within each question. I assume there is no randomization of the choice of questions, only their parameters (although that would be solved the same way).</p>
<p>So, you could have a class for each question:</p>
<pre><code>class QuestionTemplate1():
def __init__(self):
self.x = random.randint(100, 1000)
self.y = random.randint(100, 1000)
def get_question(self):
return "Find the GCD of (%d, %d)" % (self.x, self.y)
</code></pre>
<p>To create a variation of a question, just make an instance. They will be random and they will be different:</p>
<pre><code>quesition1_a = QuestionTemplate1()
quesition1_b = QuestionTemplate1()
</code></pre>
<p>You'll have a list of all question templates <code>[QuestionTemplate1, QuestionTemplate2, QuestionTemplate3,...]</code> and create 4 questions for each.</p>
<p>The only thing left is repeatability. Can you cannot repeat the same random values later? Yes.</p>
<p>At the beginning of the script set the seed.</p>
<pre><code>random.seed(3543626)
questions_a = [Q() for Q in all_templates]
questions_b = [Q() for Q in all_templates]
questions_c = [Q() for Q in all_templates]
questions_d = [Q() for Q in all_templates]
</code></pre>
<p>If you run the same code again with the same seed, you will get the same random parameters. I would probably randomize the seed at the beginning and print it with the questions. Then later, I would be able to recreate the same questions if I wanted.</p>
<p>That is it. No <code>eval</code>, no <code>exec</code>, no monkeypatching, no metaclasses. Not even a super class.</p>
| 0 |
2016-09-11T11:06:28Z
|
[
"python",
"metaclass"
] |
Convert int into str while in __getitem__ Python 2.7
| 39,433,191 |
<p>Okay, i have this string:</p>
<p><code>string = "HelloWorld"</code> </p>
<p>And for this example, I am using a dictionary similar to this:</p>
<p><code>dic = [{'a':'k','b':'i'},{'a':'i','b':'l'},{'a':'x','b':'n'},{'a':'q','b':'o'}]</code></p>
<p>Now.. I need to reference a dictionary from the list, so that I can change the characters in my string. To do so normally I would just do this:</p>
<p><code>dic[#]</code></p>
<p>But in this case I also need a value from that dictionary. Now I tried this:</p>
<p><code>dic[int(char[i[letter]])]</code></p>
<p>But I get the error:</p>
<p><code>'int' object has no attribute '__getitem__'</code></p>
<p>Searching for the error gives me answers here on StackOverflow, but they do not fix my problem.</p>
| -5 |
2016-09-11T05:34:44Z
| 39,433,308 |
<p>Here's my best crystal ball guess at what you want. The keys of your dictionary are only <code>a</code> and <code>b</code>, which aren't any characters in <code>HelloWorld</code>, but if you actually had characters from your string as keys like the following, this is how I'd do the replacement, assuming you want to rotate through the four different dictionaries:</p>
<pre><code>string = "HelloWorld"
D = [{'H':'a','o':'e','l':'i'},{'e':'b','W':'f','d':'j'},{'l':'c','o':'g'},{'l':'d','r':'h'}]
print ''.join(D[i%4][c] for i,c in enumerate(string))
</code></pre>
<p>Output:</p>
<pre><code>abcdefghij
</code></pre>
| 0 |
2016-09-11T06:01:21Z
|
[
"python",
"python-2.7"
] |
Adding one or more attractors to a set of random 2D points
| 39,433,259 |
<p>Given a set of pseudorandom 2D points generated like so:</p>
<pre><code>points = random.sample([[x, y] for x in xrange(width) for y in yrange(height)], 100)
</code></pre>
<p>I would like to be able to add one or more non random attractor points around which the other points will be drawn. I don't plan to animate this so it doesn't need to be very efficient but I would like to be able to specify how the random points are drawn to each of the attractor points (for instance based on the square of the distance and a given gravitational constant) and then feed my points to a function that returns a modified version of the original list:</p>
<pre><code>points = random.sample([[x, y] for x in xrange(width) for y in xrange(height)], 100)
attractors = [(25, 102), (456, 300), (102, 562)]
def attract(random_points_list, attractor_points_list):
(...)
return modified_points_list
new_points_list = attract(points, attractors)
</code></pre>
<p>This new points list would then be used to seed a Voronoi diagram (not part of this question).</p>
| 3 |
2016-09-11T05:50:14Z
| 39,433,706 |
<p>You said you want to be able to change the function, so we need to add a function <code>f</code> to the arguments of <code>attract</code>. This function should need one arguments, the distance of the point, and it should return a number.</p>
<pre><code>import math
def attract(random_point_list, attractor_point_list, f = lambda x: 1/x**2):
for x0, y0 in attractor_point_list:
x0, y0 = float(x0), float(y0)
modified_point_list = []
for x, y in random_point_list:
rx, ry = x0 - x, y0 - y # the relative position of the attractor
distance = math.sqrt(rx**2 + ry**2)
attraction = f(d)
modified_point_list.append((x + attraction*rx/distance, y + attraction*ry/distance)) # (rx, ry) is a vector with length distance -> by dividing with distance we get a vector (rx / distance, ry / distance) with length 1. Multiplying it with attraction, we get the difference of the original and the new location.
random_point_list = modified_point_list
return modified_point_list
</code></pre>
| 0 |
2016-09-11T07:10:45Z
|
[
"python",
"game-physics",
"voronoi"
] |
Adding one or more attractors to a set of random 2D points
| 39,433,259 |
<p>Given a set of pseudorandom 2D points generated like so:</p>
<pre><code>points = random.sample([[x, y] for x in xrange(width) for y in yrange(height)], 100)
</code></pre>
<p>I would like to be able to add one or more non random attractor points around which the other points will be drawn. I don't plan to animate this so it doesn't need to be very efficient but I would like to be able to specify how the random points are drawn to each of the attractor points (for instance based on the square of the distance and a given gravitational constant) and then feed my points to a function that returns a modified version of the original list:</p>
<pre><code>points = random.sample([[x, y] for x in xrange(width) for y in xrange(height)], 100)
attractors = [(25, 102), (456, 300), (102, 562)]
def attract(random_points_list, attractor_points_list):
(...)
return modified_points_list
new_points_list = attract(points, attractors)
</code></pre>
<p>This new points list would then be used to seed a Voronoi diagram (not part of this question).</p>
| 3 |
2016-09-11T05:50:14Z
| 39,435,357 |
<p>This turned out to be a more challenging problem than my initial estimate of it as a pure implementation-effort task. The difficulty is in defining a good attraction model.</p>
<ol>
<li><p>Simulating plain free-fall on attractors (as if in a real gravity field created by multiple point masses) is problematic since you must specify the duration of this process. If the duration is short enough, the displacements will be small and clustering around attractors will not be noticeable. If the duration is long enough then all points will fall on the attractors or be too close to them.</p></li>
<li><p>Computing the new position of each point in one shot (without doing time-based simulation) is simpler, but the question is whether the final position of every point must be affected by <em>all</em> attractors or <em>only the closest one</em> of them. The latter approach (attract-to-closest-one-only) proved to produce more visually appealing results. I could not achieve good results with the former approach (note however, that I tried only relatively simple attraction functions).</p></li>
</ol>
<p>Python 3.4 code with visualization using <code>matplotlib</code> follows:</p>
<pre><code>#!/usr/bin/env python3
import random
import numpy as np
import matplotlib.pyplot as plt
def dist(p1, p2):
return np.linalg.norm(np.asfarray(p1) - np.asfarray(p2))
def closest_neighbor_index(p, attractors):
min_d = float('inf')
closest = None
for i,a in enumerate(attractors):
d = dist(p, a)
if d < min_d:
closest, min_d = i, d
return closest
def group_by_closest_neighbor(points, attractors):
g = []
for a in attractors:
g.append([])
for p in points:
g[closest_neighbor_index(p, attractors)].append(p)
return g
def attracted_point(p, a, f):
a = np.asfarray(a)
p = np.asfarray(p)
r = p - a
d = np.linalg.norm(r)
new_d = f(d)
assert(new_d <= d)
return a + r * new_d/d
def attracted_point_list(points, attractor, f):
result=[]
for p in points:
result.append(attracted_point(p, attractor, f))
return result
# Each point is attracted only to its closest attractor (as if the other
# attractors don't exist).
def attract_to_closest(points, attractors, f):
redistributed_points = []
grouped_points = group_by_closest_neighbor(points, attractors)
for a,g in zip(attractors, grouped_points):
redistributed_points.extend(attracted_point_list(g,a,f))
return redistributed_points
def attraction_translation(p, a, f):
return attracted_point(p, a, f) - p
# Each point is attracted by multiple attracters.
# The resulting point is the average of the would-be positions
# computed for each attractor as if the other attractors didn't exist.
def multiattract(points, attractors, f):
redistributed_points = []
n = float(len(attractors))
for p in points:
p = np.asfarray(p)
t = np.zeros_like(p)
for a in attractors:
t += attraction_translation(p,a,f)
redistributed_points.append(p+t/n)
return redistributed_points
def attract(points, attractors, f):
""" Draw points toward attractors
points and attractors must be lists of points (2-tuples of the form (x, y)).
f maps distance of the point from an attractor to the new distance value,
i.e. for a single point P and attractor A, f(distance(P, A)) defines the
distance of P from A in its new (attracted) location.
0 <= f(x) <= x must hold for all non-negative values of x.
"""
# multiattract() doesn't work well with simple attraction functions
# return multiattract(points, attractors, f);
return attract_to_closest(points, attractors, f);
if __name__ == '__main__':
width=400
height=300
points = random.sample([[x, y] for x in range(width) for y in range(height)], 100)
attractors = [(25, 102), (256, 256), (302, 62)]
new_points = attract(points, attractors, lambda d: d*d/(d+100))
#plt.scatter(*zip(*points), marker='+', s=32)
plt.scatter(*zip(*new_points))
plt.scatter(*zip(*attractors), color='red', marker='x', s=64, linewidths=2)
plt.show()
</code></pre>
| 1 |
2016-09-11T10:58:36Z
|
[
"python",
"game-physics",
"voronoi"
] |
How does this reduce + lambda list filter function work?
| 39,433,301 |
<p>I saw the following code to filter a list into two classes:</p>
<pre><code>reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
</code></pre>
<p>How does it work? the <code>([], [])</code> looks initializing the <code>(a, b)</code> in lambda, but how does it work step by step?</p>
<p>This also doesn't seem to be working in Python 3. Why is that? </p>
| 0 |
2016-09-11T05:59:58Z
| 39,433,394 |
<p>To answer your first query, the equivalent using for loop:</p>
<pre><code>>>> c = [49, 58, 76, 82, 88, 90]
>>> final = ([], [])
>>> for val in c:
... if val > 60:
... final[0].append(val)
... else:
... final[1].append(val)
...
>>> final
([76, 82, 88, 90], [49, 58])
</code></pre>
<p>Equivalent in python3 is:</p>
<pre><code>In [8]: import functools
In [9]: functools.reduce(lambda x,c: (x[0]+[c],x[1]) if c > 60 else (x[0],x[1] + [c]), [49, 58, 76, 82, 88, 90],([],[]))
Out[9]: ([76, 82, 88, 90], [49, 58])
</code></pre>
| 0 |
2016-09-11T06:16:31Z
|
[
"python",
"lambda",
"reduce"
] |
How does this reduce + lambda list filter function work?
| 39,433,301 |
<p>I saw the following code to filter a list into two classes:</p>
<pre><code>reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
</code></pre>
<p>How does it work? the <code>([], [])</code> looks initializing the <code>(a, b)</code> in lambda, but how does it work step by step?</p>
<p>This also doesn't seem to be working in Python 3. Why is that? </p>
| 0 |
2016-09-11T05:59:58Z
| 39,433,411 |
<blockquote>
<p>How does it work? the <code>([], [])</code> looks initializing the <code>(a, b)</code> in lambda, but how does it work step by step?</p>
</blockquote>
<p>At each point, the reduce sees a left hand operand, <code>(a, b)</code>, which is a pair of lists (initially two empty lists), and an element <code>c</code>. It adds the list <code>[c]</code> to either <code>a</code> or <code>b</code>, depending on whether it's larger than 60, and returns the new pair of lists. Thus, it will eventually return the pair of the elements larger than 60, and less than 60, respectively.</p>
<blockquote>
<p>This also doesn't seem to be working in Python 3. Why is that? </p>
</blockquote>
<p>In Python3 you can't anymore define a function explicitly taking a tuple - <a href="https://www.python.org/dev/peps/pep-3113/" rel="nofollow">tuple unpacking has been removed</a>. So</p>
<pre><code>def foo((a, b)):
...
</code></pre>
<p>is illegal in Python3. This is the problem here as well (except in the form of a lambda).</p>
| 1 |
2016-09-11T06:19:54Z
|
[
"python",
"lambda",
"reduce"
] |
How does this reduce + lambda list filter function work?
| 39,433,301 |
<p>I saw the following code to filter a list into two classes:</p>
<pre><code>reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49, 58, 76, 82, 88, 90],([],[]))
</code></pre>
<p>How does it work? the <code>([], [])</code> looks initializing the <code>(a, b)</code> in lambda, but how does it work step by step?</p>
<p>This also doesn't seem to be working in Python 3. Why is that? </p>
| 0 |
2016-09-11T05:59:58Z
| 39,467,535 |
<p>Take a look at the following experiment:</p>
<pre><code>>>> reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49],([],[]))
([], [49])
>>> reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49,58],([],[]))
([], [49, 58])
>>> reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49,58,76],([],[]))
([76], [49, 58])
>>> reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49,58,76,82],([],[]))
([76, 82], [49, 58])
>>> reduce(lambda(a,b),c: (a+[c],b) if c > 60 else (a,b + [c]), [49,58,76,82,88,90],([],[]))
([76, 82, 88, 90], [49, 58])
</code></pre>
<p>Function <code>reduce</code> is described as follows:</p>
<pre><code>reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
</code></pre>
<p>In our example, function is a lambda function with first argument as a 2-element tuple <code>(a,b)</code> and second argument as an integer <code>c</code> picked up from the list for processing. Since function produces a 2-element tuple of lists, it is initialized as <code>([], [])</code>. When processing starts, if the element is > 60, it is added to the first list of the tuple; else it is added to the second list of the tuple.</p>
<p>The syntax <code>a+[c]</code> is really the <code>extend</code> syntax of a list. We cannot do <code>a+c</code> since <code>a</code> is a list and <code>c</code> is an integer. Likewise, for <code>b+[c]</code></p>
| 0 |
2016-09-13T10:16:03Z
|
[
"python",
"lambda",
"reduce"
] |
Numpy collapse columns according to list
| 39,433,389 |
<p>In numpy, I have a d x n array A and a list L of length n describing where I want each column of A to end up in matrix B. The idea is that column i of matrix B is the sum of all columns of A for which the corresponding value in L is i. I can do this with a loop:</p>
<pre><code>A = np.arange(15).reshape(3,5)
L = [0,1,2,1,1]
n_cols = 3
B = np.zeros((len(A), n_cols))
# assume I know the desired number of columns,
# which is also one more than the maximum value of L
for i, a in enumerate(A.T):
B[:, L[i]] += a
</code></pre>
<p>Is there a way to do this by slicing array A (or in some otherwise vectorized manner)?</p>
| 3 |
2016-09-11T06:15:28Z
| 39,434,463 |
<p>Is this iteration on ``B` the same (not tested)?</p>
<pre><code> for I in range(B.shape[1]):
B[:, I] = A[:, L==I].sum(axis=1)
</code></pre>
<p>The number loops will be fewer. But more importantly it may give other vectorization insights.</p>
<p>(edit) on testing, this works, but is much slower.</p>
<p>+========</p>
<p><code>scipy.sparse</code> does column sum with matrix product with a matrix of ones. Can we do the same here? Make <code>C</code> array with 1s in the right columns</p>
<pre><code>def my2(A,L):
n_cols = L.shape[0]
C = np.zeros((n_cols,n_cols),int)
C[np.arange(n_cols), L] = 1
return A.dot(C)
</code></pre>
<p>This is 7x faster than your loop, and slightly faster than <code>@Divakars</code> <code>reduceat</code> code.</p>
<p>==========</p>
<pre><code>In [126]: timeit vectorized_app(A,L)
The slowest run took 8.16 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 99.7 µs per loop
In [127]: timeit val2 = my2(A,L)
The slowest run took 10.46 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 81.6 µs per loop
In [128]: timeit org1(A,n_cols)
1000 loops, best of 3: 623 µs per loop
In [129]: d,n_cols
Out[129]: (10, 100)
</code></pre>
| 1 |
2016-09-11T08:59:19Z
|
[
"python",
"numpy",
"vectorization",
"numpy-broadcasting"
] |
Numpy collapse columns according to list
| 39,433,389 |
<p>In numpy, I have a d x n array A and a list L of length n describing where I want each column of A to end up in matrix B. The idea is that column i of matrix B is the sum of all columns of A for which the corresponding value in L is i. I can do this with a loop:</p>
<pre><code>A = np.arange(15).reshape(3,5)
L = [0,1,2,1,1]
n_cols = 3
B = np.zeros((len(A), n_cols))
# assume I know the desired number of columns,
# which is also one more than the maximum value of L
for i, a in enumerate(A.T):
B[:, L[i]] += a
</code></pre>
<p>Is there a way to do this by slicing array A (or in some otherwise vectorized manner)?</p>
| 3 |
2016-09-11T06:15:28Z
| 39,434,530 |
<p>You are sum-reducing/collapsing the columns off <code>A</code> using <code>L</code> for selecting those columns. Also, you are updating the columns of output array based on the uniqueness of <code>L</code> elems. </p>
<p>Thus, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow"><code>np.add.reduceat</code></a> for a vectorized solution, like so -</p>
<pre><code>sidx = L.argsort()
col_idx, grp_start_idx = np.unique(L[sidx],return_index=True)
B_out = np.zeros((len(A), n_cols))
B_out[:,col_idx] = np.add.reduceat(A[:,sidx],grp_start_idx,axis=1)
</code></pre>
<hr>
<p>Runtime test -</p>
<pre><code>In [129]: def org_app(A,n_cols):
...: B = np.zeros((len(A), n_cols))
...: for i, a in enumerate(A.T):
...: B[:, L[i]] += a
...: return B
...:
...: def vectorized_app(A,n_cols):
...: sidx = L.argsort()
...: col_idx, grp_start_idx = np.unique(L[sidx],return_index=True)
...: B_out = np.zeros((len(A), n_cols))
...: B_out[:,col_idx] = np.add.reduceat(A[:,sidx],grp_start_idx,axis=1)
...: return B_out
...:
In [130]: # Setup inputs with an appreciable no. of cols & lesser rows
...: # so as that memory bandwidth to work with huge number of
...: # row elems doesn't become the bottleneck
...: d,n_cols = 10,5000
...: A = np.random.rand(d,n_cols)
...: L = np.random.randint(0,n_cols,(n_cols,))
...:
In [131]: np.allclose(org_app(A,n_cols),vectorized_app(A,n_cols))
Out[131]: True
In [132]: %timeit org_app(A,n_cols)
10 loops, best of 3: 33.3 ms per loop
In [133]: %timeit vectorized_app(A,n_cols)
100 loops, best of 3: 1.87 ms per loop
</code></pre>
<p>As the number of rows become comparable with the number of cols in <code>A</code>, the high memory bandwidth requirements for the vectorized approach would offset any noticeable speedup from it.</p>
| 3 |
2016-09-11T09:08:47Z
|
[
"python",
"numpy",
"vectorization",
"numpy-broadcasting"
] |
How do I configure Visual Studio Code with Python extension to not complain about inability to import modules?
| 39,433,401 |
<p>I am new to VS Code and I installed e.g. PySide for my tutorial project written in Python. I try to:</p>
<pre><code>from PySide.QtGui import QDialog, QApplication, QVBoxLayout, QLineEdit, QTextBrowser
from PySide.QtCore import *
</code></pre>
<p>Although the code runs perfectly well using the imported modules, VS Code complains with:</p>
<pre><code>[pylint] E0401:Unable to import 'PySide.QtGui'
</code></pre>
<p>or</p>
<pre><code>[pylint] E0401:Unable to import 'PySide.QtCore'
</code></pre>
<p>This is very irritating, since I am able to use the modules as expected. I would guess an configuration issue, but do not know how to fix this. </p>
<p>Thank you very much.</p>
<p>See also:</p>
<p><a href="http://i.stack.imgur.com/Iy25I.png" rel="nofollow">Visual representation of VS Code complaining</a></p>
<p>EDIT: </p>
<p>I use a precompiled version of PySide. Could this be the reason for this behaviour?</p>
| 0 |
2016-09-11T06:18:28Z
| 39,461,767 |
<p>@Andreas Schwab,
You need to ensure pylint is installed in the python environment in which you have installed the PySide package.
You will also need to ensure this same environment (python interpreter) is referenced in settings.json in the python.pythonPath setting.</p>
<p>You can find more details on these two here: </p>
<ul>
<li><a href="https://github.com/DonJayamanne/pythonVSCode/wiki/Python-Path-and-Version#selecting-an-interpreter" rel="nofollow">Selecting an interpreter</a> </li>
<li><a href="https://github.com/DonJayamanne/pythonVSCode/wiki/Troubleshooting-Linting#1-unable-to-import--pylint" rel="nofollow">unable to import xxx</a> </li>
</ul>
| 0 |
2016-09-13T03:25:53Z
|
[
"python",
"qt",
"pyside",
"vscode"
] |
Smartsheet SDK exception handling
| 39,433,457 |
<p>I am trying to write try except block for smartsheet aPI using python sdk, specially in cases where the API response to call returns error object rather than a usual index result object. Could someone explain what kind of exception would I be catching. I am not sure if I would have to create custom exceptions of my own or whether there are some way to capture exceptions. The API document talks about the error messages, not handling the. Would be great if someone could share some simple examples around the same.</p>
| 0 |
2016-09-11T06:29:44Z
| 39,480,478 |
<p>Knowing what a successful response will look like you could try checking for the error response. For example, running a get_row with an invalid rowId will result in this error:</p>
<p><code>
{"requestResponse": null, "result": {"code": 1006, "name": "NotFoundError", "recommendation": "Do not retry without fixing the problem. Hint: Verify that specified URI is correct. If the URI contains an object ID, verify that the object ID is correct and that the requester has access to the corresponding object in Smartsheet.", "shouldRetry": false, "message": "Not Found", "statusCode": 404}}
</code></p>
<p>Seeing requestResponse being null you can check the result object to know what the code is to look up in the Smartsheet API docs. Also, there is a recommendation parameter that gives next steps.</p>
| 0 |
2016-09-13T23:37:33Z
|
[
"python",
"python-2.7",
"exception-handling",
"smartsheet-api",
"smartsheet-api-1.1"
] |
Python return False if list is empty
| 39,433,505 |
<p>In one coding example i saw the following code snippet that returns <strong>True</strong> if the list is empty and <strong>False</strong> if not</p>
<pre><code>return a == []
</code></pre>
<p>the reason for that is to avoid writing</p>
<pre><code>if a:
return False
else:
return True
</code></pre>
<p>In a real example with multiple thousands of entries, is there any speed difference i should be aware of?</p>
| 3 |
2016-09-11T06:39:03Z
| 39,433,777 |
<p>No. There is no speed difference in either case. Since in both cases the <code>length</code> of the list is checked first.
In the first case, the <code>len</code> of <code>a</code> is compared with the <code>len</code> of <code>[]</code> before any further comparison. Most times the <code>len</code> should differ, so the test just returns immediately.</p>
<p>But the more pythonic way would be to just <code>return not a</code> or convert it using <code>bool</code> and then return it:</p>
<pre><code>return not a
# or
return not bool(a)
</code></pre>
| 2 |
2016-09-11T07:20:31Z
|
[
"python"
] |
Python return False if list is empty
| 39,433,505 |
<p>In one coding example i saw the following code snippet that returns <strong>True</strong> if the list is empty and <strong>False</strong> if not</p>
<pre><code>return a == []
</code></pre>
<p>the reason for that is to avoid writing</p>
<pre><code>if a:
return False
else:
return True
</code></pre>
<p>In a real example with multiple thousands of entries, is there any speed difference i should be aware of?</p>
| 3 |
2016-09-11T06:39:03Z
| 39,433,990 |
<p>If you're asking which method would faster if put in a function(hence the <code>return</code>'s), then I used the <code>timeit</code> module to do a little testing. I put each method in a function, and then ran the program to see which function ran faster. Here is the program:</p>
<pre><code>import timeit
def is_empty2():
a = []
if a:
return True
else:
return False
def is_empty1():
a = []
return a == []
print("Time for method 2:")
print(timeit.timeit(is_empty2))
print("")
print("Time for method 1:")
print(timeit.timeit(is_empty1))
</code></pre>
<p>I ran the program five times, each time recording the speed for each function. After getting an average for each time, here is what I came up with:</p>
<pre><code>method one speed(milliseconds): 0.2571859563796641
----------------------------- ------------------
method two speed(milliseconds): 0.2679253742685615
</code></pre>
<p>At least from my testing above, the first method you described in your question was <em>slightly</em> faster than the second method. Of course those numbers above could drastically change depending on what exactly is inside those two functions.</p>
<p>I agree however, with what Cdarke said in the comments. Go with the one that is the most clear and concise. Don't go with one option solely based upon its speed. in the words of Guido van Rosom: <em>Readability counts</em>. </p>
| 2 |
2016-09-11T07:54:51Z
|
[
"python"
] |
i want to write a function in python named cont() which sends a message "continue" and which should take no argument
| 39,433,532 |
<p>i want to write a function in python named cont() which sends a message "continue" and which should take no argument.the function should print the message yes,y or Y.then return true otherwise false. i have done it but there is an error.</p>
<pre><code>def cont():
x = input("enter any word of your choice")
for letter in 'x':
if letter == '[0]':
a = input ("continue")
if a == 'yes' == 'y' == 'Y' :
continue
print 'current letter will be:',letter
else:
print x
if __name__=="__main__":
cont()
</code></pre>
| -5 |
2016-09-11T06:42:12Z
| 39,433,744 |
<p>Sadly the code that you supplied and the description that you wrote, do not agree with each other. There is no attempt to <code>return</code> any value, indeed, there is nothing to suggest what the decision of <code>True</code> or <code>False</code> would be based upon.<br>
Assuming that you are using python 2.7, this should get you started:</p>
<pre><code>def cont():
x = raw_input("Enter any word of your choice: ")
for letter in x:
# if letter == '[0]':
a = raw_input ("Continue? ")
if a == 'yes' or a == 'y' or a == 'Y' :
# continue
print 'Current letter will be:',letter
else:
print x
break
if __name__ == '__main__':
cont()
</code></pre>
<p>I have no idea what you were attempting to do with the <code>if letter == '[0]':</code> or the <code>continue</code> lines, so I have commented them out.
If you wish to return a value, simply <code>return True</code> or <code>return False</code> at the point of your choosing in the code. The other option is to set a variable to <code>True</code> or <code>False</code> and then, as the last statement of <code>cont()</code> use the <code>return</code> keyword with the variable.</p>
<p>Note: if you are using python3 the <code>raw_input</code> becomes <code>input</code> and the <code>print</code> commands become <code>print()</code></p>
| 0 |
2016-09-11T07:15:42Z
|
[
"python",
"python-2.7",
"python-3.x"
] |
How do you restrict the scaling of the sine wave upto certain value
| 39,433,557 |
<p>I am using the below codes so as to scale up the amplitude of the sine wave after the limit value 20.Here I am not able to restrict the amplitude of the sine wave.Please refer the figure below.I need the output as mentioned in figure in single plot window[not via subplot]. I need only amplitude scaling not the frequency scaling.Could any one help me in this.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
Limit=20
x=np.linspace(-20,20,400)
y=np.sin(x)
plt.plot(x,y)
y[(y<=Limit)] = y*0.5
plt.plot(x,y)
plt.grid()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/ODimr.png" rel="nofollow"><img src="http://i.stack.imgur.com/ODimr.png" alt="enter image description here"></a></p>
| -1 |
2016-09-11T06:46:07Z
| 39,436,918 |
<p>It can be done relatively straightforward as follows:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
Limit=20
x=np.linspace(-20,20,4000)
y=np.sin(x)
plt.plot(x[x<0],y[x<0], lw=2, color='k')
y[(y<=Limit)] = y*0.5
plt.plot(x[x>0],y[x>0], lw=2, color='k')
plt.grid()
plt.show()
</code></pre>
<p>which produces:</p>
<p><a href="http://i.stack.imgur.com/Sth8e.png" rel="nofollow"><img src="http://i.stack.imgur.com/Sth8e.png" alt="Output from the example code"></a></p>
| 0 |
2016-09-11T14:07:10Z
|
[
"python",
"numpy",
"matplotlib"
] |
How do you restrict the scaling of the sine wave upto certain value
| 39,433,557 |
<p>I am using the below codes so as to scale up the amplitude of the sine wave after the limit value 20.Here I am not able to restrict the amplitude of the sine wave.Please refer the figure below.I need the output as mentioned in figure in single plot window[not via subplot]. I need only amplitude scaling not the frequency scaling.Could any one help me in this.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
Limit=20
x=np.linspace(-20,20,400)
y=np.sin(x)
plt.plot(x,y)
y[(y<=Limit)] = y*0.5
plt.plot(x,y)
plt.grid()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/ODimr.png" rel="nofollow"><img src="http://i.stack.imgur.com/ODimr.png" alt="enter image description here"></a></p>
| -1 |
2016-09-11T06:46:07Z
| 39,438,845 |
<p>Are you looking for this:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x_limit = 20
x = np.linspace(0,40,400)
y = np.sin(x)
y[x <= x_limit] *= 0.5
plt.plot(x,y)
plt.grid()
plt.show()
</code></pre>
<p>I think you wanted to apply the limit to the x, not the y.</p>
<p><a href="http://i.stack.imgur.com/2N158.png" rel="nofollow"><img src="http://i.stack.imgur.com/2N158.png" alt="enter image description here"></a></p>
| 1 |
2016-09-11T17:36:29Z
|
[
"python",
"numpy",
"matplotlib"
] |
How to switch to frame source in selenium
| 39,433,681 |
<p>I want to click an frame source's radio button, but it doesn't work. I think, frame source doesn't have iframe id or name.
my code is this.</p>
<pre><code>import time
from selenium import webdriver
Url='https://www.youtube.com/watch?v=eIStvhR347g'
driver = webdriver.Firefox()
driver.get('https://video-download.online')
driver.find_element_by_id("link").send_keys(Url)
driver.find_element_by_id("submit").click()
time.sleep(5)
#this part is problems... don't working
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
driver.find_element_by_xpath(".//button[contains(text(),'Proceed')]").click()
</code></pre>
<p>html source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
...
<script>
if (top.location !== location) {
top.location = self.location;
}
if (location.host !== 'video-download.online' && location.host !== 'beta.video-download.online') {
eval("location.href=''+'//'+'video-download.online';");
}
</script>
<meta name="msapplication-tap-highlight" content="no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta name="author" content="Luca Steeb"/>
<meta name="theme-color" content="#008679"/>
<meta name="description" content="Download from this uploaded.net premium link generator with highspeed. For free."/>
<meta property="og:title" content="Video-Download.online"/>
<meta property="og:description" content="Download videos, mp3s and playlists from 1979 sites - for free."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="video-download.online"/>
<meta property="fb:page_id" content="1143492155680932"/>
<meta property="og:image" content="//video-download.online/img/logo.jpg"/>
<link rel="shortcut icon" href="/favicon.ico?1"/>
<link rel="icon" sizes="192x192" href="/img/logo_small.jpg"/>
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
<link rel="search" type="application/opensearchdescription+xml" title="Video-Download.online" href="/opensearch.xml"/>
<title>
Online Video Download
</title>
<meta name="robots" content="noindex, nofollow"/>
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<noscript><iframe height=0 src="//www.googletagmanager.com/ns.html?id=GTM-TWMNRP"style=display:none;visibility:hidden width=0></iframe></noscript><script>!function(e,t,a,n,r){e[n]=e[n]||[],e[n].push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var g=t.getElementsByTagName(a)[0],m=t.createElement(a),s="dataLayer"!=n?"&l="+n:"";m.async=!0,m.src="//www.googletagmanager.com/gtm.js?id="+r+s,g.parentNode.insertBefore(m,g)}(window,document,"script","dataLayer","GTM-TWMNRP")</script>
<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');ga('create','UA-54289597-5','auto');ga('send','pageview');</script>
<script>function send(action) { ga('send', 'event', 'button', 'click', 'download-' + action) }</script>
<script async src="/js/jquery.js"></script>
<script>function _(n,i){i?window[n]?i():setTimeout(function(){_(n,i)},100):window.jQuery?window.jQuery(document).ready(function(){n(window.jQuery)}):setTimeout(function(){_(n)},100)}</script>
</head>
<body>
<header class="navbar navbar-info navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle no-waves" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="nav-brand">
<a class="navbar-brand" href="/">
<img class="logo" src="/img/logo.svg" alt=""/>
<div class="parent">
Video-Download<small>.online</small>
<br/>
<span class="small-text">1979 sites officially supported</span>
<span id="changelog"></span>
</div>
<span class="clear"></span>
</a>
</div>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<div class="social">
<div class="fb-like fb-nav" data-href="https://www.facebook.com/VideoDownload.online"
data-layout="button_count" data-action="like" data-show-faces="false" data-share="true">
</div>
</div>
<div class="social-close" title="Hide all social buttons">&times;</div>
<li class=" ">
<a href="/">
Home
</a>
</li>
<li class=" ">
<a href="/sites">
Sites
</a>
</li>
<li class=" ">
<a href="/contact">
Contact
</a>
</li>
<!--html.navItem('/app', 'Mobile App')-->
</ul>
</div>
</div>
</header>
<noscript class="fixed">
<div class="container">Please enable javascript. Video Download and almost all other sites don't work properly
without it.
</div>
</noscript>
<div id="alert" class="alert alert-fixed alert-dismissible m-t-15 hidden">
<div class="container relative">
<span id="alertText"></span>
<span class="close-alert" onclick="_(function() { $('#alert').remove();$('body').removeClass('alert-showing') })" title="close">Ã</span>
</div>
</div>
<main class="container">
<div>
<h1>Legal</h1>
<div style="width: 50%;" class="center">
</div>
</main>
<script src="/sweetalert/sweetalert.js"></script>
<link rel="stylesheet" href="/sweetalert/sweetalert.css">
<script src="/waves/waves.min.js"></script>
<script src="/js/dropdown.js"></script>
<script src="/js/main.js"></script>
<script src="/js/bootstrap.js"></script>
<script type="text/javascript">/* <![CDATA[ */(function(d,s,a,i,j,r,l,m,t){try{l=d.getElementsByTagName('a');t=d.createElement('textarea');for(i=0;l.length-i;i++){try{a=l[i].href;s=a.indexOf('/cdn-cgi/l/email-protection');m=a.length;if(a&&s>-1&&m>28){j=28+s;s='';if(j<m){r='0x'+a.substr(j,2)|0;for(j+=2;j<m&&a.charAt(j)!='X';j+=2)s+='%'+('0'+('0x'+a.substr(j,2)^r).toString(16)).slice(-2);j++;s=decodeURIComponent(s)+a.substr(j,m-j)}t.innerHTML=s.replace(/</g,'&lt;').replace(/>/g,'&gt;');l[i].href='mailto:'+t.value}}catch(e){}}}catch(e){}})(document);/* ]]> */</script></body>
</html>
</code></pre>
<p>frame source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
<meta name="robots" content="noindex, nofollow"/>
...
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/jquery.js"></script>
<style>body{margin:0!important;}tr{clear:both;cursor:pointer;}td{padding:0 20px 0 0;white-space:nowrap;}.radio{margin-top:5px;margin-bottom:5px;}.small{padding:0;font-size:85%;}@media (max-width: 319px) {table{font-size:12px;}}@media (max-width: 480px) {td{padding:0 5px 0 0;}.small{font-size:50%;}}</style>
</head>
<body>
<form id="format" method="post">
<input name="id" type="hidden" value="isxklqy5blw9of7"/>
<table>
<tr>
<td class="small">
<div class="">
<div class="radio " id="undefined-wrapper">
<label class="text-capitalize" for="undefined">
<input id="undefined" name="format" type="radio" value="undefined" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>I don't care</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="small">
<div class="">
<div class="radio " id="160-wrapper">
<label class="text-capitalize" for="160">
<input id="160" name="format" type="radio" value="160" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>256x144</td>
<td></td>
<td>
30 FPS
</td>
<td>23.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="133-wrapper">
<label class="text-capitalize" for="133">
<input id="133" name="format" type="radio" value="133" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>426x240</td>
<td></td>
<td>
30 FPS
</td>
<td>51.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="134-wrapper">
<label class="text-capitalize" for="134">
<input id="134" name="format" type="radio" value="134" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>640x360</td>
<td></td>
<td>
30 FPS
</td>
<td>65.4 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="135-wrapper">
<label class="text-capitalize" for="135">
<input id="135" name="format" type="radio" value="135" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>854x480</td>
<td></td>
<td>
30 FPS
</td>
<td>138.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="136-wrapper">
<label class="text-capitalize" for="136">
<input id="136" name="format" type="radio" value="136" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
30 FPS
</td>
<td>272.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="298-wrapper">
<label class="text-capitalize" for="298">
<input id="298" name="format" type="radio" value="298" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
60 FPS
</td>
<td>385.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="137-wrapper">
<label class="text-capitalize" for="137">
<input id="137" name="format" type="radio" value="137" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
30 FPS
</td>
<td>535.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="299-wrapper">
<label class="text-capitalize" for="299">
<input id="299" name="format" type="radio" value="299" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
60 FPS
</td>
<td>707.0 MB</td>
</tr>
</table>
<button class="btn center" type="submit">Proceed &raquo;</button>
</form>
</body>
<script>
$('tr').click(function() {
$(this).find('input').prop('checked', true);
});
</script>
<script src="/waves/waves.min.js"></script>
<script>
Waves.attach('.btn', ['waves-light']);
Waves.init();
</script>
</code></pre>
<p>html and frame sources are very long code, you can be check this full code.</p>
<p><a href="http://file1.upload.pe/download.php?name=html.txt&path=/20160911/10115.dat" rel="nofollow">html link</a></p>
<p><a href="http://file1.upload.pe/download.php?name=frame.txt&path=/20160911/10116.dat" rel="nofollow">frame link</a></p>
<p>and I tried these codes, but don't work.</p>
<pre><code>driver.switch_to_frame(driver.find_element_by_xpath('//iframe[contains(@name, "frame")]'))
driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.switch_to_frame(0)
</code></pre>
<p>these iframe switching codes are any exception is nothing, but result is '[]'.</p>
<pre><code>>>> driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
>>> driver.find_elements_by_xpath("//*[@type='radio']")
[]
>>> driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
<p>I needs your help. thanks you.</p>
| 1 |
2016-09-11T07:05:58Z
| 39,433,839 |
<p>The <code>iframe</code> is inside <code><noscript></code> tag, witch means the <code>driver</code> will see it only when <code>javascript</code> is disabled, as human user would. You can try to disable <code>javascript</code> when creating the driver</p>
<pre><code>fp = webdriver.FirefoxProfile()
fp.set_preference("javascript.enabled", False)
driver = webdriver.Firefox(firefox_profile=fp)
</code></pre>
| 0 |
2016-09-11T07:30:02Z
|
[
"python",
"html",
"forms",
"selenium",
"iframe"
] |
How to switch to frame source in selenium
| 39,433,681 |
<p>I want to click an frame source's radio button, but it doesn't work. I think, frame source doesn't have iframe id or name.
my code is this.</p>
<pre><code>import time
from selenium import webdriver
Url='https://www.youtube.com/watch?v=eIStvhR347g'
driver = webdriver.Firefox()
driver.get('https://video-download.online')
driver.find_element_by_id("link").send_keys(Url)
driver.find_element_by_id("submit").click()
time.sleep(5)
#this part is problems... don't working
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
driver.find_element_by_xpath(".//button[contains(text(),'Proceed')]").click()
</code></pre>
<p>html source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
...
<script>
if (top.location !== location) {
top.location = self.location;
}
if (location.host !== 'video-download.online' && location.host !== 'beta.video-download.online') {
eval("location.href=''+'//'+'video-download.online';");
}
</script>
<meta name="msapplication-tap-highlight" content="no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta name="author" content="Luca Steeb"/>
<meta name="theme-color" content="#008679"/>
<meta name="description" content="Download from this uploaded.net premium link generator with highspeed. For free."/>
<meta property="og:title" content="Video-Download.online"/>
<meta property="og:description" content="Download videos, mp3s and playlists from 1979 sites - for free."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="video-download.online"/>
<meta property="fb:page_id" content="1143492155680932"/>
<meta property="og:image" content="//video-download.online/img/logo.jpg"/>
<link rel="shortcut icon" href="/favicon.ico?1"/>
<link rel="icon" sizes="192x192" href="/img/logo_small.jpg"/>
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
<link rel="search" type="application/opensearchdescription+xml" title="Video-Download.online" href="/opensearch.xml"/>
<title>
Online Video Download
</title>
<meta name="robots" content="noindex, nofollow"/>
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<noscript><iframe height=0 src="//www.googletagmanager.com/ns.html?id=GTM-TWMNRP"style=display:none;visibility:hidden width=0></iframe></noscript><script>!function(e,t,a,n,r){e[n]=e[n]||[],e[n].push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var g=t.getElementsByTagName(a)[0],m=t.createElement(a),s="dataLayer"!=n?"&l="+n:"";m.async=!0,m.src="//www.googletagmanager.com/gtm.js?id="+r+s,g.parentNode.insertBefore(m,g)}(window,document,"script","dataLayer","GTM-TWMNRP")</script>
<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');ga('create','UA-54289597-5','auto');ga('send','pageview');</script>
<script>function send(action) { ga('send', 'event', 'button', 'click', 'download-' + action) }</script>
<script async src="/js/jquery.js"></script>
<script>function _(n,i){i?window[n]?i():setTimeout(function(){_(n,i)},100):window.jQuery?window.jQuery(document).ready(function(){n(window.jQuery)}):setTimeout(function(){_(n)},100)}</script>
</head>
<body>
<header class="navbar navbar-info navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle no-waves" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="nav-brand">
<a class="navbar-brand" href="/">
<img class="logo" src="/img/logo.svg" alt=""/>
<div class="parent">
Video-Download<small>.online</small>
<br/>
<span class="small-text">1979 sites officially supported</span>
<span id="changelog"></span>
</div>
<span class="clear"></span>
</a>
</div>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<div class="social">
<div class="fb-like fb-nav" data-href="https://www.facebook.com/VideoDownload.online"
data-layout="button_count" data-action="like" data-show-faces="false" data-share="true">
</div>
</div>
<div class="social-close" title="Hide all social buttons">&times;</div>
<li class=" ">
<a href="/">
Home
</a>
</li>
<li class=" ">
<a href="/sites">
Sites
</a>
</li>
<li class=" ">
<a href="/contact">
Contact
</a>
</li>
<!--html.navItem('/app', 'Mobile App')-->
</ul>
</div>
</div>
</header>
<noscript class="fixed">
<div class="container">Please enable javascript. Video Download and almost all other sites don't work properly
without it.
</div>
</noscript>
<div id="alert" class="alert alert-fixed alert-dismissible m-t-15 hidden">
<div class="container relative">
<span id="alertText"></span>
<span class="close-alert" onclick="_(function() { $('#alert').remove();$('body').removeClass('alert-showing') })" title="close">Ã</span>
</div>
</div>
<main class="container">
<div>
<h1>Legal</h1>
<div style="width: 50%;" class="center">
</div>
</main>
<script src="/sweetalert/sweetalert.js"></script>
<link rel="stylesheet" href="/sweetalert/sweetalert.css">
<script src="/waves/waves.min.js"></script>
<script src="/js/dropdown.js"></script>
<script src="/js/main.js"></script>
<script src="/js/bootstrap.js"></script>
<script type="text/javascript">/* <![CDATA[ */(function(d,s,a,i,j,r,l,m,t){try{l=d.getElementsByTagName('a');t=d.createElement('textarea');for(i=0;l.length-i;i++){try{a=l[i].href;s=a.indexOf('/cdn-cgi/l/email-protection');m=a.length;if(a&&s>-1&&m>28){j=28+s;s='';if(j<m){r='0x'+a.substr(j,2)|0;for(j+=2;j<m&&a.charAt(j)!='X';j+=2)s+='%'+('0'+('0x'+a.substr(j,2)^r).toString(16)).slice(-2);j++;s=decodeURIComponent(s)+a.substr(j,m-j)}t.innerHTML=s.replace(/</g,'&lt;').replace(/>/g,'&gt;');l[i].href='mailto:'+t.value}}catch(e){}}}catch(e){}})(document);/* ]]> */</script></body>
</html>
</code></pre>
<p>frame source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
<meta name="robots" content="noindex, nofollow"/>
...
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/jquery.js"></script>
<style>body{margin:0!important;}tr{clear:both;cursor:pointer;}td{padding:0 20px 0 0;white-space:nowrap;}.radio{margin-top:5px;margin-bottom:5px;}.small{padding:0;font-size:85%;}@media (max-width: 319px) {table{font-size:12px;}}@media (max-width: 480px) {td{padding:0 5px 0 0;}.small{font-size:50%;}}</style>
</head>
<body>
<form id="format" method="post">
<input name="id" type="hidden" value="isxklqy5blw9of7"/>
<table>
<tr>
<td class="small">
<div class="">
<div class="radio " id="undefined-wrapper">
<label class="text-capitalize" for="undefined">
<input id="undefined" name="format" type="radio" value="undefined" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>I don't care</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="small">
<div class="">
<div class="radio " id="160-wrapper">
<label class="text-capitalize" for="160">
<input id="160" name="format" type="radio" value="160" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>256x144</td>
<td></td>
<td>
30 FPS
</td>
<td>23.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="133-wrapper">
<label class="text-capitalize" for="133">
<input id="133" name="format" type="radio" value="133" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>426x240</td>
<td></td>
<td>
30 FPS
</td>
<td>51.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="134-wrapper">
<label class="text-capitalize" for="134">
<input id="134" name="format" type="radio" value="134" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>640x360</td>
<td></td>
<td>
30 FPS
</td>
<td>65.4 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="135-wrapper">
<label class="text-capitalize" for="135">
<input id="135" name="format" type="radio" value="135" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>854x480</td>
<td></td>
<td>
30 FPS
</td>
<td>138.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="136-wrapper">
<label class="text-capitalize" for="136">
<input id="136" name="format" type="radio" value="136" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
30 FPS
</td>
<td>272.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="298-wrapper">
<label class="text-capitalize" for="298">
<input id="298" name="format" type="radio" value="298" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
60 FPS
</td>
<td>385.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="137-wrapper">
<label class="text-capitalize" for="137">
<input id="137" name="format" type="radio" value="137" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
30 FPS
</td>
<td>535.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="299-wrapper">
<label class="text-capitalize" for="299">
<input id="299" name="format" type="radio" value="299" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
60 FPS
</td>
<td>707.0 MB</td>
</tr>
</table>
<button class="btn center" type="submit">Proceed &raquo;</button>
</form>
</body>
<script>
$('tr').click(function() {
$(this).find('input').prop('checked', true);
});
</script>
<script src="/waves/waves.min.js"></script>
<script>
Waves.attach('.btn', ['waves-light']);
Waves.init();
</script>
</code></pre>
<p>html and frame sources are very long code, you can be check this full code.</p>
<p><a href="http://file1.upload.pe/download.php?name=html.txt&path=/20160911/10115.dat" rel="nofollow">html link</a></p>
<p><a href="http://file1.upload.pe/download.php?name=frame.txt&path=/20160911/10116.dat" rel="nofollow">frame link</a></p>
<p>and I tried these codes, but don't work.</p>
<pre><code>driver.switch_to_frame(driver.find_element_by_xpath('//iframe[contains(@name, "frame")]'))
driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.switch_to_frame(0)
</code></pre>
<p>these iframe switching codes are any exception is nothing, but result is '[]'.</p>
<pre><code>>>> driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
>>> driver.find_elements_by_xpath("//*[@type='radio']")
[]
>>> driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
<p>I needs your help. thanks you.</p>
| 1 |
2016-09-11T07:05:58Z
| 39,437,692 |
<p>As I'm seeing <a href="https://video-download.online" rel="nofollow">on this url</a>, there are multiple <code>iframe</code> present while, you are trying to switch to <code>iframe</code> with it's <code>tagName</code> only which will switch to first find <code>iframe</code> in order while your desired <code>iframe</code> is at <code>4th</code> index which has no <code>id</code> and <code>name</code> attribute present, so you should try using <code>CSS_SELECTOR</code> with <a href="http://selenium-python.readthedocs.io/waits.html" rel="nofollow"><code>WebDriverWait</code></a> using <code>EC.frame_to_be_available_and_switch_to_it</code> which will try to wait until desired <code>iframe</code> to be available and then switch to it as below working code :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe:not([id]):not([name])")))
#now do your stuff to find element inside this iframe
#after doing all stuff inside this iframe switch back to default content for further steps
driver.switch_to_default_content()
</code></pre>
<p><strong>Note</strong>:- You can also consider below one of these options to switch your <code>desired</code> <code>iframe</code> :-</p>
<pre><code>wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, ".//iframe[not(@name) and not(@id)]")))
</code></pre>
<p>or</p>
<pre><code> wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src*='selectFormat']")))
</code></pre>
<p>or using <code>index</code> :-</p>
<pre><code>wait.until(EC.frame_to_be_available_and_switch_to_it(3))
</code></pre>
| 0 |
2016-09-11T15:28:49Z
|
[
"python",
"html",
"forms",
"selenium",
"iframe"
] |
How to switch to frame source in selenium
| 39,433,681 |
<p>I want to click an frame source's radio button, but it doesn't work. I think, frame source doesn't have iframe id or name.
my code is this.</p>
<pre><code>import time
from selenium import webdriver
Url='https://www.youtube.com/watch?v=eIStvhR347g'
driver = webdriver.Firefox()
driver.get('https://video-download.online')
driver.find_element_by_id("link").send_keys(Url)
driver.find_element_by_id("submit").click()
time.sleep(5)
#this part is problems... don't working
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
driver.find_element_by_xpath(".//button[contains(text(),'Proceed')]").click()
</code></pre>
<p>html source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
...
<script>
if (top.location !== location) {
top.location = self.location;
}
if (location.host !== 'video-download.online' && location.host !== 'beta.video-download.online') {
eval("location.href=''+'//'+'video-download.online';");
}
</script>
<meta name="msapplication-tap-highlight" content="no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta name="author" content="Luca Steeb"/>
<meta name="theme-color" content="#008679"/>
<meta name="description" content="Download from this uploaded.net premium link generator with highspeed. For free."/>
<meta property="og:title" content="Video-Download.online"/>
<meta property="og:description" content="Download videos, mp3s and playlists from 1979 sites - for free."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="video-download.online"/>
<meta property="fb:page_id" content="1143492155680932"/>
<meta property="og:image" content="//video-download.online/img/logo.jpg"/>
<link rel="shortcut icon" href="/favicon.ico?1"/>
<link rel="icon" sizes="192x192" href="/img/logo_small.jpg"/>
<link rel="apple-touch-icon" href="/img/apple-touch-icon.png"/>
<link rel="search" type="application/opensearchdescription+xml" title="Video-Download.online" href="/opensearch.xml"/>
<title>
Online Video Download
</title>
<meta name="robots" content="noindex, nofollow"/>
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<noscript><iframe height=0 src="//www.googletagmanager.com/ns.html?id=GTM-TWMNRP"style=display:none;visibility:hidden width=0></iframe></noscript><script>!function(e,t,a,n,r){e[n]=e[n]||[],e[n].push({"gtm.start":(new Date).getTime(),event:"gtm.js"});var g=t.getElementsByTagName(a)[0],m=t.createElement(a),s="dataLayer"!=n?"&l="+n:"";m.async=!0,m.src="//www.googletagmanager.com/gtm.js?id="+r+s,g.parentNode.insertBefore(m,g)}(window,document,"script","dataLayer","GTM-TWMNRP")</script>
<script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');ga('create','UA-54289597-5','auto');ga('send','pageview');</script>
<script>function send(action) { ga('send', 'event', 'button', 'click', 'download-' + action) }</script>
<script async src="/js/jquery.js"></script>
<script>function _(n,i){i?window[n]?i():setTimeout(function(){_(n,i)},100):window.jQuery?window.jQuery(document).ready(function(){n(window.jQuery)}):setTimeout(function(){_(n)},100)}</script>
</head>
<body>
<header class="navbar navbar-info navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle no-waves" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="nav-brand">
<a class="navbar-brand" href="/">
<img class="logo" src="/img/logo.svg" alt=""/>
<div class="parent">
Video-Download<small>.online</small>
<br/>
<span class="small-text">1979 sites officially supported</span>
<span id="changelog"></span>
</div>
<span class="clear"></span>
</a>
</div>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<div class="social">
<div class="fb-like fb-nav" data-href="https://www.facebook.com/VideoDownload.online"
data-layout="button_count" data-action="like" data-show-faces="false" data-share="true">
</div>
</div>
<div class="social-close" title="Hide all social buttons">&times;</div>
<li class=" ">
<a href="/">
Home
</a>
</li>
<li class=" ">
<a href="/sites">
Sites
</a>
</li>
<li class=" ">
<a href="/contact">
Contact
</a>
</li>
<!--html.navItem('/app', 'Mobile App')-->
</ul>
</div>
</div>
</header>
<noscript class="fixed">
<div class="container">Please enable javascript. Video Download and almost all other sites don't work properly
without it.
</div>
</noscript>
<div id="alert" class="alert alert-fixed alert-dismissible m-t-15 hidden">
<div class="container relative">
<span id="alertText"></span>
<span class="close-alert" onclick="_(function() { $('#alert').remove();$('body').removeClass('alert-showing') })" title="close">Ã</span>
</div>
</div>
<main class="container">
<div>
<h1>Legal</h1>
<div style="width: 50%;" class="center">
</div>
</main>
<script src="/sweetalert/sweetalert.js"></script>
<link rel="stylesheet" href="/sweetalert/sweetalert.css">
<script src="/waves/waves.min.js"></script>
<script src="/js/dropdown.js"></script>
<script src="/js/main.js"></script>
<script src="/js/bootstrap.js"></script>
<script type="text/javascript">/* <![CDATA[ */(function(d,s,a,i,j,r,l,m,t){try{l=d.getElementsByTagName('a');t=d.createElement('textarea');for(i=0;l.length-i;i++){try{a=l[i].href;s=a.indexOf('/cdn-cgi/l/email-protection');m=a.length;if(a&&s>-1&&m>28){j=28+s;s='';if(j<m){r='0x'+a.substr(j,2)|0;for(j+=2;j<m&&a.charAt(j)!='X';j+=2)s+='%'+('0'+('0x'+a.substr(j,2)^r).toString(16)).slice(-2);j++;s=decodeURIComponent(s)+a.substr(j,m-j)}t.innerHTML=s.replace(/</g,'&lt;').replace(/>/g,'&gt;');l[i].href='mailto:'+t.value}}catch(e){}}}catch(e){}})(document);/* ]]> */</script></body>
</html>
</code></pre>
<p>frame source is this.</p>
<pre><code><html>
<head>
<meta charset="utf-8"/>
<meta name="robots" content="noindex, nofollow"/>
...
<link rel="stylesheet" href="/css/bt.css"/>
<link rel="stylesheet" href="/css/style.css"/>
<script src="/js/jquery.js"></script>
<style>body{margin:0!important;}tr{clear:both;cursor:pointer;}td{padding:0 20px 0 0;white-space:nowrap;}.radio{margin-top:5px;margin-bottom:5px;}.small{padding:0;font-size:85%;}@media (max-width: 319px) {table{font-size:12px;}}@media (max-width: 480px) {td{padding:0 5px 0 0;}.small{font-size:50%;}}</style>
</head>
<body>
<form id="format" method="post">
<input name="id" type="hidden" value="isxklqy5blw9of7"/>
<table>
<tr>
<td class="small">
<div class="">
<div class="radio " id="undefined-wrapper">
<label class="text-capitalize" for="undefined">
<input id="undefined" name="format" type="radio" value="undefined" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>I don't care</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td class="small">
<div class="">
<div class="radio " id="160-wrapper">
<label class="text-capitalize" for="160">
<input id="160" name="format" type="radio" value="160" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>256x144</td>
<td></td>
<td>
30 FPS
</td>
<td>23.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="133-wrapper">
<label class="text-capitalize" for="133">
<input id="133" name="format" type="radio" value="133" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>426x240</td>
<td></td>
<td>
30 FPS
</td>
<td>51.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="134-wrapper">
<label class="text-capitalize" for="134">
<input id="134" name="format" type="radio" value="134" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>640x360</td>
<td></td>
<td>
30 FPS
</td>
<td>65.4 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="135-wrapper">
<label class="text-capitalize" for="135">
<input id="135" name="format" type="radio" value="135" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>854x480</td>
<td></td>
<td>
30 FPS
</td>
<td>138.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="136-wrapper">
<label class="text-capitalize" for="136">
<input id="136" name="format" type="radio" value="136" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
30 FPS
</td>
<td>272.2 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="298-wrapper">
<label class="text-capitalize" for="298">
<input id="298" name="format" type="radio" value="298" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1280x720</td>
<td>HD</td>
<td>
60 FPS
</td>
<td>385.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="137-wrapper">
<label class="text-capitalize" for="137">
<input id="137" name="format" type="radio" value="137" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
30 FPS
</td>
<td>535.0 MB</td>
</tr><tr>
<td class="small">
<div class="">
<div class="radio " id="299-wrapper">
<label class="text-capitalize" for="299">
<input id="299" name="format" type="radio" value="299" onchange="" undefined required />
<span class=circle></span><span class=check></span>
<span class="grey-text"></span>
</label>
</div>
</div>
</td>
<td>1920x1080</td>
<td>Full HD</td>
<td>
60 FPS
</td>
<td>707.0 MB</td>
</tr>
</table>
<button class="btn center" type="submit">Proceed &raquo;</button>
</form>
</body>
<script>
$('tr').click(function() {
$(this).find('input').prop('checked', true);
});
</script>
<script src="/waves/waves.min.js"></script>
<script>
Waves.attach('.btn', ['waves-light']);
Waves.init();
</script>
</code></pre>
<p>html and frame sources are very long code, you can be check this full code.</p>
<p><a href="http://file1.upload.pe/download.php?name=html.txt&path=/20160911/10115.dat" rel="nofollow">html link</a></p>
<p><a href="http://file1.upload.pe/download.php?name=frame.txt&path=/20160911/10116.dat" rel="nofollow">frame link</a></p>
<p>and I tried these codes, but don't work.</p>
<pre><code>driver.switch_to_frame(driver.find_element_by_xpath('//iframe[contains(@name, "frame")]'))
driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
driver.switch_to_frame(0)
</code></pre>
<p>these iframe switching codes are any exception is nothing, but result is '[]'.</p>
<pre><code>>>> driver.switch_to_frame(driver.find_element_by_xpath('//iframe'))
>>> driver.find_elements_by_xpath("//*[@type='radio']")
[]
>>> driver.find_elements_by_xpath("//*[@type='radio']")[0].click()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
<p>I needs your help. thanks you.</p>
| 1 |
2016-09-11T07:05:58Z
| 39,629,725 |
<p>I have created a simple method for switching the frames :</p>
<pre><code>**public static void fn_SwitchToFrame(WebDriver driver, String frame){
if(frame.contains(">")){
String[] List = frame.split(">");
int ListSize = List.length;
for (int i=0; i<=(ListSize-1); i++){
driver.switchTo().frame(List[i]);
System.out.println("Switched to Frame :"+List[i]);
}
} else {
driver.switchTo().frame(frame);
System.out.println("Switched to Frame :"+frame);
}
}**
</code></pre>
<p>It works like this :
className.fn_SwitchToFrame(driver, "searchView>searchContent");</p>
<p>This will first switch to frame 'searchView' and then to 'searchContent'.</p>
<p>Hope this helps you.</p>
| 0 |
2016-09-22T03:22:52Z
|
[
"python",
"html",
"forms",
"selenium",
"iframe"
] |
Python dedicated class for file names
| 39,433,691 |
<p>I am writing a program that utilises a large number of files. Does Python feature an inbuilt class for file paths, or does one have to be implemented by the user (like below):</p>
<pre><code>class FilePath:
def __init__(path):
shazam(path)
def shazam(self, path):
""" something happens, path is formatted, etc """
self.formatted_path = foobar
</code></pre>
<p><strong>Why would it be useful?</strong></p>
<p>Suppose the program and its data is copied to a different operating system. The class could modify itself on launch to support the a different path separator.</p>
<p><strong>Why not just write it yourself?</strong></p>
<p>Someone might have already written a class in the standard Python library.</p>
| 2 |
2016-09-11T07:07:43Z
| 39,433,748 |
<p>Python has several cross platform modules for dealing with the file system, <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">paths</a> and <a href="https://docs.python.org/2/library/os.html" rel="nofollow">operating system</a>.</p>
<p>The <a href="https://docs.python.org/2/library/os.html" rel="nofollow"><code>os</code></a> module specifically has an <a href="https://docs.python.org/2/library/os.html#os.sep" rel="nofollow"><code>os.sep</code></a> character.</p>
<p><a href="https://docs.python.org/2/library/os.path.html#os.path.join" rel="nofollow"><code>os.path.join()</code></a> is OS-aware and will use the correct separator when joining paths together.</p>
<p>Additionally, <a href="https://docs.python.org/2/library/os.path.html#os.path.normpath" rel="nofollow"><code>os.path.normpath()</code></a> will take any path and convert the separators to whatever the native OS supports.</p>
| 2 |
2016-09-11T07:15:58Z
|
[
"python",
"file",
"class",
"variables"
] |
Python dedicated class for file names
| 39,433,691 |
<p>I am writing a program that utilises a large number of files. Does Python feature an inbuilt class for file paths, or does one have to be implemented by the user (like below):</p>
<pre><code>class FilePath:
def __init__(path):
shazam(path)
def shazam(self, path):
""" something happens, path is formatted, etc """
self.formatted_path = foobar
</code></pre>
<p><strong>Why would it be useful?</strong></p>
<p>Suppose the program and its data is copied to a different operating system. The class could modify itself on launch to support the a different path separator.</p>
<p><strong>Why not just write it yourself?</strong></p>
<p>Someone might have already written a class in the standard Python library.</p>
| 2 |
2016-09-11T07:07:43Z
| 39,435,016 |
<p>Since Python 3.4 there is <a href="https://docs.python.org/3/library/pathlib.html" rel="nofollow">pathlib</a> which seems to be what you are looking for. Of course there are the functions from <a href="https://docs.python.org/3/library/os.path.html" rel="nofollow">os.path</a>, too - but for an object-oriented approach pathlib is fitting better.</p>
| 1 |
2016-09-11T10:14:22Z
|
[
"python",
"file",
"class",
"variables"
] |
Django: How to implement user profiles?
| 39,433,707 |
<p>I'm making a Twitter clone and trying to load profile pages. My logic was to start simple and find all tweets that match a certain author and load those tweets on a page as the user's profile. I really don't know where to start.</p>
<p>urls.py</p>
<pre><code>url(r'^users/(?P<username>\w+)/$', views.UserProfileView.as_view(), name='user-profile'),
</code></pre>
<p>models.py</p>
<pre><code>class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
</code></pre>
<p>views.py</p>
<pre><code>class UserProfileView(DetailView):
"""
A page that loads howls from a specific author based on input
"""
model = get_user_model()
context_object_name = 'user_object'
template_name = 'howl/user-profile.html'
</code></pre>
<p>user-profile.html</p>
<pre><code>{% block content %}
<h1>{{user_object.author}}</h1>
{% endblock %}
</code></pre>
<p>I'm currently getting an error that says "Generic detail view UserProfileView must be called with either an object pk or a slug." whenever I try something like localhost:8000/users/</p>
<p>I also went on the shell and tried</p>
<pre><code>Howl.objects.filter(author="admin")
</code></pre>
<p>But got </p>
<pre><code>ValueError: invalid literal for int() with base 10: 'admin'
</code></pre>
| 0 |
2016-09-11T07:11:02Z
| 39,434,004 |
<p>Foreign key require model object or primary key of object.</p>
<p>pass the id of object whose username is "admin". use</p>
<pre><code>Howl.objects.filter(author=1)
</code></pre>
<p>instead of</p>
<pre><code>Howl.objects.filter(author="admin")
</code></pre>
<p>or you can use this one also</p>
<pre><code>user = User.objects.get(username = "admin")
Howl.objects.filter(author=user)
</code></pre>
| 0 |
2016-09-11T07:57:14Z
|
[
"python",
"django"
] |
Changing strings into integers
| 39,433,738 |
<p>I'm going crazy and I can not figure the right solution :(</p>
<p>How can I solve that problems. I have a loop and I can get diffrent types like:</p>
<pre><code>empty string
10
10K
2.3K
2.34K
2M
2.2M
2.23M
</code></pre>
<p>I need to change them into numbers:</p>
<pre><code>0
10
10000
2300
2340
2000000
2200000
2230000
</code></pre>
| 1 |
2016-09-11T07:15:22Z
| 39,433,807 |
<p>Your steps should be:</p>
<ul>
<li>check if string is empty
<ul>
<li>return 0</li>
</ul></li>
<li>check if string ends in K or M
<ul>
<li>if it does, strip that character off the end, store it for later</li>
<li>multiply by appropriate factor (K = 1000 or M = 1000000)</li>
</ul></li>
</ul>
<p>This can be achieved with the following:</p>
<pre><code>def convert(value):
if value:
# determine multiplier
multiplier = 1
if value.endswith('K'):
multiplier = 1000
value = value[0:len(value)-1] # strip multiplier character
elif value.endswith('M'):
multiplier = 1000000
value = value[0:len(value)-1] # strip multiplier character
# convert value to float, multiply, then convert the result to int
return int(float(value) * multiplier)
else:
return 0
values = [
'',
'10',
'10K',
'2.3K',
'2.34K',
'2M',
'2.2M',
'2.23M',
]
# use a list comprehension to call the function on all values
numbers = [convert(value) for value in values]
print numbers
</code></pre>
<p>This should return</p>
<pre><code>[0, 10, 10000, 2300, 2340, 2000000, 2200000, 2230000]
</code></pre>
| 2 |
2016-09-11T07:24:36Z
|
[
"python",
"regex",
"python-2.7"
] |
Changing strings into integers
| 39,433,738 |
<p>I'm going crazy and I can not figure the right solution :(</p>
<p>How can I solve that problems. I have a loop and I can get diffrent types like:</p>
<pre><code>empty string
10
10K
2.3K
2.34K
2M
2.2M
2.23M
</code></pre>
<p>I need to change them into numbers:</p>
<pre><code>0
10
10000
2300
2340
2000000
2200000
2230000
</code></pre>
| 1 |
2016-09-11T07:15:22Z
| 39,433,816 |
<p>A quick hack to get the floats:</p>
<pre><code>In [15]: powers = {'K': 10 ** 3, 'M': 10 ** 6}
In [16]: def f(s):
...: try:
...: if s[-1] in powers.keys():
...: return float(s[:-1]) * powers[s[-1]]
...: else:
...: return float(s)
...: except:
...: return s
...:
In [17]: map(f, ['', '10', '10K', '2.3K', '2.34K', '2M', '2.2M', '2.23M'])
Out[17]: ['', 10.0, 10000.0, 2300.0, 2340.0, 2000000.0, 2200000.0, 2230000.0]
</code></pre>
| 2 |
2016-09-11T07:26:01Z
|
[
"python",
"regex",
"python-2.7"
] |
Changing strings into integers
| 39,433,738 |
<p>I'm going crazy and I can not figure the right solution :(</p>
<p>How can I solve that problems. I have a loop and I can get diffrent types like:</p>
<pre><code>empty string
10
10K
2.3K
2.34K
2M
2.2M
2.23M
</code></pre>
<p>I need to change them into numbers:</p>
<pre><code>0
10
10000
2300
2340
2000000
2200000
2230000
</code></pre>
| 1 |
2016-09-11T07:15:22Z
| 39,437,859 |
<p>I agree with other answers, this solution will be best to solve it without Regular Expression.</p>
<p>But, if you still want to use regex, here is a nice way to do this using JavaScript (sorry, not familiar with Python):</p>
<pre><code>var new_arr = ['','10','10K','2.3K','2.34K','2M','2.2M','2.23M'].map(function(value) {
return value.replace(/^(\d*(?:\.\d+)?)([kgm]?)$/i, function(_, number, group) {
return !group && (number||'0') || parseFloat(number) * Math.pow(10, {'k':3,'m':6,'g':9}[group.toLowerCase()]);
});
});
</code></pre>
<p>If someone could translate it to Python, it would be best (and it will teach me a bit of Python well). :))</p>
| 0 |
2016-09-11T15:46:35Z
|
[
"python",
"regex",
"python-2.7"
] |
How can I make a while loop only run a limited number of times?
| 39,433,761 |
<p>In the code below, I'd like to run the function <code>roll()</code>, after: <code>deal = input("Your Turn: ")</code>, but only up to a limited number of cycles (52)</p>
<p>How can I achieve that?</p>
<pre><code>import random
ydeal = random.randint(1,15)
adeal = random.randint(1,15)
yscore = 0
ascore = 0
def roll():
if deal == "Deal":
print(ydeal, adeal)
if ydeal > adeal:
yscore + 1
elif ydeal < adeal:
ascore + 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
</code></pre>
<p>As a side note: I noticed that when printing <code>yscore</code> and <code>ascore</code> the value does not change during the loop, how can I fix that?</p>
| -2 |
2016-09-11T07:18:25Z
| 39,433,892 |
<p>Not sure about your code, but you can limit the number of loops by adding one to <code>n</code> on each loop, and use <code>while n <= 52</code> (or any other value):</p>
<pre><code>n = 1
while n <= 3:
word = "monkey" if n == 1 else "monkeys"
print(n, word)
if input("press Return to increase the number of monkeys ") == "":
n += 1
print("\nOoops, we ran out of monkeys...")
</code></pre>
<p>Then:</p>
<pre><code>1 monkey
press Return to increase the number of monkeys
2 monkeys
press Return to increase the number of monkeys
3 monkeys
press Return to increase the number of monkeys
Ooops, we ran out of monkeys...
</code></pre>
<p>In your situation:</p>
<pre><code>n = 1
while n <= 52:
deal = input("Your Turn: ")
roll()
n += 1
</code></pre>
<p>However, your function <code>roll()</code> isn't quite working as it should:</p>
<ul>
<li>your <code>ydeal</code> and <code>adeal</code> are fixed values, and won't change during the game.</li>
<li>whatever you do with your variables <em>inside the function</em> has no effect outside, unless you set the variable to be <code>global</code>, or you make the function return something.</li>
</ul>
<p>An example:</p>
<pre><code>test = 5
def add_one(var):
return var + 1
test = add_one(test)
print(test)
> 6
</code></pre>
<p>but that is another question :).</p>
| 0 |
2016-09-11T07:38:39Z
|
[
"python"
] |
How can I make a while loop only run a limited number of times?
| 39,433,761 |
<p>In the code below, I'd like to run the function <code>roll()</code>, after: <code>deal = input("Your Turn: ")</code>, but only up to a limited number of cycles (52)</p>
<p>How can I achieve that?</p>
<pre><code>import random
ydeal = random.randint(1,15)
adeal = random.randint(1,15)
yscore = 0
ascore = 0
def roll():
if deal == "Deal":
print(ydeal, adeal)
if ydeal > adeal:
yscore + 1
elif ydeal < adeal:
ascore + 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
</code></pre>
<p>As a side note: I noticed that when printing <code>yscore</code> and <code>ascore</code> the value does not change during the loop, how can I fix that?</p>
| -2 |
2016-09-11T07:18:25Z
| 39,433,958 |
<p>I noticed a couple of problems in your code:</p>
<ol>
<li>Inside the <code>roll()</code> function you have to declare that you want to use the global variables and not two new variables that are local to the function,</li>
<li>You are not assigning the increment to the value. A correct way to do it is: <code>yscore += 1</code>.</li>
</ol>
<p>At the end, I report to you a reviewed version of your code. At the end of the code I have inserted a 52 iterations while loop example.</p>
<pre><code>import random
ydeal = random.randint(1,9)
adeal = random.randint(1,9)
yscore = 0
ascore = 0
def roll():
#Notify that the variables you want to use are not defined inside the function
global yscore
global ascore
if deal == "!":
print(ydeal)
print(adeal)
if ydeal > adeal:
yscore += 1
elif ydeal < adeal:
ascore += 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
#while loop
max_iteration = 52
counter = 0
while counter < max_iteration :
counter += 1
print ("while: ", counter)
</code></pre>
| 0 |
2016-09-11T07:49:41Z
|
[
"python"
] |
How can I make a while loop only run a limited number of times?
| 39,433,761 |
<p>In the code below, I'd like to run the function <code>roll()</code>, after: <code>deal = input("Your Turn: ")</code>, but only up to a limited number of cycles (52)</p>
<p>How can I achieve that?</p>
<pre><code>import random
ydeal = random.randint(1,15)
adeal = random.randint(1,15)
yscore = 0
ascore = 0
def roll():
if deal == "Deal":
print(ydeal, adeal)
if ydeal > adeal:
yscore + 1
elif ydeal < adeal:
ascore + 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
</code></pre>
<p>As a side note: I noticed that when printing <code>yscore</code> and <code>ascore</code> the value does not change during the loop, how can I fix that?</p>
| -2 |
2016-09-11T07:18:25Z
| 39,434,044 |
<p>I support Jacob's answer that you can limit the number of loops by adding one to n on each loop, and use while n <= 52 (or any other value). I also read many programming tips at <a href="http://ubuhanga.com" rel="nofollow">http://ubuhanga.com</a> and I think they can also help you</p>
| 0 |
2016-09-11T08:02:27Z
|
[
"python"
] |
How can I make a while loop only run a limited number of times?
| 39,433,761 |
<p>In the code below, I'd like to run the function <code>roll()</code>, after: <code>deal = input("Your Turn: ")</code>, but only up to a limited number of cycles (52)</p>
<p>How can I achieve that?</p>
<pre><code>import random
ydeal = random.randint(1,15)
adeal = random.randint(1,15)
yscore = 0
ascore = 0
def roll():
if deal == "Deal":
print(ydeal, adeal)
if ydeal > adeal:
yscore + 1
elif ydeal < adeal:
ascore + 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
</code></pre>
<p>As a side note: I noticed that when printing <code>yscore</code> and <code>ascore</code> the value does not change during the loop, how can I fix that?</p>
| -2 |
2016-09-11T07:18:25Z
| 39,434,124 |
<p>How about this using <code>range</code> as per my comment</p>
<pre><code>import random
def ydeal():
return random.randint(1,15)
def adeal():
return random.randint(1,15)
yscore = ascore = draw = 0
def roll():
global yscore, ascore, draw
if deal == "Deal":
for x in range(52):
yydeal = ydeal()
aadeal = adeal()
if yydeal > aadeal:
yscore += 1
elif yydeal < aadeal:
ascore += 1
else:
draw += 1
print("Score:", yscore, ascore, draw)
deal = input("Your Turn: ")
roll()
</code></pre>
<p>Note: using python2.7 you would need to change <code>deal = input("Your Turn: ")</code> to <code>deal = raw_input("Your Turn: ")</code></p>
| 0 |
2016-09-11T08:14:22Z
|
[
"python"
] |
How can I make a while loop only run a limited number of times?
| 39,433,761 |
<p>In the code below, I'd like to run the function <code>roll()</code>, after: <code>deal = input("Your Turn: ")</code>, but only up to a limited number of cycles (52)</p>
<p>How can I achieve that?</p>
<pre><code>import random
ydeal = random.randint(1,15)
adeal = random.randint(1,15)
yscore = 0
ascore = 0
def roll():
if deal == "Deal":
print(ydeal, adeal)
if ydeal > adeal:
yscore + 1
elif ydeal < adeal:
ascore + 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
</code></pre>
<p>As a side note: I noticed that when printing <code>yscore</code> and <code>ascore</code> the value does not change during the loop, how can I fix that?</p>
| -2 |
2016-09-11T07:18:25Z
| 39,434,202 |
<p>Here my previous suggestion with the while loop in the correct place:</p>
<pre><code>import random
yscore = 0
ascore = 0
max_score = 52;
def roll():
#Notify that the variables you want to use are not defined inside the function
global yscore
global ascore
if deal == "!":
while (yscore < max_score and ascore < max_score) :
ydeal = random.randint(1,9)
adeal = random.randint(1,9)
print(ydeal)
print(adeal)
if ydeal > adeal:
yscore += 1
elif ydeal < adeal:
ascore += 1
print(yscore, ascore)
deal = input("Your Turn: ")
roll()
</code></pre>
| 0 |
2016-09-11T08:23:31Z
|
[
"python"
] |
Missing .dll when running pyinstaller .exe file on another computer
| 39,433,821 |
<p>I have been busy making a short script in python to get users HWID. Because computers without python installed can't run the script, I have converted it to an .exe file using pyinstaller.</p>
<p>However, when I tried running the .exe file on my laptop (running windows 7 ultimate and does not have python installed) it gives the error message: </p>
<pre><code>The procedure entry point ucrtbase.terminate could not be located in the dynamic link library api-ms-win-crt-runtime-l1-1-0.dll.
</code></pre>
<p>Here is how I converted to .exe, just in-case i'm doing it wrong. </p>
<p>Code:</p>
<pre><code>import subprocess
import hashlib
import time
def addToClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
x = subprocess.check_output('wmic csproduct get UUID') #gets UUID from pc
x = x[42:] # removes unnecessary parts of string
x = x[:-9] # removes unnecessary parts of string
hash_object = hashlib.sha512(x) # Converts to sha512 hash
hex_dig = hash_object.hexdigest() # Converts hash to hex-decimal string
os.system("title HWID tool")
os.system("color 4e")
print("Your protected hardware ID is")
print(hex_dig)
time.sleep(3)
print("This has been automatically saved to your clipboard.")
addToClipBoard(hex_dig) #saves hex decimal string to clipboard.
</code></pre>
<p>Than I go into CMD, make sure im in the correct directory and run this. </p>
<pre><code>pyinstaller.exe --onefile compile.py
</code></pre>
<p>NOTE: I only get the error when running the .exe file on my laptop. I do not get the error when running on the computer I converted it to an .exe on. </p>
<p>Both the computer I compiled it on, and the laptop are 64bit, windows 7 ultimate machines. </p>
<p>EDIT: Works on my friends computer, however he has python installed. </p>
<p>Can you please tell me why I am getting this error and how to fix it?</p>
| 1 |
2016-09-11T07:26:28Z
| 40,029,542 |
<p>The issue is a missing <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48145" rel="nofollow">Visual C++ 2015 Redistributable</a> as @eryksun alluded to. However it was published July 10, 2015 so I don't know that it's necessarily an update issue as well.</p>
<p>I had the same problem on a recently installed & updated Windows 7 Professional x64 computer where the compiled .exe did not work (with the <code>api-ms-win-crt-runtime-l1-1-0.dll</code> error) prior to installing the redistributable and then did after installing it.</p>
| 0 |
2016-10-13T19:38:57Z
|
[
"python",
"windows",
"python-3.x",
"compilation",
"pyinstaller"
] |
Insert HTML tag in all HTML files in a folder in Python
| 39,433,888 |
<p>I'm new to python and trying a program to do the following:</p>
<ol>
<li><p>Open all folder and subfolders in a directory path</p></li>
<li><p>Identify the HTML files</p></li>
<li><p>Load the HTML in BeautifulSoup</p></li>
<li><p>Find the first body tag</p></li>
<li><p>If the body tag is immediately followed by < Google Tag Manager> then continue</p></li>
<li><p>If not then add < Google Tag Manager> code and save the file.</p></li>
</ol>
<p>I'm not able to scan all subfolders within each folder.
I'm not able to set seen() if < Google Tag Manager> appears immediately after the body tag.
Any help to perform the above tasks is appreciated.</p>
<p>My code attempt is as follows:</p>
<pre><code> import sys
import os
from os import path
from bs4 import BeautifulSoup
directory_path = '/input'
files = [x for x in os.listdir(directory_path) if path.isfile(directory_path+os.sep+x)]
for root, dirs, files in os.walk(directory_path):
for fname in files:
seen = set()
a = directory_path+os.sep+fname
if fname.endswith(".html"):
with open(a) as f:
soup = BeautifulSoup(f)
for li in soup.select('body'):
if li in seen:
continue
else:
seen.add("<!-- Google Tag Manager --><noscript><iframe src='//www.googletagmanager.com/ns.html?id=GTM-54QWZ8'height='0' width='0' style='display:none;visibility:hidden'></iframe></noscript><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-54QWZ8');</script><!-- End Google Tag Manager â>\n")
</code></pre>
| 0 |
2016-09-11T07:37:59Z
| 39,434,670 |
<p>So you can install the <a href="https://docs.python.org/3/library/glob.html" rel="nofollow">iglob</a> library for python. With iglob you can recursively traverse the main directory you specify and the sub-directories and list all the files with a given extension. Then open up the HTML file, read all the lines, traverse through the lines manually until you find "" for the tag as some users who may use a frame work might have other content inside the body tag. Either way, loop through the lines looking for the start of the body tag, then check the next line, if the text as you specified "Google Tag Manager" is not in the next line, write it out. Please keep in mind I wrote this in the event you will always have the Google Tag Manager tags right after the body tag. </p>
<p>Please keep in mind that:</p>
<ol>
<li>In the event the Google Tag Manager text is not directly after the body tag, this code will add it anyways, so if Google Tag manager is somewhere in the Two body tags, and works, this could break the functionality of your Google Tag Manager.</li>
<li>I am using Python 3.x for this, so if you are using Python 2, you might have to translate this to that version of python. </li>
<li>Replace the 'Path.html' with the variable path so that it rewrite the file it is looking at with the modifications. I put in 'path.html' so that i could see the output and compare to original while I was writing the script.</li>
</ol>
<p>Here is the code:</p>
<pre><code>import glob
types = ('*.html', '*.htm')
paths = []
for fType in types:
for filename in glob.iglob('./**/' + fType, recursive=True):
paths.append(filename)
#print(paths)
for path in paths:
print(path)
with open(path,'r') as f:
lines = f.readlines()
with open(path, 'w') as w:
for i in range(0,len(lines)):
w.write(lines[i])
if "<body>" in lines[i]:
if "<!-- Google Tag Manager -->" not in lines[i+1]:
w.write('<!-- Google Tag Manager --> <!-- End Google Tag Manager -->\n')
</code></pre>
| 2 |
2016-09-11T09:26:15Z
|
[
"python",
"html",
"beautifulsoup"
] |
Insert HTML tag in all HTML files in a folder in Python
| 39,433,888 |
<p>I'm new to python and trying a program to do the following:</p>
<ol>
<li><p>Open all folder and subfolders in a directory path</p></li>
<li><p>Identify the HTML files</p></li>
<li><p>Load the HTML in BeautifulSoup</p></li>
<li><p>Find the first body tag</p></li>
<li><p>If the body tag is immediately followed by < Google Tag Manager> then continue</p></li>
<li><p>If not then add < Google Tag Manager> code and save the file.</p></li>
</ol>
<p>I'm not able to scan all subfolders within each folder.
I'm not able to set seen() if < Google Tag Manager> appears immediately after the body tag.
Any help to perform the above tasks is appreciated.</p>
<p>My code attempt is as follows:</p>
<pre><code> import sys
import os
from os import path
from bs4 import BeautifulSoup
directory_path = '/input'
files = [x for x in os.listdir(directory_path) if path.isfile(directory_path+os.sep+x)]
for root, dirs, files in os.walk(directory_path):
for fname in files:
seen = set()
a = directory_path+os.sep+fname
if fname.endswith(".html"):
with open(a) as f:
soup = BeautifulSoup(f)
for li in soup.select('body'):
if li in seen:
continue
else:
seen.add("<!-- Google Tag Manager --><noscript><iframe src='//www.googletagmanager.com/ns.html?id=GTM-54QWZ8'height='0' width='0' style='display:none;visibility:hidden'></iframe></noscript><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-54QWZ8');</script><!-- End Google Tag Manager â>\n")
</code></pre>
| 0 |
2016-09-11T07:37:59Z
| 39,434,723 |
<p>My take on it, might have some bugs:</p>
<p>edited to add: I have since realized that this code does not ensure <code><!-- Google Tag Manager --></code> is the first tag after <code><body></code>, instead it ensures it is the first comment after <code><body></code>. Which is not what the question asked for.</p>
<pre><code>import fnmatch
import os
from bs4 import BeautifulSoup, Comment
from HTMLParser import HTMLParser
def get_soup(filename):
with open(filename, 'r') as myfile:
data=myfile.read()
return BeautifulSoup(data, 'lxml')
def write_soup(filename, soup):
with open(filename, "w") as file:
output = HTMLParser().unescape(soup.prettify())
file.write(output)
def needs_insertion(soup):
comments = soup.find_all(text=lambda text:isinstance(text, Comment))
try:
if comments[0] == ' Google Tag Manager ':
return False # has correct comment
else:
return True # has comments, but not correct one
except IndexError:
return True # has no comments
def get_html_files_in_dir(top_level_directory):
matches = []
for root, dirnames, filenames in os.walk(top_level_directory):
for filename in fnmatch.filter(filenames, '*.html'):
matches.append(os.path.join(root, filename))
return matches
my_html_files_path = '/home/azrad/whateveryouneedhere'
for full_file_name in get_html_files_in_dir(my_html_files_path):
soup = get_soup(full_file_name)
if needs_insertion(soup):
soup.body.insert(0, '<!-- Google Tag Manager --> <!-- End Google Tag Manager -->')
write_soup(full_file_name, soup)
</code></pre>
| 0 |
2016-09-11T09:33:53Z
|
[
"python",
"html",
"beautifulsoup"
] |
Python Import Error: No module named Flask.myMethod
| 39,434,016 |
<p>I've read documentation, but I still can't quite wrap my head around how Python handles imports. I get the following error:</p>
<p>I've checked for circular imports (serv imports class_definitions: <code>from class_definitions import *</code> as well as a few other typical python modules) <code>class_definitions.py</code> only imports pickle
I've tried rebuilding the venv
I consolidated code to these two files to try to make it go away.</p>
<p>The most headway I got in debugging it was that if I get rid of a call to a function I defined in <code>class_definitions.py</code> called <code>load_pumps()</code> it would typically go away. I could replace the function call to a set of dummy data that represents the data load_pumps() should return and I would not get this error. <code>load_pumps</code> is called in other parts of the code throughout <code>serv.py</code> and I didn't get this error until earlier today. Any ideas?</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/pi/Desktop/barbot/flask-files/serv.py", line 89, in admin
pump_list=load_pumps(),
File "/home/pi/Desktop/barbot/flask-files/class_definitions.py", line 90, in load_pumps
read_pump_list = pickle.load(file_pump)
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/usr/lib/python2.7/pickle.py", line 1124, in find_class
__import__(module)
ImportError: No module named Flask.class_definitions
</code></pre>
<p>And file tree looks like this</p>
<pre><code>âââ admin_config.cfg
âââ class_definitions.py
âââ class_definitions.pyc
âââ __init__.py
âââ __init__.pyc
âââ lists
âààâââ bac_list.py
âààâââ bac_list.pyc
âààâââ cocktails_all.py
âààâââ cocktails_all.pyc
âààâââ garnishes_all.lst
âààâââ garnishes_selected.lst
âààâââ __init__.py
âààâââ __init__.pyc
âààâââ mixers_all.lst
âààâââ pumps.cfg
âààâââ spirits_all.lst
âââ requirements.txt
âââ serv.py
âââ serv.pyc
âââ templates
âââ admin_console.html
2 directories, 20 files
</code></pre>
| -2 |
2016-09-11T07:59:12Z
| 39,435,047 |
<p>It seems that you have a py file at this path:</p>
<pre><code>"/home/pi/Desktop/barbot/flask-files/class_definitions.py"
</code></pre>
<p>And you are trying to import something named <code>Flask.class_definitions</code> when you <code>pickle.load</code>.</p>
<p>This fails because <code>class_definitions</code> is not in the <code>Flask</code> package.</p>
<p>Since you are loading a pickle, I would say you had a <code>class_definitions</code> module within a <code>Flask</code> package at some time in the past, when you created the pickle.</p>
<p>The way pickle works is that it saved the exact names of the classes which were used when it saves the instances, so that it can find them and reconstruct the instances when loading. If you change your code in the meantime, the pickle can become incompatible.</p>
<p>There are ways to implement compatibility for such situations, but instead of that I suggest that, for now at least, you dont change your class names and directory structures after saving a pickle.</p>
| 0 |
2016-09-11T10:18:24Z
|
[
"python",
"flask"
] |
Regular expression for separating strings
| 39,434,084 |
<p>I have the following string</p>
<blockquote>
<p>Long string 1 [sucess 50] long string 2 [apple 5 banana 20 orange 75]
long string 3 [failure: 100]</p>
</blockquote>
<p>Now I want to split it into three strings:</p>
<ol>
<li>Long string 1 [sucess 50]<br/></li>
<li>long string 2 [apple 5 banana 20 orange 75]<br/></li>
<li>long string 3 [failure: 100]<br/></li>
</ol>
<p>inside [] there could be one or more instances of combination of a string and a number, and the number is from 0 to 100.</p>
<p>How this can be done with regex in python?</p>
| -7 |
2016-09-11T08:07:30Z
| 39,434,165 |
<p>No need for regular expressions in such a simple task. Just use Python's built-in <code>str.replace()</code> method like so:</p>
<pre><code>your_str = your_str.replace(']', ']\n')
</code></pre>
<p>To split it and get a list, use <code>your_str.split(']')</code></p>
<p>But if you really want regex or the string inside the brackets can contain more brackets, you can try this:</p>
<pre><code>import re
your_str = "Long string 1 [sucess 50] long string 2 [apple 5 banana 20 orange 75] long string 3 [failure: 100]"
your_str = re.sub(r'\[(.+? [0-9]+)\] ', r'[\1]\n', your_str)
print(your_str)
</code></pre>
<p>The following code produces this output:</p>
<pre><code>Long string 1 [sucess 50]
long string 2 [apple 5 banana 20 orange 75]
long string 3 [failure: 100]
</code></pre>
<p>But this is going to be a string. To get a list of strings, you can then simply split by newline like this:</p>
<pre><code>your_str.split('\n')
</code></pre>
| 3 |
2016-09-11T08:19:43Z
|
[
"python",
"regex"
] |
Regular expression for separating strings
| 39,434,084 |
<p>I have the following string</p>
<blockquote>
<p>Long string 1 [sucess 50] long string 2 [apple 5 banana 20 orange 75]
long string 3 [failure: 100]</p>
</blockquote>
<p>Now I want to split it into three strings:</p>
<ol>
<li>Long string 1 [sucess 50]<br/></li>
<li>long string 2 [apple 5 banana 20 orange 75]<br/></li>
<li>long string 3 [failure: 100]<br/></li>
</ol>
<p>inside [] there could be one or more instances of combination of a string and a number, and the number is from 0 to 100.</p>
<p>How this can be done with regex in python?</p>
| -7 |
2016-09-11T08:07:30Z
| 39,434,201 |
<pre><code>In [79]: import re
In [80]: my_string = "Long string 1 [sucess 50] long string 2 [apple 5 banana 20 orange 75] long string 3 [failure: 100]"
In [81]: re.findall(r'([^\[]*\[[^\]]*\])(?: ?)', my_string)
Out[81]:
['Long string 1 [sucess 50]',
'long string 2 [apple 5 banana 20 orange 75]',
'long string 3 [failure: 100]']
</code></pre>
<p>How the regex works:</p>
<pre><code>([^\[]*\[[^\]]*\])(?: ?)
</code></pre>
<p><img src="https://www.debuggex.com/i/pH92LSnQn9168BW5.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/pH92LSnQn9168BW5" rel="nofollow">Debuggex Demo</a></p>
<p>Detailed explanation at: <a href="https://regex101.com/r/oS1oL8/1" rel="nofollow">https://regex101.com/r/oS1oL8/1</a></p>
| 0 |
2016-09-11T08:23:30Z
|
[
"python",
"regex"
] |
Refreshing a specific div every few seconds in django using javascript
| 39,434,086 |
<p>I am trying to refresh the content of a table every few seconds in my html page using javascript. I keep getting 500 error when it tries to refresh the div, internal server error. Could someone enlighten the reason this is not working? I have used this: <a href="http://stackoverflow.com/questions/3776571/refresh-div-using-jquery-in-django-while-using-the-template-system">Refresh div using JQuery in Django while using the template system</a>
as reference to what I was doing. The page loads perfectly the first time just fails to refresh.</p>
<p>Here is my code:</p>
<p>urls.py</p>
<pre><code>url(r'^specialScoreboard/$', views.specialScoreboard.as_view(), name='specialScoreboard'),
url(r'^specialScoreboardDiv/$', views.specialScoreboardDiv , name='specialScoreboardDiv'),
</code></pre>
<p>views.py</p>
<pre><code>class specialScoreboard(generic.ListView):
template_name = 'CTF/specialScoreboard.html'
context_object_name = 'teams'
@method_decorator(login_required)
@method_decorator(never_ever_cache)
def dispatch(self, request, *args, **kwargs):
if getAnyActiveGame and request.user.is_staff:
return super(specialScoreboard, self).dispatch(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('CTF:no_active_game'))
def get_queryset(self):
"""
ordering teams by score
"""
game = getAnyActiveGame()
teams = get_teams_from_game(game)
return sorted(teams, key=lambda a: a.get_score(game), reverse=True)
def specialScoreboardDiv():
game = getAnyActiveGame()
teams = get_teams_from_game(game)
sortedList = sorted(teams, key=lambda a: a.get_score(game), reverse=True)
return render_to_response('CTF/specialscoreboardDiv.html' , {'sortedList' :sortedList})
</code></pre>
<p>scoreboardRefresh.js + scoreboardDiv.html</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-js lang-js prettyprint-override"><code>< script >
var scoreboardURL = '{% url '
CTF: specialScoreboardDiv ' %}';
function refresh() {
$.ajax({
url: scoreboardURL,
success: function(data) {
$('#scoreboardDiv').html(data);
}
});
};
$(document).ready(function($) {
refresh();
setInterval("refresh()", 3000);
})
< /script></code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel panel-info">
<div class="panel-heading">Scoreboard</div>
<div class="panel-body">
<div class="table-striped">
<table id="scoreboardDiv" class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Team Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{% for team in teams %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{team.name}}</td>
<td>{{team|getScoreTeam}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>i can't seem to be able to format the error, here is a picture of it: <a href="http://i.imgur.com/Yc11juA.png" rel="nofollow">http://i.imgur.com/Yc11juA.png</a>
<a href="http://i.imgur.com/QluqZyc.png" rel="nofollow">http://i.imgur.com/QluqZyc.png</a>
<a href="http://imgur.com/QluqZyc" rel="nofollow">http://imgur.com/QluqZyc</a></p>
| -4 |
2016-09-11T08:07:44Z
| 39,434,842 |
<p>Your django view takes no arguments, but usually django tries to pass request param into it. From the error in the screenshot you provided in comments, looks likе this is your problem. </p>
<p>I think you error will be fixed by making your view function take this argument:</p>
<pre><code>def specialScoreboardDiv(request):
game = getAnyActiveGame()
...
</code></pre>
| 0 |
2016-09-11T09:47:54Z
|
[
"javascript",
"jquery",
"python",
"html",
"django"
] |
Python; How to replace escaped non-unicode characters with their respective 'real' utf-8
| 39,434,177 |
<p>I am relatively new to programming, and I have a small problem writing a python equivalent of Snip for spotify for ubuntu(linux)
Somehow i can encode the title correctly, but am unable to encode the artist the same way</p>
<p>when i try to encode the artist in the same fashion i get this:</p>
<pre><code>File "./songfinder.py", line 11, in currentplaying
artiststr = str((metadata['xesam:artist']).encode('utf-8'))
AttributeError: 'dbus.Array' object has no attribute 'encode'
</code></pre>
<p>however the title is done exactly the same and that is working.</p>
<p>Code so far IS working but has for example \xd8 instead of Ã, and similar:</p>
<pre><code>import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")
def currentplaying():
metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
title = str((metadata['xesam:title']).encode('utf-8'))
artiststr = str((metadata['xesam:artist']))
if ("dbus.string" in artiststr.lower()):
artists = artiststr.split("(u")
artist = artists[1]
artists = artist.split(")],")
artist = artists[0]
artist = artist.replace("(u", "")
else:
artist = "'unknown'"
artist = (artist.replace("'",""))
playing = (artist + " - " + title + " ")
return playing
#save playing to file.txt
</code></pre>
<p>relevant qna's:
<a href="http://stackoverflow.com/questions/3704731/replace-non-ascii-chars-from-a-unicode-string-in-python">Replace non-ascii chars from a unicode string in Python</a></p>
<p>Why it does not resolve my problem: I would like to print/save the actual character, not replace it with similar ones</p>
| 3 |
2016-09-11T08:20:40Z
| 39,434,245 |
<p>The error you getting is not about unicode, it is about wrong type. Python complains that you trying to call string method <code>encode</code> from the array object. Which does not have this method. </p>
<p>The first this I would try is to remove redundant brackets here it getting artiststr like this: <code>artiststr = str(metadata['xesam:artist'])</code>.</p>
<p>But I'm not sure this would work. If it doesn't work, you need to find out what type has metadata['xesam:artist']. Looks like it is not string, but array. So you need to fix the code which fills <code>metadata['xesam:artist']</code> with data. You can try to use debugger or just <code>print()</code> function to find out the content of <code>metadata['xesam:artist']</code>. Or provide the relevant code in you question too.</p>
| 0 |
2016-09-11T08:30:40Z
|
[
"python",
"unicode",
"encoding",
"utf-8",
"dbus"
] |
Python; How to replace escaped non-unicode characters with their respective 'real' utf-8
| 39,434,177 |
<p>I am relatively new to programming, and I have a small problem writing a python equivalent of Snip for spotify for ubuntu(linux)
Somehow i can encode the title correctly, but am unable to encode the artist the same way</p>
<p>when i try to encode the artist in the same fashion i get this:</p>
<pre><code>File "./songfinder.py", line 11, in currentplaying
artiststr = str((metadata['xesam:artist']).encode('utf-8'))
AttributeError: 'dbus.Array' object has no attribute 'encode'
</code></pre>
<p>however the title is done exactly the same and that is working.</p>
<p>Code so far IS working but has for example \xd8 instead of Ã, and similar:</p>
<pre><code>import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")
def currentplaying():
metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
title = str((metadata['xesam:title']).encode('utf-8'))
artiststr = str((metadata['xesam:artist']))
if ("dbus.string" in artiststr.lower()):
artists = artiststr.split("(u")
artist = artists[1]
artists = artist.split(")],")
artist = artists[0]
artist = artist.replace("(u", "")
else:
artist = "'unknown'"
artist = (artist.replace("'",""))
playing = (artist + " - " + title + " ")
return playing
#save playing to file.txt
</code></pre>
<p>relevant qna's:
<a href="http://stackoverflow.com/questions/3704731/replace-non-ascii-chars-from-a-unicode-string-in-python">Replace non-ascii chars from a unicode string in Python</a></p>
<p>Why it does not resolve my problem: I would like to print/save the actual character, not replace it with similar ones</p>
| 3 |
2016-09-11T08:20:40Z
| 39,434,496 |
<p>Final program, feel free to use if you like:</p>
<pre><code>import time
import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")
def currentplaying():
metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
title = str((metadata['xesam:title']).encode('utf-8'))
artiststr = str((metadata['xesam:artist'])[0].encode('utf-8'))
artist = artiststr
playing = (artist + " - " + title + " ")
return playing
while True:
filetxt = open("/home/USER/Desktop/currentsongspotify.txt", "r")
oldtitle = filetxt.read()
filetxt.close()
newtitle = str(currentplaying())
if(newtitle == oldtitle):
time.sleep(1)
else:
filetxt = open("/home/USER/Desktop/currentsongspotify.txt", "w") #save newtitle to file, overwriting existing data
filetxt.write(str(newtitle))
print("new file saved: " + newtitle)
</code></pre>
| 0 |
2016-09-11T09:03:27Z
|
[
"python",
"unicode",
"encoding",
"utf-8",
"dbus"
] |
Python; How to replace escaped non-unicode characters with their respective 'real' utf-8
| 39,434,177 |
<p>I am relatively new to programming, and I have a small problem writing a python equivalent of Snip for spotify for ubuntu(linux)
Somehow i can encode the title correctly, but am unable to encode the artist the same way</p>
<p>when i try to encode the artist in the same fashion i get this:</p>
<pre><code>File "./songfinder.py", line 11, in currentplaying
artiststr = str((metadata['xesam:artist']).encode('utf-8'))
AttributeError: 'dbus.Array' object has no attribute 'encode'
</code></pre>
<p>however the title is done exactly the same and that is working.</p>
<p>Code so far IS working but has for example \xd8 instead of Ã, and similar:</p>
<pre><code>import dbus
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")
def currentplaying():
metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
title = str((metadata['xesam:title']).encode('utf-8'))
artiststr = str((metadata['xesam:artist']))
if ("dbus.string" in artiststr.lower()):
artists = artiststr.split("(u")
artist = artists[1]
artists = artist.split(")],")
artist = artists[0]
artist = artist.replace("(u", "")
else:
artist = "'unknown'"
artist = (artist.replace("'",""))
playing = (artist + " - " + title + " ")
return playing
#save playing to file.txt
</code></pre>
<p>relevant qna's:
<a href="http://stackoverflow.com/questions/3704731/replace-non-ascii-chars-from-a-unicode-string-in-python">Replace non-ascii chars from a unicode string in Python</a></p>
<p>Why it does not resolve my problem: I would like to print/save the actual character, not replace it with similar ones</p>
| 3 |
2016-09-11T08:20:40Z
| 39,439,062 |
<p>Looking at your question <code>metadata</code> contains at least something like this with Unicode strings. The artist field seems to be some sort of iterable the begins with the artist. Something like this (feel free to post actual metadata content):</p>
<pre><code>metadata = {'xesam:title':u'title','xesam:artist':[u'artist']}
</code></pre>
<p>In the <code>title</code> assignment line, <code>str</code> is unnecessary since encoding a Unicode string returns a <code>str</code> anyway, but no need to encode it either. Unicode strings represent text, so leave it that way:</p>
<pre><code>title = metadata['xesam:title']
</code></pre>
<p>Similar for <code>artist</code> assignment, but get the first element of the iterable:</p>
<pre><code>artist = metadata['xesam:artist'][0]
</code></pre>
<p>Next, in your song-updating logic, use <code>io.open</code> to open the files with a UTF-8 encoding. This lets Unicode strings (text) be written directly and the file will handle the encoding. Also use a <code>with</code> statement to automatically close the file when the <code>with</code> ends.</p>
<p>Program with recommended changes:</p>
<pre><code>import time
import dbus
import io
session_bus = dbus.SessionBus()
spotify_bus = session_bus.get_object("org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2")
spotify_properties = dbus.Interface(spotify_bus, "org.freedesktop.DBus.Properties")
def currentplaying():
metadata = spotify_properties.Get("org.mpris.MediaPlayer2.Player", "Metadata")
title = metadata['xesam:title']
artist = metadata['xesam:artist'][0]
playing = artist + " - " + title + " "
return playing
while True:
with io.open('currentsongspotify.txt', encoding='utf8') as filetxt:
oldtitle = filetxt.read()
newtitle = currentplaying()
if newtitle == oldtitle:
time.sleep(1)
else:
with io.open('currentsongspotify.txt','w',encoding='utf8') as filetxt: # save newtitle to file, overwriting existing data
filetxt.write(newtitle)
print 'new file saved:',newtitle
</code></pre>
| 0 |
2016-09-11T18:00:49Z
|
[
"python",
"unicode",
"encoding",
"utf-8",
"dbus"
] |
I can't understand why "ax=ax" meaning in matplotlib
| 39,434,190 |
<pre><code>from datetime import datetime
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
data=pd.read_csv(r"C:\Users\champion\Desktop\ch02\spx.csv")
spx=data["SPX"]
spx.plot(**ax=ax**,style="k-")
</code></pre>
<p>I can't understand why "ax=ax" meaning in matplotlib.</p>
| 0 |
2016-09-11T08:21:47Z
| 39,434,237 |
<p>From the documentation of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">plot()</a>:</p>
<blockquote>
<p>DataFrame.plot(x=None, y=None, kind='line', ax=None, subplots=False,
sharex=None, sharey=False, layout=None, figsize=None, use_index=True,
title=None, grid=None, legend=True, style=None, logx=False,
logy=False, loglog=False, xticks=None, yticks=None, xlim=None,
ylim=None, rot=None, fontsize=None, colormap=None, table=False,
yerr=None, xerr=None, secondary_y=False, sort_columns=False, **kwds)</p>
<p>Parameters: ax : matplotlib axes object, default None</p>
</blockquote>
<p>You can see that <code>ax</code> is a keyword argument here. It just happens that you also named your variable as <code>ax</code> and you are sending it as the value of that keyword argument to the function <code>plot()</code>.</p>
| 0 |
2016-09-11T08:28:29Z
|
[
"python",
"matplotlib"
] |
Using Oauth library in python
| 39,434,207 |
<p>I am running a twitter api in python using oauth library. I have included the code below. When I run the code "twtest.py", I get the error `'module' object has no attribute 'OAuthConsumer'.</p>
<p>1.twtest.py</p>
<pre><code> import urllib
from twurl import augment
print '* Calling Twitter...'
url = augment('https://api.twitter.com/1.1/statuses/user_timeline.json',
{'screen_name': 'saurabhpathak20', 'count': '2'} )
print url
connection = urllib.urlopen(url)
data = connection.read()
print data
headers = connection.info().dict
print headers
</code></pre>
<p>2.twurl.py</p>
<pre><code>import urllib
import oauth
import hidden
def augment(url, parameters) :
secrets = hidden.oauth()
consumer = oauth.OAuthConsumer(secrets['consumer_key'], secrets['consumer_secret'])
token = oauth.OAuthToken(secrets['token_key'],secrets['token_secret'])
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
token=token, http_method='GET', http_url=url, parameters=parameters)
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
return oauth_request.to_url()
def test_me() :
print '* Calling Twitter...'
url = augment('https://api.twitter.com/1.1/statuses/user_timeline.json',
{'screen_name': 'saurabhpathak20', 'count': '2'} )
print url
connection = urllib.urlopen(url)
data = connection.read()
print data
headers = connection.info().dict
print headers
</code></pre>
<p>3.hidden.py</p>
<pre><code>def oauth() :
return { "consumer_key" : "pj......U8fFRyjV",
"consumer_secret" : "zty3njhO4IRl........ELh1YC1j1rX",
"token_key" : "515167047-xaRfSm7.......wBBOrjNd61anI55D",
"token_secret" : " y7ZCBDf6d..........x1eJV8mHRnL8hh" }
</code></pre>
<p>Kindly help me to understand what is wrong in the code.
Thanks.</p>
| 0 |
2016-09-11T08:24:17Z
| 39,434,272 |
<p>You need to import <code>oauth</code> from <code>oauth</code> instead of <code>import oauth</code></p>
<pre><code>>>> from oauth import oauth
>>> oauth.OAuthConsumer
<class 'oauth.oauth.OAuthConsumer'>
</code></pre>
| 0 |
2016-09-11T08:35:03Z
|
[
"python",
"python-2.7",
"oauth",
"web-scraping",
"twitter-oauth"
] |
Removing noise from image Python PIL
| 39,434,216 |
<p>Newbie here.
Have an image
I added noise on image, and them i need to clear image with noise(or something like that).
The unnoising algorythm is next:</p>
<blockquote>
<p>If the brightness of the pixel is greater than the average brightness
of the local neighborhood, then the brightness of the pixel is
replaced with the average brightness of the surroundings.</p>
</blockquote>
<pre><code>from PIL import Image
import random
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
img=Image.open('pic.bmp')
print(img.size)
randomenter=int(input('Enter numpix: '))
for numpix in range(0, randomenter):
x=random.randint(0,int(img.size[0]-1))
y=random.randint(0,int(img.size[1]-1))
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
img.putpixel((x,y),(r,g,b))
img.show()
img.save("noise.bmp", "BMP")
img2=Image.open("noise.bmp")
w, h = img2.size
pix=img2.copy()
for x in range(0,w-1):
if x-1>0 and x<w:
for y in range(0,h-1):
if y-1>0 and y<h:
local1=(0.3 * pix.getpixel((x-1,y-1))[0]) + (0.59 * pix.getpixel((x-1,y-1))[1]) + (0.11 * pix.getpixel((x-1,y-1))[2])
local2=(0.3 * pix.getpixel((x-1,y))[0]) + (0.59 * pix.getpixel((x-1,y))[1]) + (0.11 * pix.getpixel((x-1,y))[2])
local3=(0.3 * pix.getpixel((x-1,y+1))[0]) + (0.59 * pix.getpixel((x-1,y+1))[1]) + (0.11 * pix.getpixel((x-1,y+1))[2])
local4=(0.3 * pix.getpixel((x,y-1))[0]) + (0.59 * pix.getpixel((x,y-1))[1]) + (0.11 * pix.getpixel((x,y-1))[2])
LOCAL5=(0.3 * pix.getpixel((x,y))[0]) + (0.59 * pix.getpixel((x,y))[1]) + (0.11 * pix.getpixel((x,y))[2])
local6=(0.3 * pix.getpixel((x,y+1))[0]) + (0.59 * pix.getpixel((x,y+1))[1]) + (0.11 * pix.getpixel((x,y+1))[2])
local7=(0.3 * pix.getpixel((x+1,y-1))[0]) + (0.59 * pix.getpixel((x+1,y-1))[1]) + (0.11 * pix.getpixel((x+1,y-1))[2])
local8=(0.3 * pix.getpixel((x+1,y))[0]) + (0.59 * pix.getpixel((x+1,y))[1]) + (0.11 * pix.getpixel((x+1,y))[2])
local9=(0.3 * pix.getpixel((x+1,y+1))[0]) + (0.59 * pix.getpixel((x+1,y+1))[1]) + (0.11 * pix.getpixel((x+1,y+1))[2])
localall=(local1+local2+local3+local4+local6+local7+local8+local9)/8
if LOCAL5<localall:
img2.putpixel((x,y),(int(pix.getpixel((x,y))[0]*localall/LOCAL5),int(pix.getpixel((x,y))[1]*localall/LOCAL5),int(pix.getpixel((x,y))[2]*localall/LOCAL5)))
img2.show()
</code></pre>
<p>There is a problem at the moment of the brightness changing.
Official docks have no detail information about this case.
Is there any solution?</p>
| 2 |
2016-09-11T08:25:31Z
| 39,437,920 |
<p>First of all, you need to create a copy of your image to write your data to: <code>imgCopy = img.copy()</code>.
Else, your noise corrected pixels will influence the correction of pixels not yet touched.
In your else statement you simply have to normalize your middle pixel, then multiply it with the average brightness you calculated:</p>
<pre><code>imgCopy[i, j] = imgCopy[i, j] * local / nuzh
</code></pre>
| 1 |
2016-09-11T15:52:41Z
|
[
"python",
"python-imaging-library"
] |
is this a series or dataframe?
| 39,434,323 |
<p>I am quite new to Python, and have some basic questions which I could not find answer till now.</p>
<p>suppose I have the following dataframe named phone.</p>
<pre><code> current_cellphone | months of usage | previous_cellphone
0 | Motorola | 11 | Motorola
1 | Huawei | 21 | Nokia
2 | Motorola | 13 | Motorola
3 | Nokia | 2 | iphone
4 | Huawei | 20 | Huawei
5 | Motorola | 15 | Motorola
6 | Sony | 9 | HTC
</code></pre>
<p>My initiative is to group by current_cellphone, select those which are counted more than once (Motorola and Huawei).</p>
<pre><code>phone['current_cellphone'].value_counts
</code></pre>
<p>The result is </p>
<pre><code>Motorola | 3
Huawei | 2
Nokia | 1
</code></pre>
<p><strong>My 1st question is :</strong> does the code above yield a dataframe or series?</p>
<p><strong>My 2nd question is</strong>: how do I retrieve the first and second column of the above table? </p>
<p>Thank you very much for your helps.. </p>
| 3 |
2016-09-11T08:42:40Z
| 39,434,395 |
<p>It's <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="nofollow">pandas.Series</a> object. You can find that out using <a href="https://docs.python.org/2/library/functions.html#type" rel="nofollow">type()</a>.</p>
<pre><code>In [157]: phone
Out[157]:
current_cellphone | months of usage |.1 previous_cellphone
0 Motorola | 11 | Motorola NaN NaN
1 Huawei | 21 | Nokia NaN NaN
2 Motorola | 13 | Motorola NaN NaN
3 Nokia | 2 | iphone NaN NaN
4 Huawei | 20 | Huawei NaN NaN
5 Motorola | 15 | Motorola NaN NaN
6 Sony | 9 | HTC NaN NaN
In [158]: vc = phone['current_cellphone'].value_counts()
In [159]: vc
Out[159]:
Motorola 3
Huawei 2
Nokia 1
Sony 1
Name: current_cellphone, dtype: int64
In [160]: type(vc)
Out[160]: pandas.core.series.Series
</code></pre>
<p>To extract the information from the series:</p>
<pre><code>In [169]: vc.values
Out[169]: array([3, 2, 1, 1])
In [170]: vc.keys()
Out[170]: Index([u'Motorola', u'Huawei', u'Nokia', u'Sony'], dtype='object')
In [176]: vc.to_dict()
Out[176]: {'Huawei': 2, 'Motorola': 3, 'Nokia': 1, 'Sony': 1}
In [177]: vc.to_dict().keys()
Out[177]: ['Nokia', 'Huawei', 'Motorola', 'Sony']
In [178]: vc.to_dict().values()
Out[178]: [1, 2, 3, 1]
</code></pre>
<p>Converting to dataframe:</p>
<pre><code>In [180]: pd.DataFrame(vc)
Out[180]:
current_cellphone
Motorola 3
Huawei 2
Nokia 1
Sony 1
</code></pre>
| 4 |
2016-09-11T08:51:26Z
|
[
"python",
"pandas",
"numpy"
] |
is this a series or dataframe?
| 39,434,323 |
<p>I am quite new to Python, and have some basic questions which I could not find answer till now.</p>
<p>suppose I have the following dataframe named phone.</p>
<pre><code> current_cellphone | months of usage | previous_cellphone
0 | Motorola | 11 | Motorola
1 | Huawei | 21 | Nokia
2 | Motorola | 13 | Motorola
3 | Nokia | 2 | iphone
4 | Huawei | 20 | Huawei
5 | Motorola | 15 | Motorola
6 | Sony | 9 | HTC
</code></pre>
<p>My initiative is to group by current_cellphone, select those which are counted more than once (Motorola and Huawei).</p>
<pre><code>phone['current_cellphone'].value_counts
</code></pre>
<p>The result is </p>
<pre><code>Motorola | 3
Huawei | 2
Nokia | 1
</code></pre>
<p><strong>My 1st question is :</strong> does the code above yield a dataframe or series?</p>
<p><strong>My 2nd question is</strong>: how do I retrieve the first and second column of the above table? </p>
<p>Thank you very much for your helps.. </p>
| 3 |
2016-09-11T08:42:40Z
| 39,434,479 |
<pre><code>type(phone['current_cellphone'].value_counts())
pandas.core.series.Series
</code></pre>
<hr>
<pre><code>phone['current_cellphone'].value_counts().to_frame()
</code></pre>
<p><a href="http://i.stack.imgur.com/a2mWg.png" rel="nofollow"><img src="http://i.stack.imgur.com/a2mWg.png" alt="enter image description here"></a></p>
<hr>
<p>Or:</p>
<pre><code>phone['current_cellphone'].value_counts().reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/EUht7.png" rel="nofollow"><img src="http://i.stack.imgur.com/EUht7.png" alt="enter image description here"></a></p>
<pre><code>type(phone['current_cellphone'].value_counts().to_frame())
pandas.core.frame.DataFrame
</code></pre>
| 3 |
2016-09-11T09:01:35Z
|
[
"python",
"pandas",
"numpy"
] |
Post/Redirect/Get pattern in flask
| 39,434,377 |
<p>The view function of my toy app was:</p>
<pre><code>@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)
</code></pre>
<p>And it looks like this when I use PRG:</p>
<pre><code>@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))
</code></pre>
<p>As you can see, the <code>form.name.data = ''</code> line is used to clear the input field in the first version, but it's not needed in the second version. I thought Flask-WTF would automatically pass the text in <code>StringField</code> into the new <code>form</code> instance, but for some reasons, it didn't.</p>
<p>My question is: Why <code>form.name.data</code> is no longer available between different requests when I use PRG?</p>
| 0 |
2016-09-11T08:48:45Z
| 39,434,390 |
<p>It can't pass anything on a redirect, as it is a completely new request.</p>
| 1 |
2016-09-11T08:51:12Z
|
[
"python",
"redirect",
"flask",
"flask-wtforms",
"post-redirect-get"
] |
Python scrapy ReactorNotRestartable substitute
| 39,434,406 |
<p>I have been trying to make an app in Python using <code>Scrapy</code> that has the following functionality:</p>
<ul>
<li>A <strong><em>rest api</em></strong> (I had made that using flask) listens to all requests to crawl/scrap and return the response after crawling.(the crawling part is short enough, so the connection can be keep-alive till crawling gets completed.)</li>
</ul>
<p>I am able to do this using the following code:</p>
<pre><code>items = []
def add_item(item):
items.append(item)
# set up crawler
crawler = Crawler(SpiderClass,settings=get_project_settings())
crawler.signals.connect(add_item, signal=signals.item_passed)
# This is added to make the reactor stop, if I don't use this, the code stucks at reactor.run() line.
crawler.signals.connect(reactor.stop, signal=signals.spider_closed) #@UndefinedVariable
crawler.crawl(requestParams=requestParams)
# start crawling
reactor.run() #@UndefinedVariable
return str(items)
</code></pre>
<p>Now the problem I am facing is after making the reactor stop (which seems necessary to me since I don't want to stuck to the <code>reactor.run()</code>). I couldn't accept the further request after first request. After first request gets completed, I got the following error:</p>
<pre><code>Traceback (most recent call last):
File "c:\python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "c:\python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "c:\python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:\my_workspace\jobvite\jobvite\com\jobvite\web\RequestListener.py", line 38, in submitForm
reactor.run() #@UndefinedVariable
File "c:\python27\lib\site-packages\twisted\internet\base.py", line 1193, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "c:\python27\lib\site-packages\twisted\internet\base.py", line 1173, in startRunning
ReactorBase.startRunning(self)
File "c:\python27\lib\site-packages\twisted\internet\base.py", line 684, in startRunning
raise error.ReactorNotRestartable()
ReactorNotRestartable
</code></pre>
<p>Which is obvious, since we can not restart the reactor.</p>
<p>So my questions are:</p>
<p>1) How could I provide support for the next requests to crawl? </p>
<p>2) Is there any way to move to next line after reactor.run() without stopping it?</p>
| 7 |
2016-09-11T08:52:33Z
| 39,516,357 |
<p>I recommend you using a queue system like <a href="http://python-rq.org/" rel="nofollow">Rq</a> (for simplicity, but there are few others).<br>
You could have a craw function:</p>
<pre><code>from twisted.internet import reactor
import scrapy
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from scrapy.utils.project import get_project_settings
from spiders import MySpider
def runCrawler(url, keys, mode, outside, uniqueid):
runner = CrawlerRunner( get_project_settings() )
d = runner.crawl( MySpider, url=url, param1=value1, ... )
d.addBoth(lambda _: reactor.stop())
reactor.run()
</code></pre>
<p>Then in your main code, use the Rq queue in order to collect crawler executions:</p>
<pre><code># other imports
pool = redis.ConnectionPool( host=REDIS_HOST, port=REDIS_PORT, db=your_redis_db_number)
redis_conn =redis.Redis(connection_pool=pool)
q = Queue('parse', connection=redis_conn)
# urlSet is a list of http:// or https:// like url's
for url in urlSet:
job = q.enqueue(runCrawler, url, param1, ... , timeout=600 )
</code></pre>
<p>Do not forget to start a rq worker process, working for the same queue name (here <strong>parse</strong>). For example, execute in a terminal session:</p>
<pre><code>rq worker parse
</code></pre>
| 1 |
2016-09-15T16:46:08Z
|
[
"python",
"flask",
"scrapy",
"reactor",
"twisted.internet"
] |
Python scrapy ReactorNotRestartable substitute
| 39,434,406 |
<p>I have been trying to make an app in Python using <code>Scrapy</code> that has the following functionality:</p>
<ul>
<li>A <strong><em>rest api</em></strong> (I had made that using flask) listens to all requests to crawl/scrap and return the response after crawling.(the crawling part is short enough, so the connection can be keep-alive till crawling gets completed.)</li>
</ul>
<p>I am able to do this using the following code:</p>
<pre><code>items = []
def add_item(item):
items.append(item)
# set up crawler
crawler = Crawler(SpiderClass,settings=get_project_settings())
crawler.signals.connect(add_item, signal=signals.item_passed)
# This is added to make the reactor stop, if I don't use this, the code stucks at reactor.run() line.
crawler.signals.connect(reactor.stop, signal=signals.spider_closed) #@UndefinedVariable
crawler.crawl(requestParams=requestParams)
# start crawling
reactor.run() #@UndefinedVariable
return str(items)
</code></pre>
<p>Now the problem I am facing is after making the reactor stop (which seems necessary to me since I don't want to stuck to the <code>reactor.run()</code>). I couldn't accept the further request after first request. After first request gets completed, I got the following error:</p>
<pre><code>Traceback (most recent call last):
File "c:\python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "c:\python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "c:\python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "F:\my_workspace\jobvite\jobvite\com\jobvite\web\RequestListener.py", line 38, in submitForm
reactor.run() #@UndefinedVariable
File "c:\python27\lib\site-packages\twisted\internet\base.py", line 1193, in run
self.startRunning(installSignalHandlers=installSignalHandlers)
File "c:\python27\lib\site-packages\twisted\internet\base.py", line 1173, in startRunning
ReactorBase.startRunning(self)
File "c:\python27\lib\site-packages\twisted\internet\base.py", line 684, in startRunning
raise error.ReactorNotRestartable()
ReactorNotRestartable
</code></pre>
<p>Which is obvious, since we can not restart the reactor.</p>
<p>So my questions are:</p>
<p>1) How could I provide support for the next requests to crawl? </p>
<p>2) Is there any way to move to next line after reactor.run() without stopping it?</p>
| 7 |
2016-09-11T08:52:33Z
| 39,535,459 |
<p>Here is a simple solution to your problem</p>
<pre><code>from flask import Flask
import threading
import subprocess
import sys
app = Flask(__name__)
class myThread (threading.Thread):
def __init__(self,target):
threading.Thread.__init__(self)
self.target = target
def run(self):
start_crawl()
def start_crawl():
pid = subprocess.Popen([sys.executable, "start_request.py"])
return
@app.route("/crawler/start")
def start_req():
print ":request"
threadObj = myThread("run_crawler")
threadObj.start()
return "Your crawler is in running state"
if (__name__ == "__main__"):
app.run(port = 5000)
</code></pre>
<p>In the above solution I assume that you are able to start your crawler from command line using command start_request.py file on shell/command line.</p>
<p>Now what we are doing is using threading in python to launch a new thread for each incoming request.
Now you can easily able to run your crawler instance in parallel for each hit.
Just control your number of threads using threading.activeCount()</p>
| 1 |
2016-09-16T15:45:16Z
|
[
"python",
"flask",
"scrapy",
"reactor",
"twisted.internet"
] |
Extending functionality of Element and ElementTree
| 39,434,449 |
<p>I would like to extend the functionality of <code>Element</code> and <code>ElementTree</code> classes from <code>xml.etree</code> and use them with <code>xml.etree.ElementTree.parse()</code>.</p>
<p>After a few tries, I've managed to create a solution for that problem, but I would like to know if there is a better solution or if this one has any hidden dangers.</p>
<p><strong>FooElementTree.py</strong></p>
<pre><code>import xml.etree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import ElementTree
class FooElement(Element):
def __repr__(self):
return "<FooElement %s at 0x%x>" % (repr(self.tag), id(self))
class FooElementTree(ElementTree):
pass
xml.etree.ElementTree.Element = FooElement
xml.etree.ElementTree.ElementTree = FooElementTree
from xml.etree.ElementTree import parse
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code>>>> import FooElementTree
>>> e = FooElementTree.parse('xml.cfg')
>>> e
<FooElementTree.FooElementTree object at 0x023AB650>
>>> r = e.getroot()
>>> r
<FooElement 'configuration' at 0x23c5470>
</code></pre>
| 1 |
2016-09-11T08:57:27Z
| 39,434,539 |
<p>This is the way, hot patching works. But be aware, that the patch has to be applied before any other Module (or Submodule) is imported, that uses ElementTree, too.</p>
| 0 |
2016-09-11T09:10:01Z
|
[
"python",
"xml.etree"
] |
500 Internal Server Error (trying to upload file)
| 39,434,467 |
<p>I have small app in flask was is hosted on pythonanywhere. When I try uploading a file I get 500 error. I copied the code exactly except for changing the UPLOAD_FOLDER path and ALLOWED_EXTENSIONS. Local(on my computer) all working good but on server not.</p>
<p><a href="http://pastebin.com/hWdh4VvB" rel="nofollow">Log error</a></p>
<p><a href="http://pastebin.com/riq5hKMx" rel="nofollow">My Code</a></p>
| -1 |
2016-09-11T08:59:42Z
| 39,434,930 |
<p>Looks like the problem is in <code>UPLOAD_FOLDER</code> path value.</p>
<p>Your python script complains it can't find the directory you set up for uploads. And since you set up it as:</p>
<pre><code>UPLOAD_FOLDER = 'upload/'
</code></pre>
<p>And in docs this variable has absolute path to the directory, I think, if you change <code>upload/</code> to </p>
<pre><code>UPLOAD_FOLDER = '/absolute/path/to/your/upload/directory/'
</code></pre>
<p>it would help.</p>
| 2 |
2016-09-11T10:01:58Z
|
[
"python",
"flask",
"pythonanywhere"
] |
Does Python VM cache the integer objects which cannot be released automatically?
| 39,434,547 |
<p>I have a single script as below:</p>
<pre><code>a = 999999999999999999999999999999
b = 999999999999999999999999999999
print(a is b)
</code></pre>
<p>Output is:</p>
<pre><code>[root@centos7-sim04 python]# python test2.py
True
</code></pre>
<p>On the other hand, the same code with command line:</p>
<pre><code>>>> a = 999999999999999999999999999999
>>> b = 999999999999999999999999999999
>>> print(a is b)
False
</code></pre>
<p>The output is <code>False</code>.</p>
<ul>
<li>What is the difference between the 2 ways?</li>
<li>When python script running, how does Python VM to manage the integer objects?</li>
<li>I see that the number from -5 to 256 is generated by VM automatically when VM started and VM will also assign the empty int blocks(chain struct) to avoid allocating memory frequently for large number storage.</li>
<li>Will these blocks be released automatically by python VM when memory is not enough? For my understanding, Python just keeps these blocks to avoid allocating memory frequently so that them will never be released automatically once allocated?</li>
</ul>
<p>Just test with following code:</p>
<pre><code>for i in range(1, 100000000):
pass
print("OK")
gc.collect()
time.sleep(20)
print("slept")
for i in range(1, 100000000)
pass
</code></pre>
<p>The memory is:</p>
<pre><code>PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
17351 root 20 0 3312060 3.039g 2096 S 11.3 82.4 0:03.53 python
</code></pre>
<p>Here is the result of <code>vmstat</code>:</p>
<pre><code>[root@centos7-sim04 ~]# vmstat 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 0 3376524 40 330084 0 0 2 5 25 41 0 0 100 0 0
1 0 0 185644 40 330084 0 0 0 0 714 28 14 3 82 1 0
0 0 0 967420 40 330084 0 0 0 0 292 15 7 0 93 0 0
0 0 0 967296 40 330084 0 0 0 0 20 23 0 0 100 0 0
0 0 0 967296 40 330084 0 0 0 0 15 17 0 0 100 0 0
0 0 0 967312 40 330068 0 0 0 1 27 39 0 0 100 0 0
1 0 0 185288 40 330068 0 0 0 2 701 55 17 0 83 0 0
0 0 0 3375780 40 330068 0 0 0 0 202 75 3 1 96 0 0
</code></pre>
<ul>
<li>It seems that the memory is never released. Is this right?</li>
<li>If I want to release the integer objects when memory is not enough, how can I do?</li>
</ul>
<p>Thanks a lot.</p>
| 2 |
2016-09-11T09:10:50Z
| 39,434,850 |
<p>Regarding your first question actually that because of peephole optimizer which simplifies the expressions. Which in this case it means using one integer for all equal ones. It also use this approach for interning the strings.</p>
<p>The reason that you don't see such behavior within the interactive shell is that every command executed separately and gives the corresponding result, whereas in a file or in a function (even in terminal) all the commands interpreted at once. Here is an example:</p>
<pre><code>In [1]: def func():
...: a = 9999999999999
...: b = 9999999999999
...: return a is b
...:
In [2]: func()
Out[2]: True
In [3]: a = 9999999999999
In [4]: b = 9999999999999
In [5]: a is b
Out[5]: False
</code></pre>
<p>And regarding your second question, there are plenty of misunderstanding, first off, the duty of VM in python is executing the machine code corresponding to each bytecode, while managing the integers and actually parsing the code and compiling to the bytecode is the interpreter and compiler's task. And as it mentioned as comment in your question, <code>range()</code> in python 2 returns a list while in python 3 it's a smart object that preserves the start, end and step, and is a generator like object which generated the items on demand.</p>
<p>Also about the functionality of <code>gc.collect</code>, as mentioned in <a href="https://docs.python.org/3/library/gc.html#gc.collect" rel="nofollow">documentation</a> when you don't pass an argument to it, <code>gc.collect</code> run a full collection, and:</p>
<blockquote>
<p>The free lists maintained for a number of built-in types are cleared
whenever a full collection or collection of the highest generation (2)
is run. Not all items in some free lists may be freed due to the
particular implementation, in particular float</p>
</blockquote>
| 0 |
2016-09-11T09:49:07Z
|
[
"python",
"integer"
] |
Extract data from JSON in python
| 39,434,587 |
<p>Can I access link inside <code>next</code> from the below <code>Json</code> data? I am doing in this way </p>
<pre><code>data = json.loads(html.decode('utf-8'))
for i in data['comments']:
for h in i['paging']:
print(h)
{
</code></pre>
<p>Because <code>comments</code> is a main object. Inside the <code>comments</code> there are three sub objects <code>data</code> , <code>paging</code> and <code>summary</code>. The above code is doing the same , inside <code>comments</code>, because of <code>paging</code> is an object of multiple other objects, in the loop and print that. It is giving the error</p>
<blockquote>
<p>for h in i['paging']:
TypeError: string indices must be integers </p>
</blockquote>
<pre><code> "comments": {
"data": [
{
"created_time": "2016-05-22T14:57:04+0000",
"from": {
"id": "908005352638687",
"name": "Marianela Ferrer"
},
"id": "101536081674319615443",
"message": "I love the way you talk! I can not get enough of your voice. I'm going to buy Seveneves! I'm going to read it this week. Thanks again se\u00f1or Gates. I hope you have a beautiful day:-)"
}
],
"paging": {
"cursors": {
"after": "NzQ0",
"before": "NzQ0"
},
"next": "https://graph.facebook.com/v2.7/10153608167431961/comments?access_token=xECxPrxuXbaRqcippFcrwZDZD&summary=true&limit=1&after=NzQ0"
},
"summary": {
"can_comment": true,
"order": "ranked",
"total_count": 744
}
},
"id": "10153608167431961"
}
</code></pre>
| 0 |
2016-09-11T09:16:26Z
| 39,434,634 |
<p>You're iterating through "comments" which results in three objects: <code>data</code>, <code>paging</code>, and <code>summary</code>. All you want is <code>paging</code>, but your first for-loop wants you to go through all the others.</p>
<p>Thus, when it starts with <code>data</code>, you're trying to call <code>data['paging']</code>, but this doesn't work because <code>data</code>'s value is a list and not a dictionary.</p>
<p>You want to immediately access <code>paging</code>:</p>
<pre><code>print data['comments']['paging']['next']
</code></pre>
| 1 |
2016-09-11T09:21:54Z
|
[
"python",
"json"
] |
Why do I get this TypeError?
| 39,434,606 |
<p>I believe this error means I can't include a variable in a loop however I am struggling to see a way around....</p>
<p>the error is </p>
<pre><code>TypeError: range() integer end argument expected, got unicode.
</code></pre>
<p>The problem the book tried to ask me is: </p>
<blockquote>
<p>Try wring a program the will prompt for an number and print the correct times table (up to 12).</p>
</blockquote>
<p>This is my code:</p>
<pre><code>def main():
pass
choice = raw_input("Which times table would you like")
print ("This is the", choice , "'s times table to 12")
var1 = choice*12 + 1
for loopCounter in range (0,var1,choice):
print(loopCounter)
if __name__ == '__main__':
main()
</code></pre>
<p>Any suggestions? thanks in advance.</p>
| 1 |
2016-09-11T09:19:02Z
| 39,434,667 |
<p>The <code>raw_input</code> function gives you a <em>string,</em> not an integer. If you want it as an integer (such as if you want to multiply it by twelve or use it in that <code>range</code> call), you need something such as:</p>
<pre><code>choice = int(raw_input("Which times table would you like"))
</code></pre>
<p>There are potential issues with this simplistic solution (e.g., what happens when what you enter is <em>not</em> a number), but this should be enough to get past your current problem.</p>
| 1 |
2016-09-11T09:25:50Z
|
[
"python",
"python-2.7"
] |
Why do I get this TypeError?
| 39,434,606 |
<p>I believe this error means I can't include a variable in a loop however I am struggling to see a way around....</p>
<p>the error is </p>
<pre><code>TypeError: range() integer end argument expected, got unicode.
</code></pre>
<p>The problem the book tried to ask me is: </p>
<blockquote>
<p>Try wring a program the will prompt for an number and print the correct times table (up to 12).</p>
</blockquote>
<p>This is my code:</p>
<pre><code>def main():
pass
choice = raw_input("Which times table would you like")
print ("This is the", choice , "'s times table to 12")
var1 = choice*12 + 1
for loopCounter in range (0,var1,choice):
print(loopCounter)
if __name__ == '__main__':
main()
</code></pre>
<p>Any suggestions? thanks in advance.</p>
| 1 |
2016-09-11T09:19:02Z
| 39,434,673 |
<p>Your program will run with a few changes.</p>
<pre><code>def main():
pass
choice = input("Which times table would you like")
print ("This is the " + choice + "'s times table to 12")
var1 = int(choice)*12 + 1
for loopCounter in range (0,var1,int(choice)):
print(loopCounter)
if __name__ == '__main__':
main()
</code></pre>
<p>Now you may want to adjust it more so that you get the correct output, the above will compile and run. </p>
| -1 |
2016-09-11T09:26:53Z
|
[
"python",
"python-2.7"
] |
Why do I get this TypeError?
| 39,434,606 |
<p>I believe this error means I can't include a variable in a loop however I am struggling to see a way around....</p>
<p>the error is </p>
<pre><code>TypeError: range() integer end argument expected, got unicode.
</code></pre>
<p>The problem the book tried to ask me is: </p>
<blockquote>
<p>Try wring a program the will prompt for an number and print the correct times table (up to 12).</p>
</blockquote>
<p>This is my code:</p>
<pre><code>def main():
pass
choice = raw_input("Which times table would you like")
print ("This is the", choice , "'s times table to 12")
var1 = choice*12 + 1
for loopCounter in range (0,var1,choice):
print(loopCounter)
if __name__ == '__main__':
main()
</code></pre>
<p>Any suggestions? thanks in advance.</p>
| 1 |
2016-09-11T09:19:02Z
| 39,434,678 |
<p>This error just means that it got a unicode value when an integer was assumed.
That happens because you use <code>raw_input</code> for <code>choice</code>.</p>
<p>Edit: <code>raw_input</code> does not interpret your input. <code>input</code> does. </p>
| 0 |
2016-09-11T09:27:23Z
|
[
"python",
"python-2.7"
] |
Setting elements to None in pandas dataframe
| 39,434,733 |
<p>I'm not sure why this happens</p>
<pre><code>>>> df = pd.DataFrame(np.arange(15).reshape(5,3),columns=list('ABC'))
>>> df
A B C
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
4 12 13 14
</code></pre>
<p>Assign <code>None</code> to elements in last row turns it into <code>NaN NaN NaN</code>:</p>
<pre><code>>>> df.ix[5,:] = None
>>> df
A B C
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
4 12 13 14
5 NaN NaN NaN
</code></pre>
<p>Change two element in last column to 'nan'</p>
<pre><code>>>> df.ix[:1,2] = 'nan'
>>> df
A B C
0 0 1 nan
1 3 4 nan
2 6 7 8
3 9 10 11
4 12 13 14
5 NaN NaN NaN
</code></pre>
<p>Now last row becomes <code>NaN NaN None</code></p>
<pre><code>>>> df.ix[5,:] = None
>>> df
A B C
0 0 1 nan
1 3 4 nan
2 6 7 8
3 9 10 11
4 12 13 14
5 NaN NaN None
</code></pre>
| 1 |
2016-09-11T09:34:54Z
| 39,434,877 |
<p>It's because your dtypes are being changed after each assignment:</p>
<pre><code>In [7]: df = pd.DataFrame(np.arange(15).reshape(5,3),columns=list('ABC'))
In [8]: df.dtypes
Out[8]:
A int32
B int32
C int32
dtype: object
In [9]: df.ix[5,:] = None
In [10]: df.dtypes
Out[10]:
A float64
B float64
C float64
dtype: object
In [11]: df.ix[:1,2] = 'nan'
</code></pre>
<p>after that last assignment the <code>C</code> column has been implicitly converted to <code>object</code> (string) dtype:</p>
<pre><code>In [12]: df.dtypes
Out[12]:
A float64
B float64
C object
dtype: object
</code></pre>
<p><a href="http://stackoverflow.com/questions/39434733/setting-elements-to-none-in-pandas-dataframe/39434877#comment66192432_39434877">@ayhan has written very neat answer as a comment</a>:</p>
<blockquote>
<p>I think the main reason is for numerical columns, when you insert None
or np.nan, it is converted to np.nan to have a Series of type float.
For objects, it takes whatever is passed (if None, it uses None; if
np.nan, it uses np.nan -
<a href="http://pandas.pydata.org/pandas-docs/stable/missing_data.html#inserting-missing-data" rel="nofollow">docs</a>)</p>
<p>(c) <a href="http://stackoverflow.com/users/2285236/ayhan">ayhan</a></p>
</blockquote>
<p>Here is a corresponding demo:</p>
<pre><code>In [39]: df = pd.DataFrame(np.arange(15).reshape(5,3),columns=list('ABC'))
In [40]: df.ix[4, 'A'] = None
In [41]: df.ix[4, 'C'] = np.nan
In [42]: df
Out[42]:
A B C
0 0.0 1 2.0
1 3.0 4 5.0
2 6.0 7 8.0
3 9.0 10 11.0
4 NaN 13 NaN
In [43]: df.dtypes
Out[43]:
A float64
B int32
C float64
dtype: object
In [44]: df.ix[0, 'C'] = 'a string'
In [45]: df
Out[45]:
A B C
0 0.0 1 a string
1 3.0 4 5
2 6.0 7 8
3 9.0 10 11
4 NaN 13 NaN
In [46]: df.dtypes
Out[46]:
A float64
B int32
C object
dtype: object
</code></pre>
<p>now we can use both <code>None</code> and <code>np.nan</code> for the <code>object</code> dtype:</p>
<pre><code>In [47]: df.ix[1, 'C'] = None
In [48]: df.ix[2, 'C'] = np.nan
In [49]: df
Out[49]:
A B C
0 0.0 1 a string
1 3.0 4 None
2 6.0 7 NaN
3 9.0 10 11
4 NaN 13 NaN
</code></pre>
| 2 |
2016-09-11T09:53:10Z
|
[
"python",
"pandas",
"dataframe"
] |
How to change element class attribute value using selenium
| 39,434,821 |
<p>I lost my credentials.. so I'm creating this new thread. The old question it here if it helps: <a href="http://stackoverflow.com/questions/39424703/how-to-click-a-button-to-vote-with-python">How to click a button to vote with python</a></p>
<p>I'd like to change this line:</p>
<pre><code><a data-original-title="I&nbsp;like&nbsp;this&nbsp;faucet" href="#" class="vote-link up" data-faucet="39274" data-vote="up" data-toggle="tooltip" data-placement="top" title=""><span class="glyphicon glyphicon-thumbs-up"></span></a>
</code></pre>
<p>to this:</p>
<pre><code><a data-original-title="I&nbsp;like&nbsp;this&nbsp;faucet" href="#" class="vote-link up voted" data-faucet="39274" data-vote="up" data-toggle="tooltip" data-placement="top" title=""><span class="glyphicon glyphicon-thumbs-up"></span></a>
</code></pre>
<p>So that the vote is set changing <code>vote-link up</code> to <code>vote-link up voted</code>.</p>
<p>But the problem is that in that site, there are severals items to vote, and the element "data-faucet" changes. If I use this script:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get("linkurl")
element = driver.find_element_by_css_selector(".vote-link.up")
element_attribute_value = element.get_attribute("data-faucet")
if element_attribute_value == "39274":
print ("Value: {0}".format(element_attribute_value))
driver.quit()
</code></pre>
<p>But it obsiusly doesn't print anything, cause the first attribute value has another number. How can I select my line with the input of the number of <code>data-faucet</code> element, so I can replace it with <code>vote-link up voted</code>?</p>
<p>I only can do this selenium? Is there another way without using a real browser?</p>
<p>Anyway, this is the structure of the webpage:</p>
<pre><code><html>
<head></head>
<body role="document">
<div id="static page" class="container-fluid">
<div id="page" class="row"></div>
<div id="faucets-list">
<tbody>
<tr class=""></tr>
<tr class=""></tr>
<tr class=""></tr>
<tr class=""></tr>
# an infinite number of nodes, until there's mine
<tr class="">
<td class="vote-col">
<div class="vote-box">
<div class="vote-links">
<a class="vote-link up" data-original-title="I like this faucet" href="#" data-faucet"39274" data-vote"up" data-toggle"tooltip" data-placement="top" title=""></a>
</code></pre>
<p>The site is this: <a href="https://faucetbox.com/en/list/BTC" rel="nofollow">https://faucetbox.com/en/list/BTC</a></p>
| 1 |
2016-09-11T09:44:39Z
| 39,439,119 |
<p>From comments:-</p>
<blockquote>
<p>Do you want to interact with element which has <code>data-faucet</code> attribute value <code>39274</code>??</p>
<p>exatly! just what I want to do!</p>
</blockquote>
<p>You should try using <code>css_selector</code> as below :-</p>
<pre><code>element = driver.find_element_by_css_selector(".vote-link.up[data-faucet = '39274']")
</code></pre>
<blockquote>
<p>ok.. now it selects something in fact if I print(element) terminal shows: <code><selenium.webdriver.remote.webelement.WebElement (session="d54ae232-6d42-455f-a130-097be89adf1e", element="{96385594-1725-4843-bfed-d5a4e7b9af41}")>.</code> so now that I've selected it, how can I replace "vote-link up" with "vote-link up voted"?</p>
</blockquote>
<p>You can replace <code>class</code> attribute value using <code>execute_script()</code> as below :-</p>
<pre><code>driver.execute_script("arguments[0].setAttribute('class','vote-link up voted')", element)
</code></pre>
| 0 |
2016-09-11T18:05:50Z
|
[
"python",
"python-3.x",
"selenium",
"selenium-webdriver",
"css-selectors"
] |
Why is sklearn's Perceptron predicting with accuracy, precision etc. of 1?
| 39,434,858 |
<p>I am using sklearn.linear_model.Perceptron on a synthetic dataset I created. The data consists of 2 classes each of which is a multivariate Gaussian with a common non-diagonal covariance matrix. The centroids of the classes are close enough that there is significant overlap. </p>
<pre><code>mean1 = np.ones((20,))
mean2 = 2 * np.ones((20,))
A = 0.1 * np.random.randn(20,20)
cov = np.dot(A, A.T)
class1 = np.random.multivariate_normal(mean1, cov, 2000)
class2 = np.random.multivariate_normal(mean2, cov, 2000)
class1 = np.concatenate((class1, np.ones((len(class1), 1))), axis=1)
class2 = np.concatenate((class2, 2*np.ones((len(class2), 1))), axis=1)
class1_train, class1_test = train_test_split(class1, test_size=0.3)
class2_train, class2_test = train_test_split(class2, test_size=0.3)
train = np.concatenate((class1_train, class2_train), axis=0)
test = np.concatenate((class1_test, class2_test), axis=0)
np.random.shuffle(train)
np.random.shuffle(test)
y_train = train[:,20]
x_train = train[:,0:20]
y_test = test[:,20]
x_test = test[:,0:20]
</code></pre>
<p>After saving this data, I just used :</p>
<pre><code>classifier = sklearn.linear_model.Perceptron()
classifier.fit(x_train, y_train)
predicted_test = classifier.predict(x_test)
accuracy = sklearn.metrics.accuracy_score(y_test, predicted_test)
precision = sklearn.metrics.precision_score(y_test, predicted_test)
recall = sklearn.metrics.recall_score(y_test, predicted_test)
f_measure = sklearn.metrics.f1_score(y_test, predicted_test)
print(accuracy, precision, recall, f_measure)
</code></pre>
<p>The data is overlapping by design. But yet the linear classifier is able to predict perfectly somehow with accuracy, precision etc. all being 1.</p>
| 1 |
2016-09-11T09:50:40Z
| 39,436,473 |
<p>The correct way of using <code>cross_validation.train_test_split</code> is to give it the complete dataset, and letting it partition the data to <code>x_train, x_test, y_train, y_test</code>.</p>
<p>The following code works better:</p>
<pre><code>class1 = np.random.multivariate_normal(mean1, cov, 2000)
class2 = np.random.multivariate_normal(mean2, cov, 2000)
class1 = np.concatenate((class1, np.ones((len(class1), 1))), axis=1)
class2 = np.concatenate((class2, 2*np.ones((len(class2), 1))), axis=1)
dataset = np.concatenate((class1, class2), axis=0)
np.random.shuffle(dataset)
x_train, x_test, y_train, y_test = \
cross_validation.train_test_split(dataset[:,:20], dataset[:,20], test_size=0.3)
</code></pre>
<p>Notice that the Perceptron can actually acheive 100% accuracy with your data. Try adding some noise to it, in order to get a feeling of it.</p>
<p>For instance:</p>
<pre><code>noise = np.random.normal(0,1,(4000, 20))
dataset[:, 0:20] = dataset[:, 0:20] + noise
x_train, x_test, y_train, y_test = \
cross_validation.train_test_split(dataset[:,:20], dataset[:,20], test_size=0.3)
</code></pre>
| -1 |
2016-09-11T13:12:23Z
|
[
"python",
"scikit-learn"
] |
Youtube-dl python module missing ffprobe or avprobe
| 39,434,894 |
<p>I am just trying to run the example of converting youtube videos to mp3.
Here is the code: </p>
<pre><code>from __future__ import unicode_literals
import youtube_dl
def my_hook(d):
if d['status'] == 'finished':
print('Done downloading, now converting ...')
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'progress_hooks': [my_hook],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/watch?v=GwR3pWbKaLE'])
</code></pre>
<p>But I keep getting this error:</p>
<pre><code>youtube_dl.utils.DownloadError: ERROR: ffprobe or avprobe not found. Please install one.
</code></pre>
<p>So I tried placing the <code>ffprobe.exe</code> and <code>avprobe.exe</code> in the youtube_dl directory. Still I get the same error.
Any idea on how to make the conversion work?</p>
| 0 |
2016-09-11T09:56:05Z
| 39,589,158 |
<p>You must placed ffmpeg.exe and ffprobe.exe into your youtube-dl project directory root. This works fine.</p>
| 0 |
2016-09-20T08:28:14Z
|
[
"python",
"youtube",
"youtube-dl",
"ffprobe",
"avprobe"
] |
Sort certain rows in Data Frames by columns
| 39,434,933 |
<p>I have a dataframe that is unsorted. I want to sort columns <code>A</code>,<code>B</code>,<code>C</code> and <code>D</code> in descending order (largest to smallest) however they must remain in the denomination group. For example, it should sort denomination 100 by columns <code>A</code>,<code>B</code>,<code>C</code> and <code>D</code> so hence the row 0,1,2 changes to 0,2,1. </p>
<pre><code>Index Denomination A B C D
0 100 5 0 0 0
1 100 0 0 1 0
2 100 0 2 0 0
3 200 5 2 0 0
4 200 5 0 1 0
5 200 0 4 0 0
6 200 10 0 0 0
7 200 0 2 1 0
8 200 0 0 2 0
</code></pre>
<p>The order of sorting levels must be <code>A</code>,<code>B</code>,<code>C</code> and then <code>D</code>. Relabeling <code>Index</code> is not important.
The resulting dataframe should be:</p>
<pre><code>Index Denomination A B C D
0 100 5 0 0 0
2 100 0 2 0 0
1 100 0 0 1 0
6 200 10 0 0 0
3 200 5 2 0 0
4 200 5 0 1 0
5 200 0 4 0 0
7 200 0 2 1 0
8 200 0 0 2 0
</code></pre>
<p>This can be done in excel by selecting the rows and then applying a custom sort but I need it to be done in python using dataframes.</p>
| 1 |
2016-09-11T10:02:50Z
| 39,434,976 |
<p>This should do it:</p>
<pre><code>df.sort_values(by=['Denomination', 'A', 'B', 'C', 'D'],
ascending=[True, False, False, False, False])
Out:
Denomination A B C D
0 100 5 0 0 0
2 100 0 2 0 0
1 100 0 0 1 0
6 200 10 0 0 0
3 200 5 2 0 0
4 200 5 0 1 0
5 200 0 4 0 0
7 200 0 2 1 0
8 200 0 0 2 0
</code></pre>
<p>Sorts by <code>Denomination</code> in ascending order; in case of ties, it sorts by <code>A</code> in descending order; in case of ties, it sorts by <code>B</code> in descending order and so on.</p>
<p>If the Denomination column shouldn't be sorted but should be left in the order of appearence for groups, you can do something like this:</p>
<pre><code>df.groupby('Denomination')['Denomination'].transform(pd.Series.first_valid_index)
Out:
0 0
1 0
2 0
3 3
4 3
5 3
6 3
7 3
8 3
Name: Denomination, dtype: int64
</code></pre>
<p>This returns a new column to keep track of the groups. You can add this column to the DataFrame and it can have the highest priority.</p>
<pre><code>(df.assign(denomination_group =
df.groupby('Denomination')['Denomination'].transform(pd.Series.first_valid_index))
.sort_values(by=['denomination_group', 'A', 'B', 'C', 'D'],
ascending=[True, False, False, False, False])
.drop('denomination_group', axis=1))
</code></pre>
| 3 |
2016-09-11T10:07:58Z
|
[
"python",
"sorting",
"pandas",
"dataframe"
] |
Django rest_framework IsAdminUser not behaving
| 39,434,937 |
<p>I have a <code>viewset</code> in rest framework that is not behaving like I would expect. If I login with a non-staff user and navigate to the api-url/users I can see all the users listed there. </p>
<p>The <code>IsAuthenticated</code> permission is working, because if I logout I get an error saying that I am not authenticated. </p>
<p>Am I using these permissions wrong? I have done the tutorial and looked through the docs, but I can't find anything to tell me why this shouldn't work</p>
<p>views:</p>
<pre><code>class UserViewSet(viewsets.ModelViewSet):
"""Viewset for viewing users. Only to be used by admins"""
queryset = LangaLangUserProfile.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.DjangoFilterBackend, )
filter_fields = '__all__'
permissions_classes = (permissions.IsAdminUser, )
class LanguageViewSet(viewsets.ReadOnlyModelViewSet):
"""Viewset for Language objects, use the proper HTTP methods to modify them"""
queryset = Language.objects.all()
serializer_class = LanguageSerializer
filter_backends = (filters.DjangoFilterBackend, )
filter_fields = '__all__'
permissions_classes = (permissions.IsAuthenticated, )
</code></pre>
<p>urls:</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'language', views.LanguageViewSet)
</code></pre>
<p>serializers:</p>
<pre><code>class UserSerializer(serializers.ModelSerializer):
"""Serializer for User objects"""
class Meta:
model = LangaLangUserProfile
fields = '__all__'
class LanguageSerializer(serializers.ModelSerializer):
"""Serializer for the Language model"""
class Meta:
model = Language
fields = '__all__'
depth = 2
</code></pre>
| 0 |
2016-09-11T10:03:15Z
| 39,434,975 |
<p>Typo!</p>
<p>It's <a href="http://www.django-rest-framework.org/api-guide/permissions/" rel="nofollow"><code>permission_classes</code></a>, not <code>permissions_classes</code>.</p>
<hr>
<p>About this part:</p>
<blockquote>
<p>The IsAuthenticated permission is working, because if I logout I cget an error saysing that I am not authenticated.</p>
</blockquote>
<p>I'm not sure why this is happening but I'd blame <code>DEFAULT_PERMISSION_CLASSES</code> in your Django settings - maybe you have <code>IsAuthenticated</code> specified there?</p>
| 1 |
2016-09-11T10:07:56Z
|
[
"python",
"django",
"django-rest-framework"
] |
AttributeError: 'Timestamp' object has no attribute 'timestamp
| 39,434,979 |
<p>While converting a <code>panda</code> object to a timestamp, I am facing this strange issue.</p>
<p>Train['date'] value is like <code>01/05/2014</code> which I am trying to convert into linuxtimestamp.</p>
<p>My code:</p>
<pre><code>Train = pd.read_csv("data.tsv", sep='\t') # use TAB as column separator
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
</code></pre>
<p>And I get this error:</p>
<pre><code>Traceback (most recent call last):
File "socratis.py", line 11, in <module>
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
File "/home/ubuntu/.local/lib/python2.7/site-packages/pandas/core/series.py", line 2220, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas/src/inference.pyx", line 1088, in pandas.lib.map_infer (pandas/lib.c:62658)
File "socratis.py", line 11, in <lambda>
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
AttributeError: 'Timestamp' object has no attribute 'timestamp'
</code></pre>
| 0 |
2016-09-11T10:08:36Z
| 39,435,091 |
<p>The method to_datetime will return a <code>TimeStamp</code> instance. I'm not sure what you are hoping to accomplish by the lambda function, but it appears you are trying to convert some object to a <code>TimeStamp</code>. </p>
<p>Try removing the apply section so it looks like this:</p>
<p><code>Train['timestamp'] = pd.to_datetime(Train['date'])</code></p>
| 0 |
2016-09-11T10:25:13Z
|
[
"python",
"time",
"timestamp"
] |
AttributeError: 'Timestamp' object has no attribute 'timestamp
| 39,434,979 |
<p>While converting a <code>panda</code> object to a timestamp, I am facing this strange issue.</p>
<p>Train['date'] value is like <code>01/05/2014</code> which I am trying to convert into linuxtimestamp.</p>
<p>My code:</p>
<pre><code>Train = pd.read_csv("data.tsv", sep='\t') # use TAB as column separator
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
</code></pre>
<p>And I get this error:</p>
<pre><code>Traceback (most recent call last):
File "socratis.py", line 11, in <module>
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
File "/home/ubuntu/.local/lib/python2.7/site-packages/pandas/core/series.py", line 2220, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas/src/inference.pyx", line 1088, in pandas.lib.map_infer (pandas/lib.c:62658)
File "socratis.py", line 11, in <lambda>
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
AttributeError: 'Timestamp' object has no attribute 'timestamp'
</code></pre>
| 0 |
2016-09-11T10:08:36Z
| 39,679,056 |
<p>You're looking for <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp" rel="nofollow"><code>datetime.timestamp()</code></a>, which was added in Python 3.3. Pandas itself isn't involved.</p>
<blockquote>
<p><em>N.B.</em> <code>.timestamp()</code> will localize naive timestamps to the computer's UTC offset. To the contrary, suggestions in this answer are timezone-agnostic.</p>
</blockquote>
<p>Since pandas <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#timestamp-limitations" rel="nofollow">uses nanoseconds internally</a> (numpy <a href="http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html#datetime-units" rel="nofollow">datetime64[ns]</a>), you should be able to do this even with Python 2:</p>
<pre><code>Train['timestamp'] = pd.to_datetime(Train['date']).value / 1e9
</code></pre>
<p>Or be more explicit wtih something like this (from the datetime docs):</p>
<pre><code>import pandas as pd
from datetime import datetime, timedelta
def posix_time(dt):
return (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Train['timestamp'] = pd.to_datetime(Train['date']).apply(posix_time)
</code></pre>
| 0 |
2016-09-24T17:26:54Z
|
[
"python",
"time",
"timestamp"
] |
Comparing by section two numpy arrays in python and displays the index column which is not the same
| 39,434,996 |
<p>I want to show you where the index column of the array is not the same.</p>
<pre><code>import numpy as np
array1 = np.array(list(np.zeros(10))+list(np.ones(10)))
array2 = np.array(list(np.random.randint(2, size=10))+list(np.random.randint(2, size=10)))
matches = array1 == array2
section_sums = np.bincount(np.arange(matches.size)//10,matches)
att = int(section_sums[0])
att2 = int(section_sums[1])
print section_sums
print 'first 10 : '+ str(att)
print 'second 10 : '+ str(att2)
</code></pre>
<p>example:</p>
<pre><code>Array1:
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
Array2:
[ 0. 1. 0 . 1. 1. 1. 0. 1. 0. 1. 1. 1. 1. 0. 1. 0. 1. 1. 1. 0.]
</code></pre>
<p>I want the output:</p>
<pre><code>in section 1 index is not the same: 2,4,5,6,8,10
in section 2 index is not the same: 4,6,10
</code></pre>
| 0 |
2016-09-11T10:11:38Z
| 39,435,090 |
<p>Here's an approach -</p>
<pre><code>idx = np.flatnonzero(~matches)
cut_idx = np.unique(idx//10,return_index=True)[1]
out = np.split(np.mod(idx,10)+1,cut_idx)[1:]
</code></pre>
<p>Sample run for the given input arrays -</p>
<pre><code>In [182]: matches = array1 == array2
...: idx = np.flatnonzero(~matches)
...: cut_idx = np.unique(idx//10,return_index=True)[1]
...: out = np.split(np.mod(idx,10)+1,cut_idx)[1:]
...:
In [183]: out
Out[183]: [array([ 2, 4, 5, 6, 8, 10]), array([ 4, 6, 10])]
</code></pre>
| 0 |
2016-09-11T10:24:51Z
|
[
"python",
"arrays",
"python-2.7",
"numpy"
] |
Comparing by section two numpy arrays in python and displays the index column which is not the same
| 39,434,996 |
<p>I want to show you where the index column of the array is not the same.</p>
<pre><code>import numpy as np
array1 = np.array(list(np.zeros(10))+list(np.ones(10)))
array2 = np.array(list(np.random.randint(2, size=10))+list(np.random.randint(2, size=10)))
matches = array1 == array2
section_sums = np.bincount(np.arange(matches.size)//10,matches)
att = int(section_sums[0])
att2 = int(section_sums[1])
print section_sums
print 'first 10 : '+ str(att)
print 'second 10 : '+ str(att2)
</code></pre>
<p>example:</p>
<pre><code>Array1:
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
Array2:
[ 0. 1. 0 . 1. 1. 1. 0. 1. 0. 1. 1. 1. 1. 0. 1. 0. 1. 1. 1. 0.]
</code></pre>
<p>I want the output:</p>
<pre><code>in section 1 index is not the same: 2,4,5,6,8,10
in section 2 index is not the same: 4,6,10
</code></pre>
| 0 |
2016-09-11T10:11:38Z
| 39,435,098 |
<p>If you split your arrays into the two section then you can compare them.</p>
<pre><code>In [18]: a = np.array(np.split(a, [10]))
In [19]: b = np.array(np.split(b, [10]))
In [23]: ind, items = np.where(a != b)
In [25]: items[ind==0] + 1
Out[25]: array([ 2, 4, 5, 6, 8, 10])
In [26]: items[ind==1] + 1
Out[26]: array([ 4, 6, 10])
</code></pre>
| 1 |
2016-09-11T10:25:48Z
|
[
"python",
"arrays",
"python-2.7",
"numpy"
] |
python list comprehension to create repeated value from the list
| 39,435,027 |
<p>I am trying to create </p>
<pre><code>[ x
for x in [1,2,3]
for y in [3,1,4] ]
</code></pre>
<p>Output:</p>
<pre><code>[1, 1, 1, 2, 2, 2, 3, 3, 3]
</code></pre>
<p>but what I want is to create </p>
<ul>
<li>1 3 times </li>
<li>2 1 times </li>
<li>3 4 times</li>
</ul>
<p><strong>Expected Output:</strong> </p>
<pre><code>[1, 1, 1, 2, 3, 3, 3, 3]
</code></pre>
<p>Is it possible to do this in list comprehension ? </p>
| 0 |
2016-09-11T10:16:11Z
| 39,435,040 |
<p>Use the <a href="https://docs.python.org/3/library/functions.html#zip"><code>zip()</code> function</a> to pair up your numbers with their counts:</p>
<pre><code>numbers = [1, 2, 3]
counts = [3, 1, 4]
output = [n for n, c in zip(numbers, counts) for _ in range(c)]
</code></pre>
| 5 |
2016-09-11T10:17:44Z
|
[
"python",
"list"
] |
python list comprehension to create repeated value from the list
| 39,435,027 |
<p>I am trying to create </p>
<pre><code>[ x
for x in [1,2,3]
for y in [3,1,4] ]
</code></pre>
<p>Output:</p>
<pre><code>[1, 1, 1, 2, 2, 2, 3, 3, 3]
</code></pre>
<p>but what I want is to create </p>
<ul>
<li>1 3 times </li>
<li>2 1 times </li>
<li>3 4 times</li>
</ul>
<p><strong>Expected Output:</strong> </p>
<pre><code>[1, 1, 1, 2, 3, 3, 3, 3]
</code></pre>
<p>Is it possible to do this in list comprehension ? </p>
| 0 |
2016-09-11T10:16:11Z
| 39,435,045 |
<p>Sure, with <code>zip</code>:</p>
<pre><code>>>> [item for x,y in zip([1,2,3], [3,1,4]) for item in [x]*y]
[1, 1, 1, 2, 3, 3, 3, 3]
</code></pre>
| 2 |
2016-09-11T10:18:12Z
|
[
"python",
"list"
] |
python list comprehension to create repeated value from the list
| 39,435,027 |
<p>I am trying to create </p>
<pre><code>[ x
for x in [1,2,3]
for y in [3,1,4] ]
</code></pre>
<p>Output:</p>
<pre><code>[1, 1, 1, 2, 2, 2, 3, 3, 3]
</code></pre>
<p>but what I want is to create </p>
<ul>
<li>1 3 times </li>
<li>2 1 times </li>
<li>3 4 times</li>
</ul>
<p><strong>Expected Output:</strong> </p>
<pre><code>[1, 1, 1, 2, 3, 3, 3, 3]
</code></pre>
<p>Is it possible to do this in list comprehension ? </p>
| 0 |
2016-09-11T10:16:11Z
| 39,435,064 |
<p>I'm you could also use <code>np.repeat</code> if you fine with an array as a results</p>
<pre><code>import numpy as np
np.repeat([1, 2, 3] ,[3, 1, 4])
</code></pre>
| 1 |
2016-09-11T10:21:35Z
|
[
"python",
"list"
] |
Ranking tweets from most relevant to least relevant in a document using Python
| 39,435,110 |
<p>I have a document with, say, 15 tweets. Given a query, how can we rank the tweets from most relevant to the query to least relevant?</p>
<p>That is, let D be the document containing 15 tweets:</p>
<pre><code>D = ['Tweet 1', 'Tweet 2' ..... 'Tweet 15']
Q = "some noun phrase"
</code></pre>
<p>Given Q, what method we can use for ranking the tweets from most relevant to least relevant?</p>
<p>All tweets are similar and belong to the same topic.
Can I use <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow">tf-idf</a> (it's a bad idea, I think), topic modelling?</p>
| -3 |
2016-09-11T10:27:04Z
| 39,435,161 |
<p>It can be on the basis of how many words contained in the tweet are contained on the tweet topic. If they are on the same topic or the top topic, ranking should be a good idea.</p>
| 0 |
2016-09-11T10:34:46Z
|
[
"python",
"python-2.7",
"tf-idf",
"topic-modeling"
] |
Ranking tweets from most relevant to least relevant in a document using Python
| 39,435,110 |
<p>I have a document with, say, 15 tweets. Given a query, how can we rank the tweets from most relevant to the query to least relevant?</p>
<p>That is, let D be the document containing 15 tweets:</p>
<pre><code>D = ['Tweet 1', 'Tweet 2' ..... 'Tweet 15']
Q = "some noun phrase"
</code></pre>
<p>Given Q, what method we can use for ranking the tweets from most relevant to least relevant?</p>
<p>All tweets are similar and belong to the same topic.
Can I use <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow">tf-idf</a> (it's a bad idea, I think), topic modelling?</p>
| -3 |
2016-09-11T10:27:04Z
| 39,435,469 |
<p>Yoe need <a href="http://www.nltk.org"" rel="nofollow">nltk</a> (Natural Language Toolkit) libery. There is built-in function which count tf-idf</p>
| 0 |
2016-09-11T11:13:20Z
|
[
"python",
"python-2.7",
"tf-idf",
"topic-modeling"
] |
Python version conflicts and pip3
| 39,435,176 |
<p>It is a tough situation I am dealing with. Here is short version of my problem:</p>
<ul>
<li>I am working on Ubuntu 12.04</li>
<li>I would like to install <code>Python 3.5.x</code> with <code>openCV</code> library. I would also like to use <code>pip3</code> for managing package installation of python. </li>
</ul>
<p><strong>Here is how the version of my pythons looks like</strong></p>
<pre><code> $ python --version
Python 2.7.3
$ python3 --version
Python 3.5.2
</code></pre>
<p>So far it looks I have achieved my goal.</p>
<p><strong>When I use <code>virtualenv</code> to manage <code>python3</code> libraries:</strong></p>
<pre><code> virtualenv -p /usr/bin/python3 py3env
source py3env/bin/activate
</code></pre>
<p>I see the version of my python as follows:</p>
<pre><code> (py3env)yxxxxa@yxxxxa-Precision-M4800:~$ python3 --version
Python 3.2.3
</code></pre>
<p>I seems there is another version of python in my machine <code>3.2.3</code> messing up with the version <code>3.5.2</code> that I have installed. This is my first problem.</p>
<p><strong>The second related problem is that I am unable to install <code>pip 3</code>. There is this error I receive due to the same python version conflict:</strong></p>
<pre><code> $ pip
/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/_vendor /pkg_resources/__init__.py:80: UserWarning: Support for Python 3.0-3.2 has been dropped. Future versions will fail here.
warnings.warn(msg)
Traceback (most recent call last):
File "/usr/local/bin/pip", line 9, in <module>
load_entry_point('pip==8.1.2', 'console_scripts', 'pip')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 337, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2280, in load_entry_point
return ep.load()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1990, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/__init__.py", line 16, in <module>
from pip.vcs import git, mercurial, subversion, bazaar # noqa
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/vcs/mercurial.py", line 9, in <module>
from pip.download import path_to_url
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/download.py", line 36, in <module>
from pip.utils.ui import DownloadProgressBar, DownloadProgressSpinner
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/utils/ui.py", line 15, in <module>
from pip._vendor.progress.bar import Bar, IncrementalBar
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/_vendor/progress/bar.py", line 48
empty_fill = u'â'
^
SyntaxError: invalid syntax
yasharatena@yasharatena-Precision-M4800:~$ pip3
/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/_vendor/pkg_resources/__init__.py:80: UserWarning: Support for Python 3.0-3.2 has been dropped. Future versions will fail here.
warnings.warn(msg)
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 9, in <module>
load_entry_point('pip==8.1.2', 'console_scripts', 'pip3')()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 337, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2280, in load_entry_point
return ep.load()
File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1990, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/__init__.py", line 16, in <module>
from pip.vcs import git, mercurial, subversion, bazaar # noqa
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/vcs/mercurial.py", line 9, in <module>
from pip.download import path_to_url
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/download.py", line 36, in <module>
from pip.utils.ui import DownloadProgressBar, DownloadProgressSpinner
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/utils/ui.py", line 15, in <module>
from pip._vendor.progress.bar import Bar, IncrementalBar
File "/usr/local/lib/python3.2/dist-packages/pip-8.1.2-py3.2.egg/pip/_vendor/progress/bar.py", line 48
empty_fill = u'â'
^
SyntaxError: invalid syntax
</code></pre>
<p>What are your expert opinions about the stated problem? Any cool idea to handle this? Thanks alot in advance</p>
| 0 |
2016-09-11T10:36:18Z
| 39,474,390 |
<blockquote>
<p>This solved my first problem. Now the second problem aslo remains, how
can I install pip3 under python 3.5.2 (preferably using viretualenv) ?</p>
</blockquote>
<p>Here is answer:</p>
<pre><code>python3 -m virtualenv py3env
source py3env/bin/activate
</code></pre>
<p>Python 3.5 should have pip by default, also after above commands You can use pip:) </p>
<p>For example :</p>
<pre><code>python -m pip install requests
</code></pre>
<p>EDIT:</p>
<p><a href="http://stackoverflow.com/questions/6587507/how-to-install-pip-with-python-3">Here</a> You could find very good explainations if You still need install pip after create virtualenv.</p>
| 1 |
2016-09-13T15:59:49Z
|
[
"python",
"python-3.x",
"pip"
] |
Plotting 2 data sets in 1 graph + linear regression in MATPLOTLIB
| 39,435,177 |
<p>I'm new to Python and have any programming background..
I'm trying to plot 2 data sets of y for the same x data set, linear regress it using scipy and get the R^2 value. This is how i've gotten so far:</p>
<pre><code>import matplotlib
import matplotlib.pyplot as pl
from scipy import stats
#first order
'''sin(Îθ)'''
y1 = [-0.040422445,-0.056402365,-0.060758191]
#second order
'''sin(Îθ)'''
y2 = [-0.083967708, -0.107420964, -0.117248521]
''''λ, theo (nm)'''
x= [404.66, 546.07, 579.06]
pl.title('Angular displacements vs. Theoretical wavelength')
pl.xlabel('theoretical λ (in nm)')
pl.y1label('sin(Îθ) of 1st order images')
pl.y2label('sin(Îθ) of 2nd order images')
plot1 = pl.plot(x, y1, 'r')
plot2 = pl.plot(x, y2, 'b')
pl.legend([plot1, plot2], ('1st order images', '2nd order images'), 'best', numpoints=1)
slope1, intercept1, r_value1, p_value1, std_err1 = stats.linregress(x,y1)
slope2, intercept2, r_value2, p_value2, std_err2 = stats.linregress(x,y2)
print "r-squared:", r_value1**2
print "r-squared:", r_value2**2
pl.show()
</code></pre>
<p>...i dont' get any plot and i get the error:
"UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 12: ordinal not in range(128)"</p>
<p>which i don't understand. can somebody help and tell me what's wrong with my code? thank youuu</p>
| 0 |
2016-09-11T10:36:23Z
| 39,435,241 |
<p>There are multiple errors in this code.</p>
<ol>
<li><p>You cannot simply type greek letters in plot labels and titles, here
is how you can do it:</p>
<pre><code>pl.xlabel(r'theoretical $\lambda$ (in nm)')
</code></pre></li>
<li><p><code>y1label</code> and <code>y2label</code> are not objects of the <code>pl</code> module</p></li>
<li><p>In Python, <code># blah blah</code> is different from <code>'''blah blah'''</code>. The first one is a comment, the second one is an expression. You can assign the second one to a variable (<code>a = '''blah blah'''</code>) but you cannot assign the first one to a variable: <code>a = # blah blah</code> yields a SyntaxError.</p></li>
</ol>
<p>Here is a code that should work:</p>
<pre><code>import matplotlib
import matplotlib.pyplot as pl
from scipy import stats
y1 = [-0.040422445,-0.056402365,-0.060758191]
y2 = [-0.083967708, -0.107420964, -0.117248521]
x= [404.66, 546.07, 579.06]
pl.title('Angular displacements vs. Theoretical wavelength')
pl.xlabel(r'theoretical $\lambda$ (in nm)')
pl.ylabel(r'sin($\Delta\theta$)')
y1label = '1st order images'
y2label = '2nd order images'
plot1 = pl.plot(x, y1, 'r', label=y1label)
plot2 = pl.plot(x, y2, 'b', label=y2label)
pl.legend()
slope1, intercept1, r_value1, p_value1, std_err1 = stats.linregress(x,y1)
slope2, intercept2, r_value2, p_value2, std_err2 = stats.linregress(x,y2)
print "r-squared:", r_value1**2
print "r-squared:", r_value2**2
pl.show()
</code></pre>
| 0 |
2016-09-11T10:47:03Z
|
[
"python",
"matplotlib",
"linear-regression"
] |
python pandas elegant dataframe access rows 2:end
| 39,435,218 |
<p>I have a dataframe, <code>dF = pd.DataFrame(X)</code> where X is a numpy array of doubles. I want to remove the last row from the dataframe. I know for the first row I can do something like this <code>dF.ix[1:]</code>. I want to do something similar for the last row. I know in matlab you could do something like this <code>dF[1:end-1]</code>. What is a good and readable way to do this with pandas?</p>
<p>The end goal is to achieve this:
first matrix</p>
<pre><code>1 2 3
4 5 6
7 8 9
</code></pre>
<p>second matrix</p>
<pre><code>a b c
d e f
g h i
</code></pre>
<p>now get rid of first row of first matrix and last row of second matrix and horizontally concatentate them like so:</p>
<pre><code>4 5 6 a b c
7 8 9 d e f
</code></pre>
<p>done. In matlab a = firstMatrix. b = secondMatrix. <code>c = [a[2:end,:] b[1:end-1,:]]</code> where c is the resulting matrix.</p>
| 1 |
2016-09-11T10:42:34Z
| 39,435,700 |
<p>you can do it this way:</p>
<pre><code>In [129]: df1
Out[129]:
c1 c2 c3
0 1 2 3
1 4 5 6
2 7 8 9
In [130]: df2
Out[130]:
c1 c2 c3
0 a b c
1 d e f
2 g h i
In [131]: df1.iloc[1:].reset_index(drop=1).join(df2.iloc[:-1].reset_index(drop=1), rsuffix='_2')
Out[131]:
c1 c2 c3 c1_2 c2_2 c3_2
0 4 5 6 a b c
1 7 8 9 d e f
</code></pre>
<p>Or a pure NumPy solution:</p>
<pre><code>In [132]: a1 = df1.values
In [133]: a1
Out[133]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=int64)
In [134]: a2 = df2.values
In [135]: a2
Out[135]:
array([['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']], dtype=object)
In [136]: a1[1:]
Out[136]:
array([[4, 5, 6],
[7, 8, 9]], dtype=int64)
In [137]: a2[:-1]
Out[137]:
array([['a', 'b', 'c'],
['d', 'e', 'f']], dtype=object)
In [138]: np.concatenate((a1[1:], a2[:-1]), axis=1)
Out[138]:
array([[4, 5, 6, 'a', 'b', 'c'],
[7, 8, 9, 'd', 'e', 'f']], dtype=object)
</code></pre>
| 0 |
2016-09-11T11:42:07Z
|
[
"python",
"matlab",
"pandas",
"numpy"
] |
Appending data to Dataframe
| 39,435,236 |
<p>I have a directory which contains some csv files called :</p>
<pre><code>results_roll_3_oe_2016-02-04
results_roll_2_oe_2016-01-28
</code></pre>
<p>results_roll_3_oe_2016-02-04 looks like:</p>
<pre><code>date day_performance
2016-01-26 3.714011839374111
2016-01-27 -8.402334555591418
2016-01-28 -41.09889373400086
</code></pre>
<p>results_roll_2_oe_2016-01-28 looks like:</p>
<pre><code>date day_performance
2016-02-02 52.07647107113144
2016-02-03 -1.7503249876724
2016-02-04 -158.1667860104882
</code></pre>
<p>(In reality there are more files that this). I am trying to look though the directory sticking together the result_roll csv fies into one dataframe (so my eventual output would look like):</p>
<pre><code>date day_performance
2016-01-26 3.714011839374111
2016-01-27 -8.402334555591418
2016-01-28 -41.09889373400086
2016-02-02 52.07647107113144
2016-02-03 -1.7503249876724
2016-02-04 -158.1667860104882
</code></pre>
<p>I have written some code (below) that can loop through the files and tries to append the result_roll files together into a new dataframe (<code>dfs</code>), but I get the following output:</p>
<pre><code>date day_performance
2016-02-02 52.07647107113144
2016-02-03 -1.7503249876724
2016-02-04 -158.1667860104882
date day_performance
2016-02-02 52.07647107113144
2016-02-03 -1.7503249876724
2016-02-04 -158.1667860104882
</code></pre>
<p>Where it looks to be taking result_roll_2 and appending the data twice along with the header twice.</p>
<p>My code is as follwos:</p>
<pre><code>def main():
dfs = pd.DataFrame()
ResultsDataPath = 'C:/Users/stacey/Documents/data/VwapBacktestResults/'
print(ResultsDataPath)
allfiles = glob.glob(os.path.join(ResultsDataPath, "*oe*"))
for fname in allfiles:
df = pd.read_csv(fname, header=None, usecols=[1,2],
parse_dates=[0], dayfirst=True,
index_col=[0], names=['date', 'day_performance'])
print(df)
dfs = df.append(df,ignore_index=False)
</code></pre>
<p>Any help on obtaining my desired output much appreciated.</p>
<p>my exact CSV (results_roll_2_oe_2016-01-28) looks like :</p>
<pre><code> date day_performance
0 26/01/2016 3.714011839
1 27/01/2016 -8.402334556
2 28/01/2016 -41.09889373
</code></pre>
<p>and my CSV (results_roll_3_oe_2016-02-04) looks like:</p>
<pre><code> date day_performance
0 02/02/2016 52.07647107
1 03/02/2016 -1.750324988
2 04/02/2016 -158.166786
</code></pre>
<p>They are both MS excel Comma Separated Values files</p>
<p>Thanks </p>
| 2 |
2016-09-11T10:46:18Z
| 39,435,264 |
<p><strong>UPDATE:</strong> your CSV files are either space-delimited or TAB-delimited, so you have to specify it. Beside that all your CSV files have a header line and have only two columns, so you don't need to use <code>usecols</code>, <code>header</code>, <code>names</code> parameters:</p>
<pre><code>In [100]: fmask = r'D:\temp\.data\results_roll_*'
In [101]: df = get_merged_csv(glob.glob(fmask),
.....: delim_whitespace=True,
.....: index_col=0)
In [102]: df['date'] = pd.to_datetime(df['date'], dayfirst=True)
In [103]: df
Out[103]:
date day_performance
0 2016-01-26 3.714012
1 2016-01-27 -8.402335
2 2016-01-28 -41.098894
3 2016-02-02 52.076471
4 2016-02-03 -1.750325
5 2016-02-04 -158.166786
</code></pre>
<p><strong>OLD answer:</strong></p>
<p>try this:</p>
<pre><code>import glob
import pandas as pd
def get_merged_csv(flist, **kwargs):
return pd.concat([pd.read_csv(f, **kwargs) for f in flist], ignore_index=True)
fmask = '/path/to/results_roll_*.csv'
df = get_merged_csv(glob.glob(fmask),
header=None, usecols=[1,2],
parse_dates=[0], dayfirst=True,
index_col=[0], names=['date', 'day_performance'])
</code></pre>
| 0 |
2016-09-11T10:49:15Z
|
[
"python",
"pandas"
] |
Insert statment created by django ORM at bulk_create
| 39,435,322 |
<p>I am kind of new to python and django.</p>
<p>I am using <code>bulk_create</code> to insert a lot of rows and as a former DBA I would very much like to see what insert statments are being executed. I know that for querys you can use <code>.query</code> but for insert statments I can't find a command.</p>
<p>Is there something I'm missing or is there no easy way to see it? (A regular print is fine by me.)</p>
| 0 |
2016-09-11T10:55:08Z
| 39,437,816 |
<p>The easiest way is to set <code>DEBUG = True</code> and check <code>connection.queries</code> after executing the query. This stores the raw queries and the time each query takes. </p>
<pre><code>from django.db import connection
MyModel.objects.bulk_create(...)
print(connection.queries[-1]['sql'])
</code></pre>
<p>There's more information <a href="https://docs.djangoproject.com/en/1.10/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running" rel="nofollow">in the docs</a>. </p>
<p>A great tool to make this information easily accessible is the <a href="https://github.com/jazzband/django-debug-toolbar" rel="nofollow">django-debug-toolbar</a>. </p>
| 0 |
2016-09-11T15:41:52Z
|
[
"python",
"django",
"orm"
] |
How do I make strings and variables editable and printing them? (Python)
| 39,435,339 |
<p>Yes I know that this is very much to ask, and I'm sorry, but I usually learn the best by doing stuff instead of reading stuff.</p>
<p>So I would like to for example set a variable to 1995 and a string to John
and then when I open the python file, I would be able to see the name of the string and variable and change them, like this.</p>
<p><strong>python file:</strong></p>
<pre><code>Name John
Year 1995
set year 2005
show options
Name John
Year 1995
</code></pre>
<p>And when I'm done I would like to print all strings and variables to a text file. You don't have to teach me like a baby, just tell me where I can find this information?</p>
| -2 |
2016-09-11T10:56:50Z
| 39,435,496 |
<p>for learn you should read python reference:</p>
<p><a href="https://www.python.org/" rel="nofollow">https://www.python.org/</a></p>
<p>but :</p>
<p>in python create variable is very easy </p>
<pre><code>year = 1995
</code></pre>
<p>and then :</p>
<pre><code>year = input("Enter Year:")
print(year)
</code></pre>
<p>if you want save your data in file , you can use this method:</p>
<pre><code>my_result = open("myfile.txt","a")
my_result.write(year)
</code></pre>
<p>And all these can have different method in python </p>
| 1 |
2016-09-11T11:16:14Z
|
[
"python"
] |
Python trainticket machine
| 39,435,359 |
<p>I am stuck at an excercise, I need to make a train ticket machine but I am just 1 week practicing in Python and I don't know how to start.</p>
<p>First I've got this:</p>
<pre><code>stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam Sloterdijk','Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', ' âs-Hertogenbosch', 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']
begin = input('What is your starting station?: ')
</code></pre>
<p>but now it needs to check if the input is in stations, if its not it need to print:</p>
<pre><code>'This is not a station, your starting station will be: Schagen.'
</code></pre>
<p>Next step is asking for the final destination. If the final destination is in stations, after that it checks if the final destination has a higher index in the list then the begin station, if not, then print 'Wrong station' (or something like that) and add the last station in the list as final destination.</p>
<p>Next step needs to print the following:
- Name of the starting station</p>
<ul>
<li><p>Name of the destination station</p></li>
<li><p>names of stations which Are passed during the trip</p></li>
<li><p>Price of the trip (per station its like 5 euros.</p></li>
<li><p>and finally a summary;</p></li>
</ul>
<p>You get on the train on station: <em>beginstation</em></p>
<p>Here the names of the stations we pass during our trip like:</p>
<p>-Heerhugowaard</p>
<p>-Alkmaar</p>
<p>You get out of the train in: ...</p>
<p>Could you give me some tips how to think like a programmer so I can realize this, the above exercise is pretty awesome, but very hard if you're just one week in to python/programming ;).</p>
<p>Regards,</p>
| 0 |
2016-09-11T10:58:44Z
| 39,436,860 |
<p>In languages like C++ and Java, you use curly braces for different constructs. However, in Python, you use spaces or tabs for indentation instead of curly braces.</p>
<p>Here's a code that will get you started:</p>
<pre><code>src = input('Source station:')
dest = input('Destination: ')
if src in stations and dest in stations:
for x in range((stations.index(src)+1), (stations.index(dest))-1):
print(stations[x])
else:
print('Invalid stations')
</code></pre>
<p>A <code>for-range loop</code> must be provided with 2 arguments: <code>initial value</code>, and <code>final value</code>.
Basically, we are finding the index of the source and destination stations from the stations list and then looping through the range of the values and at the same time, accessing all the elements from the <code>stations list</code>.</p>
<p>Try doing the rest of the stuff on your own! :) </p>
| 0 |
2016-09-11T14:01:18Z
|
[
"python",
"python-3.x"
] |
Can I join lists with sum()?
| 39,435,401 |
<p>Is it pythonic to use <code>sum()</code> for list concatenation?</p>
<pre><code>>>> sum(([n]*n for n in range(1,5)),[])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>
| 3 |
2016-09-11T11:03:17Z
| 39,435,470 |
<p>No it's not, Actually it's <a href="http://en.wikichip.org/wiki/schlemiel_the_painter%27s_algorithm" rel="nofollow">shlemiel the painter algorithm</a>. Because each time it wants to concatenate a new list it has to traverse the whole list from beginning. (For more info read this article by Joel:
<a href="http://www.joelonsoftware.com/articles/fog0000000319.html" rel="nofollow">http://www.joelonsoftware.com/articles/fog0000000319.html</a>)</p>
<p>The most pythonic way is using a list comprehension:</p>
<pre><code>In [28]: [t for n in range(1,5) for t in [n]*n ]
Out[28]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>
<p>Or <code>itertools.chain</code>:</p>
<pre><code>In [29]: from itertools import chain
In [32]: list(chain.from_iterable([n]*n for n in range(1,5)))
Out[32]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>
<p>Or as a pute generator based approach you can use <code>repeat</code> instead of multiplying the list:</p>
<pre><code>In [33]: from itertools import chain, repeat
# In python2.X use xrange instead of range
In [35]: list(chain.from_iterable(repeat(n, n) for n in range(1,5)))
Out[35]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>
<p>Or if you are interest to numpy, or want a super fast approach here is one:</p>
<pre><code>In [46]: import numpy as np
In [46]: np.repeat(np.arange(1, 5), np.arange(1, 5))
Out[46]: array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
</code></pre>
| 8 |
2016-09-11T11:13:24Z
|
[
"python"
] |
Can I join lists with sum()?
| 39,435,401 |
<p>Is it pythonic to use <code>sum()</code> for list concatenation?</p>
<pre><code>>>> sum(([n]*n for n in range(1,5)),[])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
</code></pre>
| 3 |
2016-09-11T11:03:17Z
| 39,435,707 |
<p>No, this will get very slow for large lists. List comprehensions are a far better option.</p>
<p>Code for timing list flattening via list comprehensions, summation and itertools.chain.from_iterable:</p>
<pre><code>import time
from itertools import chain
def increasing_count_lists(upper):
yield from ([n]*n for n in range(1,upper))
def printtime(func):
def clocked_func(*args):
t0 = time.perf_counter()
result = func(*args)
elapsed_s = time.perf_counter() - t0
print('{:.4}ms'.format(elapsed_s*1000))
return result
return clocked_func
@printtime
def concat_list_sum(upper):
return sum(increasing_count_lists(upper), [])
@printtime
def concat_list_listcomp(upper):
return [item for sublist in increasing_count_lists(upper) for item in sublist]
@printtime
def concat_list_chain(upper):
return list(chain.from_iterable(increasing_count_lists(upper)))
</code></pre>
<p>And running them:</p>
<pre><code>>>> _ = concat_list_sum(5)
0.03351ms
>>> _ = concat_list_listcomp(5)
0.03034ms
>>> _ = concat_list_chain(5)
0.02717ms
>>> _ = concat_list_sum(50)
0.2373ms
>>> _ = concat_list_listcomp(50)
0.2169ms
>>> _ = concat_list_chain(50)
0.1467ms
>>> _ = concat_list_sum(500)
167.6ms
>>> _ = concat_list_listcomp(500)
8.319ms
>>> _ = concat_list_chain(500)
12.02ms
</code></pre>
| 3 |
2016-09-11T11:43:14Z
|
[
"python"
] |
Django datatable and enum
| 39,435,418 |
<p>I have a campaign model as follows:</p>
<pre><code>id campaign objective platform
1 Hello Word MOBILE_APP_ENGAGEMENT Facebook
2 Hi There VIDEO_VIEWS_PREROLL Twitter
</code></pre>
<p>Model:</p>
<pre><code>class Campaign(Model):
id = models.TextField(primary_key=True)
name = models.TextField(default="")
objective = models.TextField(null=True)
platform = enumfields.EnumField(Platform, max_length=10, null=True)
</code></pre>
<p>The campaign holds both Twitter and FB campaigns.</p>
<p>The objective field was a free text, but I am not happy with it.</p>
<p>I would like to create 2 different enums (enum34):</p>
<pre><code>class FacebookObjective(Enum):
MOBILE_APP_ENGAGEMENT
MOBILE_APP_DOWNLOAD
class TwitterObjective(Enum):
VIDEO_VIEWS_PREROLL
TWEET_ENGAGEMENTS
</code></pre>
<p>and somehow use them on the same column. but not sure how to do it.</p>
<p>I thought to use enum, because I need the other uses to use it easily in the code. e.g:</p>
<pre><code>TwitterObjective.VIDEO_VIEWS_PREROLL
</code></pre>
| 2 |
2016-09-11T11:06:06Z
| 39,437,249 |
<p>As far as I know (which isn't much where Django is concerned), to make this work you'll need to use a single <code>Enum</code> per field. So in your case I would put the Twitter or FB designation in the name of the members:</p>
<pre><code>Class Objective(Enum):
FB_MOBILE_APP_ENGAGEMENT
FB_MOBILE_APP_DOWNLOAD
TW_VIDEO_VIEWS_PREROLL
TW_TWEET_ENGAGEMENTS
</code></pre>
<p>If you really want to use different <code>Enum</code>s you have a couple choices:</p>
<ul>
<li>use nested <code>Enum</code> classes (see <a href="http://stackoverflow.com/a/35886825/208880">http://stackoverflow.com/a/35886825/208880</a>)</li>
<li>use two classes and have your implementation choose between them (which will require either embedding a FaceBook or Twitter code in the name, such as FB_ and TW_, or using unique names across the two <code>Enum</code>s so you can reverse the lookup when going from db to Python)</li>
</ul>
<p><a href="http://stackoverflow.com/a/28842582/208880">This answer</a> may help with the details.</p>
| 1 |
2016-09-11T14:45:07Z
|
[
"python",
"django",
"enums"
] |
Creating a Calc Function that performs arithmetic in Python
| 39,435,436 |
<p>Ok, so I'm trying to create a function in Python named calc that can perform the 4 basic arithmetic operations.</p>
<pre><code>def calc(n, num1, num2):
if n == '+':
return num1 + num2
elif n == '-':
return num1 - num2
elif n == 'x':
return num1 * num2
elif n == '/':
return num1 / num2
</code></pre>
<p>This is my code so far. So when I execute it like so, I get a syntax error pointing to the number 6, the 3rd argument to be passed.</p>
<pre><code>calc(+ 4 6)
SyntaxError: invalid syntax
</code></pre>
<p>Can someone tell me what's wrong? I'm just now learning python and I'm expected to create an Interpreter with loops, conditions, functions and variable assignments so getting stuck on this makes me somewhat frustrated, any help is appreciated.</p>
| 0 |
2016-09-11T11:08:49Z
| 39,435,468 |
<p>You can't make a function which would handle this:</p>
<pre><code>calc(+ 4 6)
</code></pre>
<p>That is invalid syntax.</p>
<p>But you could do this:</p>
<pre><code>calc('+', 4, 6)
</code></pre>
<p>You function would already work with it.</p>
<p>Or you could have this:</p>
<pre><code>calc('+ 4 6')
</code></pre>
<p>and then a function which has to parse the contents.</p>
| 0 |
2016-09-11T11:13:15Z
|
[
"python",
"function"
] |
Why is Python 3 http.client so much faster than python-requests?
| 39,435,443 |
<p>I was testing different Python HTTP libraries today and I realized that <a href="https://docs.python.org/3/library/http.client.html" rel="nofollow"><code>http.client</code></a> library seems to perform much much faster than <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>. </p>
<p>To test it you can run following two code samples.</p>
<pre><code>import http.client
conn = http.client.HTTPConnection("localhost", port=8000)
for i in range(1000):
conn.request("GET", "/")
r1 = conn.getresponse()
body = r1.read()
print(r1.status)
conn.close()
</code></pre>
<p>and here is code doing same thing with python-requests:</p>
<pre><code>import requests
with requests.Session() as session:
for i in range(1000):
r = session.get("http://localhost:8000")
print(r.status_code)
</code></pre>
<p>If I start SimpleHTTPServer:</p>
<pre><code>> python -m http.server
</code></pre>
<p>and run above code samples (I'm using Python 3.5.2). I get following results:</p>
<p>http.client:</p>
<pre><code>0.35user 0.10system 0:00.71elapsed 64%CPU
</code></pre>
<p>python-requests:</p>
<pre><code>1.76user 0.10system 0:02.17elapsed 85%CPU
</code></pre>
<p>Are my measurements and tests correct? Can you reproduce them too? If yes does anyone know what's going on inside <code>http.client</code> that make it so much faster? Why is there such big difference in processing time?</p>
| 1 |
2016-09-11T11:09:45Z
| 39,438,703 |
<p>Based on profiling both, the main difference appears to be that the <code>requests</code> version is doing a DNS lookup for every request, while the <code>http.client</code> version is doing so once.</p>
<pre><code># http.client
ncalls tottime percall cumtime percall filename:lineno(function)
1974 0.541 0.000 0.541 0.000 {method 'recv_into' of '_socket.socket' objects}
1000 0.020 0.000 0.045 0.000 feedparser.py:470(_parse_headers)
13000 0.015 0.000 0.563 0.000 {method 'readline' of '_io.BufferedReader' objects}
...
# requests
ncalls tottime percall cumtime percall filename:lineno(function)
1481 0.827 0.001 0.827 0.001 {method 'recv_into' of '_socket.socket' objects}
1000 0.377 0.000 0.382 0.000 {built-in method _socket.gethostbyname}
1000 0.123 0.000 0.123 0.000 {built-in method _scproxy._get_proxy_settings}
1000 0.111 0.000 0.111 0.000 {built-in method _scproxy._get_proxies}
92000 0.068 0.000 0.284 0.000 _collections_abc.py:675(__iter__)
...
</code></pre>
<p>You're providing the hostname to <code>http.client.HTTPConnection()</code> once, so it makes sense it would call <code>gethostbyname</code> once. <code>requests.Session</code> probably could cache hostname lookups, but it apparently does not. </p>
<p>EDIT: After some further research, it's not just a simple matter of caching. There's a function for determining whether to bypass proxies which ends up invoking <code>gethostbyname</code> regardless of the actual request itself.</p>
| 4 |
2016-09-11T17:20:22Z
|
[
"python",
"http",
"python-requests"
] |
Why is Python 3 http.client so much faster than python-requests?
| 39,435,443 |
<p>I was testing different Python HTTP libraries today and I realized that <a href="https://docs.python.org/3/library/http.client.html" rel="nofollow"><code>http.client</code></a> library seems to perform much much faster than <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a>. </p>
<p>To test it you can run following two code samples.</p>
<pre><code>import http.client
conn = http.client.HTTPConnection("localhost", port=8000)
for i in range(1000):
conn.request("GET", "/")
r1 = conn.getresponse()
body = r1.read()
print(r1.status)
conn.close()
</code></pre>
<p>and here is code doing same thing with python-requests:</p>
<pre><code>import requests
with requests.Session() as session:
for i in range(1000):
r = session.get("http://localhost:8000")
print(r.status_code)
</code></pre>
<p>If I start SimpleHTTPServer:</p>
<pre><code>> python -m http.server
</code></pre>
<p>and run above code samples (I'm using Python 3.5.2). I get following results:</p>
<p>http.client:</p>
<pre><code>0.35user 0.10system 0:00.71elapsed 64%CPU
</code></pre>
<p>python-requests:</p>
<pre><code>1.76user 0.10system 0:02.17elapsed 85%CPU
</code></pre>
<p>Are my measurements and tests correct? Can you reproduce them too? If yes does anyone know what's going on inside <code>http.client</code> that make it so much faster? Why is there such big difference in processing time?</p>
| 1 |
2016-09-11T11:09:45Z
| 39,446,009 |
<p>copy-pasting response from @Lukasa posted <a href="https://github.com/kennethreitz/requests/issues/3568#issuecomment-246271506" rel="nofollow">here</a>:</p>
<blockquote>
<p>The reason Requests is slower is because it does substantially more than httplib. httplib can be thought of as the bottom layer of the stack: it does the low-level wrangling of sockets. Requests is two layers further up, and adds things like cookies, connection pooling, additional settings, and kinds of other fun things. This is necessarily going to slow things down. We simply have to compute a lot more than httplib does.</p>
<p>You can see this by looking at cProfile results for Requests: there's just way more result than there is for httplib. This is always to be expected with high-level libraries: they add more overhead because they have to do a lot more work.</p>
<p>While we can look at targetted performance improvements, the sheer height of the call stack in all cases is going to hurt our performance markedly. That means that the complaint that "requests is slower than httplib" is always going to be true: it's like complaining that "requests is slower than sending carefully crafted raw bytes down sockets." That's true, and it'll always be true: there's nothing we can do about that.</p>
</blockquote>
| 0 |
2016-09-12T08:19:20Z
|
[
"python",
"http",
"python-requests"
] |
How to generate numbers in range with specific average with Python?
| 39,435,481 |
<p>For example I would like to generate 22 numbers between 20 and 46 with an average value of 27. And I would like the numbers to cover the range as well as possible.</p>
<p>EDIT:
These numbers don't need to be random.</p>
| 1 |
2016-09-11T11:14:23Z
| 39,435,600 |
<p>Warning: this is not the optimal solution but it works quite fast with your input parameters:</p>
<pre><code>import random
def gen_avg(expected_avg=27, n=22, a=20, b=46):
while True:
l = [random.randint(a, b) for i in range(n)]
avg = reduce(lambda x, y: x + y, l) / len(l)
if avg == expected_avg:
return l
for i in range(100):
print gen_avg()
</code></pre>
<p>In my laptop will give 100 random sequences in ~2.5s:</p>
<pre><code>[21, 20, 20, 23, 25, 24, 29, 22, 42, 23, 31, 26, 30, 25, 29, 38, 20, 31, 46, 28, 41, 20]
[20, 30, 39, 26, 24, 31, 35, 36, 22, 22, 20, 32, 23, 21, 42, 32, 23, 24, 26, 28, 29, 25]
[23, 43, 21, 31, 44, 24, 24, 20, 27, 31, 28, 22, 26, 33, 25, 30, 21, 26, 33, 20, 31, 25]
[36, 28, 24, 29, 32, 21, 36, 28, 24, 27, 24, 22, 28, 28, 33, 21, 20, 32, 23, 30, 35, 21]
[21, 34, 25, 32, 20, 37, 31, 20, 46, 25, 21, 25, 35, 36, 21, 26, 21, 35, 24, 21, 30, 28]
[28, 23, 43, 22, 20, 23, 30, 41, 25, 32, 20, 21, 21, 30, 26, 22, 46, 40, 27, 26, 26, 21]
[21, 26, 38, 27, 42, 36, 43, 21, 29, 32, 22, 29, 26, 20, 23, 22, 21, 38, 23, 21, 21, 23]
[28, 21, 27, 34, 38, 21, 25, 37, 27, 22, 36, 38, 27, 20, 32, 35, 20, 24, 31, 22, 24, 24]
[28, 31, 23, 26, 36, 23, 30, 36, 32, 23, 20, 25, 23, 25, 25, 40, 21, 27, 21, 25, 28, 38]
[30, 24, 24, 25, 38, 27, 35, 31, 21, 31, 27, 22, 25, 25, 39, 31, 22, 23, 30, 29, 20, 23]
[25, 21, 42, 24, 24, 31, 22, 34, 32, 21, 23, 27, 20, 35, 31, 23, 26, 33, 20, 23, 22, 43]
[23, 23, 20, 40, 27, 22, 22, 41, 20, 21, 45, 26, 22, 28, 29, 39, 24, 23, 26, 34, 20, 38]
[22, 44, 27, 36, 29, 22, 24, 35, 30, 20, 20, 31, 38, 23, 20, 31, 25, 29, 30, 21, 24, 28]
[27, 30, 21, 28, 39, 30, 33, 33, 25, 21, 26, 33, 33, 24, 31, 20, 24, 25, 22, 27, 28, 20]
[23, 28, 24, 20, 35, 29, 33, 22, 23, 21, 31, 39, 32, 22, 24, 39, 22, 21, 29, 32, 34, 25]
[38, 25, 20, 22, 21, 44, 32, 20, 26, 20, 21, 29, 25, 20, 37, 27, 33, 23, 20, 39, 28, 27]
[29, 22, 30, 20, 31, 23, 23, 24, 28, 28, 46, 27, 24, 23, 21, 35, 20, 21, 45, 29, 27, 34]
[21, 29, 21, 33, 38, 44, 21, 20, 41, 30, 26, 23, 23, 29, 21, 32, 20, 29, 32, 29, 21, 26]
[21, 20, 24, 40, 30, 30, 31, 27, 20, 34, 28, 37, 31, 20, 38, 43, 25, 25, 21, 20, 27, 22]
[27, 35, 30, 21, 36, 37, 41, 21, 23, 24, 23, 32, 23, 25, 20, 23, 36, 40, 30, 24, 20, 24]
[39, 30, 30, 21, 26, 23, 20, 25, 36, 22, 23, 29, 23, 42, 20, 23, 32, 20, 30, 36, 25, 31]
[24, 24, 25, 41, 20, 27, 35, 31, 21, 24, 31, 36, 20, 25, 22, 32, 31, 30, 21, 22, 33, 25]
[22, 34, 33, 20, 29, 24, 34, 27, 27, 31, 20, 24, 22, 33, 36, 22, 21, 31, 21, 38, 21, 44]
[20, 43, 29, 23, 22, 32, 20, 21, 26, 23, 26, 33, 34, 22, 26, 20, 38, 21, 29, 32, 24, 33]
[23, 38, 39, 35, 21, 33, 25, 39, 33, 28, 23, 20, 22, 22, 25, 30, 20, 26, 28, 31, 24, 30]
[21, 36, 32, 42, 25, 25, 20, 46, 24, 22, 22, 22, 33, 32, 22, 29, 24, 26, 30, 23, 22, 21]
[25, 34, 20, 23, 44, 21, 40, 21, 25, 20, 26, 25, 44, 20, 24, 32, 21, 23, 31, 21, 43, 22]
[34, 31, 23, 20, 25, 30, 22, 23, 30, 22, 31, 21, 41, 42, 21, 22, 36, 20, 26, 24, 31, 32]
[27, 27, 35, 34, 31, 36, 21, 21, 24, 39, 22, 29, 29, 20, 20, 46, 23, 30, 27, 24, 28, 21]
[28, 37, 30, 31, 38, 23, 21, 20, 21, 32, 29, 24, 32, 20, 20, 21, 28, 20, 32, 41, 25, 40]
[27, 25, 24, 46, 23, 24, 26, 28, 30, 23, 23, 27, 38, 20, 44, 21, 27, 25, 20, 23, 26, 28]
[20, 28, 24, 33, 25, 22, 28, 27, 22, 27, 42, 25, 43, 27, 20, 26, 29, 33, 29, 24, 36, 23]
[39, 31, 27, 20, 23, 25, 22, 22, 24, 26, 25, 42, 21, 22, 21, 21, 28, 24, 44, 31, 35, 34]
[20, 20, 31, 30, 41, 30, 40, 20, 28, 20, 21, 25, 23, 30, 28, 25, 29, 21, 28, 28, 38, 24]
[35, 37, 30, 20, 24, 25, 36, 21, 23, 29, 25, 23, 21, 27, 22, 44, 41, 24, 33, 30, 22, 20]
[22, 22, 25, 20, 22, 29, 25, 25, 21, 33, 23, 20, 21, 42, 39, 32, 33, 30, 46, 34, 21, 22]
[26, 25, 27, 35, 30, 39, 20, 26, 43, 20, 29, 33, 23, 27, 35, 21, 20, 36, 24, 27, 21, 28]
[20, 30, 24, 31, 36, 23, 24, 46, 30, 28, 24, 25, 24, 22, 20, 33, 20, 21, 24, 23, 39, 27]
[20, 22, 33, 22, 33, 22, 38, 24, 29, 36, 23, 31, 26, 24, 28, 28, 26, 28, 43, 24, 25, 20]
[36, 26, 24, 24, 24, 33, 21, 28, 27, 29, 31, 31, 21, 27, 25, 24, 34, 20, 33, 37, 23, 30]
[25, 33, 24, 27, 30, 35, 25, 30, 23, 23, 20, 20, 28, 30, 29, 38, 25, 25, 32, 21, 25, 33]
[30, 21, 27, 33, 21, 43, 23, 23, 25, 29, 23, 38, 28, 24, 21, 44, 22, 31, 32, 21, 20, 27]
[21, 33, 26, 26, 33, 27, 26, 32, 41, 31, 25, 29, 33, 22, 26, 38, 24, 22, 21, 28, 21, 21]
[26, 28, 31, 20, 38, 20, 26, 23, 24, 24, 30, 21, 21, 33, 26, 33, 38, 28, 40, 24, 21, 26]
[21, 27, 30, 22, 24, 28, 38, 27, 20, 23, 41, 20, 26, 41, 26, 24, 29, 22, 20, 43, 21, 42]
[22, 28, 21, 25, 25, 46, 29, 27, 24, 34, 24, 27, 23, 23, 34, 21, 37, 26, 20, 44, 28, 24]
[32, 27, 21, 35, 28, 37, 21, 32, 23, 20, 21, 20, 31, 21, 32, 24, 35, 26, 42, 35, 22, 24]
[22, 36, 41, 35, 27, 20, 25, 21, 28, 32, 31, 30, 23, 26, 23, 26, 28, 33, 23, 35, 20, 23]
[28, 24, 27, 39, 37, 25, 21, 29, 36, 27, 24, 24, 26, 27, 37, 27, 28, 23, 27, 21, 22, 26]
[32, 33, 24, 31, 22, 35, 39, 20, 39, 39, 22, 21, 23, 28, 34, 23, 20, 21, 35, 24, 23, 22]
[25, 20, 20, 25, 28, 23, 37, 30, 34, 27, 22, 20, 41, 22, 22, 23, 42, 27, 39, 25, 22, 24]
[20, 36, 22, 21, 21, 38, 20, 45, 36, 28, 23, 23, 35, 26, 20, 30, 31, 28, 33, 22, 25, 31]
[30, 23, 21, 45, 20, 31, 35, 21, 22, 24, 29, 32, 34, 30, 23, 31, 20, 20, 31, 35, 29, 20]
[22, 21, 22, 32, 42, 24, 35, 22, 26, 21, 28, 23, 24, 21, 31, 20, 27, 39, 42, 21, 37, 33]
[26, 28, 24, 20, 42, 23, 22, 20, 22, 33, 24, 25, 24, 28, 38, 26, 44, 28, 31, 20, 28, 25]
[25, 42, 32, 20, 25, 20, 27, 22, 21, 20, 31, 28, 21, 31, 25, 25, 46, 28, 30, 41, 25, 20]
[20, 27, 28, 26, 34, 23, 20, 22, 34, 20, 36, 30, 21, 23, 26, 23, 31, 37, 23, 34, 40, 29]
[28, 30, 22, 21, 20, 35, 20, 24, 23, 24, 34, 33, 37, 34, 24, 21, 24, 21, 41, 32, 22, 30]
[21, 20, 21, 28, 24, 42, 36, 26, 29, 33, 26, 22, 33, 28, 26, 31, 20, 22, 29, 32, 27, 28]
[23, 41, 24, 39, 22, 23, 25, 21, 24, 35, 20, 27, 31, 43, 34, 29, 24, 22, 23, 21, 37, 21]
[20, 29, 32, 21, 27, 25, 32, 36, 24, 34, 33, 31, 25, 21, 29, 26, 21, 32, 23, 33, 20, 29]
[21, 32, 22, 26, 40, 40, 23, 28, 26, 25, 31, 21, 20, 37, 30, 30, 25, 35, 27, 24, 24, 21]
[25, 25, 27, 21, 27, 23, 20, 39, 20, 43, 29, 21, 38, 27, 30, 23, 24, 29, 20, 24, 36, 30]
[26, 20, 22, 25, 28, 22, 21, 29, 30, 37, 23, 39, 20, 34, 33, 23, 25, 30, 27, 41, 27, 26]
[29, 20, 32, 22, 26, 27, 21, 20, 27, 26, 22, 42, 28, 24, 26, 23, 40, 24, 27, 42, 23, 44]
[21, 38, 25, 26, 35, 28, 21, 40, 37, 28, 25, 23, 26, 22, 22, 21, 46, 29, 23, 23, 21, 32]
[39, 23, 20, 37, 26, 22, 30, 21, 25, 25, 32, 20, 39, 20, 33, 23, 24, 32, 38, 22, 33, 27]
[21, 21, 21, 20, 34, 20, 27, 36, 25, 20, 20, 26, 34, 40, 32, 32, 30, 22, 28, 29, 36, 35]
[37, 30, 23, 20, 21, 38, 26, 21, 41, 34, 33, 26, 36, 26, 25, 34, 34, 20, 24, 21, 20, 25]
[28, 24, 25, 29, 41, 24, 24, 29, 34, 37, 20, 29, 21, 30, 21, 28, 33, 20, 22, 43, 27, 20]
[35, 36, 20, 29, 26, 30, 26, 26, 34, 22, 24, 25, 21, 35, 34, 34, 25, 21, 23, 31, 24, 20]
[24, 25, 22, 22, 31, 28, 38, 42, 33, 24, 37, 27, 21, 42, 22, 28, 25, 20, 21, 25, 22, 29]
[26, 38, 33, 40, 22, 22, 21, 26, 29, 26, 23, 25, 35, 21, 27, 23, 35, 21, 43, 29, 20, 29]
[26, 31, 25, 20, 20, 21, 25, 25, 24, 28, 22, 30, 22, 22, 40, 37, 29, 46, 20, 38, 22, 24]
[24, 26, 23, 22, 34, 26, 30, 20, 24, 21, 32, 24, 24, 31, 31, 27, 28, 31, 32, 45, 25, 33]
[30, 32, 24, 27, 24, 21, 25, 22, 23, 39, 39, 22, 27, 23, 37, 23, 32, 23, 38, 21, 36, 22]
[27, 23, 22, 24, 28, 42, 26, 33, 28, 20, 20, 35, 22, 20, 31, 27, 34, 23, 32, 36, 23, 38]
[31, 35, 23, 28, 21, 28, 37, 20, 38, 34, 27, 20, 24, 27, 22, 26, 20, 29, 35, 31, 28, 21]
[28, 21, 33, 31, 24, 29, 20, 23, 25, 22, 28, 27, 30, 25, 29, 28, 26, 22, 38, 39, 30, 33]
[23, 36, 41, 26, 23, 29, 29, 45, 20, 23, 34, 21, 22, 39, 35, 24, 20, 24, 24, 25, 23, 28]
[25, 25, 21, 32, 44, 24, 32, 28, 33, 21, 22, 38, 32, 22, 25, 29, 22, 27, 29, 26, 26, 32]
[35, 28, 35, 24, 27, 34, 25, 30, 25, 42, 29, 26, 20, 36, 25, 25, 20, 20, 23, 21, 31, 34]
[44, 23, 20, 25, 24, 28, 20, 23, 38, 21, 24, 28, 35, 30, 20, 45, 23, 28, 39, 26, 23, 25]
[22, 25, 22, 45, 21, 22, 31, 37, 42, 28, 21, 24, 26, 25, 30, 25, 20, 36, 23, 25, 23, 29]
[32, 21, 28, 20, 20, 41, 25, 20, 46, 21, 38, 31, 25, 26, 21, 30, 20, 31, 39, 24, 22, 24]
[34, 24, 23, 26, 33, 20, 26, 26, 24, 20, 24, 25, 21, 29, 31, 30, 39, 34, 28, 27, 25, 41]
[26, 36, 20, 27, 23, 23, 20, 27, 32, 23, 24, 36, 34, 23, 24, 43, 25, 25, 33, 24, 31, 31]
[23, 21, 28, 20, 33, 46, 20, 43, 21, 24, 28, 21, 22, 34, 38, 25, 20, 20, 20, 25, 44, 32]
[30, 35, 26, 21, 28, 20, 21, 22, 24, 35, 23, 22, 21, 26, 24, 31, 41, 37, 27, 20, 43, 25]
[34, 42, 21, 20, 26, 21, 40, 20, 41, 21, 21, 23, 29, 22, 21, 26, 30, 25, 32, 29, 39, 27]
[31, 44, 40, 27, 22, 21, 44, 21, 30, 26, 20, 34, 22, 20, 20, 20, 29, 36, 22, 21, 22, 38]
[21, 43, 46, 28, 32, 22, 23, 21, 24, 21, 28, 21, 20, 33, 21, 24, 36, 22, 23, 28, 45, 32]
[21, 22, 24, 39, 21, 25, 25, 20, 23, 20, 22, 26, 40, 39, 22, 28, 41, 38, 20, 20, 33, 33]
[34, 22, 26, 23, 28, 20, 32, 25, 24, 20, 39, 28, 41, 24, 29, 32, 24, 33, 23, 34, 24, 23]
[22, 39, 36, 22, 24, 20, 28, 23, 30, 39, 23, 33, 37, 25, 27, 20, 23, 27, 34, 31, 25, 20]
[34, 20, 20, 22, 26, 21, 26, 40, 23, 20, 42, 23, 31, 25, 46, 31, 27, 28, 22, 31, 34, 23]
[24, 29, 39, 24, 39, 26, 25, 25, 29, 23, 27, 20, 46, 21, 27, 25, 20, 41, 24, 31, 25, 22]
[42, 25, 23, 30, 22, 23, 37, 20, 29, 32, 28, 22, 35, 36, 22, 20, 27, 39, 21, 20, 22, 32]
[24, 26, 37, 44, 26, 23, 21, 23, 34, 33, 36, 22, 22, 22, 21, 27, 35, 24, 22, 44, 21, 20]
[24, 27, 22, 30, 20, 27, 21, 24, 31, 22, 30, 33, 35, 24, 23, 20, 32, 28, 30, 44, 26, 29]
</code></pre>
| 3 |
2016-09-11T11:29:12Z
|
[
"python",
"math"
] |
How to generate numbers in range with specific average with Python?
| 39,435,481 |
<p>For example I would like to generate 22 numbers between 20 and 46 with an average value of 27. And I would like the numbers to cover the range as well as possible.</p>
<p>EDIT:
These numbers don't need to be random.</p>
| 1 |
2016-09-11T11:14:23Z
| 39,435,610 |
<p>You could sove this in a pure mathematical way. <br/></p>
<ol>
<li>Randomly pick a number (call it n) within the wanted range</li>
<li>The next number will be avg + abs(n-avg)</li>
<li>repeat this until you fill the amount of numbers you want</li>
</ol>
<p>if the amount of needed numbers is no even - just select one of the numbers as the average itself and then you will need to generate k-1 numbers (which is even)</p>
<p>** <strong>EDIT</strong> **<br/>
you can use this code that manipulates an initial list to meet the requirements of a average so the resulting list is not symmetrical. (Better than generating lists until you hit the correct one)</p>
<pre><code>import random
def generate_numbers(wanted_avg, numbers_to_generate, start, end):
rng = [i for i in range(start, end)]
initial_selection = [random.choice(rng) for _ in range(numbers_to_generate)]
initial_avg = reduce(lambda x, y: x+y, initial_selection) / float(numbers_to_generate)
print "initial selection is: " + str(initial_selection)
print "initial avg is: " + str(initial_avg)
if initial_avg == wanted_avg:
return initial_selection
off = abs(initial_avg - wanted_avg)
manipulation = off * numbers_to_generate
sign = -1 if initial_avg > wanted_avg else 1
manipulation_action = dict()
acceptable_indices = range(numbers_to_generate)
while manipulation > 0:
random_index = random.choice(acceptable_indices)
factor = manipulation_action[random_index] if random_index in manipulation_action else 0
after_manipulation = initial_selection[random_index] + factor + sign * 1
if start <= after_manipulation <= end:
if random_index in manipulation_action:
manipulation_action[random_index] += sign * 1
manipulation -= 1
else:
manipulation_action[random_index] = sign * 1
manipulation -= 1
else:
acceptable_indices.remove(random_index)
for key in manipulation_action:
initial_selection[key] += manipulation_action[key]
print "after manipulation selection is: " + str(initial_selection)
print "after manipulation avg is: " + str(reduce(lambda x, y: x+y, initial_selection) / float(numbers_to_generate))
return initial_selection
</code></pre>
| 1 |
2016-09-11T11:30:34Z
|
[
"python",
"math"
] |
How to generate numbers in range with specific average with Python?
| 39,435,481 |
<p>For example I would like to generate 22 numbers between 20 and 46 with an average value of 27. And I would like the numbers to cover the range as well as possible.</p>
<p>EDIT:
These numbers don't need to be random.</p>
| 1 |
2016-09-11T11:14:23Z
| 39,436,460 |
<p>So I also used the random number generator. In addition, in order to meet the specification to cover the range as well as possible, I also calculated the standard deviation, which is a good measure of spread. So whenever a sample set meets the criteria of mean of 27, I compared it to previous matches and constantly choose the samples that have the highest std dev (mean always = 27). SO in my script, I did 5 trials, and you can see the output that the final answer matches the samples_list that had highest std dev. Note that Python 3.4 or higher is needed to use statistics module. If you're using Python 2, then you can replace the stdev function with of your own (which you can easily find on Google or Stackoverflow)</p>
<pre><code>import random as rd
import statistics as st
min_val = 20
max_val = 46
sample_count = 22
expected_mean = 27
num_of_trials = 5
def get_samples_list(min_v, max_v, s_count, exp_mean):
target_sum = sample_count * expected_mean
samples_list = []
curr_stdev_max = 0
for trials in range(num_of_trials):
samples = [0] * sample_count
while sum(samples) != target_sum:
samples = [rd.randint(min_v, max_v) for trial in range(s_count)]
print ("Mean: ", st.mean(samples), "Std Dev: ", st.stdev(samples), )
print (samples, "\n")
if st.stdev(samples) > curr_stdev_max:
curr_stdev_max = st.stdev(samples)
samples_best = samples[:]
return samples_best
samples_list = get_samples_list(min_val, max_val, sample_count, expected_mean)
print ("\nFinal list: ",samples_list)
samples_list.sort()
print ("\nSorted Final list: ",samples_list)
</code></pre>
<p>Here is the output:</p>
<pre><code>Mean: 27 Std Dev: 6.90755280213519
[34, 30, 39, 21, 23, 32, 22, 23, 22, 20, 27, 30, 29, 20, 32, 24, 42, 20, 39, 24, 20, 21]
Mean: 27 Std Dev: 6.07100838882165
[21, 21, 34, 27, 35, 22, 29, 34, 24, 21, 20, 22, 20, 23, 26, 29, 28, 31, 30, 41, 21, 35]
Mean: 27 Std Dev: 6.2105900340811875
[26, 27, 26, 26, 25, 42, 32, 23, 21, 34, 23, 20, 25, 25, 21, 27, 40, 21, 26, 26, 37, 21]
Mean: 27 Std Dev: 8.366600265340756
[27, 22, 22, 44, 41, 21, 28, 36, 21, 23, 21, 25, 20, 20, 39, 46, 23, 25, 21, 23, 20, 26]
Mean: 27 Std Dev: 6.347102826149446
[21, 30, 20, 41, 25, 23, 39, 26, 27, 20, 28, 23, 29, 24, 20, 40, 27, 27, 22, 25, 34, 23]
Final list: [27, 22, 22, 44, 41, 21, 28, 36, 21, 23, 21, 25, 20, 20, 39,
46, 23, 25, 21, 23, 20, 26]
Sorted Final list: [20, 20, 20, 21, 21, 21, 21, 22, 22, 23, 23, 23, 25, 25,
26, 27, 28, 36, 39, 41, 44, 46]
>>>
</code></pre>
| 1 |
2016-09-11T13:10:53Z
|
[
"python",
"math"
] |
How to generate numbers in range with specific average with Python?
| 39,435,481 |
<p>For example I would like to generate 22 numbers between 20 and 46 with an average value of 27. And I would like the numbers to cover the range as well as possible.</p>
<p>EDIT:
These numbers don't need to be random.</p>
| 1 |
2016-09-11T11:14:23Z
| 39,445,629 |
<p>Not optimal in terms of covering the range as much as possible, but you can try this:</p>
<pre><code>def GenerateArr(count,minimum,maximum,average):
arr = []
diff = 1
while len(arr) < count-1:
if minimum <= average-diff and average+diff <= maximum:
arr.append(average-diff)
arr.append(average+diff)
diff += 1
else:
arr.append(average)
diff = 1
if len(arr) < count:
arr.append(average)
return arr
print GenerateArr(22,20,46,27)
</code></pre>
| 1 |
2016-09-12T07:50:44Z
|
[
"python",
"math"
] |
How to run Scrapy unit tests in Pycharm
| 39,435,518 |
<p>I am working with Pycharm, trying to run scrapy unit tests - and it fails to run.
The errors are for missing imports, seems like all imports are failing.
e.g.</p>
<pre><code> Import error... "no module named mock"
</code></pre>
<p>what I did:</p>
<ol>
<li><p>Get scrapy from github</p></li>
<li><p>Run pip to install all dependencies from requirements.txt</p></li>
<li><p>Installed TOX , made sure I can run the tests using TOX.</p></li>
<li><p>Configured Pycharm to run tests using py.test</p></li>
</ol>
<p>I'm working on Ubuntu 14.04, Python 2.7 .</p>
| 4 |
2016-09-11T11:18:02Z
| 39,435,565 |
<p>You need to additionally pip install the <a href="https://github.com/scrapy/scrapy/blob/master/tests/requirements.txt" rel="nofollow">tests requirements</a>:</p>
<pre><code>pip install -r tests/requirements.txt # Python 2
pip install -r tests/requirements-py3.txt # Python 3
</code></pre>
<p>That would install the <code>mock</code> package and solve the <code>no module named mock</code> on Python 2 (assuming you are installing into the same environment, you are running tests from).</p>
<hr>
<p>Note that to run the tests, you should use <code>tox</code> (which would also install the missing dependencies from <code>requirements.txt</code> during a test run setup phase):</p>
<pre><code>tox -- tests/test_loader.py
</code></pre>
<p>(just done all of that and the tests are running and passing for me).</p>
<p>FYI, here is my PyCharm configuration for the tox runner:</p>
<p><a href="http://i.stack.imgur.com/xPgw3.png" rel="nofollow"><img src="http://i.stack.imgur.com/xPgw3.png" alt="enter image description here"></a></p>
| 4 |
2016-09-11T11:24:31Z
|
[
"python",
"python-2.7",
"scrapy",
"pycharm"
] |
"Can't load the profile" error occured with Selenium WebDriver by Python3.5 and FF48
| 39,435,532 |
<p> I'm trying to use Selenium with Python.<br />
So, I wrote the following codes and save as the file named <strong>test.py</strong> in working directory <strong>/Users/ykt68/seleniumwork</strong> .</p>
<pre class="lang-none prettyprint-override"><code>[ykt68@macbp15 seleniumwork]$ pwd
/Users/ykt68/seleniumwork
[ykt68@macbp15 seleniumwork]$ cat -n test.py
</code></pre>
<pre class="lang-py prettyprint-override"><code> 1 #! /usr/bin/env python
2 # -*- encoding: utf-8 -*-
3
4 from selenium import webdriver
5 from selenium.webdriver.common.keys import Keys
6
7 driver = webdriver.Firefox()
8 driver.get("http://www.python.org")
9 assert "Python" in driver.title
10 elem = driver.find_element_by_name("q")
11 elem.clear()
12 elem.send_keys("pycon")
13 elem.send_keys(Keys.RETURN)
14 assert "No results found." not in driver.page_source
15 driver.close()
</code></pre>
<pre class="lang-none prettyprint-override"><code>[ykt68@macbp15 seleniumwork]$
</code></pre>
<p> These codes above are the same as <a href="http://selenium-python.readthedocs.io/getting-started.html#simple-usage" rel="nofollow">2.1 Simple Usage</a> in documents of <a href="http://selenium-python.readthedocs.io/index.html" rel="nofollow">Selenium with Python</a>.</p>
<p> When I ran the python command for test.py above,</p>
<ul>
<li>FireFox browser started and opened a blank tab.</li>
<li>And after about 30 seconds have passed, the following error messages were displayed and FireFox window was closed.</li>
</ul>
<pre class="lang-none prettyprint-override"><code>[ykt68@macbp15 seleniumwork]$ python test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
driver = webdriver.Firefox()
File "/Users/ykt68/.pyenv/versions/seleniumwork/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__
self.binary, timeout)
File "/Users/ykt68/.pyenv/versions/seleniumwork/lib/python3.5/site-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__
self.binary.launch_browser(self.profile, timeout=timeout)
File "/Users/ykt68/.pyenv/versions/seleniumwork/lib/python3.5/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser
self._wait_until_connectable(timeout=timeout)
File "/Users/ykt68/.pyenv/versions/seleniumwork/lib/python3.5/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 108, in _wait_until_connectable
% (self.profile.path))
selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /var/folders/86/55p1gj4j4xz2nw9g5q224bk40000gn/T/tmpf0uolidn If you specified a log_file in the FirefoxBinary constructor, check it for details.
[ykt68@macbp15 seleniumwork]$
</code></pre>
<p> Please teach me why this error has occured and how to solve the problem or list some posts or documents I should refer.</p>
<p> In addition, </p>
<ol>
<li>Environments:
<ul>
<li>OS: Apple OS X Version 10.11.6</li>
<li>Python Version: 3.5.2</li>
<li>FireFox Version: 48.0.2</li>
<li>selenium Version: 2.53.6</li>
</ul></li>
</ol>
<pre class="lang-none prettyprint-override"><code>[ykt68@macbp15 seleniumwork]$ python -V
Python 3.5.2
[ykt68@macbp15 seleniumwork]$ /Applications/Firefox.app/Contents/MacOS/firefox -v
Mozilla Firefox 48.0.2
[ykt68@macbp15 seleniumwork]$ /Applications/Firefox.app/Contents/MacOS/firefox-bin -v
Mozilla Firefox 48.0.2
[ykt68@macbp15 seleniumwork]$ pip list
pip (8.1.2)
selenium (2.53.6)
setuptools (20.10.1)
[ykt68@macbp15 seleniumwork]$
</code></pre>
<ol start="2">
<li>I reffered the similar post of
<a href="http://stackoverflow.com/questions/6682009/selenium-firefoxprofile-exception-cant-load-the-profile">Selenium: FirefoxProfile exception Can't load the profile</a>. So I tried</li>
</ol>
<pre><code>pip install -U selenium
</code></pre>
<p>But the situation with error messages above remains unchanged.</p>
<p>Best Regards.</p>
| 4 |
2016-09-11T11:19:46Z
| 39,435,615 |
<p>From what I understand and concluded, you can keep the latest <code>selenium</code> package version, but you have to <em>downgrade Firefox to 47</em> (<a href="https://ftp.mozilla.org/pub/firefox/releases/47.0.1/" rel="nofollow">47.0.1</a> is the latest stable from the 47 branch).</p>
| 2 |
2016-09-11T11:31:21Z
|
[
"python",
"selenium",
"selenium-webdriver"
] |
Transforming string output to JSON
| 39,435,620 |
<p>I'm getting some data from an external system (Salesforce Marketing Cloud) over API and I'm getting the data back in the format below:</p>
<pre><code>Results: [(List){
Client =
(ClientID){
ID = 113903
}
PartnerKey = None
CreatedDate = 2013-07-29 04:43:32.000073
ModifiedDate = 2013-07-29 04:43:32.000073
ID = 1966872
ObjectID = None
CustomerKey = "343431CD-031D-43C7-981F-51B778A5A47F"
ListName = "PythonSDKList"
Category = 578615
Type = "Private"
Description = "This list was created with the PythonSDK"
ListClassification = "ExactTargetList"
}]
</code></pre>
<p>It's tantalisingly close to JSON, I'd like to format it like a JSON file so that I can import it into our database. Any ideas of how I can do this?</p>
<p>Thanks</p>
| 5 |
2016-09-11T11:31:52Z
| 39,440,076 |
<p>It looks like an object called suds which is already in Python. The Fuel-SDK uses it.</p>
<p>The suds object already did that for you. Just call the attribute you are looking for.</p>
<p><BR>
However, if you want it as a dict, attached is the common function for that:</p>
<pre><code>from suds.sudsobject import asdict
def recursive_asdict(d):
out = {}
for k, v in asdict(d).iteritems():
if hasattr(v, '__keylist__'):
out[k] = recursive_asdict(v)
elif isinstance(v, list):
out[k] = []
for item in v:
if hasattr(item, '__keylist__'):
out[k].append(recursive_asdict(item))
else:
out[k].append(item)
else:
out[k] = v
return out
def suds_to_json(data):
return json.dumps(recursive_asdict(data))
</code></pre>
<p>The first one will translate it to dict and the second one to proper json.</p>
<p>Some useful links:
<a href="https://fedorahosted.org/suds/wiki/Documentation" rel="nofollow">https://fedorahosted.org/suds/wiki/Documentation</a></p>
| 1 |
2016-09-11T19:56:04Z
|
[
"python",
"json"
] |
Transforming string output to JSON
| 39,435,620 |
<p>I'm getting some data from an external system (Salesforce Marketing Cloud) over API and I'm getting the data back in the format below:</p>
<pre><code>Results: [(List){
Client =
(ClientID){
ID = 113903
}
PartnerKey = None
CreatedDate = 2013-07-29 04:43:32.000073
ModifiedDate = 2013-07-29 04:43:32.000073
ID = 1966872
ObjectID = None
CustomerKey = "343431CD-031D-43C7-981F-51B778A5A47F"
ListName = "PythonSDKList"
Category = 578615
Type = "Private"
Description = "This list was created with the PythonSDK"
ListClassification = "ExactTargetList"
}]
</code></pre>
<p>It's tantalisingly close to JSON, I'd like to format it like a JSON file so that I can import it into our database. Any ideas of how I can do this?</p>
<p>Thanks</p>
| 5 |
2016-09-11T11:31:52Z
| 39,440,332 |
<p>To convert your array, you could use
var jsonString = JSON.stringify(yourArray);</p>
| 2 |
2016-09-11T20:28:19Z
|
[
"python",
"json"
] |
ERR IOError: [Errno 21] Is a directory: '/app/.heroku/python/lib/python2.7/site-packages/setuptools-20.3-py2.7.egg'
| 39,435,645 |
<p>I try to deploy a Flask app in python (python 2.7.10).
It is a very easy app with requirements.txt </p>
<ul>
<li>Flask==0.10.1</li>
<li>distribute==0.6.27</li>
<li>setuptools==20.3</li>
<li>scipy==0.17</li>
<li>matplotlib==1.5.1</li>
<li>pickleshare==0.7.2</li>
<li>scikit-learn==0.17.1</li>
<li>numpy==1.11.1</li>
</ul>
<p>The app worked locally.
I now try to deploy it on IBM Bluemix and after pasting the command </p>
<pre><code>sudo cf push app
sudo cf logs predict_population --recent
</code></pre>
<p>I have this error:</p>
<pre><code>ERR Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-bPyipf/distribute/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-RwvTnr-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-bPyipf/distribute/ 2016-09-11T14:09:39.93+0300
[STG/0] ERR Traceback (most recent call last): 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/bin/pip", line 9, in <module> 2016-09-11T14:09:39.93+0300
[STG/0] ERR load_entry_point('pip==8.1.1', 'console_scripts', 'pip')() 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/__init__.py", line 217, in main 2016-09-11T14:09:39.93+0300
[STG/0] ERR return command.main(cmd_args) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecommand.py", line 246, in main 2016-09-11T14:09:39.93+0300
[STG/0] ERR pip_version_check(session) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/utils/outdated.py", line 102, in pip_version_check 2016-09-11T14:09:39.93+0300
[STG/0] ERR installed_version = get_installed_version("pip") 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/utils/__init__.py", line 848, in get_installed_version 2016-09-11T14:09:39.93+0300
[STG/0] ERR working_set = pkg_resources.WorkingSet() 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 626, in __init__ 2016-09-11T14:09:39.93+0300
[STG/0] ERR self.add_entry(entry) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 682, in add_entry 2016-09-11T14:09:39.93+0300
[STG/0] ERR for dist in find_distributions(entry, True): 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 2080, in find_eggs_in_zip 2016-09-11T14:09:39.93+0300
[STG/0] ERR if metadata.has_metadata('PKG-INFO'): 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 1610, in has_metadata 2016-09-11T14:09:39.93+0300
[STG/0] ERR return self.egg_info and self._has(self._fn(self.egg_info, name)) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 1968, in _has 2016-09-11T14:09:39.93+0300
[STG/0] ERR return zip_path in self.zipinfo or zip_path in self._index() 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 1848, in zipinfo 2016-09-11T14:09:39.93+0300
[STG/0] ERR return self._zip_manifests.load(self.loader.archive) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 1791, in load 2016-09-11T14:09:39.93+0300
[STG/0] ERR manifest = self.build(path) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 1764, in build 2016-09-11T14:09:39.93+0300
[STG/0] ERR with ContextualZipFile(path) as zfile: 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.1-py2.7.egg/pip/_vendor/pkg_resources/__init__.py", line 1813, in __new__ 2016-09-11T14:09:39.93+0300
[STG/0] ERR return zipfile.ZipFile(*args, **kwargs) 2016-09-11T14:09:39.93+0300
[STG/0] ERR File "/app/.heroku/python/lib/python2.7/zipfile.py", line 756, in __init__ 2016-09-11T14:09:39.94+0300
[STG/0] ERR self.fp = open(file, modeDict[mode]) 2016-09-11T14:09:39.94+0300
[STG/0] ERR IOError: [Errno 21] Is a directory: '/app/.heroku/python/lib/python2.7/site-packages/setuptools-20.3-py2.7.egg'
</code></pre>
| 0 |
2016-09-11T11:35:46Z
| 39,449,227 |
<p>Solved ! Instead of writing if name == "main": app.run() Just do port = os.getenv('PORT', PORT_NUMBER) if name == "main": app.run(host='0.0.0.0', port=int(port)) and it works !</p>
| 0 |
2016-09-12T11:23:59Z
|
[
"python",
"heroku",
"flask",
"ibm-bluemix"
] |
Wagtail: How can I copy a page instance in wagtail with all its property and method
| 39,435,711 |
<p>I have a CoursePage model in Wagtail site.</p>
<pre><code>class CoursePage(Page):
.....
institute = models.ForeignKey(Institute)
.....
</code></pre>
<p>I have a django models ForeignKey field in it named <em>institute</em></p>
<p>I want to make a copy of its instance programmatically so that the newly created instance <strong>institute</strong> field can be modified.</p>
<p>I tried django approach of copying model instance, that is:</p>
<pre><code>course = CoursePage.objects.all()[0]
course.pk = None
course.save()
</code></pre>
<p>But it doesnot work out.
It only works with the model inherited with django <em>models.Model</em>. but not with the model inherited with <strong>Page</strong></p>
| 0 |
2016-09-11T11:43:42Z
| 39,437,618 |
<p>The <code>Page</code> model implements a <code>copy</code> method to do this:</p>
<pre><code>def copy(self, recursive=False, to=None, update_attrs=None,
copy_revisions=True, keep_live=True, user=None):
</code></pre>
<p>The parameters it accepts are:</p>
<ul>
<li><code>recursive</code> - if true, copies child pages as well</li>
<li><code>to</code> - the page to create the new copy under (defaults to creating a sibling of the existing page)</li>
<li><code>update_attrs</code> - a dict of fields to update while copying, such as <code>{'institute': other_institute}</code></li>
<li><code>copy_revisions</code> - whether to copy revision history</li>
<li><code>keep_live</code> - whether to copy the 'live' status</li>
<li><code>user</code> - the owner of the new page, for permission purposes</li>
</ul>
| 1 |
2016-09-11T15:21:16Z
|
[
"python",
"django-models",
"wagtail"
] |
Setting scan coordinates in device options on pyinsane
| 39,435,820 |
<p>I use Sane's command line utility (<code>scanimage</code>) in order to scan films from the transparency unit of my scanner. Here is the command that I have been using with success:</p>
<pre><code>scanimage --device-name pixma:04A9190D \
--source 'Transparency Unit' \
--resolution "4800" \
--format "tiff" \
--mode "color" \
-l "80.6" -x "56.2" -t "25.8" -y "219.2" \
> scan.tiff
</code></pre>
<p>I have decided to move this to Python code, using <code>pyinsane</code> in order to enable further integration with my image-processing workflow. This should supposedly give the following in Python code:</p>
<pre><code>import pyinsane.abstract as pyinsane
device = pyinsane.get_devices()[0]
device.options['resolution'].value = 4800
device.options['mode'].value = 'Color'
device.options['source'].value = 'Transparency Unit'
# Setting coordinates to non-integers fails
device.options['tl-y'].value = 25.8
device.options['tl-x'].value = 80.6
device.options['br-y'].value = 219.2
device.options['br-x'].value = 56.2
scan_session = device.scan(multiple=False)
try:
while True:
scan_session.scan.read()
except EOFError:
pass
image = scan_session.images[0]
</code></pre>
<p>But my first trials have been unsuccessful because I can not figure out how to set the scan coordinates <code>pyinsane</code>. As you see, I have found the appropriate options, but I don't know what unit they are in. <code>scanimage</code> takes the coordinates in millimetres by default, but <code>pyinsane</code> only takes integers. I have tried using pixel coordinates to no avail. I wonder what units the coordinate parameters take, and whether I am using them in the right order.</p>
| 0 |
2016-09-11T11:58:12Z
| 39,449,601 |
<p>pyinsane's option descriptions actually say the values are in milimeters: </p>
<pre><code>Option: br-x
Title: Bottom-right x
Desc: Bottom-right x position of scan area.
Type: <class 'pyinsane.rawapi.SaneValueType'> : Fixed (2)
Unit: <class 'pyinsane.rawapi.SaneUnit'> : Mm (3)
Size: 4
Capabilities: <class 'pyinsane.rawapi.SaneCapabilities'> :[ Automatic, Soft_select, Soft_detect,]
Constraint type: <class 'pyinsane.rawapi.SaneConstraintType'> : Range (1)
Constraint: (0, 14160319, 0)
Value: 20
</code></pre>
<p>But they are not! I divided the range maximum for <code>br-x</code> variable by the width of the scanning area of my scanner, and I got to the number 65536 (which is 2^16). Setting the coordinates to the millimetre value times 65536 works. Maybe these values define the number of steps of the stepper motor?</p>
<p>Also not that while scanimage interprets the <code>-x</code> and <code>-y</code> switches as width and length, and the <code>-l</code> and <code>-t</code> switches as offset, pyinsane takes bottom-right x (<code>br-x</code>), top-left y (<code>tl-y</code>), etc.</p>
| 0 |
2016-09-12T11:47:26Z
|
[
"python",
"scanning",
"sane",
"pyinsane"
] |
Setting scan coordinates in device options on pyinsane
| 39,435,820 |
<p>I use Sane's command line utility (<code>scanimage</code>) in order to scan films from the transparency unit of my scanner. Here is the command that I have been using with success:</p>
<pre><code>scanimage --device-name pixma:04A9190D \
--source 'Transparency Unit' \
--resolution "4800" \
--format "tiff" \
--mode "color" \
-l "80.6" -x "56.2" -t "25.8" -y "219.2" \
> scan.tiff
</code></pre>
<p>I have decided to move this to Python code, using <code>pyinsane</code> in order to enable further integration with my image-processing workflow. This should supposedly give the following in Python code:</p>
<pre><code>import pyinsane.abstract as pyinsane
device = pyinsane.get_devices()[0]
device.options['resolution'].value = 4800
device.options['mode'].value = 'Color'
device.options['source'].value = 'Transparency Unit'
# Setting coordinates to non-integers fails
device.options['tl-y'].value = 25.8
device.options['tl-x'].value = 80.6
device.options['br-y'].value = 219.2
device.options['br-x'].value = 56.2
scan_session = device.scan(multiple=False)
try:
while True:
scan_session.scan.read()
except EOFError:
pass
image = scan_session.images[0]
</code></pre>
<p>But my first trials have been unsuccessful because I can not figure out how to set the scan coordinates <code>pyinsane</code>. As you see, I have found the appropriate options, but I don't know what unit they are in. <code>scanimage</code> takes the coordinates in millimetres by default, but <code>pyinsane</code> only takes integers. I have tried using pixel coordinates to no avail. I wonder what units the coordinate parameters take, and whether I am using them in the right order.</p>
| 0 |
2016-09-11T11:58:12Z
| 39,919,746 |
<p>Pyinsane reports what Sane reports, as is. And Sane reports what the drivers report. In my experience, all the drivers don't behave exactly the same way, which may explain this weird unit (in other words, it could be a driver's bug). I never really worried about the unit before. I will check on my scanner what it says when I have some time..</p>
<p>Anyway I'm unsure why it does say 'mm', because in my experience, the unit here is actually always pixels (again, the documentation says it can be 'mm', so I need to check).
If you want to scan a specific size, you should have a look at the resolution (dot per inch), and then do the math to figure out the size in pixels you expect.</p>
| 0 |
2016-10-07T14:31:06Z
|
[
"python",
"scanning",
"sane",
"pyinsane"
] |
Django rest framework, should be able to override get_queryset and not define queryset attribute?
| 39,435,836 |
<p>I am confused. Looking through the ViewSet source code it looks like I should be able to not define a queryset in a viewset and then just override the get queryset function to get whatever queryset I want. But my code fails with this error:</p>
<pre><code>AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute.
</code></pre>
<p>So even if I override the queryset attribute I still need to set it to some fake attribute in the beginning... this works, but it feels weird to define the queryset and then just override it a second later.</p>
<pre><code>class StudyQuestion(viewsets.ReadOnlyModelViewSet):
queryset = Model.objects.all()
serializer_class = ModelSerializer
permission_classes = (permissions.IsAuthenticated, )
def get_queryset(self):
""""""
return Model.objects.order_by('-word__frequency')
</code></pre>
| 1 |
2016-09-11T12:01:09Z
| 39,436,581 |
<p>DRF Router is complaining, because it can't <a href="http://www.django-rest-framework.org/api-guide/routers/" rel="nofollow">automatically generate a basename for the viewset</a>:</p>
<blockquote>
<p><strong>base_name</strong> - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set base_name when registering the viewset.</p>
</blockquote>
| 1 |
2016-09-11T13:25:39Z
|
[
"python",
"django",
"django-rest-framework"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.