title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
SQLite-Python "executemany()" not executing to the database | 39,790,006 | <p>I need to get this program to store the values for a persons firstname and surname in a database. The database is called Class and the table inside it that I am trying to insert data into is called Names.
I have tried to rearrange this several times and removed it from its try loop to try diagnose the issue. Thanks in advance. I will help the best I can :)</p>
<pre><code>new_first,new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [new_surname, new_first]
print(new_name)
c.executemany("INSERT INTO Names VALUES (?,?)", new_name)
</code></pre>
<p>The error message I keep getting is:
Incorrect number of bindings supplied. The current statement uses 2, and there are 7 supplied.</p>
| -2 | 2016-09-30T11:02:47Z | 39,790,071 | <p><code>executemany()</code> expects <em>many</em> items, as the name suggests.</p>
<p>That means a list of lists, or any similar data structure. You give it only one item.</p>
<pre><code>new_first, new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [[new_surname, new_first]]
c.executemany("INSERT INTO Names VALUES (?,?)", new_name)
</code></pre>
<p>or use <code>execute</code> if you only have one item</p>
<pre><code>new_first, new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [new_surname, new_first]
c.execute("INSERT INTO Names VALUES (?,?)", new_name)
</code></pre>
| 1 | 2016-09-30T11:06:07Z | [
"python",
"sqlite"
]
|
SQLite-Python "executemany()" not executing to the database | 39,790,006 | <p>I need to get this program to store the values for a persons firstname and surname in a database. The database is called Class and the table inside it that I am trying to insert data into is called Names.
I have tried to rearrange this several times and removed it from its try loop to try diagnose the issue. Thanks in advance. I will help the best I can :)</p>
<pre><code>new_first,new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [new_surname, new_first]
print(new_name)
c.executemany("INSERT INTO Names VALUES (?,?)", new_name)
</code></pre>
<p>The error message I keep getting is:
Incorrect number of bindings supplied. The current statement uses 2, and there are 7 supplied.</p>
| -2 | 2016-09-30T11:02:47Z | 39,790,073 | <p>Don't use <code>cursor.executemany()</code>, use <code>cursor.execute()</code>:</p>
<pre><code>c.execute("INSERT INTO Names VALUES (?,?)", new_name)
</code></pre>
<p><code>executemany()</code> should be used for <em>multiple rows of data</em>, but you have just one. </p>
<p>The error is caused by the <code>executemany()</code> method treating <code>new_surname</code> as a row by itself, and since a string is iterable an attempt is made to use every individual character from that string as a parameter. A string length of 7 would give you 7 parameters, and that doesn't match the 2 in the SQL statement.</p>
<p>If you <em>do</em> have many rows, then each row would have to consist of a last and first name value for the two parameters:</p>
<pre><code>new_names = [
[new_surname, new_first],
['another surname', 'another first name'],
# ...
]
c.executemany("INSERT INTO Names VALUES (?,?)", new_names)
</code></pre>
| 1 | 2016-09-30T11:06:14Z | [
"python",
"sqlite"
]
|
Python Pandas plot multiindex specify x and y | 39,790,041 | <p>Below is an example <code>DataFrame</code>.</p>
<pre><code> joaquin manolo
xx 0 0.000000e+00 44.000000
1 1.570796e+00 52.250000
2 3.141593e+00 60.500000
3 4.712389e+00 68.750000
4 6.283185e+00 77.000000
yy 0 0.000000e+00 37.841896
1 2.078796e+00 39.560399
2 5.292179e-17 41.026434
3 -8.983291e-02 42.304767
4 -4.573916e-18 43.438054
</code></pre>
<p>As you can see, the row index has two levels, <code>['xx', 'yy']</code> and <code>[0, 1, 2, 3, 4]</code>. I want to call <code>DataFrame.plot()</code> in such a way that it will produce two subplots, one for <code>joaquin</code> and one for <code>manolo</code>, and where I can specify to use <code>data.loc["xx", :]</code> for the domain data and to use <code>data.loc["yy", :]</code> for the ordinate data. In addition, I want the option to supply the subplots on which the plots should be drawn, in a list (or array) of <code>matplotlib.axes._subplots.AxesSubplot</code> instances, such as those that can be returned by the <code>DataFrame.hist()</code> method. How can this be done?</p>
<h3>Generating the data above</h3>
<p>Just in case you're wondering, below is the code I used to generate the data. If there is an easier way to generate this data, I'd be very interested to know as a side-note.</p>
<pre><code>joaquin_dict = {}
xx_joaquin = numpy.linspace(0, 2*numpy.pi, 5)
yy_joaquin = 10 * numpy.sin(xx_joaquin) * numpy.exp(-xx_joaquin)
for i in range(len(xx_joaquin)):
joaquin_dict[("xx", i)] = xx_joaquin[i]
joaquin_dict[("yy", i)] = yy_joaquin[i]
manolo_dict = {}
xx_manolo = numpy.linspace(44, 77, 5)
yy_manolo = 10 * numpy.log(xx_manolo)
for i in range(len(xx_manolo)):
manolo_dict[("xx", i)] = xx_manolo[i]
manolo_dict[("yy", i)] = yy_manolo[i]
data_dict = {"joaquin": joaquin_dict, "manolo": manolo_dict}
data = pandas.DataFrame.from_dict(data_dict)
</code></pre>
| 2 | 2016-09-30T11:04:26Z | 39,791,006 | <p>Just use a for loop:</p>
<pre><code>fig, axes = pl.subplots(1, 2)
for ax, col in zip(axes, data.columns):
data[col].unstack(0).plot(x="xx", y="yy", ax=ax, title=col)
</code></pre>
<p>output:</p>
<p><a href="http://i.stack.imgur.com/SrYbq.png" rel="nofollow"><img src="http://i.stack.imgur.com/SrYbq.png" alt="enter image description here"></a></p>
| 3 | 2016-09-30T11:57:43Z | [
"python",
"pandas",
"plot"
]
|
Flask app doesn't builds on MS Azure cloud | 39,790,145 | <p>I want to deploy my flask web application on Azure cloud. In Deployment options, I have selected GitHub as source destination for my flask code. after doing the configuration test successfully, the init.py file now starts building;<a href="http://i.stack.imgur.com/9vwfW.png" rel="nofollow"><img src="http://i.stack.imgur.com/9vwfW.png" alt="enter image description here"></a></p>
<p>Now when I go to my application link, it shows me this;<a href="http://i.stack.imgur.com/tWZfD.png" rel="nofollow"><img src="http://i.stack.imgur.com/tWZfD.png" alt="enter image description here"></a></p>
<p>Now at this point, I went back to my deployment options, it says Building failed;
<a href="http://i.stack.imgur.com/Yjhyf.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yjhyf.png" alt="enter image description here"></a></p>
<p>the log generated for this building failed can be seen in the first picture. All the tests has passed except the last one "Performance test". Have anyone encountered the same issue before ? what can be the reason for that ?</p>
<p>I am running the application on localhost @ port 8000.</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
</code></pre>
<p>Do I need to run it on another IP ? </p>
| 0 | 2016-09-30T11:09:50Z | 39,791,229 | <p>You cannot listen on port 8000 in Web Apps. Only port 80 or 443. You'll need to read the port number from the environment, to know what to listen on.</p>
| 0 | 2016-09-30T12:10:31Z | [
"python",
"azure",
"flask",
"azure-web-sites"
]
|
Flask app doesn't builds on MS Azure cloud | 39,790,145 | <p>I want to deploy my flask web application on Azure cloud. In Deployment options, I have selected GitHub as source destination for my flask code. after doing the configuration test successfully, the init.py file now starts building;<a href="http://i.stack.imgur.com/9vwfW.png" rel="nofollow"><img src="http://i.stack.imgur.com/9vwfW.png" alt="enter image description here"></a></p>
<p>Now when I go to my application link, it shows me this;<a href="http://i.stack.imgur.com/tWZfD.png" rel="nofollow"><img src="http://i.stack.imgur.com/tWZfD.png" alt="enter image description here"></a></p>
<p>Now at this point, I went back to my deployment options, it says Building failed;
<a href="http://i.stack.imgur.com/Yjhyf.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yjhyf.png" alt="enter image description here"></a></p>
<p>the log generated for this building failed can be seen in the first picture. All the tests has passed except the last one "Performance test". Have anyone encountered the same issue before ? what can be the reason for that ?</p>
<p>I am running the application on localhost @ port 8000.</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
</code></pre>
<p>Do I need to run it on another IP ? </p>
| 0 | 2016-09-30T11:09:50Z | 39,825,145 | <p>Based on your <code>500</code> error, I think some python packages are not installed correctly.</p>
<p>To check your code is working correctly in naive manner, do as follows.</p>
<ol>
<li>If you are developing on Windows machine, copy all of your <code>site-packages</code> files in development machine to WebApp <code>/site/wwwroot/env/Lib/site-packages</code> folder.</li>
<li>Hit <code>Restart</code> in Azure Portal and <code>F5</code> in browser.</li>
</ol>
<p>If it works, your deployment process might have a problem. Mainly it is caused by library installation.</p>
<p>First, check you have <code>requirements.txt</code> at the root folder. <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-python-configure/#git-publishing" rel="nofollow">This documentation</a> describes some considerations to load Flask on Azure WebApp. Of course, it would be <em>really</em> helpful to read the documentation from the first line carefully.</p>
<p>Second, login WebApp via FTP and check the package is installed correctly. You can see <code>/pip</code> folder has <code>pip.log</code> file, and <code>/site/wwwroot/env/Lib/site-packages</code> folder has its libraries. </p>
<p>For some libraries which you might require more than simple hello world app, you may have to push x86 <code>.whl</code> files along with python codes as they are not installed correctly in x86 environment.</p>
<p>Additionally, in order to show internal error to outside, consider to apply <a href="http://stackoverflow.com/a/15174092/361100">this option</a> during development (not for production).</p>
| 0 | 2016-10-03T05:37:11Z | [
"python",
"azure",
"flask",
"azure-web-sites"
]
|
Flask app doesn't builds on MS Azure cloud | 39,790,145 | <p>I want to deploy my flask web application on Azure cloud. In Deployment options, I have selected GitHub as source destination for my flask code. after doing the configuration test successfully, the init.py file now starts building;<a href="http://i.stack.imgur.com/9vwfW.png" rel="nofollow"><img src="http://i.stack.imgur.com/9vwfW.png" alt="enter image description here"></a></p>
<p>Now when I go to my application link, it shows me this;<a href="http://i.stack.imgur.com/tWZfD.png" rel="nofollow"><img src="http://i.stack.imgur.com/tWZfD.png" alt="enter image description here"></a></p>
<p>Now at this point, I went back to my deployment options, it says Building failed;
<a href="http://i.stack.imgur.com/Yjhyf.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yjhyf.png" alt="enter image description here"></a></p>
<p>the log generated for this building failed can be seen in the first picture. All the tests has passed except the last one "Performance test". Have anyone encountered the same issue before ? what can be the reason for that ?</p>
<p>I am running the application on localhost @ port 8000.</p>
<pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
</code></pre>
<p>Do I need to run it on another IP ? </p>
| 0 | 2016-09-30T11:09:50Z | 39,864,475 | <p>If you created the Azure Webapp using the Flask tool, the default app is called <code>FlaskWebProject1</code>. If your app has a different name, you need to modify <code>web.config</code> in your <code>wwwroot</code> folder to reflect the correct app name. </p>
<p>Then redeploy using the Azure portal or change it in your GIT and push again.</p>
| 0 | 2016-10-05T02:20:57Z | [
"python",
"azure",
"flask",
"azure-web-sites"
]
|
calculating factorial of large numbers in 0.5 second with python | 39,790,221 | <p>I've been trying to find a super fast code that can calculate the factorial of a big number like 70000 in 0.5 second,My own code could do it in 10 seconds.I've searched everywhere, every code I find has memory error problem or is not as fast as I want. Can anyone help me with this?</p>
<pre><code>enter code here
import math
num =int(raw_input())
usefrm=0
if len(str(num)) > 2:
if int(str(num)[-2]) % 2 == 0:
usefrm = 'even'
else:
usefrm = 'odd'
else:
if num % 2 == 0:
usefrm = 'even1'
else:
usefrm = 'odd1'
def picknumber(num):
s = str(math.factorial(num))
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
def picknumber1(num):
s = str(num)
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
if usefrm == 'even':
e=picknumber1(6*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
if usefrm == 'odd':
e=picknumber1(4*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
else:
e=picknumber1(math.factorial(num))
print e
</code></pre>
| 0 | 2016-09-30T11:14:15Z | 39,790,388 | <p>Try to use the commutativity property of integer multiplication.</p>
<p>When multiplied numbers are long (they do not fit in a single word), the time necessary to perform the operation grows superlinearly with their length.</p>
<p>If you multiply the smallest (shortest in terms of memory representation) factors (and partial products) first, you may save a lot of time.</p>
| 0 | 2016-09-30T11:22:52Z | [
"python",
"factorial"
]
|
calculating factorial of large numbers in 0.5 second with python | 39,790,221 | <p>I've been trying to find a super fast code that can calculate the factorial of a big number like 70000 in 0.5 second,My own code could do it in 10 seconds.I've searched everywhere, every code I find has memory error problem or is not as fast as I want. Can anyone help me with this?</p>
<pre><code>enter code here
import math
num =int(raw_input())
usefrm=0
if len(str(num)) > 2:
if int(str(num)[-2]) % 2 == 0:
usefrm = 'even'
else:
usefrm = 'odd'
else:
if num % 2 == 0:
usefrm = 'even1'
else:
usefrm = 'odd1'
def picknumber(num):
s = str(math.factorial(num))
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
def picknumber1(num):
s = str(num)
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
if usefrm == 'even':
e=picknumber1(6*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
if usefrm == 'odd':
e=picknumber1(4*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
else:
e=picknumber1(math.factorial(num))
print e
</code></pre>
| 0 | 2016-09-30T11:14:15Z | 39,790,889 | <p>For most practical use, the <a href="https://en.wikipedia.org/wiki/Stirling%27s_approximation" rel="nofollow">Stirling's approximation</a> is very fast and quite accurate</p>
<pre><code>import math
from decimal import Decimal
def fact(n):
d = Decimal(n)
return (Decimal(2 * math.pi) * d).sqrt() * (d / Decimal(math.e)) ** d
print(fact(70000))
1.176811014417743803074731978E+308759
</code></pre>
| 0 | 2016-09-30T11:51:28Z | [
"python",
"factorial"
]
|
calculating factorial of large numbers in 0.5 second with python | 39,790,221 | <p>I've been trying to find a super fast code that can calculate the factorial of a big number like 70000 in 0.5 second,My own code could do it in 10 seconds.I've searched everywhere, every code I find has memory error problem or is not as fast as I want. Can anyone help me with this?</p>
<pre><code>enter code here
import math
num =int(raw_input())
usefrm=0
if len(str(num)) > 2:
if int(str(num)[-2]) % 2 == 0:
usefrm = 'even'
else:
usefrm = 'odd'
else:
if num % 2 == 0:
usefrm = 'even1'
else:
usefrm = 'odd1'
def picknumber(num):
s = str(math.factorial(num))
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
def picknumber1(num):
s = str(num)
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
if usefrm == 'even':
e=picknumber1(6*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
if usefrm == 'odd':
e=picknumber1(4*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
else:
e=picknumber1(math.factorial(num))
print e
</code></pre>
| 0 | 2016-09-30T11:14:15Z | 39,791,477 | <p>If you don't want a perfect precision, you can use the Stirling's approximation
<a href="https://en.wikipedia.org/wiki/Stirling's_approximation" rel="nofollow">https://en.wikipedia.org/wiki/Stirling's_approximation</a></p>
<pre><code>import np
n! ~ np.sqrt(2*np.pi*n)*(n/np.e)**n
</code></pre>
<p>for large n values. This calculation is literally instantaneous.</p>
| 0 | 2016-09-30T12:24:03Z | [
"python",
"factorial"
]
|
calculating factorial of large numbers in 0.5 second with python | 39,790,221 | <p>I've been trying to find a super fast code that can calculate the factorial of a big number like 70000 in 0.5 second,My own code could do it in 10 seconds.I've searched everywhere, every code I find has memory error problem or is not as fast as I want. Can anyone help me with this?</p>
<pre><code>enter code here
import math
num =int(raw_input())
usefrm=0
if len(str(num)) > 2:
if int(str(num)[-2]) % 2 == 0:
usefrm = 'even'
else:
usefrm = 'odd'
else:
if num % 2 == 0:
usefrm = 'even1'
else:
usefrm = 'odd1'
def picknumber(num):
s = str(math.factorial(num))
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
def picknumber1(num):
s = str(num)
l = []
for n in s:
if int(n) != 0:
l.append(int(n))
return l[-1]
if usefrm == 'even':
e=picknumber1(6*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
if usefrm == 'odd':
e=picknumber1(4*picknumber(int(num/5))*picknumber(int(str(num)[-1])))
else:
e=picknumber1(math.factorial(num))
print e
</code></pre>
| 0 | 2016-09-30T11:14:15Z | 39,791,501 | <p>You may use <code>math.factorial()</code>. For example:</p>
<pre><code>from math import factorial
factorial(7000)
</code></pre>
<p>with <strong>execution time of 20.5 msec</strong> for calculating the factorial of <em>7000</em>:</p>
<pre><code>python -m timeit -c "from math import factorial; factorial(7000)"
10 loops, best of 3: 20.5 msec per loop
</code></pre>
| 0 | 2016-09-30T12:25:08Z | [
"python",
"factorial"
]
|
Bubble Sort in PHP and Python | 39,790,316 | <p>As far as I can tell, these two programs should do exactly the same thing. However, the Python version works and the PHP one doesn't. What am I missing please?</p>
<pre><code>def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
my_list = [2,3,5,4,1]
bubbleSort(my_list)
print(my_list)
</code></pre>
<hr>
<pre><code><?php
// Bubble Sort
$my_list = [2,3,5,4,1];
function bubble_sort($arr){
$size = count($arr);
for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
for($i = 0; $i < $pass_num; $i++){
if($arr[i] > $arr[$i + 1]){
swap($arr, $arr[i], $arr[$i+1]);
}
}
}
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
bubble_sort($my_list);
print_r ($my_list);
</code></pre>
| 1 | 2016-09-30T11:19:32Z | 39,790,581 | <p>The sort is in fact working, but as you dont pass a reference to the <code>bubble_sort($arr)</code> function you never get to see the actual result. Telling <code>bubble_sort()</code> that the array is being passed by reference means you are changing <code>$my_list</code> and not a copy of <code>$my_list</code></p>
<p>Oh and you had some compile errors, using <code>$arr[i]</code> instead of <code>$arr[$i]</code></p>
<pre><code>// Bubble Sort
$my_list = [2,3,5,4,1];
function bubble_sort(&$arr){ // <-- changed to &$arr
$size = count($arr);
for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
for($i = 0; $i < $pass_num; $i++){
if($arr[$i] > $arr[$i + 1]){
// also changed this line to pass just the indexes
swap($arr, $i, $i+1);
}
}
}
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
bubble_sort($my_list);
print_r ($my_list);
</code></pre>
<p>If you are testing this on a live server where error reporting is turned off add these lines to the top of any script you are developing, while you are developing it.</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
</code></pre>
<p>And the compile errors would have shown on the web page</p>
| 1 | 2016-09-30T11:33:07Z | [
"php",
"python",
"bubble-sort"
]
|
How to generate unique name for each JSON value | 39,790,342 | <p>I have following JSON, returned from a REST service, where I want to generate a unique names for each value by combining parent keys. For example. <code>name+phone+address+city+name</code> , <code>name+phone+address+city+population+skilled+male</code> and so on. </p>
<pre><code>{
"name": "name",
"phone": "343444444",
"address": {
"lat": 23.444,
"lng": 34.3322,
"city":{
"name": "city name",
"population": {
"skilled": {
"male": 2,
"female": 4
},
"uneducated": {
"male": 20,
"femail": 4
}
}
}
},
"email": "email",
"education": "phd"
}
</code></pre>
<p>I want to combine all key names starting from the parent of the JSON tree.</p>
<p>Here is what I am doing</p>
<pre><code>class TestJson
def walk_through(self, json_object):
for k, v in json_object.items():
self.x_path = self.x_path + k
if type(v) is dict:
self.walk_through(v)
else:
print(self.x_path)
self.x_path = ""
</code></pre>
<p>This code is printing keys but only starting from the current parent node. I want to combine all keys up to root of the json. </p>
| -3 | 2016-09-30T11:20:44Z | 39,791,176 | <p>If you want to print all keys of your python dict you can do the following:</p>
<pre><code>def print_keys(d):
for key, value in d.iteritems():
print key,
if isinstance(value, dict):
print_keys(value)
</code></pre>
| 0 | 2016-09-30T12:07:22Z | [
"python",
"json",
"python-3.x"
]
|
How to generate unique name for each JSON value | 39,790,342 | <p>I have following JSON, returned from a REST service, where I want to generate a unique names for each value by combining parent keys. For example. <code>name+phone+address+city+name</code> , <code>name+phone+address+city+population+skilled+male</code> and so on. </p>
<pre><code>{
"name": "name",
"phone": "343444444",
"address": {
"lat": 23.444,
"lng": 34.3322,
"city":{
"name": "city name",
"population": {
"skilled": {
"male": 2,
"female": 4
},
"uneducated": {
"male": 20,
"femail": 4
}
}
}
},
"email": "email",
"education": "phd"
}
</code></pre>
<p>I want to combine all key names starting from the parent of the JSON tree.</p>
<p>Here is what I am doing</p>
<pre><code>class TestJson
def walk_through(self, json_object):
for k, v in json_object.items():
self.x_path = self.x_path + k
if type(v) is dict:
self.walk_through(v)
else:
print(self.x_path)
self.x_path = ""
</code></pre>
<p>This code is printing keys but only starting from the current parent node. I want to combine all keys up to root of the json. </p>
| -3 | 2016-09-30T11:20:44Z | 39,792,230 | <p>If you ignore the <code>name</code> and <code>phone</code> keys, since they are not ancestors of <code>city name</code> or <code>skilled male</code> and the order of keys is not guaranteed, you can recursively build a flattened dict. </p>
<pre><code>def walk_through(json_object):
d = {}
for k, v in json_object.items():
if isinstance(v, dict):
v = walk_through(v)
for vk, vv in v.items():
d["%s+%s" % (k, vk)] = vv
else:
d[k] = v
return d
print(json.dumps(walk_through(json_object), indent=2))
</code></pre>
<p>This prints:</p>
<pre><code>{
"address+city+population+skilled+male": 2,
"name": "name",
"address+lng": 34.3322,
"address+city+name": "city name",
"address+lat": 23.444,
"address+city+population+uneducated+male": 20,
"phone": "343444444",
"address+city+population+uneducated+femail": 4,
"education": "phd",
"email": "email",
"address+city+population+skilled+female": 4
}
</code></pre>
<p><strong>Note:</strong> this ignores lists an will not find dicts inside them.</p>
| 1 | 2016-09-30T13:03:31Z | [
"python",
"json",
"python-3.x"
]
|
Docker for windows10 run django fail: Can't open file 'manage.py': [Errno 2] No such file or directory | 39,790,384 | <p>I just start a sample django app. And use docker to run it. My docker image like:</p>
<pre><code>FROM python:3.5
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/
</code></pre>
<p>My docker-compose.yml file:</p>
<pre><code>version: '2'
services:
django:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- "8000:8000"
</code></pre>
<p>When I run <code>docker-compose up</code> command,it build successfully but failed in running <code>command: python manage.py runserver 0.0.0.0:8000</code>,it complained <code>python: can't open file 'manage.py': [Errno 2] No such file or directory</code>.</p>
<p>Is this a bug in docker for windows? Because I just follow the docs of docker <a href="https://docs.docker.com/compose/django/" rel="nofollow">Quickstart: Docker Compose and Django</a></p>
<p>Thank for you help!</p>
| 2 | 2016-09-30T11:22:39Z | 39,795,499 | <p>I think you either missed this step: <code>docker-compose run web django-admin.py startproject composeexample .</code> or you're using a directory that isn't available to the Virtual Machine that is running docker.</p>
<p>If it works when you remove <code>volumes: .:/code</code> from the Compose file, then you know the issue is the volumes.</p>
<p>I believe by default only the users home directory is shared with the VM, so if you create a project outside of that tree, you won't have access to the files from volumes.</p>
| 1 | 2016-09-30T15:54:39Z | [
"python",
"django",
"docker",
"docker-compose",
"cookiecutter-django"
]
|
openpyxl if condition formula with reference fails | 39,790,457 | <p>Using python 2.7 and openpyxl, I am inserting an IF formula into excel worksheet that references fields in other sheet.</p>
<p>While other formulas work (CONTIF, COUTN, SUM, etc) I kind of do not find the reason for this "simple" IF formula does not to work. Only IF is the problem</p>
<p>This is my code </p>
<pre><code>for i in range(0,len(sortedWorkers)):
for a, rr in enumerate(dates):
row_nb = i + 3
coll = 3 + a
clmn_letter = get_column_letter(coll + 3)
# =IF(Worked!I$2=7;Worked!I3;"")
valFormula = '=IF(Worked!%s$2=7;Worked!%s%s;"")' %(clmn_letter,clmn_letter, str(row_nb))
_cl = ws12.cell(column= coll, row= row_nb, value=valFormula)
</code></pre>
<p>in the comment you can se the formula. The format is correct. It also works if I manually insert it into excel.</p>
<p>Also field coordinates and everything matches. </p>
<p>Any suggestions?
Thank you</p>
| 0 | 2016-09-30T11:26:48Z | 39,790,987 | <p>Formulas are sometimes serialised in the XML differently than they appear in the GUI. They may have prefixes, or use different words, or, and I think this may be the case here, they use different separators between parameters. In countries which use a comma as the decimal separator, semi-colons are used to separate parameters in the GUI, but the XML will use commas.</p>
<p>You can check this by looking at the source of a file created by Excel.</p>
| 1 | 2016-09-30T11:57:01Z | [
"python",
"excel",
"openpyxl"
]
|
openpyxl if condition formula with reference fails | 39,790,457 | <p>Using python 2.7 and openpyxl, I am inserting an IF formula into excel worksheet that references fields in other sheet.</p>
<p>While other formulas work (CONTIF, COUTN, SUM, etc) I kind of do not find the reason for this "simple" IF formula does not to work. Only IF is the problem</p>
<p>This is my code </p>
<pre><code>for i in range(0,len(sortedWorkers)):
for a, rr in enumerate(dates):
row_nb = i + 3
coll = 3 + a
clmn_letter = get_column_letter(coll + 3)
# =IF(Worked!I$2=7;Worked!I3;"")
valFormula = '=IF(Worked!%s$2=7;Worked!%s%s;"")' %(clmn_letter,clmn_letter, str(row_nb))
_cl = ws12.cell(column= coll, row= row_nb, value=valFormula)
</code></pre>
<p>in the comment you can se the formula. The format is correct. It also works if I manually insert it into excel.</p>
<p>Also field coordinates and everything matches. </p>
<p>Any suggestions?
Thank you</p>
| 0 | 2016-09-30T11:26:48Z | 39,874,517 | <p>So at the end the whole problem was that with using IF formula commas have to be used "," not semi-colons ";"</p>
<p>NB you must use the English name for a function and function arguments must be separated by commas and not other punctuation such as semi-colons.</p>
| 0 | 2016-10-05T12:52:40Z | [
"python",
"excel",
"openpyxl"
]
|
How the generate this specific chart in Python / Matplotlib | 39,790,566 | <p>I need to plot this specific chart in Python, or at least come very close to it, see the picture. I prefer to use the Matplotlib package and I already tried to a great extend but didn't came close enough. If I need another package for this then I am ok with that. </p>
<p><a href="http://i.stack.imgur.com/dGJ64.png" rel="nofollow"><img src="http://i.stack.imgur.com/dGJ64.png" alt="enter image description here"></a></p>
| -3 | 2016-09-30T11:32:32Z | 39,828,327 | <p>Well, this is an attempt for an answer, unfortunately it is not categorical. </p>
<pre><code>import matplotlib.pyplot as plt
# example data
x = (1, 2, 3, 4)
y = (1, 2, 3, 4)
# example variable error bar values
yerr = [[0.2, 0.1, 0.5, 0.35], [0.7, 0.7, 0.3, 0.2]]
plt.figure()
plt.errorbar(x, y, yerr=yerr, fmt="r^")
plt.show()
</code></pre>
<p>Will generate this picture:
<a href="http://i.stack.imgur.com/5Hn4V.png" rel="nofollow"><img src="http://i.stack.imgur.com/5Hn4V.png" alt="Output picture"></a></p>
| 0 | 2016-10-03T09:24:43Z | [
"python",
"matplotlib",
"charts"
]
|
How the generate this specific chart in Python / Matplotlib | 39,790,566 | <p>I need to plot this specific chart in Python, or at least come very close to it, see the picture. I prefer to use the Matplotlib package and I already tried to a great extend but didn't came close enough. If I need another package for this then I am ok with that. </p>
<p><a href="http://i.stack.imgur.com/dGJ64.png" rel="nofollow"><img src="http://i.stack.imgur.com/dGJ64.png" alt="enter image description here"></a></p>
| -3 | 2016-09-30T11:32:32Z | 39,960,312 | <p>By searching the web (found most of the answers on this site) and a lot of trail and error I was able to generate the following chart:</p>
<p><a href="http://i.stack.imgur.com/HbfU8.png" rel="nofollow">enter image description here</a></p>
<p>These were the 3 key elements in the global construction of the chart:</p>
<ul>
<li>Using <code>axhspan</code> or <code>axvspan</code> it is easy to partition the background into different colors independently of whatever chart type is choosen.</li>
<li>Scatter plot was the chart type used for ploting the single points.</li>
<li>Adding a table at the bottom for displaying the values. I did not expect it but the table is independent of the chart and the creator of the chart is free to fill it with any data he or she desires. </li>
</ul>
<p>As you can see I came very close to my desired chart. I am open for suggestions for non-obvious refactoring. </p>
<p>Some things however are still not perfect yet:</p>
<ol>
<li>I do not display percentages yet. It is easy to do by formatting to percentages but then I 'll need to multiply everything by 100. Is there a more elegant method without the need to multiply everything by 100?</li>
<li>Can I display the scatter symbols to the legend in the table on the left just like in my chart from the question? Otherwise I might plot a legend on the right side of the chart.</li>
<li>I am struggling a bit with anti-aliasing. When using the <code>savefig</code> command I want to font to be anti aliased but the graphics not. What is the best way to do this?</li>
<li>I still have to manually plot 3 + 1 = 4 lines. One of them is the horizontal zero ax. The other 3 lines are to connect the scatter points. Is there a clever solution to avoid this? </li>
<li>Would plotly give me a better and easier way of creating the same chart?</li>
</ol>
<p>The complete code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
# Given data
data = [[0.129, 0.031, 0.071],
[0.067, -0.041, 0.012],
[-0.013, -0.08, -0.07]]
columns = ['Apple', 'Orange', 'Banana']
rows = ['top', 'mid', 'bottom']
# This code is only necessary for the chart to look as intended on the screen
# Probably need to be removed when saving chart as a picture using the savefig
# command
plt.figure().patch.set_facecolor('white')
# set global line color of the axes
plt.rc('axes', edgecolor='#cecece')
# partition chart background into 3 strokes of different colors
pastel_shades = ['#ffefb7', '#e6fff2', '#f5feda']
for i in range(3):
plt.axvspan(i, i + 1, facecolor=pastel_shades[i], linewidth=0)
# (cosmetic) marker settings
markers = [('D', "#0070c0", 0),
('_', "#ff0000", 2),
('s', "#0070c0", 0)]
# Add a table at the bottom of the axes
the_table = plt.table(cellText=data,
rowLabels=rows,
colLabels=columns,
loc='bottom',
cellLoc='center')
# set fontsize and fontcolor of values in table
# adjust vertical height
# set table border color
the_table.set_fontsize(9)
the_table.scale(1.0, 1.3)
for key, cell in the_table.get_celld().items():
cell.set_edgecolor('#cecece')
cell._text.set_color("#595959")
# Adjust layout to make room for the table
plt.subplots_adjust(left=0.2, bottom=0.2)
# set color and fontsize of the labels at the y-ax ticks
for tl in plt.axes().get_yticklabels():
tl.set_color("#595959")
tl.set_fontsize(7)
# set other axes properties
plt.ylabel("Y-axis", color="#595959")
plt.tick_params(axis='y', direction='out', right='off', color='#cecece')
plt.xticks([])
# Set chart title
plt.title('Chart title', color="#595959")
# Draw horizontal zero-ax
plt.axhline(0, 0, 1, color='#cecece', zorder=1)
# draw scatter plot
plt.axes().set_xlim([0, 3])
for data_row, marker in zip(data, markers):
x = np.array([0.5, 1.5, 2.5])
y = np.array(data_row)
shape, color, width = marker
plt.scatter(x, y,
s=60,
c=color,
zorder=3,
marker=shape,
linewidths=width,
edgecolors=color)
# Draw lines connecting the scatter points
vertical_data_slice = [[r[k] for r in data] for k in range(3)]
for data_column, x in zip(vertical_data_slice, np.array([0.5, 1.5, 2.5])):
plt.vlines(x, data_column[0], data_column[2], colors="#000000", zorder=2)
# Show chart on screen
plt.show()
</code></pre>
| 0 | 2016-10-10T14:12:00Z | [
"python",
"matplotlib",
"charts"
]
|
LMDB database for training of caffe convolutional network | 39,790,578 | <p>I am new to python and caffe and want to set up a convolutional network that takes images as input and gives processed images as output.
What I understood from some internet research was that caffe can take lmdb databases as input for training.
My question now is how to make a database entry with two images (raw and processed) for training.</p>
<p>If this has been solved somewhere and I did not find it, please post a link.</p>
<p>Thanks a lot!</p>
| 0 | 2016-09-30T11:33:01Z | 39,876,076 | <p>you can, but don't have to make <code>lmdb</code> file as input. try this <a href="http://mi.eng.cam.ac.uk/projects/segnet/tutorial.html" rel="nofollow">tutorial</a>. good luck.</p>
| 0 | 2016-10-05T14:01:22Z | [
"python",
"deep-learning",
"caffe",
"lmdb"
]
|
Tensorflow equivalent of Theano's dimshuffle | 39,790,829 | <p>How can I find the Tensorflow equivalent of Theano's dimshuffle function.</p>
<pre><code>mask = mask.dimshuffle(0, 1, "x")
</code></pre>
<p>I'm doing this I have tried many ways but couldn't find. Thank you :)</p>
| 1 | 2016-09-30T11:47:55Z | 39,792,376 | <p>You can use <a href="https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#transpose" rel="nofollow"><code>tf.transpose</code></a>:</p>
<pre><code> mask = tf.transpose(mask, perm=[0, 1])
</code></pre>
| 1 | 2016-09-30T13:11:19Z | [
"python",
"tensorflow",
"deep-learning",
"theano"
]
|
Getting a tuple in a Dafaframe into multiple rows | 39,790,830 | <p>I have a Dataframe, which has two columns (Customer, Transactions).
The Transactions column is a tuple of all the transaction id's of that customer.</p>
<pre><code>Customer Transactions
1 (a,b,c)
2 (d,e)
</code></pre>
<p>I want to convert this into a dataframe, which has customer and transaction id's, like this.</p>
<pre><code>Customer Transactions
1 a
1 b
1 c
2 d
2 e
</code></pre>
<p>We can do it using loops, but is there a straight 1 or 2 lines way for doing that.</p>
| 1 | 2016-09-30T11:47:57Z | 39,790,938 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor:</p>
<pre><code>df = pd.DataFrame({'Customer':[1,2],
'Transactions':[('a','b','c'),('d','e')]})
print (df)
Customer Transactions
0 1 (a, b, c)
1 2 (d, e)
df1 = pd.DataFrame(df.Transactions.values.tolist(), index=df.Customer)
print (df1)
0 1 2
Customer
1 a b c
2 d e None
</code></pre>
<p>Then reshape with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>:</p>
<pre><code>print (df1.stack().reset_index(drop=True, level=1).reset_index(name='Transactions'))
Customer Transactions
0 1 a
1 1 b
2 1 c
3 2 d
4 2 e
</code></pre>
| 1 | 2016-09-30T11:54:05Z | [
"python",
"pandas",
"dataframe",
"tuples",
"reshape"
]
|
Getting a tuple in a Dafaframe into multiple rows | 39,790,830 | <p>I have a Dataframe, which has two columns (Customer, Transactions).
The Transactions column is a tuple of all the transaction id's of that customer.</p>
<pre><code>Customer Transactions
1 (a,b,c)
2 (d,e)
</code></pre>
<p>I want to convert this into a dataframe, which has customer and transaction id's, like this.</p>
<pre><code>Customer Transactions
1 a
1 b
1 c
2 d
2 e
</code></pre>
<p>We can do it using loops, but is there a straight 1 or 2 lines way for doing that.</p>
| 1 | 2016-09-30T11:47:57Z | 39,791,660 | <p>I think following is faster:</p>
<pre><code>import numpy as np
import random
import string
import pandas as pd
from itertools import chain
customer = np.unique(np.random.randint(0, 1000000, 100000))
transactions = [tuple(string.ascii_letters[:random.randint(3, 10)]) for _ in range(len(customer))]
df = pd.DataFrame({"customer":customer, "transactions":transactions})
df2 = pd.DataFrame({
"customer": np.repeat(df.customer.values, df.transactions.str.len()),
"transactions": list(chain.from_iterable(df.transactions))})
</code></pre>
| 0 | 2016-09-30T12:34:29Z | [
"python",
"pandas",
"dataframe",
"tuples",
"reshape"
]
|
python: can't open file get-pip.py error 2] no such file or directory | 39,790,923 | <p>when I am trying to execute this in CMD</p>
<pre><code>python get-pip.py
</code></pre>
<p>I am getting this
python: can't open file get-pip.py error 2] no such file or directory</p>
<p>while the file store in (get-pip.py)</p>
<blockquote>
<p>C:\Python27\Tools\Scripts</p>
</blockquote>
| 0 | 2016-09-30T11:53:22Z | 39,790,976 | <p>Try to either <code>cd</code> into folder with script (<code>cd "C:\Python27\Tools\Scripts"</code>) or add this folder to your PATH variable.</p>
| 1 | 2016-09-30T11:56:29Z | [
"python"
]
|
Setting an index limit in SQLAlchemy | 39,791,026 | <p>I would like to set up a maximum limit for an index within a <code>Column</code> definition or just through the <code>Index</code> constructor but I don't seem to find a way to achieve it.</p>
<p>Basically, I would like to simulate this MySQL behaviour:</p>
<pre><code>CREATE TABLE some_table (
id int(11) NOT NULL AUTO_INCREMENT,
some_text varchar(2048) DEFAULT NULL,
PRIMARY KEY (id),
KEY some_text (some_text(1024)), # <- this line
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPRESSED;
</code></pre>
<p>In SQLAlchemy I would have something like:</p>
<pre><code>class SomeTable(BaseModel):
__tablename__ = 'some_table'
__seqname__ = 'some_table_id_seq'
id = sa.Column(sa.Integer(11), sa.Sequence(__seqname__), primary_key=True)
some_text = sa.Column(sa.String(2048), index=True) # <- this line
</code></pre>
<p>but I can't find anything that would suggest the limit of the index can be customised. Something like:</p>
<pre><code>some_text = sa.Column(sa.String(2048), index=True, index_length=1024)
</code></pre>
<p>I guess since this option for the <code>Column</code> constructor is just an alias for the <code>Index</code> constructor, is there a custom param to include in the <code>Index</code> constructor to allow this setting?</p>
<p>Thanks!</p>
| 2 | 2016-09-30T11:59:14Z | 39,791,161 | <p>I think you can do something like: </p>
<pre><code>class SomeTable(BaseModel):
__tablename__ = 'some_table'
__seqname__ = 'some_table_id_seq'
__table_args__ = (
sa.Index("idx_some_text", "some_text", mysql_length=1024),
)
id = sa.Column(sa.Integer(11), sa.Sequence(__seqname__), primary_key=True)
some_text = sa.Column(sa.String(2048))
</code></pre>
<p>Reference:
<a href="http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#index-length" rel="nofollow">http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#index-length</a></p>
| 3 | 2016-09-30T12:06:48Z | [
"python",
"mysql",
"indexing",
"sqlalchemy"
]
|
How to append a list of csr matrices | 39,791,088 | <p>I have a list of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow">csr matrices</a> in a list called <code>L</code>. All the matrices have the same dimension which is <code>1</code> by <code>100000</code>. How can I append them so I end up with one csr matrix of dimension <code>len(L)</code> by <code>100000</code>?</p>
| 0 | 2016-09-30T12:03:12Z | 39,791,169 | <p>I think a <em>vertical stack</em> i.e. <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.sparse.vstack.html" rel="nofollow"><code>vstack</code></a> will do:</p>
<pre><code>from scipy.sparse import vstack
new_array = vstack(L).toarray()
</code></pre>
| 3 | 2016-09-30T12:07:09Z | [
"python",
"scipy"
]
|
Changing the proxy server during Selenium | 39,791,242 | <p>So everything works</p>
<pre><code>fp = webdriver.FirefoxProfile()
fp.set_preference("network.proxy.type", 1)
fp.set_preference("network.proxy.http", PROXY_HOST)
fp.set_preference("network.proxy.http_port", int(PROXY_PORT))
fp.update_preferences()
driver = webdriver.Firefox(firefox_profile=fp)
</code></pre>
<p>But if the driver has already been created, the proxy can not install.
It does not work</p>
<pre><code>driver = webdriver.Firefox()
driver.profile.set_preference("network.proxy.type", 1)
driver.profile.set_preference("network.proxy.http", PROXY_HOST)
driver.profile.set_preference("network.proxy.http_port", int(PROXY_PORT))
driver.profile.update_preferences()
</code></pre>
<p>And so, too.</p>
<pre><code> driver = webdriver.Firefox()
driver.firefox_profile.set_preference("network.proxy.type", 1)
driver.firefox_profile.set_preference("network.proxy.http", PROXY_HOST)
driver.firefox_profile.set_preference("network.proxy.http_port", int(PROXY_PORT))
driver.firefox_profile.update_preferences()
</code></pre>
<p>Why? Can not understand.
I'm doing something wrong?</p>
| 0 | 2016-09-30T12:11:16Z | 39,810,577 | <p>When using WebDriver with Firefox, the use of the profile is a one-time thing. When the driver launches the browser, it writes the profile object to disk, then starts the browser executable. After that point, there is no mechanism for the browser to read any further changes to the WebDriver profile object. To change the proxy, you have to set the settings in the profile before the browser is launched.</p>
| 0 | 2016-10-01T19:17:19Z | [
"python",
"selenium",
"selenium-webdriver",
"proxy",
"updates"
]
|
How do I install a .whl file in a PyCharm virtualenv? | 39,791,243 | <p>The package manager in Project Interpreter doesn't appear to have any way for me to run a pure pip command so I'm unable to install the wheel as I normally would through command line.</p>
<p>Running through command line installs the wheel on my base python install and not the virtualenv. Help?</p>
| 2 | 2016-09-30T12:11:18Z | 39,791,424 | <p>To install via your command line, and avoid installing on your <em>base</em> Python, you'll have to first <em>activate</em> the <code>virtualenv</code>:</p>
<pre><code>$ source path_to_your_venv/bin/activate
</code></pre>
<p>for POSIX systems, and:</p>
<pre><code>> path_to_venv\Scripts\activate
</code></pre>
<p>for Windows systems (<code>.whl</code> only pertains to Windows)</p>
<p>And then <code>pip install</code> the <code>.whl</code> file.</p>
| 1 | 2016-09-30T12:21:04Z | [
"python",
"python-2.7",
"python-3.x",
"pycharm"
]
|
calculate number ticks from outside of the .net framework | 39,791,257 | <p>Does anyone know how to calculate the number of .net time ticks from outside of the .net framework? my situation involves a python script on Linux (my side) needing to send a timestamp as the number of ticks in a message destined for a C# process (the other side, who can't change its code). I can't find any libraries that do this... Any thoughts? Thanks! </p>
| 0 | 2016-09-30T12:12:12Z | 39,792,175 | <p>You can easily determine what the Unix/Linux epoch (1970-01-01 00:00:00) is in DateTime ticks:</p>
<pre><code>DateTime netTime = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(netTime.Ticks);
// Prints 621355968000000000
</code></pre>
<p>Since the Unix/Linux timestamp is the number of seconds since 1970-01-01 00:00:00, you can convert that to 100ns ticks by multiplying it by <code>10000000</code>, and then convert it to DateTime ticks by adding <code>621355968000000000</code>:</p>
<pre><code>long netTicks = 621355968000000000L + 10000000L * linuxTimestamp;
</code></pre>
| 1 | 2016-09-30T13:01:10Z | [
"c#",
"python",
".net",
"timestamp"
]
|
Create Excel Hyperlinks in Python | 39,791,441 | <p>I am using win32com to modify an Excel spreadsheet (Both read and edit at the same time) I know there are other modules out there that can do one or the other but for the application I am doing I need it read and processed at the same time.</p>
<p>The final step is to create some hyperlinks off of a path name. Here is an Example of what I have so far:</p>
<pre><code>import win32com.client
excel = r'I:\Custom_Scripts\Personal\Hyperlinks\HyperlinkTest.xlsx'
xlApp = win32com.client.Dispatch("Excel.Application")
workbook = xlApp.Workbooks.Open(excel)
worksheet = workbook.Worksheets("Sheet1")
for xlRow in xrange(1, 10, 1):
a = worksheet.Range("A%s"%(xlRow)).Value
if a == None:
break
print a
workbook.Close()
</code></pre>
<p>I found some code for reading Hyperlinks using win32com:</p>
<pre><code>sheet.Range("A8").Hyperlinks.Item(1).Address
</code></pre>
<p>but not how to set hyperlinks</p>
<p>Can someone assist me?</p>
| 0 | 2016-09-30T12:21:56Z | 39,791,989 | <p>Borrowing heavily from <a href="https://www.experts-exchange.com/questions/21349668/Using-win32com-with-Python.html" rel="nofollow">this</a> question, as I couldn't find anything on SO to link to as a duplicate...</p>
<p>This code will create a Hyperlink in cells <code>A1:A9</code></p>
<pre><code>import win32com.client
excel = r'I:\Custom_Scripts\Personal\Hyperlinks\HyperlinkTest.xlsx'
xlApp = win32com.client.Dispatch("Excel.Application")
workbook = xlApp.Workbooks.Open(excel)
worksheet = workbook.Worksheets("Sheet1")
for xlRow in xrange(1, 10, 1):
worksheet.Hyperlinks.Add(Anchor = worksheet.Range('A{}'.format(xlRow)),
Address="http://www.microsoft.com",
ScreenTip="Microsoft Web Site",
TextToDisplay="Microsoft")
workbook.Save()
workbook.Close()
</code></pre>
<p>And here is a link to the <a href="https://msdn.microsoft.com/en-us/library/office/ff822490.aspx?f=255&MSPPError=-2147217396" rel="nofollow">Microsoft Documentation</a> for the <code>Hyperlinks.Add()</code> method.</p>
| 1 | 2016-09-30T12:52:09Z | [
"python",
"excel",
"python-2.7",
"win32com"
]
|
Create list of given length with given values - convert histogram to list of values | 39,791,535 | <p>I have a histogram which I need to convert into a list of individual instances for another piece of software I am using: If I have four hits for a value of "1" and three hits for a value of "2" then my list would need to read <code>[1,1,1,1,2,2,2]</code>.</p>
<p>My histogram is structured as two numpy arrays packed into a list called <code>hist</code>, say. The array in <code>hist[1]</code> stores my bin edges, the array in <code>hist[0]</code> stores the counts for each bin.</p>
<p>A very crude way of achieving this conversion would be to simply run the following code:</p>
<pre><code>inhist=[]
for i in range(len(hist[0])):
for j in xrange(int(hist[0][i])):
inhist.append(int(hist[1][i]))
</code></pre>
<p>Is there a better way of doing this? Particularly as the histogram gets very large this will presumably not be the most efficient way of achieving this anymore. Seeing as I know precisely how many time I want a certain value I wonder if I could save myself all that looping? </p>
<p>I realise doing this whole thing in general will eat RAM and isn't terribly efficient but, alas, I have little choice at the moment.</p>
<p>EDIT:
<code>print hist</code> returns:</p>
<pre><code>[array([ 0.00000000e+00, 1.83413630e+07, 1.74493106e+09,
7.91390628e+10, 4.54474023e+11, 5.38810039e+11,
3.01718080e+11, 1.38440761e+11, 6.17865624e+10,
2.77457730e+10, 1.32412328e+10, 6.71579967e+09,
3.35556066e+09, 2.00513046e+09, 1.18435261e+09,
7.34440685e+08, 5.13846805e+08, 3.97894623e+08,
1.97770421e+08, 1.11546165e+08, 6.63624300e+07,
3.93196820e+07, 2.81038760e+07, 1.87733930e+07,
1.57307950e+07, 1.55162030e+07, 1.38710060e+07,
3.52969100e+06, 2.32881000e+05, 5.32210000e+04,
1.59100000e+04, 4.89700000e+03, 1.61300000e+03,
6.54000000e+02, 2.63000000e+02, 1.08000000e+02,
3.10000000e+01, 8.00000000e+00, 4.00000000e+00,
2.00000000e+00]),
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40], dtype=uint64)]
</code></pre>
| 2 | 2016-09-30T12:26:54Z | 39,791,670 | <p>Those <code>i</code> indices are basically range of elements ranging for the length of number of <code>hist[0]</code> elements repeated by the numbers present in that first array <code>hist[0]</code> itself. Using those we simply index into the second array <code>hist[1]</code> to give us the desired output. For the <code>repeat</code> part, we could use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.repeat.html" rel="nofollow"><code>np.repeat</code></a>.</p>
<p>So, we would have an implementation, like so -</p>
<pre><code>inhist = hist[1][np.arange(len(hist[0])).repeat(hist[0])]
</code></pre>
<p>Being a vectorized solution that avoids appending elements off NumPy arrays, this should be pretty efficient.</p>
<p>Also, if we are working with NumPy arrays of floating point numbers, we might need to convert to <code>int</code> dtype. So, feed in <code>hist[0].astype(int)</code> and if the output is needed as <code>int</code> dtype too, use the same conversion on it, like so -</p>
<pre><code>inhist = hist[1][np.arange(len(hist[0])).repeat(hist[0].astype(int))]
</code></pre>
| 2 | 2016-09-30T12:34:57Z | [
"python",
"arrays",
"list",
"numpy"
]
|
Integer matrix to stochastic matrix normalization | 39,791,643 | <p>Suppose I have matrix with integer values. I want to make it stochastic matrix (i.e. sum of each row in matrix equal to 1)</p>
<p>I create random matrix, count sum of each row and divide each element in row for row sum.</p>
<pre><code>dt = pd.DataFrame(np.random.randint(0,10000,size=10000).reshape(100,100))
dt['sum_row'] = dt.sum(axis=1)
for col_n in dt.columns[:-1]:
dt[col_n] = dt[col_n] / dt['sum_row']
</code></pre>
<p>After this sum of each row should be equal to 1. But it is not.</p>
<pre><code>(dt.sum_row_normalized == 1).value_counts()
> False 75
> True 25
> Name: sum_row_normalized, dtype: int64
</code></pre>
<p>I understand that some values is not exactly 1 but very close to it. Nevertheless, how can I normalize matrix correctly?</p>
| 0 | 2016-09-30T12:33:35Z | 39,792,848 | <p>You can't guarantee the floats will be exactly one, but you can check the closely to an arbitrary precision with <code>np.around</code>.</p>
<p>This is probably easier/faster without looping through pandas columns.</p>
<pre><code>X = np.random.randint(0,10000,size=10000).reshape(100,100)
X_float = X.astype(float)
Y = X_float/X_float.sum(axis=1)[:,np.newaxis]
sum(np.around(Y.sum(axis=1),decimals=10)==1) # is 100
</code></pre>
<p>(you don't need the <code>.astype(float)</code> step in python 3.x)</p>
| 1 | 2016-09-30T13:35:16Z | [
"python",
"pandas",
"numpy",
"normalization",
"stochastic"
]
|
How to number unique words on each individual line, not miss paragraph? | 39,791,891 | <p>Before anything I am reading English language and programming, but I am beginner now. So I did a lot of methods to learn EN ( self-study ) but finally I make a personal method to learn.<br>
So I collected a lot of <strong>short story</strong> then, read those, day after day. Now I am doing this method as usual.<br>
A week a go I started to learn <strong>perl one-liner</strong> and it was so useful to me.</p>
<p>However, I get into <code>perl -pe '$q=0; s/(\w+)/++Sq." ".$1'</code><br>
for content: </p>
<blockquote>
<p>just another<br>
perl hacker<br>
hacking perl code</p>
</blockquote>
<p>it become to: </p>
<blockquote>
<p>1.just 2.another<br>
1.perl 2.hacker<br>
1.hacking 2.perl 3.code</p>
</blockquote>
<p>Okay, after I saw this <strong>perl one-liner</strong> I got an idea </p>
<p>For example I read this short-story: </p>
<blockquote>
<ol>
<li><p>Morning<br>
He wakes up. He sees the sun rise. He brushes his teeth. His teeth are white. He puts on his clothes. His shirt is blue. His
shoes are yellow. His pants are brown. He goes downstairs. He gets a
bowl. He pours milk and cereal. He eats. He gets the newspaper. He
reads.</p></li>
<li><p>First<br>
Day of School He goes to class. There is an empty seat in front. He sits in the seat. He looks around. There are different
people. He says "hi" to the girl next to him. She smiles. The teacher
comes in. She closes the door. Everyone is silent. The first day of
school begins.</p></li>
<li><p>Water on the Floor<br>
She is thirsty. She gets a glass of water. She begins to walk. She drops the glass. There is water on the floor. The
puddle is big. She gets a mop. She wipes the water off. The floor is
clean. She gets another glass of water. She drinks it. She is happy.</p></li>
<li><p>Babysitting<br>
Casey wants a new car. She needs money. She decides to babysit. She takes care of the child. She feeds him lunch. She reads
him a story. The story is funny. The child laughs. Casey likes him.
The child's mom comes home. The child kisses Casey. Casey leaves. She
will babysit him again.</p></li>
</ol>
<p>5.a docter<br>
Sam is a doctor. He takes care of people. He smiles at them. He gives them medicine. He gives stickers to the younger
patients. The younger patients like him. They see him when they are
sick. He makes them feel better. This makes him happy. He loves his
job. He goes home proud.</p>
</blockquote>
<p>As you can see, it is very easy. But at the beginning, it is not easy for someone who just started to learn English. </p>
<p>So my idea is this. I want a script may be in <strong>bash</strong> or <strong>perl</strong> that I think <strong>perl</strong> is better, that script can read a lot of <strong>short-story</strong> that I have and for each unique work, it number the word in the place. </p>
<p>For example in the above context that I put, I want something like this: </p>
<blockquote>
<p>1.He 2.wakes 3.up. He 4.sees 5.the 6.sun 7.rise. He 8.brushes 9.his 10.teeth 11.are 12.white He 13.puts 14.on his 15.clothes. ... so on.</p>
</blockquote>
<p>Here the first <strong>He</strong> is unique so number it to 1.<br>
And until the end of content the "He" word is ignored, and so on.
Then the script does this to second words, if it is unique, then numbers it, otherwise ignore it. </p>
<p>Also the paragraph and each line <strong>must not miss</strong>, because I print it out in paper and read daily. </p>
<p>For completing this idea to use by everyone else I need to have a <strong>database</strong> from one word that script is parsed so that I can after, for example 100 short-story, I see whet word I have read.<br>
And use this <strong>database</strong> for ignoring the repeated word in the new short-story that I want to read. </p>
<p>Why am I doing this? Because this help me to know what word I have read and what word I have not read. Also It can be a good method for the others, so that they can learn English easily. please help me to develop this idea If you see something bad in my idea or if you know the similar idea like this, that have done,please tell me.</p>
<p><strong>In summary, I want a content that each word only once (one time) has been numbered</strong></p>
<p>Sorry guys, but I want to print the content without missing the paragraph. Please the photo </p>
<p><a href="http://i.stack.imgur.com/BfemJ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BfemJ.jpg" alt="my homework"></a></p>
<p>As you can see, I have to cross the new word in the <strong>new short story</strong> for read those in the future. The script must print paragraph with numbering word as usual so that I can save it, then I print it for reading on the paper.</p>
<p>I want to do in this form:
<code>$ script my_context.txt > new_context.txt</code> </p>
<p>Then I can print it out.</p>
<p>I am so sorry if you see some mistake in my writing. If you does not understand my idea please comment, so that I put explain it in more detail. </p>
<p>Thank a lot!</p>
| -2 | 2016-09-30T12:47:43Z | 39,792,050 | <p>A quick and very dirty solution in Python...</p>
<pre><code>story = 'He wakes up. He sees the sun rise. He brushes his teeth are white He puts on his clothes. His shirt is blue. His shoes are yellow. His pants are brown. He goes downstairs. He gets a bowl. He pours some milk and cereal. He eats. He gets the newspaper. He reads.'
already_seen = set()
count = 0
my_story_string = ''
for word in story.split():
if word not in already_seen:
count += 1
res = " ".join([str(count), word])
print(word_number_tuple)
already_seen.add(word)
else:
res = word
print(word)
my_story_string += ' ' + res
>>> my_story_string
' 1 He 2 wakes 3 up. He 4 sees 5 the 6 sun 7 rise. He 8 brushes 9 his 10 teeth 11 are 12 white He 13 puts 14 on his 15 clothes. 16 His 17 shirt 18 is 19 blue. His 20 shoes are 21 yellow. His 22 pants are 23 brown. He 24 goes 25 downstairs. He 26 gets 27 a 28 bowl. He 29 pours 30 some 31 milk 32 and 33 cereal. He 34 eats. He gets the 35 newspaper. He 36 reads.'
</code></pre>
| 0 | 2016-09-30T12:55:11Z | [
"python",
"bash",
"perl"
]
|
How to number unique words on each individual line, not miss paragraph? | 39,791,891 | <p>Before anything I am reading English language and programming, but I am beginner now. So I did a lot of methods to learn EN ( self-study ) but finally I make a personal method to learn.<br>
So I collected a lot of <strong>short story</strong> then, read those, day after day. Now I am doing this method as usual.<br>
A week a go I started to learn <strong>perl one-liner</strong> and it was so useful to me.</p>
<p>However, I get into <code>perl -pe '$q=0; s/(\w+)/++Sq." ".$1'</code><br>
for content: </p>
<blockquote>
<p>just another<br>
perl hacker<br>
hacking perl code</p>
</blockquote>
<p>it become to: </p>
<blockquote>
<p>1.just 2.another<br>
1.perl 2.hacker<br>
1.hacking 2.perl 3.code</p>
</blockquote>
<p>Okay, after I saw this <strong>perl one-liner</strong> I got an idea </p>
<p>For example I read this short-story: </p>
<blockquote>
<ol>
<li><p>Morning<br>
He wakes up. He sees the sun rise. He brushes his teeth. His teeth are white. He puts on his clothes. His shirt is blue. His
shoes are yellow. His pants are brown. He goes downstairs. He gets a
bowl. He pours milk and cereal. He eats. He gets the newspaper. He
reads.</p></li>
<li><p>First<br>
Day of School He goes to class. There is an empty seat in front. He sits in the seat. He looks around. There are different
people. He says "hi" to the girl next to him. She smiles. The teacher
comes in. She closes the door. Everyone is silent. The first day of
school begins.</p></li>
<li><p>Water on the Floor<br>
She is thirsty. She gets a glass of water. She begins to walk. She drops the glass. There is water on the floor. The
puddle is big. She gets a mop. She wipes the water off. The floor is
clean. She gets another glass of water. She drinks it. She is happy.</p></li>
<li><p>Babysitting<br>
Casey wants a new car. She needs money. She decides to babysit. She takes care of the child. She feeds him lunch. She reads
him a story. The story is funny. The child laughs. Casey likes him.
The child's mom comes home. The child kisses Casey. Casey leaves. She
will babysit him again.</p></li>
</ol>
<p>5.a docter<br>
Sam is a doctor. He takes care of people. He smiles at them. He gives them medicine. He gives stickers to the younger
patients. The younger patients like him. They see him when they are
sick. He makes them feel better. This makes him happy. He loves his
job. He goes home proud.</p>
</blockquote>
<p>As you can see, it is very easy. But at the beginning, it is not easy for someone who just started to learn English. </p>
<p>So my idea is this. I want a script may be in <strong>bash</strong> or <strong>perl</strong> that I think <strong>perl</strong> is better, that script can read a lot of <strong>short-story</strong> that I have and for each unique work, it number the word in the place. </p>
<p>For example in the above context that I put, I want something like this: </p>
<blockquote>
<p>1.He 2.wakes 3.up. He 4.sees 5.the 6.sun 7.rise. He 8.brushes 9.his 10.teeth 11.are 12.white He 13.puts 14.on his 15.clothes. ... so on.</p>
</blockquote>
<p>Here the first <strong>He</strong> is unique so number it to 1.<br>
And until the end of content the "He" word is ignored, and so on.
Then the script does this to second words, if it is unique, then numbers it, otherwise ignore it. </p>
<p>Also the paragraph and each line <strong>must not miss</strong>, because I print it out in paper and read daily. </p>
<p>For completing this idea to use by everyone else I need to have a <strong>database</strong> from one word that script is parsed so that I can after, for example 100 short-story, I see whet word I have read.<br>
And use this <strong>database</strong> for ignoring the repeated word in the new short-story that I want to read. </p>
<p>Why am I doing this? Because this help me to know what word I have read and what word I have not read. Also It can be a good method for the others, so that they can learn English easily. please help me to develop this idea If you see something bad in my idea or if you know the similar idea like this, that have done,please tell me.</p>
<p><strong>In summary, I want a content that each word only once (one time) has been numbered</strong></p>
<p>Sorry guys, but I want to print the content without missing the paragraph. Please the photo </p>
<p><a href="http://i.stack.imgur.com/BfemJ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BfemJ.jpg" alt="my homework"></a></p>
<p>As you can see, I have to cross the new word in the <strong>new short story</strong> for read those in the future. The script must print paragraph with numbering word as usual so that I can save it, then I print it for reading on the paper.</p>
<p>I want to do in this form:
<code>$ script my_context.txt > new_context.txt</code> </p>
<p>Then I can print it out.</p>
<p>I am so sorry if you see some mistake in my writing. If you does not understand my idea please comment, so that I put explain it in more detail. </p>
<p>Thank a lot!</p>
| -2 | 2016-09-30T12:47:43Z | 39,792,081 | <pre><code>#!/usr/bin/perl
use strict;
use warnings;
my @words = <DATA> =~ /(\w+)/g;
my %seen;
my $count = 1;
foreach my $value (@words) {
if ( !$seen{$value} ) {
print "$count.$value ";
$seen{$value} = 1;
}
else{
print "$value";
}
$count++;
}
__DATA__
He wakes up. He sees the sun rise. He brushes his teeth are white He puts on his clothes. His shirt is blue. His shoes are yellow. His pants are brown. He goes downstairs. He gets a bowl. He pours some milk and cereal. He eats. He gets the newspaper. He reads.
</code></pre>
<p><strong><a href="http://ideone.com/bk1RBJ" rel="nofollow">Demo</a></strong></p>
| 1 | 2016-09-30T12:57:10Z | [
"python",
"bash",
"perl"
]
|
How to number unique words on each individual line, not miss paragraph? | 39,791,891 | <p>Before anything I am reading English language and programming, but I am beginner now. So I did a lot of methods to learn EN ( self-study ) but finally I make a personal method to learn.<br>
So I collected a lot of <strong>short story</strong> then, read those, day after day. Now I am doing this method as usual.<br>
A week a go I started to learn <strong>perl one-liner</strong> and it was so useful to me.</p>
<p>However, I get into <code>perl -pe '$q=0; s/(\w+)/++Sq." ".$1'</code><br>
for content: </p>
<blockquote>
<p>just another<br>
perl hacker<br>
hacking perl code</p>
</blockquote>
<p>it become to: </p>
<blockquote>
<p>1.just 2.another<br>
1.perl 2.hacker<br>
1.hacking 2.perl 3.code</p>
</blockquote>
<p>Okay, after I saw this <strong>perl one-liner</strong> I got an idea </p>
<p>For example I read this short-story: </p>
<blockquote>
<ol>
<li><p>Morning<br>
He wakes up. He sees the sun rise. He brushes his teeth. His teeth are white. He puts on his clothes. His shirt is blue. His
shoes are yellow. His pants are brown. He goes downstairs. He gets a
bowl. He pours milk and cereal. He eats. He gets the newspaper. He
reads.</p></li>
<li><p>First<br>
Day of School He goes to class. There is an empty seat in front. He sits in the seat. He looks around. There are different
people. He says "hi" to the girl next to him. She smiles. The teacher
comes in. She closes the door. Everyone is silent. The first day of
school begins.</p></li>
<li><p>Water on the Floor<br>
She is thirsty. She gets a glass of water. She begins to walk. She drops the glass. There is water on the floor. The
puddle is big. She gets a mop. She wipes the water off. The floor is
clean. She gets another glass of water. She drinks it. She is happy.</p></li>
<li><p>Babysitting<br>
Casey wants a new car. She needs money. She decides to babysit. She takes care of the child. She feeds him lunch. She reads
him a story. The story is funny. The child laughs. Casey likes him.
The child's mom comes home. The child kisses Casey. Casey leaves. She
will babysit him again.</p></li>
</ol>
<p>5.a docter<br>
Sam is a doctor. He takes care of people. He smiles at them. He gives them medicine. He gives stickers to the younger
patients. The younger patients like him. They see him when they are
sick. He makes them feel better. This makes him happy. He loves his
job. He goes home proud.</p>
</blockquote>
<p>As you can see, it is very easy. But at the beginning, it is not easy for someone who just started to learn English. </p>
<p>So my idea is this. I want a script may be in <strong>bash</strong> or <strong>perl</strong> that I think <strong>perl</strong> is better, that script can read a lot of <strong>short-story</strong> that I have and for each unique work, it number the word in the place. </p>
<p>For example in the above context that I put, I want something like this: </p>
<blockquote>
<p>1.He 2.wakes 3.up. He 4.sees 5.the 6.sun 7.rise. He 8.brushes 9.his 10.teeth 11.are 12.white He 13.puts 14.on his 15.clothes. ... so on.</p>
</blockquote>
<p>Here the first <strong>He</strong> is unique so number it to 1.<br>
And until the end of content the "He" word is ignored, and so on.
Then the script does this to second words, if it is unique, then numbers it, otherwise ignore it. </p>
<p>Also the paragraph and each line <strong>must not miss</strong>, because I print it out in paper and read daily. </p>
<p>For completing this idea to use by everyone else I need to have a <strong>database</strong> from one word that script is parsed so that I can after, for example 100 short-story, I see whet word I have read.<br>
And use this <strong>database</strong> for ignoring the repeated word in the new short-story that I want to read. </p>
<p>Why am I doing this? Because this help me to know what word I have read and what word I have not read. Also It can be a good method for the others, so that they can learn English easily. please help me to develop this idea If you see something bad in my idea or if you know the similar idea like this, that have done,please tell me.</p>
<p><strong>In summary, I want a content that each word only once (one time) has been numbered</strong></p>
<p>Sorry guys, but I want to print the content without missing the paragraph. Please the photo </p>
<p><a href="http://i.stack.imgur.com/BfemJ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BfemJ.jpg" alt="my homework"></a></p>
<p>As you can see, I have to cross the new word in the <strong>new short story</strong> for read those in the future. The script must print paragraph with numbering word as usual so that I can save it, then I print it for reading on the paper.</p>
<p>I want to do in this form:
<code>$ script my_context.txt > new_context.txt</code> </p>
<p>Then I can print it out.</p>
<p>I am so sorry if you see some mistake in my writing. If you does not understand my idea please comment, so that I put explain it in more detail. </p>
<p>Thank a lot!</p>
| -2 | 2016-09-30T12:47:43Z | 39,792,614 | <p><code>awk</code> to the rescue!</p>
<pre><code>$ awk -v RS=" +" -v ORS=" " '{key=$0;gsub(/[^A-Za-z]/,"",key);
if(key in a)print $0;
else{a[key];print ++c"."$0}}' file
</code></pre>
<blockquote>
<p>1.He 2.wakes 3.up. He 4.sees 5.the 6.sun 7.rise. He 8.brushes 9.his 10.teeth 11.are 12.white He 13.puts 14.on his 15.clothes. 16.His 17.shirt 18.is 19.blue. His 20.shoes are 21.yellow. His 22.pants are 23.brown. He 24.goes 25.downstairs. He 26.gets 27.a 28.bowl. He 29.pours 30.some 31.milk 32.and 33.cereal. He 34.eats. He gets the 35.newspaper. He 36.reads.</p>
</blockquote>
<p>you can also make is non case-sensitive by changing the key as I did for filtering non alphabetical chars.</p>
| 1 | 2016-09-30T13:23:07Z | [
"python",
"bash",
"perl"
]
|
How to number unique words on each individual line, not miss paragraph? | 39,791,891 | <p>Before anything I am reading English language and programming, but I am beginner now. So I did a lot of methods to learn EN ( self-study ) but finally I make a personal method to learn.<br>
So I collected a lot of <strong>short story</strong> then, read those, day after day. Now I am doing this method as usual.<br>
A week a go I started to learn <strong>perl one-liner</strong> and it was so useful to me.</p>
<p>However, I get into <code>perl -pe '$q=0; s/(\w+)/++Sq." ".$1'</code><br>
for content: </p>
<blockquote>
<p>just another<br>
perl hacker<br>
hacking perl code</p>
</blockquote>
<p>it become to: </p>
<blockquote>
<p>1.just 2.another<br>
1.perl 2.hacker<br>
1.hacking 2.perl 3.code</p>
</blockquote>
<p>Okay, after I saw this <strong>perl one-liner</strong> I got an idea </p>
<p>For example I read this short-story: </p>
<blockquote>
<ol>
<li><p>Morning<br>
He wakes up. He sees the sun rise. He brushes his teeth. His teeth are white. He puts on his clothes. His shirt is blue. His
shoes are yellow. His pants are brown. He goes downstairs. He gets a
bowl. He pours milk and cereal. He eats. He gets the newspaper. He
reads.</p></li>
<li><p>First<br>
Day of School He goes to class. There is an empty seat in front. He sits in the seat. He looks around. There are different
people. He says "hi" to the girl next to him. She smiles. The teacher
comes in. She closes the door. Everyone is silent. The first day of
school begins.</p></li>
<li><p>Water on the Floor<br>
She is thirsty. She gets a glass of water. She begins to walk. She drops the glass. There is water on the floor. The
puddle is big. She gets a mop. She wipes the water off. The floor is
clean. She gets another glass of water. She drinks it. She is happy.</p></li>
<li><p>Babysitting<br>
Casey wants a new car. She needs money. She decides to babysit. She takes care of the child. She feeds him lunch. She reads
him a story. The story is funny. The child laughs. Casey likes him.
The child's mom comes home. The child kisses Casey. Casey leaves. She
will babysit him again.</p></li>
</ol>
<p>5.a docter<br>
Sam is a doctor. He takes care of people. He smiles at them. He gives them medicine. He gives stickers to the younger
patients. The younger patients like him. They see him when they are
sick. He makes them feel better. This makes him happy. He loves his
job. He goes home proud.</p>
</blockquote>
<p>As you can see, it is very easy. But at the beginning, it is not easy for someone who just started to learn English. </p>
<p>So my idea is this. I want a script may be in <strong>bash</strong> or <strong>perl</strong> that I think <strong>perl</strong> is better, that script can read a lot of <strong>short-story</strong> that I have and for each unique work, it number the word in the place. </p>
<p>For example in the above context that I put, I want something like this: </p>
<blockquote>
<p>1.He 2.wakes 3.up. He 4.sees 5.the 6.sun 7.rise. He 8.brushes 9.his 10.teeth 11.are 12.white He 13.puts 14.on his 15.clothes. ... so on.</p>
</blockquote>
<p>Here the first <strong>He</strong> is unique so number it to 1.<br>
And until the end of content the "He" word is ignored, and so on.
Then the script does this to second words, if it is unique, then numbers it, otherwise ignore it. </p>
<p>Also the paragraph and each line <strong>must not miss</strong>, because I print it out in paper and read daily. </p>
<p>For completing this idea to use by everyone else I need to have a <strong>database</strong> from one word that script is parsed so that I can after, for example 100 short-story, I see whet word I have read.<br>
And use this <strong>database</strong> for ignoring the repeated word in the new short-story that I want to read. </p>
<p>Why am I doing this? Because this help me to know what word I have read and what word I have not read. Also It can be a good method for the others, so that they can learn English easily. please help me to develop this idea If you see something bad in my idea or if you know the similar idea like this, that have done,please tell me.</p>
<p><strong>In summary, I want a content that each word only once (one time) has been numbered</strong></p>
<p>Sorry guys, but I want to print the content without missing the paragraph. Please the photo </p>
<p><a href="http://i.stack.imgur.com/BfemJ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/BfemJ.jpg" alt="my homework"></a></p>
<p>As you can see, I have to cross the new word in the <strong>new short story</strong> for read those in the future. The script must print paragraph with numbering word as usual so that I can save it, then I print it for reading on the paper.</p>
<p>I want to do in this form:
<code>$ script my_context.txt > new_context.txt</code> </p>
<p>Then I can print it out.</p>
<p>I am so sorry if you see some mistake in my writing. If you does not understand my idea please comment, so that I put explain it in more detail. </p>
<p>Thank a lot!</p>
| -2 | 2016-09-30T12:47:43Z | 39,793,083 | <pre><code>$ cat script.txt
BEGIN {RS=" "; ORS=" "} # the record is a word
{
key=$0 # separate key to clean it up
gsub(/[^a-zA-Z]/,"",key) # remove ".," etc.
key=tolower(key) # and capitals
if(!(key in a)) { # if not seen before
print ++i; a[key] # print the running number
}
} 1 # and the word
</code></pre>
<p>Run it:</p>
<pre><code>$ awk -f script.awk short_story_in_2_paragraphs.txt
</code></pre>
<blockquote>
<p>1 He 2 wakes 3 up. He 4 sees 5 the 6 sun 7 rise. He 8 brushes 9 his 10 teeth 11 are 12 white He 13 puts 14 on his 15 clothes. His 16 shirt 17 is 18 blue. His 19 shoes are 20 yellow. His 21 pants are 22 brown. He 23 goes 24 downstairs. He 25 gets 26 a 27 bowl. He 28 pours 29 some 30 milk 31 and 32 cereal. He 33 eats. He gets the 34 newspaper. He 35 reads.</p>
<p>He wakes up. He sees the sun rise. He brushes his teeth are white He puts on his clothes. His shirt is blue. His shoes are yellow. His pants are brown. He goes downstairs. He gets a bowl. He pours some milk and cereal. He eats. He gets the newspaper. He 36 reads.</p>
</blockquote>
<p>I don't understand the last number <code>36 reads</code>, thou :D.</p>
<p>Version 2(.1 :)</p>
<pre><code>BEGIN {RS=" "; ORS=" "} # the record is a word
NR==FNR {a[$0]; next} # read the database of words into memory
{
key=$0 # separate key to clean it up
gsub(/[^a-zA-Z]/,"",key) # remove ".," etc.
key=tolower(key) # and capitals
if(!(key in a)) { # if not seen before
print ++i; a[key] # print the running number
print key >> "database.txt" # append word to database
}
} 1 # and the word
</code></pre>
<p>Run it:</p>
<pre><code>$ awk -f script2.awk database.txt story.txt
</code></pre>
<p>It expect that <code>database.txt</code> exists and has at least one word in it:</p>
<pre><code>$ echo -n a\ > database.txt
</code></pre>
| 1 | 2016-09-30T13:48:02Z | [
"python",
"bash",
"perl"
]
|
Text from LineEdit1 (Form1) to LineEdit2 (Form2)_ Python, PyQt | 39,791,935 | <p>I have created MainWindow with LineEdit11 and button1 in main window. Also I created V1 Form 2 with LineEdit and a button 2.</p>
<p>When I cliked a Button1 Form 2 will show. I write a text in lineEdit and i want to transfer text to LineEdit11 in form1 by cliked Button2. How to connect them? </p>
<p>Python 3.5, PyQT 4</p>
<p>Thank you in advance</p>
<p>OK so I write in V1 class </p>
<pre><code>def wyslij(self):
self.lineEdit.setText(self.Ui_Form.lineEdit_11.text())
</code></pre>
<p>And i get error:</p>
<blockquote>
<p>'Ui_V1' object has no attribute 'Ui_Form'
Of course i add V1 class into Ui_Form. V1 is second window and Ui_Form is main window.</p>
</blockquote>
<p>This is a whole code:</p>
<pre><code>from PyQt4 import QtCore, QtGui
from V1 import Ui_V1
from V2 import Ui_V2
from V3 import Ui_V3
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
# V1 window
class Ui_V1(object):
def setupUi(self, V1):
V1.setObjectName(_fromUtf8("V1"))
V1.resize(400, 300)
self.label = QtGui.QLabel(V1)
...
self.pushButton.setText(_translate("V1", "Wyslij", None))
self.pushButton_2.setText(_translate("V1", "Wyslij", None))
self.pushButton.clicked.connect(lambda: self.wyslij())
def wyslij(self):
self.lineEdit.setText(self.Ui_Form.lineEdit_11.text())
# V2 okno
class Ui_V2(object):
def setupUi(self, V2):
V2.setObjectName(_fromUtf8("V2"))
V2.resize(400, 300)
self.label_4 = QtGui.QLabel(V2)
...
self.pushButton.setText(_translate("V2", "Wyslij", None))
self.label.setText(_translate("V2", "V2", None))
self.label_3.setText(_translate("V2", "A", None))
self.pushButton_2.setText(_translate("V2", "Wyslij", None))
# V3 okno
class Ui_V3(object):
def setupUi(self, V3):
V3.setObjectName(_fromUtf8("V3"))
V3.resize(400, 300)
self.label_4 = QtGui.QLabel(V3)
...
self.pushButton.setText(_translate("V3", "Wyslij", None))
self.label.setText(_translate("V3", "V3", None))
self.label_3.setText(_translate("V3", "A", None))
self.pushButton_2.setText(_translate("V3", "Wyslij", None))
# Main window!
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(728, 601)
Form.setMinimumSize(QtCore.QSize(728, 601))
self.label_6 = QtGui.QLabel(Form)
self.label_6.setGeometry(QtCore.QRect(169, 3, 401, 41))
self.label_6.setObjectName(_fromUtf8("label_6"))...
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.label_6.setText(_translate("Form", "<html><head/><body><p><span style=\" font-size:16pt; font-weight:600;\">TYGODNIOWA KONTROLA JAKOSCI</span></p></body></html>", None))
self.label_8.setText(_translate("Form", "(dd-mm-rrrr)", None))...
self.pushButton_2.clicked.connect(lambda: self.zapis_tyg()) # Do zapisu do tyg formularza
self.pushButton_5.clicked.connect(lambda: self.openV1()) # Do pojawienia si eokna V1
self.pushButton_6.clicked.connect(lambda: self.openV2()) # Do pojawienia si eokna V2
self.pushButton_7.clicked.connect(lambda: self.openV3()) # Do pojawienia si eokna V3
#zapis do pliku formularza tyg
def zapis_tyg(self): # ZAPIS DO FORMULARZ TYGODNIOWEGO
s = ""
seq = (self.comboBox_6.currentText(), ".txt"); # This is sequence of strings. laczenie aby nazywaÅ pliki wzaleznosci od aparatu
a= s.join( seq )
text_file = open( a , "a")
text_file.write(self.lineEdit.text()+ "\t" ) #data
text_file.write(self.lineEdit_2.text()+ "\t" ) #osoba
text_file.write(self.comboBox_6.currentText() + "\t" ) #aparat
text_file.write(self.comboBox.currentText() + "\t" ) #AKCESORIUM
text_file.write(self.comboBox_2.currentText() + "\t" ) #ZAB ANTYK
text_file.write(self.comboBox_3.currentText() + "\t" ) #iZO
text_file.write(self.comboBox_4.currentText() + "\t" )# CENTRQTOR
text_file.write(self.comboBox_5.currentText() + "\t" )# TELEMETR
text_file.write(self.textEdit.toPlainText()+ "\n" ) # KOM MECH
text_file.close()
#function to show a new form
def openV1(self):
self.V1Window=QtGui.QMainWindow()
self.ui= Ui_V1()
self.ui.setupUi(self.V1Window)
self.V1Window.show()
def openV2(self):
self.V2Window=QtGui.QMainWindow()
self.ui= Ui_V2()
self.ui.setupUi(self.V2Window)
self.V2Window.show()
def openV3(self):
self.V3Window=QtGui.QMainWindow()
self.ui= Ui_V3()
self.ui.setupUi(self.V3Window)
self.V3Window.show()
</code></pre>
<p>And this Line:</p>
<pre><code>def wyslij(self):
self.lineEdit.setText(self.Ui_Form.lineEdit_11.text())
</code></pre>
<p>Not work properly .</p>
| -2 | 2016-09-30T12:49:34Z | 39,792,710 | <p>Without any code the simplest way (but not the best) would be something like that :</p>
<pre><code>def on_button2_click(self):
self.form2.lineEdit2.setText(self.lineEdit1.text())
</code></pre>
| 0 | 2016-09-30T13:27:58Z | [
"python",
"pyqt4"
]
|
python Tkinter tkFileDialog | 39,791,942 | <p>in short, what's the difference between</p>
<pre><code>tkFileDialog.asksaveasfile
</code></pre>
<p>and</p>
<pre><code>tkFileDialog.asksaveasfilename
</code></pre>
<p>I could not understand from the build in docs</p>
| 0 | 2016-09-30T12:49:53Z | 39,792,020 | <p><code>asksaveasfile</code> asks the user for a file, then opens that file in write mode and returns it to you so you can write in it.</p>
<p><code>asksaveasfilename</code> asks the user for a file, then returns that file's name. No file is opened; if you want to write to the file, you'll have to open it yourself.</p>
<p><code>asksaveasfilename</code> might be preferred over <code>asksaveasfile</code> if you want to do something fancier to the file than just writing data to it. For instance, you might want to first copy the file to another directory as a backup. In which case, you'd prefer to get just the file name so you can perform the copy without having to worry about whether having the file open will cause the copy to fail.</p>
| 4 | 2016-09-30T12:53:51Z | [
"python",
"tkinter"
]
|
python Tkinter tkFileDialog | 39,791,942 | <p>in short, what's the difference between</p>
<pre><code>tkFileDialog.asksaveasfile
</code></pre>
<p>and</p>
<pre><code>tkFileDialog.asksaveasfilename
</code></pre>
<p>I could not understand from the build in docs</p>
| 0 | 2016-09-30T12:49:53Z | 39,792,041 | <p>According to the <a href="http://tkinter.unpythonic.net/wiki/tkFileDialog" rel="nofollow">http://tkinter.unpythonic.net/</a> wiki:</p>
<p>Similar to:</p>
<blockquote>
<p>First you have to decide if you want to open a file or just want to get a filename in order to open the file on your own. In the first case you should use <code>tkFileDialog.askopenfile()</code> in the latter case <code>tkFileDialog.askopenfilename()</code>.</p>
</blockquote>
<p>then:</p>
<blockquote>
<p>Saving files works in a similar way. You also have two variants of the function, one to get an opened file which you can use to save your data and another to get a file name in order to open the file on your own. These functions are only provided in the single file version. A multiple file version would make no sense.</p>
</blockquote>
| 2 | 2016-09-30T12:54:46Z | [
"python",
"tkinter"
]
|
Using adaptive time step for scipy.integrate.ode when solving ODE systems | 39,792,111 | <p>I have to just read <a href="http://stackoverflow.com/questions/12926393/using-adaptive-step-sizes-with-scipy-integrate-ode">Using adaptive step sizes with scipy.integrate.ode</a> and the accepted solution to that problem, and have even reproduced the results by copy-and-paste in my Python interpreter. </p>
<p>My problem is that when I try and adapt the solution code to my own code I only get flat lines.</p>
<p>My code is as follows:</p>
<pre><code>from scipy.integrate import ode
from matplotlib.pyplot import plot, show
initials = [1,1,1,1,1]
integration_range = (0, 100)
f = lambda t,y: [1.0*y[0]*y[1], -1.0*y[0]*y[1], 1.0*y[2]*y[3] - 1.0*y[2], -1.0*y[2]*y[3], 1.0*y[2], ]
y_solutions = []
t_solutions = []
def solution_getter(t,y):
t_solutions.append(t)
y_solutions.append(y)
backend = "dopri5"
ode_solver = ode(f).set_integrator(backend)
ode_solver.set_solout(solution_getter)
ode_solver.set_initial_value(y=initials, t=0)
ode_solver.integrate(integration_range[1])
plot(t_solutions,y_solutions)
show()
</code></pre>
<p>And the plot it yields:
<a href="http://i.stack.imgur.com/9Aki3.png" rel="nofollow"><img src="http://i.stack.imgur.com/9Aki3.png" alt="enter image description here"></a></p>
| 0 | 2016-09-30T12:58:30Z | 39,815,225 | <p>In the line </p>
<pre><code> y_solutions.append(y)
</code></pre>
<p>you think that you are appending the current vector. What actally happens is that you are appending the object reference to <code>y</code>. Since apparently the integrator reuses the vector <code>y</code> during the integration loop, you are always appending the same object reference. Thus at the end, each position of the list is filled by the same reference pointing to the vector of the last state of <code>y</code>.</p>
<p>Long story short: replace with</p>
<pre><code> y_solutions.append(y.copy())
</code></pre>
<p>and everything is fine.</p>
| 1 | 2016-10-02T08:30:48Z | [
"python",
"python-3.x",
"scipy",
"ode"
]
|
Selenium with Python keeps to load a page | 39,792,146 | <p>I am trying to read a page using a simple Python/Selenium script</p>
<pre><code># encoding=utf8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import datetime as dt
import codecs
import os
myDriver=webdriver.Chrome()
myDriver.get("http://spb.beeline.ru/customers/products/mobile/tariffs/")
print "Test"
myDriver.quit()
</code></pre>
<p>Now, if i open that url using google chrome, the page load and that's it.
While doing it through this script, the page remains in a load state and the script can't go further.</p>
<p>I'm on Windows 7, using Python 2.7.12, Selenium 2.53.6 and chromedriver 2.24.41.74.31</p>
| 0 | 2016-09-30T12:59:41Z | 39,792,558 | <p>I'm not sure what that page is doing, but it is certainly atypical. My best suggestion is to set the page load timeout and then handle the associated TimeoutException:</p>
<pre><code># encoding=utf8
from __future__ import print_function
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
myDriver=webdriver.Chrome()
try:
# Set the page load timeout
myDriver.set_page_load_timeout(10)
try:
myDriver.get("http://spb.beeline.ru/customers/products/mobile/tariffs/")
except TimeoutException:
print("Page expired")
# Do stuff here
finally:
myDriver.quit()
</code></pre>
<p>The downside is that (I think) this will kill whatever is happening in the back ground that prevents the <code>driver.get</code> call from returning, so some page functionality may be fundamentally broken.</p>
| 0 | 2016-09-30T13:20:14Z | [
"python",
"selenium",
"selenium-chromedriver"
]
|
Vectorizing sRGB to linear conversion properly in Numpy | 39,792,163 | <p>In my image editing app I have a function for converting a 32 bit float image from sRGB to linear color space. The formula is:</p>
<pre><code>if value <= 0.04045: (value / 12.92)
if value > 0.04045: ((value + 0.055) / 1.055)^2.4)
</code></pre>
<p>My image is a three-dimensional <strong>numpy.ndarray</strong> named <strong>img32</strong>.</p>
<p>My implementation so far:</p>
<pre><code>boolarray = img32 <= 0.04045
lower = (img32 / 12.92) * boolarray.astype(np.int)
upper = np.power(((img32 + 0.055) / 1.055), 2.4) * np.invert(boolarray).astype(np.int)
img32 = lower + upper
</code></pre>
<p>So, I am creating a new array <strong>boolarray</strong> with truth values for <= 0.04045 and multiply by that.</p>
<p>What would be a better solution?</p>
<p>I tried something like:</p>
<pre><code>img32[img32 < 0.04045] = img32 / 12.92
</code></pre>
<p>which works on the first step but fails on the second:</p>
<pre><code>img32[img32 >= 0.04045] = np.power(((img32 + 0.055) / 1.055), 2.4)
</code></pre>
<p>probably because it doesn't work when wrapped in the <strong>np.power</strong> function</p>
<p>Any help is appreciated.</p>
| 2 | 2016-09-30T13:00:30Z | 39,792,372 | <p>A clean way would be with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> that lets us choose between two values based on a mask. In our case, the mask could be <code>img32 >= 0.04045</code> and we will choose <code>((img32 + 0.055) / 1.055)**2.4</code> when <code>True</code>, else go with <code>img32/12.92</code>.</p>
<p>So, we would have an implementation like so -</p>
<pre><code>np.where( img32 >= 0.04045,((img32 + 0.055) / 1.055)**2.4, img32/12.92 )
</code></pre>
<hr>
<p>If you care about memory a lot and would like to write back the results into the input array, you could it in three steps by creating and selectively set elems corresponding to those two conditions, like so -</p>
<pre><code>mask = img32 >= 0.04045
img32[mask] = ((img32[mask] + 0.055) / 1.055)**2.4
img32[~mask] = img32[~mask] / 12.92
</code></pre>
<p>Sample case -</p>
<pre><code>In [143]: img32 = np.random.rand(4,5).astype(np.float32)
In [144]: img32.nbytes
Out[144]: 80
In [145]: mask.nbytes
Out[145]: 20
</code></pre>
<p>So, we are avoiding the creation of an output array that would have costed us <code>80</code> bytes and instead using <code>20</code> bytes on the mask. Thus, making a saving of <code>75%</code> of input array size there on memory. Please note that this might lead to a slight reduction in performance though.</p>
| 1 | 2016-09-30T13:11:12Z | [
"python",
"numpy",
"vectorization",
"color-space",
"srgb"
]
|
Vectorizing sRGB to linear conversion properly in Numpy | 39,792,163 | <p>In my image editing app I have a function for converting a 32 bit float image from sRGB to linear color space. The formula is:</p>
<pre><code>if value <= 0.04045: (value / 12.92)
if value > 0.04045: ((value + 0.055) / 1.055)^2.4)
</code></pre>
<p>My image is a three-dimensional <strong>numpy.ndarray</strong> named <strong>img32</strong>.</p>
<p>My implementation so far:</p>
<pre><code>boolarray = img32 <= 0.04045
lower = (img32 / 12.92) * boolarray.astype(np.int)
upper = np.power(((img32 + 0.055) / 1.055), 2.4) * np.invert(boolarray).astype(np.int)
img32 = lower + upper
</code></pre>
<p>So, I am creating a new array <strong>boolarray</strong> with truth values for <= 0.04045 and multiply by that.</p>
<p>What would be a better solution?</p>
<p>I tried something like:</p>
<pre><code>img32[img32 < 0.04045] = img32 / 12.92
</code></pre>
<p>which works on the first step but fails on the second:</p>
<pre><code>img32[img32 >= 0.04045] = np.power(((img32 + 0.055) / 1.055), 2.4)
</code></pre>
<p>probably because it doesn't work when wrapped in the <strong>np.power</strong> function</p>
<p>Any help is appreciated.</p>
| 2 | 2016-09-30T13:00:30Z | 39,792,474 |
<pre><code>b = (img32 < 0.04045)
img32[b] /= 12.92
not_b = numpy.logical_not(b)
img32[not_b] += 0.05
img32[not_b] /= 1.055
img32[not_b] **= 2.4
</code></pre>
| 0 | 2016-09-30T13:16:29Z | [
"python",
"numpy",
"vectorization",
"color-space",
"srgb"
]
|
Vectorizing sRGB to linear conversion properly in Numpy | 39,792,163 | <p>In my image editing app I have a function for converting a 32 bit float image from sRGB to linear color space. The formula is:</p>
<pre><code>if value <= 0.04045: (value / 12.92)
if value > 0.04045: ((value + 0.055) / 1.055)^2.4)
</code></pre>
<p>My image is a three-dimensional <strong>numpy.ndarray</strong> named <strong>img32</strong>.</p>
<p>My implementation so far:</p>
<pre><code>boolarray = img32 <= 0.04045
lower = (img32 / 12.92) * boolarray.astype(np.int)
upper = np.power(((img32 + 0.055) / 1.055), 2.4) * np.invert(boolarray).astype(np.int)
img32 = lower + upper
</code></pre>
<p>So, I am creating a new array <strong>boolarray</strong> with truth values for <= 0.04045 and multiply by that.</p>
<p>What would be a better solution?</p>
<p>I tried something like:</p>
<pre><code>img32[img32 < 0.04045] = img32 / 12.92
</code></pre>
<p>which works on the first step but fails on the second:</p>
<pre><code>img32[img32 >= 0.04045] = np.power(((img32 + 0.055) / 1.055), 2.4)
</code></pre>
<p>probably because it doesn't work when wrapped in the <strong>np.power</strong> function</p>
<p>Any help is appreciated.</p>
| 2 | 2016-09-30T13:00:30Z | 39,792,885 | <p>You could also use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html" rel="nofollow">numpy.piecewise</a>:</p>
<pre><code>In [11]: img32 = np.random.rand(800, 600).astype(np.float32)
In [12]: img_linear = np.piecewise(img32,
[img32 <= 0.04045, img32 > 0.04045],
[lambda v: v/12.92, lambda v: ((v + 0.055)/1.055)**2.4] )
In [13]: img_linear.shape
Out[13]: (800, 600)
In [14]: img_linear.dtype
Out[14]: dtype('float32')
</code></pre>
| 1 | 2016-09-30T13:37:02Z | [
"python",
"numpy",
"vectorization",
"color-space",
"srgb"
]
|
(timezone aware) datetime in netcdf using python | 39,792,228 | <p>I'm trying to save a timeserie in a netcdf file. According to documentation I found, this can be done using the date2num method from the netCDF4 module. I can't get it working however (see example below):</p>
<pre><code>from datetime import datetime as dt
from netCDF4 import Dataset
from netCDF4 import num2date, date2num
import pytz
filename = 'test.nc'
root = Dataset(filename, 'w', format='NETCDF4_CLASSIC')
root.name = 'test'
# create dimension
root.createDimension('datetime', None)
# create variable
timeserie = root.createVariable('timeserie', 'f4', ('datetime',))
timeserie.units = 'days since 1970-01-01 00:00:00 UTC' # reference: epoch
timeserie.calendar = 'gregorian'
# create testList
listDT = [dt.now(pytz.utc), dt(1970, 1, 2, 12, 0, 0, 0, pytz.utc)]
print date2num(listDT, units=timeserie.units, calendar=timeserie.calendar)
root.close()
</code></pre>
<p>The error it gives me:</p>
<blockquote>
<pre><code>Traceback (most recent call last):
File "test.py", line 20, in <module>
print date2num(listDT, units=timeserie.units, calendar=timeserie.calendar)
File "netCDF4\_netCDF4.pyx", line 5128, in netCDF4._netCDF4.date2num (netCDF4\_netCDF4.c:60367)
TypeError: can't subtract offset-naive and offset-aware datetimes
</code></pre>
</blockquote>
<p>How would I save datetime data (preferably timezone aware) to netcdf using python?</p>
| 1 | 2016-09-30T13:03:29Z | 39,797,924 | <p>The <a href="http://unidata.github.io/netcdf4-python/#netCDF4.date2num" rel="nofollow">date2num() doc</a> says that the datetime object must be UTC. A number cannot be timezone aware,unless it is UTC. Would cause great problems with standard/daylight time transitions.</p>
<p>Try</p>
<pre><code>listDT = [dt.now(), dt(1970, 1, 2, 12, 0, 0, 0)]
print date2num(listDT, units=timeserie.units, calendar=timeserie.calendar)
</code></pre>
<p>To demonstrate that it is timezone aware, try Eastern offset as units.</p>
<pre><code>print date2num(listDT, units='days since 1970-01-01 00:00:00-04:00', calendar=timeserie.calendar)
</code></pre>
| 0 | 2016-09-30T18:31:31Z | [
"python",
"datetime",
"netcdf"
]
|
catching a form with Flask (very basic case) | 39,792,231 | <p>I want to use a very simple form to post comments to a Flask server.</p>
<p>My index.html is:</p>
<pre><code><form method="post" enctype="text/plain">
Name:<br>
<input type="text" name="id"> <br>
Comment:<br>
<input type="text" name="comment"> <br>
<input type="submit" value="Submit">
</form>
</code></pre>
<p>The Flask app is:</p>
<pre><code>@app.route("/", methods=['GET', 'POST'])
def index():
if (request.method == 'POST'):
try:
print (request.form['id'])
print (request.form['comment'])
except KeyError:
print('KeyError')
return render_template('index.html')
app.run(host= '0.0.0.0')
</code></pre>
<p>I expect it to print the content of the form fields on the prompt output, but actually it prints "KeyError".
Where is the problem ?</p>
| -1 | 2016-09-30T13:03:33Z | 39,793,029 | <p>You're getting a KeyError there because <code>request.form</code> is a <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict" rel="nofollow"><code>ImmutableMultiDict</code></a> and a descendant of a python <code>dict</code>. You get <code>KeyError</code> raised when you try to access a key that doesn't exist.</p>
<p>This is happening because the key names you're trying to get don't match the HTML you've posted. You need to use the same field name you've entered in the HTML, so <code>nom</code> should be <code>id</code> and <code>remarks</code> should be <code>comment</code>?</p>
<p>But still you'll find that the snippet doesn't work. </p>
<p>This is because specifying <code>enctype="text/plain"</code> will prevent flask from parsing the POST'ed form-data into <code>request.form</code> as that is not a valid encoding for form submissions. See <a href="https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4" rel="nofollow">here</a>. Usually not setting <code>enctype</code> (or setting it to <code>application/x-www-form-urlencoded</code>) will suffice unless you have binary content or large sized payloads (usually file uploads) - if so set it to <code>multipart/form-data</code>.</p>
| 1 | 2016-09-30T13:44:55Z | [
"python",
"html",
"forms",
"flask"
]
|
How is this a coroutine? | 39,792,323 | <p>I'm trying to understand the coroutines in Python (and in general). Been reading about the theory, the concept and a few examples, but I'm still struggling. I understand the asynchronous model (did a bit of Twisted) but not coroutines yet.</p>
<p>One <a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">tutorial</a> gives this as a coroutine example (I made a few changes to illustrate my problem):</p>
<pre><code>async def download_coroutine(url, number):
"""
A coroutine to download the specified url
"""
request = urllib.request.urlopen(url)
filename = os.path.basename(url)
print("Downloading %s" % url)
with open(filename, 'wb') as file_handle:
while True:
print(number) # prints numbers to view progress
chunk = request.read(1024)
if not chunk:
print("Finished")
break
file_handle.write(chunk)
msg = 'Finished downloading {filename}'.format(filename=filename)
return msg
</code></pre>
<p>This is run with this</p>
<pre><code>coroutines = [download_coroutine(url, number) for number, url in enumerate(urls)]
completed, pending = await asyncio.wait(coroutines)
</code></pre>
<p>Looking at generator coroutines examples I can see a few <code>yield</code> statements. There's nothing here, and urllib is synchronous, AFAIK.</p>
<p>Also, since the code is supposed to be asynchronous, I am expecting to see a series of interleaved numbers. (1, 4, 5, 1, 2, ..., "Finished", ...) . What I'm seeing is a single number repeating ending in a <code>Finished</code> and then another one (3, 3, 3, 3, ... "Finished", 1, 1, 1, 1, ..., "Finished" ...).</p>
<p>At this point I'm tempted to say the tutorial is wrong, and this is a coroutine just because is has async in front.</p>
| 2 | 2016-09-30T13:08:18Z | 39,792,393 | <p>The <em>co</em> in <em>coroutine</em> stands for <em>cooperative</em>. Yielding (to other routines) makes a routine a co-routine, really, because only by yielding when waiting can other co-routines be interleaved. In the new <code>async</code> world of Python 3.5 and up, that usually is achieved by <code>await</code>-ing results from other coroutines.</p>
<p>By that definition, the code you found is <em>not</em> a coroutine. As far as <em>Python</em> is concerned, it is a coroutine <em>object</em>, because that's the type given to a function object created using <code>async def</code>.</p>
<p>So yes, the tutorial is.. unhelpful, in that they used entirely synchronous, uncooperative code inside a coroutine function.</p>
<p>Instead of <code>urllib</code>, an asynchronous HTTP library would be needed. Like <a href="http://aiohttp.readthedocs.io/en/stable/" rel="nofollow"><code>aiohttp</code></a>:</p>
<pre><code>import aiohttp
async def download_coroutine(url):
"""
A coroutine to download the specified url
"""
filename = os.path.basename(url)
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
with open(filename, 'wb') as fd:
while True:
chunk = await resp.content.read(1024)
if not chunk:
break
fd.write(chunk)
msg = 'Finished downloading {filename}'.format(filename=filename)
return msg
</code></pre>
<p>This coroutine can yield to other routines when waiting for a connection to be established, and when waiting for more network data, as well as when closing the session again.</p>
| 6 | 2016-09-30T13:12:16Z | [
"python",
"python-3.x",
"async-await",
"coroutine"
]
|
how to i use check button to show the snap | 39,792,541 | <p><strong>My program is designed to:</strong></p>
<ul>
<li><p>Initially, the Label shows nothing (i.e., it is empty).</p></li>
<li><p>Any number of the Checkbuttons may be selected by the user.</p></li>
<li><p>Any selected Checkbuttons may be unselected by the user.</p></li>
<li><p>When any two Checkbuttons are selected, the Label shows "Snap".</p></li>
<li><p>When any other number of Checkbuttons is selected, the Label shows
nothing (i.e., it is empty).</p></li>
</ul>
<p><strong>This is my code, so far</strong></p>
<pre><code>display = ScrolledText(the_window,font=('Arial',24),width =10,height =2,
borderwidth=2,relief='groove')
display.place(x=80,y=7)
def display_snap():
display.insert(END,'Snap')
if display_snap
checkbox = Checkbutton(the_window,command = display_snap)
checkbox.place(x=10,y=80)
checkbox2 = Checkbutton(the_window)
checkbox2.place(x=60 , y=80)
checkbox3 = Checkbutton(the_window)
checkbox3.place(x=110 , y=80)
checkbox4 = Checkbutton(the_window)
checkbox4.place(x=160 , y=80)
checkbox5 = Checkbutton(the_window)
checkbox5.place(x=210 , y=80)
</code></pre>
| -1 | 2016-09-30T13:19:09Z | 39,793,323 | <p>It looks like you're using Tkinter. As the <a href="http://effbot.org/tkinterbook/checkbutton.htm" rel="nofollow">Tkinter docs</a> say "each Checkbutton widget should be associated with a variable". You can detect whether the widget is selected or not by using the <code>.get()</code> method of the variable: a value of 0 means the button is unselected, 1 means it's selected.</p>
<p>Here's a simple program that stores the buttons' variables in a list. We can then use the built-in <code>sum</code> function to count how many buttons are selected, and update the text of the Label widget accordingly.</p>
<pre><code>import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='')
label.grid(row=0, column=0, columnspan=5)
def set_snap():
text = 'Snap' if sum(v.get() for v in states) == 2 else ''
label.config(text=text)
states = []
for i in range(5):
var = tk.IntVar()
states.append(var)
cb = tk.Checkbutton(root, variable=var, command=set_snap)
cb.grid(row=1, column=i)
root.mainloop()
</code></pre>
<p>The above code is for Python 3. To run it on Python 2, just change the <code>import</code> line to</p>
<pre><code>import Tkinter as tk
</code></pre>
| 3 | 2016-09-30T14:00:52Z | [
"python",
"tkinter"
]
|
Scrapy (python) TypeError: unhashable type: 'list' | 39,792,600 | <p>I have this simple scrappy code. However get this error when i use <code>response.urljoin(port_homepage_url)</code> this portion of the code.</p>
<pre><code>import re
import scrapy
from vesseltracker.items import VesseltrackerItem
class GetVessel(scrapy.Spider):
name = "getvessel"
allowed_domains = ["marinetraffic.com"]
start_urls = [
'http://www.marinetraffic.com/en/ais/index/ports/all/flag:AE',
]
def parse(self, response):
item = VesseltrackerItem()
for ports in response.xpath('//table/tr[position()>1]'):
item['port_name'] = ports.xpath('td[2]/a/text()').extract()
port_homepage_url = ports.xpath('td[7]/a/@href').extract()
port_homepage_url = response.urljoin(port_homepage_url)
yield scrapy.Request(port_homepage_url, callback=self.parse, meta={'item': item})
</code></pre>
<p>What could be wrong?</p>
<p>Here is the error log.</p>
<pre><code>2016-09-30 17:17:13 [scrapy] DEBUG: Crawled (200) <GET http://www.marinetraffic.com/robots.txt> (referer: None)
2016-09-30 17:17:14 [scrapy] DEBUG: Crawled (200) <GET http://www.marinetraffic.com/en/ais/index/ports/all/flag:AE> (referer: None)
2016-09-30 17:17:14 [scrapy] ERROR: Spider error processing <GET http://www.marinetraffic.com/en/ais/index/ports/all/flag:AE> (referer: None)
Traceback (most recent call last):
File "/Users/noussh/python/env/lib/python2.7/site-packages/scrapy/utils/defer.py", line 102, in iter_errback
yield next(it)
File "/Users/noussh/python/env/lib/python2.7/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output
for x in result:
File "/Users/noussh/python/env/lib/python2.7/site-packages/scrapy/spidermiddlewares/referer.py", line 22, in <genexpr>
return (_set_referer(r) for r in result or ())
File "/Users/noussh/python/env/lib/python2.7/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
return (r for r in result or () if _filter(r))
File "/Users/noussh/python/env/lib/python2.7/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr>
return (r for r in result or () if _filter(r))
File "/Users/noussh/python/vesseltracker/vesseltracker/spiders/marinetraffic.py", line 19, in parse
port_homepage_url = response.urljoin(port_homepage_url)
File "/Users/noussh/python/env/lib/python2.7/site-packages/scrapy/http/response/text.py", line 78, in urljoin
return urljoin(get_base_url(self), url)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py", line 261, in urljoin
urlparse(url, bscheme, allow_fragments)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py", line 143, in urlparse
tuple = urlsplit(url, scheme, allow_fragments)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py", line 176, in urlsplit
cached = _parse_cache.get(key, None)
TypeError: unhashable type: 'list'
</code></pre>
| 2 | 2016-09-30T13:22:17Z | 39,792,931 | <p>The <code>ports.xpath('td[7]/a/@href').extract()</code> returns a <em>list</em> and when you try to do the "urljoin" on it, it fails. Use <code>extract_first()</code> instead:</p>
<pre><code>port_homepage_url = ports.xpath('td[7]/a/@href').extract_first()
</code></pre>
| 2 | 2016-09-30T13:39:43Z | [
"python",
"scrapy"
]
|
Using Selenium to extract data provided by an autocomplete search | 39,792,641 | <p>I want to extract part of the result provided by a site's search bar's auto complete. I'm having trouble extracting the result. I'm able to enter the query I want, but I'm unable to store the autosuggestion. It seems whenever I click the drop down suggestions to "inspect element" in order to find what to select the drop down menu vanishes! </p>
<p>Here's the code I'm working with:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os
from scrapy.selector import HtmlXPathSelector
#launch chromedirver
driver.get("http://www.marinetraffic.com/en/ais/index/ports/all")
searchBox = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(
(By.XPATH, '//input[@id= "portname"]')
)
)
searchBox.click()
searchBox.clear()
a = searchBox.send_keys('Belawan') #so far so good
selen_html = driver.find_element_by_class_name('input-group').get_attribute('innerHTML')
hxs = HtmlXPathSelector(text=selen_html)
suggests = hxs.select('//div[@class= "input-group"/Belawan/@title').extract
driver.close()
</code></pre>
<p>The error, unsurprisingly, is <code>ValueError: XPath error: Invalid predicate in //div[@....[etc]</code>. How do I find the correct name to put in my XPath? </p>
<p>The autocomplete takes the form <code>BELAWAN - Port [ID]</code> the end goal is to pull out <code>ID</code>. </p>
<p>Edit:
<a href="http://imgur.com/a/cjpXk" rel="nofollow">screenshot</a></p>
| 0 | 2016-09-30T13:24:37Z | 39,792,898 | <p>This should work.
Basically you will have find the xpath locators of those web elements'</p>
<p>In your case it was like </p>
<pre><code><ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all" id="ui-id-3" tabindex="0" style="display: none; top: 375px; left: 63px; width: 306px;">
<li class="ui-menu-item" role="presentation"><a id="ui-id-7" class="ui-corner-all" tabindex="-1"><b>BELA</b>WAN&nbsp;-&nbsp;Port [ID]</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-8" class="ui-corner-all" tabindex="-1"><b>BELA</b>WAN ANCH&nbsp;-&nbsp;Ancorage [ID]</a></li>
</ul>
</code></pre>
<p>So I used id to get the other <code>ul</code> and then used <code>find_elements_by_xpath</code> to get list of childrend matching the xpath.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os
#launch chromedirver
driver = webdriver.Chrome()
driver.get("http://www.marinetraffic.com/en/ais/index/ports/all")
searchBox = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located(
(By.XPATH, '//input[@id= "portname"]')
)
)
searchBox.click()
searchBox.clear()
a = searchBox.send_keys('Belawan') #so far so good
web_elem_list = driver.find_element_by_id("ui-id-3").find_elements_by_xpath("//li[@role='presentation']/a")
suggests = [web_elem.text for web_elem in web_elem_list]
driver.close()
print suggests
# Will Give o/p
[u'BELAWAN - Port [ID]', u'BELAWAN ANCH - Ancorage [ID]']
</code></pre>
| 2 | 2016-09-30T13:37:37Z | [
"python",
"selenium",
"selenium-chromedriver"
]
|
How to get the reactor from ApplicationRunner in autobahnPython | 39,792,761 | <p>I have an autobahn client using the ApplicationRunner class from autobahn to connect to a WAMP router (crossbar). In the main section it attaches my ApplicationSession class "REScheduler" like this:</p>
<pre><code>if __name__ == '__main__':
from autobahn.twisted.wamp import ApplicationRunner
runner = ApplicationRunner(url=u"ws://localhost:8080/ws", realm=u"RE_acct")
runner.run(REScheduler, start_reactor=True, auto_reconnect=True)
</code></pre>
<p>Now I need the reactor that the application runner started for other purposes as well. Like e.g. to call some <code>reactor.callLater(...)</code>.
How can I access this reactor. I did not find anything in the docs.</p>
| 0 | 2016-09-30T13:31:07Z | 39,792,913 | <p>Twisted (sadly) uses a (process) global reactor object. That means, once a reactor is chosen (which <code>ApplicationRunner</code> does if you set <code>start_reactor=True</code>), simply do a <code>from twisted.internet import reactor</code> at <strong>the place within your code</strong> where you need it.</p>
<p>asyncio has properly encapsulated the event loop (you can have multiple event loops in a single process).</p>
<blockquote>
<p>txaio provides a convenience method that will work on both (it will expose the single, global reactor in Twisted, and it will expose the event loop under which ApplicationRunner is started): <code>txaio.config.loop = reactor</code></p>
</blockquote>
| 2 | 2016-09-30T13:38:17Z | [
"python",
"twisted",
"autobahn",
"crossbar"
]
|
Equating the lengths of the arrays in an array of arrays | 39,792,815 | <p>Given an array of arrays with different lengths. Is there a cleaner (shorter) way to equate the lengths of the arrays by filling the shorter ones with zeros other than the following code:</p>
<pre><code>a = [[1.0, 2.0, 3.0, 4.0],[2.0, 3.0, 1.0],[5.0, 5.0, 5.0, 5.0],[1.0, 1.0]]
max =0
for x in a:
if len(x) > max:
max = len(x)
print max
new = []
for x in a:
if len(x)<max:
x.extend([0.0]* (max-len(x)) )
new.append(x)
print new
</code></pre>
| 2 | 2016-09-30T13:33:31Z | 39,792,869 | <pre><code>In: b = [i+[0.]*(max(map(len,a))-len(i)) for i in a]
In: b
Out:
[[1.0, 2.0, 3.0, 4.0],
[2.0, 3.0, 1.0, 0.0],
[5.0, 5.0, 5.0, 5.0],
[1.0, 1.0, 0.0, 0.0]]
</code></pre>
| 1 | 2016-09-30T13:36:19Z | [
"python"
]
|
Equating the lengths of the arrays in an array of arrays | 39,792,815 | <p>Given an array of arrays with different lengths. Is there a cleaner (shorter) way to equate the lengths of the arrays by filling the shorter ones with zeros other than the following code:</p>
<pre><code>a = [[1.0, 2.0, 3.0, 4.0],[2.0, 3.0, 1.0],[5.0, 5.0, 5.0, 5.0],[1.0, 1.0]]
max =0
for x in a:
if len(x) > max:
max = len(x)
print max
new = []
for x in a:
if len(x)<max:
x.extend([0.0]* (max-len(x)) )
new.append(x)
print new
</code></pre>
| 2 | 2016-09-30T13:33:31Z | 39,792,878 | <p>You can find the length of the largest list within <code>a</code> using either:</p>
<p><code>len(max(a, key=len))</code> </p>
<p>or </p>
<p><code>max(map(len, a))</code></p>
<p>and also use a list comprehension to construct a new list:</p>
<pre><code>>>> a = [[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 1.0], [5.0, 5.0, 5.0, 5.0], [1.0, 1.0]]
>>> m = len(max(a, key=len))
>>> new = [x + [0]*(m - len(x)) for x in a]
>>> new
[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 1.0, 0], [5.0, 5.0, 5.0, 5.0], [1.0, 1.0, 0, 0]]
</code></pre>
| 5 | 2016-09-30T13:36:53Z | [
"python"
]
|
Django - Using multiple models for authentication | 39,792,837 | <p>I am kind of new to django and I am concerned about can we use multiple models for authentication for different types of users for our application e.g for Customers use Customer model, for Suppliers use Supplier model and also keep default User registration model for administration use only? If so can you point me in the right direction, how it can be done? Which package should be used?
There is one way that I came around is by adding a foreign key to each model viz needed for authentication but that will involve joins in every query which could result in performance issues. I need to know if there is a better way. An also these custom models can benefit for all permissions stuff available in admin panel.
Expert opinion will be really appreciated. </p>
| 0 | 2016-09-30T13:34:40Z | 39,794,111 | <p>There are a few different options to handle that.
Maybe check first <a href="https://docs.djangoproject.com/en/1.8/topics/auth/customizing/" rel="nofollow">the Django-docu</a>.
I've you'ld like to customize it to authenticate your users with a mail-address, there's a nice Tutorial <a class='doc-link' href="http://stackoverflow.com/documentation/django/1282/authentication-backends#t=201609301437273937302">right here!</a></p>
| 0 | 2016-09-30T14:40:27Z | [
"python",
"django",
"authentication",
"django-registration",
"custom-authentication"
]
|
Getting flask-restful routes from within a blueprint | 39,792,872 | <p>Is there a way to get the routes defined in a blueprint? I know this (<a href="http://flask.pocoo.org/snippets/117/" rel="nofollow">http://flask.pocoo.org/snippets/117/</a>) snippit exists, but requires to have the app initalized to use url_map. Is there a way to view the routes without an application? I'm developing an api with flask-restful and I would like to display the routes from within the blueprint without the app to keep it self contained.</p>
| 0 | 2016-09-30T13:36:35Z | 39,808,625 | <p>Using the information provided by polyfunc, I was able to come up with this solution:</p>
<pre><code>from flask import Blueprint, current_app, url_for
from flask_restful import Resource, Api
api_blueprint = Blueprint('api', __name__)
api = Api(api_blueprint)
@api.resource('/foo')
class Foo(Resource):
def get(self):
prefix = api_blueprint.name + '.' # registered classes will have this as their prefix
# Get current rules
rules = current_app.url_map.iter_rules()
# Get list from routes registered under the blueprint
routes = [url_for(rule.endpoint) for rule in rules if rule.endpoint.startswith(prefix)]
</code></pre>
| 0 | 2016-10-01T15:55:58Z | [
"python",
"flask",
"flask-restful"
]
|
Subquery with count in SQLAlchemy | 39,792,884 | <p>Given these SQLAlchemy model definitions:</p>
<pre><code>class Store(db.Model):
__tablename__ = 'store'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
class CustomerAccount(db.Model, AccountMixin):
__tablename__ = 'customer_account'
id = Column(Integer, primary_key=True)
plan_id = Column(Integer, ForeignKey('plan.id'), index=True, nullable=False)
store = relationship('Store', backref='account', uselist=False)
plan = relationship('Plan', backref='accounts', uselist=False)
class Plan(db.Model):
__tablename__ = 'plan'
id = Column(Integer, primary_key=True)
store_id = Column(Integer, ForeignKey('store.id'), index=True)
name = Column(String, nullable=False)
subscription_amount = Column(Numeric, nullable=False)
num_of_payments = Column(Integer, nullable=False)
store = relationship('Store', backref='plans')
</code></pre>
<p>How do I write a query to get a breakdown of subscription revenues by plan?
I'd like to get back a list of the plans for a given Store, and for each plan the total revenues for that plan, calculated by multiplying Plan.subscription_amount * Plan.num_of_payments * num of customers subscribed to that plan</p>
<p>At the moment I'm trying with this query and subquery:</p>
<pre><code>store = db.session.query(Store).get(1)
subscriber_counts = db.session.query(func.count(CustomerAccount.id)).as_scalar()
q = db.session.query(CustomerAccount.plan_id, func.sum(subscriber_counts * Plan.subscription_amount * Plan.num_of_payments))\
.outerjoin(Plan)\
.group_by(CustomerAccount.plan_id)
</code></pre>
<p>The problem is the subquery is not filtering on the current plan id.</p>
<p>I also tried with this other approach (no subquery):</p>
<pre><code>q = db.session.query(CustomerAccount.plan_id, func.count(CustomerAccount.plan_id) * Plan.subscription_amount * Plan.num_of_payments)\
.outerjoin(Plan)\
.group_by(CustomerAccount.plan_id, Plan.subscription_amount, Plan.num_of_payments)
</code></pre>
<p>And while the results seem fine, I don't know how to get back the plan name or other plan columns, as I'd need to add them to the group by (and that changes the results).</p>
<p>Ideally if a plan doesn't have any subscribers, I'd like it to be returned with a total amount of zero.</p>
<p>Thanks!</p>
| 0 | 2016-09-30T13:37:00Z | 39,795,716 | <p>Thanks to Alex Grönholm on #sqlalchemy I ended up with this working solution:</p>
<pre><code>from sqlalchemy.sql.expression import label
from sqlalchemy.sql.functions import coalesce
from instalment.models import db
from sqlalchemy import func, desc
def projected_total_money_volume_breakdown(store):
subscriber_counts = db.session.query(CustomerAccount.plan_id, func.count(CustomerAccount.id).label('count'))\
.group_by(CustomerAccount.plan_id)\
.subquery()
total_amount_exp = coalesce(subscriber_counts.c.count, 0) * Plan.subscription_amount * Plan.num_of_payments
return db.session.query(Plan, label('total_amount', total_amount_exp))\
.outerjoin(subscriber_counts, subscriber_counts.c.plan_id == Plan.id)\
.filter(Plan.store == store)\
.order_by(desc('total_amount'))\
.all()
</code></pre>
| 0 | 2016-09-30T16:06:21Z | [
"python",
"sql",
"sqlalchemy"
]
|
What are some ways to post python pandas dataframes to slack? | 39,792,891 | <p>How can I export a pandas dataframe to slack? </p>
<p>df.to_json() seems like a potential candidate, coupled with the slack incoming webhook, but then parsing the message to display as a nice markdown/html-ized table isn't obvious to me.</p>
<p>Long time listener, first time caller, please go easy on me...</p>
| 1 | 2016-09-30T13:37:19Z | 39,793,055 | <p>There is a <code>.to_html()</code> method on DataFrames, so that might work. But if you are just looking to cut and paste, <a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">Tabulate</a> is a good choice. From the docs:</p>
<pre><code>from tabulate import tabulate
df = pd.DataFrame([["Name","Age"],["Alice",24],["Bob",19]])
print tabulate(df, tablefmt="grid")
</code></pre>
<p>Returns</p>
<pre><code>+---+-------+-----+
| 0 | Name | Age |
+---+-------+-----+
| 1 | Alice | 24 |
+---+-------+-----+
| 2 | Bob | 19 |
+---+-------+-----+
</code></pre>
<p>Paste that in a code block in Slack and it should show up nicely.</p>
| 0 | 2016-09-30T13:46:47Z | [
"python",
"pandas",
"slack"
]
|
level curves with pyqtgraph: isocurve | 39,792,905 | <p>Does anybody know a way to obtain this (<a href="http://i.stack.imgur.com/SZLIl.png" rel="nofollow">level curves from matplotlib</a>) using isocurve from pyqtgraph?
Here's my code...</p>
<p>Thank you!</p>
<pre><code>from pyqtgraph.Qt import QtGui,QtCore
import numpy as np
import pyqtgraph as pg
import sys
#data creation
app=QtGui.QApplication([])
x = np.linspace(0,6.28,30)
y = x[:]
xx,yy = np.meshgrid(x,y)
z = np.sin(xx)+np.cos(yy)
win = pg.GraphicsWindow()
win.setWindowTitle('esempio isocurve')
vb = win.addViewBox()
img = pg.ImageItem(z)
vb.addItem(img) #visualizes img in viewbox vb
vb.setAspectLocked() #set img proportions (?)
c = pg.IsocurveItem(data=z,level=2,pen='r')
c.setParentItem(img) #set img as parent of the isocurve item c (?)
c.setZValue(10) #I DO NOT KNOW THE MEANING OF THIS, JUST COPIED FROM THE EXAMPLE isocurve.py
vb.addItem(c)
win.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-09-30T13:37:57Z | 39,835,334 | <p>[SOLVED] I had to edit the "functions.py" at row ~1500 in order to get rid of the error</p>
<pre><code>"TypeError: Cannot cast ufunc add output from dtype('int32') to dtype('uint8') with casting rule 'same_kind'".
</code></pre>
<p>The file "functions.py" is located in
C:\Users\my_name\AppData\Local\Programs\Python\Python35\Lib\site-packages\pyqtgraph (the windows search engine did not find it, as it was located inside a hidden folder!). Here's the modification suggested by <a href="https://groups.google.com/forum/#!topic/pyqtgraph/sG6NrMeHEwI" rel="nofollow">this Google Group</a>:</p>
<pre><code>index += (fields[i,j] * 2**vertIndex)
</code></pre>
<p>becomes</p>
<pre><code>index += (fields[i,j] * 2**vertIndex).astype(np.ubyte).
</code></pre>
<p>In my code, i had to set</p>
<pre><code>level=0
</code></pre>
<p>instead of</p>
<pre><code>level=2
</code></pre>
<p>, as 2 was greater than the maximum value of z. In other words, I was trying to draw a 2000m level curve for a 1500m mountain. Always remember to provide an appropriate level!!! <a href="http://i.stack.imgur.com/sxqs2.png" rel="nofollow">Here's the correct output</a> (-.-')</p>
| 0 | 2016-10-03T15:37:27Z | [
"python",
"surface",
"level",
"pyqtgraph"
]
|
Lazily create dask dataframe from generator | 39,792,928 | <p>I want to lazily create a Dask dataframe from a generator, which looks something like:</p>
<pre><code>[parser.read(local_file_name) for local_file_name in repo.download_files())]
</code></pre>
<p>Where both parser.read and repo.download_files return generators (using yield). parser.read yields a dictionary of key-value pairs, which (if I was just using plain pandas) would collect each dictionary in to a list, and then use:</p>
<pre><code>df = pd.DataFrame(parsed_rows)
</code></pre>
<p>What's the best way to create a dask dataframe from this? The reason is that a) I don't know necessarily the number of results returned, and b) I don't know the memory allocation of the machine that it will be deployed on.</p>
<p>Alternatively what should I be doing differently (e.g. maybe create a bunch of dataframes and then put those in to dask instead?)</p>
<p>Thanks.</p>
| 1 | 2016-09-30T13:39:33Z | 39,807,277 | <p>If you want to use the single-machine Dask scheduler then you'll need to know how many files you have to begin with. This might be something like the following:</p>
<pre><code>filenames = repo.download_files()
dataframes = [delayed(load)(filename) for filename in filenames]
df = dd.from_delayed(dataframes)
</code></pre>
<p>If you use the <a href="http://distributed.readthedocs.io/en/latest/" rel="nofollow">distributed scheduler</a> you can add new computations on the fly, but this is a bit more advanced.</p>
| 1 | 2016-10-01T13:34:52Z | [
"python",
"pandas",
"dask"
]
|
Resampling Error : cannot reindex a non-unique index with a method or limit | 39,792,933 | <p>I am using Pandas to structure and process Data.</p>
<p>I have here a DataFrame with dates as index, Id and bitrate.
I want to group my Data by Id and resample, at the same time, timedates which are relative to every Id, and finally keep the bitrate score.</p>
<p>For example, given :</p>
<pre><code>df = pd.DataFrame(
{'Id' : ['CODI126640013.ts', 'CODI126622312.ts'],
'beginning_time':['2016-07-08 02:17:42', '2016-07-08 02:05:35'],
'end_time' :['2016-07-08 02:17:55', '2016-07-08 02:26:11'],
'bitrate': ['3750000', '3750000'],
'type' : ['vod', 'catchup'],
'unique_id' : ['f2514f6b-ce7e-4e1a-8f6a-3ac5d524be30', 'f2514f6b-ce7e-4e1a-8f6a-3ac5d524bb22']})
</code></pre>
<p>which gives :</p>
<p><a href="http://i.stack.imgur.com/1g8sE.png" rel="nofollow"><img src="http://i.stack.imgur.com/1g8sE.png" alt="enter image description here"></a></p>
<p>This is my code to get a unique column for dates with every time the Id and the bitrate :</p>
<pre><code>df = df.drop(['type', 'unique_id'], axis=1)
df.beginning_time = pd.to_datetime(df.beginning_time)
df.end_time = pd.to_datetime(df.end_time)
df = pd.melt(df, id_vars=['Id','bitrate'], value_name='dates').drop('variable', axis=1)
df.set_index('dates', inplace=True)
</code></pre>
<p>which gives :</p>
<p><a href="http://i.stack.imgur.com/HXi3M.png" rel="nofollow"><img src="http://i.stack.imgur.com/HXi3M.png" alt="enter image description here"></a></p>
<p>And now, time for Resample !
This is my code :</p>
<pre><code>print (df.groupby('Id').resample('1S').ffill())
</code></pre>
<p>And this is the result :</p>
<p><a href="http://i.stack.imgur.com/KkAvd.png" rel="nofollow"><img src="http://i.stack.imgur.com/KkAvd.png" alt="enter image description here"></a></p>
<p>This is exactly what I want to do !
I have 38279 logs with the same columns and I have an error message when I do the same thing. The first part works perfectly, and gives this :</p>
<p><a href="http://i.stack.imgur.com/QsH0s.png" rel="nofollow"><img src="http://i.stack.imgur.com/QsH0s.png" alt="enter image description here"></a></p>
<p>The part <strong>(df.groupby('Id').resample('1S').ffill())</strong> gives this error message :</p>
<pre><code>ValueError: cannot reindex a non-unique index with a method or limit
</code></pre>
<p>Any ideas ? Thnx !</p>
| 2 | 2016-09-30T13:39:44Z | 39,793,110 | <p>It seems there is problem with duplicates in columns <code>beginning_time</code> and <code>end_time</code>, I try simulate it:</p>
<pre><code>df = pd.DataFrame(
{'Id' : ['CODI126640013.ts', 'CODI126622312.ts', 'a'],
'beginning_time':['2016-07-08 02:17:42', '2016-07-08 02:17:42', '2016-07-08 02:17:45'],
'end_time' :['2016-07-08 02:17:42', '2016-07-08 02:17:42', '2016-07-08 02:17:42'],
'bitrate': ['3750000', '3750000', '444'],
'type' : ['vod', 'catchup', 's'],
'unique_id':['f2514f6b-ce7e-4e1a-8f6a-3ac5d524be30', 'f2514f6b-ce7e-4e1a-8f6a-3ac5d524bb22','w']})
print (df)
Id beginning_time bitrate end_time \
0 CODI126640013.ts 2016-07-08 02:17:42 3750000 2016-07-08 02:17:42
1 CODI126622312.ts 2016-07-08 02:17:42 3750000 2016-07-08 02:17:42
2 a 2016-07-08 02:17:45 444 2016-07-08 02:17:42
type unique_id
0 vod f2514f6b-ce7e-4e1a-8f6a-3ac5d524be30
1 catchup f2514f6b-ce7e-4e1a-8f6a-3ac5d524bb22
2 s w
</code></pre>
<pre><code>df = df.drop(['type', 'unique_id'], axis=1)
df.beginning_time = pd.to_datetime(df.beginning_time)
df.end_time = pd.to_datetime(df.end_time)
df = pd.melt(df, id_vars=['Id','bitrate'], value_name='dates').drop('variable', axis=1)
df.set_index('dates', inplace=True)
print (df)
Id bitrate
dates
2016-07-08 02:17:42 CODI126640013.ts 3750000
2016-07-08 02:17:42 CODI126622312.ts 3750000
2016-07-08 02:17:45 a 444
2016-07-08 02:17:42 CODI126640013.ts 3750000
2016-07-08 02:17:42 CODI126622312.ts 3750000
2016-07-08 02:17:42 a 444
print (df.groupby('Id').resample('1S').ffill())
</code></pre>
<blockquote>
<p>ValueError: cannot reindex a non-unique index with a method or limit</p>
</blockquote>
<p>One possible solution is add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a> and use old <a href="http://stackoverflow.com/a/37296822/2901002">way</a> for <code>resample</code> with <code>groupby</code>:</p>
<pre><code>df = df.drop(['type', 'unique_id'], axis=1)
df.beginning_time = pd.to_datetime(df.beginning_time)
df.end_time = pd.to_datetime(df.end_time)
df = pd.melt(df, id_vars=['Id','bitrate'], value_name='dates').drop('variable', axis=1)
print (df.groupby('Id').apply(lambda x : x.drop_duplicates('dates')
.set_index('dates')
.resample('1S')
.ffill()))
Id bitrate
Id dates
CODI126622312.ts 2016-07-08 02:17:42 CODI126622312.ts 3750000
CODI126640013.ts 2016-07-08 02:17:42 CODI126640013.ts 3750000
a 2016-07-08 02:17:41 a 444
2016-07-08 02:17:42 a 444
2016-07-08 02:17:43 a 444
2016-07-08 02:17:44 a 444
2016-07-08 02:17:45 a 444
</code></pre>
<p>You can also check duplicates by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (df[df.beginning_time == df.end_time])
2 s w
Id beginning_time bitrate end_time \
0 CODI126640013.ts 2016-07-08 02:17:42 3750000 2016-07-08 02:17:42
1 CODI126622312.ts 2016-07-08 02:17:42 3750000 2016-07-08 02:17:42
type unique_id
0 vod f2514f6b-ce7e-4e1a-8f6a-3ac5d524be30
1 catchup f2514f6b-ce7e-4e1a-8f6a-3ac5d524bb22
</code></pre>
| 2 | 2016-09-30T13:49:21Z | [
"python",
"python-2.7",
"pandas",
"group-by",
"resampling"
]
|
write unicode objects from loop to list in Python | 39,793,030 | <p>I have a loop that returns me unicode objects:</p>
<pre><code>for i in X:
print i
Output:
A
B
C
...
Z
</code></pre>
<p>How can I make a list of these objects to get the folloving?</p>
<pre><code>['A', 'B', ..., 'Z']
</code></pre>
<p>If they were numbers, i'd do</p>
<pre><code>for i in X:
y=[]
i.append(y)
</code></pre>
<p>but here i get the error </p>
<pre><code>AttributeError: 'unicode' object has no attribute 'append'
</code></pre>
| -1 | 2016-09-30T13:45:00Z | 39,793,062 | <p>try this:</p>
<p><code>output_list = [y for y in x]</code></p>
<p>in your loop:</p>
<pre><code>for i in X:
i.append(X)
</code></pre>
<p>it takes each item in <code>X</code>, which are unicode chars, and tries to append the whole <code>X</code> object to it.</p>
<p>I think what you're wanting to do is like this:</p>
<pre><code>l = []
for i in X:
l.append(i)
print l
</code></pre>
<p>but this can be accomplished with simple list comprehension showed above.</p>
| 0 | 2016-09-30T13:46:59Z | [
"python",
"list",
"unicode",
"append"
]
|
write unicode objects from loop to list in Python | 39,793,030 | <p>I have a loop that returns me unicode objects:</p>
<pre><code>for i in X:
print i
Output:
A
B
C
...
Z
</code></pre>
<p>How can I make a list of these objects to get the folloving?</p>
<pre><code>['A', 'B', ..., 'Z']
</code></pre>
<p>If they were numbers, i'd do</p>
<pre><code>for i in X:
y=[]
i.append(y)
</code></pre>
<p>but here i get the error </p>
<pre><code>AttributeError: 'unicode' object has no attribute 'append'
</code></pre>
| -1 | 2016-09-30T13:45:00Z | 39,793,159 | <p>If you are looping through a variable, you already know it is an iterable, such as a generator or list. First, you need to tell us the type of the <code>x</code> variable in your statement.</p>
<p>If your expected output is a list and <code>x</code> is not one, simply call the <code>list</code> function:</p>
<pre><code>new_list = list(x)
</code></pre>
<p>If it's necessary that you build the list in a loop for some reason, you should call the <code>append</code> function on a previously created list--not an item, as you do in your example:</p>
<pre><code>new_list = []
for i in x:
new_list.append(i)
print (new_list)
</code></pre>
| 0 | 2016-09-30T13:51:20Z | [
"python",
"list",
"unicode",
"append"
]
|
sqlite3 INSERT IF NOT EXIST (with Python) | 39,793,327 | <p>First of all, I am really super-new so I hope that I will be able to post the question correctly. Please tell me if there is any problem.</p>
<p>Now, here is my question: I would like to fill a database with a data, only if it doesn't already exist in it. I searched for this topic and I think I found correct the answer (you can read one example here: [<a href="http://stackoverflow.com/questions/19337029/insert-if-not-exists-statement-in-sqlite]">"Insert if not exists" statement in SQLite</a>) but I need to write these simple command line in python.. and that's my problem. (I anticipate that I am quite new in Python too)</p>
<p>So, here is what I did:</p>
<pre><code> self.cur.execute("INSERT INTO ProSolut VALUES('a','b','c')")
self.cur.execute("SELECT * FROM ProSolut")
self.cur.execute("WHERE NOT EXISTS (SELECT * FROM ProSolut WHERE VALUES = ('a','b','c'))")
</code></pre>
<p>and here's the error:</p>
<pre><code>[ERROR] behavior.box :_safeCallOfUserMethod:125 _Behavior__lastUploadedChoregrapheBehaviorbehavior_1142022496:/ProSolutDB_11: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/albehavior.py", line 113, in _safeCallOfUserMethod func(functionArg) File "<string>", line 45, in onInput_onStart OperationalError: near "WHERE": syntax error
</code></pre>
<p>so basically I think there is some problem with the bracket "(" in the 3rd string. --> ("OperationalError: near "WHERE": syntax error")</p>
<p>I know that probably it's a stupid error.
If you can help me, I would really appreciate. </p>
<p>Thank you so much</p>
<hr>
<p>E.G.: I forgot to say that I am using the <strong>software Choregraphe</strong>, which uses the Python language to construct all the functional blocks.
That means that, even if the language is basically Python, sometimes the semantic is not perfectly the same.
I hope that this post can help someone in the future.</p>
| 0 | 2016-09-30T14:01:09Z | 39,794,247 | <p>First, you need to combine everything into a single <code>self.cur.execute()</code> call. Each call to this must be a complete query, they're not concatenated to each other.</p>
<p>Second, you can't have both <code>VALUES</code> and <code>SELECT</code> as the source of data in an
<code>INSERT</code> query, it has to be one or the other.</p>
<p>Third, you don't want to select from your table as the source of the data, as that will insert a new row for every row in the table that matches the <code>WHERE</code> expression (which is either all or none, because the <code>WHERE</code> expression doesn't refer to anything in the row being selected). You just want to select the values by themselves.</p>
<pre><code>this.cur.execute("""
INSERT INTO ProSolut (col1, col2, col3)
SELECT 'a', 'b', 'c'
WHERE NOT EXISTS (SELECT * FROM ProSolut WHERE col1 = 'a', col2 = 'b', col3 = 'c';
""")
</code></pre>
<p>Replace <code>col1</code>, <code>col2</code>, <code>col3</code> with the actual names of the columns you're filling in.</p>
<p>If any or all of the columns are a unique key in the table, you could just use <code>INSERT OR IGNORE</code>:</p>
<pre><code>this.cur.execute("""
INSERT OR IGNORE INTO ProSolut (col1, col2, col3)
VALUES ('a', 'b', 'c');
""");
</code></pre>
| 0 | 2016-09-30T14:47:25Z | [
"python",
"database",
"sqlite",
"sqlite3",
"insert"
]
|
sqlite3 INSERT IF NOT EXIST (with Python) | 39,793,327 | <p>First of all, I am really super-new so I hope that I will be able to post the question correctly. Please tell me if there is any problem.</p>
<p>Now, here is my question: I would like to fill a database with a data, only if it doesn't already exist in it. I searched for this topic and I think I found correct the answer (you can read one example here: [<a href="http://stackoverflow.com/questions/19337029/insert-if-not-exists-statement-in-sqlite]">"Insert if not exists" statement in SQLite</a>) but I need to write these simple command line in python.. and that's my problem. (I anticipate that I am quite new in Python too)</p>
<p>So, here is what I did:</p>
<pre><code> self.cur.execute("INSERT INTO ProSolut VALUES('a','b','c')")
self.cur.execute("SELECT * FROM ProSolut")
self.cur.execute("WHERE NOT EXISTS (SELECT * FROM ProSolut WHERE VALUES = ('a','b','c'))")
</code></pre>
<p>and here's the error:</p>
<pre><code>[ERROR] behavior.box :_safeCallOfUserMethod:125 _Behavior__lastUploadedChoregrapheBehaviorbehavior_1142022496:/ProSolutDB_11: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/albehavior.py", line 113, in _safeCallOfUserMethod func(functionArg) File "<string>", line 45, in onInput_onStart OperationalError: near "WHERE": syntax error
</code></pre>
<p>so basically I think there is some problem with the bracket "(" in the 3rd string. --> ("OperationalError: near "WHERE": syntax error")</p>
<p>I know that probably it's a stupid error.
If you can help me, I would really appreciate. </p>
<p>Thank you so much</p>
<hr>
<p>E.G.: I forgot to say that I am using the <strong>software Choregraphe</strong>, which uses the Python language to construct all the functional blocks.
That means that, even if the language is basically Python, sometimes the semantic is not perfectly the same.
I hope that this post can help someone in the future.</p>
| 0 | 2016-09-30T14:01:09Z | 39,794,295 | <p>Assuming <code>a</code> is in a column called "Col1", <code>b</code> is in "Col2" and <code>c</code> is in "Col3", the following should check for the existence of such a row:</p>
<pre><code>self.cur.execute('SELECT * FROM ProSolut WHERE (Col1=? AND Col2=? AND Col3=?)', ('a', 'b', 'c'))
entry = self.cur.fetchone()
if entry is None:
print 'No entry found'
else:
print 'Entry found'
</code></pre>
<p>This selects all entries in <code>ProSolut</code> that match these values. <code>fetchone</code> then tries to grab a result of this query - if there are no such matches then it returns <code>None</code>.</p>
<p><strong>EDIT:</strong> In line with Barmar's comment, to make this insert the values, adapt to the following:</p>
<pre><code>self.cur.execute('SELECT * FROM ProSolut WHERE (Col1=? AND Col2=? AND Col3=?)', ('a', 'b', 'c'))
entry = self.cur.fetchone()
if entry is None:
self.cur.execute('INSERT INTO ProSolut (Col1, Col2, Col3) VALUES (?,?,?)', ('a', 'b', 'c'))
print 'New entry added'
else:
print 'Entry found'
</code></pre>
<p>You'll need to make sure you <code>commit()</code> your changes too!</p>
| 0 | 2016-09-30T14:49:42Z | [
"python",
"database",
"sqlite",
"sqlite3",
"insert"
]
|
Mykrobe predictor AMR prediction not working | 39,793,340 | <p>I am getting the following error message when trying to execute AMR prediction on the command line.</p>
<pre><code>mykrobe predict tb_sample_id tb -1 /home/TB/demo_input_file_for_M.tuberculosis_app.fastq
</code></pre>
<p>The species chosen was Tuberculosis (TB), whereas the sample data file was pulled down from Mykrobe website (<a href="https://github.com/iqbal-lab/Mykrobe-predictor/releases/download/v0.1.1-beta/demo_input_file_for_M.tuberculosis_app.fastq.gz" rel="nofollow">https://github.com/iqbal-lab/Mykrobe-predictor/releases/download/v0.1.1-beta/demo_input_file_for_M.tuberculosis_app.fastq.gz</a>).</p>
<p>and the error message I'm getting...</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/mykrobe", line 9, in <module>
load_entry_point('mykrobe==0.4.2', 'console_scripts', 'mykrobe')()
File "/usr/local/lib/python2.7/site-packages/mykrobe/mykrobe_predictor.py", line 99, in main
args.func(parser, args)
File "/usr/local/lib/python2.7/site-packages/mykrobe/mykrobe_predictor.py", line 32, in run_subtool
run(parser, args)
File "/usr/local/lib/python2.7/site-packages/mykrobe/cmds/amr.py", line 127, in run
cp.run()
File "/usr/local/lib/python2.7/site-packages/mykatlas/typing/typer/genotyper.py", line 73, in run
self._run_cortex()
File "/usr/local/lib/python2.7/site-packages/mykatlas/typing/typer/genotyper.py", line 90, in _run_cortex
self.mc_cortex_runner.run()
File "/usr/local/lib/python2.7/site-packages/mykatlas/cortex/mccortex.py", line 161, in run
self._run_cortex()
File "/usr/local/lib/python2.7/site-packages/mykatlas/cortex/mccortex.py", line 173, in _run_cortex
self._build_panel_binary_if_required()
File "/usr/local/lib/python2.7/site-packages/mykatlas/cortex/mccortex.py", line 190, in _build_panel_binary_if_required
subprocess.check_output(cmd)
File "/usr/local/lib/python2.7/subprocess.py", line 566, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/local/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>Any suggestions would be appreciated.</p>
| 1 | 2016-09-30T14:01:54Z | 39,795,539 | <p>The error indicates that <code>mccortex31</code> is missing. </p>
<p>Did you install it according to the <a href="https://github.com/iqbal-lab/Mykrobe-predictor" rel="nofollow">documentation</a>?</p>
<pre><code>cd Mykrobe-predictor
cd mccortex
make
export PATH=$PATH:$(pwd)/bin
cd ..
</code></pre>
| 1 | 2016-09-30T15:56:35Z | [
"python",
"linux",
"sequence",
"bioinformatics"
]
|
dropbox object does not have Dropbox attribute in Python | 39,793,429 | <p>I am now using Python to download files from Dropbox, and I following <a href="https://www.dropbox.com/developers/documentation/python#tutorial" rel="nofollow">this tutorial</a>. However, it did not succeed on the first two lines of codes:</p>
<pre><code>import dropbox
dbx = dropbox.Dropbox('YOUR_ACCESS_TOKEN')
</code></pre>
<p>My Python complains that <code>AttributeError: 'module' object has no attribute 'Dropbox'</code> Any ideas?</p>
| 0 | 2016-09-30T14:06:14Z | 39,795,219 | <p>After careful examination, I found the reason is because I am using functions from dropbox-v2 while in my machine dropbox-v1 was installed. </p>
| 0 | 2016-09-30T15:39:49Z | [
"python",
"dropbox-api"
]
|
Python -Two figures in one plot | 39,793,508 | <p>I have two python plot functions: </p>
<pre><code>def plotData(data):
fig, ax = plt.subplots()
results_accepted = data[data['accepted'] == 1]
results_rejected = data[data['accepted'] == 0]
ax.scatter(results_accepted['exam1'], results_accepted['exam2'], marker='+', c='b', s=40)
ax.scatter(results_rejected['exam1'], results_rejected['exam2'], marker='o', c='r', s=30)
ax.set_xlabel('Exam 1 score')
ax.set_ylabel('Exam 2 score')
return ax
</code></pre>
<p>And second function is:</p>
<pre><code>def plot_boundry(theta,x):
"""
"""
plt.figure(1)
px = np.array([x[:, 1].min() - 2, x[:, 1].max() + 2])
py = (-1 / theta[2]) * (theta[1] * px + theta[0])
fig, ax = plt.subplots()
ax.plot(px, py)
return ax
</code></pre>
<p>And i am calling both :</p>
<pre><code>#####PLOT ######
ax = plotData(df)
ax = plot_boundry(opt_theta, x)
</code></pre>
<p>I get 2 separate plots:<br>
<a href="http://i.stack.imgur.com/j60xl.png" rel="nofollow"><img src="http://i.stack.imgur.com/j60xl.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/GszfC.png" rel="nofollow"><img src="http://i.stack.imgur.com/GszfC.png" alt="enter image description here"></a></p>
<p>I got 2 separate picture.How Do I add two plot into one.
Both the plot should be one plot.</p>
| 3 | 2016-09-30T14:09:50Z | 39,793,589 | <p>It depends what you want exactly:</p>
<ol>
<li><p>If you want the two figures overlayed, then you can call <a href="http://stackoverflow.com/questions/21465988/python-equivalent-to-hold-on-in-matlab"><code>hold</code></a><code>(True)</code> after the first, then plot the second, then call <code>hold(False)</code>.</p></li>
<li><p>If you want the two figures in a single figure, but side by side (or one over the other), then you can use <a href="http://matplotlib.org/examples/pylab_examples/subplot_demo.html" rel="nofollow"><code>subplot</code></a>. E.g., call <code>subplot(2, 1, 1)</code> before plotting the first, then <code>subplot(2, 1, 2)</code> before the second.</p></li>
</ol>
| 2 | 2016-09-30T14:14:11Z | [
"python",
"matplotlib"
]
|
how to halt python program after pdb.set_trace() | 39,793,521 | <p>When debugging scripts in Python (2.7, running on Linux) I occasionally inject pdb.set_trace() (note that I'm actually using ipdb), e.g.:</p>
<pre><code>import ipdb as pdb
try:
do_something()
# I'd like to look at some local variables before running do_something_dangerous()
pdb.set_trace()
except:
pass
do_something_dangerous()
</code></pre>
<p>I typically run my script from the shell, e.g.</p>
<pre><code>python my_script.py
</code></pre>
<p>Sometimes during my debugging session I realize that I don't want to run do_something_dangerous(). What's the easiest way to halt program execution so that do_something_dangerous() is not run and I can quit back to the shell?</p>
<p>As I understand it pressing ctrl-d (or issuing the debugger's quit command) will simply exit ipdb and the program will continue running (in my example above). Pressing ctrl-c seems to raise a KeyboardInterrupt but I've never understood the context in which it was raised.</p>
<p>I'm hoping for something like ctrl-q to simply take down the entire process, but I haven't been able to find anything.</p>
<p>I understand that my example is highly contrived, but my question is about how to abort execution from pdb when the code being debugged is set up to catch exceptions. It's not about how to restructure the above code so it works!</p>
| 2 | 2016-09-30T14:10:25Z | 39,793,564 | <p>From the <a href="https://docs.python.org/3/library/pdb.html#pdbcommand-quit" rel="nofollow">module docs</a>:</p>
<blockquote>
<p>q(uit)
Quit from the debugger. The program being executed is aborted.</p>
</blockquote>
<p>Specifically, this will cause the next debugger function that gets called to raise a <a href="https://docs.python.org/3/library/bdb.html#bdb.BdbQuit" rel="nofollow"><code>BdbQuit</code></a> exception. </p>
| 0 | 2016-09-30T14:12:59Z | [
"python",
"pdb",
"ipdb"
]
|
how to halt python program after pdb.set_trace() | 39,793,521 | <p>When debugging scripts in Python (2.7, running on Linux) I occasionally inject pdb.set_trace() (note that I'm actually using ipdb), e.g.:</p>
<pre><code>import ipdb as pdb
try:
do_something()
# I'd like to look at some local variables before running do_something_dangerous()
pdb.set_trace()
except:
pass
do_something_dangerous()
</code></pre>
<p>I typically run my script from the shell, e.g.</p>
<pre><code>python my_script.py
</code></pre>
<p>Sometimes during my debugging session I realize that I don't want to run do_something_dangerous(). What's the easiest way to halt program execution so that do_something_dangerous() is not run and I can quit back to the shell?</p>
<p>As I understand it pressing ctrl-d (or issuing the debugger's quit command) will simply exit ipdb and the program will continue running (in my example above). Pressing ctrl-c seems to raise a KeyboardInterrupt but I've never understood the context in which it was raised.</p>
<p>I'm hoping for something like ctrl-q to simply take down the entire process, but I haven't been able to find anything.</p>
<p>I understand that my example is highly contrived, but my question is about how to abort execution from pdb when the code being debugged is set up to catch exceptions. It's not about how to restructure the above code so it works!</p>
| 2 | 2016-09-30T14:10:25Z | 39,802,284 | <p>I found that ctrl-z to suspend the python/ipdb process, followed by 'kill %1' to terminate the process works well and is reasonably quick for me to type (with a bash alias k='kill %1'). I'm not sure if there's anything cleaner/simpler though.</p>
| 1 | 2016-10-01T01:56:45Z | [
"python",
"pdb",
"ipdb"
]
|
Reverse redirect does not work but inserts data into db | 39,793,640 | <pre><code>from django.db import models
from django.core.urlresolvers import reverse
class Gallery(models.Model):
Title = models.CharField(max_length=250)
Category = models.CharField(max_length=250)
Gallery_logo = models.CharField(max_length=1000)
def get_absolute_url(self):
return reverse('photos:detail', kwargs={'pk', self.pk})
def __str__(self):
return self.Title + '_' + self.Gallery_logo
class Picture (models.Model):
Gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
Title = models.CharField(max_length=250)
Artist = models.CharField(max_length=250)
Price = models.CharField(max_length=20)
interested = models.BooleanField(default=False)
def __str__(self):
return self.Title
</code></pre>
<p>Am getting this error below </p>
<pre><code>TypeError at /photos/gallery/add/
_reverse_with_prefix() argument after ** must be a mapping, not set
Request Method: POST
Request URL: http://127.0.0.1:8000/photos/gallery/add/
Django Version: 1.10.1
Exception Type: TypeError
Exception Value:
_reverse_with_prefix() argument after ** must be a mapping, not set
Exception Location: C:\Users\JK\AppData\Local\Programs\Python\Python35\lib\site-packages\django-1.10.1-py3.5.egg\django\urls\base.py in reverse, line 91
Python Executable: C:\Users\JK\AppData\Local\Programs\Python\Python35\python.exe
Python Version: 3.5.2
Python Path:
['C:\\Users\\JK\\PycharmProjects\\catalog',
'C:\\Users\\JK\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-packages\\django-1.10.1-py3.5.egg',
'C:\\Users\\JK\\PycharmProjects\\catalog',
'C:\\Users\\JK\\AppData\\Local\\Programs\\Python\\Python35\\python35.zip',
'C:\\Users\\JK\\AppData\\Local\\Programs\\Python\\Python35\\DLLs',
'C:\\Users\\JK\\AppData\\Local\\Programs\\Python\\Python35\\lib',
'C:\\Users\\JK\\AppData\\Local\\Programs\\Python\\Python35',
'C:\\Users\\JK\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-packages']
Server time: Fri, 30 Sep 2016 17:15:55 +0300
</code></pre>
<p>Again am just a newbie </p>
| 0 | 2016-09-30T14:16:40Z | 39,793,730 | <p>You're passing <code>kwargs</code> to <code>reverse</code> as a <em>set</em>, when it should be a dictionary:</p>
<pre><code>kwargs={'pk': self.pk}
# ^
</code></pre>
| 2 | 2016-09-30T14:20:45Z | [
"python",
"django",
"python-2.7"
]
|
Installing pyfm in virtual envornment | 39,793,646 | <p>I am not able to install the <a href="https://github.com/coreylynch/pyFM" rel="nofollow"><code>pyFM</code> module</a> in my virtualenv, only globally.</p>
<p>When I try to install it I get <code>ImportError: No module named Cython.Distutils</code>. However, when I try to <code>pip install cython</code>, I get <code>unable to execute gcc-4.2: No such file or directory</code>.</p>
<p>I've even tried to <code>ln -s /usr/bin/gcc gcc-4.2</code> but it doesn't work.</p>
| 0 | 2016-09-30T14:17:02Z | 39,807,075 | <p>When linking gcc, you are linking it to the current folder, not <code>/usr/bin</code>. Try</p>
<p><code>ln -s /usr/bin/gcc-4.2 /usr/bin/gcc</code></p>
<p>to link into /usr/bin so your OS finds it. You can also do <code>brew install gcc</code> if you use homebrew to get the latest version.</p>
| 0 | 2016-10-01T13:16:16Z | [
"python",
"virtualenv"
]
|
split a list according to size of float entries | 39,793,681 | <p>I have a list of floats where the size at each sequential index can vary.
i.e.</p>
<pre><code>float_list = [167.233, 95.6242, 181.367, 20.6354, 147.505, 41.9396, 20.3126]
</code></pre>
<p>What I am trying to do is to split the list according to the size of the floats in the indices. In particular, if the float at one index is less than that at the index before, then group the indices together to return the total number of indices that are less than those before.</p>
<p>For example, if we start from the first index the value is 167.233. Because the value at the next index, 95.6242, is smaller than that of the one prior, I would like to group these two together to return their length i.e. 2.</p>
<p>The third index is larger than the second, so this becomes the new 'benchmark'. Since the following index is smaller than that at the third, this returns the length 2.
The fifth index is the next 'benchmark' and the floats at the remaining indices decrease, therefore returning the length of those indices 3.</p>
<p>The way in which I would like this returned, is a list of the length of those indices i.e [2,2,3]</p>
<p>Apologies in advance if this is confusing, it is difficult to explain in words.</p>
| 0 | 2016-09-30T14:18:40Z | 39,793,873 | <p>Use <code>numpy.diff</code> and <code>numpy.where</code> in order to find the indices that the items are not ordered, then use <code>numpy.split()</code> to split the array in that indices, and finally use <code>map()</code> to find the length of splitted arrays:</p>
<pre><code>In [19]: import numpy as np
In [20]: float_list = np.array([167.233, 95.6242, 181.367, 20.6354, 147.505, 41.9396, 20.3126])
# In [22]: np.split(float_list, np.where(np.diff(float_list) > 0)[0] + 1)
# Out[22]:
# [array([ 167.233 , 95.6242]),
# array([ 181.367 , 20.6354]),
# array([ 147.505 , 41.9396, 20.3126])]
In [23]: map(len, np.split(float_list, np.where(np.diff(float_list) > 0)[0] + 1))
Out[23]: [2, 2, 3]
</code></pre>
| 2 | 2016-09-30T14:28:00Z | [
"python"
]
|
split a list according to size of float entries | 39,793,681 | <p>I have a list of floats where the size at each sequential index can vary.
i.e.</p>
<pre><code>float_list = [167.233, 95.6242, 181.367, 20.6354, 147.505, 41.9396, 20.3126]
</code></pre>
<p>What I am trying to do is to split the list according to the size of the floats in the indices. In particular, if the float at one index is less than that at the index before, then group the indices together to return the total number of indices that are less than those before.</p>
<p>For example, if we start from the first index the value is 167.233. Because the value at the next index, 95.6242, is smaller than that of the one prior, I would like to group these two together to return their length i.e. 2.</p>
<p>The third index is larger than the second, so this becomes the new 'benchmark'. Since the following index is smaller than that at the third, this returns the length 2.
The fifth index is the next 'benchmark' and the floats at the remaining indices decrease, therefore returning the length of those indices 3.</p>
<p>The way in which I would like this returned, is a list of the length of those indices i.e [2,2,3]</p>
<p>Apologies in advance if this is confusing, it is difficult to explain in words.</p>
| 0 | 2016-09-30T14:18:40Z | 39,793,944 | <p>You can also do it like following:</p>
<pre><code>def group_list(l):
if not l:
return []
result = [0]
prev = l[0] + .1
for el in l:
if el < prev:
result[-1] += 1
else:
result.append(1)
prev = el
return result
>>> group_list([167.233, 95.6242, 181.367, 20.6354, 147.505, 41.9396, 20.3126])
[2, 2, 3]
>>> group_list([167.233, 95.6242, 1.367, 20.6354, 147.505, 41.9396, 20.3126])
[3, 1, 3]
>>> group_list([167.233, 95.6242, 1.367, 20.6354, 147.505, 41.9396, 70.3126])
[3, 1, 2, 1]
>>> group_list([-167.233, 95.6242, 1.367, 20.6354, 147.505, 41.9396, 70.3126])
[1, 2, 1, 2, 1]
</code></pre>
| 0 | 2016-09-30T14:31:20Z | [
"python"
]
|
split a list according to size of float entries | 39,793,681 | <p>I have a list of floats where the size at each sequential index can vary.
i.e.</p>
<pre><code>float_list = [167.233, 95.6242, 181.367, 20.6354, 147.505, 41.9396, 20.3126]
</code></pre>
<p>What I am trying to do is to split the list according to the size of the floats in the indices. In particular, if the float at one index is less than that at the index before, then group the indices together to return the total number of indices that are less than those before.</p>
<p>For example, if we start from the first index the value is 167.233. Because the value at the next index, 95.6242, is smaller than that of the one prior, I would like to group these two together to return their length i.e. 2.</p>
<p>The third index is larger than the second, so this becomes the new 'benchmark'. Since the following index is smaller than that at the third, this returns the length 2.
The fifth index is the next 'benchmark' and the floats at the remaining indices decrease, therefore returning the length of those indices 3.</p>
<p>The way in which I would like this returned, is a list of the length of those indices i.e [2,2,3]</p>
<p>Apologies in advance if this is confusing, it is difficult to explain in words.</p>
| 0 | 2016-09-30T14:18:40Z | 39,794,031 | <p>It seems like you want to obtain a list containing the sizes of decreasing/non-increasing ranges in the list of floats.</p>
<pre><code>def size_of_decreasing_ranges(float_list):
if len(float_list) == 0:
return []
result = []
count = 1
for index, ele in enumerate(float_list):
if index > 0:
if float_list[index] > float_list[index-1]:
result.append(count)
count = 1
else:
count += 1
result.append(count)
return result
</code></pre>
| 0 | 2016-09-30T14:35:53Z | [
"python"
]
|
Looping with while function with Selenium throws error NameError: name 'neadaclick' is not defined | 39,793,700 | <p>I am trying to automate a task in my work. I already have the task and every time I click on the program I can accomplish it, however I would want to be able to do the tasks several times with one click so I want to enter a loop using while. So I started testing, this is my current code:</p>
<pre><code>from selenium import webdriver
browser = webdriver.Chrome()
def countdown(n):
while (n >= 0):
#Lets get rid of this
# print (n)
browser.get('http://www.simplesite.com/')
needaclick = browser.find_element_by_id('startwizard')
neadaclick.click()
n = n - 1
print ('Sucess!')
#Change from static to user input.
#countdown (10)
countdown (int(input('Enter a real number:')))
#Failed script code, leaving it here for documentation
#int(countdown) = input('Enter a real number:')
</code></pre>
<p>As you can see I have a simple countdown and in theory (or at least in my mind) what should happen is that the number of times that I input should be the number of times that the program should open a browser and click on the element startwizard. But, I keep getting the error <code>needaclick</code> is not defined and I am unsure of how to fix this properly. </p>
<p>Error code:</p>
<blockquote>
<p>Traceback (most recent call last):
File "C:/Users/AMSUser/AppData/Local/Programs/Python/Python35-32/Scripts/Countdown Test.py", line 14, in
countdown (int(input('Enter a real number:')))
File "C:/Users/AMSUser/AppData/Local/Programs/Python/Python35-32/Scripts/Countdown Test.py", line 9, in countdown
neadaclick.click()
NameError: name 'neadaclick' is not defined</p>
</blockquote>
| 0 | 2016-09-30T14:19:30Z | 39,831,172 | <p>@ElmoVanKielmo pointed out a mistake that i failed to notice, my first declaration is needaclick but on the next line i wrote neadaclick, this has been solved and its working.</p>
| 0 | 2016-10-03T12:04:38Z | [
"python",
"python-3.x",
"selenium-chromedriver"
]
|
Custom rendering of foreign field in form in django template | 39,793,748 | <p>In my modelform I have a foreign key, I cannot figure out how to change the appearance of this field in template. I can change the text by changing</p>
<pre><code>__unicode__
</code></pre>
<p>of the model, but how would I make it bold, for example?</p>
<p>in <strong>models.py</strong> I tried the following but form renders with and all other tags as if they were just text:</p>
<pre><code>def __unicode__(self):
u'<b>Name</b>: {}\n<b>Loyal</b>: {}'.format(self.name, self.loyal)
</code></pre>
<p>my <strong>template.html</strong>:</p>
<pre><code> <form method="post">
{% csrf_token %}
{{ form.client|safe}}
<br>
<input type="submit" value="Save changes" class="btn btn-s btn-success">
</form>
</code></pre>
<p>doesn't work.</p>
<p>Here is the picture:</p>
<p><a href="http://i.stack.imgur.com/8eu3u.png" rel="nofollow"><img src="http://i.stack.imgur.com/8eu3u.png" alt="enter image description here"></a></p>
| 0 | 2016-09-30T14:21:28Z | 39,793,881 | <p>Django 1.9 has a <code>format_html</code> function that might be what you are looking for. From <a href="https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.html.format_html" rel="nofollow">the Docs</a>:</p>
<blockquote>
<p><code>format_html(format_string, *args, **kwargs)</code></p>
<p>This is similar to str.format(), except that <strong>it is appropriate for building up HTML fragments</strong>. All args and kwargs are passed through conditional_escape() before being passed to str.format().</p>
<p><strong>For the case of building up small HTML fragments, this function is to be preferred over string interpolation</strong> using % or str.format() directly, because it applies escaping to all arguments - just like the template system applies escaping by default.</p>
</blockquote>
<p>More information here: <a href="http://stackoverflow.com/questions/3298083/prevent-django-admin-from-escaping-html">Prevent django admin from escaping html</a></p>
| 0 | 2016-09-30T14:28:34Z | [
"python",
"django",
"django-forms"
]
|
Issues accessing Tkinter Radio Button CTRL var | 39,793,857 | <p>I am having trouble getting the value of the selected radio button. Currently when I use the <code>.get()</code> function on my varible that the radio buttons use it returns "" nothing. If I use the message box without the <code>.get()</code> function then it returns <code>PY_VAR</code>x where x is the specific instance of the tkinter variable.</p>
<p>The radio buttons are using the variable properly, as seen by the fact that you can only select one radio button at a time, but I am not able to read the value properly. I want to read the current selection and put it into a different variable.</p>
<p>Below is abridged code (you are only seeing the radio button part of the program).</p>
<pre><code>from tkinter import *
from tkinter import messagebox, ttk
class init_system:
def __init__(self):
self.init_vars = {"w_audiocodec": "Windows Media Audio 9.2 Lossless"}
class render_window:
def __init__(self, height, width, window_title):
self.root_window = Tk()
w = width
h = height
ws = self.root_window.winfo_screenwidth() # width of the screen
hs = self.root_window.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
self.root_window.title(window_title)
self.root_window.minsize(width, height)
self.root_window.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.master_dictionary = {"radio_ctrl": StringVar()}
def new_button(self, button_text, button_command="", grid_row=0, grid_column=0, grid_sticky="NESW", grid_columnspan=1, grid_rowspan=1):
self.button = ttk.Button(self.root_window, text=button_text, command=button_command)
self.button.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan)
self.responsive_grid(grid_row, grid_column)
def new_label(self, label_text, text_alignment="center", grid_row=0, grid_column=0, grid_sticky="NESW", grid_columnspan=1, grid_rowspan=1):
self.label = ttk.Label(self.root_window, text=label_text, anchor=text_alignment)
self.label.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan)
self.responsive_grid(grid_row, grid_column)
def responsive_grid(self, row_responsive=0, column_responsive=0, row_weight_num=1, column_weight_num=1):
self.root_window.grid_columnconfigure(column_responsive, weight=column_weight_num)
self.root_window.grid_rowconfigure(row_responsive, weight=row_weight_num)
def new_radio_button(self, widget_text="Radio Button", radio_value="Radio Btn", radio_command="", grid_row=0, grid_column=0, grid_sticky="NESW", grid_columnspan=1, grid_rowspan=1):
self.radio_button = ttk.Radiobutton(self.root_window, text=widget_text, variable=self.master_dictionary["radio_ctrl"], value=radio_value, command=radio_command)
self.radio_button.grid(row=grid_row, column=grid_column, sticky=grid_sticky, columnspan=grid_columnspan, rowspan=grid_rowspan)
self.responsive_grid(grid_row, grid_column)
class change_var_window(render_window):
change_var_window_values = {"example_data_below": "Check it out!",
"var_to_change": "show_ui",
"toggle": False,
"radio": False,
"free_form":False,
"line_one": "Current value of:",
"line_two": "some varible name here passwed with a dicrionary",
"Custom_Data_Bool": False,
"Custom_Disable": "Enable me",
"Custom_Enable": "Disable me",
"radio_list": [("Radio Button 1", "btn_1"), ("Radio Button 2", "btn_2"), ("Radio Button 3", "btn_3")],
"is_number": True}
def save_radio_var(self):
vars_system.init_vars[self.change_var_window_values["var_to_change"]] = self.master_dictionary["radio_ctrl"].get()
messagebox.showinfo("debug", self.master_dictionary["radio_ctrl"].get())
def create_change_var_window(self):
self.new_label(self.change_var_window_values["line_one"], grid_columnspan=2)
self.new_label(self.change_var_window_values["line_two"], grid_row=1, grid_columnspan=2)
if self.change_var_window_values["radio"]:
grid_placement = 2
self.master_dictionary["radio_ctrl"] = StringVar()
#self.master_dictionary["radio_ctrl"].set(vars_system.init_vars[self.change_var_window_values["var_to_change"]])
for radio_name, value in self.change_var_window_values["radio_list"]:
self.new_radio_button(widget_text=radio_name, radio_value=value, grid_row=grid_placement)
grid_placement +=1
grid_placement -=1
self.new_button("Cancle", self.root_window.destroy, grid_row=grid_placement, grid_column=1)
grid_placement -=1
self.new_button("Save", self.save_radio_var, grid_row=grid_placement, grid_column=1)
# Radio Requires:
# "radio_list" "var_to_change"
self.root_window.mainloop()
def radio_example():
radio = change_var_window(300, 350, "Radio Select")
radio.change_var_window_values.update({"free_form": False, "toggle": False, "radio": True, "var_to_change": "w_audiocodec", "line_one": "Current value of w_audiocodec:", "line_two": vars_system.init_vars["w_audiocodec"]})
radio.change_var_window_values.update({"radio_list": [("Windows Media Audio 9.2", "Windows Media Audio 9.2"), ("Windows Media Audio 9.2 Lossless", "Windows Media Audio 9.2 Lossless"), ("Windows Media Audio 10 Professional", "Windows Media Audio 10 Professional")]})
#main_window.root_window.withdraw()
radio.create_change_var_window()
vars_system = init_system()
main_window = render_window(200, 250, "Main Window")
main_window.new_button("Radio Var", radio_example)
main_window.root_window.mainloop()
</code></pre>
<p>Thank you for taking time to look at this issue :-)</p>
| 0 | 2016-09-30T14:27:07Z | 39,794,491 | <p>The problem is related to the fact that you are creating more than one root window. You need to change your code so that you create exactly one instance of <code>Tk</code> for the life of your program. Widgets and variables in one root cannot be shared with widgets and variables from another root window. </p>
<p>If you need more than one window, all but the root window need to be instances of <code>Toplevel</code>. </p>
| 1 | 2016-09-30T14:58:59Z | [
"python",
"python-3.x",
"variables",
"tkinter",
"radio-button"
]
|
Understanding net_surgery in caffe | 39,793,953 | <p>I'm following the <a href="http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/net_surgery.ipynb" rel="nofollow">net_surgery.ipynb</a> example of caffe which explains how to modify the weights of a saved <code>.caffemodel</code>. However since I'm quite new to python I can't understand some of the syntax.</p>
<p>Can someone explain me what the 7th line starting with <code>conv_params = {pr: ...</code> means in the code example given below? (example is from <a href="http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/net_surgery.ipynb" rel="nofollow">net_surgery.ipynb</a> - step 8). Especially what is <code>pr:</code>? Is it a key in a (key,value) like structure?</p>
<pre><code># Load the fully convolutional network to transplant the parameters.
net_full_conv = caffe.Net('net_surgery/bvlc_caffenet_full_conv.prototxt',
'../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel',
caffe.TEST)
params_full_conv = ['fc6-conv', 'fc7-conv', 'fc8-conv']
# conv_params = {name: (weights, biases)}
conv_params = {pr: (net_full_conv.params[pr][0].data, net_full_conv.params[pr][1].data) for pr in params_full_conv}
for conv in params_full_conv:
print '{} weights are {} dimensional and biases are {} dimensional'.format(conv, conv_params[conv][0].shape, conv_params[conv][1].shape)
</code></pre>
| 1 | 2016-09-30T14:32:07Z | 39,870,756 | <p>The line you are struggling with:</p>
<pre><code>conv_params = {pr: (net_full_conv.params[pr][0].data, net_full_conv.params[pr][1].data) for pr in params_full_conv}
</code></pre>
<p>defines a dictionary <code>conv_params</code> with keys <code>'fc6-conv'</code>, <code>'fc7-conv'</code> and <code>'fc8-conv'</code>.<br>
The construction of the dictionary using <code>for</code> statement (<code>... for pr in ...</code>) is called 'Dictionary comprehension" and you can find more information about this construct <a href="http://stackoverflow.com/q/14507591/1714410">here</a>.</p>
| 1 | 2016-10-05T09:50:55Z | [
"python",
"neural-network",
"deep-learning",
"caffe",
"pycaffe"
]
|
How to check the shape of multiple arrays contained in a list? | 39,793,994 | <p>I got a list containing multiple arrays, and I wrote the following codes try to see shape[0] of these arrays,</p>
<pre><code>for i in xrange(len(list)):
k = list[i].shape[0]
print k
</code></pre>
<p>the outputs were correct, but I want to <strong>check</strong> these shape[0], that is, if they are the same, the function would continue, otherwise, if they are not the same number, the function breaks. How to do this? Feel free to give me advice, thanks a lot.</p>
<h1>Update</h1>
<p>I created a list named 'ab' containing 3 different arrays, and used errors and exceptions codes to check the shape[0]:</p>
<pre><code>ab = [np.array([[1,2,3],[1,2,3]]),
np.array([[1,2,3]]),
np.array([[1,2,3],[1,2,3],[0,1,2],[0,9,9]])]
for i in xrange(len(ab)):
k = ab[i].shape[0]
print k
try:
all(x.shape[0]==ab[0].shape[0] for x in ab)
print 'True'
except ValueError:
print 'False'
</code></pre>
<p>but the outputs were:</p>
<pre><code>2
1
4
True
</code></pre>
<p>the outputs were wrong, where did I make a mistake?</p>
| 0 | 2016-09-30T14:34:12Z | 39,794,043 | <pre><code>all(x.shape[0]==list[0].shape[0] for x in list)
</code></pre>
| 5 | 2016-09-30T14:36:42Z | [
"python",
"arrays",
"numpy"
]
|
How to check the shape of multiple arrays contained in a list? | 39,793,994 | <p>I got a list containing multiple arrays, and I wrote the following codes try to see shape[0] of these arrays,</p>
<pre><code>for i in xrange(len(list)):
k = list[i].shape[0]
print k
</code></pre>
<p>the outputs were correct, but I want to <strong>check</strong> these shape[0], that is, if they are the same, the function would continue, otherwise, if they are not the same number, the function breaks. How to do this? Feel free to give me advice, thanks a lot.</p>
<h1>Update</h1>
<p>I created a list named 'ab' containing 3 different arrays, and used errors and exceptions codes to check the shape[0]:</p>
<pre><code>ab = [np.array([[1,2,3],[1,2,3]]),
np.array([[1,2,3]]),
np.array([[1,2,3],[1,2,3],[0,1,2],[0,9,9]])]
for i in xrange(len(ab)):
k = ab[i].shape[0]
print k
try:
all(x.shape[0]==ab[0].shape[0] for x in ab)
print 'True'
except ValueError:
print 'False'
</code></pre>
<p>but the outputs were:</p>
<pre><code>2
1
4
True
</code></pre>
<p>the outputs were wrong, where did I make a mistake?</p>
| 0 | 2016-09-30T14:34:12Z | 39,794,075 | <p>You can use a <code>set</code> comprehension to create a set of unique shapes then check if the length of the set is more than 1:</p>
<pre><code>shapes = {arr.shape[0] for arr in my_list}
if len(shapes) > 1:
# return None
</code></pre>
<p>Or as a better way try to apply a numpy function on your array, if they are not in same shape it will raise a <code>ValueError</code>:</p>
<pre><code>try:
np.hstack(my_list)
except ValueError:
# rasise exception or return None
</code></pre>
| 2 | 2016-09-30T14:38:15Z | [
"python",
"arrays",
"numpy"
]
|
pandas: create single size & sum columns after group by multiple columns | 39,794,016 | <p>I have a dataframe where I am doing groupby on 3 columns and aggregating the sum and size of the numerical columns. After running the code </p>
<pre><code>df = pd.DataFrame.groupby(['year','cntry', 'state']).agg(['size','sum'])
</code></pre>
<p>I am getting something like below:</p>
<p><a href="http://i.stack.imgur.com/mZvvz.png" rel="nofollow"><img src="http://i.stack.imgur.com/mZvvz.png" alt="Image of datafram"></a></p>
<p>Now I want to split my size sub columns from main columns and create only single size column but want to keep the sum columns under main column headings. I have tried different approaches but not successful.
These are the methods I have tried but unable to get things working for me:</p>
<p><a href="http://stackoverflow.com/questions/19384532/how-to-count-number-of-rows-in-a-group-in-pandas-group-by-object">How to count number of rows in a group in pandas group by object?</a></p>
<p><a href="http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">Converting a Pandas GroupBy object to DataFrame</a></p>
<p>Will be grateful to if anyone can help me with this one.</p>
<p>Regards,</p>
| 3 | 2016-09-30T14:35:26Z | 39,796,429 | <p><strong><em>Setup</em></strong> </p>
<pre><code>d1 = pd.DataFrame(dict(
year=np.random.choice((2014, 2015, 2016), 100),
cntry=['United States' for _ in range(100)],
State=np.random.choice(states, 100),
Col1=np.random.randint(0, 20, 100),
Col2=np.random.randint(0, 20, 100),
Col3=np.random.randint(0, 20, 100),
))
df = d1.groupby(['year', 'cntry', 'State']).agg(['size', 'sum'])
df
</code></pre>
<p><a href="http://i.stack.imgur.com/3igw5.png" rel="nofollow"><img src="http://i.stack.imgur.com/3igw5.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>Answer</em></strong><br>
Easiest way would have been to only run <code>size</code> after <code>groupby</code></p>
<pre><code>d1.groupby(['year', 'cntry', 'State']).size()
year cntry State
2014 United States California 10
Florida 9
Massachusetts 8
Minnesota 5
2015 United States California 9
Florida 7
Massachusetts 4
Minnesota 11
2016 United States California 8
Florida 8
Massachusetts 11
Minnesota 10
dtype: int64
</code></pre>
<hr>
<p>To use the calculated <code>df</code></p>
<pre><code>df.xs('size', axis=1, level=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/eiwXV.png" rel="nofollow"><img src="http://i.stack.imgur.com/eiwXV.png" alt="enter image description here"></a></p>
<p>And that would be useful if the <code>size</code> were different for each column. But because the <code>size</code> column is the same for <code>['Col1', 'Col2', 'Col3']</code>, we can just do</p>
<pre><code>df[('Col1', 'size')]
year cntry State
2014 United States California 10
Florida 9
Massachusetts 8
Minnesota 5
2015 United States California 9
Florida 7
Massachusetts 4
Minnesota 11
2016 United States California 8
Florida 8
Massachusetts 11
Minnesota 10
Name: (Col1, size), dtype: int64
</code></pre>
<hr>
<p><strong><em>Combined View 1</em></strong></p>
<pre><code>pd.concat([df[('Col1', 'size')].rename('size'),
df.xs('sum', axis=1, level=1)], axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/gPHTA.png" rel="nofollow"><img src="http://i.stack.imgur.com/gPHTA.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>Combined View 2</em></strong> </p>
<pre><code>pd.concat([df[('Col1', 'size')].rename(('', 'size')),
df.xs('sum', axis=1, level=1, drop_level=False)], axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/8WiC6.png" rel="nofollow"><img src="http://i.stack.imgur.com/8WiC6.png" alt="enter image description here"></a></p>
| 5 | 2016-09-30T16:53:31Z | [
"python",
"pandas"
]
|
pandas: create single size & sum columns after group by multiple columns | 39,794,016 | <p>I have a dataframe where I am doing groupby on 3 columns and aggregating the sum and size of the numerical columns. After running the code </p>
<pre><code>df = pd.DataFrame.groupby(['year','cntry', 'state']).agg(['size','sum'])
</code></pre>
<p>I am getting something like below:</p>
<p><a href="http://i.stack.imgur.com/mZvvz.png" rel="nofollow"><img src="http://i.stack.imgur.com/mZvvz.png" alt="Image of datafram"></a></p>
<p>Now I want to split my size sub columns from main columns and create only single size column but want to keep the sum columns under main column headings. I have tried different approaches but not successful.
These are the methods I have tried but unable to get things working for me:</p>
<p><a href="http://stackoverflow.com/questions/19384532/how-to-count-number-of-rows-in-a-group-in-pandas-group-by-object">How to count number of rows in a group in pandas group by object?</a></p>
<p><a href="http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">Converting a Pandas GroupBy object to DataFrame</a></p>
<p>Will be grateful to if anyone can help me with this one.</p>
<p>Regards,</p>
| 3 | 2016-09-30T14:35:26Z | 39,796,737 | <p>piRSquared beat me to it but if you must do it this way and want to keep the alignment with columns and sum or size underneath you could reindex the columns to remove the size value and then add in a new column to contain the size value.</p>
<p>For example:</p>
<pre><code>group = df.groupby(['year', 'cntry','state']).agg(['sum','size'])
mi = pd.MultiIndex.from_product([['Col1','Col2','Col3'],['sum']])
group = group.reindex_axis(mi,axis=1)
sizes = df.groupby('state').size().values
group['Tot'] = 0
group.columns = group.columns.set_levels(['sum','size'], level=1)
group.Tot.size = sizes
</code></pre>
<p>It will end up looking like this:</p>
<pre><code> Col1 Col2 Col3 Tot
sum sum sum size
year cntry State
2015 US CA 20 0 4 1
FL 40 3 5 1
MASS 8 1 3 1
MN 12 2 3 1
</code></pre>
| 2 | 2016-09-30T17:14:48Z | [
"python",
"pandas"
]
|
Specifying Readonly access for Django.db connection object | 39,794,123 | <p>I have a series of integration-level tests that are being run as a management command in my Django project. These tests are verifying the integrity of a large amount of weather data ingested from external sources into my database. Because I have such a large amount of data, I really have to test against my production database for the tests to be meaningful. What I'm trying to figure out is how I can define a read-only database connection that is specific to that command or connection object. I should also add that these tests can't go through the ORM, so I need to execute raw SQL. </p>
<p>The structure of my test looks like this</p>
<pre><code>class Command(BaseCommand):
help = 'Runs Integration Tests and Query Tests against Prod Database'
def handle(self,*args, **options):
suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherModel)
ret = unittest.TextTestRunner().run(suite)
if(len(ret.failures) != 0):
sys.exit(1)
else:
sys.exit(0)
class TestWeatherModel(unittest.TestCase):
def testCollectWeatherDataHist(self):
wm = WeatherManager()
wm.CollectWeatherData()
self.assertTrue(wm.weatherData is not None)
</code></pre>
<p>And the WeatherManager.CollectWeatherData() method would look like this:</p>
<pre><code>def CollecWeatherData(self):
cur = connection.cursor()
cur.execute(<Raw SQL Query>)
wm.WeatherData = cur.fetchall()
cur.close()
</code></pre>
<p>I want to somehow idiot-proof this, so that someone else (or me) can't come along later and accidentally write a test that would modify the production database.</p>
| 2 | 2016-09-30T14:41:21Z | 39,794,212 | <p>If you add a serializer for you model, you could specialized in the serializer that is working in readonly mode</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
read_only_fields = ('account_name',)
</code></pre>
<p>from <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields" rel="nofollow">http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields</a></p>
| 0 | 2016-09-30T14:45:40Z | [
"python",
"django",
"django-testing",
"django-database",
"django-postgresql"
]
|
Specifying Readonly access for Django.db connection object | 39,794,123 | <p>I have a series of integration-level tests that are being run as a management command in my Django project. These tests are verifying the integrity of a large amount of weather data ingested from external sources into my database. Because I have such a large amount of data, I really have to test against my production database for the tests to be meaningful. What I'm trying to figure out is how I can define a read-only database connection that is specific to that command or connection object. I should also add that these tests can't go through the ORM, so I need to execute raw SQL. </p>
<p>The structure of my test looks like this</p>
<pre><code>class Command(BaseCommand):
help = 'Runs Integration Tests and Query Tests against Prod Database'
def handle(self,*args, **options):
suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherModel)
ret = unittest.TextTestRunner().run(suite)
if(len(ret.failures) != 0):
sys.exit(1)
else:
sys.exit(0)
class TestWeatherModel(unittest.TestCase):
def testCollectWeatherDataHist(self):
wm = WeatherManager()
wm.CollectWeatherData()
self.assertTrue(wm.weatherData is not None)
</code></pre>
<p>And the WeatherManager.CollectWeatherData() method would look like this:</p>
<pre><code>def CollecWeatherData(self):
cur = connection.cursor()
cur.execute(<Raw SQL Query>)
wm.WeatherData = cur.fetchall()
cur.close()
</code></pre>
<p>I want to somehow idiot-proof this, so that someone else (or me) can't come along later and accidentally write a test that would modify the production database.</p>
| 2 | 2016-09-30T14:41:21Z | 39,794,285 | <p>Man, once again, I should read the docs more carefully before I post questions here. I can define a readonly connection to my production database in the settings file, and then straight from the <a href="https://docs.djangoproject.com/en/1.10/topics/db/sql/" rel="nofollow">docs</a>:</p>
<p>If you are using more than one database, you can use django.db.connections to obtain the connection (and cursor) for a specific database. django.db.connections is a dictionary-like object that allows you to retrieve a specific connection using its alias:</p>
<pre><code>from django.db import connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
</code></pre>
| 1 | 2016-09-30T14:49:05Z | [
"python",
"django",
"django-testing",
"django-database",
"django-postgresql"
]
|
Python lxml - retrieved elements nodes aren't removed | 39,794,161 | <p>I have an xml doxument I want to remove any line of xml that contains</p>
<pre><code>number="0"
</code></pre>
<p>This is a sample</p>
<pre><code> <race id="219729" number="2" nomnumber="8" division="0" name="NEWGATE BREEDERS' PLATE" mediumname="BRDRS PLTE" shortname="BRDRS PLTE" stage="Acceptances" distance="1000" minweight="50" raisedweight="0" class="~ " age="2 " grade="0" weightcondition="SW " trophy="0" owner="0" trainer="0" jockey="0" strapper="0" totalprize="150000" first="89100" second="29700" third="14850" fourth="7425" fifth="2970" time="2016-10-01T12:55:00" bonustype=" " nomsfee="0" acceptfee="0" trackcondition=" " timingmethod=" " fastesttime=" " sectionaltime=" " formavailable="0" racebookprize="Of $150000. First $89100, second $29700, third $14850, fourth $7425, fifth $2970, sixth $1485, seventh $1485, eighth $1485">
<condition line="1">Of $150000. First $89100, second $29700, third $14850, fourth $7425, fifth $2970, sixth $1485, seventh $1485, eighth $1485</condition>
<condition line="3">No class restriction, Set Weights, For Two-Years-Old, Colts and Geldings, (Listed)</condition>
<condition line="5">No Allowances for apprentices. Field Limit: 14 + 4 EM</condition>
<nomination number="1" saddlecloth="1" horse="Bowerman" id="207678" idnumber="" regnumber="" blinkers="0" trainernumber="81525" trainersurname="Freedman" trainerfirstname="Michael" trainertrack="Randwick" rsbtrainername="Michael Freedman" jockeynumber="1472" jockeysurname="McEvoy" jockeyfirstname="Kerrin" barrier="3" weight="56" rating="0" description="B C 2 Snitzel x Sabanci (Encosta de Lago)" colours="Red, Yellow Stars And Halved Sleeves, Red And Yellow Star Cap" owners="China Horse Club Racing Pty Ltd (Mgr: A K Teo) Winstar Farm Llc (Mgr: J Mullikin) " dob="2014-08-11T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="2" saddlecloth="2" horse="Condor Heroes" id="207750" idnumber="" regnumber="" blinkers="0" trainernumber="685" trainersurname="Ryan" trainerfirstname="Gerald" trainertrack="Rosehill" rsbtrainername="Gerald Ryan" jockeynumber="40275" jockeysurname="Clark" jockeyfirstname="Tim" barrier="10" weight="56" rating="0" description="B C 2 Not a Single Doubt x Gosetgo (More Than Ready(USA))" colours="Yellow, Red Sun Logo, Red Epaulettes, Hooped Sleeves, Red Cap With Gold Logo" owners="Sun Bloodstock Pty Ltd (Mgr: Ms M C Cheng)" dob="2014-09-29T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="4" saddlecloth="4" horse="Invader" id="207745" idnumber="" regnumber="" blinkers="0" trainernumber="81215" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Peter &amp; Paul Snowden" jockeynumber="331" jockeysurname="Brown" jockeyfirstname="Corey" barrier="9" weight="56" rating="0" description="CH C 2 Snitzel x Flame of Sydney (Encosta de Lago)" colours="Red, Yellow Stars And Halved Sleeves, Red And Yellow Star Cap" owners="Newgate S F (Mgr: G D Murphy), Aquis Farm (Mgr: Miss K A Fogden), China Horse Club Racing Pty Ltd (Mgr: A K Teo), Horse Ventures (Mgr: M B Sandblom) &amp; Winstar Farm Llc (Mgr: J Mullikin)" dob="2014-10-01T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="5" saddlecloth="5" horse="Khan" id="207711" idnumber="" regnumber="" blinkers="0" trainernumber="81215" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Peter &amp; Paul Snowden" jockeynumber="40133" jockeysurname="Shinn" jockeyfirstname="Blake" barrier="1" weight="56" rating="0" description="CH C 2 Exceed And Excel x Mandawara(FR) (Daylami(IRE))" colours="Dark Green, Gold Epaulettes" owners="James Harron Bloodstock Colts, Mrs B C Bateman, Love Racing, Doyles Breeding &amp; Racing, P Mehrten, Rockingham Thoroughbreds, J A &amp; Mrs F A Ingham, G1G Racing &amp; Breeding &amp; N Gillard" dob="2014-08-09T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="6" saddlecloth="6" horse="Medal Kun" id="207681" idnumber="" regnumber="" blinkers="0" trainernumber="81483" trainersurname="Cummings" trainerfirstname="James" trainertrack="Randwick" rsbtrainername="James Cummings" jockeynumber="336" jockeysurname="Boss" jockeyfirstname="Glen" barrier="7" weight="56" rating="0" description="BR C 2 Medaglia D'oro(USA) x Run for Roses (Danehill(USA))" colours="Red, Black Stripes" owners="Gooree Stud (Mgr: E M Cojuangco)" dob="2014-09-30T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="7" saddlecloth="7" horse="Misty Lad" id="207698" idnumber="" regnumber="" blinkers="1" trainernumber="81637" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Gai Waterhouse &amp; Adrian Bott" jockeynumber="349" jockeysurname="Bowman" jockeyfirstname="Hugh" barrier="5" weight="56" rating="0" description="B C 2 Redoute's Choice x Anadan (Anabaa(USA))" colours="Gold, Purple Star, Gold And White Stars Sleeves, Purple Cap" owners="Mt Hallowell Stud (Mgr: C G Thompson) &amp; D K M Walpole " dob="2014-10-09T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="8" saddlecloth="8" horse="Opulentus" id="207699" idnumber="" regnumber="" blinkers="1" trainernumber="81215" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Peter &amp; Paul Snowden" jockeynumber="84015" jockeysurname="Avdulla" jockeyfirstname="Brenton" barrier="8" weight="56" rating="0" description="CH C 2 Choisir x Aurum Valley (Made of Gold(USA))" colours="Dark Green, Gold Epaulettes" owners="James Harron Bloodstock Colts, Mrs B C Bateman, Love Racing, Doyles Breeding &amp; Racing, P Mehrten, Rockingham Thoroughbreds, J A &amp; Mrs F A Ingham, G1G Racing &amp; Breeding, S N Gillard, Archer Racing, Mrs C J Inglis, D Saab &amp; Platinum Breeding &amp; Racing" dob="2014-08-24T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="9" saddlecloth="9" horse="Piracy" id="207724" idnumber="" regnumber="" blinkers="0" trainernumber="235" trainersurname="O'Shea" trainerfirstname="John" trainertrack="Agnes Banks/Hawkesbury" rsbtrainername="John O'Shea" jockeynumber="86876" jockeysurname="McDonald" jockeyfirstname="James" barrier="12" weight="56" rating="0" description="B C 2 Exceed And Excel x Plagiarize (Stravinsky(USA))" colours="Royal Blue" owners="Godolphin" dob="2014-09-25T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="10" saddlecloth="10" horse="Prophet's Voice" id="207523" idnumber="" regnumber="" blinkers="0" trainernumber="7626" trainersurname="Sharah" trainerfirstname="John" trainertrack="Warwick Farm" rsbtrainername="John Sharah" jockeynumber="57544" jockeysurname="Hyeronimus" jockeyfirstname="Adam" barrier="2" weight="56" rating="0" description="B C 2 Poet's Voice(GB) x Gold Beauty (Street Cry(IRE))" colours="Black, White Hooped Sleeves And Cap" owners="J M Sharah " dob="2014-10-15T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="11" saddlecloth="11" horse="Showtime" id="207713" idnumber="" regnumber="" blinkers="0" trainernumber="77974" trainersurname="Hawkes" trainerfirstname="Michael" trainertrack="Rosehill" rsbtrainername="Michael, Wayne &amp; John Hawkes" jockeynumber="51661" jockeysurname="Berry" jockeyfirstname="Tommy" barrier="14" weight="56" rating="0" description="CH C 2 Snitzel x Flidais (Timber Country(USA))" colours="Red, Yellow Stripes, Black Sleeves, Red And Yellow Striped Cap" owners="Arrowfield Pastoral Syndicate (Mgr: J M Messara), K Yoshida, Belford Productions Syndicate (Mgr: A B Jones), Pinecliff Racing Syndicate (Mgr: J B Munz), Koundouris Bloodstock Syndicate (Mgr: A E Koundouris), J G Moore &amp; G P I Racing Syndicate (Mgr: G P Ingham)" dob="2014-09-21T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="12" saddlecloth="12" horse="Spencer" id="207700" idnumber="" regnumber="" blinkers="1" trainernumber="38701" trainersurname="Cummings" trainerfirstname="Anthony" trainertrack="Randwick" rsbtrainername="Anthony Cummings" jockeynumber="57688" jockeysurname="Schofield" jockeyfirstname="Glyn" barrier="6" weight="56" rating="0" description="B C 2 Pierro x Alice's Smart(USA) (Smart Strike(CAN))" colours="Yellow, Red Quarters, Red and White Checked Armbands And Checked Cap" owners="Edinburgh Park (I Smith), S Bennett, C Battese, S K Bennett, P R A Falk, M J Hayne B A Rutter, Glenrock (H Cooper) &amp; Monaro Bloodstock (R J Logan)" dob="2014-09-28T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="13" saddlecloth="13" horse="The Mission" id="207726" idnumber="" regnumber="" blinkers="0" trainernumber="318" trainersurname="Perry" trainerfirstname="Paul" trainertrack="Newcastle" rsbtrainername="Paul Perry" jockeynumber="48503" jockeysurname="Williams" jockeyfirstname="Craig" barrier="4" weight="56" rating="0" description="B C 2 Choisir x My Amelia (Redoute's Choice)" colours="Yellow, Black Sash, Armbands And Cap" owners="Ms C G Collis, Mrs B J Grant, Mrs J P Poole &amp; Mrs D M McCarthy" dob="2014-09-07T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="14" saddlecloth="14" horse="Thy Kingdom Come" id="207685" idnumber="" regnumber="" blinkers="0" trainernumber="77972" trainersurname="Thompson" trainerfirstname="John P" trainertrack="Randwick" rsbtrainername="John P Thompson" jockeynumber="46930" jockeysurname="Angland" jockeyfirstname="Tye" barrier="11" weight="56" rating="0" description="CH C 2 Lope de Vega(IRE) x Family Jewels (Secret Savings(USA))" colours="Royal Blue And Gold Diagonal Stripes, White Cap And Pom Pom" owners="Francis Racing (Mgr: J Francis), Dr K P Rewell, G Bakhos, M J Grace, T Khoury &amp; B D Lawrence " dob="2014-08-01T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
<nomination number="0" saddlecloth="0" horse="Inquiry" id="207696" idnumber="" blinkers="0" trainernumber="0" jockeynumber="0" barrier="13" weight="0" rating="0" description="CH C 2 Exceed And Excel x Screen (Lonhro)" colours="Royal Blue" dob="2014-09-19T00:00:00" age="2" career="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="0" decimalmargin="0.00" penalty="0" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
</race>
</code></pre>
<p>I am able to return the elements</p>
<pre><code>from lxml import etree
import csv
with open("20161001RAND0.xml", 'rb') as f, open(
"output/310916RABD.csv", 'w', newline='') as csvf:
tree = etree.parse(f)
root = tree.getroot()
for nom in root.iter("nomination"):
if nom.attrib['number'] == '0':
nom.getparent().remove(nom)
print(nom)
</code></pre>
<p>The output shows I got the element</p>
<pre><code>± |master U:1 ?:1 â| â python3 race.py
<Element nomination at 0x7f3e1f7c8f88>
</code></pre>
<p>However the item still remains, how can I delete the line so that it would return with this line removed</p>
<pre><code> <nomination number="0" saddlecloth="0" horse="Inquiry" id="207696" idnumber="" blinkers="0" trainernumber="0" jockeynumber="0" barrier="13" weight="0" rating="0" description="CH C 2 Exceed And Excel x Screen (Lonhro)" colours="Royal Blue" dob="2014-09-19T00:00:00" age="2" career="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="0" decimalmargin="0.00" penalty="0" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator="" />
</code></pre>
| 1 | 2016-09-30T14:43:22Z | 39,794,574 | <p>I cannot reproduce it, here is the processing code completely based on yours:</p>
<pre><code>from lxml import etree
with open("input.xml", 'rb') as input_file, open("output.xml", 'wb') as output_file:
tree = etree.parse(input_file)
root = tree.getroot()
for nom in root.iter("nomination"):
if nom.attrib['number'] == '0':
nom.getparent().remove(nom)
print(nom)
tree.write(output_file)
</code></pre>
<p>The content of the <code>output.xml</code> after running this code:</p>
<pre><code><race id="219729" number="2" nomnumber="8" division="0" name="NEWGATE BREEDERS' PLATE" mediumname="BRDRS PLTE" shortname="BRDRS PLTE" stage="Acceptances" distance="1000" minweight="50" raisedweight="0" class="~ " age="2 " grade="0" weightcondition="SW " trophy="0" owner="0" trainer="0" jockey="0" strapper="0" totalprize="150000" first="89100" second="29700" third="14850" fourth="7425" fifth="2970" time="2016-10-01T12:55:00" bonustype=" " nomsfee="0" acceptfee="0" trackcondition=" " timingmethod=" " fastesttime=" " sectionaltime=" " formavailable="0" racebookprize="Of $150000. First $89100, second $29700, third $14850, fourth $7425, fifth $2970, sixth $1485, seventh $1485, eighth $1485">
<condition line="1">Of $150000. First $89100, second $29700, third $14850, fourth $7425, fifth $2970, sixth $1485, seventh $1485, eighth $1485</condition>
<condition line="3">No class restriction, Set Weights, For Two-Years-Old, Colts and Geldings, (Listed)</condition>
<condition line="5">No Allowances for apprentices. Field Limit: 14 + 4 EM</condition>
<nomination number="1" saddlecloth="1" horse="Bowerman" id="207678" idnumber="" regnumber="" blinkers="0" trainernumber="81525" trainersurname="Freedman" trainerfirstname="Michael" trainertrack="Randwick" rsbtrainername="Michael Freedman" jockeynumber="1472" jockeysurname="McEvoy" jockeyfirstname="Kerrin" barrier="3" weight="56" rating="0" description="B C 2 Snitzel x Sabanci (Encosta de Lago)" colours="Red, Yellow Stars And Halved Sleeves, Red And Yellow Star Cap" owners="China Horse Club Racing Pty Ltd (Mgr: A K Teo) Winstar Farm Llc (Mgr: J Mullikin) " dob="2014-08-11T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="2" saddlecloth="2" horse="Condor Heroes" id="207750" idnumber="" regnumber="" blinkers="0" trainernumber="685" trainersurname="Ryan" trainerfirstname="Gerald" trainertrack="Rosehill" rsbtrainername="Gerald Ryan" jockeynumber="40275" jockeysurname="Clark" jockeyfirstname="Tim" barrier="10" weight="56" rating="0" description="B C 2 Not a Single Doubt x Gosetgo (More Than Ready(USA))" colours="Yellow, Red Sun Logo, Red Epaulettes, Hooped Sleeves, Red Cap With Gold Logo" owners="Sun Bloodstock Pty Ltd (Mgr: Ms M C Cheng)" dob="2014-09-29T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="4" saddlecloth="4" horse="Invader" id="207745" idnumber="" regnumber="" blinkers="0" trainernumber="81215" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Peter &amp; Paul Snowden" jockeynumber="331" jockeysurname="Brown" jockeyfirstname="Corey" barrier="9" weight="56" rating="0" description="CH C 2 Snitzel x Flame of Sydney (Encosta de Lago)" colours="Red, Yellow Stars And Halved Sleeves, Red And Yellow Star Cap" owners="Newgate S F (Mgr: G D Murphy), Aquis Farm (Mgr: Miss K A Fogden), China Horse Club Racing Pty Ltd (Mgr: A K Teo), Horse Ventures (Mgr: M B Sandblom) &amp; Winstar Farm Llc (Mgr: J Mullikin)" dob="2014-10-01T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="5" saddlecloth="5" horse="Khan" id="207711" idnumber="" regnumber="" blinkers="0" trainernumber="81215" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Peter &amp; Paul Snowden" jockeynumber="40133" jockeysurname="Shinn" jockeyfirstname="Blake" barrier="1" weight="56" rating="0" description="CH C 2 Exceed And Excel x Mandawara(FR) (Daylami(IRE))" colours="Dark Green, Gold Epaulettes" owners="James Harron Bloodstock Colts, Mrs B C Bateman, Love Racing, Doyles Breeding &amp; Racing, P Mehrten, Rockingham Thoroughbreds, J A &amp; Mrs F A Ingham, G1G Racing &amp; Breeding &amp; N Gillard" dob="2014-08-09T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="6" saddlecloth="6" horse="Medal Kun" id="207681" idnumber="" regnumber="" blinkers="0" trainernumber="81483" trainersurname="Cummings" trainerfirstname="James" trainertrack="Randwick" rsbtrainername="James Cummings" jockeynumber="336" jockeysurname="Boss" jockeyfirstname="Glen" barrier="7" weight="56" rating="0" description="BR C 2 Medaglia D'oro(USA) x Run for Roses (Danehill(USA))" colours="Red, Black Stripes" owners="Gooree Stud (Mgr: E M Cojuangco)" dob="2014-09-30T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="7" saddlecloth="7" horse="Misty Lad" id="207698" idnumber="" regnumber="" blinkers="1" trainernumber="81637" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Gai Waterhouse &amp; Adrian Bott" jockeynumber="349" jockeysurname="Bowman" jockeyfirstname="Hugh" barrier="5" weight="56" rating="0" description="B C 2 Redoute's Choice x Anadan (Anabaa(USA))" colours="Gold, Purple Star, Gold And White Stars Sleeves, Purple Cap" owners="Mt Hallowell Stud (Mgr: C G Thompson) &amp; D K M Walpole " dob="2014-10-09T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="8" saddlecloth="8" horse="Opulentus" id="207699" idnumber="" regnumber="" blinkers="1" trainernumber="81215" trainersurname="" trainerfirstname="" trainertrack="Randwick" rsbtrainername="Peter &amp; Paul Snowden" jockeynumber="84015" jockeysurname="Avdulla" jockeyfirstname="Brenton" barrier="8" weight="56" rating="0" description="CH C 2 Choisir x Aurum Valley (Made of Gold(USA))" colours="Dark Green, Gold Epaulettes" owners="James Harron Bloodstock Colts, Mrs B C Bateman, Love Racing, Doyles Breeding &amp; Racing, P Mehrten, Rockingham Thoroughbreds, J A &amp; Mrs F A Ingham, G1G Racing &amp; Breeding, S N Gillard, Archer Racing, Mrs C J Inglis, D Saab &amp; Platinum Breeding &amp; Racing" dob="2014-08-24T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="9" saddlecloth="9" horse="Piracy" id="207724" idnumber="" regnumber="" blinkers="0" trainernumber="235" trainersurname="O'Shea" trainerfirstname="John" trainertrack="Agnes Banks/Hawkesbury" rsbtrainername="John O'Shea" jockeynumber="86876" jockeysurname="McDonald" jockeyfirstname="James" barrier="12" weight="56" rating="0" description="B C 2 Exceed And Excel x Plagiarize (Stravinsky(USA))" colours="Royal Blue" owners="Godolphin" dob="2014-09-25T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="10" saddlecloth="10" horse="Prophet's Voice" id="207523" idnumber="" regnumber="" blinkers="0" trainernumber="7626" trainersurname="Sharah" trainerfirstname="John" trainertrack="Warwick Farm" rsbtrainername="John Sharah" jockeynumber="57544" jockeysurname="Hyeronimus" jockeyfirstname="Adam" barrier="2" weight="56" rating="0" description="B C 2 Poet's Voice(GB) x Gold Beauty (Street Cry(IRE))" colours="Black, White Hooped Sleeves And Cap" owners="J M Sharah " dob="2014-10-15T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="11" saddlecloth="11" horse="Showtime" id="207713" idnumber="" regnumber="" blinkers="0" trainernumber="77974" trainersurname="Hawkes" trainerfirstname="Michael" trainertrack="Rosehill" rsbtrainername="Michael, Wayne &amp; John Hawkes" jockeynumber="51661" jockeysurname="Berry" jockeyfirstname="Tommy" barrier="14" weight="56" rating="0" description="CH C 2 Snitzel x Flidais (Timber Country(USA))" colours="Red, Yellow Stripes, Black Sleeves, Red And Yellow Striped Cap" owners="Arrowfield Pastoral Syndicate (Mgr: J M Messara), K Yoshida, Belford Productions Syndicate (Mgr: A B Jones), Pinecliff Racing Syndicate (Mgr: J B Munz), Koundouris Bloodstock Syndicate (Mgr: A E Koundouris), J G Moore &amp; G P I Racing Syndicate (Mgr: G P Ingham)" dob="2014-09-21T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="12" saddlecloth="12" horse="Spencer" id="207700" idnumber="" regnumber="" blinkers="1" trainernumber="38701" trainersurname="Cummings" trainerfirstname="Anthony" trainertrack="Randwick" rsbtrainername="Anthony Cummings" jockeynumber="57688" jockeysurname="Schofield" jockeyfirstname="Glyn" barrier="6" weight="56" rating="0" description="B C 2 Pierro x Alice's Smart(USA) (Smart Strike(CAN))" colours="Yellow, Red Quarters, Red and White Checked Armbands And Checked Cap" owners="Edinburgh Park (I Smith), S Bennett, C Battese, S K Bennett, P R A Falk, M J Hayne B A Rutter, Glenrock (H Cooper) &amp; Monaro Bloodstock (R J Logan)" dob="2014-09-28T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="13" saddlecloth="13" horse="The Mission" id="207726" idnumber="" regnumber="" blinkers="0" trainernumber="318" trainersurname="Perry" trainerfirstname="Paul" trainertrack="Newcastle" rsbtrainername="Paul Perry" jockeynumber="48503" jockeysurname="Williams" jockeyfirstname="Craig" barrier="4" weight="56" rating="0" description="B C 2 Choisir x My Amelia (Redoute's Choice)" colours="Yellow, Black Sash, Armbands And Cap" owners="Ms C G Collis, Mrs B J Grant, Mrs J P Poole &amp; Mrs D M McCarthy" dob="2014-09-07T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
<nomination number="14" saddlecloth="14" horse="Thy Kingdom Come" id="207685" idnumber="" regnumber="" blinkers="0" trainernumber="77972" trainersurname="Thompson" trainerfirstname="John P" trainertrack="Randwick" rsbtrainername="John P Thompson" jockeynumber="46930" jockeysurname="Angland" jockeyfirstname="Tye" barrier="11" weight="56" rating="0" description="CH C 2 Lope de Vega(IRE) x Family Jewels (Secret Savings(USA))" colours="Royal Blue And Gold Diagonal Stripes, White Cap And Pom Pom" owners="Francis Racing (Mgr: J Francis), Dr K P Rewell, G Bakhos, M J Grace, T Khoury &amp; B D Lawrence " dob="2014-08-01T00:00:00" age="2" sex="C" career="0-0-0-0" thistrack="0-0-0-0" thisdistance="0-0-0-0" goodtrack="0-0-0-0" heavytrack="0-0-0-0" slowtrack="" deadtrack="" fasttrack="0-0-0-0" firstup="0-0-0-0" secondup="0-0-0-0" mindistancewin="0" maxdistancewin="0" finished="0" weightvariation="0" variedweight="56" decimalmargin="0.00" penalty="0" pricestarting="" sectional200="0" sectional400="0" sectional600="0" sectional800="0" sectional1200="0" bonusindicator=""/>
</race>
</code></pre>
<p>As you can see, no nomination element with <code>number="0"</code> left.</p>
<p>The problem must be in the way you write the filtered data.</p>
| 1 | 2016-09-30T15:02:48Z | [
"python"
]
|
In python how can you select the integer that closest to 0? | 39,794,193 | <p>list [1,2,3,4,5,6]</p>
<p>How would you write a line or lines of code that could sort through the list and find the value closest to 0?</p>
| -4 | 2016-09-30T14:45:00Z | 39,794,229 | <p>If you don't care about negative numbers use <a href="https://docs.python.org/2/library/functions.html#min" rel="nofollow">min</a>:</p>
<pre><code>>>> arr = [1, 2, 3, 4, 5]
>>> min(arr)
1
</code></pre>
| 2 | 2016-09-30T14:46:25Z | [
"python",
"for-loop"
]
|
Python logging setLevel() not taking effect | 39,794,194 | <p>I have a python program that utilizes multiprocessing to increase efficiency, and a function that creates a logger for each process. The logger function looks like this:</p>
<pre><code>import logging
import os
def create_logger(app_name):
"""Create a logging interface"""
# create a logger
if logging in os.environ:
logging_string = os.environ["logging"]
if logging_string == "DEBUG":
logging_level = loggin.DEBUG
else if logging_string == "INFO":
logging_level = logging.INFO
else if logging_string == "WARNING":
logging_level = logging.WARNING
else if logging_string == "ERROR":
logging_level = logging.ERROR
else if logging_string == "CRITICAL":
logging_level = logging.CRITICAL
else:
logging_level = logging.INFO
logger = logging.getLogger(app_name)
logger.setLevel(logging_level)
# Console handler for error output
console_handler = logging.StreamHandler()
console_handler.setLevel(logging_level)
# Formatter to make everything look nice
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(console_handler)
return logger
</code></pre>
<p>And my processing functions look like this:</p>
<pre><code>import custom_logging
def do_capture(data_dict_access):
"""Process data"""
# Custom logging
LOGGER = custom_logging.create_logger("processor")
LOGGER.debug("Doing stuff...")
</code></pre>
<p>However, no matter what the logging environment variable is set to, I still receive debug log messages in the console. Why is my logging level not taking effect, surely the calls to setLevel() should stop the debug messages from being logged?</p>
| 1 | 2016-09-30T14:45:02Z | 39,794,595 | <p>Here is an easy way to create a logger object:</p>
<pre><code>import logging
import os
def create_logger(app_name):
"""Create a logging interface"""
logging_level = os.getenv('logging', logging.INFO)
logging.basicConfig(
level=logging_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(app_name)
return logger
</code></pre>
<h1>Discussion</h1>
<ul>
<li>There is no need to convert from <em>"DEBUG"</em> to <code>logging.DEBUG</code>, the <code>logging</code> module understands these strings.</li>
<li>Use <code>basicConfig</code> to ease the pain of setting up a logger. You don't need to create handler, set format, set level, ... This should work for most cases.</li>
</ul>
<h1>Update</h1>
<p>I found out why your code does not work, besides the <code>else if</code>. Consider your line:</p>
<pre><code>if logging in os.environ:
</code></pre>
<p>On this line <code>loggging</code> without quote refers to the <code>logging</code> library package. What you want is:</p>
<pre><code>if 'logging' in os.environ:
</code></pre>
| 1 | 2016-09-30T15:03:54Z | [
"python",
"logging",
"python-multiprocessing"
]
|
Python filling string column "forward" and groupby attaching groupby result to dataframe | 39,794,206 | <p>I have a dataframe looking generated by:</p>
<pre><code>df = pd.DataFrame([[100, ' tes t ', 3], [100, np.nan, 2], [101, ' test1', 3 ], [101,' ', 4]])
</code></pre>
<p>It looks like</p>
<pre><code> 0 1 2
0 100 tes t 3
1 100 NaN 2
2 101 test1 3
3 101 4
</code></pre>
<p>I would like to a fill column 1 "forward" with test and test1. I believe one approach would be to work with replacing whitespace by np.nan, but it is difficult since the words contain whitespace as well. I could also groupby column 0 and then use the first element of each group to fill forward. Could you provide me with some code for both alternatives I do not get it coded?</p>
<p>Additionally, I would like to add a column that contains the group means that is
the final dataframe should look like this</p>
<pre><code> 0 1 2 3
0 100 tes t 3 2.5
1 100 tes t 2 2.5
2 101 test1 3 3.5
3 101 test1 4 3.5
</code></pre>
<p>Could you also please advice how to accomplish something like this?</p>
<p>Many thanks please let me know in case you need further information.</p>
| 2 | 2016-09-30T14:45:25Z | 39,795,135 | <p>IIUC, you could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a> and then check if the stripped string is empty.
Then, perform <code>groupby</code> operations and filling the <code>Nans</code> by the method <code>ffill</code> and calculating the means using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>groupby.transform</code></a> function as shown: </p>
<pre><code>df[1] = df[1].str.strip().dropna().apply(lambda x: np.NaN if len(x) == 0 else x)
df[1] = df.groupby(0)[1].fillna(method='ffill')
df[3] = df.groupby(0)[2].transform(lambda x: x.mean())
df
</code></pre>
<p><a href="http://i.stack.imgur.com/OH80S.png" rel="nofollow"><img src="http://i.stack.imgur.com/OH80S.png" alt="Image"></a></p>
<p>Note: If you must forward fill <code>NaN</code> values with first element of that group, then you must do this:</p>
<pre><code>df.groupby(0)[1].apply(lambda x: x.fillna(x.iloc[0]))
</code></pre>
<hr>
<p><strong>Breakup of steps:</strong></p>
<p>Since we want to apply the function only on strings, we drop all the <code>NaN</code> values present before, else we would be getting the <code>TypeError</code> due to both floats and string elements present in the column and complains of float having no method as <code>len</code>.</p>
<pre><code>df[1].str.strip().dropna()
0 tes t # operates only on indices where strings are present(empty strings included)
2 test1
3
Name: 1, dtype: object
</code></pre>
<p>The reindexing part isn't a necessary step as it only computes on the indices where strings are present.</p>
<p>Also, the <code>reset_index(drop=True)</code> part was indeed unwanted as the groupby object returns a series after <code>fillna</code> which could be assigned back to column 1.</p>
| 2 | 2016-09-30T15:34:19Z | [
"python",
"pandas"
]
|
Can't change a variable using a function Python | 39,794,225 | <p>I'm playing with functions in Python and i though I could do the JOptionPane from Java using the Tkinter... I'm running Python 3.x but I'm having a little trouble</p>
<pre><code>from tkinter import *
def showMessageDialog(text):
text = text
janela = Tk()
janela.geometry("400x100")
janela["bg"] = "grey"
janela.title(" ")
lb = Label(janela, text=str(text))
lb.place(x=200,y=50)
janela.mainloop()
def showInputDialog(text):
x = " "
def botaoClicado():
x = ed.get()
janela.destroy()
return x
text = str(text)
janela = Tk()
janela.geometry("400x100")
janela["bg"] = "grey"
janela.title(" ")
lb = Label(janela, text=str(text))
lb.place(x=120,y=10)
bt = Button(janela, width=10, text="Ok", command=botaoClicado)
bt.place(x=120,y=65)
ed = Entry(janela)
ed.place(x=120,y=35)
janela.mainloop()
return x
x=0
x = showInputDialog("Insira seu nome!")
</code></pre>
<p>I'm sorry it is in portuguese, but I think it's possible for you guys to help me. My problem is the following:</p>
<p>When I click the button, the Entry don't get returned to the other function. I apologize but i don't know how I can explain better.</p>
| 0 | 2016-09-30T14:46:18Z | 39,794,484 | <p>The call to mainloop does not stop until all tkinter Windows close. Therefore your function hangs when you call <code>janela.mainloop()</code>. Instead, it's best practice to call mainloop in the main thread (at the bottom of your script), and use callbacks to process input. For example, once your message dialog box gets an answer, it can call a function to process the answer.</p>
| 0 | 2016-09-30T14:58:47Z | [
"python",
"function",
"tkinter"
]
|
Precise nth root | 39,794,338 | <p>I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!<br>
Where could I obtain at least a guide how to program <strong>Nth root function that produces precise <code>float</code>/<code>Decimal</code></strong>?<br>
Such function that <strong>doesn't return <code>1</code> nor <code>0</code> for <code>root(125, 1756482845)</code></strong> (1st argument is the number, 2nd is the root depth (or something)).</p>
<p><strong>EDIT:</strong> So, you were giving me this solution: <code>n ** (1.0 / exp)</code> which I knew when I asked this question, but it just doesn't work for, for example, <code>exp = 3</code>. You can't express <code>1/3</code> in terms of rational numbers, so <code>125 ** (1/3)</code> gives incorrect result <code>4.999999...</code>. I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational <code>exp</code>. If there isn't such function or algorithm, I will use this (<code>n ** (1/exp)</code>).</p>
| 2 | 2016-09-30T14:51:33Z | 39,794,435 | <p>You mean something like that:</p>
<pre><code>>>> 125**(1/9.0)
1.7099759466766968
</code></pre>
<p>Something else that might interest you is <a href="https://pythonhosted.org/bigfloat/" rel="nofollow">bigfloat</a> module (haven't used personally just know it exists :) - actually had problem installing it in the past-maybe an OS X fault)</p>
| 1 | 2016-09-30T14:56:01Z | [
"python",
"algorithm",
"floating-point",
"precision",
"nth-root"
]
|
Precise nth root | 39,794,338 | <p>I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!<br>
Where could I obtain at least a guide how to program <strong>Nth root function that produces precise <code>float</code>/<code>Decimal</code></strong>?<br>
Such function that <strong>doesn't return <code>1</code> nor <code>0</code> for <code>root(125, 1756482845)</code></strong> (1st argument is the number, 2nd is the root depth (or something)).</p>
<p><strong>EDIT:</strong> So, you were giving me this solution: <code>n ** (1.0 / exp)</code> which I knew when I asked this question, but it just doesn't work for, for example, <code>exp = 3</code>. You can't express <code>1/3</code> in terms of rational numbers, so <code>125 ** (1/3)</code> gives incorrect result <code>4.999999...</code>. I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational <code>exp</code>. If there isn't such function or algorithm, I will use this (<code>n ** (1/exp)</code>).</p>
| 2 | 2016-09-30T14:51:33Z | 39,794,437 | <p>It's the function <code>pow</code> of <code>math</code> module.</p>
<pre><code>import math
math.pow(4, 0.5)
</code></pre>
<p>will return the square root of 4, which is <code>2.0</code>.</p>
<p>For <code>root(125, 1756482845)</code>, what you need to do is</p>
<pre><code>math.pow(125, 1.0 / 1756482845)
</code></pre>
| 0 | 2016-09-30T14:56:05Z | [
"python",
"algorithm",
"floating-point",
"precision",
"nth-root"
]
|
Precise nth root | 39,794,338 | <p>I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!<br>
Where could I obtain at least a guide how to program <strong>Nth root function that produces precise <code>float</code>/<code>Decimal</code></strong>?<br>
Such function that <strong>doesn't return <code>1</code> nor <code>0</code> for <code>root(125, 1756482845)</code></strong> (1st argument is the number, 2nd is the root depth (or something)).</p>
<p><strong>EDIT:</strong> So, you were giving me this solution: <code>n ** (1.0 / exp)</code> which I knew when I asked this question, but it just doesn't work for, for example, <code>exp = 3</code>. You can't express <code>1/3</code> in terms of rational numbers, so <code>125 ** (1/3)</code> gives incorrect result <code>4.999999...</code>. I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational <code>exp</code>. If there isn't such function or algorithm, I will use this (<code>n ** (1/exp)</code>).</p>
| 2 | 2016-09-30T14:51:33Z | 39,795,201 | <p>I would try the <a href="https://pypi.python.org/pypi/gmpy2" rel="nofollow">gmpy2</a> library.</p>
<pre><code>>>> import gmpy2
>>> gmpy2.root(125,3)
mpfr('5.0')
>>>
</code></pre>
<p><code>gmpy2</code> uses the <a href="http://www.mpfr.org/" rel="nofollow">MPFR</a> library to perform correctly rounded floating point operations. The default precision is 53 bits but that can be increased.</p>
<pre><code>>>> gmpy2.root(1234567890123456789**11, 11)
mpfr('1.2345678901234568e+18') # Last digits are incorrect.
>>> gmpy2.get_context().precision=200
>>> gmpy2.root(1234567890123456789**11, 11)
mpfr('1234567890123456789.0',200)
>>>
</code></pre>
<p>Disclaimer: I maintain <code>gmpy2</code>.</p>
| 4 | 2016-09-30T15:38:34Z | [
"python",
"algorithm",
"floating-point",
"precision",
"nth-root"
]
|
Precise nth root | 39,794,338 | <p>I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!<br>
Where could I obtain at least a guide how to program <strong>Nth root function that produces precise <code>float</code>/<code>Decimal</code></strong>?<br>
Such function that <strong>doesn't return <code>1</code> nor <code>0</code> for <code>root(125, 1756482845)</code></strong> (1st argument is the number, 2nd is the root depth (or something)).</p>
<p><strong>EDIT:</strong> So, you were giving me this solution: <code>n ** (1.0 / exp)</code> which I knew when I asked this question, but it just doesn't work for, for example, <code>exp = 3</code>. You can't express <code>1/3</code> in terms of rational numbers, so <code>125 ** (1/3)</code> gives incorrect result <code>4.999999...</code>. I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational <code>exp</code>. If there isn't such function or algorithm, I will use this (<code>n ** (1/exp)</code>).</p>
| 2 | 2016-09-30T14:51:33Z | 39,802,349 | <p>You can do a binary search on the answer. If you want to find the X that is equal to the kth root of N, you can do a binary search on X testing for each step of the binary search whether X^k equals N +- some small constant to avoid precision issues.</p>
<p>Here is the code:</p>
<pre><code>import math
N,K = map(float,raw_input().split()) # We want Kth root of N
lo = 0.0
hi = N
while 1:
mid = (lo+hi)/2
if math.fabs(mid**K-N) < 1e-9: # mid^K is really close to N, consider mid^K == N
print mid
break
elif mid**K < N: lo = mid
else: hi = mid
</code></pre>
<p>For (N,K) = (125,3) it prints 5.0, the correct answer. You can make it more precise by changing the 1e-9 constant, but there is a precision limit related to the float variables precision limit in Python</p>
| 2 | 2016-10-01T02:10:39Z | [
"python",
"algorithm",
"floating-point",
"precision",
"nth-root"
]
|
Precise nth root | 39,794,338 | <p>I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!<br>
Where could I obtain at least a guide how to program <strong>Nth root function that produces precise <code>float</code>/<code>Decimal</code></strong>?<br>
Such function that <strong>doesn't return <code>1</code> nor <code>0</code> for <code>root(125, 1756482845)</code></strong> (1st argument is the number, 2nd is the root depth (or something)).</p>
<p><strong>EDIT:</strong> So, you were giving me this solution: <code>n ** (1.0 / exp)</code> which I knew when I asked this question, but it just doesn't work for, for example, <code>exp = 3</code>. You can't express <code>1/3</code> in terms of rational numbers, so <code>125 ** (1/3)</code> gives incorrect result <code>4.999999...</code>. I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational <code>exp</code>. If there isn't such function or algorithm, I will use this (<code>n ** (1/exp)</code>).</p>
| 2 | 2016-09-30T14:51:33Z | 39,822,888 | <p>In Squeak Smalltalk, there is a <code>nthRoot:</code> message that answers the exact <code>Integer</code> result if ever the Integer receiver is exact nth power of some whole number. However, if the solution is an algebraic root, then the implementation does not fallback to a naive <code>n**(1/exp)</code>; the method rounds to nearest float by appropriate care of residual.</p>
<p>Relevant code (MIT license) is reproduced here. The base algorithm is searching for truncated nth root of an Integer with some Newton-Raphson:</p>
<pre><code>Integer>>nthRootTruncated: aPositiveInteger
"Answer the integer part of the nth root of the receiver."
| guess guessToTheNthMinusOne nextGuess |
self = 0 ifTrue: [^0].
self negative
ifTrue:
[aPositiveInteger even ifTrue: [ ArithmeticError signal: 'Negative numbers don''t have even roots.' ].
^(self negated nthRootTruncated: aPositiveInteger) negated].
guess := 1 bitShift: self highBitOfMagnitude + aPositiveInteger - 1 // aPositiveInteger.
[
guessToTheNthMinusOne := guess raisedTo: aPositiveInteger - 1.
nextGuess := (aPositiveInteger - 1 * guess * guessToTheNthMinusOne + self) // (guessToTheNthMinusOne * aPositiveInteger).
nextGuess >= guess ] whileFalse:
[ guess := nextGuess ].
( guess raisedTo: aPositiveInteger) > self ifTrue:
[ guess := guess - 1 ].
^guess
</code></pre>
<p>It's not particularly clever, because convergence can be very slow in case of huge exponent, but well, it works.
Then, the same root rounded away from zero:</p>
<pre><code>Integer>>nthRootRounded: aPositiveInteger
"Answer the integer nearest the nth root of the receiver."
| guess |
self = 0 ifTrue: [^0].
self negative
ifTrue:
[aPositiveInteger even ifTrue: [ ArithmeticError signal: 'Negative numbers don''t have even roots.' ].
^(self negated nthRootRounded: aPositiveInteger) negated].
guess := self nthRootTruncated: aPositiveInteger.
^self * 2 > ((guess + 1 raisedTo: aPositiveInteger) + (guess raisedTo: aPositiveInteger))
ifTrue: [guess + 1]
ifFalse: [guess]
</code></pre>
<p>Then exactness is tested in nthRoot:</p>
<pre><code>Integer>>nthRoot: aPositiveInteger
"Answer the nth root of the receiver.
Answer an Integer if root is exactly this Integer, else answer the Float nearest the exact root."
| guess excess scaled nBits |
guess := self nthRootRounded: aPositiveInteger.
excess := (guess raisedTo: aPositiveInteger) - self.
excess = 0 ifTrue: [ ^ guess ].
nBits := Float precision - guess highBitOfMagnitude.
nBits <= 0 ifTrue: [ ^(Fraction numerator: guess * 4 - excess sign denominator: 4) asFloat].
scaled := self << (nBits * aPositiveInteger).
guess := scaled nthRootRounded: aPositiveInteger.
excess := (guess raisedTo: aPositiveInteger) - scaled.
^(Fraction numerator: guess * 4 - excess sign denominator: 1 << (nBits + 2)) asFloat
</code></pre>
<p>This could be applied to Fraction too, but the nearest float is a bit more complex, and Squeak implementation is currently naive.</p>
<p>It works for large integers like:</p>
<ul>
<li><code>(10 raisedTo: 600) nthRoot: 300</code> -> <code>100</code> "exact"</li>
<li><code>(10 raisedTo: 600) + 1 nthRoot: 300</code> -> <code>100.0</code> "inexact"</li>
</ul>
<p>If you don't have such expectations, the initial guess could use inexact naive <code>n**(1/exp)</code>.</p>
<p>The code should be easy to port in Python and leaves a lot of place for optimization.</p>
<p>I didn't check what was available in Python, but maybe you'll need correctly rounded LargeInteger -> Float, and Fraction -> Float, like explained here (Smalltalk too, sorry about that, but the language does not really matter).</p>
<ul>
<li><a href="http://smallissimo.blogspot.fr/2011/09/clarifying-and-optimizing.html" rel="nofollow">http://smallissimo.blogspot.fr/2011/09/clarifying-and-optimizing.html</a></li>
<li><a href="http://smallissimo.blogspot.fr/2011/09/reviewing-fraction-asfloat.html" rel="nofollow">http://smallissimo.blogspot.fr/2011/09/reviewing-fraction-asfloat.html</a></li>
</ul>
| 1 | 2016-10-02T23:48:59Z | [
"python",
"algorithm",
"floating-point",
"precision",
"nth-root"
]
|
Hadoop Streaming simple job fails error python | 39,794,372 | <p>I'm new to hadoop and mapreduce, I'm trying to write a mapreduce that counts the top 10 count words of a word count txt file.</p>
<p>My txt file 'q2_result.txt' looks like:</p>
<pre><code>yourself 268
yourselves 73
yoursnot 1
youst 1
youth 270
youthat 1
youthful 31
youths 9
youtli 1
youwell 1
youwondrous 1
youyou 1
zanies 1
zany 1
zeal 32
zealous 6
zeals 1
</code></pre>
<p>Mapper:</p>
<pre><code>#!/usr/bin/env python
import sys
for line in sys.stdin:
line = line.strip()
word, count = line.split()
print "%s\t%s" % (word, count)
</code></pre>
<p>Reducer:</p>
<pre><code>#!usr/bin/env/ python
import sys
top_n = 0
for line in sys.stdin:
line = line.strip()
word, count = line.split()
top_n += 1
if top_n == 11:
break
print '%s\t%s' % (word, count)
</code></pre>
<p>I know you can pass a flag to -D option in Hadoop jar command so it sorts on the key you want(in my case the count which is k2,2), here I'm just using a simple command first:</p>
<pre><code>hadoop jar /usr/hdp/2.5.0.0-1245/hadoop-mapreduce/hadoop-streaming-2.7.3.2.5.0.0-1245.jar -file /root/LAB3/mapper.py -mapper mapper.py -file /root/LAB3/reducer.py -reducer reducer.py -input /user/root/lab3/q2_result.txt -output /user/root/lab3/test_out
</code></pre>
<p>So I thought such simple mapper and reducer shouldn't give me errors, but it did and I can't figure out why, errors here: <a href="http://pastebin.com/PvY4d89c" rel="nofollow">http://pastebin.com/PvY4d89c</a></p>
<p>(I'm using the Horton works HDP Sandbox on a virtualBox on Ubuntu16.04)</p>
| 0 | 2016-09-30T14:53:00Z | 39,800,438 | <p>I know, "file not found error" means something completely different from "file cannot be executed", in this case the problem is that the file cannot be executed.</p>
<p>In Reducer.py:</p>
<p>Wrong:</p>
<pre><code>#!usr/bin/env/ python
</code></pre>
<p>Correct:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
| 0 | 2016-09-30T21:37:46Z | [
"java",
"python",
"hadoop",
"mapreduce",
"streaming"
]
|
Subprocess terminating when Python exits when using disown in i3 | 39,794,457 | <p>I currently have the following setup:</p>
<p>in i3 config:</p>
<pre><code>bindsym $mod+d exec xfce4-terminal --title="Supermenu" -e "path/to/supermenu"
for_window [title="Supermenu"] floating enable
</code></pre>
<p>The script it executes is a Python script executable (using a shebang and chmod +x), that has this line (among a lot of others, which have nothing to do with it):</p>
<pre><code>os.system(command + " >/dev/null 2>&1 &")
</code></pre>
<p>My expectation, is that when the Python script exits, the process called by <code>command</code> should stay running, because of the <code>&</code>. However, it still exits once the xfce4-terminal exits! (which happens after the script terminates obviously).</p>
<p>I also tried sticking <code>disown</code> at the end and <code>nohup</code> at the beginning, both made no difference.</p>
<p>I can confirm it happens when the script exits, because I tried using <code>time.sleep</code> to see if it even launches, and yes it does - but terminates after the terminal closes.</p>
<p><strong>However, if I launch <code>firefox</code> or <code>ghetto-skype</code>, they do terminate, however, an <code>xfce4-terminal</code> does not terminate after the "menu" closes!</strong></p>
<p><strong>And even weird - if I launch the script from an xfce4-terminal (instead of with i3), the subprocess will not terminate either!</strong></p>
<p>I am very confused as to what is going on, and would appreciate any help with understanding it, and prevent the processes other than <code>xfce4-terminal</code> from closing after the menu does.</p>
| 0 | 2016-09-30T14:57:23Z | 39,808,750 | <p>You aren't redirecting standard input. I'm guessing it gets an EOF when <code>xfce4-terminal</code> closes.</p>
| 1 | 2016-10-01T16:08:40Z | [
"python",
"linux",
"process"
]
|
Python argparse does not parse images with wildcard | 39,794,501 | <p>I use this library <a href="https://github.com/cmusatyalab/openface" rel="nofollow">https://github.com/cmusatyalab/openface</a> for image comparison. </p>
<p>I have downloaded Docker container with preinstalled environment. </p>
<p>I start the container and I'm accessing this file:
<a href="https://github.com/cmusatyalab/openface/blob/master/demos/compare.py" rel="nofollow">https://github.com/cmusatyalab/openface/blob/master/demos/compare.py</a></p>
<p>with this command:</p>
<blockquote>
<p>./demos/compare.py images/examples/{lennon*,clapton*}</p>
</blockquote>
<p>(check <a href="http://cmusatyalab.github.io/openface/demo-2-comparison/" rel="nofollow">http://cmusatyalab.github.io/openface/demo-2-comparison/</a> if you want)</p>
<p>It works fine when I execute the command directly from Docker terminal. Parsed arguments look like this:</p>
<pre><code>Namespace(dlibFacePredictor='/root/openface/demos/../models/dlib/shape_predictor_68_face_landmarks.dat', imgDim=96, imgs=['images/examples/lennon-1.jpg', 'images/examples/lennon-2.jpg', 'images/examples/clapton-1.jpg', 'images/examples/clapton-2.jpg'],
networkModel='/root/openface/demos/../models/openface/nn4.small2.v1.t7', verbose=False)
</code></pre>
<p>The problem is when I execute the same command from PHP file (I start simple PHP web server to access this script from host machine). PHP code:</p>
<blockquote>
<p>echo shell_exec('./demos/compare.py
images/examples/{lennon*,clapton*}')</p>
</blockquote>
<p>Parsed arguments look now like this:</p>
<pre><code>Namespace(dlibFacePredictor='/root/openface/demos/../models/dlib/shape_predictor_68_face_landmarks.dat', imgDim=96, imgs=['images/examples/{lennon*,clapton*}'],
networkModel='/root/openface/demos/../models/openface/nn4.small2.v1.t7', verbose=False)
</code></pre>
<p><strong>BOTTOMLINE:</strong></p>
<p>When script is executed directly, imgs argument is parsed correctly</p>
<pre><code>imgs=['images/examples/lennon-1.jpg', 'images/examples/lennon-2.jpg', 'images/examples/clapton-1.jpg', 'images/examples/clapton-2.jpg']
</code></pre>
<p>When script is executed from PHP script, imgs argument is not correctly parsed:</p>
<pre><code>imgs=['images/examples/{lennon*,clapton*}']
</code></pre>
<p>Code:</p>
<pre><code>import time
start = time.time()
import argparse
import cv2
import itertools
import os
import numpy as np
np.set_printoptions(precision=2)
import openface
fileDir = os.path.dirname(os.path.realpath(__file__))
modelDir = os.path.join(fileDir, '..', 'models')
dlibModelDir = os.path.join(modelDir, 'dlib')
openfaceModelDir = os.path.join(modelDir, 'openface')
parser = argparse.ArgumentParser()
parser.add_argument('imgs', type=str, nargs='+', help="Input images.")
parser.add_argument('--dlibFacePredictor', type=str, help="Path to dlib's face predictor.",
default=os.path.join(dlibModelDir, "shape_predictor_68_face_landmarks.dat"))
parser.add_argument('--networkModel', type=str, help="Path to Torch network model.",
default=os.path.join(openfaceModelDir, 'nn4.small2.v1.t7'))
parser.add_argument('--imgDim', type=int,
help="Default image dimension.", default=96)
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()
</code></pre>
<p>Any idea why this happens? Thanks.</p>
| 0 | 2016-09-30T14:59:28Z | 39,794,606 | <p>Neither python nor <code>argparse</code> do <em>any</em> wildcard expansion on the <code>argv</code> list passed in from the parent process. Instead, this is handled by the shell.</p>
<p>It'll depend on the shell wether or not your style of expansion is even supported. Evidently, the shell that <code>shell_exec()</code> spawns (usually <code>/bin/sh</code>) does not support <a href="https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html" rel="nofollow">bash-style brace expansion</a>. Instead, the wildcards are passed through to Python un-expanded.</p>
<p>Simplify the wildcard style by relying on <code>*</code> expansion only:</p>
<pre><code>echo shell_exec('./demos/compare.py images/examples/lennon* images/examples/clapton*')
</code></pre>
| 2 | 2016-09-30T15:04:26Z | [
"php",
"python",
"django",
"python-2.7"
]
|
Cannot successfully redirect stdout from Popen to temp file | 39,794,541 | <p>The title says it all, really. Currently running Python 2.7.8, using <code>subprocess32</code>. Minimum reproducing snippet, copied directly from the REPL:</p>
<pre><code>Python 2.7.8 (default, Aug 14 2014, 13:26:38)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> import subprocess32 as subp
>>> tfil = tempfile.TemporaryFile()
>>> tfil
<open file '<fdopen>', mode 'w+b' at 0x7f79dcf158a0>
>>> proc = subp.Popen(['ls', '-al'], stdout=tfil, stderr=subp.STDOUT)
>>> proc
<subprocess32.Popen object at 0x7f79dcf04a50>
>>> proc.wait()
0
>>> tfil.read()
''
>>>
</code></pre>
<p>Changes to the code that made no difference in the result, in any combination:</p>
<ul>
<li>Using <code>subprocess</code> instead of <code>subprocess32</code></li>
<li>Using <code>NamedTemporaryFile</code> instead of <code>TemporaryFile</code></li>
<li>Setting <code>bufsize=0</code> on either or both of <code>tfil</code> and <code>proc</code></li>
<li>If I try <code>subp.Popen(['ls', '-al'], stdout=sys.stdout, stderr=subp.STDOUT)</code>, the output redirects to the terminal just fine - but I need to capture it somewhere else, I can't just mix it together with actual terminal output. Redirecting <code>sys.stdout</code> to the temp file, and then setting it back after the process is done, doesn't work either.</li>
</ul>
<p>I need to do this because the command I want to use in the actual non-minimal-example program (<code>qacct -j</code>) has an output that's too big for <code>subprocess.PIPE</code>, raising a <code>MemoryError</code> (no further details).</p>
<p>The most relevant existing question I've found is <a href="http://stackoverflow.com/questions/2331339/piping-output-of-subprocess-popen-to-files">this</a>, but that didn't actually help.</p>
| 2 | 2016-09-30T15:01:27Z | 39,794,799 | <p>The file is properly written to, but your <code>tfil.read()</code> command will start reading at the point where the last write happened, so it will return nothing. You need to call <code>tfil.seek(0)</code> first.</p>
| 2 | 2016-09-30T15:14:17Z | [
"python",
"subprocess",
"io-redirection",
"temporary-files"
]
|
How should I escape commas in Active Directory filters? | 39,794,550 | <p>I'm using python-ldap to query Active Directory</p>
<p>I have this DN </p>
<pre><code>CN=Whalen\, Sean,OU=Users,OU=Users and Groups,DC=example,DC=net
</code></pre>
<p>That works fine as a base in a query, but if I try to use it in a search filter like this</p>
<pre><code>(&(objectClass=group)(memberof:1.2.840.113556.1.4.1941:=CN=Whalen\, Sean,OU=Users,OU=Users and Groups,DC=example,DC=net))
</code></pre>
<p>I get a <code>Bad search filter</code> error. From my testing, the comma in the CN seems to be the culprit, even though I escaped it with a backslash (<code>\</code>). But, comma isn't listed in the <a href="http://social.technet.microsoft.com/wiki/contents/articles/5312.active-directory-characters-to-escape.aspx#LDAP_Filters" rel="nofollow">Microsoft documentation</a> as a character that needs escaped in filters.</p>
<p>What am I missing? </p>
| 0 | 2016-09-30T15:02:02Z | 39,805,523 | <p>The LDAP filter specification assigns special meaning to the following characters <code>* ( ) \ NUL</code> that should be escaped with the backslash escape character followed by the two character ASCII hexadecimal representation of the character (<a href="https://tools.ietf.org/search/rfc2254#page-5" rel="nofollow">rfc2254</a>) :</p>
<pre><code>* \2A
( \28
) \29
\ \5C
Nul \00
</code></pre>
<p>So in your case, any backslash used for escaping DN' special characters must be represented by <code>\5c</code> when used in a search filter :</p>
<pre><code>(&(objectClass=group)(memberof:1.2.840.113556.1.4.1941:=CN=Whalen\5c, Sean,OU=Users,OU=Users and Groups,DC=example,DC=net))
</code></pre>
| 1 | 2016-10-01T10:29:26Z | [
"python",
"active-directory",
"ldap",
"ldap-query",
"python-ldap"
]
|
Pywinauto: unable to bring window to foreground | 39,794,729 | <p>Working on the Python-powered automation tool.</p>
<p>Imagine there is a pool of apps running:</p>
<pre><code>APPS_POOL = ['Chrome', 'SomeApp', 'Foo']
</code></pre>
<p>The script runs in the loop (every second) and needs to switch randomly between them:</p>
<pre><code># Init App object
app = application.Application()
# Select random app from the pull of apps
random_app = random.choice(APPS_POOL)
app.connect(title_re=".*%s" % random_app)
print 'Select "%s"' % random_app
# Access app's window object
app_dialog = app.window_(title_re=".*%s.*" % random_app)
if app_dialog.Exists():
app_dialog.SetFocus()
</code></pre>
<p>The first time it works fine, but every other - the window would not be brought into foreground. Any ideas?</p>
<p><strong>EDIT:</strong> the script is ran from Win7 CMD. Is it possible the system "blocks" CMD from setting focus somehow, once focus is set to other window?</p>
| 2 | 2016-09-30T15:10:32Z | 39,800,690 | <p>I think the <code>SetFocus</code> is a bit buggy. At least on my machine I get an error: <code>error: (87, 'AttachThreadInput', 'The parameter is incorrect.')</code>. So maybe you can play with Minimize/Restore. Notice that this approach is not bullet proof either.</p>
<pre><code>import random
import time
from pywinauto import application
from pywinauto.findwindows import WindowAmbiguousError, WindowNotFoundError
APPS_POOL = ['Chrome', 'GVIM', 'Notepad', 'Calculator', 'SourceTree', 'Outlook']
# Select random app from the pull of apps
def show_rand_app():
# Init App object
app = application.Application()
random_app = random.choice(APPS_POOL)
try:
print 'Select "%s"' % random_app
app.connect(title_re=".*%s.*" % random_app)
# Access app's window object
app_dialog = app.top_window_()
app_dialog.Minimize()
app_dialog.Restore()
#app_dialog.SetFocus()
except(WindowNotFoundError):
print '"%s" not found' % random_app
pass
except(WindowAmbiguousError):
print 'There are too many "%s" windows found' % random_app
pass
for i in range(15):
show_rand_app()
time.sleep(0.3)
</code></pre>
| 2 | 2016-09-30T22:02:02Z | [
"python",
"pywinauto"
]
|
Pandas DataFrame.values conversion error or feature? | 39,794,731 | <p>I having some difficulty with some "behind the scenes" conversions that <code>pandas</code> (v. 0.18.0) seems to be performing for the <code>values</code> property of a <code>DataFrame</code>.
I have a data set that looks something like the following: </p>
<pre><code>data = [(1473897600000000, 9.9166, 1.8621, 15),
(1473897660000000, 19.9166, 3.8621, 20),
(1473897720000000, 29.9166, 5.8621, 25),
(1473897780000000, 39.9166, 7.8621, 30)]
</code></pre>
<p>The first element of each tuple represents a POSIX UTC timestamp in microseconds. The <code>(name, dtype)</code> of each element is given by the following record array:</p>
<pre><code>dtype = [('timestamp', np.dtype('int64')),
('a', np.dtype('float32')),
('b', np.dtype('float32')),
('c', np.dtype('uint8'))]
</code></pre>
<p>I'm converting this to a <code>DataFrame</code> as using the following code:</p>
<pre><code>data_array = np.array(data, dtype=dtype)
df = pd.DataFrame.from_records(data_array)
</code></pre>
<p>However, the following code gives some strange results (at least to me):</p>
<pre><code>ts_orig = np.array([x[0] for x in data], dtype=float)
ts_column = df['timestamp'].values.astype(float)
ts_values = df.values[:, 0]
ts_diff = ts_values - ts_column
print(np.column_stack((ts_orig, ts_column, ts_values, ts_diff)))
# OUTPUT
# ts_orig ts_column ts_values ts_diff
[[ 1.47389760e+15 1.47389760e+15 1.47389762e+15 1.87351040e+07]
[ 1.47389766e+15 1.47389766e+15 1.47389762e+15 -4.12648960e+07]
[ 1.47389772e+15 1.47389772e+15 1.47389775e+15 3.29528320e+07]
[ 1.47389778e+15 1.47389778e+15 1.47389775e+15 -2.70471680e+07]]
</code></pre>
<p>It seems clear that there is no problem converting the timestamp values to identical floating point values directly (columns 1 and 2). Accurate values are still retained in the <code>DataFrame</code>, however when the entire <code>DataFrame</code> is converted to an array through the <code>DataFrame.values</code> property (3rd column) something happens to scramble the timestamp values and throw them wildly off. </p>
<p>Why is this happening and how do I prevent it?</p>
| 2 | 2016-09-30T15:10:39Z | 39,795,869 | <p>At the risk of sounding stupid, I'll answer my own question, should have dug a little deeper in the first place. The root of the problem is the conversion to the lowest common denominator type, quoting from the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html#pandas.DataFrame.values" rel="nofollow">DataFrame.values</a> docmentation: </p>
<blockquote>
<p>The dtype will be a lower-common-denominator dtype (implicit upcasting); that is to say if the dtypes (even of numeric types) are mixed, the one that accommodates all will be chosen. Use this with care if you are not dealing with the blocks</p>
</blockquote>
<p>In this case the most accommodating type chosen is <code>float32</code> so all values are converted to that. This can store the value of the <code>int64</code> timestamp but due to numeric precision issues with the <code>float32</code> type the timestamp values snap to the nearest <code>float32</code> value. If you change one of the <code>dtype</code> values in the original data to <code>float64</code> the problem silently disappears. </p>
<p>Here is a followup question though. Given a mixed data set with 64 bit integer types and floating point types, wouldn't the best course of action be to choose the widest type (64 bit) so no precision is lost?</p>
| 1 | 2016-09-30T16:16:33Z | [
"python",
"pandas"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.