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 |
|---|---|---|---|---|---|---|---|---|---|
Shorten a list of tuples by cutting out loops? | 38,862,164 | <p>I have a function that generates a list of tuples like:</p>
<pre><code>[(0, 0), (1, 1), (1, 2), (1,3), (2, 4), (3, 5), (4, 5)]
</code></pre>
<p>which are used to represent a path of tiles (row, column) in a game I'm making.</p>
<p>The function that I use to generate these paths isn't perfect, since it often produ... | 4 | 2016-08-09T23:49:09Z | 38,862,312 | <p>Although your definition of a "loop" isn't too clear, try this</p>
<pre><code>def clean(path):
path1 = []
for (x1,y1) in path:
for (i,(x2,y2)) in enumerate(path1[:-1]):
if abs(x1-x2) <= 1 and abs(y1-y2) <= 1:
path1 = path1[:i+1]
break
path1.a... | 2 | 2016-08-10T00:08:49Z | [
"python",
"list",
"tuples"
] |
Shorten a list of tuples by cutting out loops? | 38,862,164 | <p>I have a function that generates a list of tuples like:</p>
<pre><code>[(0, 0), (1, 1), (1, 2), (1,3), (2, 4), (3, 5), (4, 5)]
</code></pre>
<p>which are used to represent a path of tiles (row, column) in a game I'm making.</p>
<p>The function that I use to generate these paths isn't perfect, since it often produ... | 4 | 2016-08-09T23:49:09Z | 38,862,351 | <p>How long are your paths? If they're all under 1000 elements, even a naive brute-force algorithm would work:</p>
<pre><code>path = [
(2, 0),
(2, 1),
(1, 2),
(0, 3),
(0, 4),
(1, 5),
(2, 5),
(3, 4),
(3, 3),
(3, 2),
(4, 1)
]
def adjacent(elem, next_elem):
return (abs(el... | 1 | 2016-08-10T00:16:12Z | [
"python",
"list",
"tuples"
] |
When does a class warrant a sub-class? | 38,862,165 | <p>For example, I am trying to build an enemy class for a simple game. Each <em>enemy</em> that spawns has a <em>type</em> which affects it stats which are fields in the <em>enemy</em> class.</p>
<pre><code>class Enemy:
#Base Stats for all enemies
name = "foo"
current_health = 4
max_health = 4
atta... | 0 | 2016-08-09T23:49:14Z | 38,862,272 | <p>If you want to go the dictionary route you could do something like this with a tuple being returned by the key:</p>
<pre><code>enemy_types = {"goblin": ("goblin", 8, 8, 3, 2, 0, goblin_attack)}
def goblin_attack(enemy):
do_stuff()
</code></pre>
<p>Though you may want to use a named_tuple </p>
<p><a href="htt... | 0 | 2016-08-10T00:03:24Z | [
"python",
"dictionary",
"inheritance",
"pygame",
"python-object"
] |
When does a class warrant a sub-class? | 38,862,165 | <p>For example, I am trying to build an enemy class for a simple game. Each <em>enemy</em> that spawns has a <em>type</em> which affects it stats which are fields in the <em>enemy</em> class.</p>
<pre><code>class Enemy:
#Base Stats for all enemies
name = "foo"
current_health = 4
max_health = 4
atta... | 0 | 2016-08-09T23:49:14Z | 38,862,275 | <p>If the set of attributes and possible actions for each enemy type is mostly common across types, I don't see a reason to do anything more complicated than defining an 80 item enumeration for the type, and using a single class called <code>Enemy</code>.</p>
<p>If you do need a variety of actions and such, perhaps yo... | 0 | 2016-08-10T00:03:28Z | [
"python",
"dictionary",
"inheritance",
"pygame",
"python-object"
] |
When does a class warrant a sub-class? | 38,862,165 | <p>For example, I am trying to build an enemy class for a simple game. Each <em>enemy</em> that spawns has a <em>type</em> which affects it stats which are fields in the <em>enemy</em> class.</p>
<pre><code>class Enemy:
#Base Stats for all enemies
name = "foo"
current_health = 4
max_health = 4
atta... | 0 | 2016-08-09T23:49:14Z | 38,862,278 | <p>The goblin should probably be an instance of Enemy. However, in your example you added a method called <code>attack</code>. I would say the best way to do this is like this:</p>
<pre><code>class Enemy:
#Base Stats for all enemies
def __init__ (self, **kwargs):
self.name = "foo"
self.current_health = 4
... | 0 | 2016-08-10T00:03:33Z | [
"python",
"dictionary",
"inheritance",
"pygame",
"python-object"
] |
Automatically download files using selenium and tor | 38,862,166 | <p>I am using Tor as my webdriver with selenium</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary('/Applications/TorBrowser.app/Contents/MacOS/firefox')
driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=profile)
</c... | 0 | 2016-08-09T23:49:23Z | 38,882,609 | <pre><code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
profile = profile = FirefoxProfile('/Applications/TorBrowser.app/TorBrowser/Data/Browser/profile.default')
profile.set_preference("browser.... | 0 | 2016-08-10T20:08:02Z | [
"python",
"selenium",
"tor"
] |
Find an item in a list using the known index | 38,862,203 | <p>I'm having trouble with Python here and need your help.</p>
<p>I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using <code>myList.index(item)</code>.</p>
<p>Snippet... | -1 | 2016-08-09T23:53:20Z | 38,862,230 | <p>You reference an item in a list by using square brackets, like so</p>
<pre><code>c = new_lst[a]
d = new_lst[b]
</code></pre>
| 2 | 2016-08-09T23:57:09Z | [
"python",
"list",
"indexing"
] |
Find an item in a list using the known index | 38,862,203 | <p>I'm having trouble with Python here and need your help.</p>
<p>I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using <code>myList.index(item)</code>.</p>
<p>Snippet... | -1 | 2016-08-09T23:53:20Z | 38,862,234 | <p>You don't want the <code>list.index</code> function - this is for finding the position of an item in a list. To find the item at a position, you should use slicing (which, in other languages, is sometimes called "indexing", which is probably what confused you). Slicing a single element out of an iterable looks like ... | 0 | 2016-08-09T23:57:48Z | [
"python",
"list",
"indexing"
] |
Find an item in a list using the known index | 38,862,203 | <p>I'm having trouble with Python here and need your help.</p>
<p>I want to return an item found at a particular index. I can't know what the item is yet, only the index. Everything I have found is the opposite of what I need, i.e., find the index of a known item using <code>myList.index(item)</code>.</p>
<p>Snippet... | -1 | 2016-08-09T23:53:20Z | 38,862,239 | <blockquote>
<p>I want to return an item found at a particular index.</p>
</blockquote>
<p>Do you want to use the <code>[]</code> operator?</p>
<p><code>new_lst[a]</code> gets the item in <code>new_lst</code> at index <code>a</code>.</p>
<p>See <a href="https://docs.python.org/3.5/library/stdtypes.html#sequence-ty... | 0 | 2016-08-09T23:58:12Z | [
"python",
"list",
"indexing"
] |
Is there a python ReportLab equivalent of TCPDF's 'annotate' function? | 38,862,237 | <p>I'm trying to use the reportlab library to write an 'annotation' on a pdf. I've successfully written new data to a pdf using reportlab, but I can't find any information on how I would create an annotation.</p>
<p>When I say annotation I am referring to TCPDF's annotate function. This creates a clickable and movable... | 1 | 2016-08-09T23:58:03Z | 38,914,750 | <p>There is good news and bad news about annotation in <a href="/questions/tagged/reportlab" class="post-tag" title="show questions tagged 'reportlab'" rel="tag">reportlab</a>, the good news is it is possible to annotate in <a href="/questions/tagged/reportlab" class="post-tag" title="show questions tagged '... | 0 | 2016-08-12T09:39:13Z | [
"php",
"python",
"pdf",
"tcpdf",
"reportlab"
] |
How to Add Incremental Numbers to a New Column Using Pandas | 38,862,293 | <p>I have this simplified dataframe:</p>
<pre><code>ID Fruit
F1 Apple
F2 Orange
F3 Banana
</code></pre>
<p>I want to add in the begining of the dataframe a new column <code>df['New_ID']</code> which has the number <code>880</code> that increments by one in each row.</p>
<p>The output should be simply like:... | 2 | 2016-08-10T00:05:36Z | 38,862,360 | <p>Here:</p>
<pre><code>df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880
</code></pre>
| 1 | 2016-08-10T00:17:21Z | [
"python",
"pandas",
"dataframe"
] |
How to Add Incremental Numbers to a New Column Using Pandas | 38,862,293 | <p>I have this simplified dataframe:</p>
<pre><code>ID Fruit
F1 Apple
F2 Orange
F3 Banana
</code></pre>
<p>I want to add in the begining of the dataframe a new column <code>df['New_ID']</code> which has the number <code>880</code> that increments by one in each row.</p>
<p>The output should be simply like:... | 2 | 2016-08-10T00:05:36Z | 38,862,389 | <pre><code>df.insert(0, 'New_ID', range(880, 880 + len(df)))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/10mjk.png"><img src="http://i.stack.imgur.com/10mjk.png" alt="enter image description here"></a></p>
| 5 | 2016-08-10T00:21:28Z | [
"python",
"pandas",
"dataframe"
] |
How to Add Incremental Numbers to a New Column Using Pandas | 38,862,293 | <p>I have this simplified dataframe:</p>
<pre><code>ID Fruit
F1 Apple
F2 Orange
F3 Banana
</code></pre>
<p>I want to add in the begining of the dataframe a new column <code>df['New_ID']</code> which has the number <code>880</code> that increments by one in each row.</p>
<p>The output should be simply like:... | 2 | 2016-08-10T00:05:36Z | 38,862,663 | <pre><code>df = df.assign(New_ID=[880 + i for i in xrange(len(df))])
>>> df
ID Fruit New_ID
0 F1 Apple 880
1 F2 Orange 881
2 F3 Banana 882
</code></pre>
| 3 | 2016-08-10T00:59:49Z | [
"python",
"pandas",
"dataframe"
] |
trouble installing rPython | 38,862,299 | <p>I tried to install rPython package in Linux system but I got following errors. I tried to search online but couldn't find a solution. I appreciate any suggestions.</p>
<pre><code>> Sys.setenv(PATH = "/opt/anaconda/2.3.0/bin")
> system("python --version")
Python 2.7.10 :: Anaconda 2.3.0 (64-bit)
> install.... | 0 | 2016-08-10T00:06:34Z | 38,862,603 | <p>You're doing wrong with setting up env var <code>PATH</code>. It should be something equivalent with this shell command:</p>
<p><code>
$ export PATH=$PATH:/path/to/your/dir
</code></p>
| 0 | 2016-08-10T00:51:04Z | [
"python"
] |
get Json data from request with Django | 38,862,330 | <p>I'm trying to develop a very simple script in Django, I'd collect a Json data from the request and then store all data in the database.</p>
<p>I developed one python script that I'm using to send the Json data to the Django view, but I'm doing something wrong and I can't understand what, because every time that I r... | 0 | 2016-08-10T00:11:07Z | 38,862,615 | <p>Your dictionary "data" in sender.py contains only one value with key "ids" but in view.py you are trying to access keys "label" and "url" in this parsed dictionary. </p>
| 0 | 2016-08-10T00:53:42Z | [
"python",
"json",
"django"
] |
string cleaning in python | 38,862,344 | <p>Input:</p>
<pre><code> " The Elephant's 4 cats. "
</code></pre>
<p>Expected Output:</p>
<pre><code> the elephants 4 cats
</code></pre>
<p>Code:</p>
<pre><code> import re
temp1 = re.sub('\W+',' ', str).strip()
output = temp2.lower()
</code></pre>
<p>My output:</p>
<pre><code> the elephant s 4 cats
</code></... | 0 | 2016-08-10T00:14:03Z | 38,862,377 | <p>try:</p>
<pre><code>temp1 = re.sub(r'[^\w\s_]+', '', str).strip()
</code></pre>
<p>Basically, your original \W+ means "non-word characters", which matches spaces, quotes, and periods. So it replaces them all with a "space"...which means the apostrophe gains a space.</p>
<p>By specifically matching non-word-non-sp... | 3 | 2016-08-10T00:19:22Z | [
"python",
"pyspark"
] |
Regex: How to match words without consecutive vowels? | 38,862,349 | <p>I'm really new to regex and I've been able to find regex which can match this quite easily, but I am unsure how to only match words without it.</p>
<p>I have a .txt file with words like</p>
<pre><code>sheep
fleece
eggs
meat
potato
</code></pre>
<p>I want to make a regular expression that matches words in which vo... | 4 | 2016-08-10T00:15:54Z | 38,862,495 | <p>Note that, since the desired output includes <code>meat</code> but not <code>fleece</code>, desired words are allowed to have repeated vowels, just not the same vowel repeated.</p>
<p>To select lines with no repeated vowel:</p>
<pre><code>>>> [w for w in open('file.txt') if not re.search(r'([aeiou])\1', w... | 7 | 2016-08-10T00:35:16Z | [
"python",
"regex"
] |
Regex: How to match words without consecutive vowels? | 38,862,349 | <p>I'm really new to regex and I've been able to find regex which can match this quite easily, but I am unsure how to only match words without it.</p>
<p>I have a .txt file with words like</p>
<pre><code>sheep
fleece
eggs
meat
potato
</code></pre>
<p>I want to make a regular expression that matches words in which vo... | 4 | 2016-08-10T00:15:54Z | 38,862,546 | <p>@John1024 's answer should work
I also would try</p>
<blockquote>
<p>"\w*(a{2,}|e{2,}|i{2,}|o{2,}|u{2,})\w*"ig</p>
</blockquote>
| 1 | 2016-08-10T00:45:02Z | [
"python",
"regex"
] |
list not entering first input | 38,862,399 | <p>I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance
Here is my code:</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != qui... | 1 | 2016-08-10T00:22:44Z | 38,862,417 | <p>That is because you never put it in there.</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = [user_input] # Create the list with the original input
...
</code></pre>
<p>With the above, the first thing entered by the user is placed in the list when the list is creat... | 1 | 2016-08-10T00:25:22Z | [
"python",
"list",
"python-2.7",
"raw-input"
] |
list not entering first input | 38,862,399 | <p>I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance
Here is my code:</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != qui... | 1 | 2016-08-10T00:22:44Z | 38,862,473 | <pre><code> def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
n... | 0 | 2016-08-10T00:32:17Z | [
"python",
"list",
"python-2.7",
"raw-input"
] |
list not entering first input | 38,862,399 | <p>I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance
Here is my code:</p>
<pre><code>def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != qui... | 1 | 2016-08-10T00:22:44Z | 38,862,487 | <p>You do not add your initial input to the array. Instead you enter the loop and ask for another input and check then add that to the array. You should ask for all inputs within the loop, as this means you only need one <code>raw_input</code> and one check for the done value. </p>
<p>A common way to do this is to go ... | 0 | 2016-08-10T00:34:19Z | [
"python",
"list",
"python-2.7",
"raw-input"
] |
How to plot an ROC curve for binary-valued scores using scikit-learn? | 38,862,419 | <p>I plotted an <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic" rel="nofollow">ROC curve</a> using the code shown below:</p>
<pre><code>fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
plt.plot(fpr["micro"], tpr["micro"],
label='ROC curve Fold1 (area = %0.2... | 0 | 2016-08-10T00:25:59Z | 38,862,820 | <p>ROC curves are a way to compare a set of <em>continuous-valued</em> scores to a set of binary-valued labels by applying a varying discrimination threshold to the scores.</p>
<p>If your scores are already binary then there's no need to apply any threshold - just compute the true-positive rate and false-positive rate... | 1 | 2016-08-10T01:21:27Z | [
"python",
"scikit-learn",
"roc"
] |
Find value greater than level - Python Pandas | 38,862,657 | <p>In a time series (ordered tuples), what's the most efficient way to find the first time a criterion is met? </p>
<p>In particular, what's the most efficient way to determine when a value goes over 100 for the value of a column in a pandas data frame?</p>
<p>I was hoping for a clever vectorized solution, and not ha... | 1 | 2016-08-10T00:59:18Z | 38,863,264 | <p>Try this: "> 99" </p>
<pre><code>df[df['price'].gt(99)].index[0]
</code></pre>
<p>returns <code>"2"</code>, the second index row. </p>
<p>all row indexes greater than 99 </p>
<pre><code>df[df['price'].gt(99)].index
Int64Index([2, 5, 6], dtype='int64')
</code></pre>
| 2 | 2016-08-10T02:21:46Z | [
"python",
"pandas"
] |
Python - Looking for a solution to prevent duplicates in lists generated via text file | 38,862,685 | <p>As the title mentions, I'm looking for a way for my code to not only detect duplicates in a list, but to separate the items, moving them to other lists.</p>
<p>I am relatively new at programming, having just finished an introductory course to python at my local JC. During the course of the semester, I had an idea t... | 0 | 2016-08-10T01:02:24Z | 38,862,893 | <p>How about just to use simple for-cycle? I will try to make it simple for you. If I understood your idea correctly then it can be implemented like this:</p>
<pre><code># Some input into this example
fruits = ["apple", "apple", "banana", "pear", "orange", "kiwi"]
# The code you're probably looking for
first_basket ... | 0 | 2016-08-10T01:31:04Z | [
"python",
"python-3.x"
] |
Python - Looking for a solution to prevent duplicates in lists generated via text file | 38,862,685 | <p>As the title mentions, I'm looking for a way for my code to not only detect duplicates in a list, but to separate the items, moving them to other lists.</p>
<p>I am relatively new at programming, having just finished an introductory course to python at my local JC. During the course of the semester, I had an idea t... | 0 | 2016-08-10T01:02:24Z | 38,863,017 | <p>I'm assuming if you have more than 2 copies of any word, you can ignore everything after the first two. My suggested solution splits the list into repeated values, which will be shared by both groups and single values, which will be shuffled and split among the two groups.</p>
<pre><code>import collections
list = ... | 2 | 2016-08-10T01:49:22Z | [
"python",
"python-3.x"
] |
Range of logarithmic axis of scatter plot is not being set appropriately by matplotlib.pyplot | 38,862,697 | <p>I'm trying to plot 5 points (x, y) on a 2D scatter plot with a logarithmic y axis. The plot is produced but the range of the y-axis is not chosen well so only one point is displayed. The problem goes away when I remove the first point (0.38, 0.005).</p>
<p>Is this a bug in matplotlib?</p>
<p>Could someone try re... | 1 | 2016-08-10T01:04:52Z | 38,864,897 | <p>edit: I got the same scaling error.</p>
<p>Add this to the end of your code</p>
<pre><code>ax.set_ylim([0.001, 100])
</code></pre>
<p>It will force the axis to behave. </p>
<p>It might be a jupyter thing?<br>
When I ran your code as a script from the command line (altering it not to be "inline"), the axes scaled... | 1 | 2016-08-10T05:27:24Z | [
"python",
"matplotlib",
"logarithm"
] |
Trouble building PySide on Mac OS X (El Capitan) | 38,862,699 | <p>I am trying build PySide on a Mac running El Capitan (10.11.5).</p>
<p>This is the command I am using:</p>
<pre><code>python setup.py bdist_wheel --cmake=/Applications/CMake.app/Contents/bin/cmake
</code></pre>
<p>However, every time I run this, I get the following error messages:</p>
<pre><code>In file included... | 0 | 2016-08-10T01:05:09Z | 38,984,653 | <p>Here is how I built PySide without Phonon:</p>
<p>Download the PySide source to a temp direct and uncompress the archive:</p>
<pre><code>$ pwd
/Users/spearsc/Documents/pyside_tmp
$ tar âxvzf dist\PySide-1.2.4.tar
</code></pre>
<p>Now you need to edit PySide-1.2.4/sources/pyside/CMakeLists.txt. Find this line ... | 0 | 2016-08-16T21:18:57Z | [
"python",
"osx",
"qt",
"pyside"
] |
Check and extract composition args in sympy python | 38,862,764 | <p>i want to check if an expression is a composition of two functions and extract the args for example</p>
<pre><code>Log(x-1) :
</code></pre>
<p>i want get :</p>
<pre><code>[log(x),x-1]
</code></pre>
<p>and </p>
<pre><code>sin(x)/(1-sin(x))
</code></pre>
<p>i want get :</p>
<pre><code>[x/(1-x),sin(x)]
</code></... | 3 | 2016-08-10T01:13:32Z | 38,880,365 | <p>There isn't a simple function that does it. You could use <code>cse</code> to pull out common subexpressions and <code>expr.args</code> to pull out non-common subexpressions from those. </p>
| 0 | 2016-08-10T17:53:14Z | [
"python",
"sympy"
] |
transaction based in django | 38,862,775 | <p>I would like to get some idea on how to improve (if any) my code in implementing transaction based query in Django.</p>
<p>This is how I understand the ATOMIC_REQUEST I read on django documentation. I have this function view:</p>
<pre><code>from django.db import transaction
import sys
@transaction.atomic
def save_... | 0 | 2016-08-10T01:15:38Z | 38,863,136 | <p>You don't need both decorator <code>@transaction.atomic</code> and <code>with atomic.transaction()</code>, just use one. Also while using <code>with atomic.transaction()</code>, catch database exceptions (<code>IntegrityError</code>) instead of broadly handling all exceptions at once. </p>
<pre><code>def save_progr... | 1 | 2016-08-10T02:07:08Z | [
"python",
"django"
] |
Why can't Django see my static files? | 38,862,786 | <p>I am trying to implement sass_processor in my django_cms site and am getting a weird error.</p>
<pre><code>Unable to locate file mysite/static/scss/main.scss while rendering tag 'sass_src' in template /Users/USER/Work/DIR/APP/SITE/mysite/templates/base.html
</code></pre>
<p>I have followed the latest Django CMS in... | 0 | 2016-08-10T01:17:25Z | 39,052,121 | <p>You should change the type of your SASS import to "<em>text/css</em>". The "<em>text/x-scss</em>" type is used by <strong>django-compressor</strong>, but not by <strong>django-sass-processor</strong>.</p>
<p>Your new SASS import then becomes:</p>
<pre><code><link href="{% sass_src 'myapp/static/scss/main.scss' ... | 0 | 2016-08-20T08:29:42Z | [
"python",
"django",
"sass",
"django-cms"
] |
Pandas Melt several groups of columns into multiple target columns by name | 38,862,832 | <p>I would like to melt several groups of columns of a dataframe into multiple target columns. Similar to questions <a href="http://stackoverflow.com/questions/35187963/python-pandas-melt-groups-of-initial-columns-into-multiple-target-columns">Python Pandas Melt Groups of Initial Columns Into Multiple Target Columns</a... | 4 | 2016-08-10T01:23:09Z | 38,863,051 | <p>You can convert the column names to multi index based on the columns pattern and then stack at a particular level depending on the result you need:</p>
<pre><code>import pandas as pd
df.set_index('id', inplace=True)
df.columns = pd.MultiIndex.from_tuples(tuple(df.columns.str.split("_")))
df.stack(level = 1).reset_i... | 5 | 2016-08-10T01:54:48Z | [
"python",
"pandas",
"melt"
] |
Pandas Melt several groups of columns into multiple target columns by name | 38,862,832 | <p>I would like to melt several groups of columns of a dataframe into multiple target columns. Similar to questions <a href="http://stackoverflow.com/questions/35187963/python-pandas-melt-groups-of-initial-columns-into-multiple-target-columns">Python Pandas Melt Groups of Initial Columns Into Multiple Target Columns</a... | 4 | 2016-08-10T01:23:09Z | 38,865,238 | <pre><code>cols = df.columns.difference(['id'])
pd.lreshape(df, cols.groupby(cols.str.split('_').str[0])).sort_values('id')
Out:
id a c b
0 101 a aa 1
2 101 b bb 2
4 101 c cc 3
1 102 d dd 4
3 102 e ee 5
5 102 f ff 6
</code></pre>
| 3 | 2016-08-10T05:53:21Z | [
"python",
"pandas",
"melt"
] |
else statement not executing | 38,862,881 | <p>The part of my code where I ask the user if they want some cake has me confused.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'ye... | 0 | 2016-08-10T01:29:25Z | 38,862,892 | <p>I haven't written a single line of python before, but my intuition says you need to replace</p>
<pre><code>if cake == 'yes' or 'ya' or 'Ya':
</code></pre>
<p>with</p>
<pre><code>if cake == 'yes' or cake == 'ya' or cake == 'Ya':
</code></pre>
<hr>
<p>You could try <a href="http://stackoverflow.com/questions/9659... | 1 | 2016-08-10T01:30:57Z | [
"python",
"if-statement",
"boolean-logic"
] |
else statement not executing | 38,862,881 | <p>The part of my code where I ask the user if they want some cake has me confused.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'ye... | 0 | 2016-08-10T01:29:25Z | 38,862,921 | <p>Non-empty strings are always evaluated as <code>True</code> in Python. Your code </p>
<pre><code>if cake == 'yes' or 'ya' or 'Ya':
</code></pre>
<p>, using boolean logic, will always execute the tasks under it no matter you enter there. So it always prints "Cool!".</p>
<p>To prevent this from happening you should... | 0 | 2016-08-10T01:35:36Z | [
"python",
"if-statement",
"boolean-logic"
] |
else statement not executing | 38,862,881 | <p>The part of my code where I ask the user if they want some cake has me confused.</p>
<pre><code>import time
print("Here comes dat boi")
time.sleep(.5)
print("Waddup dat boi")
time.sleep(1)
name = input("Whats your name?\n")
print ("Hello,",name)
time.sleep(.5)
cake = input("Hello, want some cake?\n")
if cake == 'ye... | 0 | 2016-08-10T01:29:25Z | 38,862,951 | <p>An if statement is built on conditions. If you plan to use a statement with multiple different 'triggers' you must state the new conditions for each. </p>
<p>As such, your statement requires <code>cake ==</code> for every potential true or false outcome.</p>
<pre><code>import time
print("Here comes dat boi")
time.... | 2 | 2016-08-10T01:40:01Z | [
"python",
"if-statement",
"boolean-logic"
] |
Python regular expression for matching '0' with no decimal point | 38,862,890 | <p>Consider the multiline string</p>
<pre><code>text = """SPLINE
8 # <------ everything from here
0
70
12
71
2
72
8
73
5
42
0.1000000000000000E-08
43
0.1000000000000000E+01
40
0.1000000000000000E... | 0 | 2016-08-10T01:30:43Z | 38,863,547 | <p>Fairly trivial, just needed to add a newline character to skip over all the decimals. Successful regex was <code>SPLINE(.*?)\s\s0\n</code>, such that</p>
<pre><code>re.findall('SPLINE(.*?)\s\s0\n', text, re.DOTALL)
</code></pre>
<p>did the trick.</p>
| 0 | 2016-08-10T02:57:58Z | [
"python",
"regex"
] |
how to use flask driver in python splinter | 38,862,891 | <p>all my code is just:</p>
<pre><code>from splinter import Browser
from flask import Flask, request
from splinter.driver.flaskclient import FlaskClient
app = Flask(__name__)
browser = Browser('flask', app=app)
browser.visit('https://www.google.com')
print(browser.html)
</code></pre>
<p>which print the 404 html:
... | 0 | 2016-08-10T01:30:43Z | 38,867,405 | <p>You are getting a 404 error because <strong>your Flask app has no routes</strong>.</p>
<p>I believe the purpose of the Splinter Flask client is to test your Flask app, not to test/request other domains. Visiting another domain with the Splinter Flask client will simply request the URL from your domain. You have no... | 1 | 2016-08-10T07:56:21Z | [
"python",
"python-3.x",
"splinter"
] |
Python selenium script to continue running if element is not found | 38,862,929 | <p>I am dealing with a pop up issue that seems to be random before I click on a button. I want to know if there is any way I can check if the element is displayed and click it, if it is not displayed, i want it to continue running the script. my current script keeps getting an error. when the pop up is displayed, my sc... | -1 | 2016-08-10T01:36:35Z | 38,863,075 | <p>Actually <code>find_element_by_xpath</code> always returns either element or throws exception, So if there is no element by provided locator you can't execute <code>is_displayed()</code>. You should try using <code>find_elements_by_xpath</code> instead and check the length as below :-</p>
<pre><code>onetouch = self... | 0 | 2016-08-10T01:58:33Z | [
"python",
"selenium"
] |
Python selenium script to continue running if element is not found | 38,862,929 | <p>I am dealing with a pop up issue that seems to be random before I click on a button. I want to know if there is any way I can check if the element is displayed and click it, if it is not displayed, i want it to continue running the script. my current script keeps getting an error. when the pop up is displayed, my sc... | -1 | 2016-08-10T01:36:35Z | 38,864,279 | <p>Try following:</p>
<pre><code>from selenium.common.exceptions import NoSuchElementException
try:
time.sleep(2)
self.driver.find_element_by_xpath(".//*[@id='memberReview']/div[2]/div/div/div[2]/div[1]/div[1]/a").click()
except NoSuchElementException:
print "onetouch not present....continuing script"
</c... | 0 | 2016-08-10T04:30:33Z | [
"python",
"selenium"
] |
Sum dictionary items based on rank | 38,862,949 | <p>I can sum items in a list of dicts per key like so:</p>
<pre><code>import functools
dict(
functools.reduce(
lambda x, y:x.update(y) or x,
dict1,
collections.Counter())
)
</code></pre>
<p>But given that</p>
<pre><code>dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
{'ledecky'... | 2 | 2016-08-10T01:39:52Z | 38,863,116 | <p>The <code>get()</code> dictionary function works really well in this example, we either give the newly created dictionary a default value of <code>0</code> or add it's current value with the weighted value using our <code>value</code> (<em>the value of</em> <code>dict1</code>) as the search key.</p>
<pre><code>def ... | 3 | 2016-08-10T02:03:59Z | [
"python",
"dictionary",
"collections",
"counter"
] |
Sum dictionary items based on rank | 38,862,949 | <p>I can sum items in a list of dicts per key like so:</p>
<pre><code>import functools
dict(
functools.reduce(
lambda x, y:x.update(y) or x,
dict1,
collections.Counter())
)
</code></pre>
<p>But given that</p>
<pre><code>dict1 = [{'ledecky': 1, 'king': 2, 'vollmer': 3},
{'ledecky'... | 2 | 2016-08-10T01:39:52Z | 38,863,473 | <p>Just define a lookup function to transform the original dict to a medal values dict:</p>
<pre><code>def lookup(d):
return dict((k, medal_value[v]) for k, v in d.items())
</code></pre>
<p>And apply this function to your update part of the expression:</p>
<pre><code>dict(
functools.reduce(
lambda x,... | 1 | 2016-08-10T02:47:44Z | [
"python",
"dictionary",
"collections",
"counter"
] |
Class not creating new instances upon repeated calls | 38,863,073 | <p>May be I am missing something really basic here, but when I define a class in the following manner:</p>
<pre><code>class Arbitrary(object):
"""Arbitary class to test init"""
def __init__(self):
self.x = dict()
</code></pre>
<p>and repeatedly instantiate the class in the following way</p>
<pre><cod... | 0 | 2016-08-10T01:57:52Z | 38,863,204 | <p>I'm not a Python expert but I can see you are overwring your instances. I tried changing it to below and it runs ok :</p>
<pre><code>#!/bin/env python
class Arbitrary(object):
"""Arbitary class to test init"""
def __init__(self):
self.x = dict()
a = []
for i in range(5):
a.append(Arbitrary())
... | 4 | 2016-08-10T02:15:04Z | [
"python",
"class",
"oop",
"heap-memory"
] |
Python: Pandas Series - Difference between consecutive datetime rows in seconds | 38,863,137 | <p>I have a pandas Series called 'df' as follows</p>
<pre><code> value
date_time_index
2015-10-28 01:54:00 1.0
2015-10-28 01:55:00 1.0
2015-10-28 01:56:00 1.0
2015-10-28 01:57:00 1.0
2015-10-28 01:58:00 1.0
</code></pre>
<p>and I just want a new column with ... | 1 | 2016-08-10T02:07:12Z | 38,863,249 | <p>I think Ive worked it out using </p>
<pre><code>df['temp_index'] = df.index
df['Delta'] = df['temp_index'].diff().astype('timedelta64[m]')
</code></pre>
<p>in minutes rather than seconds (change m to s for seconds)</p>
| 1 | 2016-08-10T02:19:57Z | [
"python",
"datetime",
"pandas",
"difference",
"seconds"
] |
Python: Pandas Series - Difference between consecutive datetime rows in seconds | 38,863,137 | <p>I have a pandas Series called 'df' as follows</p>
<pre><code> value
date_time_index
2015-10-28 01:54:00 1.0
2015-10-28 01:55:00 1.0
2015-10-28 01:56:00 1.0
2015-10-28 01:57:00 1.0
2015-10-28 01:58:00 1.0
</code></pre>
<p>and I just want a new column with ... | 1 | 2016-08-10T02:07:12Z | 38,865,697 | <p>I'd do it like this:</p>
<pre><code>df.index.to_series().diff().dt.total_seconds().fillna(0)
date_time_index
2015-10-28 01:54:00 0.0
2015-10-28 01:55:00 60.0
2015-10-28 01:56:00 60.0
2015-10-28 01:57:00 60.0
2015-10-28 01:58:00 60.0
Name: date_time_index, dtype: float64
</code></pre>
| 2 | 2016-08-10T06:22:33Z | [
"python",
"datetime",
"pandas",
"difference",
"seconds"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pr... | 0 | 2016-08-10T02:15:25Z | 38,863,256 | <p>I'm pretty sure that you cannot. The <code>%p</code> format code is the locale-specific "national representation of either "ante meridiem" (a.m.) or "post meridiem" (p.m.) as appropriate". <code>de_DE</code> is the generic German locale which is what defines the national representation which happens to be lowerc... | 2 | 2016-08-10T02:20:55Z | [
"python",
"datetime"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pr... | 0 | 2016-08-10T02:15:25Z | 38,863,271 | <p><code>en_US</code> and <code>de_DE</code> are <a href="https://docs.python.org/2/library/locale.html" rel="nofollow">locales</a>.</p>
<p><code>en_US</code> = English US<br>
<code>de_DE</code> = German Germany</p>
<p>In the <code>en_US</code> locale, AM/PM are uppercase whereas for the <code>de_DE</code> locale, it... | 1 | 2016-08-10T02:22:31Z | [
"python",
"datetime"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pr... | 0 | 2016-08-10T02:15:25Z | 38,863,349 | <p>From the documentation you've linked:</p>
<blockquote>
<p>Because the format depends on the current locale, care should be taken
when making assumptions about the output value. Field orderings will
vary (for example, âmonth/day/yearâ versus âday/month/yearâ), and the
output may contain Unicode chara... | 1 | 2016-08-10T02:31:33Z | [
"python",
"datetime"
] |
How to make pythons datetime object show AM and PM in lowercase? | 38,863,210 | <p>Over here: <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior</a> it says that <code>%p</code> displays AM / PM. It shows this</p>
<pre><code>AM, PM (en_US);
am, pm (de_DE)
</code></pr... | 0 | 2016-08-10T02:15:25Z | 38,863,352 | <p>Try changing '%p' to '%P'. Whether '%P' is supported depends on the 'strftime' function provided by the platform C library.</p>
| 2 | 2016-08-10T02:32:00Z | [
"python",
"datetime"
] |
How can I filter queries in view.py and render them into the template? | 38,863,224 | <p>I understand the querying from a basic perspective. That is if I write:</p>
<pre><code>{% for item in items %}
{{ item.jurisdiction}}
{% endfor %}
</code></pre>
<p>It will for every row item in my database table which has an entry in the "jurisdiction" column capture that row and return just the "jurisdiction"... | 0 | 2016-08-10T02:16:41Z | 38,863,338 | <p>Think of view function is just another normal function. The test is not rendered because the function is already returned. Once the function returns anything no further lines would be executed.</p>
<p>You can pass multiple filtered queries to template by passing all the querysets in the context. </p>
<pre><code>r... | 1 | 2016-08-10T02:29:54Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Change subplot size in python matplotlib | 38,863,262 | <p>I would like to change the size of the <em>subplot</em> when I use Python's matplotlib. I already know how to change the size of the <em>figure</em>, however, how does one go about changing the size of the corresponding subplots themselves? This has remained somewhat elusive in my googling. Thanks. </p>
<p>(For exa... | 0 | 2016-08-10T02:21:43Z | 38,863,444 | <p>You can use <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.subplots_adjust" rel="nofollow"><code>.subplots_adjust()</code></a>, e.g.</p>
<pre><code>import seaborn as sns, matplotlib.pyplot as plt
titanic = sns.load_dataset('titanic')
g = sns.factorplot(x='sex',y='age',hue='class',dat... | 0 | 2016-08-10T02:43:38Z | [
"python",
"numpy",
"matplotlib",
"plot",
"figure"
] |
Change subplot size in python matplotlib | 38,863,262 | <p>I would like to change the size of the <em>subplot</em> when I use Python's matplotlib. I already know how to change the size of the <em>figure</em>, however, how does one go about changing the size of the corresponding subplots themselves? This has remained somewhat elusive in my googling. Thanks. </p>
<p>(For exa... | 0 | 2016-08-10T02:21:43Z | 38,863,470 | <p>You can also play with the axis size.
<a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">http://matplotlib.org/api/axes_api.html</a></p>
<p>set_position() can be used to change width and height of your axis.</p>
<pre><code>import matplotlib.pyplot as plt
ax = plt.subplot(111)
box = ax.get_position... | 1 | 2016-08-10T02:47:30Z | [
"python",
"numpy",
"matplotlib",
"plot",
"figure"
] |
Given a set of bounding boxes in an 2D space, group them into rows | 38,863,534 | <p>Given a set of <strong>N</strong> bounding boxes with vertex coordinates:</p>
<pre><code>"vertices": [
{
"y": 486,
"x": 336
},
{
"y": 486,
"x": 2235
},
{
"y": 3393,
"x": 2235
},
{
"y": 3393,
"x": 336
}
]
</code></pre>
<p>I wou... | 0 | 2016-08-10T02:55:39Z | 38,864,257 | <p>I think this is a clustering problem. In fact, because you can ignore the x co-ordinates, I think this is a 1-dimensional clustering problem. Some standard clustering algorithms such as k-means are good for minimising sums of squares from cluster centres, which amounts to what you are looking for. Unfortunately, the... | 0 | 2016-08-10T04:28:34Z | [
"python",
"algorithm",
"geometry",
"computational-geometry"
] |
Search nested dicts for key trees | 38,863,540 | <p>I would like to check if a tuple of keys exists in a nested dictionary, similarly to <code>dict.get</code>. The functionality can be achieved as follows.</p>
<pre><code>nested_dict = {
'x': 1,
'a': {
'b': {
'c': 2,
'y': 3
},
'z': 4
}
}
def check(nested, *... | 1 | 2016-08-10T02:56:59Z | 38,863,581 | <p>For python 3.x do <code>from functools import reduce</code>.</p>
<p>You can wrap a <code>try .. except KeyError</code> (and <code>TypeError</code>) and return the appropriate boolean value:</p>
<pre><code>>>> reduce(lambda x,y: x[y], ["a", "b", "c"], nested_dict)
2
>>> reduce(lambda x,y: x[y], ["... | 1 | 2016-08-10T03:04:29Z | [
"python",
"python-3.x",
"dictionary",
"nested",
"python-3.5"
] |
Python: best practice for a dynamic Facebook picture url with access token | 38,863,706 | <p>I've got a Django app where users can sign up with facebook. I'm using <a href="https://pypi.python.org/pypi/facebook-sdk" rel="nofollow">facebook-sdk</a> to query the Facebook Graph API. I'm running into a problem when constructing a profile picture url for a given user.</p>
<p>According to various sources, I can ... | 0 | 2016-08-10T03:23:19Z | 38,864,823 | <ul>
<li>if an access token is rejected do regenerate it . An access token might be revoked when user changes his password</li>
<li>Request your long lived token and store it with metadata when to refresh it : <a href="https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension" rel="nofo... | 0 | 2016-08-10T05:20:44Z | [
"python",
"django",
"facebook",
"facebook-graph-api"
] |
scikit learn py-earth method parameter 'check_every' and 'min_search_point' doesn't work | 38,863,733 | <p>I am using the method named py-earth from <a href="https://github.com/scikit-learn-contrib/py-earth" rel="nofollow">https://github.com/scikit-learn-contrib/py-earth</a>.</p>
<p>I am trying to use the parameter <code>check_every</code> to control my fitting time, but I found it didn't make any differences when I cha... | 0 | 2016-08-10T03:27:31Z | 38,987,813 | <p>Quoted from <a href="https://github.com/scikit-learn-contrib/py-earth/issues/130#issuecomment-239050763" rel="nofollow">github</a>:</p>
<blockquote>
<p>I think if you set check_every sufficiently high, you should eventually see a worse fit (and maybe a very slight speed up). I think it speaks to the usefulness of... | 0 | 2016-08-17T03:48:45Z | [
"python",
"scikit-learn"
] |
How to get count of all element in numpy? | 38,863,775 | <p>suppose I have an array in numpy</p>
<pre><code>array([1,1,2,3,4,5,5,5,6,7,7,7,7])
</code></pre>
<p>What I want is to get two arrays to give count of each element:</p>
<pre><code>array([1,2,3,4,5,6,7])
array([1,1,1,1,3,1,4])
</code></pre>
<p>How can I do this without any for loops?</p>
| 0 | 2016-08-10T03:32:26Z | 38,863,921 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> :</p>
<pre><code>>>> import numpy as np
>>> a = np.array([1,1,2,3,4,5,5,5,6,7,7,7,7])
>>> b = np.bincount(a)
>>> b[np.unique(a)]
array([2, 1, ... | 0 | 2016-08-10T03:52:18Z | [
"python",
"numpy",
"vectorization"
] |
How to get count of all element in numpy? | 38,863,775 | <p>suppose I have an array in numpy</p>
<pre><code>array([1,1,2,3,4,5,5,5,6,7,7,7,7])
</code></pre>
<p>What I want is to get two arrays to give count of each element:</p>
<pre><code>array([1,2,3,4,5,6,7])
array([1,1,1,1,3,1,4])
</code></pre>
<p>How can I do this without any for loops?</p>
| 0 | 2016-08-10T03:32:26Z | 38,863,932 | <pre><code>In [1043]: np.unique(np.array([1,1,2,3,4,5,5,5,6,7,7,7,7]),return_counts=True)
Out[1043]: (array([1, 2, 3, 4, 5, 6, 7]), array([2, 1, 1, 1, 3, 1, 4]))
</code></pre>
| 6 | 2016-08-10T03:53:11Z | [
"python",
"numpy",
"vectorization"
] |
quick sort recursion error | 38,863,810 | <p>My thoughts:
i'm trying to implement quick sort with python.
i set the first element as pivot.
if the element of left mark is larger than pivot then i start moving the right mark to find an element smaller than pivot and then swap.
if right mark is smaller than left mark, swap pivot with the element of right mark.
t... | 1 | 2016-08-10T03:37:08Z | 38,863,954 | <p>You are slicing the list wrong. You should replace <code>lst[0:j+1]</code> to <code>lst[ : j ]</code> and <code>lst[i:len(lst)+1]</code> to <code>lst[ j + 1 : ]</code>, since the pivot is at position <code>j</code>and you should ignore it (here, the emptiness before <code>:</code> represent <code>from the start</cod... | 0 | 2016-08-10T03:55:41Z | [
"python",
"recursion"
] |
quick sort recursion error | 38,863,810 | <p>My thoughts:
i'm trying to implement quick sort with python.
i set the first element as pivot.
if the element of left mark is larger than pivot then i start moving the right mark to find an element smaller than pivot and then swap.
if right mark is smaller than left mark, swap pivot with the element of right mark.
t... | 1 | 2016-08-10T03:37:08Z | 38,863,974 | <p>You may also use this for quick sort.</p>
<pre><code>import random
def qsort(a,start,end):
if(start >= end):
return a
pivot = a[random.randint(start,end)]
i,j = start,end
while(i <= j):
while(a[i] < pivot):
i+=1
while(a[j] > pivot):
j-=1
... | -2 | 2016-08-10T03:58:50Z | [
"python",
"recursion"
] |
Changing value in pandas dataframe is same row is present in another dataframe | 38,863,830 | <p>I have the foll. 2 pandas dataframes:</p>
<pre><code>df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14], 'col3' : [0,2,0,-1,0]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12], 'col6' : [20, 31, 12]})
</code></pre>
<p>How do I change the value in <code... | 2 | 2016-08-10T03:40:23Z | 38,864,490 | <p>If you merge two DataFrames on <code>col1</code> and <code>col2</code>, the resulting DataFrame will have rows where both DataFrames have the same value in those columns. However, pandas <a href="http://stackoverflow.com/questions/11976503/how-to-keep-index-when-using-pandas-merge">loses the index</a> when merging. ... | 2 | 2016-08-10T04:50:26Z | [
"python",
"pandas"
] |
Changing value in pandas dataframe is same row is present in another dataframe | 38,863,830 | <p>I have the foll. 2 pandas dataframes:</p>
<pre><code>df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14], 'col3' : [0,2,0,-1,0]})
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12], 'col6' : [20, 31, 12]})
</code></pre>
<p>How do I change the value in <code... | 2 | 2016-08-10T03:40:23Z | 38,866,884 | <p>A quick numpy solution. <code>i</code> gets indices for every combination of one row from <code>df1</code> and another row from <code>df2</code>. I use the <code>==</code> to determine which cells are equal. <code>all(2)</code> determines if all cells from one row equal all cells from the other row. If true, the... | 2 | 2016-08-10T07:30:05Z | [
"python",
"pandas"
] |
Method to generate an array of datetimes in python | 38,863,887 | <p>I am trying to come up with a method to generate a set of timestamps 15 minutes every hours, 8 hours per day for the last month. My approach is top-down, first generate the days and then use these candidates to generate 8 children-timestamps for every day and then finally generate 4 grandchildren-timestamps for ever... | 0 | 2016-08-10T03:48:54Z | 38,884,619 | <p>How about something like this:</p>
<pre><code>first = datetime(2016, 8, 1, 8, 0, 0)
dates = [first]
for days in range(1, 31): # How many days.
for _ in range(8 * 4): # 8 hours, 4x 15 min intervals per hour
dates.append(dates[-1] + timedelta(minutes = 15))
dates.append(dates[0] + timedelta(days = days))
</co... | 1 | 2016-08-10T22:33:39Z | [
"python",
"datetime",
"date-range"
] |
How to file open with different filename using python ftplib | 38,863,906 | <p>My current python code:</p>
<pre><code>import ftplib
import hashlib
import urllib
def ftp():
hashing="123"
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
file = open('Desktop/test.png','rb')
m.update(hashing)
dd = m.hexdigest()
ftp.storbinary('ST... | -1 | 2016-08-10T03:50:44Z | 38,864,146 | <p>How about this? Use glob to find the files, then loop over the list from glob running ftp() on each file?</p>
<pre><code>import ftplib
import hashlib
import urllib
from glob import glob
def ftp(filename):
hashing="123"
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=ha... | 0 | 2016-08-10T04:18:46Z | [
"python",
"python-2.7",
"ftp"
] |
How to file open with different filename using python ftplib | 38,863,906 | <p>My current python code:</p>
<pre><code>import ftplib
import hashlib
import urllib
def ftp():
hashing="123"
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
m=hashlib.md5()
file = open('Desktop/test.png','rb')
m.update(hashing)
dd = m.hexdigest()
ftp.storbinary('ST... | -1 | 2016-08-10T03:50:44Z | 38,864,375 | <p>Try this version instead:</p>
<pre><code>import os
import ftplib
import hashlib
import glob
image_directory = '/home/Desktop/images/'
hashing = "123"
m = hashlib.md5()
m.update(hashing)
dd = m.hexdigest()
ftp = ftplib.FTP('localhost','kevin403','S$ip1234')
ftp.cwd('/var/www/html/image')
for image in glob.iglob(... | 1 | 2016-08-10T04:38:38Z | [
"python",
"python-2.7",
"ftp"
] |
Choosing python data structures to speed up algorithm implementation | 38,863,940 | <p>So I'm given a large collection (roughly 200k) of lists. Each contains a subset of the numbers 0 through 27. I want to return two of the lists where the product of their lengths is greater than the product of the lengths of any other pair of lists. There's another condition, namely that the lists have no numbers ... | 2 | 2016-08-10T03:53:59Z | 38,864,174 | <p>This is a bit too long for a comment so I will post it as an answer. One more direct way to index your subsets as integers is to use "bitsets" with each bit in the binary representation corresponding to one of the numbers.</p>
<p>For example, the set {0,2,3} would be represented by 2<sup>0</sup> + 2<sup>2</sup> + 2... | 1 | 2016-08-10T04:21:32Z | [
"python",
"algorithm",
"performance",
"optimization",
"data-structures"
] |
Choosing python data structures to speed up algorithm implementation | 38,863,940 | <p>So I'm given a large collection (roughly 200k) of lists. Each contains a subset of the numbers 0 through 27. I want to return two of the lists where the product of their lengths is greater than the product of the lengths of any other pair of lists. There's another condition, namely that the lists have no numbers ... | 2 | 2016-08-10T03:53:59Z | 38,864,815 | <p>Given that your indexes are just ints, you could save some time and space by using lists instead of dicts. I'd go further and bring in <a href="http://www.numpy.org/" rel="nofollow">NumPy</a> arrays. They offer compact storage representation and efficient operations that let you implicitly perform repetitive work in... | 2 | 2016-08-10T05:19:41Z | [
"python",
"algorithm",
"performance",
"optimization",
"data-structures"
] |
Error in code in python | 38,863,959 | <pre><code>data=open('D:\\e.txt','r',encoding='utf-8')
x= data.readlines()
tw= x.split(',"text":" ')[1].split('","source')[0]
</code></pre>
<p>i have problem </p>
<pre><code>AttributeError: 'list' object has no attribute 'split'
</code></pre>
| 0 | 2016-08-10T03:56:11Z | 38,865,544 | <p><code>readlines()</code> returns a list of all the lines in a file. Whereas split() is a string method. As @inspectorG4dget suggested if you want to use <code>split()</code>, use <code>read()</code> which returns the contents of a file as string.</p>
<pre><code>data=open('D:\\file_path','r')
x= data.read()
tw= x.sp... | 0 | 2016-08-10T06:14:02Z | [
"python"
] |
How to understand logging formatter? | 38,863,988 | <p>To Python Experts:</p>
<p>I'm new to programming and learning logging python package. </p>
<p>According to logging document, I set the format of my logging message as follows:</p>
<pre><code>logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
</code></pre>
<p>Here is the ... | 0 | 2016-08-10T04:00:39Z | 38,864,057 | <p>For your first question:</p>
<p>Just add an extra newline to your call of <code>logging.debug</code>:</p>
<p>For example, if your logger is called <code>logger</code>, and you are logging the message through <code>logging.debug(msg)</code>, you can call <code>logging.debug('\n' + msg</code>) to move the message on... | 1 | 2016-08-10T04:08:56Z | [
"python",
"logging"
] |
Creating an instance of a class existing in a different file(python) | 38,864,032 | <p>I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)</p>
<p>main.py</p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an in... | 0 | 2016-08-10T04:06:10Z | 38,864,266 | <p>Drop the <code>import main</code> in player.py and change the last line in main.py to:</p>
<pre><code>p1 = player.hero("woody.png",[2,2])
</code></pre>
<p><strong>Edit:</strong>
Python does not know what class/function <code>hero</code> is. It needs you to tell it hero is a class in the player module. And that's w... | 0 | 2016-08-10T04:29:25Z | [
"python",
"python-2.7",
"oop"
] |
Creating an instance of a class existing in a different file(python) | 38,864,032 | <p>I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)</p>
<p>main.py</p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an in... | 0 | 2016-08-10T04:06:10Z | 38,864,284 | <p>Like Athena said above, don't import <code>main</code> into <code>player</code> and <code>player</code> into <code>main</code>. This causes a import loop. Just simply import <code>player</code> into <code>main</code></p>
<p>Secondly, you must say <code>player.hero()</code> if you want to use the class <code>hero</c... | 0 | 2016-08-10T04:30:52Z | [
"python",
"python-2.7",
"oop"
] |
Creating an instance of a class existing in a different file(python) | 38,864,032 | <p>I am trying to learn how to change my programs so that they use code from multiple python scripts. I have two scripts (these are big files, so cutting them down to only what's needed)</p>
<p>main.py</p>
<pre><code>import pygame
import player #Imports the player.py script
p1 = hero("woody.png",[2,2]) #Creates an in... | 0 | 2016-08-10T04:06:10Z | 38,864,322 | <ol>
<li><p>To import <code>hero</code> from another module, you should write <code>player.hero</code>, or simply <code>from player import hero</code>.</p></li>
<li><p>Importing <code>player</code> in <code>main</code> and <code>main</code> in <code>player</code> would cause "circular references".</p></li>
</ol>
<hr>
... | 1 | 2016-08-10T04:33:47Z | [
"python",
"python-2.7",
"oop"
] |
How to call a function that is later in a Python script? | 38,864,080 | <p>I am currently learning Python for some penetration testing and was practicing making password cracking scripts. While I was making a script for a telnet pass cracker I ran into a problem with some of the functionality of it. While trying to allow the user to output the findings, as well as some extra information,... | 0 | 2016-08-10T04:10:57Z | 38,864,117 | <p>Move the function to the top level of the script. Don't nest it inside of an if statement inside of a loop. </p>
<p>There's no need to redefine a function in a loop (and defining it in a conditional doesn't seem good either)</p>
<blockquote>
<p>a function has to be written above where it is called</p>
</blockquo... | 2 | 2016-08-10T04:15:50Z | [
"python",
"scripting",
"telnet",
"penetration-testing"
] |
How to call a function that is later in a Python script? | 38,864,080 | <p>I am currently learning Python for some penetration testing and was practicing making password cracking scripts. While I was making a script for a telnet pass cracker I ran into a problem with some of the functionality of it. While trying to allow the user to output the findings, as well as some extra information,... | 0 | 2016-08-10T04:10:57Z | 38,864,191 | <p>Python is a dynamic language, but requires functions at the top-level to be resolved by interpretation time.</p>
<p>Just move the function to the top and call it later, or nest it within a function. </p>
<p>For example, this <strong>will not</strong> work:</p>
<pre><code>x()
def x():
pass
</code></pre>
<p>T... | 0 | 2016-08-10T04:22:59Z | [
"python",
"scripting",
"telnet",
"penetration-testing"
] |
create a third list by combining values in two lists | 38,864,103 | <p>I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get th... | 1 | 2016-08-10T04:13:54Z | 38,864,206 | <p>Use a <code>dict</code>, with the charity number as the key. You simply add the donation to the corresponding <code>dict</code> value. If the <code>dict</code> element doesn't exist yet, set it to zero as its initial value.
I'm using <code>defaultdict</code>: the <code>lambda: 0</code> argument will guarantee a zero... | 2 | 2016-08-10T04:24:02Z | [
"python",
"list"
] |
create a third list by combining values in two lists | 38,864,103 | <p>I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get th... | 1 | 2016-08-10T04:13:54Z | 38,864,231 | <p>This seems a good example to use the <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">zip</a> function. It gets two lists as argument (in your case the <code>donlist</code> and <code>charlist</code>) and creates an iterator of these, so you can iterate one time adding the values from <co... | 1 | 2016-08-10T04:26:09Z | [
"python",
"list"
] |
create a third list by combining values in two lists | 38,864,103 | <p>I have to two arrays (in my code below): "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I need to create a third array using the total donations for each charity. So if charity #3 appears 8 times in "charlist", I have to get th... | 1 | 2016-08-10T04:13:54Z | 38,864,690 | <pre><code>>>> l1 = [1,1,3,4] # charity list
>>> l2 = [5,6,7,8] # donation list
>>> zip(l1,l2)
[(1, 5), (1, 6), (3, 7), (4, 8)]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for k,v in zip(l1,l2):
... d[k] += v
...
>>> d
defaultdi... | 0 | 2016-08-10T05:09:57Z | [
"python",
"list"
] |
pymysql inserting random numbers into a column using python | 38,864,144 | <p>I want to insert random numbers to a MySQL column <code>rnd_value</code> with 100 random numbers including and between 1 to 100 using python.</p>
<p>I will generate random numbers from python using </p>
<pre><code>random.randrange(1,100)
</code></pre>
<p>I have added MYSQL query to the database </p>
<pre><code> ... | 0 | 2016-08-10T04:18:13Z | 38,864,471 | <p>How about this simple approach? Connect to the db (assuming localhost and database name is exercise). Then shove the 100 values in 1 by 1? </p>
<pre><code>import pymysql
import random
with pymysql.connect(host='localhost', db='exercise') as db:
for i in random.randrange(1,100):
qry = "INSERT INTO random_v... | 1 | 2016-08-10T04:48:09Z | [
"python",
"mysql",
"random",
"pymysql"
] |
pymysql inserting random numbers into a column using python | 38,864,144 | <p>I want to insert random numbers to a MySQL column <code>rnd_value</code> with 100 random numbers including and between 1 to 100 using python.</p>
<p>I will generate random numbers from python using </p>
<pre><code>random.randrange(1,100)
</code></pre>
<p>I have added MYSQL query to the database </p>
<pre><code> ... | 0 | 2016-08-10T04:18:13Z | 38,864,508 | <p>referred some portions from:
<a href="http://stackoverflow.com/questions/20485332/pymysql-insert-into-not-working">Pymysql Insert Into not working</a></p>
<h3>install pymysql</h3>
<pre><code>pip install pymysql
</code></pre>
<h3>in mysql</h3>
<pre><code>CREATE TABLE `t1` (`c1` INT NULL,`c2` INT NULL )
</code></p... | 0 | 2016-08-10T04:51:46Z | [
"python",
"mysql",
"random",
"pymysql"
] |
pymysql inserting random numbers into a column using python | 38,864,144 | <p>I want to insert random numbers to a MySQL column <code>rnd_value</code> with 100 random numbers including and between 1 to 100 using python.</p>
<p>I will generate random numbers from python using </p>
<pre><code>random.randrange(1,100)
</code></pre>
<p>I have added MYSQL query to the database </p>
<pre><code> ... | 0 | 2016-08-10T04:18:13Z | 38,865,142 | <p>Thanks for all the responses, this code seems to work for me,</p>
<pre><code>import pymysql
import random
connection=pymysql.connect(host='localhost',user='root',password='server',
db='exercise',charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try... | 0 | 2016-08-10T05:46:21Z | [
"python",
"mysql",
"random",
"pymysql"
] |
Splitting a network into subnets of multiple prefixes | 38,864,268 | <p>I'm using the <code>netaddr</code> module and trying to figure out how/if I can split a network into subnets of varying prefixes. For example take a /16 and split it into X /23s and Y /24s. </p>
<p>From what I can tell we can use the <code>subnet</code> function to split a network in X number of a given prefix but ... | 4 | 2016-08-10T04:29:36Z | 38,865,810 | <p>Try the below </p>
<pre><code>from netaddr import IPNetwork, cidr_merge, cidr_exclude
class IPSplitter(object):
def __init__(self, base_range):
self.avail_ranges = set((IPNetwork(base_range),))
def get_subnet(self, prefix, count=None):
for ip_network in self.get_available_ranges():
... | 3 | 2016-08-10T06:29:41Z | [
"python",
"python-2.7",
"networking"
] |
Splitting a network into subnets of multiple prefixes | 38,864,268 | <p>I'm using the <code>netaddr</code> module and trying to figure out how/if I can split a network into subnets of varying prefixes. For example take a /16 and split it into X /23s and Y /24s. </p>
<p>From what I can tell we can use the <code>subnet</code> function to split a network in X number of a given prefix but ... | 4 | 2016-08-10T04:29:36Z | 38,876,316 | <p>In my case the prefixes aren't completely arbitrary and they'll always result in an even split. For example for a /24 I'll always ask for 6 /27s and 4 /28s and in a /23 I'll always ask for 2 /25s, 2 /26s, 2 /27s and 4 /28s and I'll always be starting with either a /24 or /23 so the scheme is fairly predictable. </p>... | 1 | 2016-08-10T14:31:15Z | [
"python",
"python-2.7",
"networking"
] |
Splitting a network into subnets of multiple prefixes | 38,864,268 | <p>I'm using the <code>netaddr</code> module and trying to figure out how/if I can split a network into subnets of varying prefixes. For example take a /16 and split it into X /23s and Y /24s. </p>
<p>From what I can tell we can use the <code>subnet</code> function to split a network in X number of a given prefix but ... | 4 | 2016-08-10T04:29:36Z | 38,933,612 | <p>You could first split it into a number of <code>/23</code> and then split a certain number of those into the number of <code>/24</code> you want. Quick example code off the top of my head.</p>
<pre><code>>>> from netaddr import *
>>> ip = IPNetwork('172.24.0.0/16')
>>> subnet_23 = list(ip... | 1 | 2016-08-13T14:17:22Z | [
"python",
"python-2.7",
"networking"
] |
Connect to local bluetooth | 38,864,366 | <p>I am using pybluez to develop a bluetooth application on linux in python. I want to know if it is possible to connect to a "localhost" for bluetooth so I can run the client and server on the same machine (as most people do for web development).</p>
<p>If this is not possible, how to most people develop bluetooth ap... | 0 | 2016-08-10T04:38:07Z | 38,886,021 | <p>Through further research I have found that it is not possible to run a bluetooth client and server on the same device with the same bluetooth adapter. For local testing you can either use two bluetooth enabled computers or get a bluetooth dongle.</p>
| 0 | 2016-08-11T01:42:27Z | [
"python",
"bluetooth",
"pybluez"
] |
Conditional cumsum based on column | 38,864,592 | <p>Given the following dataframe, how do I generate a conditional cumulative sum column.</p>
<pre><code>import pandas as pd
import numpy as np
data = {'D':[2015,2015,2015,2015,2016,2016,2016,2017,2017,2017], 'Q':np.arange(10)}
df = pd.DataFrame(data)
D Q
0 2015 0
1 2015 1
2 2015 2
3 ... | 1 | 2016-08-10T05:01:09Z | 38,864,639 | <pre><code>>>> df['Q_cum'] = df.groupby('D').cumsum()
>>> df
D Q Q_cum
0 2015 0 0
1 2015 1 1
2 2015 2 3
3 2015 3 6
4 2016 4 4
5 2016 5 9
6 2016 6 15
7 2017 7 7
8 2017 8 15
9 2017 9 24
</code></pre>
<p>As @Ayhan said, If you wa... | 2 | 2016-08-10T05:05:40Z | [
"python",
"pandas",
"numpy"
] |
Pycharm not showing inherited fields of base class in django 1.10 | 38,864,604 | <p>I am using pycharm for my project, and I have created a core folder such that, it host all the abstract models, such that</p>
<pre><code>class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstra... | 1 | 2016-08-10T05:02:16Z | 38,875,234 | <p>Man you imported <code>TimeStampedModel</code>. But I didn't find your <code>models</code>. Where did you import? if your <code>models</code> inside <code>TimeStampedModel</code> then, import like that,</p>
<p><code>from ..core.TimeStampedModel import models</code> or</p>
<p><code>from ..core import TimeStampedMod... | 0 | 2016-08-10T13:45:08Z | [
"python",
"django",
"pycharm"
] |
The current URL did not match any of these, include() giving problems | 38,864,608 | <p>I decided to make a <code>urls.py</code> for each app. However I am running into problems when I <code>include</code> the urls. I do not know what is the problem as I have done everything right. My site has the same structure as the Django 1.9 tutorial. I have <code>template</code> folder at the root, and also a <co... | 0 | 2016-08-10T05:02:47Z | 38,866,500 | <p>You seem to be going to just /profile, but you don't have that defined as a URL, you have /myapp/profile.</p>
| 0 | 2016-08-10T07:10:39Z | [
"python",
"django",
"django-views",
"django-urls"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. ... | 12 | 2016-08-10T05:11:53Z | 38,913,757 | <p>You could try setting the affinity mask to make sure each process runs on a different core. I use this on windows 7. </p>
<pre><code>def setaffinity(mask = 128): # 128 is core 7
pid = win32api.GetCurrentProcessId()
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
win32process.Se... | -2 | 2016-08-12T08:48:26Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. ... | 12 | 2016-08-10T05:11:53Z | 38,915,996 | <blockquote>
<p>I want my program to read in images from a video stream in the main process</p>
</blockquote>
<p>In producer/consumer implementations, which is what you have above, the producer, what puts tasks into the queue to be executed by the consumers, needs to be separate from the main/controlling process so ... | 7 | 2016-08-12T10:40:54Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. ... | 12 | 2016-08-10T05:11:53Z | 38,953,909 | <p>(Updated solution based on you last code sample)</p>
<p>It will get images from the stream, put one in the task queue as soon as it is available, and display the last image with the last text.</p>
<p>I put some active loop in there to simulate a processing longer than the time between two images.
I means that the ... | 2 | 2016-08-15T11:06:20Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. ... | 12 | 2016-08-10T05:11:53Z | 38,963,942 | <p>Let me suggest you a slightly different approach, with a lot less "red tape". I think the main problem is that you are overlooking the main way to communicate with a process: it is through its arguments and return values. If you can send the frame data as an argument, there is no need of queues or pipes or other met... | 1 | 2016-08-15T22:23:59Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. ... | 12 | 2016-08-10T05:11:53Z | 38,985,343 | <p>After reading your comment to my previous answer, I understood your problem a 'bit' better. I would like to have more information about your code/problem. Anyway, and because this code is significantly different than my previous answer, I decided to provide another answer. I won't comment the code too much though, b... | 1 | 2016-08-16T22:16:22Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
How to optimize multiprocessing in Python | 38,864,711 | <p><em>EDIT:
I've had questions about what the video stream is, so I will offer more clarity. The stream is a live video feed from my webcam, accessed via OpenCV. I get each frame as the camera reads it, and send it to a separate process for processing. The process returns text based on computations done on the image. ... | 12 | 2016-08-10T05:11:53Z | 39,001,345 | <p>Here's a more elegant (IMHO) solution that utilizes multiple processes for processing your frames:</p>
<pre><code>def process_image(args):
image, frame = args
#Do computations on image
return "text", frame
import cv2
pool = multiprocessing.Pool()
def image_source():
#Creating window and starting ... | 2 | 2016-08-17T15:59:37Z | [
"python",
"multithreading",
"python-2.7",
"queue",
"multiprocessing"
] |
Python Tkinter StringVar only displaying Py_Var(number) | 38,864,986 | <p>I am using Tkinter in python 3.4 to make a text based game, and I cannot figure out how to get a string from an Entry widget, it just returns <code>Py_Var#</code>, # being a number. I have looked at answers to similar questions, but none of them quite line up with what I need and have. Here's the relevant pieces of ... | 0 | 2016-08-10T05:34:42Z | 38,865,088 | <p>You have two mistakes in <code>SubmitName()</code>.</p>
<p>First, you need to get the text like this:</p>
<pre><code>txt = playername.get()
</code></pre>
<p>Then you need to print that <code>txt</code>:</p>
<pre><code>print(txt)
</code></pre>
<p>By mistake you printed the <code>StringVar</code> variable itself.... | 2 | 2016-08-10T05:42:52Z | [
"python",
"tkinter",
"entry"
] |
Python Tkinter StringVar only displaying Py_Var(number) | 38,864,986 | <p>I am using Tkinter in python 3.4 to make a text based game, and I cannot figure out how to get a string from an Entry widget, it just returns <code>Py_Var#</code>, # being a number. I have looked at answers to similar questions, but none of them quite line up with what I need and have. Here's the relevant pieces of ... | 0 | 2016-08-10T05:34:42Z | 38,865,346 | <pre><code>from tkinter import *
import pickle
win = Tk()
win.geometry("787x600")
def SubmitName():
playername = entry1.get()
messagebox.showinfo("Success", playername)
print(playername)
frame3 = Frame(win)
frame3.grid()
label1 = Label(frame3, text="You awaken in a room, with no memories of y... | 0 | 2016-08-10T06:00:54Z | [
"python",
"tkinter",
"entry"
] |
Is `await` in Python3 Cooperative Multitasking? | 38,865,050 | <p>I am trying to understand the new <a href="https://docs.python.org/3/library/asyncio-task.html#example-chain-coroutines" rel="nofollow">await</a> coroutines (introduced in Python 3.5). </p>
<p>In 1997 I attended a course at university which roughly covered the content of the book <a href="https://en.wikipedia.org/w... | 2 | 2016-08-10T05:39:52Z | 38,865,200 | <blockquote>
<p>Inside a coroutine function, the await expression can be used to
suspend coroutine execution until the result is available. Any object
can be awaited, as long as it implements the awaitable protocol by
defining the <strong>await</strong>() method.</p>
</blockquote>
<p>A coroutine can pause exec... | 2 | 2016-08-10T05:50:06Z | [
"python",
"asynchronous",
"async-await",
"python-asyncio"
] |
Is `await` in Python3 Cooperative Multitasking? | 38,865,050 | <p>I am trying to understand the new <a href="https://docs.python.org/3/library/asyncio-task.html#example-chain-coroutines" rel="nofollow">await</a> coroutines (introduced in Python 3.5). </p>
<p>In 1997 I attended a course at university which roughly covered the content of the book <a href="https://en.wikipedia.org/w... | 2 | 2016-08-10T05:39:52Z | 38,953,375 | <p>Yes. According to <a href="https://en.wikipedia.org/wiki/Coroutine" rel="nofollow">Wikipedia</a>: </p>
<blockquote>
<p>Coroutines are computer program components that generalize subroutines for <strong>nonpreemptive multitasking</strong>, by allowing multiple entry points for suspending and resuming execution at ... | 0 | 2016-08-15T10:26:55Z | [
"python",
"asynchronous",
"async-await",
"python-asyncio"
] |
Is `await` in Python3 Cooperative Multitasking? | 38,865,050 | <p>I am trying to understand the new <a href="https://docs.python.org/3/library/asyncio-task.html#example-chain-coroutines" rel="nofollow">await</a> coroutines (introduced in Python 3.5). </p>
<p>In 1997 I attended a course at university which roughly covered the content of the book <a href="https://en.wikipedia.org/w... | 2 | 2016-08-10T05:39:52Z | 39,024,906 | <p>It is cooperative multitasking indeed.</p>
<p>What about a small program to prove it. Let's first sleep with cooperative <code>asyncio.sleep</code> for a second and then let's sleep with blocking <code>time.sleep</code> for a second. Let's print a thread id, time spent in the coroutine and id of a task.</p>
<pre><... | 1 | 2016-08-18T18:13:46Z | [
"python",
"asynchronous",
"async-await",
"python-asyncio"
] |
Exiting interactive python3 session from script | 38,865,080 | <p>I'd like my program to automatically exit if it detects an error when loading a file and parsing it (even when called from an interactive mode with -i). I've tried variations of <code>exit()</code> and <code>sys.exit()</code>, but nothing seems to be working. Instead of exiting the interactive session I get a stack ... | 1 | 2016-08-10T05:42:08Z | 38,866,028 | <p>Try calling <a href="https://docs.python.org/2/library/os.html#os._exit" rel="nofollow">os._exit()</a> to exit directly, without throwing an exception</p>
<pre><code>import os
os._exit(1)
</code></pre>
<p>Note that this will bypass all of the python shutdown logic.
Hope it helps.</p>
| 2 | 2016-08-10T06:41:54Z | [
"python"
] |
Python - getting the average of two dict lists? | 38,865,129 | <p>Here I have two lists: "donlist" is a list of random donation amounts between $1 and $100, and "charlist" is a list of random charity numbers between 1 and 15. I used two "dict"'s: "totals" to calculate the total donation per charity, and "numdon" to calculate the number of donations per charity. I now have to find... | 0 | 2016-08-10T05:45:39Z | 38,865,380 | <p>Solve your problem:</p>
<pre><code>avg = [totals[i] / numdon[i] for i in numdon]
</code></pre>
<p><strong>Reason</strong>:</p>
<p>In python list comprehension of a dict, the default iteration will be on the key of a dict. Try this:</p>
<pre><code>l = {1: 'a', 2: 'b'}
for i in l:
print(i)
# output:
# 1
# 2
<... | 3 | 2016-08-10T06:02:53Z | [
"python",
"arrays",
"dictionary",
"random"
] |
How to automate "pull-request creation" on GitHub? | 38,865,157 | <p>I have forked a rep from my organization's repo. </p>
<p>I am updating some files on regular basis and pushing changes to my forked repo.</p>
<p>Lets say: My organization repo URL is : X and my forked repo URL: Y</p>
<p>I know we can use "git pull-request" but I am not getting what exactly the command should be.... | 0 | 2016-08-10T05:47:26Z | 38,867,178 | <p><code>git request-pull [-p] <start> <url> [<end>]</code></p>
<p><a href="https://git-scm.com/docs/git-request-pull" rel="nofollow">https://git-scm.com/docs/git-request-pull</a></p>
| 0 | 2016-08-10T07:45:35Z | [
"java",
"python",
"git",
"github",
"version-control"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.