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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Debugging a Python Prime Number Program | 38,567,337 | <p>I wrote the code for a Python prime number generator, to generate the first 100 primes. But, somehow, I get non-primes like 22, 25, etc. in my output. I've rechecked it over and over again for hours now and still can't figure out where I went wrong... Please help!</p>
<p>Here's my code:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
else:
y.append(x)
x=x+1
break
print(y)
</code></pre>
| 2 | 2016-07-25T12:06:17Z | 38,567,679 | <p>I would have done it this way; a bit more Pythonic:</p>
<pre><code>y = [2]
x = 3
while len(y) < 100:
if all(x % i != 0 for i in range(2, int(round(sqrt(x) + 1)))):
y.append(x)
x = x + 1
print(y)
</code></pre>
<p>The <code>all()</code> function is very useful, read about <a class='doc-link' href="http://stackoverflow.com/documentation/python/209/list/8125/any-and-all#t=201607251235132359487">all and any</a>.
Also read about the <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201607251234215953846">list comprehensions</a> that I've used inside of the <code>all()</code>.</p>
<p>This is more similar to what you did; please note the <code>break</code> statement and what it does:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y) != 100:
is_prime = True
for i in range (2, int(round(sqrt(x) + 1))):
if x % i == 0:
x += 1
is_prime = False
break # this means that x is not prime and we can move on, note that break breaks only the for loop
if is_prime:
y.append(x)
x += 1
print(y)
</code></pre>
| 6 | 2016-07-25T12:23:04Z | [
"python",
"debugging"
] |
Debugging a Python Prime Number Program | 38,567,337 | <p>I wrote the code for a Python prime number generator, to generate the first 100 primes. But, somehow, I get non-primes like 22, 25, etc. in my output. I've rechecked it over and over again for hours now and still can't figure out where I went wrong... Please help!</p>
<p>Here's my code:</p>
<pre><code>from math import sqrt
y=[2]
x=3
while len(y)!=100:
for i in range (2,int(round(sqrt(x)+1))):
if x%i==0:
x=x+1
else:
y.append(x)
x=x+1
break
print(y)
</code></pre>
| 2 | 2016-07-25T12:06:17Z | 38,567,768 | <p>The other answers are correct, but none of them show that you can actually use an <code>else</code> clause on the <code>for</code> loop. Read more about this <a href="http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html" rel="nofollow">here</a>. So you don't need the <code>if is_prime:</code> statement. The resulting code could look something like this.</p>
<pre><code> from math import sqrt
y = [2]
x = 3
while len(y) != 100:
for i in range (2, int(round(sqrt(x) + 1))):
if x % i == 0:
x = x + 1
break
else:
y.append(x)
x = x + 1
print(y)
</code></pre>
<p>Tip: <code>x+=1</code> could replace <code>x=x+1</code></p>
<p>Furthermore, as @user2346536, you can actually use a much more efficient algorithm for calculating the prime numbers, which will be important if you are looping over large numbers.</p>
| 4 | 2016-07-25T12:26:49Z | [
"python",
"debugging"
] |
Writting several files according to an element of an original file | 38,567,536 | <p>I need to read a file in bed format that contains coordinates of all chr in a genome, into different files according with the chr. I tried this approach but it doesn't work, it doesn't create any files. Any idees why this happens or alternative approaches to solve this problem?</p>
<pre><code>import sys
def make_out_file(dir_path, chr_name, extension):
file_name = dir_path + "/" + chr_name + extension
out_file = open(file_name, "w")
out_file.close()
return file_name
def append_output_file(line, out_file):
with open(out_file, "a") as f:
f.write(line)
f.close()
in_name = sys.argv[1]
dir_path = sys.argv[2]
with open(in_name, "r") as in_file:
file_content = in_file.readlines()
chr_dict = {}
out_file_dict = {}
line_count = 0
for line in file_content[:0]:
line_count += 1
elems = line.split("\t")
chr_name = elems[0]
chr_dict[chr_name] += 1
if chr_dict.get(chr_name) = 1:
out_file = make_out_file(dir_path, chr_name, ".bed")
out_file_dict[chr_name] = out_file
append_output_file(line, out_file)
elif chr_dict.get(chr_name) > 1:
out_file = out_file_dict.get(chr_name)
append_output_file(line, out_file)
else:
print "There's been an Error"
in_file.close()
</code></pre>
| 0 | 2016-07-25T12:16:28Z | 38,567,909 | <p>This line:</p>
<pre><code>for line in file_content[:0]:
</code></pre>
<p>says to iterate over an empty list. The empty list comes from the slice <code>[:0]</code> which says to slice from the beginning of the list to just before the first element. Here's a demonstration:</p>
<pre><code>>>> l = ['line 1\n', 'line 2\n', 'line 3\n']
>>> l[:0]
[]
>>> l[:1]
['line 1\n']
</code></pre>
<p>Because the list is empty no iteration takes place, so the code in the body of your for loop in not executed.</p>
<p>To iterate over each line of the file you do not need the slice:</p>
<pre><code>for line in file_content:
</code></pre>
<p>However, it is better again to iterate over the file object as this does not require that the whole file be first read into memory:</p>
<pre><code>with open(in_name, "r") as in_file:
chr_dict = {}
out_file_dict = {}
line_count = 0
for line in in_file:
...
</code></pre>
<p>Following that there are numerous problems, including syntax errors, with the code in the for loop which you can begin debugging.</p>
| 1 | 2016-07-25T12:32:22Z | [
"python",
"file"
] |
Where should I clone into when cloning a python packages from github? | 38,567,555 | <p>Problem: the package I want to install is outdated on pip, and conda doesn't have it in the repo. So, when I install a python package from github using, </p>
<pre><code>git clone package_url
cd package_name
python setup.py
</code></pre>
<p>should I DOWNLOAD the package from within the directory that is the directory in which conda or pip usually would install my package? For example, should I run git clone from within:</p>
<pre><code>['/Users/home/anaconda/lib/python2.7/site-packages',
'/Users/home/anaconda/lib/site-python']
</code></pre>
<p>OR, can I just run git clone, from whatever directory I happen to be in. </p>
<p>The concern is that I download from git in something like, /Users/home/Downloads, and then, when I run the setup.py file, I would only install within the /Users/home/Downloads directory, and then when I import, I wouldn't be able to find the package.</p>
<p>Accepted answer: I can run the git clone command in terminal from within any directory. Then, I can change directory into the newly established directory for the package that I cloned, and run the setup.py script. Running the setup.py script should "automatically install [the package] within the site-packages of whatever python [is being] used when python [is invoked]". I hope this helps someone overly anxious about running setup.py files. </p>
| 0 | 2016-07-25T12:17:41Z | 38,567,632 | <p>Run it from the folder containing <code>setup.py</code>.</p>
<p>Doing:</p>
<pre><code>python setup.py install
</code></pre>
<p>Will install the package in the appropriate directory. The file already contains the logic that puts the package in the right installation directory, so you don't need to worry about how the package make its way to its installation directory.</p>
| 0 | 2016-07-25T12:21:04Z | [
"python",
"git",
"github",
"packages",
"setup.py"
] |
Where should I clone into when cloning a python packages from github? | 38,567,555 | <p>Problem: the package I want to install is outdated on pip, and conda doesn't have it in the repo. So, when I install a python package from github using, </p>
<pre><code>git clone package_url
cd package_name
python setup.py
</code></pre>
<p>should I DOWNLOAD the package from within the directory that is the directory in which conda or pip usually would install my package? For example, should I run git clone from within:</p>
<pre><code>['/Users/home/anaconda/lib/python2.7/site-packages',
'/Users/home/anaconda/lib/site-python']
</code></pre>
<p>OR, can I just run git clone, from whatever directory I happen to be in. </p>
<p>The concern is that I download from git in something like, /Users/home/Downloads, and then, when I run the setup.py file, I would only install within the /Users/home/Downloads directory, and then when I import, I wouldn't be able to find the package.</p>
<p>Accepted answer: I can run the git clone command in terminal from within any directory. Then, I can change directory into the newly established directory for the package that I cloned, and run the setup.py script. Running the setup.py script should "automatically install [the package] within the site-packages of whatever python [is being] used when python [is invoked]". I hope this helps someone overly anxious about running setup.py files. </p>
| 0 | 2016-07-25T12:17:41Z | 38,567,667 | <p>You can run the setup.py file as you stated, and you follow it by install as follow: </p>
<pre><code>python setup.py install
</code></pre>
<p>Usually, this would lead to installing the package you want to the python path.</p>
| 0 | 2016-07-25T12:22:38Z | [
"python",
"git",
"github",
"packages",
"setup.py"
] |
Where should I clone into when cloning a python packages from github? | 38,567,555 | <p>Problem: the package I want to install is outdated on pip, and conda doesn't have it in the repo. So, when I install a python package from github using, </p>
<pre><code>git clone package_url
cd package_name
python setup.py
</code></pre>
<p>should I DOWNLOAD the package from within the directory that is the directory in which conda or pip usually would install my package? For example, should I run git clone from within:</p>
<pre><code>['/Users/home/anaconda/lib/python2.7/site-packages',
'/Users/home/anaconda/lib/site-python']
</code></pre>
<p>OR, can I just run git clone, from whatever directory I happen to be in. </p>
<p>The concern is that I download from git in something like, /Users/home/Downloads, and then, when I run the setup.py file, I would only install within the /Users/home/Downloads directory, and then when I import, I wouldn't be able to find the package.</p>
<p>Accepted answer: I can run the git clone command in terminal from within any directory. Then, I can change directory into the newly established directory for the package that I cloned, and run the setup.py script. Running the setup.py script should "automatically install [the package] within the site-packages of whatever python [is being] used when python [is invoked]". I hope this helps someone overly anxious about running setup.py files. </p>
| 0 | 2016-07-25T12:17:41Z | 38,567,698 | <p>It can be simpler to use <code>pip</code> for this package as well, by pointing <code>pip</code> directly at the URL:</p>
<pre><code>pip install git+http://....git
</code></pre>
<p>The <code>git+</code> in front of the URL is required.</p>
<p>You can even go a step further and install a specific branch:</p>
<pre><code>pip install git+http://....git@branchname
</code></pre>
| 0 | 2016-07-25T12:23:52Z | [
"python",
"git",
"github",
"packages",
"setup.py"
] |
What is the issue with inheritance in this code? | 38,567,613 | <pre><code>class a(object):
def __init__(self):
self.num1=0
self.num2=0
def set1(self,score1,score2):
self.num1=score1
self.num2=score2
def show1(self):
print("num1",self.num1,"num2",self.num2)
class b(a):
def __init__(self):
super().__init__()
def set2(self):
self.sum=self.num1+self.num2
def show2(self):
print("d=",self.sum)
class c(b):
def __init__(self):
super.__init__()
def set3(self):
self.multiplication=self.num1*self.num2
def show3(self):
print("f=",self.multiplication)
objects=c()
objects.set1(1000,100)
objects.show1()
objects.set2()
objects.show2()
objects.set3()
objects.show3()
</code></pre>
<p>I wrote this code to work on the meaning of inheritance, but I receive: </p>
<pre><code> objects=c()
File "C:\Users\user\Desktop\New folder\2.py", line 23, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
</code></pre>
<p>num1 and num2 are two numbers and I want to calculate sum and multiplication of them via concept of inheritance in Python.
I do not know what is the problem with.What is the problem with this code?
Thanks,</p>
| 0 | 2016-07-25T12:20:24Z | 38,567,678 | <p>You wrote <code>super.__init__()</code> instead of <code>super().__init__()</code> in <code>__init__</code> of class <code>c</code>.</p>
<p>If you are using Python 2 you will need to call <code>super</code> in the following way: <br/><code>super(ClassName, self).__init__()</code>.</p>
| 0 | 2016-07-25T12:23:03Z | [
"python"
] |
What is the issue with inheritance in this code? | 38,567,613 | <pre><code>class a(object):
def __init__(self):
self.num1=0
self.num2=0
def set1(self,score1,score2):
self.num1=score1
self.num2=score2
def show1(self):
print("num1",self.num1,"num2",self.num2)
class b(a):
def __init__(self):
super().__init__()
def set2(self):
self.sum=self.num1+self.num2
def show2(self):
print("d=",self.sum)
class c(b):
def __init__(self):
super.__init__()
def set3(self):
self.multiplication=self.num1*self.num2
def show3(self):
print("f=",self.multiplication)
objects=c()
objects.set1(1000,100)
objects.show1()
objects.set2()
objects.show2()
objects.set3()
objects.show3()
</code></pre>
<p>I wrote this code to work on the meaning of inheritance, but I receive: </p>
<pre><code> objects=c()
File "C:\Users\user\Desktop\New folder\2.py", line 23, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
</code></pre>
<p>num1 and num2 are two numbers and I want to calculate sum and multiplication of them via concept of inheritance in Python.
I do not know what is the problem with.What is the problem with this code?
Thanks,</p>
| 0 | 2016-07-25T12:20:24Z | 38,567,725 | <p>You need to call super, right now its just a reference.</p>
<pre><code>class c(b):
super().__init__()
</code></pre>
<p>The other thing is that if you wanted to make this inheritance more robust, you could pass through all args and kwargs to <code>__init__</code> like so:</p>
<pre><code>def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
</code></pre>
<p>This would make your classes more flexible, and open to multiple inheritance.</p>
| 0 | 2016-07-25T12:25:02Z | [
"python"
] |
What is the issue with inheritance in this code? | 38,567,613 | <pre><code>class a(object):
def __init__(self):
self.num1=0
self.num2=0
def set1(self,score1,score2):
self.num1=score1
self.num2=score2
def show1(self):
print("num1",self.num1,"num2",self.num2)
class b(a):
def __init__(self):
super().__init__()
def set2(self):
self.sum=self.num1+self.num2
def show2(self):
print("d=",self.sum)
class c(b):
def __init__(self):
super.__init__()
def set3(self):
self.multiplication=self.num1*self.num2
def show3(self):
print("f=",self.multiplication)
objects=c()
objects.set1(1000,100)
objects.show1()
objects.set2()
objects.show2()
objects.set3()
objects.show3()
</code></pre>
<p>I wrote this code to work on the meaning of inheritance, but I receive: </p>
<pre><code> objects=c()
File "C:\Users\user\Desktop\New folder\2.py", line 23, in __init__
super.__init__()
TypeError: descriptor '__init__' of 'super' object needs an argument
</code></pre>
<p>num1 and num2 are two numbers and I want to calculate sum and multiplication of them via concept of inheritance in Python.
I do not know what is the problem with.What is the problem with this code?
Thanks,</p>
| 0 | 2016-07-25T12:20:24Z | 38,567,974 | <p>I think it's how you used the <code>super()</code> built-in <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow">Here the doc</a></p>
<p>In your case, super need two argument: the class and an instance of the class.</p>
<p>In your <code>b.__init__</code> the synthax will be:</p>
<pre><code>super(b,self).__init__()
</code></pre>
<p>here the solution for your problem:</p>
<pre><code>class b(a):
def __init__(self):
super(b, self).__init__()
def set2(self):
self.sum=self.num1+self.num2
def show2(self):
print("d=",self.sum)
class c(b):
def __init__(self):
super(c, self).__init__()
def set3(self):
self.multiplication=self.num1*self.num2
def show3(self):
print("f=",self.multiplication)
</code></pre>
| 0 | 2016-07-25T12:35:29Z | [
"python"
] |
Recursive to iterative using a systematic method | 38,567,618 | <p>I've started reading the book <em><a href="https://www.amazon.com/gp/search?index=books&linkCode=qs&keywords=9781107036604" rel="nofollow">Systematic Program Design: From Clarity to Efficiency</a></em> few days ago. Chapter 4 talks about a systematic method to convert any recursive algorithm into its counterpart iterative. It seems this is a really powerful general method but I'm struggling quite a lot to understand how it works.</p>
<p>After reading a few articles talking about recursion removal using custom stacks, it feels like this proposed method would produce a much more readable, optimized and compact output.</p>
<hr>
<h2>Recursive algorithms in Python where I want to apply the method</h2>
<pre><code>#NS: lcs and knap are using implicit variables (i.e.: defined globally), so they won't
#work directly
# n>=0
def fac(n):
if n==0:
return 1
else:
return n*fac(n-1)
# n>=0
def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1)+fib(n-2)
# k>=0, k<=n
def bin(n,k):
if k==0 or k==n:
return 1
else:
return bin(n-1,k-1)+bin(n-1,k)
# i>=0, j>=0
def lcs(i,j):
if i==0 or j==0:
return 0
elif x[i]==y[j]:
return lcs(i-1,j-1)+1
else:
return max(lcs(i,j-1),lcs(i-1,j))
# i>=0, u>=0, for all i in 0..n-1 w[i]>0
def knap(i,u):
if i==0 or u==0:
return 0
elif w[i]>u:
return knap(i-1,u)
else:
return max(v[i]+knap(i-1,u-w[i]), knap(i-1,u))
# i>=0, n>=0
def ack(i,n):
if i==0:
return n+1
elif n==0:
return ack(i-1,1)
else:
return ack(i-1,ack(i,n-1))
</code></pre>
<h2>Step Iterate: Determine minimum increments, transform recursion into iteration</h2>
<p>The Section 4.2.1 the book talks about determining the appropriate increment:</p>
<pre><code>1) All possible recursive calls
fact(n) => {n-1}
fib(n) => {fib(n-1), fib(n-2)}
bin(n,k) => {bin(n-1,k-1),bin(n-1,k)}
lcs(i,j) => {lcs(i-1,j-1),lcs(i,j-1),lcs(i-1,j)}
knap(i,u) => {knap(i-1,u),knap(i-1,u-w[i])}
ack(i,n) => {ack(i-1,1),ack(i-1,ack(i,n-1)), ack(i,n-1)}
2) Decrement operation
fact(n) => n-1
fib(n) => n-1
bin(n,k) => [n-1,k]
lcs(i,j) => [i-1,j]
knap(i,u) => [i-1,u]
ack(i,n) => [i,n-1]
3) Minimum increment operation
fact(n) => next(n) = n+1
fib(n) => next(n) = n+1
bin(n,k) => next(n,k) = [n+1,k]
lcs(i,j) => next(i,j) = [i+1,j]
knap(i,u) => next(i,u) = [i+1,u]
ack(i,n) => next(i,n) = [i,n+1]
</code></pre>
<p>Section 4.2.2 talks about forming the optimized program:</p>
<pre><code>Recursive
---------
def fExtOpt(x):
if base_cond(x) then fExt0(x ) -- Base case
else let rExt := fExtOpt(prev(x)) in -- Recursion
f Extâ(prev(x),rExt) -- Incremental computation
Iterative
---------
def fExtOpt(x):
if base_cond(x): return fExt0(x) -- Base case
x1 := init_arg; rExt := fExt0(x1) -- Initialization
while x1 != x: -- Iteration
x1 := next(x1); rExt := fExtâ(prev(x1),rExt) -- Incremental comp
return rExt
</code></pre>
<p>How do I create <code>{fibExtOpt,binExtOpt,lcsExtOpt,knapExtOpt,ackExtOpt}</code> in Python?</p>
<p>Additional material about this topic can be found in one of <a href="http://www3.cs.stonybrook.edu/~liu/papers/IncEff-HOSC00.pdf" rel="nofollow">the papers</a> of the main author of the method, <a href="http://www3.cs.stonybrook.edu/~liu/" rel="nofollow">Y. Annie Liu, Professor</a>.</p>
| -19 | 2016-07-25T12:20:48Z | 39,128,242 | <p>So, to restate the question. We have a function <em>f</em>, in our case <code>fac</code>. </p>
<pre><code>def fac(n):
if n==0:
return 1
else:
return n*fac(n-1)
</code></pre>
<p>It is implemented recursively. We want to implement a function <code>facOpt</code> that does the same thing but iteratively. <code>fac</code> is written almost in the form we need. Let us rewrite it just a bit:</p>
<pre><code>def fac_(n, r):
return (n+1)*r
def fac(n):
if n==0:
return 1
else:
r = fac(n-1)
return fac_(n-1, r)
</code></pre>
<p>This is exactly the recursive definition from section 4.2. Now we need to rewrite it iteratively:</p>
<pre><code>def facOpt(n):
if n==0:
return 1
x = 1
r = 1
while x != n:
x = x + 1
r = fac_(x-1, r)
return r
</code></pre>
<p>This is exactly the iterative definition from section 4.2. Note that <code>facOpt</code> does not call itself anywhere. Now, this is neither the most clear nor the most pythonic way of writing down this algorithm -- this is just a way to transform one algorithm to another. We can implement the same algorithm differently, e.g. like that:</p>
<pre><code>def facOpt(n):
r = 1
for x in range(1, n+1):
r *= x
return r
</code></pre>
<p>Things get more interesting when we consider more complicated functions. Let us write <code>fibObt</code> where <code>fib</code> is :</p>
<pre><code>def fib(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fib(n-1) + fib(n-2)
</code></pre>
<p><code>fib</code> calls itself two times, but the recursive pattern from the book allows only a single call. That is why we need to extend the function to returning not one, but two values. Fully reformated, <code>fib</code> looks like this:</p>
<pre><code>def fibExt_(n, rExt):
return rExt[0] + rExt[1], rExt[0]
def fibExt(n):
if n == 0:
return 0, 0
elif n == 1:
return 1, 0
else:
rExt = fibExt(n-1)
return fibExt_(n-1, rExt)
def fib(n):
return fibExt(n)[0]
</code></pre>
<p>You may notice that the first argument to <code>fibExt_</code> is never used. I just added it to follow the proposed structure exactly.
Now, it is again easy to turn <code>fib</code> into an iterative version:</p>
<pre><code>def fibExtOpt(n):
if n == 0:
return 0, 0
if n == 1:
return 1, 0
x = 2
rExt = 1, 1
while x != n:
x = x + 1
rExt = fibExt_(x-1, rExt)
return rExt
def fibOpt(n):
return fibExtOpt(n)[0]
</code></pre>
<p>Again, the new version does not call itself. And again one can streamline it to this, for example:</p>
<pre><code>def fibOpt(n):
if n < 2:
return n
a, b = 1, 1
for i in range(n-2):
a, b = b, a+b
return b
</code></pre>
<p>The next function to translate to iterative version is <code>bin</code>:</p>
<pre><code>def bin(n,k):
if k == 0 or k == n:
return 1
else:
return bin(n-1,k-1) + bin(n-1,k)
</code></pre>
<p>Now neither <code>x</code> nor <code>r</code> can be just numbers. The index (<code>x</code>) has two components, and the cache (<code>r</code>) has to be even larger. One (not quite so optimal) way would be to return the whole previous row of the Pascal triangle:</p>
<pre><code>def binExt_(r):
return [a + b for a,b in zip([0] + r, r + [0])]
def binExt(n):
if n == 0:
return [1]
else:
r = binExt(n-1)
return binExt_(r)
def bin(n, k):
return binExt(n)[k]
</code></pre>
<p>I have't followed the pattern so strictly here and removed several useless variables. It is still possible to translate to an iterative version directly:</p>
<pre><code>def binExtOpt(n):
if n == 0:
return [1]
x = 1
r = [1, 1]
while x != n:
r = binExt_(r)
x += 1
return r
def binOpt(n, k):
return binExtOpt(n)[k]
</code></pre>
<p>For completeness, here is an optimized solution that caches only part of the row:</p>
<pre><code>def binExt_(n, k_from, k_to, r):
if k_from == 0 and k_to == n:
return [a + b for a, b in zip([0] + r, r + [0])]
elif k_from == 0:
return [a + b for a, b in zip([0] + r[:-1], r)]
elif k_to == n:
return [a + b for a, b in zip(r, r[1:] + [0])]
else:
return [a + b for a, b in zip(r[:-1], r[1:])]
def binExt(n, k_from, k_to):
if n == 0:
return [1]
else:
r = binExt(n-1, max(0, k_from-1), min(n-1, k_to+1) )
return binExt_(n, k_from, k_to, r)
def bin(n, k):
return binExt(n, k, k)[0]
def binExtOpt(n, k_from, k_to):
if n == 0:
return [1]
ks = [(k_from, k_to)]
for i in range(1,n):
ks.append((max(0, ks[-1][0]-1), min(n-i, ks[-1][1]+1)))
x = 0
r = [1]
while x != n:
x += 1
r = binExt_(x, *ks[n-x], r)
return r
def binOpt(n, k):
return binExtOpt(n, k, k)[0]
</code></pre>
<p>In the end, the most difficult task is not switching from recursive to iterative implementation, but to have a recursive implementation that follows the required pattern. So the real question is how to create <code>fibExt'</code>, not <code>fibExtOpt</code>.</p>
| 3 | 2016-08-24T16:09:43Z | [
"python",
"recursion"
] |
Efficient way to Reshape Data for Time Series Prediction Machine Learning (Numpy) | 38,567,631 | <p>Lets say I have a data set (numpy array) X of N samples of time series each with T time steps of a D-dimensional vector so that:</p>
<pre><code>X.shape == (N,T,D)
</code></pre>
<p>Now I want to reshape it into x (data set) and y (labels) to apply a machine learning to predict the step in the times series.</p>
<p>I want to take every subseries of each sample of length n
<pre><code>x.shape==(N*(T-n),n,D) and y.shape==(N*(T-n)),D)
</code></pre>
<p>with </p>
<pre><code>X[k,j:j+n,:]
</code></pre>
<p>being one of my samples in <code>x</code> and </p>
<pre><code>X[k,j+n+1,:]
</code></pre>
<p>it's label in <code>y</code>.</p>
<p>Is a for-loop the only way to do that? </p>
| 0 | 2016-07-25T12:21:03Z | 38,568,460 | <p>So I have the following method, but it has a for loop, and I am not sure that I cannot do better:</p>
<pre><code> def reshape_data(self, X, n):
"""
Reshape a data set of N time series samples of T time steps each
Args:
data: Time series data of shape (N,T,D)
n: int, length of time window used to predict x[t+1]
Returns:
"""
N,T,D = X.shape
x = np.zeros((N*(T-n),n,D))
y = np.zeros((N*(T-n),D))
for i in range(T-n):
x[N*i:N*(i+1),:,:] = X[:,i:i+n,:]
y[N*i:N*(i+1),:] = X[:,i+n,:]
return x,y
</code></pre>
| 0 | 2016-07-25T12:59:46Z | [
"python",
"numpy",
"machine-learning",
"time-series",
"reshape"
] |
PyCharm - Django settings honoured in run config but not in python console | 38,567,641 | <p>While setting up my django project in PyCharms I am having trouble configuring the python shell for django. My project structure is as follows:</p>
<pre><code>- mysite_root
- deployment
- ...ansible files
- mysite
- __init__.py
- manage.py
- mysite
- __init__.py
- settings.py
- local_dev_settings.py
- app1
- __init__.py
- ...other files
- app2
- __init__.py
- ...other files
</code></pre>
<p>The Sources root is set to <code>mysite_root/mysite</code>
My Run/Debug configuration has the environment variable <code>DJANGO_SETTINGS_MODULE=mysite.local_dev_settings</code> & it works perfectly.
Inside the Project settings under <code>Language & Frameworks --> Django</code> the configuration is as follows:</p>
<pre><code>- Django project root -- <path to mysite_root/mysite>
- Settings -- mysite/local_dev_settings.py
- Manage script -- manage.py
- Environment variables -- DJANGO_SETTINGS_MODULE=mysite.local_dev_settings
</code></pre>
<p>Now, while launching the Python Console or Manage.py Tasks via Tools, I get this error message:</p>
<pre><code>Traceback (most recent call last):
File "/Users/utkarsh/.venvs/mysite/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-4578708c9793>", line 5, in <module>
if 'setup' in dir(django): django.setup()
File "/Users/utkarsh/.venvs/mysite/lib/python3.5/site-packages/django/__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/Users/utkarsh/.venvs/mysite/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in __getattr__
self._setup(name)
File "/Users/utkarsh/.venvs/mysite/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "/Users/utkarsh/.venvs/mysite/lib/python3.5/site-packages/django/conf/__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/Users/utkarsh/.venvs/mysite/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'mysite.local_dev_settings'
</code></pre>
<p><strong>Edit: Found the Resolution for the issue</strong>
Please refer answer below for the resolution of this problem.</p>
| 0 | 2016-07-25T12:21:26Z | 39,659,756 | <p>Found the resolution myself.</p>
<p>The issue was that under <kbd>Build, Execution, Deployment</kbd> -> <kbd>Console</kbd> -> <kbd>Django Console</kbd> both Content & Sources root were included & hence <code>mysite_root/mysite</code> came before <code>mysire_root/mysite/mysite</code> due to which PyCharm failed in loading the settings, even though it should have looked in the latter package as well. Upon disabling the option <code>Add Contents root to PYTHONPATH</code>, everything started working fine. :)</p>
| 1 | 2016-09-23T11:32:57Z | [
"python",
"django",
"pycharm"
] |
Produce new data frame from extracted grouped data | 38,567,693 | <p>I'm a Python novice. I'm trying to extract trip duration from a series of GPS fixes. There are multiple different tracks that I am trying to get information from and put the results into seperate data frame. The data looks like this (latitude and longitude columns excluded): </p>
<pre><code> track_id DateTime
0 track_1 2015-12-19 03:39:01
1 track_1 2015-12-19 14:23:21
2 track_1 2015-12-20 02:39:01
3 track_2 2016-01-02 05:44:23
4 track_2 2016-01-02 12:12:34
5 track_2 2016-01-02 19:44:33
6 track_3 2016-01-07 00:44:23
7 track_3 2016-01-07 13:11:05
8 track_3 2016-01-08 00:44:24
</code></pre>
<p>The desired output would look something like this:</p>
<pre><code> track_id trip_dur
0 track_1 0 days 23:00:00
1 track_2 0 days 14:00:10
2 track_3 1 days 00:00:01
</code></pre>
<p>I've managed to produce this information as a series using <code>groupby</code> but can't quite work how to produce a data frame like my desired output. I'd like to do it in a more 'pythonic' way if possible. </p>
<pre><code>#Calculate trip durations
trip_dur = df.groupby(['track_id'], sort=False)['DateTime'].max() - \
df.groupby(['track_id'], sort=False)['DateTime'].min()
</code></pre>
<p>Any help appreciated,
Cheers. </p>
| 1 | 2016-07-25T12:23:37Z | 38,567,810 | <p>You were nearly there, basically you can call <code>reset_index</code> with <code>name</code> param to to restore the 'track_id' column and name the aggregated column:</p>
<pre><code>In [44]:
(df.groupby('track_id')['DateTime'].max() - df.groupby('track_id')['DateTime'].min()).reset_index(name='trip_dur')
Out[44]:
track_id trip_dur
0 track_1 0 days 23:00:00
1 track_2 0 days 14:00:10
2 track_3 1 days 00:00:01
</code></pre>
| 1 | 2016-07-25T12:28:32Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
Is it safe to "finally" drop a table just after a fetchall with psycopg2 | 38,567,787 | <p>Give a cursor variable curr over a connection conn, is it safe to "finally" drop a table after fetching all results from it? Something like the following</p>
<pre><code>curr.execute(some_select_query)
try:
results = curr.fetchall()
except:
some_error_handling()
finally:
curr.execute(drop_table_query)
conn.commit()
use_results_array_here
</code></pre>
<p>Will all results be fetched into the results array already? Is performance affected by the drop there?</p>
| 0 | 2016-07-25T12:27:38Z | 38,567,934 | <p>yes, all the rows will be fetched as a list of tuples but, maybe, you want to use <code>else</code> instead of <code>finally</code></p>
<p><code>Else</code> is executed only if <code>try</code> was succesfull, in this way you avoid deleting the table in case of errors during fetching (connection drops, etc...).</p>
<pre><code>curr.execute(some_select_query)
try:
results = curr.fetchall()
except:
some_error_handling()
else:
curr.execute(drop_table_query)
conn.commit()
use_results_array_here
</code></pre>
| 1 | 2016-07-25T12:33:36Z | [
"python",
"postgresql",
"psycopg2"
] |
Is it possible to have icon in tkinter menubar in python | 38,567,830 | <p>What I get:</p>
<p><img src="http://i.imgur.com/tc0xN71.jpg" alt="Icons not displayed in menu"></p>
<p>My code:</p>
<pre><code>self.menu_bar = tk.Menu(self)
...
self.read_menu = tk.Menu(self.menu_bar, tearoff=False)
self.menu_bar.add_cascade(label='Read', underline=0, state=tk.DISABLED, menu=self.read_menu)
self.read_menu.add_command(label='First Page', underline=0, image=self.read_first_image, compound=tk.LEFT,
command=self.menu_read_first, accelerator='Home', state=tk.DISABLED)
self.read_menu.add_command(label='Last Page', underline=1, image=self.read_last_image, compound=tk.LEFT,
command=self.menu_read_last, accelerator='End')
self.read_menu.add_command(label='Next Page', underline=0, image=self.read_next_image, compound=tk.LEFT,
command=self.menu_read_next, accelerator='PgDn')
self.read_menu.add_command(label='Previous Page', underline=0, image=self.read_previous_image, compound=tk.LEFT,
command=self.menu_read_previous, accelerator='PgUp', state=tk.DISABLED)
...
self.menu_bar.add_separator()
self.menu_bar.add_command(command=self.menu_read_first, image=self.read_first_image, state=tk.DISABLED)
self.menu_bar.add_command(command=self.menu_read_previous, image=self.read_previous_image, state=tk.DISABLED)
self.menu_bar.add_command(command=self.menu_read_next, image=self.read_next_image)
self.menu_bar.add_command(command=self.menu_read_last, image=self.read_last_image)
</code></pre>
<p>As you can see, the separator and the Icons are not displayed in the topmenu, but are well displayed in the submenu:-(</p>
<p>Im I doing something wrong or it is just impossible?</p>
| 0 | 2016-07-25T12:29:16Z | 38,568,066 | <p>It is impossible to do what you want if you are on Windows. Tkinter won't allow you to add icons to the menubar. I think this is related to limitations in the windows API that the underlying tk library uses.</p>
<p>Note: menubars are designed for menus, not commands. Placing a command on a menubar will likely frustrate your users, because they will expect that clicking on an item will display a menu. </p>
| 1 | 2016-07-25T12:39:48Z | [
"python",
"python-3.x",
"tkinter",
"menu"
] |
Is it possible to have icon in tkinter menubar in python | 38,567,830 | <p>What I get:</p>
<p><img src="http://i.imgur.com/tc0xN71.jpg" alt="Icons not displayed in menu"></p>
<p>My code:</p>
<pre><code>self.menu_bar = tk.Menu(self)
...
self.read_menu = tk.Menu(self.menu_bar, tearoff=False)
self.menu_bar.add_cascade(label='Read', underline=0, state=tk.DISABLED, menu=self.read_menu)
self.read_menu.add_command(label='First Page', underline=0, image=self.read_first_image, compound=tk.LEFT,
command=self.menu_read_first, accelerator='Home', state=tk.DISABLED)
self.read_menu.add_command(label='Last Page', underline=1, image=self.read_last_image, compound=tk.LEFT,
command=self.menu_read_last, accelerator='End')
self.read_menu.add_command(label='Next Page', underline=0, image=self.read_next_image, compound=tk.LEFT,
command=self.menu_read_next, accelerator='PgDn')
self.read_menu.add_command(label='Previous Page', underline=0, image=self.read_previous_image, compound=tk.LEFT,
command=self.menu_read_previous, accelerator='PgUp', state=tk.DISABLED)
...
self.menu_bar.add_separator()
self.menu_bar.add_command(command=self.menu_read_first, image=self.read_first_image, state=tk.DISABLED)
self.menu_bar.add_command(command=self.menu_read_previous, image=self.read_previous_image, state=tk.DISABLED)
self.menu_bar.add_command(command=self.menu_read_next, image=self.read_next_image)
self.menu_bar.add_command(command=self.menu_read_last, image=self.read_last_image)
</code></pre>
<p>As you can see, the separator and the Icons are not displayed in the topmenu, but are well displayed in the submenu:-(</p>
<p>Im I doing something wrong or it is just impossible?</p>
| 0 | 2016-07-25T12:29:16Z | 38,571,943 | <p>It is not possible to add an image to menubar, so the submenus of this menubar will have images instead of string names. However, you can use <code>Menubutton</code> widgets, and set their position close to the left top corner of the parent window to have a visually same view with a <code>Menu</code> object. Here's how you can achieve this:</p>
<pre><code>from tkinter import *
root = Tk()
root.geometry("500x500-500+50")
imgvar1 = PhotoImage(file='airplane1.png')
mainmenu1 = Menubutton(root, image=imgvar1)
mainmenu1.grid(row=0, column=0)
submenu1 = Menu(mainmenu1)
mainmenu1.config(menu=submenu1)
submenu1.add_command(label="Option 1.1")
submenu1.add_command(label="Option 1.2")
imgvar2 = PhotoImage(file='automobile1.png')
mainmenu2 = Menubutton(root, image=imgvar2)
mainmenu2.grid(row=0, column=1)
submenu2 = Menu(mainmenu2)
mainmenu2.config(menu=submenu2)
submenu2.add_command(label="Option 2.1")
submenu2.add_command(label="Option 2.2")
imgvar = PhotoImage(file='eye.gif')
button = Button(root, image=imgvar)
button.grid(row=0, column=2)
</code></pre>
<p>Additionally, I consider this as a kind of bug in <code>Menu</code>, because <code>add_cascade</code> method of <code>Menu</code> has an option <a href="http://effbot.org/tkinterbook/menu.htm#Tkinter.Menu.add-method" rel="nofollow"><code>image</code></a>, because it does not return any unknown option error, but it does not show any image either, it just shows a string: "(Image)".</p>
| 1 | 2016-07-25T15:33:55Z | [
"python",
"python-3.x",
"tkinter",
"menu"
] |
Codingbat make_bricks timed out with while loop in python | 38,567,853 | <p>My goal is:
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.</p>
<p>My code is:</p>
<pre><code>def make_bricks(small, big, goal):
if small + 5*big < goal:
return False
elif small + 5*big == goal:
return True
else:
while small > 0:
small -= 1
goal -= 1
if goal % 5 == 0 and big >= goal/5:
return True
return False
</code></pre>
<p>In my IDLE this works well, but codingbat resulted in TimedOut. Is it happenning because for big numbers <code>while</code> loop is too slow? I am using python 3.2.5.</p>
<p>EDIT:</p>
<p>I tried another code:</p>
<pre><code>def make_bricks(small, big, goal):
if small ==0:
if goal % 5 == 0 and goal / 5 <= big:
return True
else:
return False
elif small + 5*big < goal:
return False
elif small + 5*big == goal:
return True
else:
while small > 0:
small -= 1
goal -= 1
if goal % 5 == 0 and big >= goal/5:
return True
return False
</code></pre>
<p>But with same issue.</p>
| 0 | 2016-07-25T12:30:11Z | 38,568,548 | <p>Okay I know why it doesn't work. Your code would work. But if there is a <code>loop</code> with about ~229500 (I tried to find the limit value on codebat, but sometime it timeout at this value, sometimes it doesn't. But the value is arround 230k) And as you said : One time out, and every value becomes time out. So to sum up, your code is working, but for the <code>make_bricks(1000000, 1000, 1000100) â True</code> test, there is a too big loop, and Codebat crashes.</p>
<p>So if you want to make it work on Codebat, you have to get rid of the <code>while</code> statement :</p>
<pre><code>def make_bricks(small, big, goal):
if small>=5 :
if (goal - (big + (small // 5 - 1)) * 5) <= (small % 5 + 5):
return True
else:
return False
else :
if (goal - big * 5) % 5 <= (small % 5) :
return True
else :
return False
</code></pre>
<p><code>small//5</code> return the <code>whole division</code>.
I think this is enought. (this should be the alst edit sorry)</p>
| 0 | 2016-07-25T13:02:56Z | [
"python",
"python-3.x"
] |
Selenium is not working with firefox and python webdriver on ububtu | 38,567,872 | <p>I am trying to write test cases for my webapp using selenium, firefox and python webdrivers while my development environment is setup on ubuntu 16.04 LTS but I am getting Exception,</p>
<pre><code>WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code></pre>
<p><strong>Here is my code block</strong></p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
driver.close()
</code></pre>
<p><strong>Here is complete exception stack:</strong></p>
<pre><code>Traceback (most recent call last):
File "LoginLogout.py", line 4, in <module>
driver = webdriver.Firefox()
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__
self.binary, timeout)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__
self.binary.launch_browser(self.profile, timeout=timeout)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser
self._wait_until_connectable(timeout=timeout)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 99, in _wait_until_connectable
"The browser appears to have exited "
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary constructor, check it for details.
</code></pre>
<p><strong>I have the following environment setup</strong></p>
<blockquote>
<p>Mozilla Firefox: 47.0</p>
<p>Selenium Version: 2.53.6</p>
<p>python version: 2.7.12</p>
<p>OS: Linux 4.4.0-31-generic #50-Ubuntu SMP x86_64</p>
</blockquote>
| 0 | 2016-07-25T12:31:01Z | 38,569,808 | <p>Selenium is moving away from using FirefoxDriver in favor of <a href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver" rel="nofollow">Marionette</a>. I had this issue a few weeks ago when moving to Firefox 47.0 and made the switch to at that time. </p>
<p>The following <a href="https://github.com/seleniumhq/selenium/issues/2110" rel="nofollow">link</a> discusses the issue more fully. </p>
| 1 | 2016-07-25T14:00:48Z | [
"python",
"python-2.7",
"selenium",
"selenium-webdriver",
"selenium-firefoxdriver"
] |
Is there any way setting font size in Reportlab? | 38,567,880 | <p>I am trying to make simple chart using reportlab with python.</p>
<p>I made chart with title of x and y, but the font seems like small.</p>
<p>I wanna change font to be bold and increase font size.</p>
<p>here is my code.</p>
<pre><code>def DrawPowerChart(self):
arrX = [0]*6
arrY = [0]*3
for i in range(6):
arrX[i] = i * 60
for i in range(3):
arrY[i] = i * 40
drawing = Drawing(400,400)
self.data = [
((10,30), (40,3), (70,72), (100,33), (130,14), (160,52), (190,68), (220,37),(250,70),(280,80))
]
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 300
lp.width = 300
lp.data = self.data
lp.joinedLines = 3
lp.lines[0].strokeWidth = 4
lp.strokeColor = colors.black
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = 300
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 80
lp.xValueAxis.valueSteps = arrX
lp.yValueAxis.valueSteps = arrY
drawing.add(String(360,40,"Time(s)")) #this is label x
drawing.add(String(30,370,"Power(W)")) #this is label y
</code></pre>
<p>I knew if i use canvas i will be solved but I wanna make chart picture including title</p>
| 1 | 2016-07-25T12:31:14Z | 38,569,335 | <p>See page 95 of the <a href="https://www.reportlab.com/docs/reportlab-userguide.pdf" rel="nofollow">ReportLab User Guide</a> for details. Here's an example of how you can change the font size <em>and</em> colour:</p>
<pre><code>d.add(String(150,100, 'Hello World', fontSize=18, fillColor=colors.red))
</code></pre>
| 0 | 2016-07-25T13:39:55Z | [
"python",
"pdf",
"reportlab"
] |
How to convert 4D array to another 4D with switched dimentions in Python | 38,567,949 | <p>I'm trying to get Image data from convolution layer in TensorFlow.
I have an array like:</p>
<pre><code>data = [N, Width, Height, Channel]
</code></pre>
<p>where N is the image number, Width and Height are image dimensions and Channel in the index of channel.</p>
<p>What do I need is another 4D array like:</p>
<pre><code>[N, Channel, Width, Height]
</code></pre>
<p>The reason is go in cycle by N and Channel and get 2D array of bytes for the ech channel for the each of image. </p>
<pre><code>img = Image.fromarray(data[N][Channel], 'L')
img.save('my.png')
</code></pre>
| 0 | 2016-07-25T12:34:05Z | 38,568,128 | <p>Just use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow"><code>np.transpose</code></a>:</p>
<pre><code>x = np.zeros((32, 10, 10, 3)) # image with 3 channels, size 10x10
res = np.tranpose(x, (0, 3, 1, 2))
print res.shape # prints (32, 3, 10, 10)
</code></pre>
| 1 | 2016-07-25T12:42:58Z | [
"python",
"arrays",
"image",
"numpy",
"tensorflow"
] |
How to convert 4D array to another 4D with switched dimentions in Python | 38,567,949 | <p>I'm trying to get Image data from convolution layer in TensorFlow.
I have an array like:</p>
<pre><code>data = [N, Width, Height, Channel]
</code></pre>
<p>where N is the image number, Width and Height are image dimensions and Channel in the index of channel.</p>
<p>What do I need is another 4D array like:</p>
<pre><code>[N, Channel, Width, Height]
</code></pre>
<p>The reason is go in cycle by N and Channel and get 2D array of bytes for the ech channel for the each of image. </p>
<pre><code>img = Image.fromarray(data[N][Channel], 'L')
img.save('my.png')
</code></pre>
| 0 | 2016-07-25T12:34:05Z | 38,568,134 | <p>Use the transpose function to reorder the dimensions.</p>
<p><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#transpose" rel="nofollow">https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#transpose</a></p>
<p>You would do something like this in the tensorflow code.</p>
<pre><code>image = tf.transpose(image, perm = [0, 3, 1, 2])
</code></pre>
<p>In the perm parameter you specify the new order of dimensions you want. In this case you move the channels dimension (3) into the second position.</p>
<p>If you want to do it before inputting it into the tensorflow model you can use np.transpose in the same way.</p>
| 1 | 2016-07-25T12:43:05Z | [
"python",
"arrays",
"image",
"numpy",
"tensorflow"
] |
customize Django Rest Framework serializers output? | 38,567,969 | <p>I have a Django model like this:</p>
<pre><code>class Sections(models.Model):
section_id = models.CharField(max_length=127, null=True, blank=True)
title = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
class Risk(models.Model):
title = models.CharField(max_length=256, null=False, blank=False)
section = models.ForeignKey(Sections, related_name='risks')
class Actions(models.Model):
title = models.CharField(max_length=256, null=False, blank=False)
section = models.ForeignKey(Sections, related_name='actions')
</code></pre>
<p>And serializers like that :</p>
<pre><code>class RiskSerializer(serializers.ModelSerializer):
class Meta:
model = Risk
fields = ('id', 'title',)
class ActionsSerializer(serializers.ModelSerializer):
class Meta:
model = Actions
fields = ('id', 'title',)
class RiskActionPerSectionsSerializer(serializers.ModelSerializer):
risks = RiskSerializer(many=True, read_only=True)
actions = ActionsSerializer(many=True, read_only=True)
class Meta:
model = Sections
fields = ('section_id', 'risks', 'actions')
depth = 1
</code></pre>
<p>When accessing the RiskActionPerSectionSerializer over a view, I get the following output:</p>
<pre><code>[
{
"actions": [
{
"id": 2,
"title": "Actions 2"
},
{
"id": 1,
"title": "Actions 1"
}
],
"risks": [
{
"id": 2,
"title": "Risk 2"
},
{
"id": 1,
"title": "Risk 1"
}
],
"section_id": "section 1"
}
.....
]
</code></pre>
<p>It s fine but I would prefer to have that :</p>
<pre><code>{
"section 1": {
"risks": [
{
"id": 2,
"title": "Risk 2"
},
{
"id": 1,
"title": "Risk 1"
}
],
"actions": [
{
"id": 2,
"title": "Actions 2"
},
{
"id": 1,
"title": "Actions 1"
}
]
}
}
</code></pre>
<p>How can I do that with Django Rest Framework ?</p>
| 1 | 2016-07-25T12:35:10Z | 38,568,493 | <p>You could override <code>to_representation()</code> method of your serializer: </p>
<pre><code>class RiskActionPerSectionsSerializer(serializers.ModelSerializer):
class Meta:
model = Sections
fields = ('section_id', 'risks', 'actions')
depth = 1
def to_representation(self, instance):
response_dict = dict()
response_dict[instance.section_id] = {
'actions': ActionsSerializer(instance.actions.all(), many=True).data,
'risks': RiskSerializer(instance.risks.all(), many=True).data
}
return response_dict
</code></pre>
| 2 | 2016-07-25T13:01:05Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
How to ADD OBR to the HL7 message? | 38,567,996 | <p>I am trying to generate the HL7 message using the Python library hl7apy, but when HL7 message is generate it does not gives the OBR segment in the output, please try to solve this query.</p>
<p>The code is </p>
<pre><code>from hl7apy import core
hl7 = core.Message("ORM_O01")
hl7.msh.msh_3 = "SendingApp"
hl7.msh.msh_4 = "SendingFac"
hl7.msh.msh_5 = "ReceivingApp"
hl7.msh.msh_6 = "ReceivingFac"
hl7.msh.msh_9 = "ORM^O01^ORM_O01"
hl7.msh.msh_10 = "168715"
hl7.msh.msh_11 = "P"
# PID
hl7.add_group("ORM_O01_PATIENT")
hl7.ORM_O01_PATIENT.pid.pid_2 = "1"
hl7.ORM_O01_PATIENT.pid.pid_3 = "A-10001"
hl7.ORM_O01_PATIENT.pid.pid_5 = "B-10001"
hl7.ORM_O01_PATIENT.pid.pid_6 = "DOE^JOHN"
# ORC
hl7.ORM_O01_ORDER.orc.orc_1 = "1"
hl7.ORM_O01_ORDER.ORC.orc_10 = "20150414120000"
# OBR
# We must explicitly add the OBR segment, then populate fields
hl7.ORM_O01_ORDER.ORM_O01_ORDER_DETAIL.ORM_O01_OBSERVATION.ORM_O01_ORDER_CHOICE.add_segment("OBR")
hl7.ORM_O01_ORDER.ORM_O01_ORDER_DETAIL.ORM_O01_OBSERVATION.ORM_O01_ORDER_CHOICE.OBR.obr_2 = "1"
hl7.ORM_O01_ORDER.ORM_O01_ORDER_DETAIL.ORM_O01_OBSERVATION.ORM_O01_ORDER_CHOICE.OBR.obr_3 = "2"
hl7.ORM_O01_ORDER.ORM_O01_ORDER_DETAIL.ORM_O01_OBSERVATION.ORM_O01_ORDER_CHOICE.OBR.obr_4 = "1100"
assert hl7.validate() is True
print "\n Validate HL7 Message: ", hl7.validate()
print "\n\n HL7 Message : \n\n", hl7.value
print "\n\n"
# Returns True
</code></pre>
| 1 | 2016-07-25T12:36:26Z | 38,611,477 | <p>You should add a OrderDetailGroup before adding and populating the OBR segment.</p>
| 0 | 2016-07-27T11:17:59Z | [
"python",
"hl7",
"hl7-v2",
"hl7-v3"
] |
Trouble importing Numpy into Grass GIS 7.0 on Windows 10 | 38,568,072 | <p>I recently installed Grass GIS 7 on my Windows 10. Upon loading the program, I receive an error in the terminal window stating: </p>
<blockquote>
<p>'This module requires the Numeric/numarray or NumPy module, which
could not be imported. It probably is not installed (it's part of the
standard Python distribution). See the Numeric Python site
(<a href="http://numpy.scipy.org" rel="nofollow">http://numpy.scipy.org</a>) for information on Numeric, numarray, or
NumPy not found'.</p>
</blockquote>
<p>I installed Anaconda separately which contains the NumPy module, but it is not being recognized by Grass GIS. How do I have Grass recognize this module is already installed on my computer?</p>
<p>I have Windows 10, and both Anaconda and Grass were downloaded as 64-bit. Anaconda downloaded with Python 3.5 and Grass was downloaded with OSGeo64W 7.0.4 version. </p>
| 0 | 2016-07-25T12:40:05Z | 38,568,302 | <p>I'm guessing that GRASS brings its own Python interpreter with it rather than using the Anaconda version that you installed. As the <a href="https://grasswiki.osgeo.org/wiki/GRASS_and_Python#Using_a_version_of_Python_different_from_the_default_installation" rel="nofollow">notes on GRASS and Python</a> remark "On Windows, Python scripts are invoked via <code>%GRASS_PYTHON%</code>, so changing that environment variable will change the interpreter." If you set the <code>GRASS_PYTHON</code> environment variable to point to the Anaconda Python binary you may find things start to work better.</p>
| 1 | 2016-07-25T12:51:53Z | [
"python",
"numpy",
"module",
"anaconda",
"grass"
] |
Trouble importing Numpy into Grass GIS 7.0 on Windows 10 | 38,568,072 | <p>I recently installed Grass GIS 7 on my Windows 10. Upon loading the program, I receive an error in the terminal window stating: </p>
<blockquote>
<p>'This module requires the Numeric/numarray or NumPy module, which
could not be imported. It probably is not installed (it's part of the
standard Python distribution). See the Numeric Python site
(<a href="http://numpy.scipy.org" rel="nofollow">http://numpy.scipy.org</a>) for information on Numeric, numarray, or
NumPy not found'.</p>
</blockquote>
<p>I installed Anaconda separately which contains the NumPy module, but it is not being recognized by Grass GIS. How do I have Grass recognize this module is already installed on my computer?</p>
<p>I have Windows 10, and both Anaconda and Grass were downloaded as 64-bit. Anaconda downloaded with Python 3.5 and Grass was downloaded with OSGeo64W 7.0.4 version. </p>
| 0 | 2016-07-25T12:40:05Z | 39,773,207 | <p>In OSGeo4W installer, upgrading python-numpy to 1.11.0-1 caused this error in GRASS 7.0.4 for me. Backing python-numpy to 2.7-1.7.0-1 solved the Problem</p>
| 0 | 2016-09-29T14:33:58Z | [
"python",
"numpy",
"module",
"anaconda",
"grass"
] |
How do I get minimum and maximum epoch time from python dictionary? | 38,568,174 | <p>I'm having one python dictionary. In this dictionary I saved value as a epoch times. I want to know which is maximum epoch time and which is minimum epoch time, Further I want to split those epoch times into different time-slots.</p>
<p><strong>Program-Code-</strong></p>
<pre><code>for key,value in self.key_dict.iteritems():
print 'key : ' + str(key) + ' value : ' + str(value)
</code></pre>
<p><strong>Output-</strong></p>
<pre><code>key : 1 value : 1468332422164000
key : 2 value : 1468332421672000
key : 3 value : 1468332423489000
key : 4 value : 1468332423568000
key : 5 value : 1468332421383000
key : 6 value : 1468332421818000
key : 7 value : 1468332423490000
key : 8 value : 1468332421195000
key : 9 value : 1468332421098000
</code></pre>
<p><strong>Further divide into different time slots -</strong></p>
<p>It means I just want to plot x-axis using this times. For that purpose I'm finding min and max times. Depend on difference between minimum and maximum time-slots I want to split it in 3 or 4 time-slots maximum. example - 1468332421098000 to 1468332423490000.</p>
<p>These are the epoch times as a value of the dictionary. how I can find maximum and minimum from that and further divide into different time-slots for the plotting of the x-axis of the graph?</p>
| 0 | 2016-07-25T12:45:44Z | 38,568,293 | <p>Max and min can be determined using functions <code>min()</code> and <code>max()</code> on <code>dict.values()</code> which returns a list of the dictionary's values:</p>
<pre><code>minimum = min(self.key_dict.values())
maximum = max(self.key_dict.values())
</code></pre>
| 0 | 2016-07-25T12:51:16Z | [
"python",
"dictionary",
"max",
"min",
"epoch"
] |
How do I get minimum and maximum epoch time from python dictionary? | 38,568,174 | <p>I'm having one python dictionary. In this dictionary I saved value as a epoch times. I want to know which is maximum epoch time and which is minimum epoch time, Further I want to split those epoch times into different time-slots.</p>
<p><strong>Program-Code-</strong></p>
<pre><code>for key,value in self.key_dict.iteritems():
print 'key : ' + str(key) + ' value : ' + str(value)
</code></pre>
<p><strong>Output-</strong></p>
<pre><code>key : 1 value : 1468332422164000
key : 2 value : 1468332421672000
key : 3 value : 1468332423489000
key : 4 value : 1468332423568000
key : 5 value : 1468332421383000
key : 6 value : 1468332421818000
key : 7 value : 1468332423490000
key : 8 value : 1468332421195000
key : 9 value : 1468332421098000
</code></pre>
<p><strong>Further divide into different time slots -</strong></p>
<p>It means I just want to plot x-axis using this times. For that purpose I'm finding min and max times. Depend on difference between minimum and maximum time-slots I want to split it in 3 or 4 time-slots maximum. example - 1468332421098000 to 1468332423490000.</p>
<p>These are the epoch times as a value of the dictionary. how I can find maximum and minimum from that and further divide into different time-slots for the plotting of the x-axis of the graph?</p>
| 0 | 2016-07-25T12:45:44Z | 38,568,354 | <p>In case you want both the key and the value to be returned, use <code>min</code> and <code>max</code> function, together with the <code>key</code> kwarg:</p>
<pre><code>key_dict = {'a': 1, 'b': 2}
print min(key_dict.iteritems(), key=lambda item: item[1])
# ('a', 1)
print max(key_dict.iteritems(), key=lambda item: item[1])
# ('b', 2)
</code></pre>
| 0 | 2016-07-25T12:54:16Z | [
"python",
"dictionary",
"max",
"min",
"epoch"
] |
How do I get minimum and maximum epoch time from python dictionary? | 38,568,174 | <p>I'm having one python dictionary. In this dictionary I saved value as a epoch times. I want to know which is maximum epoch time and which is minimum epoch time, Further I want to split those epoch times into different time-slots.</p>
<p><strong>Program-Code-</strong></p>
<pre><code>for key,value in self.key_dict.iteritems():
print 'key : ' + str(key) + ' value : ' + str(value)
</code></pre>
<p><strong>Output-</strong></p>
<pre><code>key : 1 value : 1468332422164000
key : 2 value : 1468332421672000
key : 3 value : 1468332423489000
key : 4 value : 1468332423568000
key : 5 value : 1468332421383000
key : 6 value : 1468332421818000
key : 7 value : 1468332423490000
key : 8 value : 1468332421195000
key : 9 value : 1468332421098000
</code></pre>
<p><strong>Further divide into different time slots -</strong></p>
<p>It means I just want to plot x-axis using this times. For that purpose I'm finding min and max times. Depend on difference between minimum and maximum time-slots I want to split it in 3 or 4 time-slots maximum. example - 1468332421098000 to 1468332423490000.</p>
<p>These are the epoch times as a value of the dictionary. how I can find maximum and minimum from that and further divide into different time-slots for the plotting of the x-axis of the graph?</p>
| 0 | 2016-07-25T12:45:44Z | 38,568,503 | <p>If you have access to <code>numpy</code>, then you can use it to help you bin the data. First, lets compute the minimum and maximum of our values.</p>
<pre><code>mn = min(self.key_dict.values())
mx = max(self.key_dict.values())
</code></pre>
<p>Now create some bins for plotting that equally divide these:</p>
<pre><code># five equally spaced points delimiting four bins
bins = numpy.linspace(mn, mx, num=5)
</code></pre>
<p>Now find the bin each value is in:</p>
<pre><code>values = numpy.array(list(self.key_dict.values())
bin_numbers = numpy.digitize(values, bins)
</code></pre>
<p>What you want to plot from there is unclear from your question. You may be wanting to plot <code>bin_numbers</code> versus your dictionary keys ... if you wish to plot a histogram, then it would easier to use <code>numpy.histogram</code> rather than <code>numpy.digitize</code>.</p>
| 0 | 2016-07-25T13:01:23Z | [
"python",
"dictionary",
"max",
"min",
"epoch"
] |
Pandas: transpose dataframe | 38,568,197 | <p>I have df:</p>
<pre><code>ID url visits count_sec buys
0012ea90a6deb4eeb2924fb13e844136 aliexpress.com 3438 33067 25
0012ea90a6deb4eeb2924fb13e844136 ebay.com 9 44
001342afb153e2775649dc5ae0460605 ozon.ru 1 6
0019b08bc9bb8da21f3b8ecc945a67d3 aliexpress.com 24 2196
0019b08bc9bb8da21f3b8ecc945a67d3 bonprix.ru 42 1378
</code></pre>
<p>I need to transponse it and get</p>
<pre><code>ID url
visits count_sec buys
aliexpress.com ebay.com ozon.ru aliexpress.com bonprix.ru
0012ea90a6deb4eeb2924fb13e844136 3438 33067 25 9 44 0 0 0 0 0 0 0 0 0 0
001342afb153e2775649dc5ae0460605 0 0 0 0 0 0 1 6 0 0 0 0 0 0 0
0019b08bc9bb8da21f3b8ecc945a67d3 0 0 0 0 0 0 0 0 0 24 2196 0 42 1378 0
</code></pre>
<p>How can I do that?</p>
| 2 | 2016-07-25T12:46:35Z | 38,568,396 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, but there is missing top <code>url</code> in <code>MultiIndex</code> in columns. Also values are only random, because it is not clear which each column contain values:</p>
<pre><code>#new column with value `url`
df['url1'] = 'url'
df1 = df.pivot_table(index='ID', values=['visits','count_sec','buys'],columns=['url1','url'])
#swap first and second level in MultiIndex in columns
df1.columns = df1.columns.swaplevel(0,1)
#remove columns names
df1 = df1.rename_axis((None,None,None), axis=1)
print (df1)
url \
visits
aliexpress.com bonprix.ru ebay.com ozon.ru
ID
0012ea90a6deb4eeb2924fb13e844136 3438.0 NaN NaN NaN
001342afb153e2775649dc5ae0460605 NaN NaN NaN NaN
0019b08bc9bb8da21f3b8ecc945a67d3 NaN NaN NaN NaN
\
count_sec
aliexpress.com bonprix.ru ebay.com ozon.ru
ID
0012ea90a6deb4eeb2924fb13e844136 33067.0 NaN 9.0 NaN
001342afb153e2775649dc5ae0460605 NaN NaN NaN 1.0
0019b08bc9bb8da21f3b8ecc945a67d3 24.0 42.0 NaN NaN
buys
aliexpress.com bonprix.ru ebay.com ozon.ru
ID
0012ea90a6deb4eeb2924fb13e844136 25.0 NaN 44.0 NaN
001342afb153e2775649dc5ae0460605 NaN NaN NaN 6.0
0019b08bc9bb8da21f3b8ecc945a67d3 2196.0 1378.0 NaN NaN
</code></pre>
| 2 | 2016-07-25T12:56:24Z | [
"python",
"pandas",
"dataframe",
"pivot-table",
"transpose"
] |
OSError: [Errno 45] Operation not supported: '/home/samuelchin' - Mac | 38,568,322 | <p><br>
I am trying to run this code: <a href="https://github.com/jkschin/svhn" rel="nofollow">https://github.com/jkschin/svhn</a> .. <br> when I run svn_train.py I get this error</p>
<pre><code>Traceback (most recent call last): File "svhn_train.py", line 93, in
<module>
tf.app.run() File "/Users/n/anaconda/lib/python2.7/site-packages/tensorflow/python/platform/app.py",
line 30, in run
sys.exit(main(sys.argv)) File "svhn_train.py", line 88, in main
gfile.MakeDirs(FLAGS.train_dir) File "/Users/n/anaconda/lib/python2.7/site-packages/tensorflow/python/platform/gfile.py",
line 295, in MakeDirs
os.makedirs(path, mode) File "/Users/n/anaconda/lib/python2.7/os.py", line 150, in makedirs
makedirs(head, mode) File "/Users/n/anaconda/lib/python2.7/os.py", line 150, in makedirs
makedirs(head, mode) File "/Users/n/anaconda/lib/python2.7/os.py", line 150, in makedirs
makedirs(head, mode) File "/Users/aljaafn/anaconda/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode) OSError: [Errno 45] Operation not supported: '/home/samuelchin'
</code></pre>
<p>The code is built in Python & Tensorflow to run and train a model on the SVHN data. </p>
<p><br> Any idea? Thanks in advance </p>
| 0 | 2016-07-25T12:52:44Z | 38,568,509 | <p><a href="https://github.com/jkschin/svhn/blob/master/svhn_flags.py#L7" rel="nofollow">https://github.com/jkschin/svhn/blob/master/svhn_flags.py#L7</a> hardcodes the author's local home directory, which is definitely not portable. Like the README says, you need to be able to hack the code in order to get it to work.</p>
| 0 | 2016-07-25T13:01:33Z | [
"python",
"python-2.7",
"tensorflow"
] |
Wait for python script to return 0 | 38,568,373 | <p>I'am trying to write a script that is waiting for a database to be online.
The script that checks the database connection is written in python and should be excited every 5 seconds. If the script returns 0 the main script should continue.</p>
<p>I have never written in shell, so i can only guess how to get the python script into the condition of the while loop. Here is my attempt, but i have no idea how to get it right.</p>
<p>The python script is working well.</p>
<p>psqltest.py:</p>
<pre><code>#!/usr/bin/python2.4
#
import psycopg2
try:
db = psycopg2.connect("dbname='postgis' user='postgres' host='db' password='postgres'")
except:
exit(1)
exit(0)
</code></pre>
<p>my main shell script:</p>
<pre><code>echo waiting for database...
while [ python /root/psqltest.py && echo 0 || echo 1 ]
do
sleep 5
done
</code></pre>
<p>the error message:</p>
<pre><code> 1 ]
</code></pre>
<p>Thanks for helping me out</p>
| 0 | 2016-07-25T12:55:23Z | 38,569,559 | <p>I have improved my Scripts, now the bash is only calling the python script and waits for it to finish, as Kristof mentioned. This is working so far, but i try to improve it further more.</p>
<pre><code>#!/usr/bin/python3
#
import psycopg2
import time
import sys
db = None
sys.stdout.write('waiting ')
while db is None:
try:
db = psycopg2.connect("dbname='postgis' user='postgres' host='db' password='...'")
db.close()
except:
sys.stdout.write('.')
sys.stdout.flush()
time.sleep( 5 )
print('')
exit(0)
</code></pre>
| 0 | 2016-07-25T13:49:44Z | [
"python",
"sh"
] |
Wait for python script to return 0 | 38,568,373 | <p>I'am trying to write a script that is waiting for a database to be online.
The script that checks the database connection is written in python and should be excited every 5 seconds. If the script returns 0 the main script should continue.</p>
<p>I have never written in shell, so i can only guess how to get the python script into the condition of the while loop. Here is my attempt, but i have no idea how to get it right.</p>
<p>The python script is working well.</p>
<p>psqltest.py:</p>
<pre><code>#!/usr/bin/python2.4
#
import psycopg2
try:
db = psycopg2.connect("dbname='postgis' user='postgres' host='db' password='postgres'")
except:
exit(1)
exit(0)
</code></pre>
<p>my main shell script:</p>
<pre><code>echo waiting for database...
while [ python /root/psqltest.py && echo 0 || echo 1 ]
do
sleep 5
done
</code></pre>
<p>the error message:</p>
<pre><code> 1 ]
</code></pre>
<p>Thanks for helping me out</p>
| 0 | 2016-07-25T12:55:23Z | 38,570,187 | <p>The shell script would simply be</p>
<pre><code>while ! python /root/psqltest.py; do
sleep 5
done
</code></pre>
<p>or the lesser known</p>
<pre><code>until python /root/psqltest.py; do
sleep 5
done
</code></pre>
| 2 | 2016-07-25T14:16:24Z | [
"python",
"sh"
] |
Code Study-New to programming | 38,568,404 | <p>i am new to programming and have been studying some code to get to know about OOP.Here is what i have understood and need help on,
1) import gym and env=gym.make('String') : This means gym is a library, and make is a class under it? Have we created an object instance?</p>
<p>I understood classes contains methods inside them..i.e functions..but in this case i am not able to decipher clearly.The line after this env.monitor.start()..this contains 3 parts..what does each indiciate..i thought env was an object instantiated earlier.</p>
<pre><code>import gym
env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1',force=True)
for i_episode in range(20):
observation = env.reset()
for t in range(1009):
env.render()
print(observation)
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1))
break
env.monitor.close()
</code></pre>
<p>Thanks for your help, apologise if the question is stupid</p>
| -3 | 2016-07-25T12:56:49Z | 38,568,563 | <p><code>gym</code> can be a package or a module. The <code>import</code> statement doesn't tell you what <code>gym</code> is. </p>
<p>gym.make means that you are calling a method called 'make' from gym. </p>
<p><code>env</code> is then whatever <code>make('CartPole-v0')</code> returns, which may or may not be an object. It has a monitor attribute which seems to be startable, from the method <code>monitor.start()</code>, so I'd guess that it is, but you can't know this without looking at the code for gym or calling <code>type(env)</code>. </p>
<p><code>env.monitor.start()</code> means that the start method from <code>env.monitor</code> is called. What <code>env.monitor</code> <em>is</em> can't be determined without looking at the code for gym.</p>
| -1 | 2016-07-25T13:03:23Z | [
"python",
"class",
"libraries"
] |
Code Study-New to programming | 38,568,404 | <p>i am new to programming and have been studying some code to get to know about OOP.Here is what i have understood and need help on,
1) import gym and env=gym.make('String') : This means gym is a library, and make is a class under it? Have we created an object instance?</p>
<p>I understood classes contains methods inside them..i.e functions..but in this case i am not able to decipher clearly.The line after this env.monitor.start()..this contains 3 parts..what does each indiciate..i thought env was an object instantiated earlier.</p>
<pre><code>import gym
env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1',force=True)
for i_episode in range(20):
observation = env.reset()
for t in range(1009):
env.render()
print(observation)
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1))
break
env.monitor.close()
</code></pre>
<p>Thanks for your help, apologise if the question is stupid</p>
| -3 | 2016-07-25T12:56:49Z | 38,568,601 | <p>Here's the basic structure of the above program:</p>
<p><code>import</code> statements bring modules into the program. These modules contain functions. The module is able to use these functions. For example,</p>
<pre><code>import myMod as mM
mM.fooFunc()
</code></pre>
<p>imports a module <code>myMod</code> and gives it an alias of <code>mM</code>. <code>fooFunc</code> belongs inside the module and so we're able to call it.</p>
<p>We don't need aliases. We can also just say </p>
<pre><code>import myMod
myMod.fooFunc()
</code></pre>
<p>but it's slightly less convenient.</p>
<p><code>env</code> is just a name for the return value of the function <code>gym.make('CartPole-v0')</code>. Functions always return something, such as an actual object, an integral type (like an integer, or a string), or <code>None</code>.</p>
<p>The return value doesn't need to always be stored, such as in <code>env.monitor.start('/tmp/cartpole-experiment-1',force=True)</code>. It simply performs some data manipulation.</p>
<p>As for the rest of the program, it's ran by <code>for-loop</code>s and <code>if</code> statements. <a href="https://docs.python.org/3/reference/compound_stmts.html" rel="nofollow">Read about it here</a>.</p>
| 0 | 2016-07-25T13:05:20Z | [
"python",
"class",
"libraries"
] |
Code Study-New to programming | 38,568,404 | <p>i am new to programming and have been studying some code to get to know about OOP.Here is what i have understood and need help on,
1) import gym and env=gym.make('String') : This means gym is a library, and make is a class under it? Have we created an object instance?</p>
<p>I understood classes contains methods inside them..i.e functions..but in this case i am not able to decipher clearly.The line after this env.monitor.start()..this contains 3 parts..what does each indiciate..i thought env was an object instantiated earlier.</p>
<pre><code>import gym
env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1',force=True)
for i_episode in range(20):
observation = env.reset()
for t in range(1009):
env.render()
print(observation)
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1))
break
env.monitor.close()
</code></pre>
<p>Thanks for your help, apologise if the question is stupid</p>
| -3 | 2016-07-25T12:56:49Z | 38,568,831 | <p><code>gym</code>can be a package or module. There is no way to tell what it is by its import statement.</p>
<p><code>env = gym.make('CartPole-v0')</code> can either assign the return value of the call of function <code>make</code> from <code>gym</code> to variable <code>env</code>, or create an item of class <code>make</code> and assign that item to variable <code>env</code></p>
<p><code>env.monitor.start('/tmp/cartpole-experiment-1',force=True)</code> means the <code>env</code> variable most likely returned an item of class that has a property/subclass called <code>monitor</code>. This property/subclass possess a function called <code>start</code></p>
<p><code>env</code> most likely also has a subclass/property <code>action_space</code> with a function <code>sample</code></p>
| 0 | 2016-07-25T13:16:14Z | [
"python",
"class",
"libraries"
] |
Code Study-New to programming | 38,568,404 | <p>i am new to programming and have been studying some code to get to know about OOP.Here is what i have understood and need help on,
1) import gym and env=gym.make('String') : This means gym is a library, and make is a class under it? Have we created an object instance?</p>
<p>I understood classes contains methods inside them..i.e functions..but in this case i am not able to decipher clearly.The line after this env.monitor.start()..this contains 3 parts..what does each indiciate..i thought env was an object instantiated earlier.</p>
<pre><code>import gym
env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1',force=True)
for i_episode in range(20):
observation = env.reset()
for t in range(1009):
env.render()
print(observation)
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1))
break
env.monitor.close()
</code></pre>
<p>Thanks for your help, apologise if the question is stupid</p>
| -3 | 2016-07-25T12:56:49Z | 38,569,159 | <p>gym.make('CartPole-v0') returns an object.</p>
<p>Therefore, <strong>'env'</strong> is an <strong>object</strong>.</p>
<p>'env' contains a property, <strong>'monitor'</strong>, which is also an <strong>object</strong>. </p>
<p>The <strong>'start'</strong> method is a method of the <strong>'monitor' object</strong>, not the <em>env object.</em> </p>
<pre><code> env = gym.make('CartPole-v0')
env.monitor.start('/tmp/cartpole-experiment-1',force=True)
</code></pre>
<p>Another way to write it would be (env.monitor).start('/tmp/cartpole-experiment-1',force=True)</p>
<p>For the sake of repetition,</p>
<pre><code> env.reset()
#env is object, reset is method of env object
env.render()
#env is object, render is method of env object
env.action_space.sample()
#env is object, action_space is object, sample is method of action_space object
env.step(action)
#env is object, step is method of env object
</code></pre>
| 0 | 2016-07-25T13:31:25Z | [
"python",
"class",
"libraries"
] |
How to get column types of an existing, named table from SQLAlchemy | 38,568,412 | <p>How can I represent this query in SQLAlchemy?</p>
<pre><code>SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'foo'
</code></pre>
| 0 | 2016-07-25T12:57:08Z | 38,570,148 | <p>Mb, I didn't understood you meant the database types. If it's a mapped table you can iterate columns like this:</p>
<pre><code>for c in foo.__table__.columns:
print(c.type)
</code></pre>
| 0 | 2016-07-25T14:15:02Z | [
"python",
"orm",
"sqlalchemy"
] |
get the subplot from pick event with matplotlib and python | 38,568,646 | <p>I have a figure with four subplots, two of which are binded on a pick event, by doing <code>canvas.mpl_connect('pick_event', onpick)</code> where onpick is onpick(event) handler.</p>
<p>Now, based on which of the two suplot the click come in, I must activate a different behaviour (ie if pick come from 1st subplot do this, else if it come from second suplot do that), but I don't know how to do it.
Can anyone help me?</p>
| 0 | 2016-07-25T13:07:13Z | 38,570,307 | <p>Here is a short example:</p>
<pre><code>import matplotlib.pyplot as plt
from random import random
def onpick(event):
if event.artist == plt1:
print("Picked on top plot")
elif event.artist == plt2:
print("Picked on bottom plot")
first = [random()*i for i in range(10)]
second = [random()*i for i in range(10)]
fig = plt.figure(1)
plt1 = plt.subplot(211)
plt.plot(range(10), first)
plt2 = plt.subplot(212)
plt.plot(range(10), second)
plt1.set_picker(True)
plt2.set_picker(True)
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
</code></pre>
<p>Note that you have to call <code>set_picker(True)</code> on the subplots that should fire this event! If you don't, nothing will happen even though you've set the event on the canvas.</p>
<p>For further reading, here's the <a href="http://matplotlib.org/api/backend_bases_api.html#matplotlib.backend_bases.PickEvent" rel="nofollow"><code>PickEvent</code> documentation</a> and an <a href="http://matplotlib.org/examples/event_handling/pick_event_demo.html" rel="nofollow">pick handling demo</a> from the matplotlib site.</p>
| 1 | 2016-07-25T14:21:33Z | [
"python",
"matplotlib"
] |
Tensorflow: why is zip() function used in the steps involving applying the gradients? | 38,568,673 | <p>I am working through Assignment 6 of the Udacity Deep Learning course. I am unsure why the zip() function is used in these steps to apply the gradients. </p>
<p>Here is the relevant code: </p>
<pre><code># define the loss function
logits = tf.nn.xw_plus_b(tf.concat(0, outputs), w, b)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits, tf.concat(0, train_labels)))
# Optimizer.
global_step = tf.Variable(0)
#staircase=True means that the learning_rate updates at discrete time steps
learning_rate = tf.train.exponential_decay(10.0, global_step, 5000, 0.1, staircase=True)
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
gradients, v = zip(*optimizer.compute_gradients(loss))
gradients, _ = tf.clip_by_global_norm(gradients, 1.25)
optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step)
</code></pre>
<p>What is the purpose of applying the <code>zip()</code> function? </p>
<p>Why is <code>gradients</code> and <code>v</code> stored that way? I thought <code>zip(*iterable)</code> returned just one zip object. </p>
| 1 | 2016-07-25T13:08:49Z | 38,568,886 | <p>I don't know Tensorflow, but presumably <code>optimizer.compute_gradients(loss)</code> yields (gradient, value) tuples.</p>
<pre><code>gradients, v = zip(*optimizer.compute_gradients(loss))
</code></pre>
<p>performs a <em>transposition</em>, creating a list of gradients and a list of values.</p>
<pre><code>gradients, _ = tf.clip_by_global_norm(gradients, 1.25)
</code></pre>
<p>then clips the gradients, and</p>
<pre><code>optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step)
</code></pre>
<p>re-zips the gradient and value lists back into an iterable of (gradient, value) tuples which is then passed to the <code>optimizer.apply_gradients</code> method.</p>
| 1 | 2016-07-25T13:19:10Z | [
"python",
"machine-learning",
"tensorflow",
"deep-learning"
] |
remove none value on a dict in python won't work | 38,568,687 | <p>I want to modify my mongo DB collection data with removing the <code>None</code> value. I have a nested dict.</p>
<p>I did a query to get all the db on my db:</p>
<pre><code>doc = db.events.find()
for document in doc:
print document
</code></pre>
<p>One printed document looks like this:</p>
<pre><code>{ u'_id': u'55f16d2a0f5cb40aa26a6f1b', u'event': {u'values': u'None', u'condition': u'None', u'comment': u'', u'date': u'None', u'delete': u'false'}}
</code></pre>
<p>So i want to replace all <code>None</code> values inside each document, where is None to write <code>No</code>, and save the updated document on the DB.</p>
<p>So I did this :</p>
<pre><code>def replace_none_values():
doc = db.events.find()
for document in doc:
for key, value in document.items():
if key == 'event':
event_part = value
for key1, value1 in event_part:
if value1 is None:
document['event'][key1] = 'No'
db.events.save(document)
replace_none_values()
</code></pre>
<p>but the code in <code>for key1, value1 in event_part:</code> is not executed. I don't know why, what I'm doing wrong here? Can somebody help me please?</p>
| -1 | 2016-07-25T13:09:21Z | 38,568,751 | <p>In your example, the parentheses are missing when you call <code>replace_none_values</code></p>
<p>use:</p>
<pre><code>replace_none_values()
</code></pre>
<p>instead of:</p>
<pre><code>replace_none_values
</code></pre>
| 0 | 2016-07-25T13:12:44Z | [
"python",
"mongodb",
"list",
"dictionary",
"nonetype"
] |
remove none value on a dict in python won't work | 38,568,687 | <p>I want to modify my mongo DB collection data with removing the <code>None</code> value. I have a nested dict.</p>
<p>I did a query to get all the db on my db:</p>
<pre><code>doc = db.events.find()
for document in doc:
print document
</code></pre>
<p>One printed document looks like this:</p>
<pre><code>{ u'_id': u'55f16d2a0f5cb40aa26a6f1b', u'event': {u'values': u'None', u'condition': u'None', u'comment': u'', u'date': u'None', u'delete': u'false'}}
</code></pre>
<p>So i want to replace all <code>None</code> values inside each document, where is None to write <code>No</code>, and save the updated document on the DB.</p>
<p>So I did this :</p>
<pre><code>def replace_none_values():
doc = db.events.find()
for document in doc:
for key, value in document.items():
if key == 'event':
event_part = value
for key1, value1 in event_part:
if value1 is None:
document['event'][key1] = 'No'
db.events.save(document)
replace_none_values()
</code></pre>
<p>but the code in <code>for key1, value1 in event_part:</code> is not executed. I don't know why, what I'm doing wrong here? Can somebody help me please?</p>
| -1 | 2016-07-25T13:09:21Z | 38,568,777 | <p>Use the <code>items</code> method again since what you have is a <em>nested dictionary</em>. And note that the values in the dictionary are not the constant <code>None</code>, but string <code>'None'</code> so <code>if value1 is None</code> isn't going to do what you intend:</p>
<pre><code>for key1, value1 in event_part.items():
# ^
if value1 == 'None':
document['event'][key1] = 'No'
</code></pre>
<hr>
<p>And then call the function: <code>replace_none_values()</code></p>
| 0 | 2016-07-25T13:13:32Z | [
"python",
"mongodb",
"list",
"dictionary",
"nonetype"
] |
How to solve a equation of the form (A'A - yBB')x = 0 with numpy | 38,568,699 | <p>Using numpy if I had a system of equations: </p>
<pre><code>3x + 2y = 5
1x + 4y = 10
</code></pre>
<p>I could solve them with <code>numpy.linalg.solve</code>: </p>
<pre><code>a = [[3,2],[1,4]]
b = [5,10]
solution = numpy.linalg.solve(a,b)
</code></pre>
<p>Now, what if I had two matrices, A and B each of shape (100,100) and I wanted to solve an equation of the form: (A'<em>A - y</em>BB')x = 0</p>
<p>I'm unsure as to how I would set this up using <code>numpy.linalg.solve</code></p>
| 1 | 2016-07-25T13:09:56Z | 38,568,913 | <p>This specific equation has an analytical solution:</p>
<ol>
<li>either <code>x</code> is 0 and <code>y</code> can be anything</li>
</ol>
<p>either</p>
<ol start="2">
<li><code>x</code> can be anything and then <code>A'A - yBB' = 0</code> which <strong>can</strong> be linear and solved using <code>numpy.linalg.solve</code> </li>
</ol>
<p><strong>can</strong> be linear because the dimensions does not add well</p>
| 1 | 2016-07-25T13:20:23Z | [
"python",
"numpy",
"scipy"
] |
How to solve a equation of the form (A'A - yBB')x = 0 with numpy | 38,568,699 | <p>Using numpy if I had a system of equations: </p>
<pre><code>3x + 2y = 5
1x + 4y = 10
</code></pre>
<p>I could solve them with <code>numpy.linalg.solve</code>: </p>
<pre><code>a = [[3,2],[1,4]]
b = [5,10]
solution = numpy.linalg.solve(a,b)
</code></pre>
<p>Now, what if I had two matrices, A and B each of shape (100,100) and I wanted to solve an equation of the form: (A'<em>A - y</em>BB')x = 0</p>
<p>I'm unsure as to how I would set this up using <code>numpy.linalg.solve</code></p>
| 1 | 2016-07-25T13:09:56Z | 38,574,409 | <p>This looks like you are trying to solve the <a href="https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix#Generalized_eigenvalue_problem" rel="nofollow">generalized eigenvalue problem</a>, with <code>y</code> being the unknown generalized eigenvalue λ and <code>x</code> being the corresponding generalized eigenvector. If that is what you want, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eig.html" rel="nofollow"><code>scipy.linalg.eig</code></a>. Here's an example.</p>
<p>To keep the output readable, I'll use arrays with shape (2, 2).</p>
<pre><code>In [91]: from scipy.linalg import eig
In [92]: A
Out[92]:
array([[2, 3],
[1, 1]])
In [93]: B
Out[93]:
array([[0, 1],
[3, 0]])
</code></pre>
<p>These are the matrices in the equation.</p>
<pre><code>In [94]: a = A.T.dot(A)
In [95]: b = B.dot(B.T)
</code></pre>
<p>Solve the generalized eigenvalue problem:</p>
<pre><code>In [96]: lam, v = eig(a, b)
</code></pre>
<p>These are the generalized eigenvalues (your <code>y</code>):</p>
<pre><code>In [97]: lam
Out[97]: array([ 6.09287487+0.j, 0.01823624+0.j])
</code></pre>
<p>The columns of <code>v</code> are the generalized eigenvectors (your <code>x</code>):</p>
<pre><code>In [98]: v
Out[98]:
array([[ 0.98803087, -0.81473616],
[ 0.1542563 , 0.57983187]])
</code></pre>
<p>Verify the solution. Note that the results are on the order of 1e-16, i.e. numerically close to 0.</p>
<pre><code>In [99]: (a - lam[0]*b).dot(v[:,0])
Out[99]: array([ 2.22044605e-16+0.j, -8.88178420e-16+0.j])
In [100]: (a - lam[1]*b).dot(v[:,1])
Out[100]: array([ 0.+0.j, 0.+0.j])
</code></pre>
| 3 | 2016-07-25T17:53:19Z | [
"python",
"numpy",
"scipy"
] |
lambda unexpected results | 38,568,796 | <p>I have the following simple python code</p>
<pre><code>numbers = range(1,100)
print (list(numbers))
numbers_over_30 = filter(lambda x: x>>30,numbers)
print (list(numbers_over_30))
</code></pre>
<p>I create a list of numbers from 1 to 99 and that works fine giving me</p>
<pre><code>[1,2,3,4,5.....97,98,99]
</code></pre>
<p>the second list should give me</p>
<pre><code>[31,32,33....97,98,99]
</code></pre>
<p>but I only get an empty list <code>[]</code>. </p>
<p>If I change the lambda function I get as below:</p>
<pre><code>x>>5 gives me [32,33,34...97,98,99]
x>>4 gives me [16,17,18...97,98,99]
x>>3 gives me [8,9,10...97,98,99]
</code></pre>
<p>Can anyone shed some light on what the lambda function is doing? I expected that <code>numbers_over_30</code> would consist of all values of numbers for which <code>x>>30</code> was true?</p>
<p>I'm sure there are better ways to do it but I'm specifically trying to achieve the result using filter and lambda per a CodeAcademy unit so am just trying to understand what is happening.</p>
| -1 | 2016-07-25T13:14:36Z | 38,569,043 | <p>You need just to delete one >, so your code will be : </p>
<pre><code>numbers = range(1,100)
print (list(numbers))
numbers_over_30 = filter(lambda x: x>30,numbers) # here your error
print (list(numbers_over_30))
</code></pre>
| 0 | 2016-07-25T13:26:13Z | [
"python",
"lambda"
] |
Python open html file, take screenshot, crop and save as image | 38,568,804 | <p>I am using the Bokeh package to generate maps to show the results of a simulation. The output is individual maps in html format with interactivity. The interactivity is needed for individual maps. </p>
<p>See this link for an example:</p>
<p><a href="http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html" rel="nofollow">http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html</a></p>
<p>The simulation can automatically be set to run a number of times and will produce a map for each run. This could be 100's of maps. I would like to be able to stitch together the maps to create a movie - the interactivity is not required for this. Bokeh has functionality to create PNG files via the browser so it is possible to manually save each map as a file and use ffmpeg to create a movie. However this is not really an option if you need to do it for 100's of files. Currently there is no way to automatically generate PNG files via Bokeh but I believe it will be added at some point.</p>
<p>So I need a workaround. My thought is to open each html file from the location they are stored on the local drive, take a screen shot, crop the image to keep the required section and save. But I have not yet found a solution that works.</p>
<p>Cropping an image is easy:</p>
<pre><code>from PIL import Image
img = Image.open(file_name)
box = (1, 1, 1000, 1000)
area = img.crop(box)
area.save('saved_image', 'jpeg')
</code></pre>
<p>My problem is opening the html file and taking the screen shot in the first place to feed to the above code.</p>
<p>For this I have tried the following but both require a URL rather than an html file. Also both use Firefox which doesn't work for me but I have installed chrome and altered the code appropriately.</p>
<p><a href="http://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python">How to take partial screenshot with Selenium WebDriver in python?</a></p>
<p><a href="http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/" rel="nofollow">http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/</a></p>
<p>My code for this is:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get('file_name')
driver.save_screenshot('image.png')
driver.quit()
</code></pre>
<p>Which returns:</p>
<pre><code>{"code":-32603,"message":"Cannot navigate to invalid URL"}
</code></pre>
<p>Clearly a filename is not a url so that is clear. It works fine if you pass it a website. Any help in getting a html loaded and a picture taken would be greatly appreciated! It does not have to involve Selenium.</p>
| 1 | 2016-07-25T13:14:58Z | 38,569,146 | <p>If you're running Linux, you may have to do the following steps. </p>
<p>First open the html file via <a href="http://askubuntu.com/questions/15354/how-to-open-file-with-default-application-from-command-line">command line</a> in the default app. You'll probably have to do something like</p>
<pre><code>import os
os.system('command to open html file')
</code></pre>
<p>Use the <a href="http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux">solution listed</a> to take your screenshot.</p>
<p>Then do the processing in PIL as suggested. </p>
<p>If you're doing this in windows, </p>
<p>You may want to setup the AutoIT drivers so that you can use your python script to manipulate GUI windows etc. </p>
| 0 | 2016-07-25T13:31:04Z | [
"python",
"html",
"selenium",
"bokeh"
] |
Python open html file, take screenshot, crop and save as image | 38,568,804 | <p>I am using the Bokeh package to generate maps to show the results of a simulation. The output is individual maps in html format with interactivity. The interactivity is needed for individual maps. </p>
<p>See this link for an example:</p>
<p><a href="http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html" rel="nofollow">http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html</a></p>
<p>The simulation can automatically be set to run a number of times and will produce a map for each run. This could be 100's of maps. I would like to be able to stitch together the maps to create a movie - the interactivity is not required for this. Bokeh has functionality to create PNG files via the browser so it is possible to manually save each map as a file and use ffmpeg to create a movie. However this is not really an option if you need to do it for 100's of files. Currently there is no way to automatically generate PNG files via Bokeh but I believe it will be added at some point.</p>
<p>So I need a workaround. My thought is to open each html file from the location they are stored on the local drive, take a screen shot, crop the image to keep the required section and save. But I have not yet found a solution that works.</p>
<p>Cropping an image is easy:</p>
<pre><code>from PIL import Image
img = Image.open(file_name)
box = (1, 1, 1000, 1000)
area = img.crop(box)
area.save('saved_image', 'jpeg')
</code></pre>
<p>My problem is opening the html file and taking the screen shot in the first place to feed to the above code.</p>
<p>For this I have tried the following but both require a URL rather than an html file. Also both use Firefox which doesn't work for me but I have installed chrome and altered the code appropriately.</p>
<p><a href="http://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python">How to take partial screenshot with Selenium WebDriver in python?</a></p>
<p><a href="http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/" rel="nofollow">http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/</a></p>
<p>My code for this is:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get('file_name')
driver.save_screenshot('image.png')
driver.quit()
</code></pre>
<p>Which returns:</p>
<pre><code>{"code":-32603,"message":"Cannot navigate to invalid URL"}
</code></pre>
<p>Clearly a filename is not a url so that is clear. It works fine if you pass it a website. Any help in getting a html loaded and a picture taken would be greatly appreciated! It does not have to involve Selenium.</p>
| 1 | 2016-07-25T13:14:58Z | 38,569,320 | <p>You can use <a href="https://docs.python.org/2/library/simplehttpserver.html" rel="nofollow" title="SimpleHTTPServer">SimpleHTTPServer</a> to create a basic webserver and expose your local file. </p>
<p>You should run this in the path where is the htmt <code>python -m SimpleHTTPServer 8000
</code></p>
<p>Then just change <code>driver.get('file_name')</code> to <code>driver.get('localhost:8000/file_name.html')</code></p>
<p>I recomend you to use <strong>"wait until"</strong> to be sure everything is loaded before take the screenshot:</p>
<p><code>driver.wait.until(EC.visibility_of_element_located((By.XPATH,'//*[@id="someID"]') ))
</code></p>
| 1 | 2016-07-25T13:39:10Z | [
"python",
"html",
"selenium",
"bokeh"
] |
Python open html file, take screenshot, crop and save as image | 38,568,804 | <p>I am using the Bokeh package to generate maps to show the results of a simulation. The output is individual maps in html format with interactivity. The interactivity is needed for individual maps. </p>
<p>See this link for an example:</p>
<p><a href="http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html" rel="nofollow">http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html</a></p>
<p>The simulation can automatically be set to run a number of times and will produce a map for each run. This could be 100's of maps. I would like to be able to stitch together the maps to create a movie - the interactivity is not required for this. Bokeh has functionality to create PNG files via the browser so it is possible to manually save each map as a file and use ffmpeg to create a movie. However this is not really an option if you need to do it for 100's of files. Currently there is no way to automatically generate PNG files via Bokeh but I believe it will be added at some point.</p>
<p>So I need a workaround. My thought is to open each html file from the location they are stored on the local drive, take a screen shot, crop the image to keep the required section and save. But I have not yet found a solution that works.</p>
<p>Cropping an image is easy:</p>
<pre><code>from PIL import Image
img = Image.open(file_name)
box = (1, 1, 1000, 1000)
area = img.crop(box)
area.save('saved_image', 'jpeg')
</code></pre>
<p>My problem is opening the html file and taking the screen shot in the first place to feed to the above code.</p>
<p>For this I have tried the following but both require a URL rather than an html file. Also both use Firefox which doesn't work for me but I have installed chrome and altered the code appropriately.</p>
<p><a href="http://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python">How to take partial screenshot with Selenium WebDriver in python?</a></p>
<p><a href="http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/" rel="nofollow">http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/</a></p>
<p>My code for this is:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get('file_name')
driver.save_screenshot('image.png')
driver.quit()
</code></pre>
<p>Which returns:</p>
<pre><code>{"code":-32603,"message":"Cannot navigate to invalid URL"}
</code></pre>
<p>Clearly a filename is not a url so that is clear. It works fine if you pass it a website. Any help in getting a html loaded and a picture taken would be greatly appreciated! It does not have to involve Selenium.</p>
| 1 | 2016-07-25T13:14:58Z | 38,585,327 | <p>hgazibara comment proved to be the simplest fix. Some simplified code is below to provide the answer. It would be nice if the web page didn't actually have to show itself for the screen shot to be taken. I will see if I can add this later.</p>
<pre><code>import glob
from PIL import Image
from selenium import webdriver
# get a list of all the files to open
glob_folder = os.path.join(file_location, '*.html')
html_file_list = glob.glob(glob_folder)
index = 1
for html_file in html_file_list:
# get the name into the right format
temp_name = "file://" + html_file
# open in webpage
driver = webdriver.Chrome()
driver.get(temp_name)
save_name = '00' + str(index) + '.png'
driver.save_screenshot(save_path, save_name))
driver.quit()
index += 1
# crop as required
img = Image.open(save_path, save_name))
box = (1, 1, 1000, 1000)
area = img.crop(box)
area.save('cropped_image' + str(index), 'png')
</code></pre>
| 0 | 2016-07-26T08:57:06Z | [
"python",
"html",
"selenium",
"bokeh"
] |
Different models in one view | 38,568,899 | <p>Hi I am very new in django. I wonder if I could user different models in one view.
So I looked this page <a href="https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/" rel="nofollow">https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/</a>
It was so useful but I couldn't see output on browser page. Where did I made mistake?</p>
<h1>my views</h1>
<pre><code>from .models import Contact, MyUser
from .forms import ContactForm, UserRegisterForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def total_register(request):
uform = UserRegisterForm()
cform = ContactForm()
if request.method == "POST":
uform = UserRegisterForm(request.POST or None, instance=MyUser())
cform = [ContactForm(request.POST or None, prefix=str(x), instance=Contact()) for x in range(0,19)]
if uform.is_valid() and all([cf.is_valid() for cf in cform]):
new_MyUser = uform.save()
for cf in cform:
new_contact = cf.save(commit=False)
new_contact.MyUser = new_MyUser
new_contact.save()
return HttpResponseRedirect('/')
else:
pform = UserRegisterForm(instance=MyUser())
cform = [ContactForm(prefix=str(x), instance=Contact()) for x in range(0,19)]
return render_to_response('total_register.html', {'UserRegisterForm': uform, 'ContactForm': cform})
</code></pre>
<h1>my forms</h1>
<pre><code>class UserRegisterForm(forms.ModelForm):
username = forms.CharField(label = 'isminizi giriniz')
lastname = forms.CharField(label = 'soyisminizi giriniz')
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'lastname',
]
def signup(self, request, user):
user.username = self.cleaned_data['username']
user.lastname = self.cleaned_data['lastname']
user.save()
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['username','soyad','cinsiyet','unvan','kurum',"bolum","gorev", "uzmanlik","adres","posta_kodu","sehir","ulke","is_tel","ev_tel","fax_no","cep_tel","email"]
</code></pre>
<h1>my urls</h1>
<pre><code> url(r'^kayit/', bildirge.views.total_register, name = 'kayit'),
</code></pre>
<h1>my html</h1>
<pre><code>{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<hr/>
<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form|crispy }}
<button type='submit'>gonder</button>
</form>
</div>
{% endblock content %}
</code></pre>
<p>Thanks in advance</p>
| 0 | 2016-07-25T13:19:41Z | 38,569,161 | <p>You've sent two variables to your template, with the keys <code>UserRegisterForm</code> and <code>ContactForm</code>. You have to use those names in your template, not just <code>form</code>.</p>
| 0 | 2016-07-25T13:31:27Z | [
"python",
"django"
] |
Different models in one view | 38,568,899 | <p>Hi I am very new in django. I wonder if I could user different models in one view.
So I looked this page <a href="https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/" rel="nofollow">https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/</a>
It was so useful but I couldn't see output on browser page. Where did I made mistake?</p>
<h1>my views</h1>
<pre><code>from .models import Contact, MyUser
from .forms import ContactForm, UserRegisterForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def total_register(request):
uform = UserRegisterForm()
cform = ContactForm()
if request.method == "POST":
uform = UserRegisterForm(request.POST or None, instance=MyUser())
cform = [ContactForm(request.POST or None, prefix=str(x), instance=Contact()) for x in range(0,19)]
if uform.is_valid() and all([cf.is_valid() for cf in cform]):
new_MyUser = uform.save()
for cf in cform:
new_contact = cf.save(commit=False)
new_contact.MyUser = new_MyUser
new_contact.save()
return HttpResponseRedirect('/')
else:
pform = UserRegisterForm(instance=MyUser())
cform = [ContactForm(prefix=str(x), instance=Contact()) for x in range(0,19)]
return render_to_response('total_register.html', {'UserRegisterForm': uform, 'ContactForm': cform})
</code></pre>
<h1>my forms</h1>
<pre><code>class UserRegisterForm(forms.ModelForm):
username = forms.CharField(label = 'isminizi giriniz')
lastname = forms.CharField(label = 'soyisminizi giriniz')
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'lastname',
]
def signup(self, request, user):
user.username = self.cleaned_data['username']
user.lastname = self.cleaned_data['lastname']
user.save()
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['username','soyad','cinsiyet','unvan','kurum',"bolum","gorev", "uzmanlik","adres","posta_kodu","sehir","ulke","is_tel","ev_tel","fax_no","cep_tel","email"]
</code></pre>
<h1>my urls</h1>
<pre><code> url(r'^kayit/', bildirge.views.total_register, name = 'kayit'),
</code></pre>
<h1>my html</h1>
<pre><code>{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ title }}</h1>
<hr/>
<form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{ form|crispy }}
<button type='submit'>gonder</button>
</form>
</div>
{% endblock content %}
</code></pre>
<p>Thanks in advance</p>
| 0 | 2016-07-25T13:19:41Z | 38,569,205 | <p>You are using the variable <code>form</code> in your template, but you are passing <code>UserRegisterForm</code> and <code>ContactForm</code> as template context.</p>
<p>Try something like:</p>
<pre><code><form...>
{{ UserRegisterForm }}
{% for form in ContactForm %}
{{ form }}
{% endfor %}
</form>
</code></pre>
<p>Two hints:</p>
<ul>
<li>check out <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/" rel="nofollow">formsets</a> for handling multiple forms of the same type</li>
<li>please make sure your code is correctly indented, especially with Python</li>
</ul>
| 1 | 2016-07-25T13:33:59Z | [
"python",
"django"
] |
Pandas: add values to dataframe | 38,568,931 | <p>I have df</p>
<pre><code>ID,"url","used_at","active_seconds"
9e871f65d402254b15470881c79cec94,"mvideo.ru/smartfony-sotovye-telefony/smartfony-205",2016-04-01 00:00:00,10
8fe968e88d209b2854c47f812211cd2d,"group.aliexpress.com/ruNew.htm?spm=2114.7749990.120000116.87.rxes4x&catId=0&page=17#product-list-tab",2016-04-01 00:00:01,32
0ba8d1c3feff21ff15a86ad77ba60b9e,"hz.ru.aliexpress.com/item/Newest-1Pcs-Novelty-Design-Funny-Pvc-Fish-Shape-Zipper-Pencil-Bag-Stationery-Supplies-Pencil-Case-Fantastic/32632783689.html?aff_platform=aaf&sk=eub6yrrBy%3A&cpt=1459447196454&af=13862&cv=2043168&cn=1o4x0n v5z81gr2tvie6cjw5apalm3lr4&dp=v5_1o4x0nv5z81gr2tvie6cjw5apalm3lr4&afref=http%3A%2F%2Fvk.com%2Faway.ph&aff_trace_key=52dd417516c0437484c16009b0fab9b2-1459447196454-01255-eub6yrrBy",2016-04-01 00:00:01,24
9dedf5c86704a4ceb7d72d3b465056a0,"ru.aliexpress.com/af/category/202040573/4.html?isAffiliate=y&site=rus&shipCountry=RU&g=y&needQuery=n",2016-04-01 00:00:01,10
0e12c8425fd2dbd919feb1055b007460,"dns-shop.ru/product/4ba05489c41e3120/avtosignalizacia-starline-a61-dialog#comment",2016-04-01 00:00:02,2
dff9169891d7e5b5585c75e2391561e4,"ru.aliexpress.com/item/AEVOGUE-Cool-Cat-Eye-Sunglasses-Women-Summer-Style-Sun-Glasses-Brand-Designer-Vintage-Gafas-Oculos-De/32380450045.html",2016-04-01 00:00:02,4
5cecd2312b300766a7668784b464dd69,"ru.aliexpress.com/category/202001922/girls-clothing.html?site=rus&SortType=price_asc&g=y&shipCountry=RU&needQuery=n&isFreeShip=y&isrefine=y",2016-04-01 00:00:03,6
61d59ec6c83bacdefc510b0fe3d2c449,"ru.aliexpress.com/item/2013-autumn-new-chiffon-harem-pants-trousers-AB7-3-C40/1242434570.html?spm=2114.30010608.3.61.YAjncN&ws_ab_test=searchweb201556_9,searchweb201602_3_10036_10035_10034_507_10020_10017_10005_10006_10021_10022_10007_10018_10019,searchweb201603_9&btsid=1403b8fd-21f4-436e-920a-c329bee1586f",2016-04-01 00:00:03,329
</code></pre>
<p>And I have another df2</p>
<pre><code> ID
6a1de956f88cdde3760a09922fa688d7
b285f7d87e9e85ca67b939e77ce5ba1d
fb2a53cf613e7fdfb98ef82af2db1fa6
f3a62fcfb7734537c3d798d866c905e2
8e1f1b728b235532f6e9243f8639c98e
7d276f5712e9ef6f331fc9234f28be5e
</code></pre>
<p>I need to add <code>ID</code> from <code>df2</code> with all values equal to <code>0</code>.
How can I do it?</p>
| 0 | 2016-07-25T13:21:18Z | 38,572,443 | <p>You can use <code>pd.concat</code> on a list of the dfs with <code>fillna(0)</code>:</p>
<pre><code>In [68]:
new_df = pd.concat([df,df2], ignore_index=True).fillna(0)
new_df
Out[68]:
ID active_seconds \
0 9e871f65d402254b15470881c79cec94 10.0
1 8fe968e88d209b2854c47f812211cd2d 32.0
2 0ba8d1c3feff21ff15a86ad77ba60b9e 24.0
3 9dedf5c86704a4ceb7d72d3b465056a0 10.0
4 0e12c8425fd2dbd919feb1055b007460 2.0
5 dff9169891d7e5b5585c75e2391561e4 4.0
6 5cecd2312b300766a7668784b464dd69 6.0
7 61d59ec6c83bacdefc510b0fe3d2c449 329.0
8 6a1de956f88cdde3760a09922fa688d7 0.0
9 b285f7d87e9e85ca67b939e77ce5ba1d 0.0
10 fb2a53cf613e7fdfb98ef82af2db1fa6 0.0
11 f3a62fcfb7734537c3d798d866c905e2 0.0
12 8e1f1b728b235532f6e9243f8639c98e 0.0
13 7d276f5712e9ef6f331fc9234f28be5e 0.0
url used_at
0 mvideo.ru/smartfony-sotovye-telefony/smartfony... 2016-04-01 00:00:00
1 group.aliexpress.com/ruNew.htm?spm=2114.774999... 2016-04-01 00:00:01
2 hz.ru.aliexpress.com/item/Newest-1Pcs-Novelty-... 2016-04-01 00:00:01
3 ru.aliexpress.com/af/category/202040573/4.html... 2016-04-01 00:00:01
4 dns-shop.ru/product/4ba05489c41e3120/avtosigna... 2016-04-01 00:00:02
5 ru.aliexpress.com/item/AEVOGUE-Cool-Cat-Eye-Su... 2016-04-01 00:00:02
6 ru.aliexpress.com/category/202001922/girls-clo... 2016-04-01 00:00:03
7 ru.aliexpress.com/item/2013-autumn-new-chiffon... 2016-04-01 00:00:03
8 0 0
9 0 0
10 0 0
11 0 0
12 0 0
13 0 0
</code></pre>
| 0 | 2016-07-25T15:58:11Z | [
"python",
"pandas"
] |
Why am I not getting any output in the below code? | 38,568,970 | <p>There are no errors while compiling the code. I am calling the function as: <code>pattern('abc')</code>. Expecting output as <code>'A-Bb-Ccc'</code></p>
<pre><code>def pattern(s):
v = []
v = list(s)
strlen = len(v)
i = 0
cntr = 0
strng = []
while i < strlen:
j = 0
while j <= i:
if j == 0:
strng.append(v[i].upper())
else:
strng.append(v[i])
j += 1
strng.append('-')
i += 1
z = ''.join(strng)
return z
</code></pre>
| 1 | 2016-07-25T13:23:33Z | 38,569,178 | <p><strong>UPDATE</strong> using <code>enumerate</code> instead of <code>zip</code></p>
<pre><code>source = 'abc'
'-'.join([(x*i).capitalize() for i, x in enumerate(source, 1)])
</code></pre>
<hr>
<pre><code>source = 'abc'
'-'.join([(x*i).capitalize() for x,i in zip(source, range(1, len(source)+1))])
</code></pre>
<p>Some explanations:</p>
<p><code>zip(source, range(1, len(source)+1))</code> create pairs <code>(a,1), (b,2), (c,3)</code></p>
<p><code>x*i</code> means concatenation i.e. <code>a*3</code> generate the string <code>aaa</code></p>
<p><code>aaa.capitalize()</code> makes first letter a capital one</p>
<p><code>'-'.join(a_list)</code> joins elements in <code>a_list</code> using <code>-</code> as separator</p>
| 3 | 2016-07-25T13:32:40Z | [
"python",
"python-2.7"
] |
Why am I not getting any output in the below code? | 38,568,970 | <p>There are no errors while compiling the code. I am calling the function as: <code>pattern('abc')</code>. Expecting output as <code>'A-Bb-Ccc'</code></p>
<pre><code>def pattern(s):
v = []
v = list(s)
strlen = len(v)
i = 0
cntr = 0
strng = []
while i < strlen:
j = 0
while j <= i:
if j == 0:
strng.append(v[i].upper())
else:
strng.append(v[i])
j += 1
strng.append('-')
i += 1
z = ''.join(strng)
return z
</code></pre>
| 1 | 2016-07-25T13:23:33Z | 38,569,674 | <p>You have no print statement. To test it, fill in </p>
<p><code>print(z)</code>. </p>
<p>Also you have to put the return outside of the while loop. </p>
| 1 | 2016-07-25T13:54:48Z | [
"python",
"python-2.7"
] |
Why am I not getting any output in the below code? | 38,568,970 | <p>There are no errors while compiling the code. I am calling the function as: <code>pattern('abc')</code>. Expecting output as <code>'A-Bb-Ccc'</code></p>
<pre><code>def pattern(s):
v = []
v = list(s)
strlen = len(v)
i = 0
cntr = 0
strng = []
while i < strlen:
j = 0
while j <= i:
if j == 0:
strng.append(v[i].upper())
else:
strng.append(v[i])
j += 1
strng.append('-')
i += 1
z = ''.join(strng)
return z
</code></pre>
| 1 | 2016-07-25T13:23:33Z | 38,570,774 | <p>Well first, you need to indent <code>return z</code> so it is not in any of the loops:</p>
<pre><code>def pattern(s):
#Rest of the code
return z
</code></pre>
<p>Then you need to assign the result of the function to a variable and print it:</p>
<pre><code>result = pattern('abc')
print result
</code></pre>
<p>Or you could do a more direct method:</p>
<pre><code>print pattern('abc')
</code></pre>
| 0 | 2016-07-25T14:42:10Z | [
"python",
"python-2.7"
] |
Why am I not getting any output in the below code? | 38,568,970 | <p>There are no errors while compiling the code. I am calling the function as: <code>pattern('abc')</code>. Expecting output as <code>'A-Bb-Ccc'</code></p>
<pre><code>def pattern(s):
v = []
v = list(s)
strlen = len(v)
i = 0
cntr = 0
strng = []
while i < strlen:
j = 0
while j <= i:
if j == 0:
strng.append(v[i].upper())
else:
strng.append(v[i])
j += 1
strng.append('-')
i += 1
z = ''.join(strng)
return z
</code></pre>
| 1 | 2016-07-25T13:23:33Z | 38,570,942 | <p>You have an infinite loop. You need to have <code>j</code> increment in the inner <code>while</code> loop or <code>j</code> will always be less then <code>i</code> if you call <code>print(pattern("abc"))</code> after you fix the indentation it should return what you are looking for.</p>
<p>TL;DR, add an indent before <code>j+=1</code></p>
| 0 | 2016-07-25T14:49:39Z | [
"python",
"python-2.7"
] |
Install dependencies based on condition | 38,568,971 | <p>I am using Travis-ci.org as continuous integration server developing some Python packages. I would like to install project dependencies from PyPi server conditionally. Builds from master branch should install dependencies from the real PyPI server while builds from other branches should install dependencies from TestPyPI.</p>
<p>I tried to use TRAVIS_BRANCH environment variable from an external bash script, but with no success. Any help would be appreciated.</p>
<p><strong>.travis.yml</strong></p>
<pre><code>language: python
python:
- "2.7"
install:
- ~/install_dependencies.sh
script:
- python runtests.py --with-coverage --cover-package=package
- python setup.py test
- python setup.py sdist --format zip
after_success:
coveralls
</code></pre>
<p><strong>install_dependencies.sh</strong></p>
<pre><code>#!/usr/bin/env bash
if [ "${TRAVIS_BRANCH}" = "master" ]; then
pip install -r requirements.txt
pip install cloudshell-automation-api>=7.0.0.0,<7.1.0.0
else
pip install -r requirements.txt --index-url https://testpypi.python.org/simple
pip install cloudshell-automation-api>=7.0.0.0,<7.1.0.0 --index-url https://testpypi.python.org/simple
fi
pip install -r test_requirements.txt
pip install coveralls
</code></pre>
<p>Thanks!</p>
| 1 | 2016-07-25T13:23:35Z | 38,570,862 | <p>The problem was with the execution of the Bash script from the .travis.yml.
It needs to be executed like this:</p>
<pre><code>bash ./install_dependencies.sh
</code></pre>
<p>Below file works fine:</p>
<p><strong>.travis.yml</strong></p>
<pre><code>language: python
python:
- "2.7"
install:
- bash ./install_dependencies.sh
script:
- python runtests.py --with-coverage --cover-package=package
- python setup.py test
- python setup.py sdist --format zip
after_success:
coveralls
</code></pre>
| 0 | 2016-07-25T14:45:56Z | [
"python",
"bash",
"continuous-integration",
"containers",
"travis-ci"
] |
Trouble piping output from python script | 38,568,995 | <p>I am having trouble getting the output from a python script, that I didn't write, redirected to grep. Below are my experiments including the base cases. "myPythonCmd" is long running and streams to stdout.</p>
<p>Any suggestions?</p>
<hr>
<pre><code>/myPythonCmd.py arg1 arg2
</code></pre>
<p>Outputs both stderr and stdout to the screen</p>
<pre><code>/myPythonCmd.py arg1 arg2 2>/dev/null
</code></pre>
<p>Outputs just stdout to the screen</p>
<pre><code>/myPythonCmd.py arg1 arg2 2>/dev/null > outputfile
</code></pre>
<p>Outputs nothing to the screen, but writes stdout to outputfile</p>
<pre><code>/myPythonCmd.py arg1 arg2 2>/dev/null | grep searchTerm
</code></pre>
<p>Outputs NOTHING even though I know searchTerm is present.</p>
<pre><code>/myPythonCmd.py arg1 arg2 2>/dev/null | grep --line-buffered searchTerm
</code></pre>
<p>Outputs NOTHING even though I know searchTerm is present.</p>
| 0 | 2016-07-25T13:24:27Z | 38,569,397 | <p>python's -u option is what was needed. Thanks @PM_2Ring</p>
<pre><code>python -u myPythonCmd.py arg1 arg2 2>/dev/null | grep searchTerm
</code></pre>
| 0 | 2016-07-25T13:42:47Z | [
"python",
"unix",
"grep",
"pipe",
"command-line-interface"
] |
How do I invert key and value in RDD in Python 3 pyspark? | 38,569,052 | <p>This works in Python 2.7, but in Python 3.5 it returns</p>
<blockquote>
<p>SyntaxError: invalid syntax.</p>
</blockquote>
<p>I'm not sure if this has to do with the fact that "tuple unpacking" was removed from Python 3, as I read on another post, or is a different issue. </p>
<pre><code>rddInverted = rdd.map(lambda (x,y): (y,x))
</code></pre>
| 0 | 2016-07-25T13:26:47Z | 38,569,339 | <p>Try something like this:</p>
<pre><code>rddInverted = rdd.map(lambda x: (x[1], x[0]))
</code></pre>
<p>I hope it will work</p>
| 1 | 2016-07-25T13:40:10Z | [
"python",
"python-3.x",
"rdd",
"invert"
] |
How do I invert key and value in RDD in Python 3 pyspark? | 38,569,052 | <p>This works in Python 2.7, but in Python 3.5 it returns</p>
<blockquote>
<p>SyntaxError: invalid syntax.</p>
</blockquote>
<p>I'm not sure if this has to do with the fact that "tuple unpacking" was removed from Python 3, as I read on another post, or is a different issue. </p>
<pre><code>rddInverted = rdd.map(lambda (x,y): (y,x))
</code></pre>
| 0 | 2016-07-25T13:26:47Z | 38,569,361 | <p>Your lambda function is on the row of the RDD, which is a tuple. Below is what you want.</p>
<pre><code>rddInverted = rdd.map(lambda x: (x[1],x[0]))
</code></pre>
| 1 | 2016-07-25T13:41:04Z | [
"python",
"python-3.x",
"rdd",
"invert"
] |
How do I invert key and value in RDD in Python 3 pyspark? | 38,569,052 | <p>This works in Python 2.7, but in Python 3.5 it returns</p>
<blockquote>
<p>SyntaxError: invalid syntax.</p>
</blockquote>
<p>I'm not sure if this has to do with the fact that "tuple unpacking" was removed from Python 3, as I read on another post, or is a different issue. </p>
<pre><code>rddInverted = rdd.map(lambda (x,y): (y,x))
</code></pre>
| 0 | 2016-07-25T13:26:47Z | 38,570,437 | <p>The solution is: </p>
<pre><code>rddInverted=rdd.map(lambda xy: (xy[1],xy[0]))
</code></pre>
| 0 | 2016-07-25T14:27:37Z | [
"python",
"python-3.x",
"rdd",
"invert"
] |
Module urllib.request not getting data | 38,569,115 | <p>I am trying to test this demo program from lynda using Python 3. I am using Pycharm as my IDE. I already added and installed the request package, but when I run the program, it runs cleanly and shows a message "Process finished with exit code 0", but does not show any output from print statement. Where am I going wrong ?</p>
<pre><code>import urllib.request # instead of urllib2 like in Python 2.7
import json
def printResults(data):
# Use the json module to load the string data into a dictionary
theJSON = json.loads(data)
# now we can access the contents of the JSON like any other Python object
if "title" in theJSON["metadata"]:
print(theJSON["metadata"]["title"])
# output the number of events, plus the magnitude and each event name
count = theJSON["metadata"]["count"];
print(str(count) + " events recorded")
# for each event, print the place where it occurred
for i in theJSON["features"]:
print(i["properties"]["place"])
# print the events that only have a magnitude greater than 4
for i in theJSON["features"]:
if i["properties"]["mag"] >= 4.0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])
# print only the events where at least 1 person reported feeling something
print("Events that were felt:")
for i in theJSON["features"]:
feltReports = i["properties"]["felt"]
if feltReports != None:
if feltReports > 0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times")
# Open the URL and read the data
urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
webUrl = urllib.request.urlopen(urlData)
print(webUrl.getcode())
if webUrl.getcode() == 200:
data = webUrl.read()
data = data.decode("utf-8") # in Python 3.x we need to explicitly decode the response to a string
# print out our customized results
printResults(data)
else:
print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))
</code></pre>
| 0 | 2016-07-25T13:29:53Z | 38,569,784 | <p>Not sure if you left this out on purpose, but this script isn't actually executing any code beyond the imports and function definition. Assuming you didn't leave it out on purpose, you would need the following at the end of your file.</p>
<pre><code>if __name__ == '__main__':
data = "" # your data
printResults(data)
</code></pre>
<p>The check on <code>__name__</code> equaling <code>"__main__"</code> is just so your code is only executing when the file is explicitly run. To always run your <code>printResults(data)</code> function when the file is accessed (like, say, if its imported into another module) you could just call it at the bottom of your file like so:</p>
<pre><code>data = "" # your data
printResults(data)
</code></pre>
| 0 | 2016-07-25T13:59:53Z | [
"python",
"pycharm",
"urllib2",
"urllib",
"python-3.5"
] |
Module urllib.request not getting data | 38,569,115 | <p>I am trying to test this demo program from lynda using Python 3. I am using Pycharm as my IDE. I already added and installed the request package, but when I run the program, it runs cleanly and shows a message "Process finished with exit code 0", but does not show any output from print statement. Where am I going wrong ?</p>
<pre><code>import urllib.request # instead of urllib2 like in Python 2.7
import json
def printResults(data):
# Use the json module to load the string data into a dictionary
theJSON = json.loads(data)
# now we can access the contents of the JSON like any other Python object
if "title" in theJSON["metadata"]:
print(theJSON["metadata"]["title"])
# output the number of events, plus the magnitude and each event name
count = theJSON["metadata"]["count"];
print(str(count) + " events recorded")
# for each event, print the place where it occurred
for i in theJSON["features"]:
print(i["properties"]["place"])
# print the events that only have a magnitude greater than 4
for i in theJSON["features"]:
if i["properties"]["mag"] >= 4.0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])
# print only the events where at least 1 person reported feeling something
print("Events that were felt:")
for i in theJSON["features"]:
feltReports = i["properties"]["felt"]
if feltReports != None:
if feltReports > 0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times")
# Open the URL and read the data
urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
webUrl = urllib.request.urlopen(urlData)
print(webUrl.getcode())
if webUrl.getcode() == 200:
data = webUrl.read()
data = data.decode("utf-8") # in Python 3.x we need to explicitly decode the response to a string
# print out our customized results
printResults(data)
else:
print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))
</code></pre>
| 0 | 2016-07-25T13:29:53Z | 38,570,114 | <p>I had to restart the IDE after installing the module. I just realized and tried it now with "Run as Admin". Strangely seems to work now.But not sure if it was a temp error, since even without restart, it was able to detect the module and its methods. </p>
| 0 | 2016-07-25T14:13:23Z | [
"python",
"pycharm",
"urllib2",
"urllib",
"python-3.5"
] |
Module urllib.request not getting data | 38,569,115 | <p>I am trying to test this demo program from lynda using Python 3. I am using Pycharm as my IDE. I already added and installed the request package, but when I run the program, it runs cleanly and shows a message "Process finished with exit code 0", but does not show any output from print statement. Where am I going wrong ?</p>
<pre><code>import urllib.request # instead of urllib2 like in Python 2.7
import json
def printResults(data):
# Use the json module to load the string data into a dictionary
theJSON = json.loads(data)
# now we can access the contents of the JSON like any other Python object
if "title" in theJSON["metadata"]:
print(theJSON["metadata"]["title"])
# output the number of events, plus the magnitude and each event name
count = theJSON["metadata"]["count"];
print(str(count) + " events recorded")
# for each event, print the place where it occurred
for i in theJSON["features"]:
print(i["properties"]["place"])
# print the events that only have a magnitude greater than 4
for i in theJSON["features"]:
if i["properties"]["mag"] >= 4.0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])
# print only the events where at least 1 person reported feeling something
print("Events that were felt:")
for i in theJSON["features"]:
feltReports = i["properties"]["felt"]
if feltReports != None:
if feltReports > 0:
print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times")
# Open the URL and read the data
urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
webUrl = urllib.request.urlopen(urlData)
print(webUrl.getcode())
if webUrl.getcode() == 200:
data = webUrl.read()
data = data.decode("utf-8") # in Python 3.x we need to explicitly decode the response to a string
# print out our customized results
printResults(data)
else:
print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))
</code></pre>
| 0 | 2016-07-25T13:29:53Z | 38,570,302 | <p>Your comments re: having to restart your IDE makes me think that pycharm might not automatically detect newly installed python packages. This SO answer seems to offer a solution.</p>
<p><a href="http://stackoverflow.com/a/26069398/3264217">SO answer</a></p>
| 0 | 2016-07-25T14:21:11Z | [
"python",
"pycharm",
"urllib2",
"urllib",
"python-3.5"
] |
Access a function present in C# dll using Python | 38,569,185 | <p>I want to access a function <strong>my_function()</strong> present in a c# file which is compiled into a .net dll - <strong>abc.dll</strong>. </p>
<p><strong>C# file</strong></p>
<pre><code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class Class1
{
public string my_function()
{
return "Hello World.. :-";
}
}
}
</code></pre>
<p>After compiling the above code to abc.dll</p>
<p><strong>Using the below python trying to access my_function()</strong></p>
<pre><code> import ctypes
lib = ctypes.WinDLL('abc.dll')
print lib.my_function()
</code></pre>
<p><strong>Above code throws error</strong></p>
<blockquote>
<blockquote>
<blockquote>
<p>lib.my_function()
Traceback (most recent call last):
File "", line 1, in
File "C:\Anaconda\lib\ctypes__init__.py", line 378, in <strong>getattr</strong>
func = self.<strong>getitem</strong>(name)
File "C:\Anaconda\lib\ctypes__init__.py", line 383, in <strong>getitem</strong>
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'my_function' not found</p>
</blockquote>
</blockquote>
</blockquote>
| -1 | 2016-07-25T13:33:08Z | 38,569,699 | <p>You haven't made the function visible in the DLL.</p>
<p>There are a few different ways you can do this. The easiest is probably to use the <a href="https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports" rel="nofollow">unmanagedexports</a> package. It allows you to call C# functions directly like normal C functions by decorating your function with [DllExport] attribute, like P/Invoke's DllImport. It uses part of the subsystem meant to make C++/CLI mixed managed libraries work.</p>
<p>C# code</p>
<pre><code>class Example
{
[DllExport("ExampleFunction", CallingConvention = CallingConvention.StdCall)]
public static int ExampleFunction(int a, int b)
{
return a + b;
}
}
</code></pre>
<p>Python</p>
<pre><code>import ctypes
lib = ctypes.WinDLL('example.dll')
print lib.ExampleFunction(12, 34)
</code></pre>
| 1 | 2016-07-25T13:55:48Z | [
"c#",
"python",
".net",
"ctypes",
"dllimport"
] |
Can't access functions in Excel.Application().Workbooks from Python 2.7/3.5: '__ComObject' object has no attribute X | 38,569,229 | <p>I am trying to use Microsoft.Office.Interop.Excel from a Python script:</p>
<pre><code>import msvcrt
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel
excel = Excel.ApplicationClass()
excel.Visible = True # makes the Excel application visible to the user - will use this as True for debug
excel.DisplayAlerts = False # turns off Excel alerts since I don't have a handler
print ("Excel: " + str(type(excel)))
print ("Workbooks: " + str(type(excel.Workbooks)))
print ("Workbooks count: " + str(excel.Workbooks.Count))
#wb = excel.Workbooks.Open(r'C:\Projects\Experiments\Python\ExcelInterop\Test.xlsx')
print ("Press any key")
msvcrt.getch()
</code></pre>
<p>Here is the output:</p>
<pre><code>C:\Projects\Experiments\Python\ExcelInterop>exceltest.py
Excel: <class 'Microsoft.Office.Interop.Excel.ApplicationClass'>
Workbooks: <class 'System.__ComObject'>
Traceback (most recent call last):
File "C:\Projects\Experiments\Python\ExcelInterop\exceltest.py", line 12, in <module>
print ("Workbooks count: " + str(excel.Workbooks.Count))
AttributeError: '__ComObject' object has no attribute 'Count'
</code></pre>
<ul>
<li>I am running in an admin cmd prompt on Windows 10</li>
<li>I have tried python 2.7 and 3.5 (using py -3 exceltest.py).</li>
<li>Microsoft.Office.Interop.Excel is version 15.0.4420.1017 (Office 2013)</li>
<li>I created a similar .NET console app, which worked fine.</li>
<li>I used ILDASM to check references from Microsoft.Office.Interop.Excel, and then gacutil -l to double-check that all referenced assemblies are in the GAC.</li>
<li>Just in case, I copied office.dll, stdole.dll and Microsoft.Vbe.Interop.dll into the folder where the Python script is running. These are the assemblies added to the .NET console application build folder if I don't embed the interop types for Microsoft.Office.Interop.Excel.</li>
<li>I have .NET for Python installed for 2.7 and 3.5 (from <a href="https://pypi.python.org/pypi/pythonnet" rel="nofollow">https://pypi.python.org/pypi/pythonnet</a>)</li>
</ul>
<p>Thanks for reading.</p>
| 1 | 2016-07-25T13:34:49Z | 39,046,725 | <p>You can only get to COM objects from pythonnet using reflection currently:</p>
<pre><code>clr.AddReference("System.Reflection")
from System.Reflection import BindingFlags
excel.Workbooks.GetType().InvokeMember("Count",
BindingFlags.GetProperty |
BindingFlags.InvokeMethod,
None, excel.Workbooks, None)
</code></pre>
<p>Here is a wrapper function:</p>
<p><a href="https://gist.github.com/denfromufa/ec559b5af41060c5ac318f7f59d8b415#file-excel_interop_vsto-ipynb" rel="nofollow">https://gist.github.com/denfromufa/ec559b5af41060c5ac318f7f59d8b415#file-excel_interop_vsto-ipynb</a></p>
| 0 | 2016-08-19T19:50:53Z | [
"python",
".net",
"excel",
"interop",
"python.net"
] |
List of sub-strings search returns multiple conditions at once | 38,569,291 | <p>I have a large list of sub-strings that I want to search through and find if two particular sub-strings can be found in a row. The logic is intended to look for the first sequence, then if it is found, look at the second sub-string and return all the matches (based off the first 15 characters of the 16 character sequence). If the first sequence can not be found, it just looks for the second sequence only, and finally, if that can not be found, defaults to zero. The matches are then appended to a list, which is processed further. The current code used is as follows:</p>
<pre><code>dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
joined_A_Search_1 = ''.join(map(str,A_vein_1))
print 'search 1', joined_A_Search_1
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
joined_A_Search_2 = ''.join(map(str,A_vein_2))
match_A = [] #empty list to append closest match to
#Match search algorithm
for i,text in enumerate(data):
if joined_A_Search_1 == text:
if joined_A_Search_2 == data[i+1][:-1]:
print 'logic stream 1'
match_A.append(data[i+1][-1])
if joined_A_Search_1 != text:
if joined_A_Search_2 == text[:-1]:
print 'logic stream 2'
#print 'match', text[:-1]
match_A.append(text[-1])
print ' A matches', match_A
try:
filter_A = max(set(match_A), key=match_A.count)
except:
filter_A = 0
print 'no match A'
filter_A = int(filter_A)
print '0utput', filter_A
</code></pre>
<p>The issue is that I get a return of both logic stream 1 and logic stream 2, when I actually want it to be a strict one or the other, in this case only logic stream 1. An example of the output looks like this:</p>
<pre><code>search 1 0100101010001000
search 2 100101010001000
logic stream 1
logic stream 2
logic stream 1
logic stream 2
logic stream 2
</code></pre>
<p>(Note: The list has been shortened, and the data inputs have been substituted in directly, as well as the print outs for the purposes of this post and error tracking) </p>
| 0 | 2016-07-25T13:37:46Z | 38,569,695 | <p>Your code confuses me. But I think I understand your issue:</p>
<pre><code>#!/usr/env/env python
dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
av1_str = "".join(map(str,A_vein_1))
av2_str = "".join(map(str,A_vein_2))
for i, d in enumerate(dataA):
if av1_str in d:
print av1_str, 'found in line', i
elif av2_str in d:
print av2_str, 'found in line', i
</code></pre>
<p>This gives me :</p>
<pre><code>jcg@jcg:~/code/python/stack_overflow$ python find_str.py
0100101010001000 found in line 0
100101010001000 found in line 0
100101010001000 found in line 1
</code></pre>
<p>After edit to elif:</p>
<pre><code>jcg@jcg:~/code/python/stack_overflow$ python find_str.py
0100101010001000 found in line 0
100101010001000 found in line 1
</code></pre>
| 0 | 2016-07-25T13:55:38Z | [
"python",
"list",
"if-statement",
"for-loop",
"substring"
] |
List of sub-strings search returns multiple conditions at once | 38,569,291 | <p>I have a large list of sub-strings that I want to search through and find if two particular sub-strings can be found in a row. The logic is intended to look for the first sequence, then if it is found, look at the second sub-string and return all the matches (based off the first 15 characters of the 16 character sequence). If the first sequence can not be found, it just looks for the second sequence only, and finally, if that can not be found, defaults to zero. The matches are then appended to a list, which is processed further. The current code used is as follows:</p>
<pre><code>dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
joined_A_Search_1 = ''.join(map(str,A_vein_1))
print 'search 1', joined_A_Search_1
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
joined_A_Search_2 = ''.join(map(str,A_vein_2))
match_A = [] #empty list to append closest match to
#Match search algorithm
for i,text in enumerate(data):
if joined_A_Search_1 == text:
if joined_A_Search_2 == data[i+1][:-1]:
print 'logic stream 1'
match_A.append(data[i+1][-1])
if joined_A_Search_1 != text:
if joined_A_Search_2 == text[:-1]:
print 'logic stream 2'
#print 'match', text[:-1]
match_A.append(text[-1])
print ' A matches', match_A
try:
filter_A = max(set(match_A), key=match_A.count)
except:
filter_A = 0
print 'no match A'
filter_A = int(filter_A)
print '0utput', filter_A
</code></pre>
<p>The issue is that I get a return of both logic stream 1 and logic stream 2, when I actually want it to be a strict one or the other, in this case only logic stream 1. An example of the output looks like this:</p>
<pre><code>search 1 0100101010001000
search 2 100101010001000
logic stream 1
logic stream 2
logic stream 1
logic stream 2
logic stream 2
</code></pre>
<p>(Note: The list has been shortened, and the data inputs have been substituted in directly, as well as the print outs for the purposes of this post and error tracking) </p>
| 0 | 2016-07-25T13:37:46Z | 38,569,934 | <p>Input :</p>
<pre><code>dataA = ['0100101010001000',
'1001010100010001',
'0010101000100010',
'0101010001000110',
'1010100010001110',
'0101000100011100',
'1010001000111010',
'0100010001110100',
'1000100011101000',
'0001000111010000']
A_vein_1 = [0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
A_vein_2 = [1,0,0,1,0,1,0,1,0,0,0,1,0,0,0]
</code></pre>
<p>code :</p>
<pre><code>av1_str = "".join(map(str,A_vein_1))
av2_str = "".join(map(str,A_vein_2))
y=[av1_str,av2_str]
print [(y,dataA.index(x)) for x in dataA for y in dataB if y in x]
</code></pre>
<p>Output :</p>
<pre><code>[('0100101010001000', 0), ('100101010001000', 0), ('100101010001000', 1)]
</code></pre>
| 0 | 2016-07-25T14:06:39Z | [
"python",
"list",
"if-statement",
"for-loop",
"substring"
] |
Read Value from a list in another list | 38,569,350 | <p>i'd like to know how to read out values from a list like that:</p>
<pre><code>fragen = [["Frage?",{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}]]
</code></pre>
<p>i'm a complete beginner in python, any help would be kind.</p>
<p>Originally, it looked like that:</p>
<pre><code>fragen = []
fragen.append(["Frage?",
{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}])
</code></pre>
<p>and i tried to call the Value like that</p>
<pre><code>fragen[0][1][0]
</code></pre>
<p>It doesn't work like that, it gives me an</p>
<pre><code>KeyError: 0
</code></pre>
<p>Thank you for the help, have a nice day.</p>
| 0 | 2016-07-25T13:40:36Z | 38,569,418 | <p><code>fragen</code> is a list of lists. The inner list happen to contain a string and a dictionary.</p>
<p><code>fragen[0]</code> returns the inner list, ie <code>["Frage?",{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}]</code>.</p>
<p><code>fragen[0][1]</code> returns the dictionary, ie <code>{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}</code>.</p>
<p><code>fragen[0][1]['ValueOne']</code> will return the value associated with the key <code>'ValueOne'</code> from that dictionary, ie <code>1</code>.</p>
<p>You can access the different keys in the dictionary in the same manner.</p>
| 4 | 2016-07-25T13:43:26Z | [
"python",
"list",
"multidimensional-array",
"value"
] |
Read Value from a list in another list | 38,569,350 | <p>i'd like to know how to read out values from a list like that:</p>
<pre><code>fragen = [["Frage?",{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}]]
</code></pre>
<p>i'm a complete beginner in python, any help would be kind.</p>
<p>Originally, it looked like that:</p>
<pre><code>fragen = []
fragen.append(["Frage?",
{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}])
</code></pre>
<p>and i tried to call the Value like that</p>
<pre><code>fragen[0][1][0]
</code></pre>
<p>It doesn't work like that, it gives me an</p>
<pre><code>KeyError: 0
</code></pre>
<p>Thank you for the help, have a nice day.</p>
| 0 | 2016-07-25T13:40:36Z | 38,569,447 | <p>The list contains string and <a href="http://learnpythonthehardway.org/book/ex39.html" rel="nofollow">dictionary</a> data types.</p>
<p>You want to try using</p>
<p><code>fragen[0][1]['ValueOne']</code> to print 1. </p>
<p>This is how you access dictionaries in Python.</p>
| 0 | 2016-07-25T13:44:35Z | [
"python",
"list",
"multidimensional-array",
"value"
] |
Read Value from a list in another list | 38,569,350 | <p>i'd like to know how to read out values from a list like that:</p>
<pre><code>fragen = [["Frage?",{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}]]
</code></pre>
<p>i'm a complete beginner in python, any help would be kind.</p>
<p>Originally, it looked like that:</p>
<pre><code>fragen = []
fragen.append(["Frage?",
{"ValueOne": 1, "ValueTwo": 0, "ValueThree": 0, "ValueFour": 5}])
</code></pre>
<p>and i tried to call the Value like that</p>
<pre><code>fragen[0][1][0]
</code></pre>
<p>It doesn't work like that, it gives me an</p>
<pre><code>KeyError: 0
</code></pre>
<p>Thank you for the help, have a nice day.</p>
| 0 | 2016-07-25T13:40:36Z | 38,592,467 | <p>@DeepSpace has already answered your question . but for future reference and easier access for multidimensional arrays</p>
<p>you could use </p>
<pre><code>import numpy
fragen=numpy.ndarray((x,y,z,..))
</code></pre>
<p>x,y,z are dimensions of your n dimensional array</p>
| 0 | 2016-07-26T14:21:24Z | [
"python",
"list",
"multidimensional-array",
"value"
] |
Using Crontab in a Python Script | 38,569,365 | <p>I am trying to use the contents of a crontab inside a python script. I want to do everything using python. In the end I hope to take the contents of the crontab, convert it to a temporary textfile, read in the lines of the text file and manipulate it.</p>
<p>Is there any way i can use the contents of the crontab file and manipulate it as if it were a text file???</p>
<p>I've looked into the subprocess module but am not too sure if this is the right solution....</p>
<p><strong>NOTE:</strong> I am not trying to edit the crontab in any way, I am just trying to read it in and manipulate it within my python code. In the end, the crontab will remain the same. I just need the information contained inside the crontab to mess with.</p>
| 0 | 2016-07-25T13:41:09Z | 38,569,423 | <p>If you were to try <code>crontab -h</code>, which is usually the help option, you'll get this:</p>
<pre><code>$ crontab -h
crontab: invalid option -- 'h'
crontab: usage error: unrecognized option
Usage:
crontab [options] file
crontab [options]
crontab -n [hostname]
Options:
-u <user> define user
-e edit user's crontab
-l list user's crontab
-r delete user's crontab
-i prompt before deleting
-n <host> set host in cluster to run users' crontabs
-c get host in cluster to run users' crontabs
-x <mask> enable debugging
Default operation is replace, per 1003.2
</code></pre>
<p>The line to note is the one that says <code>-l list user's crontab</code>. If you try that, you see that it lists out the contents of one's crontab file. Based on that, you can run the following:</p>
<pre><code>import subprocess
crontab = subprocess.check_output(['crontab', '-l'])
</code></pre>
<p>And <code>crontab</code> will contain the contents of one's crontab. In Python3 it will return binary data so you'll need <code>crontab = crontab.decode()</code>.</p>
| 2 | 2016-07-25T13:43:47Z | [
"python",
"subprocess",
"crontab"
] |
Type hint for a file or file-like object? | 38,569,401 | <p>Is there any correct type hint to use for a file or file-like object in Python? For example, how would I type-hint the return value of this function?</p>
<pre><code>def foo():
return open('bar')
</code></pre>
| 2 | 2016-07-25T13:42:50Z | 38,569,536 | <p>Use either the <code>typing.TextIO</code> or <code>typing.BinaryIO</code> types, for files opened in text mode or binary mode respectively.</p>
<p>From <a href="https://docs.python.org/3/library/typing.html#typing.io" rel="nofollow">the docs</a>:</p>
<blockquote>
<h3><em>class</em> <code>typing.io</code></h3>
<p>Wrapper namespace for I/O stream types.</p>
<p>This defines the generic type <code>IO[AnyStr]</code> and aliases <code>TextIO</code> and <code>BinaryIO</code> for respectively <code>IO[str]</code> and <code>IO[bytes]</code>. These representing the types of I/O streams such as returned by <code>open()</code>.</p>
</blockquote>
| 4 | 2016-07-25T13:48:47Z | [
"python"
] |
Named string format arguments in Python | 38,569,579 | <p>I am using Python 2.x, and trying to understand the logic of string formatting using named arguments. I understand:</p>
<p><code>"{} and {}".format(10, 20)</code> prints <code>'10 and 20'</code>.</p>
<p>In like manner <code>'{name} and {state}'.format(name='X', state='Y')</code> prints <code>X and Y</code></p>
<p>But why this isn't working?</p>
<pre><code>my_string = "Hi! My name is {name}. I live in {state}"
my_string.format(name='Xi', state='Xo')
print(my_string)
</code></pre>
<p>It prints <code>"Hi! My name is {name}. I live in {state}"</code></p>
| 4 | 2016-07-25T13:50:42Z | 38,569,648 | <p><a href="https://docs.python.org/2/library/stdtypes.html#str.format"><code>format</code></a> doesn't alter the string you call it on; it returns a new string. If you do</p>
<pre><code>my_string = "Hi! My name is {name}. I live in {state}"
new_string = my_string.format(name='Xi', state='Xo')
print(new_string)
</code></pre>
<p>then you should see the expected result.</p>
| 6 | 2016-07-25T13:53:34Z | [
"python",
"python-2.7"
] |
How do I print out just the values of keys in a dictionary? | 38,569,603 | <p>I'm trying to create a function that prints out just the value of the key given in the parameter. But it isn't quite doing what I want it to do. Please have a look at my code and see where I'm wrong? Thanks</p>
<pre><code>list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
for marks in list.items():
print(marks)
get_marks("David")
</code></pre>
| -2 | 2016-07-25T13:51:42Z | 38,569,638 | <p>You are trying this:</p>
<pre><code>def get_marks(student_name):
print(list.get(student_name))
</code></pre>
| 0 | 2016-07-25T13:53:14Z | [
"python"
] |
How do I print out just the values of keys in a dictionary? | 38,569,603 | <p>I'm trying to create a function that prints out just the value of the key given in the parameter. But it isn't quite doing what I want it to do. Please have a look at my code and see where I'm wrong? Thanks</p>
<pre><code>list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
for marks in list.items():
print(marks)
get_marks("David")
</code></pre>
| -2 | 2016-07-25T13:51:42Z | 38,569,641 | <p>You can access the value at a key using <code>my_dict[student_name]</code> but using the <code>get</code> method of the dictionary is much safer as it returns <code>None</code> when the key is not found:</p>
<pre><code>def get_marks(student_name):
print my_dict.get(student_name)
</code></pre>
<p>I have renamed your dictionary from <code>list</code> to <code>my_dict</code> to avoid shadowing the builtin list class.</p>
| 0 | 2016-07-25T13:53:20Z | [
"python"
] |
How do I print out just the values of keys in a dictionary? | 38,569,603 | <p>I'm trying to create a function that prints out just the value of the key given in the parameter. But it isn't quite doing what I want it to do. Please have a look at my code and see where I'm wrong? Thanks</p>
<pre><code>list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
for marks in list.items():
print(marks)
get_marks("David")
</code></pre>
| -2 | 2016-07-25T13:51:42Z | 38,569,696 | <pre><code>list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
print list[student_name]
get_marks("David")
</code></pre>
| 0 | 2016-07-25T13:55:40Z | [
"python"
] |
How do I print out just the values of keys in a dictionary? | 38,569,603 | <p>I'm trying to create a function that prints out just the value of the key given in the parameter. But it isn't quite doing what I want it to do. Please have a look at my code and see where I'm wrong? Thanks</p>
<pre><code>list = {
"David": 42,
"John": 11,
"Jack": 278
}
def get_marks(student_name):
for marks in list.items():
print(marks)
get_marks("David")
</code></pre>
| -2 | 2016-07-25T13:51:42Z | 38,569,817 | <p>You can either use the <a href="http://www.tutorialspoint.com/python/dictionary_get.htm" rel="nofollow">get()</a> method of the dictionary like so:</p>
<pre><code>def get_marks(student_name):
return list.get(student_name)
</code></pre>
<p>or you can just use <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">basic dictionary access (Section 5.5)</a> and handle missing keys on your own:</p>
<pre><code>def get_marks(student_name):
if student_name in list:
return list[student_name]
else:
#Key not in dict, do something
</code></pre>
| 0 | 2016-07-25T14:01:03Z | [
"python"
] |
Can't connect MongoDb on AWS EC2 using python | 38,569,626 | <p>I have installed Mongodb 3.0 using this tutorial -</p>
<p><a href="https://docs.mongodb.com/v3.0/tutorial/install-mongodb-on-amazon/" rel="nofollow">https://docs.mongodb.com/v3.0/tutorial/install-mongodb-on-amazon/</a></p>
<p>It has installed fine. I have also given permissions to 'ec2-user' to all the data and log folders ie var/lib/mongo and var/log/mongodb but and have set <code>conf</code> file as well.</p>
<p>Now thing is that mongodb server always fails to start with command </p>
<pre><code>sudo service mongod start
</code></pre>
<p>it just say <code>failed</code>, nothing else.</p>
<p>While if I run command -</p>
<pre><code>mongod --dbpath var/lib/mongo
</code></pre>
<p>it starts the mongodb server correctly (though I have mentioned same dbpath in <code>.conf</code> file as well)</p>
<p>What is it I am doing wrong here?</p>
| 1 | 2016-07-25T13:52:59Z | 38,569,890 | <p>When you run <code>sudo mongod</code> it does not load a config file at all, it literally starts with the compiled in defaults - port <a href="https://docs.mongodb.org/manual/reference/configuration-options/#net.port" rel="nofollow">27017</a>, <a href="https://docs.mongodb.org/manual/reference/configuration-options/#storage.dbPath" rel="nofollow">database path</a> of /data/db etc. - that is why you got the error about not being able to find that folder. The "Ubuntu default" is only used when you point it at the config file (if you start using the service command, this is done for you behind the scenes).</p>
<p>Next you ran it like this:</p>
<pre><code>sudo mongod -f /etc/mongodb.conf
</code></pre>
<p>If there weren't problems before, then there will be now - you have run the process, with your normal config (pointing at your usual dbpath and log) as the root user. That means that there are going to now be a number of files in that normal MongoDB folder with the user:group of <code>root:root</code>. </p>
<p>This will cause errors when you try to start it as a normal service again, because the mongodb user (which the service will attempt to run as) will not have permission to access those <code>root:root</code> files, and most notably, it will probably not be able to write to the log file to give you any information. </p>
<p>Therefore, to run it as a normal service, we need to fix those permissions. First, make sure MongoDB is not currently running as root, then:</p>
<pre><code>cd /var/log/mongodb
sudo chown -R mongodb:mongodb .
cd /var/lib/mongodb
sudo chown -R mongodb:mongodb .
</code></pre>
<p>That should fix it up (assuming the user:group is <code>mongodb:mongodb</code>), though it's probably best to verify with an <code>ls -al</code> or similar to be sure. Once this is done you should be able to get the service to start successfully again.</p>
<p>If youâre starting mongod as a service using:</p>
<pre><code>sudo service mongod start
</code></pre>
<p>Make sure the directories defined for logpath, dbpath, and pidfilepath in your mongod.conf exist and are owned by mongod:mongod.</p>
| 1 | 2016-07-25T14:04:16Z | [
"python",
"mongodb",
"amazon-web-services",
"amazon-ec2"
] |
How to read in sequence of images as 3d tensor? | 38,569,663 | <p>As an input to a CNN I am working on, I want to use a sequence of images (with 3D convolution in the conv layers).</p>
<p>However, I already fail in reading in the images as a 3D tensor that I can use for the computation.</p>
<p>Here is my primitive attempt:</p>
<pre><code>def get_sequence_as_tensor(folder):
images = [folder + "/depth-%i.png" for i in range(15)]
tensor = tf.zeros(shape=(480, 640, 15), dtype=tf.float32)
for i, image in enumerate(images):
img = tf.image.decode_png(image)
img_float = tf.cast(img, tf.float32)
img_float = tf.reshape(img_float, (480, 640))
tensor[:, :, i] = img_float
return tensor
</code></pre>
<p>Which already fails because I cannot use index notation with tensors as I would expect from numpy arrays.</p>
<pre><code>TypeError: 'Tensor' object does not support item assignment
</code></pre>
<p>What would be a proper way of reading in a sequence of images as a 3d tensor?</p>
| 0 | 2016-07-25T13:54:20Z | 38,573,206 | <p>I would recommend combining the images into a numpy array outside of tensorflow and then passing them in to a placeholder.</p>
<p>Something like this should work.</p>
<pre><code>filename = tf.placeholder("string")
png_string = tf.read_file(filename)
img = tf.image.decode_png(png_string)
img_float = tf.cast(img, tf.float32)
img_float = tf.reshape(img_float, (480, 640))
images = tf.placeholder("float", (480, 640, 15))
output = some_operation(images)
sess = tf.Session()
images_array = np.zeros((480, 640, 15), np.float32)
for i, image in enumerate(filenames):
images_array[:,:,i] = sess.run(img_float, feed_dict{filename: image})
out = sess.run(output, feed_dict={images: images_array})
</code></pre>
<p>I hope this helps.</p>
| 0 | 2016-07-25T16:38:11Z | [
"python",
"tensorflow"
] |
django-debug-toolbar: 'Template' object has no attribute 'engine' | 38,569,760 | <p>I've just tried running an existing Django project on a new computer, and I'm having trouble with django-debug-toolbar. It seems to be something to do with Jinja2. Here's the stack trace:</p>
<pre><code>Traceback:
File "/path/to/myrepo/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
223. response = middleware_method(request, response)
File "/path/to/myrepo/env/local/lib/python2.7/site-packages/debug_toolbar/middleware.py" in process_response
120. panel.generate_stats(request, response)
File "/path/to/myrepo/env/local/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in generate_stats
175. context_processors = self.templates[0]['context_processors']
Exception Type: AttributeError at /first/page/
Exception Value: 'Template' object has no attribute 'engine'
</code></pre>
<p>I'm using django-jinja2 to integrate Jinja2 into my project, and this worked okay before but it now seems to be expecting this <code>template</code> variable to be a normal Django template. In my <code>TEMPLATES</code> setting I have both Jinja2 and DjangoTemplates set up, with Jinja2 using a specific extension ('tmpl') to make sure only those templates are used by Jinja2 and everything else can go through the DjangoTemplates backend.</p>
<p>Has anyone seen this error before when using django debug toolbar with Jinja2? I can post more settings if needed.</p>
<p>EDIT: As requested, here's my TEMPLATES settings:</p>
<pre><code>TEMPLATES = [
{
#'BACKEND': 'django.template.backends.jinja2.Jinja2',
'BACKEND': 'django_jinja.backend.Jinja2',
#'NAME': 'jinja2',
'DIRS': [
os.path.join(DEPLOY_PATH, 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'match_extension': '.tmpl',
#'environment': 'jinja2.Environment',
'extensions': [
'jinja2.ext.with_',
'jinja2.ext.i18n',
'django_jinja.builtins.extensions.UrlsExtension',
'django_jinja.builtins.extensions.CsrfExtension',
'pipeline.templatetags.ext.PipelineExtension',
],
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
]
},
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(DEPLOY_PATH, 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
]
}
}
]
</code></pre>
<p><strong>Update</strong> - I've "fixed" the issue by making a small code change in the debug toolbar source: changing line 175 in <code>debug_toolbar/panels/templates/panel.py</code> from:</p>
<pre><code>template_dirs = self.templates[0]['template'].engine.dirs
</code></pre>
<p>to:</p>
<pre><code>if hasattr(self.templates[0]['template'], 'engine'):
template_dirs = self.templates[0]['template'].engine.dirs
elif hasattr(self.templates[0]['template'], 'backend'):
template_dirs = self.templates[0]['template'].backend.dirs
else:
raise RuntimeError("Couldn't find engine or backend for a template: {}",format(self.templates[0]['template']))
</code></pre>
<p>I haven't looked into why this works (for some people this combination of debug toolbar 1.5 and django-jinja 2.2.0 works fine) but I noticed that Jinja2 templates have the <code>backend</code> attribute and the Django templates have the <code>engine</code> attribute, and both appear to be used for the same thing.</p>
| 1 | 2016-07-25T13:58:57Z | 39,036,820 | <p>I get this too, you can hack it fixed based on your suggestion without hacking core by supplying your own panel class:</p>
<p><strong>debug.py</strong></p>
<pre><code>from debug_toolbar.panels.templates import TemplatesPanel as BaseTemplatesPanel
class TemplatesPanel(BaseTemplatesPanel):
def generate_stats(self, *args):
template = self.templates[0]['template']
if not hasattr(template, 'engine') and hasattr(template, 'backend'):
template.engine = template.backend
return super().generate_stats(*args)
</code></pre>
<p><strong>settings.py</strong></p>
<pre><code>DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'myapp.debug.TemplatesPanel', # original broken by django-jinja, remove this whole block later
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]
</code></pre>
| 1 | 2016-08-19T10:33:01Z | [
"python",
"django",
"templates",
"django-debug-toolbar"
] |
Handling Timeout Error(python) | 38,569,771 | <pre><code>import multiprocessing.pool
import functools
import time
import sys
def timeout(max_timeout):
def timeout_decorator(item):
@functools.wraps(item)
def func_wrapper(*args, **kwargs):
pool = multiprocessing.pool.ThreadPool(processes=1)
async_result = pool.apply_async(item, args, kwargs)
return async_result.get(max_timeout)
return func_wrapper
return timeout_decorator
</code></pre>
<p>I got this code from SE. This raises the timeout error from system level.
How could i handle this error and do something else when error pops up</p>
<p>Please Note Am a newbie in python.
Thanks in advance</p>
| 0 | 2016-07-25T13:59:23Z | 38,569,988 | <p>You can wrap an error, using a try/except :</p>
<pre><code>try:
do_something_that_can_raise_error_X()
except X:
do_something_when_error_X_is_raised()
</code></pre>
| 0 | 2016-07-25T14:08:42Z | [
"python"
] |
Handling Timeout Error(python) | 38,569,771 | <pre><code>import multiprocessing.pool
import functools
import time
import sys
def timeout(max_timeout):
def timeout_decorator(item):
@functools.wraps(item)
def func_wrapper(*args, **kwargs):
pool = multiprocessing.pool.ThreadPool(processes=1)
async_result = pool.apply_async(item, args, kwargs)
return async_result.get(max_timeout)
return func_wrapper
return timeout_decorator
</code></pre>
<p>I got this code from SE. This raises the timeout error from system level.
How could i handle this error and do something else when error pops up</p>
<p>Please Note Am a newbie in python.
Thanks in advance</p>
| 0 | 2016-07-25T13:59:23Z | 38,570,674 | <p>You need to wrap the code that might raise this exception in "try" and then except the exception that you expect.</p>
<pre><code>from multiprocessing import TimeoutError
try:
# actions that raise TimeoutError
except TimeoutError:
# handle TimeoutError
else:
# (optional) actions for when there is no TimeoutError
finally:
# (optional) actions to perform in any case
</code></pre>
<p>See this <a href="https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow">example in the multiprocessing docs</a>.</p>
<p>Note, that using except without listing precise exception types is allowed syntactically but is not a good idea.</p>
<p>Also, you might want to learn how to handle Exceptions in python, see any python tutorial.</p>
| 0 | 2016-07-25T14:37:46Z | [
"python"
] |
executing OS commands from python using modules | 38,569,772 | <p>I want to run a python script that can execute OS (linux) commands , I got few modules that helps me in doing that like os, subprocess . In OS module am not able to redirect the output to a variable . In subprocess.popen am not able to use variable in the arguments. Need someone help in finding the alternative . </p>
<p>Am trying to run some OS commands from python script . for example df -h output. It works fine with by using some modules like os or subprocess .But am not able to store those output to any variable . </p>
<p>Here am not able to save this output to a variable . How do I save this to a variable. </p>
<p>i saw multiple other options like subprocess.Popen but am not getting proper output.</p>
<p>Below program i used subprocess module but here I have another issue , as the command is big am not able to use variables in subprocess.Popen. </p>
| 0 | 2016-07-25T13:59:24Z | 38,569,963 | <p>You can use the <code>subprocess</code> method <code>check_output</code></p>
<pre><code>import subprocess
output = subprocess.check_output("your command", shell=True)
</code></pre>
<p>see previously answered SO question here for more info: <a href="http://stackoverflow.com/a/8659333/3264217">http://stackoverflow.com/a/8659333/3264217</a></p>
<p>Also for more info on check_output, see python docs here:
<a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="nofollow">https://docs.python.org/3/library/subprocess.html#subprocess.check_output</a></p>
| 0 | 2016-07-25T14:07:42Z | [
"python",
"scripting"
] |
executing OS commands from python using modules | 38,569,772 | <p>I want to run a python script that can execute OS (linux) commands , I got few modules that helps me in doing that like os, subprocess . In OS module am not able to redirect the output to a variable . In subprocess.popen am not able to use variable in the arguments. Need someone help in finding the alternative . </p>
<p>Am trying to run some OS commands from python script . for example df -h output. It works fine with by using some modules like os or subprocess .But am not able to store those output to any variable . </p>
<p>Here am not able to save this output to a variable . How do I save this to a variable. </p>
<p>i saw multiple other options like subprocess.Popen but am not getting proper output.</p>
<p>Below program i used subprocess module but here I have another issue , as the command is big am not able to use variables in subprocess.Popen. </p>
| 0 | 2016-07-25T13:59:24Z | 38,570,460 | <p>Use either subprocess or pexpect depending on what is your exact use case.</p>
<p>subprocess can do what os.system does and much more. If you need to start some command, wait for it to exit and then get the output, subprocess can do it:</p>
<pre><code>import subprocess
res = subprocess.check_output('ls -l')
</code></pre>
<p>But if you need to interact with some command line utility, that is repeatedly read/write, then have a look at pexpect module. It is written for Unix systems but if you ever want to go cross-platform, there is a port for Windows called winpexpect.</p>
<p>spawn's attribute 'before' is probably what you need:</p>
<pre><code>p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before
</code></pre>
<p>(see the <a href="http://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class" rel="nofollow">docs</a>)</p>
| 0 | 2016-07-25T14:28:38Z | [
"python",
"scripting"
] |
How to run maven command in a python script in Windows | 38,569,785 | <p>How do I write a maven command in python? I saw this example online, but it doesn't seem to be working in Windows.</p>
<pre><code>def local2(command, print_command=False):
from subprocess import Popen, PIPE
p = Popen(command, stdout=PIPE, stderr=PIPE)
if print_command: print " ".join(command)
output, errput = p.communicate()
return p.returncode, output, errput
def uploadQAJavaToNexus():
url = "example"
groupId = "example"
artifactId = "example"
repositoryId = "example"
# filePath =
version = "version"
status, stdout, stderr = local2([
"mvn",
"deploy:deploy-file",
"-Durl=" +url,
"-DrepositoryId=" +repositoryId,
"-Dversion=" + version,
"-Dfile=" + "path"
"-DartifactId=" + artifactId,
"-Dpackaging=" + "jar",
"-DgroupId" + groupId,
])
return status, stdout, stderr
</code></pre>
<p>UPDATE: This is the error I'm getting given below:</p>
<pre><code>Traceback (most recent call last):
File "C:\PythonProject\src\Get.py", line 355, in <module>
uploadQAJavaToNexus()
File "C:\Get.py", line 250, in uploadQAJavaToNexus
"-DgroupId" + groupId,
File "C:\Get.py", line 227, in local2
p = Popen(command, stdout=PIPE, stderr=PIPE)
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code></pre>
| -1 | 2016-07-25T13:59:55Z | 38,569,836 | <p>I prefer to use fabric (<a href="http://www.fabfile.org/" rel="nofollow">http://www.fabfile.org/</a>):</p>
<pre><code>from fabric import local
def maven_start():
local('<cmd>')
$ fab maven_start
</code></pre>
| 0 | 2016-07-25T14:02:01Z | [
"python",
"windows",
"maven"
] |
Initial node's ids when creating graph from edge list | 38,569,831 | <p>I wonder, where does the function <a href="http://igraph.org/python/doc/igraph.GraphBase-class.html#Read_Edgelist">Read_Edgelist</a> store the original id's from the the edge list? or under which attribute name? </p>
<p>Assume that I am reading an edge list like:</p>
<pre><code>1 2
2 1
1 3
</code></pre>
<p>where the numbers <code>1,2,3</code> are the ids (or names) of the nodes. Where does the iGraph (python version) stores these ids?
I tried retrieving these Ids from the attribute <code>name</code> or <code>id</code> but it did not work, as those two attributes, seemingly, must be explicitly defined.</p>
| 6 | 2016-07-25T14:01:46Z | 39,524,908 | <p><a href="http://igraph.org/python/doc/igraph.GraphBase-class.html#Read_Edgelist" rel="nofollow"><code>Read_Edgelist</code></a> assumes the node ids are the consecutive integers from 0 to m, where m is the maximum integer in the edge list. So there is "no need to store node ids."</p>
<p>For example, if your edgelist.txt is <code>1 3</code>, this code</p>
<pre><code>import igraph as ig
g = ig.Graph.Read_Edgelist("edgelist.txt")
print g.get_adjacency()
</code></pre>
<p>creates a graph with four nodes (0, 1, 2, 3) and prints</p>
<pre><code>[[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 0, 0]
[0, 0, 0, 0]]
</code></pre>
<p>See this <a href="http://stackoverflow.com/q/29268262/1628638">answer</a> if you do not want "intermediate" nodes to be created.</p>
<p>While the following is unnecessary for a graph with consecutive node ids starting with 0, one could access the node ids using <a href="http://igraph.org/python/doc/igraph.VertexSeq-class.html" rel="nofollow"><code>VertexSeq</code></a> and <a href="http://igraph.org/python/doc/igraph.Vertex-class.html" rel="nofollow"><code>Vertex</code></a>:</p>
<pre><code>for v in g.vs:
print v.index # node id
</code></pre>
| 1 | 2016-09-16T06:19:57Z | [
"python",
"igraph"
] |
Pandas: replace empty cell to 0 when write to file | 38,569,851 | <p>I have df and there are empty cells. I want to write it to excel and need to print there <code>0</code> instead empty. I try <code>result.fillna(0)</code> and <code>result.replace(r'\s+', np.nan, regex=True)</code> but it doesn't help.</p>
| 0 | 2016-07-25T14:02:43Z | 38,571,108 | <p>You are creating a copy of the dataframe but the original one is not keeping the changes, you need to specify "inplace=True" if you want the dataframe to persist the changes</p>
<pre><code>result.fillna(0, inplace=True)
</code></pre>
| 0 | 2016-07-25T14:56:32Z | [
"python",
"pandas"
] |
Python 3.5 tkinter: resizing widgets to window | 38,569,862 | <p>I am reading, reading and reading but still unable to find the appropriate answer to my issue. I plan to create a 'Masterwindow' in which I implement several frames (currently a Navigation Panel to the left, a 'RootFrame', which shows up, when no process is running, a Statusbar at the bottom, which is for alerts and processings and a main frame. Running the Code below, everything just works fine, but the Frames do not adjust to the resize of the window.</p>
<p>Now, I know, I need to do some sticking in main- and subclasses and set grid_column- and rowconfigure to a weight of >0 but still nothing happens.</p>
<p>I cannot see the reason why. What am I missing? Do I need to put everything in another masterframe?? which I stick to the masterwindow? that can't be right since I am inheriting Frames everywhere...</p>
<p>Thanks for your effort and Input. rgds</p>
<p>p.s: oh by the way: can any1 tell me how to iterate through the rows in a grid method so that I can just simply say 'grid the widget in the next row' (relative) and dont have to use absolute integers?</p>
<pre><code> # -*- coding: UTF-8 -*-
import tkinter.ttk
from tkinter import *
class MainApplication(tkinter.Frame):
@classmethod
def main(cls):
root = tkinter.Tk()
app = cls(root)
app.master.title('Sample')
root.resizable(True, True)
root.mainloop()
def __init__(self, parent=None, *args, **kwargs):
tkinter.Frame.__init__(self, parent, *args, **kwargs)
self.grid(sticky=N+E+S+W)
# Var-Declaration
self.h = 600
self.w = 1200
self.widget_fr_opts = dict(relief='groove', borderwidth=1, bg='#EFEFFB')
# Widget-Creation
self.rootframe = RootFrame(self)
self._visible_ = self.rootframe # internal updater what frame is visible - starting with rootframe on init
self.statusbar = Statusbar(self)
self.navbar = Navbar(self)
self.main_db = MainDB(self)
# Widget-Design
# Widget-Arrangement
self.grid_rowconfigure(0, minsize=self.h * 0.95)
self.grid_rowconfigure(1, minsize=self.h * 0.05)
self.grid_columnconfigure(0, minsize=self.w*0.15)
self.grid_columnconfigure(1, minsize=self.w*0.85)
self.navbar.grid(sticky=N+S+E+W, column=0, row=0)
self.main_db.grid(sticky=N+E+S+W, column=1, row=0)
self.rootframe.grid(sticky=N+E+S+W, column=1, row=0)
self.statusbar.grid(sticky=W+E, column=0, columnspan=2, row=1)
self.grid_columnconfigure(1, weight=1)
self.statusbar.columnconfigure(0, weight=1)
self.rootframe.columnconfigure(0, weight=1)
self.main_db.columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.navbar.rowconfigure(4, weight=1)
self.rootframe.rowconfigure(0, weight=1)
self.main_db.rowconfigure(0, weight=1)
self.rootframe.lift(self.main_db)
def visualize(self, master):
"""Lifts master to upper Level"""
master.lift(self.rootframe)
self._visible_ = master
def event_handler(self):
pass
def start_subapp(self, app):
self.visualize(app)
app.activate_content()
class RootFrame(tkinter.Frame):
"""General Launcher Frame as a Placeholder"""
def __init__(self, parent, *args, **kwargs):
tkinter.Frame.__init__(self, parent, *args, **kwargs)
# Var-Daclaration
self.widget_fr_opts = dict(relief='sunken', borderwidth=1)
self.widget_grid_opts = dict(sticky=N+E+S+W, padx=1, pady=1)
# Widget-Creation
self.Image = tkinter.ttk.Label(self, text='there would be a centered image right here', anchor='center')
# Widget-Design
self.configure(**self.widget_fr_opts)
# Widget-Arrangement
self.Image.grid(column=0, row=0, **self.widget_grid_opts)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
class Navbar(tkinter.Frame):
"""vertical NavBar"""
def __init__(self, parent, *args, **kwargs):
tkinter.Frame.__init__(self, parent, *args, **kwargs)
# Var-Daclaration
self._info_ = tkinter.StringVar()
self.widget_fr_opts = dict(relief='groove', borderwidth=1)
self.widget_grid_opts = dict(sticky=N+E+S+W, padx=1, pady=1)
self.widget_grid_subopts = dict(sticky=W+N+E, padx=1, pady=1)
self._statusbar = parent.statusbar
# Widget-Creation
self._info_.set('Menu:\n...Menusentences:')
self.TextInfo = tkinter.ttk.Label(self, textvariable=self._info_)
self.Btn_Progress = tkinter.ttk.Button(self, text='Start Progress',
command=lambda: self.statusbar_input('Starting progress ...')) # some code being started
self.Btn_Database = tkinter.ttk.Button(self, text='Database',
command=lambda: parent.start_subapp(parent.main_db)) # Database window is lifted and content initialized
self.Btn_Exit = tkinter.ttk.Button(self, text='Exit', command=parent.quit)
# Widget-Design
self.configure(**self.widget_fr_opts)
# Widget-Arrangement
self.TextInfo.grid(column=0, row=1, **self.widget_grid_subopts)
self.Btn_Progress.grid(column=0, row=2, **self.widget_grid_subopts)
self.Btn_Database.grid(column=0, row=3, **self.widget_grid_subopts)
self.Btn_Exit.grid(column=0, row=4, **self.widget_grid_subopts)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=0)
self.grid_rowconfigure(1, weight=0)
self.grid_rowconfigure(2, weight=0)
self.grid_rowconfigure(3, weight=0)
self.grid_rowconfigure(4, weight=0)
def statusbar_input(self, comm: str):
self._statusbar.start()
self._statusbar._info_.set(comm)
class Statusbar(tkinter.Frame):
"""Status-Bar at the bottom"""
def __init__(self, parent, *args, **kwargs):
tkinter.Frame.__init__(self, parent, *args, **kwargs)
# Var-Daclaration
self.prgrvalue = tkinter.IntVar()
self._info_ = tkinter.StringVar()
self._user_ = 'some user'
self.widget_fr_opts = dict(relief='sunken', borderwidth=1)
self.widget_grid_opts = dict(padx=1, pady=1)
self.widget_grid_subopts = dict(padx=1, pady=1) # sticky=W + E,
# Widget-Creation
self._info_.set('Initializing ...')
self.prgrvalue.set(0)
self.TextInfo = tkinter.ttk.Label(self, textvariable=self._info_)
self.UserInfo = tkinter.ttk.Label(self, textvariable=self._user_)
self.progress_ = tkinter.ttk.Progressbar(self)
self.Btn_Move = tkinter.ttk.Button(self, text='Move it', command=lambda: self.start()) # just for initial testing, will be removed later
self.Btn_Stop = tkinter.ttk.Button(self, text='Stop it', command=lambda: self.stop())
# Widget-Design
self.configure(**self.widget_fr_opts)
self.progress_.configure(length=200, mode='determinate', orient=tkinter.HORIZONTAL)
# Widget-Arrangement
self.progress_.grid(sticky=W+E, column=0, row=0, **self.widget_grid_subopts)
self.TextInfo.grid(column=1, row=0, **self.widget_grid_subopts)
self.UserInfo.grid(column=2, row=0, padx=1, pady=1) # sticky=E,
self.Btn_Move.grid(column=3, row=0, **self.widget_grid_subopts)
self.Btn_Stop.grid(column=4, row=0, **self.widget_grid_subopts)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, minsize=200)
self.grid_columnconfigure(2, minsize=200)
def start(self):
# just testing
self.progress_.start()
def stop(self):
# just testing
self.progress_.stop()
class MainDB(tkinter.Frame):
"""Frame for visualizing database."""
def __init__(self, parent, *args, **kwargs):
tkinter.Frame.__init__(self, parent, *args, **kwargs)
# Var-Daclaration
self._activated_ = False
self._source_ = None
self.combotext = tkinter.StringVar()
self.combotext.set('Please choose a tab...')
self.widget_fr_opts = dict(relief='sunken', borderwidth=1)
self.widget_grid_opts = dict(sticky=N+E+S+W, padx=1, pady=1)
# Widget-Creation
# CREATION OF TOOLS TO MANIPULATE DATABASE
self.toolframe = tkinter.Frame(self, width=100, height=50, relief='groove', borderwidth=1)
self.combo = tkinter.ttk.Combobox(self.toolframe, textvariable=self.combotext)
# more to come
# CREATION OF DATABASE'WINDOW
self.dbframe = tkinter.Frame(self, width=100, relief='groove', borderwidth=1)
self.db_treeview = tkinter.ttk.Treeview(self.dbframe, columns=('size', 'modified'), selectmode='extended')
# more to come
# Widget-Design
# Widget-Arrangement
self.toolframe.grid(column=0, row=0, sticky=N+E+W, padx=1, pady=1)
self.combo.grid(column=0, row=0, sticky=N+E, padx=1, pady=1)
self.dbframe.grid(column=0, row=1, sticky=NSEW, padx=1, pady=1)
self.db_treeview.grid(column=0, row=0, sticky=NSEW, padx=1, pady=1)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=0)
self.grid_rowconfigure(1, weight=1)
self.dbframe.grid_columnconfigure(0, weight=1)
self.dbframe.grid_rowconfigure(0, weight=1, minsize=600)
self.toolframe.grid_columnconfigure(0, weight=1)
self.toolframe.grid_rowconfigure(0, weight=1)
def activate_content(self):
# some contentloading and initializations
pass
def db_connector(self, comm: str, save=False) -> bool:
# some connection code
pass
if __name__ == '__main__':
UserScreen = MainApplication.main()
</code></pre>
| 0 | 2016-07-25T14:03:18Z | 38,570,633 | <p>You are neglecting to give a weight to any rows or columns in the root window. Without it, tkinter doesn't know how to allocate extra space when you resize the window.</p>
<pre><code>def main(cls):
...
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
</code></pre>
<p>Since you're only putting a single widget in the root window, I recommend using <code>pack</code> since you can accomplish everything in a single line. </p>
<pre><code> self.pack(fill="both", expand=True)
</code></pre>
| 0 | 2016-07-25T14:35:45Z | [
"python",
"tkinter",
"resize",
"grid-layout"
] |
Authentication issue using requests on aspx site | 38,569,906 | <p>I am trying to use requests (python) to grab some pages from a website that requires me to be logged in.
I did inspect the login page to check out the username and password headers. But I found the names for those fields are not the standard 'username', 'password' used by most sites as you can see from the below screenshots</p>
<p><a href="http://i.stack.imgur.com/assO1.jpg" rel="nofollow">password field</a></p>
<p>I used them that way in my python script but each time I get a 'wrong syntax' error. Even sublimetext displayed a part of the name in orange as you can see from the pix below</p>
<p>From this I know there must be some problem with the name. But try to escape the $ signs did not help.
Even the login.aspx header disappears before google chrome could register it on the network.</p>
<p>The site is www dot bncnetwork dot net</p>
<p>I'd be happy if someone could help me figure out what to do about this.</p>
<p>Here is the code`import requests</p>
<pre><code>import requests
def get_project_page(seed_page):
username = "*******************"
password = "*******************"
bnc_login = dict(ctl00$MainContent$txtEmailID=username, ctl00$MainContent$txtPassword=password)
sess_req = requests.Session()
sess_req.get(seed_page)
sess_req.post(seed_page, data=bnc_login, headers={"Referer":"http://www.bncnetwork.net/MyBNC.aspx"})
page = sess_req.get(seed_page)
return page.text`
</code></pre>
| -1 | 2016-07-25T14:05:15Z | 38,570,149 | <p>You need to use strings for the keys, the $ will cause a syntax error if you don't:</p>
<pre><code> data = {"ctl00$MainContent$txtPassword":password, "ctl00$MainContent$txtEmailID":email}
</code></pre>
<p>There are evenvalidation fileds etc.. to be filled in also, follow the logic from this <a href="http://stackoverflow.com/questions/38554235/scraping-excel-from-website-using-python-with-dopostback-link-url-hidden/38557881#38557881">answer</a> to fill them out, all the fields can be seen in chrome tools:</p>
<p><a href="http://i.stack.imgur.com/teVa4.png" rel="nofollow"><img src="http://i.stack.imgur.com/teVa4.png" alt="enter image description here"></a></p>
| 1 | 2016-07-25T14:15:03Z | [
"python",
"authentication",
"python-requests"
] |
Detect the green lines in this image and calculate their lengths | 38,569,938 | <p><a href="http://i.stack.imgur.com/ZqHix.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZqHix.png" alt="enter image description here"></a>Sample Images</p>
<p><img src="http://i.stack.imgur.com/NFEQi.png" alt=""></p>
<p>The image can be more noisy at times where more objects intervene from the background. Right now I am using various techniques using the RGB colour space to detect the lines but it fails when there is change in the colour due to intervening obstacles from the background. I am using opencv and python.
I have read that HSV is better for colour detection and used but haven't been successful yet.
I am not able to find a generic solution to this problem. Any hints or clues in this direction would be of great help. </p>
| 2 | 2016-07-25T14:06:50Z | 38,601,225 | <p>You should use the fact that you know you are trying to detect a line by using the line hough transform.
<a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html" rel="nofollow">http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html</a></p>
<ul>
<li>When the obstacle also look like a line use the fact that you know approximately what is the orientation of the green lines.</li>
<li>If you don't know the orientation of the line use hte fact that there are several green lines with the same orientation and only one line that is the obstacle </li>
</ul>
<p>Here is a code for what i meant:</p>
<pre><code>import cv2
import numpy as np
# Params
minLineCount = 300 # min number of point alogn line with the a specif orientation
minArea = 100
# Read img
img = cv2.imread('i.png')
greenChannel = img[:,:,1]
# Do noise reduction
iFilter = cv2.bilateralFilter(greenChannel,5,5,5)
# Threshold data
#ret,iThresh = cv2.threshold(iFilter,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
iThresh = (greenChannel > 4).astype(np.uint8)*255
# Remove small areas
se1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
iThreshRemove = cv2.morphologyEx(iThresh, cv2.MORPH_OPEN, se1)
# Find edges
iEdge = cv2.Canny(iThreshRemove,50,100)
# Hough line transform
lines = cv2.HoughLines(iEdge, 1, 3.14/180,75)
# Find the theta with the most lines
thetaCounter = dict()
for line in lines:
theta = line[0, 1]
if theta in thetaCounter:
thetaCounter[theta] += 1
else:
thetaCounter[theta] = 1
maxThetaCount = 0
maxTheta = 0
for theta in thetaCounter:
if thetaCounter[theta] > maxThetaCount:
maxThetaCount = thetaCounter[theta]
maxTheta = theta
# Find the rhos that corresponds to max theta
rhoValues = []
for line in lines:
rho = line[0, 0]
theta = line[0, 1]
if theta == maxTheta:
rhoValues.append(rho)
# Go over all the lines with the specific orientation and count the number of pixels on that line
# if the number is bigger than minLineCount draw the pixels in finaImage
lineImage = np.zeros_like(iThresh, np.uint8)
for rho in range(min(rhoValues), max(rhoValues), 1):
a = np.cos(maxTheta)
b = np.sin(maxTheta)
x0 = round(a*rho)
y0 = round(b*rho)
lineCount = 0
pixelList = []
for jump in range(-1000, 1000, 1):
x1 = int(x0 + jump * (-b))
y1 = int(y0 + jump * (a))
if x1 < 0 or y1 < 0 or x1 >= lineImage.shape[1] or y1 >= lineImage.shape[0]:
continue
if iThreshRemove[y1, x1] == int(255):
pixelList.append((y1, x1))
lineCount += 1
if lineCount > minLineCount:
for y,x in pixelList:
lineImage[y, x] = int(255)
# Remove small areas
## Opencv 2.4
im2, contours, hierarchy = cv2.findContours(lineImage,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE )
finalImage = np.zeros_like(lineImage)
finalShapes = []
for contour in contours:
if contour.size > minArea:
finalShapes.append(contour)
cv2.fillPoly(finalImage, finalShapes, 255)
## Opencv 3.0
# output = cv2.connectedComponentsWithStats(lineImage, 8, cv2.CV_32S)
#
# finalImage = np.zeros_like(output[1])
# finalImage = output[1]
# stat = output[2]
# for label in range(output[0]):
# if label == 0:
# continue
# cc = stat[label,:]
# if cc[cv2.CC_STAT_AREA] < minArea:
# finalImage[finalImage == label] = 0
# else:
# finalImage[finalImage == label] = 255
# Show image
#cv2.imwrite('finalImage2.jpg',finalImage)
cv2.imshow('a', finalImage.astype(np.uint8))
cv2.waitKey(0)
</code></pre>
<p>and the result for the images:
<a href="http://i.stack.imgur.com/eHO6y.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/eHO6y.jpg" alt="Result"></a></p>
<p><a href="http://i.stack.imgur.com/ad46p.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ad46p.jpg" alt="enter image description here"></a></p>
| 0 | 2016-07-26T23:01:24Z | [
"python",
"opencv",
"image-processing",
"rgb",
"hsv"
] |
Detect the green lines in this image and calculate their lengths | 38,569,938 | <p><a href="http://i.stack.imgur.com/ZqHix.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZqHix.png" alt="enter image description here"></a>Sample Images</p>
<p><img src="http://i.stack.imgur.com/NFEQi.png" alt=""></p>
<p>The image can be more noisy at times where more objects intervene from the background. Right now I am using various techniques using the RGB colour space to detect the lines but it fails when there is change in the colour due to intervening obstacles from the background. I am using opencv and python.
I have read that HSV is better for colour detection and used but haven't been successful yet.
I am not able to find a generic solution to this problem. Any hints or clues in this direction would be of great help. </p>
| 2 | 2016-07-25T14:06:50Z | 38,623,769 | <p><strong>STILL IN PROGRESS</strong></p>
<p>First of all, an RGB image consists of 3 grayscale images. Since you need the green color you will deal only with one channel. The green one. To do so, you can split the image, you can use <code>b,g,r = cv2.split('Your Image')</code>. You will get an output like that if you are showing the green channel:</p>
<p><a href="http://i.stack.imgur.com/TC4II.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/TC4II.jpg" alt="green_channel"></a></p>
<p>After that you should threshold the image using your desired way. I prefer <code>Otsu's thresholding</code> in this case. The output after thresholding is:</p>
<p><a href="http://i.stack.imgur.com/hzems.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/hzems.jpg" alt="thresholded_image"></a></p>
<p>It's obvious that the thresholded image is extremley noisy. So performing <code>erosion</code> will reduce the noise a little bit. The noise reduced image will be similar to the following:</p>
<p><a href="http://i.stack.imgur.com/eLS9n.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/eLS9n.jpg" alt="erosion"></a></p>
<p>I tried using <code>closing</code> instead of <code>dilation</code>, but <code>closing</code> preserves some unwanted noise. So I separately performed <code>erosion</code> followed by <code>dilation</code>. After <code>dilation</code> the output is:</p>
<p><a href="http://i.stack.imgur.com/zusBN.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/zusBN.jpg" alt="dilation"></a></p>
<p><strong>Note that:</strong> <em>You can do your own way in morphological operation. You can use <code>opening</code> instead of what I did. The results are subjective from
one person to another.</em></p>
<p>Now you can try one these two methods:</p>
<p><strong>1. Blob Detection.</strong>
<strong>2. HoughLine Transform.</strong></p>
<p><strong>TODO</strong></p>
<p><em>Try out these two methods and choose the best.</em></p>
| 0 | 2016-07-27T21:49:06Z | [
"python",
"opencv",
"image-processing",
"rgb",
"hsv"
] |
pandas dataframe: meaning of .index | 38,569,952 | <p>I am trying to understand the meaning of the output of the following code:</p>
<pre><code>import pandas as pd
index = ['index1','index2','index3']
columns = ['col1','col2','col3']
df = pd.DataFrame([[1,2,3],[1,2,3],[1,2,3]], index=index, columns=columns)
print df.index
</code></pre>
<p>I would expect just a list containing the index of the dataframe:</p>
<p>['index1, 'index2', 'index3']</p>
<p>however the output is:</p>
<p>Index([u'index1', u'index2', u'index3'], dtype='object')</p>
| 0 | 2016-07-25T14:07:09Z | 38,569,986 | <p>This is the pretty output of the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html#pandas.Index" rel="nofollow"><code>pandas.Index</code></a> object, if you look at the type it shows the class type:</p>
<pre><code>In [45]:
index = ['index1','index2','index3']
columns = ['col1','col2','col3']
df = pd.DataFrame([[1,2,3],[1,2,3],[1,2,3]], index=index, columns=columns)
df.index
Out[45]:
Index(['index1', 'index2', 'index3'], dtype='object')
In [46]:
type(df.index)
Out[46]:
pandas.indexes.base.Index
</code></pre>
<p>So what it shows is that you have an <code>Index</code> type with the elements 'index1' and so on, the dtype is <code>object</code> which is <code>str</code></p>
<p>if you didn't pass your list of strings for the index you get the default int index which is the new type <code>RangeIndex</code>:</p>
<pre><code>In [47]:
df = pd.DataFrame([[1,2,3],[1,2,3],[1,2,3]], columns=columns)
df.index
Out[47]:
RangeIndex(start=0, stop=3, step=1)
</code></pre>
<p>If you wanted a list of the values:</p>
<pre><code>In [51]:
list(df.index)
Out[51]:
['index1', 'index2', 'index3']
</code></pre>
| 0 | 2016-07-25T14:08:28Z | [
"python",
"pandas",
"dataframe"
] |
Python: How does string.replace("\n", " ") behave in- and outside a function? | 38,569,964 | <p>The aim of my code is to put the string <code>datastr</code> into the two-dimensional list <code>matrix</code>. This works perfectly in Code_v1 but when I put the same code into a function <code>datastr = datastr.replace("\n", " ")</code> doesn't replace the <code>\n</code> the same way it did in Code_v1 (form one <code>" "</code> to several <code>" "</code>´s; compare Output_v1 to Output_v2).</p>
<p>Why is that the case and how can I fix it?</p>
<p>I already read through numerous other questions regarding <code>.replace(old, new)</code> but they all wrote <code>string.replace(old, new)</code> instead of <code>string = string.replace(old, new)</code>. </p>
<p>Thank you in advance for your answers.</p>
<p>P.S. I don't want to use <code>matrix</code> for math. That is why I use a two-dimensional list and not <code>numpy.matrix</code>.</p>
<p>P.P.S. This is my first questions. If one has any suggestion how to improve the readability of the question or any kind of improvements for my coding, please tell me.</p>
<p>Code_v1:</p>
<pre><code>datastr = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"""
datastr = datastr.replace("\n", " ") # Remove all \n from the string
print(datastr)
datalist = datastr.split(" ") # Split the string into a new element by " " for the list datalist
matrix = [[1 for y in range(20)] for x in range(20)] # create 20x20 "matrix"
print(datalist)
for y in range(20): # Write data into the "matrix" as integer
for x in range(20):
matrix[x][y] = int(datalist[y * 20 + x])
</code></pre>
<p>Output_v1:</p>
<pre><code>C:\Users\i7\AppData\Local\Programs\Python\Python35-32\pythonw.exe C:/Users/i7/Dropbox/Programmieren/Python/test.py
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
['08', '02', '22', '97', '38', '15', '00', '40', '00', '75', '04', '05', '07', '78', '52', '12', '50', '77', '91', '08', '49', '49', '99', '40', '17', '81', '18', '57', '60', '87', '17', '40', '98', '43', '69', '48', '04', '56', '62', '00', '81', '49', '31', '73', '55', '79', '14', '29', '93', '71', '40', '67', '53', '88', '30', '03', '49', '13', '36', '65', '52', '70', '95', '23', '04', '60', '11', '42', '69', '24', '68', '56', '01', '32', '56', '71', '37', '02', '36', '91', '22', '31', '16', '71', '51', '67', '63', '89', '41', '92', '36', '54', '22', '40', '40', '28', '66', '33', '13', '80', '24', '47', '32', '60', '99', '03', '45', '02', '44', '75', '33', '53', '78', '36', '84', '20', '35', '17', '12', '50', '32', '98', '81', '28', '64', '23', '67', '10', '26', '38', '40', '67', '59', '54', '70', '66', '18', '38', '64', '70', '67', '26', '20', '68', '02', '62', '12', '20', '95', '63', '94', '39', '63', '08', '40', '91', '66', '49', '94', '21', '24', '55', '58', '05', '66', '73', '99', '26', '97', '17', '78', '78', '96', '83', '14', '88', '34', '89', '63', '72', '21', '36', '23', '09', '75', '00', '76', '44', '20', '45', '35', '14', '00', '61', '33', '97', '34', '31', '33', '95', '78', '17', '53', '28', '22', '75', '31', '67', '15', '94', '03', '80', '04', '62', '16', '14', '09', '53', '56', '92', '16', '39', '05', '42', '96', '35', '31', '47', '55', '58', '88', '24', '00', '17', '54', '24', '36', '29', '85', '57', '86', '56', '00', '48', '35', '71', '89', '07', '05', '44', '44', '37', '44', '60', '21', '58', '51', '54', '17', '58', '19', '80', '81', '68', '05', '94', '47', '69', '28', '73', '92', '13', '86', '52', '17', '77', '04', '89', '55', '40', '04', '52', '08', '83', '97', '35', '99', '16', '07', '97', '57', '32', '16', '26', '26', '79', '33', '27', '98', '66', '88', '36', '68', '87', '57', '62', '20', '72', '03', '46', '33', '67', '46', '55', '12', '32', '63', '93', '53', '69', '04', '42', '16', '73', '38', '25', '39', '11', '24', '94', '72', '18', '08', '46', '29', '32', '40', '62', '76', '36', '20', '69', '36', '41', '72', '30', '23', '88', '34', '62', '99', '69', '82', '67', '59', '85', '74', '04', '36', '16', '20', '73', '35', '29', '78', '31', '90', '01', '74', '31', '49', '71', '48', '86', '81', '16', '23', '57', '05', '54', '01', '70', '54', '71', '83', '51', '54', '69', '16', '92', '33', '48', '61', '43', '52', '01', '89', '19', '67', '48']
Process finished with exit code 0
</code></pre>
<p>Code_v2:</p>
<pre><code>#globals
matrix = 0
matrix_data = 0
def create_matrix():
global matrix
global matrix_data
datastr = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"""
datastr = datastr.replace("\n", " ") # Remove all \n from the string
print(datastr)
datalist = datastr.split(" ") # Split the string into a new element by " " for the list datalist
matrix = [[1 for y in range(20)] for x in range(20)] # create 20x20 "matrix"
matrix_data = [[1 for y in range(20)] for x in range(20)]
print(datalist)
for y in range(20): # Write data into the "matrix" as integer
for x in range(20):
matrix[x][y] = int(datalist[y * 20 + x])
create_matrix()
</code></pre>
<p>Output_v2:</p>
<pre><code>C:\Users\i7\AppData\Local\Programs\Python\Python35-32\pythonw.exe C:/Users/i7/Dropbox/Programmieren/Python/test.py
Traceback (most recent call last):
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
File "C:/Users/i7/Dropbox/Programmieren/Python/test.py", line 51, in <module>
create_matrix()
File "C:/Users/i7/Dropbox/Programmieren/Python/test.py", line 46, in create_matrix
matrix[x][y] = int(datalist[y * 20 + x])
ValueError: invalid literal for int() with base 10: ''
['08', '02', '22', '97', '38', '15', '00', '40', '00', '75', '04', '05', '07', '78', '52', '12', '50', '77', '91', '08', '', '', '', '', '49', '49', '99', '40', '17', '81', '18', '57', '60', '87', '17', '40', '98', '43', '69', '48', '04', '56', '62', '00', '', '', '', '', '81', '49', '31', '73', '55', '79', '14', '29', '93', '71', '40', '67', '53', '88', '30', '03', '49', '13', '36', '65', '', '', '', '', '52', '70', '95', '23', '04', '60', '11', '42', '69', '24', '68', '56', '01', '32', '56', '71', '37', '02', '36', '91', '', '', '', '', '22', '31', '16', '71', '51', '67', '63', '89', '41', '92', '36', '54', '22', '40', '40', '28', '66', '33', '13', '80', '', '', '', '', '24', '47', '32', '60', '99', '03', '45', '02', '44', '75', '33', '53', '78', '36', '84', '20', '35', '17', '12', '50', '', '', '', '', '32', '98', '81', '28', '64', '23', '67', '10', '26', '38', '40', '67', '59', '54', '70', '66', '18', '38', '64', '70', '', '', '', '', '67', '26', '20', '68', '02', '62', '12', '20', '95', '63', '94', '39', '63', '08', '40', '91', '66', '49', '94', '21', '', '', '', '', '24', '55', '58', '05', '66', '73', '99', '26', '97', '17', '78', '78', '96', '83', '14', '88', '34', '89', '63', '72', '', '', '', '', '21', '36', '23', '09', '75', '00', '76', '44', '20', '45', '35', '14', '00', '61', '33', '97', '34', '31', '33', '95', '', '', '', '', '78', '17', '53', '28', '22', '75', '31', '67', '15', '94', '03', '80', '04', '62', '16', '14', '09', '53', '56', '92', '', '', '', '', '16', '39', '05', '42', '96', '35', '31', '47', '55', '58', '88', '24', '00', '17', '54', '24', '36', '29', '85', '57', '', '', '', '', '86', '56', '00', '48', '35', '71', '89', '07', '05', '44', '44', '37', '44', '60', '21', '58', '51', '54', '17', '58', '', '', '', '', '19', '80', '81', '68', '05', '94', '47', '69', '28', '73', '92', '13', '86', '52', '17', '77', '04', '89', '55', '40', '', '', '', '', '04', '52', '08', '83', '97', '35', '99', '16', '07', '97', '57', '32', '16', '26', '26', '79', '33', '27', '98', '66', '', '', '', '', '88', '36', '68', '87', '57', '62', '20', '72', '03', '46', '33', '67', '46', '55', '12', '32', '63', '93', '53', '69', '', '', '', '', '04', '42', '16', '73', '38', '25', '39', '11', '24', '94', '72', '18', '08', '46', '29', '32', '40', '62', '76', '36', '', '', '', '', '20', '69', '36', '41', '72', '30', '23', '88', '34', '62', '99', '69', '82', '67', '59', '85', '74', '04', '36', '16', '', '', '', '', '20', '73', '35', '29', '78', '31', '90', '01', '74', '31', '49', '71', '48', '86', '81', '16', '23', '57', '05', '54', '', '', '', '', '01', '70', '54', '71', '83', '51', '54', '69', '16', '92', '33', '48', '61', '43', '52', '01', '89', '19', '67', '48']
Process finished with exit code 1
</code></pre>
| 1 | 2016-07-25T14:07:45Z | 38,570,014 | <p>You <strong>indented</strong> the lines of <code>datastr</code>. Those spaces at the start of each line are <em>significant</em>:</p>
<pre><code> datastr = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 ... """
# ^^ spaces here.
</code></pre>
<p>As a result each line (except for the first), starts with 4 extra spaces. Your <code>\n</code> newlines are replaced just fine, but those extra spaces are still in place.</p>
<p>Split your string with <code>str.split()</code> with <em>no arguments</em> and you won't need to replace newlines with spaces either:</p>
<pre><code>datalist = datastr.split()
</code></pre>
<p><code>str.split()</code> with no arguments (or <code>None</code> as the first argument) splits on arbitrary width whitespace, including newlines. It doesn't matter if there is one or multiple whitespace characters in-between.</p>
| 6 | 2016-07-25T14:09:33Z | [
"python",
"string"
] |
Pycharm import RuntimeWarning after updating to 2016.2 | 38,569,992 | <p>After updating to new version 2016.2, I am getting</p>
<pre><code>RuntimeWarning: Parent module 'tests' not found while handling absolute import
import unittest
RuntimeWarning: Parent module 'tests' not found while handling absolute import
import datetime as dt
</code></pre>
<p>'tests' is a package inside my main app package, and I receive these warnings when I try to execute unit tests inside this folder. This issue only came up after updating to 2016.2. Besides the warnings, the remaining code works fine.</p>
<p>Edit: This is a known issue - <a href="https://youtrack.jetbrains.com/issue/PY-20171">https://youtrack.jetbrains.com/issue/PY-20171</a>. They are suggesting to replace utrunner.py in PyCharm installation folder.</p>
| 28 | 2016-07-25T14:08:50Z | 38,670,988 | <p>On OS X I've fixed this by replacing </p>
<pre><code>Applications/PyCharm.app/Contents/helpers/pycharm/utrunner.py
</code></pre>
<p>with an older version that can be found at
<a href="http://code.metager.de/source/xref/jetbrains/intellij/community/python/helpers/pycharm/utrunner.py">http://code.metager.de/source/xref/jetbrains/intellij/community/python/helpers/pycharm/utrunner.py</a></p>
| 5 | 2016-07-30T06:21:41Z | [
"python",
"import",
"pycharm"
] |
Pycharm import RuntimeWarning after updating to 2016.2 | 38,569,992 | <p>After updating to new version 2016.2, I am getting</p>
<pre><code>RuntimeWarning: Parent module 'tests' not found while handling absolute import
import unittest
RuntimeWarning: Parent module 'tests' not found while handling absolute import
import datetime as dt
</code></pre>
<p>'tests' is a package inside my main app package, and I receive these warnings when I try to execute unit tests inside this folder. This issue only came up after updating to 2016.2. Besides the warnings, the remaining code works fine.</p>
<p>Edit: This is a known issue - <a href="https://youtrack.jetbrains.com/issue/PY-20171">https://youtrack.jetbrains.com/issue/PY-20171</a>. They are suggesting to replace utrunner.py in PyCharm installation folder.</p>
| 28 | 2016-07-25T14:08:50Z | 38,724,508 | <p>This is a known issue with the 2016.2 release. Progress can be followed on the JetBrains website <a href="https://youtrack.jetbrains.com/issue/PY-20171">here</a>. According to this page it's due to be fixed in the 2016.3 release but you can follow the utrunner.py workaround that others have mentioned in the meantime (I downloaded the 2016.1 release and copied the file over from there).</p>
| 29 | 2016-08-02T15:21:38Z | [
"python",
"import",
"pycharm"
] |
Make a list of dicts by iterating over two lists (list comprehensions) | 38,569,999 | <p>The lists have the same number of elements, and the names are unique.
I wonder, how can I make a dict in one action. </p>
<p>This is my current code:</p>
<pre><code> fees = [fee for fee in fees]
names = [name for name in names]
mdict = [
{'fees': fee[i], 'names': names[i]}
for i, val in enumerate(fees)]
</code></pre>
| 1 | 2016-07-25T14:09:01Z | 38,570,042 | <p>Try this:</p>
<pre><code>result = dict(zip(fees, names))
</code></pre>
| 1 | 2016-07-25T14:10:34Z | [
"python",
"list-comprehension"
] |
Make a list of dicts by iterating over two lists (list comprehensions) | 38,569,999 | <p>The lists have the same number of elements, and the names are unique.
I wonder, how can I make a dict in one action. </p>
<p>This is my current code:</p>
<pre><code> fees = [fee for fee in fees]
names = [name for name in names]
mdict = [
{'fees': fee[i], 'names': names[i]}
for i, val in enumerate(fees)]
</code></pre>
| 1 | 2016-07-25T14:09:01Z | 38,570,045 | <p>You mean zip?</p>
<pre><code>dict(zip(fees, names))
</code></pre>
| 1 | 2016-07-25T14:10:40Z | [
"python",
"list-comprehension"
] |
Make a list of dicts by iterating over two lists (list comprehensions) | 38,569,999 | <p>The lists have the same number of elements, and the names are unique.
I wonder, how can I make a dict in one action. </p>
<p>This is my current code:</p>
<pre><code> fees = [fee for fee in fees]
names = [name for name in names]
mdict = [
{'fees': fee[i], 'names': names[i]}
for i, val in enumerate(fees)]
</code></pre>
| 1 | 2016-07-25T14:09:01Z | 38,570,064 | <p>You can use <code>zip</code> on both lists in a <em>list comprehension</em>:</p>
<pre><code>mdict = [{'fees': f, 'names': n} for f, n in zip(fees, names)]
</code></pre>
| 4 | 2016-07-25T14:11:29Z | [
"python",
"list-comprehension"
] |
Make a list of dicts by iterating over two lists (list comprehensions) | 38,569,999 | <p>The lists have the same number of elements, and the names are unique.
I wonder, how can I make a dict in one action. </p>
<p>This is my current code:</p>
<pre><code> fees = [fee for fee in fees]
names = [name for name in names]
mdict = [
{'fees': fee[i], 'names': names[i]}
for i, val in enumerate(fees)]
</code></pre>
| 1 | 2016-07-25T14:09:01Z | 38,570,171 | <p>You want this</p>
<pre><code>{fees[i]:y[i] for i in range(len(fees))}
</code></pre>
<p>or more quite :</p>
<pre><code>dict(zip(fees, names))
</code></pre>
| 1 | 2016-07-25T14:15:54Z | [
"python",
"list-comprehension"
] |
Fixing different id having same images in a csv column by renaming? | 38,570,025 | <p>As a new Python programmer, I'm having trouble figuring out how to accomplish the following. </p>
<p>Given this input data from a csv file: </p>
<pre class="lang-none prettyprint-override"><code>Sku Image_Name
B001 a.jpg
B002 a.jpg
B001 b.jpg
B002 c.jpg
B003 x.jpg
</code></pre>
<p>Where multiple <code>Sku</code>'s might have the same image name. When that occurs, I want to rename the image name in the <code>Image__Name</code> column by concatenating <code>"_"</code> + <code>Sku</code> value as shown to the image name in that same row.</p>
<p>So the desired output data would be:</p>
<pre class="lang-none prettyprint-override"><code>Sku Image_Name
B001 a_B001.jpg
B002 a_B002.jpg
B001 b.jpg
B002 c.jpg
B003 x.jpg
</code></pre>
<p>After that it should rename the images in the image folder according to the <code>Image_Name</code> column.</p>
<p>This is all I have so far:</p>
<pre><code>import csv
#open and store the csv file
with open('D:\\test.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
</code></pre>
| -1 | 2016-07-25T14:10:00Z | 38,572,713 | <p>OK, you've got quite a ways to go, but this should give you some hints on how to proceed (assuming a reasonable number of files):</p>
<pre><code>import csv
from os.path import splitext
with open("/tmp/test.csv", 'rb') as csvfile:
itemList = []
renamedList = []
keyList = []
spamreader = csv.reader(csvfile, delimiter=",")
for row in spamreader:
keyList.append(row[0])
itemList.append(row[1])
renamedList.append(row[1])
toBeChanged = [itemNum for itemNum, item in enumerate(itemList)
if itemList.count(item) > 1]
for itemNum in toBeChanged:
name, ext = splitext(itemList[itemNum])
renamedList[itemNum] = '{}_{}{}'.format(name, keyList[itemNum], ext)
# At this point we have your desired info and can print it just like you
# have above
print("Sku\tImage_Name")
for row in zip(keyList, itemList):
print(row[0] + '\t' + row[1])
# Duplicating / renaming files is next. This isn't the only way
# to do it (or the most efficient), but it's an easy way to understand.
# The idea is to first make copies of all needed files...
from shutil import copyfile
changedNames = []
for itemNum in toBeChanged:
copyfile(itemList[itemNum], renamedList[itemNum])
changedNames.append(itemList[itemNum])
# ...and then delete the originals. The set is used to eliminate
# duplicates.
from os import remove
for item in set(changedNames):
remove(itemName)
</code></pre>
<p>There are <em>lots</em> of ways you can improve this code. The intent here was to make it more understandable. Understand it first, improve it second.</p>
| 0 | 2016-07-25T16:12:41Z | [
"python"
] |
Fixing different id having same images in a csv column by renaming? | 38,570,025 | <p>As a new Python programmer, I'm having trouble figuring out how to accomplish the following. </p>
<p>Given this input data from a csv file: </p>
<pre class="lang-none prettyprint-override"><code>Sku Image_Name
B001 a.jpg
B002 a.jpg
B001 b.jpg
B002 c.jpg
B003 x.jpg
</code></pre>
<p>Where multiple <code>Sku</code>'s might have the same image name. When that occurs, I want to rename the image name in the <code>Image__Name</code> column by concatenating <code>"_"</code> + <code>Sku</code> value as shown to the image name in that same row.</p>
<p>So the desired output data would be:</p>
<pre class="lang-none prettyprint-override"><code>Sku Image_Name
B001 a_B001.jpg
B002 a_B002.jpg
B001 b.jpg
B002 c.jpg
B003 x.jpg
</code></pre>
<p>After that it should rename the images in the image folder according to the <code>Image_Name</code> column.</p>
<p>This is all I have so far:</p>
<pre><code>import csv
#open and store the csv file
with open('D:\\test.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
</code></pre>
| -1 | 2016-07-25T14:10:00Z | 38,603,339 | <pre><code>import csv
import os
from os.path import splitext # splits name & extension from a file
import shutil #making a duplicate copy of a file
from os import rename
#open and read csv
with open('test.csv') as csvfile:
#create list for sku,old_imagename and new imagename
itemList = []
renamedList = []
keyList = []
spamreader = csv.reader(csvfile, delimiter=",")
#processing every row at a time
for row in spamreader:
keyList.append(row[0]) #for sku
itemList.append(row[1]) #for old_imagename
renamedList.append(row[1]) #for new_imagename
#Processing only sku having same images
toBeChanged = [itemNum for itemNum, item in enumerate(itemList)
if itemList.count(item) > 1]
for itemNum in toBeChanged:
name, ext = splitext(itemList[itemNum]) # splitting image name & extension: eg a-> "a" & "jpg"
oldFileName = name + ext
print("oldFileName = " + oldFileName) # oldFileName = a.jpg
newFileName = '{}_{}{}'.format(name, keyList[itemNum], ext)
print("newFileName = " + newFileName) # newFileName = a_B001.jpg & a_B002.jpg
# check if the Image file exists,
if(os.path.isfile(oldFileName)):
shutil.copy2(oldFileName, newFileName); # creating a duplicate image file
renamedList[itemNum] = '{}_{}{}'.format(name, keyList[itemNum], ext) #a_B001.jpg
# os.remove(oldFileName)
#write the final output in new csv
with open('newCsv.csv','w') as mycsv:
csvWriter = csv.writer(mycsv,delimiter=",")
for row in zip(keyList, renamedList):
print(row[0] + '\t' + '\t' + row[1])
csvWriter.writerow([row[0],row[1]])
</code></pre>
| 0 | 2016-07-27T03:42:32Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.