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 |
|---|---|---|---|---|---|---|---|---|---|
How can I print the Truth value of a variable? | 39,604,780 | <p>In Python, variables have truthy values based on their content. For example:</p>
<pre><code>>>> def a(x):
... if x:
... print (True)
...
>>> a('')
>>> a(0)
>>> a('a')
True
>>>
>>> a([])
>>> a([1])
True
>>> a([None])
True
>>&... | 2 | 2016-09-20T22:36:06Z | 39,604,788 | <p>Use the builtin <code>bool</code> type.</p>
<pre><code>print(bool(a))
</code></pre>
<p>Some examples from the REPL:</p>
<pre><code>>>> print(bool(''))
False
>>> print(bool('a'))
True
>>> print(bool([]))
False
</code></pre>
| 4 | 2016-09-20T22:37:09Z | [
"python",
"python-3.x",
"boolean",
"output"
] |
How to compress a file with bzip2 in Python? | 39,604,843 | <p>Here is what I have:</p>
<pre><code>import bz2
compressionLevel = 9
source_file = '/foo/bar.txt' #this file can be in a different format, like .csv or others...
destination_file = '/foo/bar.bz2'
tarbz2contents = bz2.compress(source_file, compressionLevel)
fh = open(destination_file, "wb")
fh.write(tarbz2contents)... | 0 | 2016-09-20T22:43:29Z | 39,604,890 | <p>The <a href="https://docs.python.org/2/library/bz2.html#bz2.compress" rel="nofollow">documentation for bz2.compress</a> for says it takes data, not a file name.<br>
Try replacing the line below:</p>
<pre><code>tarbz2contents = bz2.compress(open(source_file, 'rb').read(), compressionLevel)
</code></pre>
<p>...or ma... | 1 | 2016-09-20T22:48:03Z | [
"python",
"compression",
"bzip2"
] |
Qthread is still working when i close gui on python pyqt | 39,604,903 | <p>my code has thread, but when i close the gui, it still works on background. how can i stop threads? is there something stop(), close()?
i dont use signal, slots? Must i use this?</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys
import time
import threading
class Main(QtGui.QMainWindow):
def __init__(s... | 3 | 2016-09-20T22:49:30Z | 39,605,384 | <p>I chose to rewrite a bit this answer, because I had failed to properly look at the problem's context. As the other answers and comments tell, you code lacks thread-safety. </p>
<p>The best way to fix this is to try to really think "in threads", to restrict yourself to only use objects living in the same thread, or ... | 2 | 2016-09-20T23:44:30Z | [
"python",
"python-3.x",
"pyqt",
"pyqt4",
"qthread"
] |
Qthread is still working when i close gui on python pyqt | 39,604,903 | <p>my code has thread, but when i close the gui, it still works on background. how can i stop threads? is there something stop(), close()?
i dont use signal, slots? Must i use this?</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys
import time
import threading
class Main(QtGui.QMainWindow):
def __init__(s... | 3 | 2016-09-20T22:49:30Z | 39,609,677 | <p>A few things:</p>
<ol>
<li><p>You shouldn't be calling GUI code from outside the main thread. GUI elements are not thread-safe. <code>self.kontenjan_ara</code> updates and reads from GUI elements, it shouldn't be the target of your <code>thread</code>.</p></li>
<li><p>In almost all cases, you should use <code>QThr... | 3 | 2016-09-21T07:09:37Z | [
"python",
"python-3.x",
"pyqt",
"pyqt4",
"qthread"
] |
How to convert JSON into multiple dictonaries using Python | 39,604,911 | <p>I'd like to take the following JSON and convert it into multiple dicts so I can access each setting under the top level nodes only for that environment. This is a config file that will maintain settings for different environments, I'd like to be able to grab a top level node/environment and then use all the underly... | -1 | 2016-09-20T22:50:32Z | 39,605,043 | <p>Your question is really confusing but I'll try guessing a little bit, let's assume you got a json file (I'll emulate that using python3.x <a href="https://docs.python.org/3/library/io.html" rel="nofollow">io.StringIO</a>).</p>
<p>I assume you want to know how to load that file into a python dictionary, to do that u... | 0 | 2016-09-20T23:04:47Z | [
"python",
"json",
"dictionary",
"configuration"
] |
How to convert JSON into multiple dictonaries using Python | 39,604,911 | <p>I'd like to take the following JSON and convert it into multiple dicts so I can access each setting under the top level nodes only for that environment. This is a config file that will maintain settings for different environments, I'd like to be able to grab a top level node/environment and then use all the underly... | -1 | 2016-09-20T22:50:32Z | 39,605,051 | <p>There's std lib capable of doing it</p>
<pre><code>import json
my_dct = json.loads(json_string)
</code></pre>
<p>for more, see <a href="https://docs.python.org/3.5/library/json.html#json.loads" rel="nofollow">https://docs.python.org/3.5/library/json.html#json.loads</a></p>
| 0 | 2016-09-20T23:05:20Z | [
"python",
"json",
"dictionary",
"configuration"
] |
How to convert JSON into multiple dictonaries using Python | 39,604,911 | <p>I'd like to take the following JSON and convert it into multiple dicts so I can access each setting under the top level nodes only for that environment. This is a config file that will maintain settings for different environments, I'd like to be able to grab a top level node/environment and then use all the underly... | -1 | 2016-09-20T22:50:32Z | 39,605,129 | <p>Store above data within a variable like below and convert it to dict using json.loads
It converts text to dictionary, then you can loop over dictionary based on env to get the properties</p>
<pre><code>text='''
{ "default":
{
"build": {
"projectKey": "TEST",
"buildKey": "ME"
},
"headers": {
"json": "applica... | 0 | 2016-09-20T23:13:37Z | [
"python",
"json",
"dictionary",
"configuration"
] |
How to convert JSON into multiple dictonaries using Python | 39,604,911 | <p>I'd like to take the following JSON and convert it into multiple dicts so I can access each setting under the top level nodes only for that environment. This is a config file that will maintain settings for different environments, I'd like to be able to grab a top level node/environment and then use all the underly... | -1 | 2016-09-20T22:50:32Z | 39,605,445 | <p>You need <code>json.loads()</code> to convert your <code>string</code> to <code>json</code> object. Below is the code to open the file and load the json as <code>dict</code> or <code>list</code> based on the structure of json (in your case <code>dict</code>)</p>
<pre><code>import json
json_file = open('/path/to/con... | 0 | 2016-09-20T23:52:06Z | [
"python",
"json",
"dictionary",
"configuration"
] |
What does (n,) mean in the context of numpy and vectors? | 39,604,918 | <p>I've tried searching StackOverflow, googling, and even using symbolhound to do character searches, but was unable to find an answer. Specifically, I'm confused about Ch. 1 of Nielsen's <em>Neural Networks and Deep Learning</em>, where he says "It is assumed that the input <code>a</code> is an <code>(n, 1) Numpy ndar... | 2 | 2016-09-20T22:51:21Z | 39,605,142 | <p><code>(n,)</code> is a tuple of length 1, whose only element is <code>n</code>. (The syntax isn't <code>(n)</code> because that's just <code>n</code> instead of making a tuple.)</p>
<p>If an array has shape <code>(n,)</code>, that means it's a 1-dimensional array with a length of <code>n</code> along its only dimen... | 3 | 2016-09-20T23:14:27Z | [
"python",
"numpy",
"machine-learning",
"neural-network"
] |
What does (n,) mean in the context of numpy and vectors? | 39,604,918 | <p>I've tried searching StackOverflow, googling, and even using symbolhound to do character searches, but was unable to find an answer. Specifically, I'm confused about Ch. 1 of Nielsen's <em>Neural Networks and Deep Learning</em>, where he says "It is assumed that the input <code>a</code> is an <code>(n, 1) Numpy ndar... | 2 | 2016-09-20T22:51:21Z | 39,605,320 | <p>In <code>numpy</code> an array can have a number of different dimensions, 0, 1, 2 etc.</p>
<p>The typical 2d array has dimension <code>(n,m)</code> (this is a Python tuple). We tend to describe this as having n rows, m columns. So a <code>(n,1)</code> array has just 1 column, and a <code>(1,m)</code> has 1 row.</... | 2 | 2016-09-20T23:36:09Z | [
"python",
"numpy",
"machine-learning",
"neural-network"
] |
Python: passing parameters over functions | 39,604,958 | <p>Python Experts,</p>
<p>I have been trying to implement BST using Python and here is my code for the insert function:</p>
<p><strong>Draft 1:</strong></p>
<pre><code>def insert(self, val):
newNode = self._Node(val)
if (self._root is None):
self._root = newNode
else:
self._insert(self._... | 2 | 2016-09-20T22:55:39Z | 39,605,307 | <p>The fundamental misunderstanding you have is how variable assignment works and interacts with Python's evaluation strategy: <a href="https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing" rel="nofollow">call-by-sharing.</a></p>
<p>Essentially, in your first draft, when you do the following:</p>
<pre><c... | 2 | 2016-09-20T23:34:41Z | [
"python"
] |
Python: passing parameters over functions | 39,604,958 | <p>Python Experts,</p>
<p>I have been trying to implement BST using Python and here is my code for the insert function:</p>
<p><strong>Draft 1:</strong></p>
<pre><code>def insert(self, val):
newNode = self._Node(val)
if (self._root is None):
self._root = newNode
else:
self._insert(self._... | 2 | 2016-09-20T22:55:39Z | 39,605,422 | <p>I believe this is due to the fact that by doing :</p>
<pre><code>node = self._Node(val)
</code></pre>
<p>in the _insert function you are not changing the value of the left/right node but binding the name node to a new _Node object, thus letting the left/right node as None. </p>
<p>On your second draft you are ef... | 1 | 2016-09-20T23:48:48Z | [
"python"
] |
How do I add numbers in a list that do not equal parameters? | 39,605,064 | <p>I am trying to write a function that will add all of the numbers in a list that do not equal the parameters. The code I have, that is not working, is:</p>
<pre><code>def suminout(nums,a,b):
total=0
for i in range(len(nums)):
if nums[i]!=a or nums[i]!=b:
total=total+nums[i]
return to... | -2 | 2016-09-20T23:06:36Z | 39,605,111 | <p>As Kasramvd so duly noted, you need conjunction not disjunction.</p>
<p>Here is a list comprehension doing the same thing.</p>
<pre><code>def suminout(nums, a, b):
total = 0
total = sum([x for x in nums if (x!=a and x!=b)])
return total
</code></pre>
| 1 | 2016-09-20T23:11:51Z | [
"python",
"list",
"parameters",
"sum"
] |
How do I add numbers in a list that do not equal parameters? | 39,605,064 | <p>I am trying to write a function that will add all of the numbers in a list that do not equal the parameters. The code I have, that is not working, is:</p>
<pre><code>def suminout(nums,a,b):
total=0
for i in range(len(nums)):
if nums[i]!=a or nums[i]!=b:
total=total+nums[i]
return to... | -2 | 2016-09-20T23:06:36Z | 39,605,259 | <p>You need to use <code>and</code> instead of <code>or</code>.</p>
<pre><code>def suminout(nums,a,b):
total=0
for i in range(len(nums)):
if nums[i]!=a and nums[i]!=b:
total=total+nums[i]
return total
</code></pre>
<p>Your <code>for</code> logic could be further simplified (without usi... | 0 | 2016-09-20T23:29:48Z | [
"python",
"list",
"parameters",
"sum"
] |
How do I add numbers in a list that do not equal parameters? | 39,605,064 | <p>I am trying to write a function that will add all of the numbers in a list that do not equal the parameters. The code I have, that is not working, is:</p>
<pre><code>def suminout(nums,a,b):
total=0
for i in range(len(nums)):
if nums[i]!=a or nums[i]!=b:
total=total+nums[i]
return to... | -2 | 2016-09-20T23:06:36Z | 39,605,573 | <p>Or:</p>
<pre><code>def suminout(nums, a, b):
total = 0
total = sum([x for x in nums if x not in (a,b)])
return total
</code></pre>
| 0 | 2016-09-21T00:08:52Z | [
"python",
"list",
"parameters",
"sum"
] |
Image class keeps selecting different images instead of identical, how to fix? Sikuli | 39,605,067 | <p>I'm using the random 5 card shuffler to get the hang of some basic scripting, but the script will select A A 3 or 10 9 8 instead of just ignoring them. How could I get it to run faster?</p>
<pre><code>running = True
def runHotkey(event):
global running
running = False
Env.addHotkey(Key.F1, KeyModifier.CTR... | 0 | 2016-09-20T23:06:43Z | 40,041,254 | <p>If There are more than one match for given image at given similarity, sikuli click only one image (Randomly) out of it. So if you want to click similar images with more stably you need to develop code using findAll function and later sort the Match results of findAll function and click one of it. You can sort the im... | 0 | 2016-10-14T10:44:22Z | [
"python",
"jython",
"sikuli"
] |
Assigning custom method to on_touch_down etc. in Kivy | 39,605,079 | <p>I'm writing what is ultimately to be a mobile game app using Kivy. Given the capabilities of the framework - being able to separate form and function - I'm attempting to do most, if not all, of the design of my GUI within a .kv file using the Kivy language. This works great as far as crafting a layout, but getting t... | 0 | 2016-09-20T23:08:29Z | 39,605,322 | <p>I confess I've never used Kivy, but the <a href="https://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.on_touch_down" rel="nofollow">documentation for on_touch_down</a> indicates it receives a <code>touch</code> parameter.</p>
<p>The <a href="https://kivy.org/docs/api-kivy.lang.html#value-expression... | 1 | 2016-09-20T23:36:11Z | [
"python",
"kivy",
"kivy-language"
] |
Hollow diamond in python with an asterisk outline | 39,605,093 | <p>I have to build a hollow diamond like this one:</p>
<pre><code> ******
** **
* *
* *
** **
******
</code></pre>
<p>Heres what I have so far, </p>
<pre><code>def hollow_diamond(w):
h=int(w/2)
while 0<h:
print('*'*h)
h=h-1
i=1
while i<(w/2+1):
print(i*'*')
i=i+1
</code></p... | -3 | 2016-09-20T23:09:38Z | 39,605,216 | <p>Building a hollow diamond means, like you said, probably the following:</p>
<ol>
<li>A line with full asterisks (<code>0</code> spaces in the middle)</li>
<li>A line with <code>2</code> spaces in the middle</li>
<li>A line with <code>4</code> spaces in the middle</li>
<li>...</li>
<li>A line with <code>l-2</code> s... | 0 | 2016-09-20T23:24:27Z | [
"python",
"python-3.x"
] |
Hollow diamond in python with an asterisk outline | 39,605,093 | <p>I have to build a hollow diamond like this one:</p>
<pre><code> ******
** **
* *
* *
** **
******
</code></pre>
<p>Heres what I have so far, </p>
<pre><code>def hollow_diamond(w):
h=int(w/2)
while 0<h:
print('*'*h)
h=h-1
i=1
while i<(w/2+1):
print(i*'*')
i=i+1
</code></p... | -3 | 2016-09-20T23:09:38Z | 39,605,294 | <p>I won't steal from you the joy to fix your homework but this exercise was quite fun so I'll give you another possible version to give you few ideas:</p>
<pre><code>def cool_diamond(w):
r = []
for y in range(w):
s = '*' * (w - y)
r.append("{0}{1}{0}".format(s, ''.join(['-' for x in range(2 * ... | 0 | 2016-09-20T23:33:26Z | [
"python",
"python-3.x"
] |
Hollow diamond in python with an asterisk outline | 39,605,093 | <p>I have to build a hollow diamond like this one:</p>
<pre><code> ******
** **
* *
* *
** **
******
</code></pre>
<p>Heres what I have so far, </p>
<pre><code>def hollow_diamond(w):
h=int(w/2)
while 0<h:
print('*'*h)
h=h-1
i=1
while i<(w/2+1):
print(i*'*')
i=i+1
</code></p... | -3 | 2016-09-20T23:09:38Z | 39,605,446 | <p>You've already figured out how to print the first set of asterisks for each line; good job so far. Now, you need to figure out how many spaces to print. Let's take the first loop, where you're printing <strong>h</strong> asterisks in a grid of <strong>w</strong> lines.</p>
<p>You need <strong>h</strong> asterisks... | 1 | 2016-09-20T23:52:06Z | [
"python",
"python-3.x"
] |
Convert DateTime to sequential day of the year | 39,605,156 | <p>I have a dataframe that contains a series of dates, e.g.:</p>
<pre><code>0 2014-06-17
1 2014-05-05
2 2014-01-07
3 2014-06-29
4 2014-03-15
5 2014-06-06
7 2014-01-29
</code></pre>
<p>Now, I need a way to convert these dates to the sequential day of the year, e.g.</p>
<pre><code>0 168
1 12... | 2 | 2016-09-20T23:16:28Z | 39,605,166 | <p><strong><em>Option 1</em></strong><br>
<a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-date-components" rel="nofollow"><strong><em>time-date-components</em></strong></a><br>
Link from @root<br>
Use <code>dt.dayofyear</code></p>
<pre><code>df.iloc[:, 0].dt.dayofyear
0 168
1 125
2 ... | 4 | 2016-09-20T23:17:57Z | [
"python",
"pandas"
] |
Convert DateTime to sequential day of the year | 39,605,156 | <p>I have a dataframe that contains a series of dates, e.g.:</p>
<pre><code>0 2014-06-17
1 2014-05-05
2 2014-01-07
3 2014-06-29
4 2014-03-15
5 2014-06-06
7 2014-01-29
</code></pre>
<p>Now, I need a way to convert these dates to the sequential day of the year, e.g.</p>
<pre><code>0 168
1 12... | 2 | 2016-09-20T23:16:28Z | 39,605,588 | <p>Yes, I did it. Please refer my below code. </p>
<p><strong><em><a href="http://i.stack.imgur.com/WYI7k.png" rel="nofollow">Screen shot of my RESULT</a></em></strong></p>
<p>Step 1: Make array of String datatype and add dates in string format. </p>
<p>Step 2: Use for loop because you have multiple dates.</p>
<p>S... | -1 | 2016-09-21T00:11:45Z | [
"python",
"pandas"
] |
How to print specific value from key in a dictionary? | 39,605,252 | <p>Our teacher set us a challenge to make a program that will allow users to input a symbol of an element and the program should output some info about the element.</p>
<p>To do this I have to use dictionaries. Currently I have this:</p>
<pre><code>elements = {"Li": "Lithium" " 12" " Alkali Metal"}
element = input("E... | 0 | 2016-09-20T23:28:18Z | 39,605,283 | <p>You currently have one string as a value so there is not much you can do reliably. You would need to store separate values which you could do with a sub-dict:</p>
<pre><code>elements = {"Li": {"full_name":"Lithium", "num":"12", "type":"Alkali Metal"}}
</code></pre>
<p>Then just access the nested dict using the key... | 3 | 2016-09-20T23:31:40Z | [
"python",
"python-3.x"
] |
Tensorflow: Numpy equivalent of tf batches and reshape | 39,605,399 | <p>I am trying to classify some images using Tensorflow using the LSTM method in image classification with one-hot encoding output and a softmax classifier at the last LSTM output. My dataset is CSV and had to research a lot in Numpy and Tensorflow on how to do some modifications. I'm still getting an error:</p>
<pre>... | 1 | 2016-09-20T23:46:24Z | 39,605,486 | <p>You can make your own function called next batch that given a numpy array and indices will return that slice of the numpy array for you.</p>
<pre><code>def nextbatch(x,i,j):
return x[i:j,...]
</code></pre>
<p>You could also pass in what step you are in and maybe do modulo but this is the basic that will get it... | 2 | 2016-09-20T23:57:24Z | [
"python",
"numpy",
"machine-learning",
"tensorflow"
] |
D3 Line with JSON Data, Not Rendering | 39,605,488 | <p>I have a Flask webserver that takes a dict of Python data and uses the jsonify function to return a JSON object when a GET is called on <code>/data</code>. The JSON object is not a nested list (see sample below) like most other examples on here.</p>
<p>I've been attempting to take that JSON data and pass it into my... | 1 | 2016-09-20T23:57:34Z | 39,605,814 | <p>Your data is in a strange format for <code>d3</code>ing. <code>d3</code> prefers arrays of objects where each property of the object represents an <code>x</code> or<code>y</code>. So your data properly formatted should look something like this:</p>
<pre><code>[{
"timeStamps": "2016-09-20T23:15:07.000Z",
"outT... | 0 | 2016-09-21T00:41:49Z | [
"javascript",
"python",
"json",
"d3.js",
"svg"
] |
twist dataframe by rank | 39,605,512 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(4, 5), columns=list('ABCDE'))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/VuXYh.png" rel="nofollow"><img src="http://i.stack.imgur.com/VuXYh.png" alt="enter image description here"></a></p>
<h... | 1 | 2016-09-21T00:00:11Z | 39,605,942 | <p>Here's one way:</p>
<pre><code>In [90]: df
Out[90]:
A B C D E
0 0.444939 0.407554 0.460148 0.465239 0.462691
1 0.016545 0.850445 0.817744 0.777962 0.757983
2 0.934829 0.831104 0.879891 0.926879 0.721535
3 0.117642 0.145906 0.199844 0.437564 0.100702
In... | 3 | 2016-09-21T00:57:18Z | [
"python",
"pandas",
"numpy"
] |
twist dataframe by rank | 39,605,512 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(4, 5), columns=list('ABCDE'))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/VuXYh.png" rel="nofollow"><img src="http://i.stack.imgur.com/VuXYh.png" alt="enter image description here"></a></p>
<h... | 1 | 2016-09-21T00:00:11Z | 39,608,310 | <p>Use <code>stack</code>, <code>reset_index</code>, and <code>pivot</code></p>
<pre><code>df.rank(1).astype(int).stack().reset_index() \
.pivot('level_0', 0, 'level_1').rename_axis(None)
</code></pre>
<p><a href="http://i.stack.imgur.com/plUw1.png" rel="nofollow"><img src="http://i.stack.imgur.com/plUw1.png" alt="... | 1 | 2016-09-21T05:39:08Z | [
"python",
"pandas",
"numpy"
] |
twist dataframe by rank | 39,605,512 | <p>consider the dataframe <code>df</code></p>
<pre><code>np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(4, 5), columns=list('ABCDE'))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/VuXYh.png" rel="nofollow"><img src="http://i.stack.imgur.com/VuXYh.png" alt="enter image description here"></a></p>
<h... | 1 | 2016-09-21T00:00:11Z | 39,610,093 | <p>Here's another way.</p>
<pre><code>In [5]: df1 = df.rank(1).astype(int)
In [6]: df3 = df1.replace({rank: name for rank, name in enumerate(df1.columns, 1)})
In [7]: df3.columns = range(1, 1 + df3.shape[1])
In [8]: df3
Out[8]:
1 2 3 4 5
0 B A C E D
1 A E D C B
2 E B C D A
3 B C D E A
</... | 1 | 2016-09-21T07:28:48Z | [
"python",
"pandas",
"numpy"
] |
ImportError: No module named mako.util when running airflow | 39,605,604 | <p>I'm trying to follow the tutorial on here: <a href="http://pythonhosted.org/airflow/tutorial.html" rel="nofollow">http://pythonhosted.org/airflow/tutorial.html</a></p>
<p>but i'm using a mac, and so i had to install python via <code>brew</code>, which then comes with <code>pip</code>, which i used to install <code>... | 0 | 2016-09-21T00:14:21Z | 39,608,524 | <p>Finally figured it out. after trying a bunch of things. for one, the python that comes with Mac apparently doesn't work very well. you have to <code>brew install python</code> instead. with that python, it comes with <code>pip</code> by default</p>
<p>i had to actually <code>sudo pip uninstall airflow</code> and th... | 0 | 2016-09-21T05:55:51Z | [
"python",
"python-2.7",
"mako",
"airflow"
] |
Access a global variable to track status in multiprocessing | 39,605,634 | <p>I am writing a multiprocessing process that I want to monitor the status of. How can I access my_var from thaht context?</p>
<pre><code>from multiprocessing import Process
import time
my_var = list()
def alter_my_var():
global my_var
for x in range(10):
my_var.append(x)
time.sleep(1)
p ... | 1 | 2016-09-21T00:18:53Z | 39,605,728 | <p>Use a <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.sharedctypes.multiprocessing.Manager" rel="nofollow"><em>Manager</em></a>, each process gets a copy of the list so you are not sharing one object, with <em>Manager().list()</em> you are:</p>
<pre><code>from multiprocessing import ... | 1 | 2016-09-21T00:31:01Z | [
"python"
] |
Access a global variable to track status in multiprocessing | 39,605,634 | <p>I am writing a multiprocessing process that I want to monitor the status of. How can I access my_var from thaht context?</p>
<pre><code>from multiprocessing import Process
import time
my_var = list()
def alter_my_var():
global my_var
for x in range(10):
my_var.append(x)
time.sleep(1)
p ... | 1 | 2016-09-21T00:18:53Z | 39,605,730 | <p>Try this:</p>
<pre><code>from multiprocessing import Process, Pipe
import time
my_var = list()
def alter_my_var(my_var, conn):
for x in range(10):
my_var.append(x)
conn.send(len(my_var))
time.sleep(1)
global my_var
parent_conn, child_conn = Pipe()
p = Process(target=alter_my_var, arg... | 0 | 2016-09-21T00:31:03Z | [
"python"
] |
Access a global variable to track status in multiprocessing | 39,605,634 | <p>I am writing a multiprocessing process that I want to monitor the status of. How can I access my_var from thaht context?</p>
<pre><code>from multiprocessing import Process
import time
my_var = list()
def alter_my_var():
global my_var
for x in range(10):
my_var.append(x)
time.sleep(1)
p ... | 1 | 2016-09-21T00:18:53Z | 39,605,736 | <p>You are using <code>multiprocessing</code> not <code>threading</code>. Process run in a different memory space and variables get copied to the child process but they do not point to the same memory address anymore. Therefore, what you modify in the process can not be read by the main process. </p>
<p>If you don't c... | 2 | 2016-09-21T00:32:51Z | [
"python"
] |
How do I pull a recurring key from a JSON? | 39,605,640 | <p>I'm new to python (and coding in general), I've gotten this far but I'm having trouble. I'm querying against a web service that returns a json file with information on every employee. I would like to pull just a couple of attributes for each employee, but I'm having some trouble.</p>
<p>I have this script so far:</... | 4 | 2016-09-21T00:19:21Z | 39,605,651 | <p>Your JSON is the <code>list</code> of <code>dict</code> objects. By doing <code>j[1]</code>, you are accessing the item in the list at index <code>1</code>. In order to get all the records, you need to iterate all the elements of the list as:</p>
<pre><code>for item in j:
print item['name']
</code></pre>
<p>wh... | 6 | 2016-09-21T00:21:43Z | [
"python",
"json"
] |
How do I pull a recurring key from a JSON? | 39,605,640 | <p>I'm new to python (and coding in general), I've gotten this far but I'm having trouble. I'm querying against a web service that returns a json file with information on every employee. I would like to pull just a couple of attributes for each employee, but I'm having some trouble.</p>
<p>I have this script so far:</... | 4 | 2016-09-21T00:19:21Z | 39,605,815 | <p>Slightly nicer for mass-conversions than repeated <code>dict</code> lookup is using <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter</code></a>:</p>
<pre><code>from future_builtins import map # Only on Py2, to get lazy, generator based map
from ... | 2 | 2016-09-21T00:41:57Z | [
"python",
"json"
] |
Searching for and manipulating the content of a keyword in a huge file | 39,605,704 | <p>I have a huge HTML file that I have converted to text file. (The file is Facebook home page's source). Assume the text file has a specific keyword in some places of it. For example: "some_keyword: [bla bla]". How would I print all the different bla blas that are followed by some_keyword?</p>
<pre><code>{id:"1126830... | 0 | 2016-09-21T00:28:27Z | 39,605,735 | <p>Based on your comment, since you are the person responsible for writting the data to the file. Write the data in JSON format and read it from file using <a href="https://docs.python.org/2/library/json.html#json.loads" rel="nofollow"><code>json.loads()</code></a> as:</p>
<pre><code>import json
json_file = open('/pat... | 0 | 2016-09-21T00:32:34Z | [
"python"
] |
Searching for and manipulating the content of a keyword in a huge file | 39,605,704 | <p>I have a huge HTML file that I have converted to text file. (The file is Facebook home page's source). Assume the text file has a specific keyword in some places of it. For example: "some_keyword: [bla bla]". How would I print all the different bla blas that are followed by some_keyword?</p>
<pre><code>{id:"1126830... | 0 | 2016-09-21T00:28:27Z | 39,625,346 | <p>I just wanted to throw this out there even though I agree with all the comments about just dealing with the html directly or using Facebook's API (probably the safest way), but open file objects in Python can be used as a generator yielding lines without reading the entire file into memory and the re module can be u... | 0 | 2016-09-21T19:48:45Z | [
"python"
] |
Is there a version of __file__ that when used in a function, will get the name of the file that uses the library? | 39,605,747 | <p>So, as a joke I wrote a version of goto for python that I wanted to use as a library. The function I wrote for it is as follows.</p>
<pre><code>def goto(loc):
exec(open(__file__).read().split("# "+str(loc))[1],globals())
quit()
</code></pre>
<p>This works for cases where it is in the file where goto is used, s... | 1 | 2016-09-21T00:33:54Z | 39,605,823 | <p>Yes, you can if you inspect the call stack:</p>
<pre><code>import inspect
def goto():
try:
frame = inspect.currentframe()
print(frame.f_back.f_globals['__file__'])
finally:
# break reference cycles
# https://docs.python.org/3.6/library/inspect.html#the-interpreter-stack
... | 0 | 2016-09-21T00:42:45Z | [
"python",
"python-3.x",
"goto"
] |
Double loop takes time | 39,605,839 | <p>I have a script which takes a lot of time and can't finish so far after 2 days...
I parsed 1 file into 2 dictionaries as the following:</p>
<pre><code>gfftree = {'chr1':[(gene_id, gstart, gend),...], 'chr2':[(gene_id, gstart, gend),...],...}
TElocation = {'chr1':[(TE_id, TEstart, TEend),...], 'chr2':[(TE_id, TEstar... | 6 | 2016-09-21T00:43:56Z | 39,605,897 | <p>The OP approach is <code>O(n*m)</code>, where <code>n</code> is the number of genes and <code>m</code> is the number of TEs. Rather than test each gene against each TE as in the OP, this approach leverages the ordered nature of the genes and TEs, and the specified rules of matching, to look at each gene and TE only ... | 3 | 2016-09-21T00:51:34Z | [
"python",
"for-loop"
] |
Double loop takes time | 39,605,839 | <p>I have a script which takes a lot of time and can't finish so far after 2 days...
I parsed 1 file into 2 dictionaries as the following:</p>
<pre><code>gfftree = {'chr1':[(gene_id, gstart, gend),...], 'chr2':[(gene_id, gstart, gend),...],...}
TElocation = {'chr1':[(TE_id, TEstart, TEend),...], 'chr2':[(TE_id, TEstar... | 6 | 2016-09-21T00:43:56Z | 39,606,699 | <p>Here is a solution using multi-threading, comparing code used for nested loop methods.</p>
<p>I created two csv's, one with 8k rows and one 800 rows of (int, float1,float2) random generated numbers and import as below:</p>
<pre><code>import time
import itertools
start = time.time()
def f((TE_id, TEstart, TEend)... | 1 | 2016-09-21T02:43:43Z | [
"python",
"for-loop"
] |
Double loop takes time | 39,605,839 | <p>I have a script which takes a lot of time and can't finish so far after 2 days...
I parsed 1 file into 2 dictionaries as the following:</p>
<pre><code>gfftree = {'chr1':[(gene_id, gstart, gend),...], 'chr2':[(gene_id, gstart, gend),...],...}
TElocation = {'chr1':[(TE_id, TEstart, TEend),...], 'chr2':[(TE_id, TEstar... | 6 | 2016-09-21T00:43:56Z | 39,622,265 | <p>If the aim of the process is purely to find the gene IDs falling inside a specific start range and <em>you're not too worried about how you achieve this but are simply looking for the fastest solution</em>, then you may want to consider dropping the concept of a loop altogether and looking at a pre-existing solution... | 1 | 2016-09-21T16:49:20Z | [
"python",
"for-loop"
] |
How to check two POS tags are in the same category in NLTK? | 39,605,864 | <p>Like the title says, how can I check two POS tags are in the same category?</p>
<p>For example,</p>
<pre><code>go -> VB
goes -> VBZ
</code></pre>
<p>These two words are both verbs. Or,</p>
<pre><code>bag -> NN
bags -> NNS
</code></pre>
<p>These two are both nouns.
So my question is that whether ther... | 1 | 2016-09-21T00:46:26Z | 39,606,287 | <p>Not sure if this is what you are looking for, but you can tag with a <a href="http://www.nltk.org/book/ch05.html#reading-tagged-corpora" rel="nofollow"><code>universal</code> tagset</a>:</p>
<pre><code>from pprint import pprint
from collections import defaultdict
from nltk import pos_tag
from nltk.tokenize import ... | 0 | 2016-09-21T01:48:57Z | [
"python",
"nltk",
"pos-tagging"
] |
How to check two POS tags are in the same category in NLTK? | 39,605,864 | <p>Like the title says, how can I check two POS tags are in the same category?</p>
<p>For example,</p>
<pre><code>go -> VB
goes -> VBZ
</code></pre>
<p>These two words are both verbs. Or,</p>
<pre><code>bag -> NN
bags -> NNS
</code></pre>
<p>These two are both nouns.
So my question is that whether ther... | 1 | 2016-09-21T00:46:26Z | 39,613,600 | <p>Let's take the simple case first: Your corpus is tagged with the Brown tagset (that's what it looks like), and you'd be happy with the simple tags defined in the nltk's <a href="http://www.nltk.org/book/ch05.html#tab-universal-tagset" rel="nofollow">"universal" tagset</a>: <code>., ADJ, ADP, ADV, CONJ, DET, NOUN, NU... | 1 | 2016-09-21T10:12:08Z | [
"python",
"nltk",
"pos-tagging"
] |
small program stops - why? | 39,605,896 | <p>Whats wrong with my code?
After the second "input" the program stops...</p>
<pre><code>convr = 0
x = input("Inform value: ")
y = input("Inform if is Dolar (D) or Euro (E): ")
convt = x * convr
if y == "D":
convr = 1/0.895
print (convt)
elif y == "E":
convr = 0.895
print (convt)
else:
print (... | -1 | 2016-09-21T00:51:06Z | 39,605,968 | <p>The program doesn's stop. Just your value is empty.
You can see what I mean by changing your print() statements to:</p>
<pre><code>print ('RESULT: ' + convt)
</code></pre>
<p>Now, instead of a blank line, you will get "Result: " printed to the screen.</p>
<p>The reason you don't get a value is because of this lin... | 0 | 2016-09-21T01:01:16Z | [
"python",
"python-3.x",
"input"
] |
small program stops - why? | 39,605,896 | <p>Whats wrong with my code?
After the second "input" the program stops...</p>
<pre><code>convr = 0
x = input("Inform value: ")
y = input("Inform if is Dolar (D) or Euro (E): ")
convt = x * convr
if y == "D":
convr = 1/0.895
print (convt)
elif y == "E":
convr = 0.895
print (convt)
else:
print (... | -1 | 2016-09-21T00:51:06Z | 39,605,998 | <p>Because your <code>x</code> variable is a string, you need to transform it to number, eg. <code>float</code> or <code>int</code>.</p>
<pre><code>x = float(input("Inform value: "))
y = input("Inform if is Dolar (D) or Euro (E): ")
if y == "D":
convr = 1/0.895
convt = x * convr
print (convt)
elif y == "E... | 3 | 2016-09-21T01:04:53Z | [
"python",
"python-3.x",
"input"
] |
How do I create a randomised quiz using a dictionary? | 39,605,919 | <p>I have been attempting to make a randomised quiz but can't make the dictionary work, please help! This is my code so far. </p>
<pre><code>Import random
questions_answers = {"Which is the comparison operator for Not Equal to? Enter the number of the correct answer, 1. = 2. == 3. != ":"3",
"How many paths through a ... | -5 | 2016-09-21T00:53:42Z | 39,606,594 | <p>Ok, I decided to do this because my python is a little rusty and I thought the question was interesting.</p>
<pre><code>import sys
import random
def ask_questions():
score = 0
print ("You may quit this game at any time by pressing the letter Q")
while True:
rand_q = random.choice(questions_answ... | -1 | 2016-09-21T02:30:53Z | [
"python",
"dictionary"
] |
lambda function of another function but force fixed argument | 39,605,985 | <p>I just switched to Python from Matlab, and I want to use lambda function to map function <code>f1(x,y)</code> with multiple arguments to one argument function <code>f2(x)</code> for optimization.
I want that when I map the function <code>f2(x) <- f1(x,y=y1)</code> then <code>y</code> will stay constant no matter... | 0 | 2016-09-21T01:03:11Z | 39,606,008 | <p>Try:</p>
<pre><code>f2 = lambda x, y=y1: f1(x,y)
</code></pre>
<p>Your issue has to do with <a href="http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures" rel="nofollow">how closures work in Python</a></p>
<p>Your version of the lambda function will use the current version of <code>y1</co... | 2 | 2016-09-21T01:06:02Z | [
"python",
"function",
"lambda"
] |
lambda function of another function but force fixed argument | 39,605,985 | <p>I just switched to Python from Matlab, and I want to use lambda function to map function <code>f1(x,y)</code> with multiple arguments to one argument function <code>f2(x)</code> for optimization.
I want that when I map the function <code>f2(x) <- f1(x,y=y1)</code> then <code>y</code> will stay constant no matter... | 0 | 2016-09-21T01:03:11Z | 39,606,040 | <p>As already pointed out, your issue comes down to how closures work. However, you really shouldn't be using a lambda for this - lambdas are for anonymous functions. Make a higher-order function with <code>def</code> statements instead:</p>
<pre><code>>>> def f1(x,y):
... return x + y
...
>>> def... | 1 | 2016-09-21T01:10:56Z | [
"python",
"function",
"lambda"
] |
tkinter using two keys at the same time | 39,606,019 | <p>So tkinker can only use one key at a time.
I am unable to say move to the left and up at the same time with this example.
How would i go about doing it if I wanted to?</p>
<pre><code>import tkinter
root = tkinter.Tk()
root.title('test')
c= tkinter.Canvas(root, height=300, width=400)
c.pack()
body = c.create_oval(1... | 0 | 2016-09-21T01:08:31Z | 39,609,454 | <p>Like this :</p>
<pre><code>from Tkinter import *
root = Tk()
var = StringVar()
a_label = Label(root,textvariable = var ).pack()
history = []
def keyup(e):
print e.keycode
if e.keycode in history :
history.pop(history.index(e.keycode))
var.set(str(history))
def keydown(e):
if not e.k... | 1 | 2016-09-21T06:57:15Z | [
"python",
"tkinter",
"keypress"
] |
Selecting a random tuple from a dictionary | 39,606,049 | <p>Say I have this:</p>
<pre><code>d={'a':[(1,2),(3,4)],'b':[(9,2),(5,4)],'c':[(2,2),(7,7)]}
</code></pre>
<p>where d is a dictionary in python. I'd like to get random tuples out of this corresponding to a particular key using the <code>random.choice()</code> method.</p>
<p>This is what I'm doing and it's not workin... | 0 | 2016-09-21T01:12:48Z | 39,606,086 | <p><code>d['a']</code> is already a list, so you don't need to call <code>.values()</code> on it.</p>
<pre><code>import random
d = {
'a': [(1, 2), (3, 4)],
'b': [(9, 2), (5, 4)],
'c': [(2, 2), (7, 7)],
}
print(random.choice(d['a']))
</code></pre>
| 2 | 2016-09-21T01:19:45Z | [
"python",
"dictionary",
"tuples"
] |
Selecting a random tuple from a dictionary | 39,606,049 | <p>Say I have this:</p>
<pre><code>d={'a':[(1,2),(3,4)],'b':[(9,2),(5,4)],'c':[(2,2),(7,7)]}
</code></pre>
<p>where d is a dictionary in python. I'd like to get random tuples out of this corresponding to a particular key using the <code>random.choice()</code> method.</p>
<p>This is what I'm doing and it's not workin... | 0 | 2016-09-21T01:12:48Z | 39,606,103 | <p>If you're just trying to get a random tuple out of key you pick, you've written too much:</p>
<pre><code>random.choice(d['a'])
</code></pre>
<p>(Also NB: You'll need quotes around the keys in the dictionary. Right now you're using, e.g., the undefined variable <code>a</code> instead of the string <code>'a'</code>.... | 0 | 2016-09-21T01:21:43Z | [
"python",
"dictionary",
"tuples"
] |
why does my program return None in for loop? | 39,606,059 | <p>I have a function that should print the squares in the given interval:</p>
<pre><code>class Squares:
def __init__(self, min, max):
self.min = min
self.max = max
def __iter__(self):
return self
def __next__(self):
a_list = []
for i in range((self.max)+1):
... | 0 | 2016-09-21T01:15:20Z | 39,606,214 | <p>The reason that <em>None</em> is returned every time the variable result is not a perfect square, is that the next() function returns <em>None</em> by default if no return is specified.</p>
<p>If you <em>must</em> use an iterator for this project, you have to structure your code so that a value is returned each pas... | 0 | 2016-09-21T01:37:05Z | [
"python",
"class",
"iterator",
"next"
] |
How to check for alphanumeric characters in a binary file | 39,606,112 | <p>I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet):</p>
<pre><code>chars_to... | -3 | 2016-09-21T01:22:20Z | 39,606,172 | <p>Assuming you are reading from an arbitrary binary for which it might not be possible to decode it to ASCII/UTF-8, you could try something like the following</p>
<pre><code>import string
# create a set of the ascii code points for alphanumerics
alphanumeric_codes = {ord(c) for c in string.ascii_letters + string.digi... | 0 | 2016-09-21T01:31:06Z | [
"python"
] |
How to check for alphanumeric characters in a binary file | 39,606,112 | <p>I'm a beginner trying to write a program that will read in .exe files, .class files, or .pyc files and get the percentage of alphanumeric characters (a-z,A-Z,0-9). Here's what I have right now (I'm just trying to see if I can identify anything at the moment, not looking to count stuff yet):</p>
<pre><code>chars_to... | -3 | 2016-09-21T01:22:20Z | 39,606,216 | <p>On Windows, you could use a simple PowerShell script to get the hexdump (take a look here <a href="http://windowsitpro.com/powershell/get-hex-dumps-files-powershell" rel="nofollow">http://windowsitpro.com/powershell/get-hex-dumps-files-powershell</a>) and then, decode it to whatever standard you want (ascii, unicode... | 0 | 2016-09-21T01:37:41Z | [
"python"
] |
Filter Multi-Dimensional Array | 39,606,158 | <p>I have an array (lists) which is NxK. However, I want to "filter" is after inputting some constraints based on values in Columns 4 and 6. This is the code I have so far.</p>
<pre><code>minmag = 5
maxmag = 7
mindist = 25
maxdist = 64
filter = np.zeros((1, 7), dtype='object')
add = np.zeros((1, 7), dtype='object')
... | 0 | 2016-09-21T01:29:04Z | 39,606,247 | <p>Simplifying the most repetitive parts:</p>
<pre><code>if k==0:
for x in xrange(1,8):
lists[i,x] = filter[0,x]
k = 1
else:
for x in xrange(1,8):
lists[i,x] = add[0,x]
filter = np.append(filter, add, axis=0)
</code></pre>
<p>You could also combine your nested <code>if</code>s into a s... | 0 | 2016-09-21T01:42:44Z | [
"python",
"arrays",
"filter"
] |
Python class: Employee management system | 39,606,186 | <p>This exercise assumes that you have created the Employee class for Programming Exercise 4.
Create a program that stores Employee objects in a dictionary. Use the employee ID number
as the key. The program should present a menu that lets the user perform the following actions:
⢠Look up an employee in the dictionar... | 0 | 2016-09-21T01:33:38Z | 39,606,307 | <p>What you're trying to do is to instantiate an <code>Employee</code> object with the given parameters. To do this, you just call the class name as if it were a function and pass in those parameters. In your case, the class name is <code>Employee</code> within the <code>Employee</code> module, so you would do this:<... | 1 | 2016-09-21T01:52:00Z | [
"python",
"class",
"object",
"pickle"
] |
Sending a invite into google calendar | 39,606,198 | <p>I want to develop a app or a simple script which will parse through lines and create a even out of it and add a invite in google calendar? Is there some api which can speak with google calendar to add events in calendar. I will prefer to write the code in python?</p>
| -1 | 2016-09-21T01:35:16Z | 39,606,281 | <p>You can use the Google Calendar API:</p>
<p><a href="https://developers.google.com/google-apps/calendar/quickstart/python" rel="nofollow">https://developers.google.com/google-apps/calendar/quickstart/python</a></p>
<p><a href="https://developers.google.com/google-apps/calendar/create-events" rel="nofollow">https:/... | 0 | 2016-09-21T01:48:14Z | [
"python",
"automation",
"google-calendar"
] |
How to use blist module without installing it? | 39,606,225 | <p>Without installing <code>blist</code>, I am trying to use blist_1.3.6 module by setting the environment variable <code>PYTHONPATH</code>. However I am still getting the error below. Is there any way to use this <code>_blist</code> without installing it? I can see <code>_blist.c</code> is C language file.</p>
<pre c... | 0 | 2016-09-21T01:39:22Z | 39,606,276 | <p><code>_blist</code> is the module implemented by the object that results from compiling <code>_blist.c</code> and creating a shared library from it. You can't simply import <code>_blist.c</code> directly.</p>
| 1 | 2016-09-21T01:48:01Z | [
"python"
] |
PyCharm not respond to my change in JavaScript file | 39,606,308 | <p>I am developing a simple web application integrated with MySQL database. I am using PyCharm to write Python, HTML, JavaScript, CSS. After I make change to my JavaScript and I run my application on Chrome, the Chrome console suggests that the change did not apply. I already invalid PyCharm caches and restart Pycharm,... | 0 | 2016-09-21T01:52:22Z | 39,629,226 | <p>Open the Chrome Developer tool setting, and disable the cache.</p>
<p>credit to @All is Vanity</p>
| 0 | 2016-09-22T02:18:45Z | [
"javascript",
"python",
"pycharm"
] |
What is the python equivalent of c++ const-reference copy-constructor arguments | 39,606,315 | <p>One of the great things of C++ is the usage of <code>const</code>-reference arguments â using these type of argument, you're pretty much guaranteed objects wonât be accidentally modified, and there wonât be side effects.</p>
<p>Question is, whatâd be the Python equivalent to such arguments?</p>
<p>For inst... | 1 | 2016-09-21T01:53:19Z | 39,606,527 | <p>There is no direct equivalent. The closest is to use the <a href="https://docs.python.org/2/library/copy.html" rel="nofollow"><code>copy</code> module</a> and define the <code>__copy__()</code> and/or <code>__deepcopy__()</code> methods on your classes.</p>
| 1 | 2016-09-21T02:22:39Z | [
"python",
"c++",
"language-lawyer",
"copy-constructor",
"const-correctness"
] |
What is the python equivalent of c++ const-reference copy-constructor arguments | 39,606,315 | <p>One of the great things of C++ is the usage of <code>const</code>-reference arguments â using these type of argument, you're pretty much guaranteed objects wonât be accidentally modified, and there wonât be side effects.</p>
<p>Question is, whatâd be the Python equivalent to such arguments?</p>
<p>For inst... | 1 | 2016-09-21T01:53:19Z | 39,606,678 | <p>I hope I understood correctly.</p>
<p>Shortly, there is not one. There are two things you are after which you do not come by in python often. <code>const</code>s and copy constructors.</p>
<p>It's a design decision, python is a different language. Arguments are always passed by reference.</p>
<h3><code>const</cod... | 2 | 2016-09-21T02:41:06Z | [
"python",
"c++",
"language-lawyer",
"copy-constructor",
"const-correctness"
] |
What is the python equivalent of c++ const-reference copy-constructor arguments | 39,606,315 | <p>One of the great things of C++ is the usage of <code>const</code>-reference arguments â using these type of argument, you're pretty much guaranteed objects wonât be accidentally modified, and there wonât be side effects.</p>
<p>Question is, whatâd be the Python equivalent to such arguments?</p>
<p>For inst... | 1 | 2016-09-21T01:53:19Z | 39,606,883 | <p>Write a decorator on the function. Have it serialize the data on the way in, serialize it on the way out, and confirm the two are equal. If they are not, generate an error.</p>
<p>Python type checking is mostly runtime checks that arguments satisfy some predicate. <code>const</code> in C++ is a type check on the... | 0 | 2016-09-21T03:06:05Z | [
"python",
"c++",
"language-lawyer",
"copy-constructor",
"const-correctness"
] |
What is the python equivalent of c++ const-reference copy-constructor arguments | 39,606,315 | <p>One of the great things of C++ is the usage of <code>const</code>-reference arguments â using these type of argument, you're pretty much guaranteed objects wonât be accidentally modified, and there wonât be side effects.</p>
<p>Question is, whatâd be the Python equivalent to such arguments?</p>
<p>For inst... | 1 | 2016-09-21T01:53:19Z | 39,678,223 | <p>What kind of object is <code>position</code>? There is very likely a way to copy it, so that <code>self</code> has a private copy of the position. For instance, if <code>position</code> is a <code>Point2D</code>, then either <code>self.position = Point2D(position)</code> or <code>self.position = Point2D( position.x,... | 0 | 2016-09-24T15:53:15Z | [
"python",
"c++",
"language-lawyer",
"copy-constructor",
"const-correctness"
] |
How can I download just thumbnails using youtube-dl? | 39,606,419 | <p>I've been trying to download the thumbnails of a list of URL's (youtube videos) I have.</p>
<p>I've been using youtube-dl and I've worked it out to this so far:</p>
<pre><code> import os
with open('results.txt') as f:
for line in f:
os.system("youtube-dl " + "--write-thumbnail " +... | 0 | 2016-09-21T02:07:30Z | 39,607,541 | <p>It looks like passing --list-thumbnails will return the url to the thumbnail images, but it will just output to the screen when calling os.system().</p>
<p>The following isn't the prettiest, but it's a quick working example of getting the output of youtube-dl into a string using subprocess, parsing it to get the ur... | 0 | 2016-09-21T04:25:51Z | [
"python",
"youtube",
"youtube-dl"
] |
boto3 'str' object has no attribute 'get | 39,606,503 | <p>I am following the example at <a href="https://devcenter.heroku.com/articles/s3-upload-python" rel="nofollow">https://devcenter.heroku.com/articles/s3-upload-python</a> for uploading files directly to s3 from the client and am coming up with errors</p>
<p>views.api.sign_s3:</p>
<pre><code>def sign_s3(request):
... | 0 | 2016-09-21T02:18:47Z | 39,609,721 | <p>I think the way you are returning the response to your view is causing the trouble.</p>
<p>Try something like this - </p>
<pre><code>import json
from django.http import HttpResponse, JsonResponse
def sign_s3(request):
#Your View Code Here...
#Finally The Response (Using JsonResponse)...
json_object = {
... | 0 | 2016-09-21T07:11:48Z | [
"python",
"django",
"heroku",
"amazon-s3",
"boto3"
] |
Using a generator to iterate over a large collection in Mongo | 39,606,506 | <p>I have a collection with 500K+ documents which is stored on a single node mongo. Every now and then my pymongo cursor.find() fails as it times out.</p>
<p>While I could set the <code>find</code> to ignore timeout, I do not like that approach. Instead, I tried a generator (adapted from <a href="http://stackoverflow.... | 2 | 2016-09-21T02:19:13Z | 39,606,547 | <p>Why not use </p>
<pre><code>for result in results:
yield result
</code></pre>
<p>The for loop should handle <code>StopIteration</code> for you.</p>
| 0 | 2016-09-21T02:25:38Z | [
"python",
"mongodb",
"pymongo",
"pymongo-3.x"
] |
Using a generator to iterate over a large collection in Mongo | 39,606,506 | <p>I have a collection with 500K+ documents which is stored on a single node mongo. Every now and then my pymongo cursor.find() fails as it times out.</p>
<p>While I could set the <code>find</code> to ignore timeout, I do not like that approach. Instead, I tried a generator (adapted from <a href="http://stackoverflow.... | 2 | 2016-09-21T02:19:13Z | 39,610,669 | <p>The <code>.find()</code> method takes additional keyword arguments. One of them is <code>no_cursor_timeout</code> which you need to set to <code>True</code></p>
<pre><code>cursor = collection.find({}, no_cursor_timeout=True)
</code></pre>
<p>You don't need to write your own generator function. The <code>find()</co... | 0 | 2016-09-21T07:58:19Z | [
"python",
"mongodb",
"pymongo",
"pymongo-3.x"
] |
sqlalchemy / pandas - How do I create an sqlalchemy `selectable` to pass to pd.read_sql? | 39,606,534 | <p>I'm completely new to sqlalchemy, and I've been trying to better understand how <code>pd.read_sql</code> can be used.</p>
<p>I've succesfully run the following:</p>
<pre><code>import sqlalchemy as sa
import pandas as pd
df = pd.DataFrame( index=range(10,30), data=np.random.rand(20, 10) )
eng = sa.create_engine('sq... | 1 | 2016-09-21T02:23:49Z | 39,614,914 | <p>Getting the table in 3 different ways. (Not sure what the differences are).</p>
<p>then using the <code>.select()</code> method on that table and the <code>.where</code> on that result gets what I want.</p>
<pre><code>import sqlalchemy as sa
eng = sa.create_engine('sqlite:///test.db')
# First way to load table
m =... | 0 | 2016-09-21T11:10:39Z | [
"python",
"pandas",
"sqlalchemy"
] |
PySpark DataFrame - Join on multiple columns dynamically | 39,606,589 | <p>let's say I have two DataFrames on Spark</p>
<pre><code>firstdf = sqlContext.createDataFrame([{'firstdf-id':1,'firstdf-column1':2,'firstdf-column2':3,'firstdf-column3':4}, \
{'firstdf-id':2,'firstdf-column1':3,'firstdf-column2':4,'firstdf-column3':5}])
seconddf = sqlContext.createDataFrame([{'seconddf-id':1,'secon... | 1 | 2016-09-21T02:29:55Z | 39,615,339 | <p>Why not use a simple comprehension:</p>
<pre><code>firstdf.join(
seconddf,
[col(f) == col(s) for (f, s) in zip(columnsFirstDf, columnsSecondDf)],
"inner"
)
</code></pre>
<p>Since you use logical it is enough to provide a list of conditions without <code>&</code> operator.</p>
| 1 | 2016-09-21T11:28:54Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql",
"spark-dataframe"
] |
Python: Append a list to another list and Clear the first list | 39,606,601 | <p>So this just blew my mind. I am working on a python code where I create a list, append it to a master list and clear the first list to add some more elements to it. When I clear the first list, even the master list gets cleared. I worked on a lot of list appends and clears but never observed this.</p>
<pre><code>li... | 1 | 2016-09-21T02:31:36Z | 39,606,650 | <p>Passing a <code>list</code> to a method like <code>append</code> is just passing a <em>reference</em> to the same <code>list</code> referred to by <code>list1</code>, so that's what gets appended to <code>list2</code>. They're still the same <code>list</code>, just referenced from two different places.</p>
<p>If yo... | 4 | 2016-09-21T02:36:47Z | [
"python",
"list"
] |
Python: Append a list to another list and Clear the first list | 39,606,601 | <p>So this just blew my mind. I am working on a python code where I create a list, append it to a master list and clear the first list to add some more elements to it. When I clear the first list, even the master list gets cleared. I worked on a lot of list appends and clears but never observed this.</p>
<pre><code>li... | 1 | 2016-09-21T02:31:36Z | 39,606,851 | <p>So basically here is what the code is doing:</p>
<h3>Before delete</h3>
<p><a href="http://i.stack.imgur.com/T41Sv.png" rel="nofollow"><img src="http://i.stack.imgur.com/T41Sv.png" alt="enter image description here"></a></p>
<h3>After deleting</h3>
<p><a href="http://i.stack.imgur.com/uuiDI.png" rel="nofollow"><... | 2 | 2016-09-21T03:02:26Z | [
"python",
"list"
] |
More succinct initialization for SQLAlchemy instance | 39,606,690 | <p>It's my first attempt at sqlalchemy. I have a json file with my usr information and I would like to put them in a sqlite3 database file. It works but I find the instance initialization verbose since there are many columns in the table, as you can see below.</p>
<p>Is it possible to use a dictionary as input to init... | 1 | 2016-09-21T02:42:44Z | 39,606,812 | <p>If you know the property names in the JSON object match the column names of the Python model, you can just change:</p>
<pre><code>a = User(id=usr['id'], bbs_id=usr['bbs_id'], name=usr['name'])
</code></pre>
<p>to:</p>
<pre><code>a = User(**usr)
</code></pre>
<p><a href="https://docs.python.org/3/tutorial/control... | 2 | 2016-09-21T02:57:57Z | [
"python",
"sqlalchemy"
] |
How to convert video to spatio-temporal volumes in python | 39,606,892 | <p>I am doing my project in video analytics. I have to densely sample video. Sampling means converting video to spatio-temporal video volumes. I am using the python language. How can I do that in python? Is that option available in opencv or any other package? Input video sequence and desired output is shown <img src="... | 0 | 2016-09-21T03:07:30Z | 39,607,997 | <p>Read the video file using</p>
<pre><code>cap = cv2.VideoCapture(fileName)
</code></pre>
<p>Go over each frame:</p>
<pre><code>while(cap.isOpened()):
# Read frame
ret, frame = cap.read()
</code></pre>
<p>If you want you can just insert every frame to a 3D matrix to get the spatio-temporal matrix that you... | 1 | 2016-09-21T05:09:37Z | [
"python",
"opencv",
"video",
"image-processing",
"video-processing"
] |
Exception in making a REST call | 39,606,976 | <p>I am currently working on a REST call using Flask Framework. and I have run into some errors along the way, which I am unable to figure out as to why they occur (still trying though). The error is as shown below:</p>
<pre><code>[2016-09-20 18:53:26,486] ERROR in app: Exception on /Recommend [GET]
Traceback (most re... | -1 | 2016-09-21T03:18:52Z | 39,608,108 | <p>There are a number of errors in your <code>Apriori</code> which need to fixed. There are a few attempts to divide by <code>self.no_of_transactions</code> (e.g. line 87) which is initialised to <code>None</code> and never changed. Dividing by <code>None</code> raises an exception:</p>
<pre><code>>>> 1/None
... | 0 | 2016-09-21T05:19:54Z | [
"python",
"flask"
] |
Embed multiple matplotlib figures in wxPython | 39,607,157 | <p>I have a 2x2 <code>FlexGridSizer</code> in a panel and I want to insert four different matplotlib figures with their own toolbars at the same time.</p>
<p>I have seen many links related and working examples embedding one figure, but as I am a begginer with wxPython and OOP I get quite confuse when testing some code... | 0 | 2016-09-21T03:41:25Z | 39,613,369 | <p>You just have to follow the examples where they embed one Figure, but instead instantiate several members for each of the figures you want to create.
Here is a quick example:</p>
<pre><code>import matplotlib
matplotlib.use('WXAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import F... | 1 | 2016-09-21T10:01:24Z | [
"python",
"matplotlib",
"wxpython"
] |
Python subprocess.Popen poll seems to hang but communicate works | 39,607,172 | <pre><code>child = subprocess.Popen(command,
shell=True,
env=environment,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=sys.stdin,
... | 0 | 2016-09-21T03:42:50Z | 39,607,358 | <p>You've set the <code>Popen</code> object to receive the subprocess's <code>stdout</code> via pipe. Problem is, you're not reading from that pipe until the process exits. If the process produces enough output to fill the OS level pipe buffers, and you don't drain the pipe, then you're deadlocked; the subprocess wants... | 1 | 2016-09-21T04:03:49Z | [
"python",
"subprocess",
"popen"
] |
Conditional Help in Python | 39,607,266 | <p>I needed some help in understanding the following code:</p>
<pre><code>nextState = ((nextx, nexty), self.corners) if self.currentPosition not in self.corners else ((nextx, nexty), tuple([i for i in self.corners if i != self.currentPosition]))
successors.append((nextState, action, 1))
</code></pre>
<p>Can someone s... | 0 | 2016-09-21T03:54:23Z | 39,607,396 | <p>As an <code>if</code> statement, this would be:</p>
<pre><code>if self.currentPosition not in self.corners:
nextState = ((nextx, nexty), self.corners)
else:
nextState = ((nextx, nexty), tuple([i for i in self.corners if i != self.currentPosition]))
successors.append((nextState, action, 1))
</code></pre>
<p... | 0 | 2016-09-21T04:07:22Z | [
"python"
] |
Stuck in a django migration IntegrityError loop: can I delete those migrations that aren't yet in the db? | 39,607,359 | <p>So, I committed and pushed all my code, and then deployed my web application successfully. Then, I added a new model to my 'home' app, which (for a reason I now understand, but doesn't matter here), created an <code>IntegrityError</code> (<code>django.db.utils.IntegrityError: insert or update on table "foo" violates... | 0 | 2016-09-21T04:03:49Z | 39,607,668 | <p>OK, so I crossed my fingers, backed my local 0021-0028 migration files, and then deleted them. <strong>It worked</strong>. I think they key is that the migration files were not yet in the database yet, but not 100% sure. +1 if anyone can answer further for clarification.</p>
| 0 | 2016-09-21T04:39:03Z | [
"python",
"django"
] |
Stuck in a django migration IntegrityError loop: can I delete those migrations that aren't yet in the db? | 39,607,359 | <p>So, I committed and pushed all my code, and then deployed my web application successfully. Then, I added a new model to my 'home' app, which (for a reason I now understand, but doesn't matter here), created an <code>IntegrityError</code> (<code>django.db.utils.IntegrityError: insert or update on table "foo" violates... | 0 | 2016-09-21T04:03:49Z | 39,608,279 | <p>If you haven't applied your migrations to db, it is safe to delete them and recreate them. </p>
<p>Possible reasons of why you run into this error are:</p>
<ol>
<li>You deleted your model code but, when you run <code>migrate</code> it reads your migration files (which has information about your deleted model) and ... | 1 | 2016-09-21T05:36:02Z | [
"python",
"django"
] |
Python method to request attribute component that formed by list | 39,607,437 | <p>I need to access an item from an attribute that formed in list. This is my code:</p>
<pre><code>class Foo:
def __init__(self):
self.__words = []
@property
def word(self, index):
return self.__words[index]
@word.setter
def word(self, word):
self.__words.append(str(word)... | 0 | 2016-09-21T04:12:34Z | 39,607,556 | <p>I believe you cannot add arbitrary arguments to a method decorated by <code>@property</code>. So, if you really want to do this, you can return a method that takes an index instead of trying to get the value itself:</p>
<pre><code>class Foo:
def __init__(self):
self.__words = []
@property
def w... | 0 | 2016-09-21T04:27:27Z | [
"python",
"list",
"python-3.x"
] |
What is wrong with my code to remove duplicates from Linked List? | 39,607,536 | <p>New to Python and my code is passing all test cases other than input 1-->0, which it returns nothing instead of 1->0. does this have something to do with the value of None?</p>
<pre><code>def RemoveDuplicates(head):
if head == None or head.next == None:
return
else:
temp = head
whil... | 0 | 2016-09-21T04:24:57Z | 39,607,595 | <p>Try <code>is None</code> instead of <code>== None</code>. Comparisons to singletons should be done using <code>is</code> or <code>is not</code>.</p>
| 0 | 2016-09-21T04:32:01Z | [
"python"
] |
What is wrong with my code to remove duplicates from Linked List? | 39,607,536 | <p>New to Python and my code is passing all test cases other than input 1-->0, which it returns nothing instead of 1->0. does this have something to do with the value of None?</p>
<pre><code>def RemoveDuplicates(head):
if head == None or head.next == None:
return
else:
temp = head
whil... | 0 | 2016-09-21T04:24:57Z | 39,608,112 | <p>We can't see the class of head and what operations it has defined, is the <code>__eq__</code> magic function defined on that class?</p>
<p>Is it possible that <code>head.next == None</code> evaluates to <code>head.next.data == None</code> for the class? In which case <code>0 == None</code> evaluates to True.</p>
... | 0 | 2016-09-21T05:20:26Z | [
"python"
] |
Count the number of Occurrence of Values based on another column | 39,607,540 | <p>I have a question regarding creating pandas dataframe according to the sum of other column.</p>
<p>For example, I have this dataframe</p>
<pre><code> Country | Accident
England Car
England Car
England Car
USA Car
USA Bike
USA Plane... | 3 | 2016-09-21T04:25:44Z | 39,607,916 | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow"><code>groupby</code></a> method.</p>
<p>Example - </p>
<pre><code>In [36]: df.groupby(["country"]).count().sort_values(["accident"], ascending=False).rename(columns={"accident" : "Sum of accidents"}).reset_index()
Out... | 3 | 2016-09-21T05:02:10Z | [
"python",
"pandas"
] |
Count the number of Occurrence of Values based on another column | 39,607,540 | <p>I have a question regarding creating pandas dataframe according to the sum of other column.</p>
<p>For example, I have this dataframe</p>
<pre><code> Country | Accident
England Car
England Car
England Car
USA Car
USA Bike
USA Plane... | 3 | 2016-09-21T04:25:44Z | 39,608,197 | <p><strong><em>Option 1</em></strong><br>
Use <code>value_counts</code></p>
<pre><code>df.Country.value_counts().reset_index(name='Sum of Accidents')
</code></pre>
<p><a href="http://i.stack.imgur.com/G0Gii.png"><img src="http://i.stack.imgur.com/G0Gii.png" alt="enter image description here"></a></p>
<p><strong><em>... | 5 | 2016-09-21T05:28:59Z | [
"python",
"pandas"
] |
Reset tensorflow Optimizer | 39,607,566 | <p>I am loading from a saved model and I would like to be able to reset a tensorflow optimizer such as an Adam Optimizer. Ideally something like:</p>
<pre><code>sess.run([tf.initialize_variables(Adamopt)])
</code></pre>
<p>or</p>
<pre><code>sess.run([Adamopt.reset])
</code></pre>
<p>I have tried looking for an answ... | 0 | 2016-09-21T04:28:22Z | 39,680,248 | <p>The simplest way I found was to give the optimizer its own variable scope and then run </p>
<pre><code>optimizer_scope = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,
"scope/prefix/for/optimizer")
sess.run(tf.initialize_variables(optimizer_scope))
</code></pre>
<p>idea from <... | 0 | 2016-09-24T19:38:36Z | [
"python",
"optimization",
"tensorflow"
] |
Number of shortest paths of a knight in chessboard from A to B | 39,607,721 | <p>Here is the problem:</p>
<p>Given the input n = 4 x = 5, we must imagine a chessboard that is 4 squares across (x-axis) and 5 squares tall (y-axis). (This input changes, all the up to n = 200 x = 200)</p>
<p>Then, we are asked to determine the minimum shortest path from the bottom left square on the board to the t... | 0 | 2016-09-21T04:42:57Z | 39,607,825 | <p>Try something. Draw boards of the following sizes: 1x1, 2x2, 3x3, 4x4, and a few odd ones like 2x4 and 3x4. Starting with the smallest board and working to the largest, start at the bottom left corner and write a 0, then find all moves from zero and write a 1, find all moves from 1 and write a 2, etc. Do this until ... | 0 | 2016-09-21T04:54:39Z | [
"python",
"algorithm",
"chess"
] |
Number of shortest paths of a knight in chessboard from A to B | 39,607,721 | <p>Here is the problem:</p>
<p>Given the input n = 4 x = 5, we must imagine a chessboard that is 4 squares across (x-axis) and 5 squares tall (y-axis). (This input changes, all the up to n = 200 x = 200)</p>
<p>Then, we are asked to determine the minimum shortest path from the bottom left square on the board to the t... | 0 | 2016-09-21T04:42:57Z | 39,608,395 | <p>My approach to this question would be backtracking as the number of squares in the x-axis and y-axis are different. </p>
<p><strong>Note: Backtracking algorithms can be slow for certain cases and fast for the other</strong> </p>
<p>Create a 2-d Array for the chess-board. You know the staring index and the final in... | 0 | 2016-09-21T05:45:38Z | [
"python",
"algorithm",
"chess"
] |
Number of shortest paths of a knight in chessboard from A to B | 39,607,721 | <p>Here is the problem:</p>
<p>Given the input n = 4 x = 5, we must imagine a chessboard that is 4 squares across (x-axis) and 5 squares tall (y-axis). (This input changes, all the up to n = 200 x = 200)</p>
<p>Then, we are asked to determine the minimum shortest path from the bottom left square on the board to the t... | 0 | 2016-09-21T04:42:57Z | 39,612,988 | <p>BFS is efficient enough for this problem as it's complexity is O(n*x) since you explore each cell only one time. For keeping the number of shortest paths, you just have to keep an auxiliary array to save them.</p>
<p>You can also use A* to solve this faster but it's not necessary in this case because it is a progra... | 1 | 2016-09-21T09:45:23Z | [
"python",
"algorithm",
"chess"
] |
Number of shortest paths of a knight in chessboard from A to B | 39,607,721 | <p>Here is the problem:</p>
<p>Given the input n = 4 x = 5, we must imagine a chessboard that is 4 squares across (x-axis) and 5 squares tall (y-axis). (This input changes, all the up to n = 200 x = 200)</p>
<p>Then, we are asked to determine the minimum shortest path from the bottom left square on the board to the t... | 0 | 2016-09-21T04:42:57Z | 39,622,042 | <p>I suggest:</p>
<ol>
<li>Use BFS backwards from the target location to calculate (in just O(nx) total time) the minimum distance to the target (x, n) in knight's moves <em>from each other square</em>. For each starting square (i, j), store this distance in d[i][j].</li>
<li>Calculate c[i][j], the number of minimum-... | 1 | 2016-09-21T16:36:41Z | [
"python",
"algorithm",
"chess"
] |
how to find running script in raspberry pi 3 | 39,607,860 | <p>I have raspberry pi 3 and i m running python script at startup of raspberry pi using /etc/rc.local. I want to find which python script running in background so login using putty and i had run following command:</p>
<pre><code>ps aux|grep mail
</code></pre>
<p>so it displays two script running like following:</p>
... | 0 | 2016-09-21T04:57:44Z | 39,647,804 | <p>Use <code>ps -alx</code> and look at the PID and PPID fields, you find that the 'sudo python' process is the parent of the 'python' process. Sudo is an executable program that runs it's arguments as a sub-process.</p>
| 0 | 2016-09-22T19:53:57Z | [
"python",
"windows",
"putty",
"raspberry-pi3"
] |
Rediect to another page in blueprints | 39,607,902 | <p>Im looking for a way to redirect to another page while using flask blueprints</p>
<pre><code>from flask import Blueprint, request, render_template, redirect, url_for
import json
user = Blueprint("user",__name__,template_folder='templates')
@user.route("/index")
def index():
return render_template("index.html... | 0 | 2016-09-21T05:01:08Z | 39,608,106 | <p>Use <code>redirect</code> and <code>url_for</code>:</p>
<pre><code>return redirect(url_for('user.index'))
</code></pre>
| 2 | 2016-09-21T05:19:43Z | [
"python",
"flask",
"blueprint"
] |
Rediect to another page in blueprints | 39,607,902 | <p>Im looking for a way to redirect to another page while using flask blueprints</p>
<pre><code>from flask import Blueprint, request, render_template, redirect, url_for
import json
user = Blueprint("user",__name__,template_folder='templates')
@user.route("/index")
def index():
return render_template("index.html... | 0 | 2016-09-21T05:01:08Z | 39,614,262 | <p>Use the following working example and adjust it to fit your needs:</p>
<pre><code>from flask import Flask, Blueprint, render_template, redirect, url_for
user = Blueprint("user", __name__, template_folder='templates')
@user.route("/index")
def index():
return render_template("index.html")
@user.route('/save... | 0 | 2016-09-21T10:40:30Z | [
"python",
"flask",
"blueprint"
] |
Opencv webcam script endlessly turns webcams off and on | 39,608,123 | <p>I wrote a script to display a depth map from my webcams:</p>
<pre><code>cam_a = int(sys.argv[1])
cam_b = int(sys.argv[2])
while True:
imgl = cv2.VideoCapture(cam_a).read()[1]
imgL = cv2.cvtColor(imgl, cv2.COLOR_BGR2GRAY)
imgr = cv2.VideoCapture(cam_b).read()[1]
imgR = cv2.cvtColor(imgr, cv2.COLOR... | 0 | 2016-09-21T05:21:34Z | 39,608,521 | <p>All you need a add an delay after <code>imshow</code>:</p>
<pre><code>cv2.waitKey(10)
</code></pre>
| 0 | 2016-09-21T05:55:42Z | [
"python",
"opencv",
"video",
"webcam",
"depth"
] |
Opencv webcam script endlessly turns webcams off and on | 39,608,123 | <p>I wrote a script to display a depth map from my webcams:</p>
<pre><code>cam_a = int(sys.argv[1])
cam_b = int(sys.argv[2])
while True:
imgl = cv2.VideoCapture(cam_a).read()[1]
imgL = cv2.cvtColor(imgl, cv2.COLOR_BGR2GRAY)
imgr = cv2.VideoCapture(cam_b).read()[1]
imgR = cv2.cvtColor(imgr, cv2.COLOR... | 0 | 2016-09-21T05:21:34Z | 39,672,403 | <p>Got the problem. You are continuously initiating videocapture object under the while loop. You should use one instance initiated before while loop and access image using that instance of videocapture. See this example and change your code accordingly, hope it will fix your issues:</p>
<pre><code>import cv2
camera =... | 2 | 2016-09-24T04:10:49Z | [
"python",
"opencv",
"video",
"webcam",
"depth"
] |
match names in csv file to filename in folder | 39,608,212 | <p>I have got a list of about 7000 names in a csv file that is arranged by surname, name, date of birth etc. I also have a folder of about 7000+ scanned documents (enrolment forms) which have the name of each person as a filename. </p>
<p>Now the filenames may not exactly match the names in the csv ie. John Doe in th... | 0 | 2016-09-21T05:30:18Z | 39,609,154 | <p>The first thing you want to do is read the CSV into memory. You can do this with the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow"><code>csv</code> module</a>. The most useful tool there is <code>csv.DictReader</code>, which takes the first line of the file as keys in a dictionary, and reads th... | 0 | 2016-09-21T06:41:19Z | [
"python"
] |
Pandas error trying to convert string into integer | 39,608,282 | <p>Requirement : </p>
<p>One particular column in a DataFrame is 'Mixed' Type. It can have values like <code>"123456"</code> or <code>"ABC12345"</code>.</p>
<p>This dataframe is being written into an Excel using xlsxwriter .</p>
<p>For values like <code>"123456"</code>, down the line Pandas converting it into <code>... | 3 | 2016-09-21T05:36:20Z | 39,608,394 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a>:</p>
<pre><code>df = pd.DataFrame({'AltID':['123456','ABC12345','123456'],
'B':[4,5,6]})
print (df)
AltID B
0 123456 4
1 ABC12345 5
2 ... | 2 | 2016-09-21T05:45:34Z | [
"python",
"string",
"pandas",
"casting",
"int"
] |
Pandas error trying to convert string into integer | 39,608,282 | <p>Requirement : </p>
<p>One particular column in a DataFrame is 'Mixed' Type. It can have values like <code>"123456"</code> or <code>"ABC12345"</code>.</p>
<p>This dataframe is being written into an Excel using xlsxwriter .</p>
<p>For values like <code>"123456"</code>, down the line Pandas converting it into <code>... | 3 | 2016-09-21T05:36:20Z | 39,608,396 | <p>Use <code>apply</code> and <code>pd.to_numeric</code> with parameter <code>errors='ignore'</code></p>
<p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>s = pd.Series(['12345', 'abc12', '456', '65hg', 54, '12-31-2001'])
s.apply(pd.to_numeric, errors='ignore')
0 12345
1 abc12
2 ... | 2 | 2016-09-21T05:45:41Z | [
"python",
"string",
"pandas",
"casting",
"int"
] |
Pandas error trying to convert string into integer | 39,608,282 | <p>Requirement : </p>
<p>One particular column in a DataFrame is 'Mixed' Type. It can have values like <code>"123456"</code> or <code>"ABC12345"</code>.</p>
<p>This dataframe is being written into an Excel using xlsxwriter .</p>
<p>For values like <code>"123456"</code>, down the line Pandas converting it into <code>... | 3 | 2016-09-21T05:36:20Z | 39,626,721 | <p>Finally it worked by using 'converters' option in pandas read_excel format as</p>
<pre><code>df_w02 = pd.read_excel(excel_name, names = df_header,converters = {'AltID':str,'RatingReason' : str}).fillna("")
</code></pre>
<p>converters can 'cast' a type as defined by my function/value and keeps intefer stored as str... | 0 | 2016-09-21T21:16:33Z | [
"python",
"string",
"pandas",
"casting",
"int"
] |
Using Python dateutil, how to judge a timezone string is "valid" or not? | 39,608,283 | <p>I am using the following code to do the UTC time to local time conversion:</p>
<pre><code>def UTC_to_local(timezone_str, datetime_UTC):
"""
convert UTC datetime to local datetime. Input datetime is naive
"""
try:
from_zone = dateutil.tz.gettz('UTC')
to_zone = dateutil.tz.gettz(timezo... | 0 | 2016-09-21T05:36:33Z | 39,608,989 | <p><strong>Solution #1:</strong> If you can use <a href="https://github.com/newvem/pytz" rel="nofollow">pytz</a></p>
<pre><code>import pytz
if timezone_str in pytz.all_timezones:
...
else:
raise ValueError('Invalid timezone string!')
</code></pre>
<p><strong>Solution #2:</strong></p>
<pre><code>import os
im... | 1 | 2016-09-21T06:31:25Z | [
"python",
"timezone"
] |
Google FooBar unexpected failed valuation | 39,608,290 | <p>I am working on a Google FooBar challenge and the test case doesn't seem to be correct; below is the highlight.</p>
<pre><code>return the product of non-empty subset of those numbers. Example [2, -3, 1, 0, -5],
would be: xs[0] = 2, xs[1] = -3, xs[4] = -5,
giving the product 2*(-3)*(-5) = 30.
So ans... | 1 | 2016-09-21T05:37:08Z | 39,608,727 | <pre><code>[-2, -3, 4, -5] = -120
</code></pre>
<p>so the subset which has a highest product is</p>
<pre><code> [-3,4,-5] = 60
</code></pre>
<p>, -2 should be excluded from subset to get the maximum product.</p>
| 1 | 2016-09-21T06:13:40Z | [
"java",
"python",
"list"
] |
Google FooBar unexpected failed valuation | 39,608,290 | <p>I am working on a Google FooBar challenge and the test case doesn't seem to be correct; below is the highlight.</p>
<pre><code>return the product of non-empty subset of those numbers. Example [2, -3, 1, 0, -5],
would be: xs[0] = 2, xs[1] = -3, xs[4] = -5,
giving the product 2*(-3)*(-5) = 30.
So ans... | 1 | 2016-09-21T05:37:08Z | 39,608,767 | <p>The output of input = [-2, -3, 4, -5] should be 60.
I will tell you why?
I think you get 120 as (-2)*(-3)<em>4</em>(-5).
However the result of this operation is -120 which is the least product possible for this input.
The output should be 60 from the subset (-3)<em>4</em>(-5).</p>
<p>If you are privileged to be inv... | 1 | 2016-09-21T06:15:57Z | [
"java",
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.