title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to use class that is returned through a function? | 38,425,634 | <p>If I have a class that generates items for a text-based RPG like so -- keep in mind this is a simplified version of the code I use:</p>
<pre><code>from random import choice, randint
class Weapon(object):
def __init__(self, name, value, damage):
self.name = name
self.value = value
self.d... | 0 | 2016-07-17T20:26:47Z | 38,425,659 | <p>your generate function returns a weapon. You just need to assign it (or store it directly).</p>
<p>e.g.</p>
<pre><code>generated_weapon = CreateWeapon.generate()
self.inventory['weapons'].append(generated_weapon)
</code></pre>
<p>or to store it directly</p>
<pre><code>self.inventory['weapons'].append(CreateWeap... | 0 | 2016-07-17T20:30:28Z | [
"python",
"python-2.7"
] |
How to make scrollbars appear in a wx.lib.scrolledpanel.ScrolledPanel which has no widgets but only a straight line? | 38,425,668 | <p>I create a wx.lib.scrolledpanel.ScrolledPanel. I insert it in its parent panel inside a vertical box sizer. Parent panel's size is width=500, height=500.</p>
<p>Then, in ScrolledPanel, I draw a vertical line with a height of 1000.
When I run the app, scrollbars are not displayed on ScrolledPanel. I just see my ver... | 0 | 2016-07-17T20:31:51Z | 38,432,128 | <p>As you have not pasted any 'real' code, it's difficult to know what you are doing wrong.<br>
Perhaps this will help:</p>
<pre><code>#!/bin/env python
import wx
import wx.lib.scrolledpanel as SP
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, - 1, "Frame", size=(300, 300))
... | 0 | 2016-07-18T08:39:04Z | [
"python",
"user-interface",
"wxpython",
"scrollbar"
] |
How to make scrollbars appear in a wx.lib.scrolledpanel.ScrolledPanel which has no widgets but only a straight line? | 38,425,668 | <p>I create a wx.lib.scrolledpanel.ScrolledPanel. I insert it in its parent panel inside a vertical box sizer. Parent panel's size is width=500, height=500.</p>
<p>Then, in ScrolledPanel, I draw a vertical line with a height of 1000.
When I run the app, scrollbars are not displayed on ScrolledPanel. I just see my ver... | 0 | 2016-07-17T20:31:51Z | 38,445,992 | <p>Since you don't have any widgets on the panel then a <code>ScrolledPanel</code> is not the best choice since it bases the virtual and physical sizes of the window on the space needed by the sizer. Using a <code>wx.ScrolledWindow</code> would be a better choice, as you can then control the virtual size yourself.</p>... | 0 | 2016-07-18T21:07:06Z | [
"python",
"user-interface",
"wxpython",
"scrollbar"
] |
Why is List[str] not a subclass of Sequence[str] | 38,425,756 | <p><code>List</code> is a subclass of <code>Sequence</code>:</p>
<pre><code>>>> from typing import List, Sequence
>>> issubclass(List, Sequence)
True
</code></pre>
<p>but <code>List[str]</code> is not a subclass of <code>Sequence[str]</code>:</p>
<pre><code>>>> issubclass(List[str], Sequen... | 8 | 2016-07-17T20:41:37Z | 38,427,123 | <blockquote>
<p>What use would an IS-A relationship between <code>List[str]</code> and <code>Sequence[str]</code> have when annotating?</p>
</blockquote>
<p>This is the major point to take away. Checking if a type is a subtype of another type is not generally something you should be doing while type annotating your ... | 1 | 2016-07-18T00:12:24Z | [
"python",
"python-3.x",
"type-hinting"
] |
Wrong output in implementing T9 dictionary in python | 38,425,775 | <p>I am trying to implement <code>T9</code> dictionary in <code>python</code>. I am using <code>Trie</code> to implement it. I have this code which creates a <code>Trie</code> from the words in the dictionary and then do a lookup for the pattern</p>
<pre><code>import string
PHONE_LETTERS = 'abcdefghijklmnopqrstuvwxyz... | 2 | 2016-07-17T20:43:46Z | 38,428,806 | <p>When you <code>map</code> your <code>append</code> function are you really meaning to map it over the <em>entire</em> <code>wlist</code> string?</p>
<p>If you call <code>translate</code> on the <code>wlist</code> string instead of each individual letter you get:</p>
<pre><code>hello
hess
home
abhi
busy
disturb
Wor... | 1 | 2016-07-18T04:55:09Z | [
"python",
"dictionary",
"trie",
"t9"
] |
Getting the opposite outputs from Tensorflow learn with OR gate | 38,425,785 | <p>Given the DNN (simple case of multilayered perceptron) with 2 hidden layers of 5 and 3 dimensions respectively, I am training a model to recognize the OR gate. </p>
<p>Using tensorflow learn, it seems like it's giving me the reverse output and I have no idea why:</p>
<pre><code>from tensorflow.contrib import learn... | 2 | 2016-07-17T20:45:06Z | 38,425,956 | <p>If you specify the right argument for <code>steps</code> you get the good results:</p>
<pre><code>classifier.fit(or_input, or_output, steps=1000, batch_size=3)
</code></pre>
<p>Result:</p>
<pre><code>array([1, 1, 0, 1])
</code></pre>
<hr>
<h3>How does <code>steps</code> work</h3>
<p>The <code>steps</code> argu... | 5 | 2016-07-17T21:10:53Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow",
"deep-learning"
] |
Reflecting sqlite database with spellfix1 tables | 38,425,835 | <p>I'm trying to reflect a database (more specifically the <a href="https://www.plex.tv/" rel="nofollow">plex media server database</a>) which is sqlite based.</p>
<p>I can connect to the DB:</p>
<pre><code>import sqlalchemy as sa
from sqlalchemy.orm import create_session
from sqlalchemy.ext.automap import automap_b... | 0 | 2016-07-17T20:52:50Z | 38,430,894 | <p>SQLite is an embedded database, and can be customized.
The Plex Media Server has added the spellfix1 extension; the <a href="http://www.sqlite.org/spellfix1.html" rel="nofollow">documentation</a> says:</p>
<blockquote>
<p>The spellfix1 virtual table is not included in the SQLite amalgamation and is not a part of ... | 1 | 2016-07-18T07:28:58Z | [
"python",
"sqlite",
"sqlalchemy"
] |
Reflecting sqlite database with spellfix1 tables | 38,425,835 | <p>I'm trying to reflect a database (more specifically the <a href="https://www.plex.tv/" rel="nofollow">plex media server database</a>) which is sqlite based.</p>
<p>I can connect to the DB:</p>
<pre><code>import sqlalchemy as sa
from sqlalchemy.orm import create_session
from sqlalchemy.ext.automap import automap_b... | 0 | 2016-07-17T20:52:50Z | 38,445,330 | <p>I found out a nice workaround.</p>
<p>SQLAlchemy allows metadata reflection to provide a callable for the 'only' flag.
This would ignore the unsupported tables that require the plugin. (thanks @CL. for the hint of ignoring those!) </p>
<pre><code>m = sa.MetaData(plex)
m.reflect(only=(lambda x, y: 'spellfix' not in... | 0 | 2016-07-18T20:19:07Z | [
"python",
"sqlite",
"sqlalchemy"
] |
How to colour data points on a 3D scatterplot in matplotlib | 38,425,883 | <p>Edit: I managed to figure out what was going on. Scatter has a parameter 'line-width' (lw=n) that determines the thickness of the line surrounding the plot point for a scatter plot. Because my plot points were size 1 (s=1), the line width was so thick it was actually covering the colour of the plot point. Setting th... | 0 | 2016-07-17T21:00:10Z | 38,426,271 | <p>You have to plot like here:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.random.rand(25)
y = np.random.rand(25)
z = np.random.rand(25)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
p3d = ax.scatter(x, y,... | 0 | 2016-07-17T21:50:52Z | [
"python",
"matplotlib",
"3d"
] |
'u' at the beginning of output (Sqlite, Python) | 38,425,900 | <p>I'm really confused about the sqlite part, where I print out my database, because I keep getting an 'u' at the beginning of every line, it doesn't have ' ' around though, which I assume is not accepted as a string? This only happens on this one programme (I tested it on other as well).</p>
<p>I checked the code man... | 0 | 2016-07-17T21:02:45Z | 38,425,929 | <p>The u' is basically syntax for 'this is unicode'. Use <code>str()</code> to get a string.</p>
<p>See: <a href="https://docs.python.org/2.7/tutorial/introduction.html#unicode-strings" rel="nofollow">Unicode Strings on the python docs</a></p>
| 0 | 2016-07-17T21:06:10Z | [
"python",
"sqlite"
] |
Python2 Pygame Installation Problems OS X | 38,425,915 | <p>At first I was getting an error of 'no module pygame', then I've installed pygame using pip and when I run my program I get this error:</p>
<pre><code>[1] 60751 illegal hardware instruction python pyman.py
[1] 1521 illegal hardware instruction python pyman.py
</code></pre>
<p>At first error I thought that ... | 2 | 2016-07-17T21:04:46Z | 38,427,140 | <p>Installing pygame is not straight forward in mac. Try these set of instructions:</p>
<p>Create and add the following to ~/.bash_profile:
# Homebrew binaries now take precedence over Apple defaults
export PATH=/usr/local/bin:$PATH</p>
<p>Install Apple Xcode command line tools:
xcode-select --install</p>
... | 2 | 2016-07-18T00:18:12Z | [
"python",
"osx",
"python-2.7",
"pygame"
] |
How to access a FREE variable of a function from outside | 38,425,922 | <p>Let's consider we have a function and an inner function like this (<strong>which we can not change</strong>):</p>
<pre><code>from functools import wraps
def outer_f(some_callable):
def inner_f(v):
return some_callable(v) + 1
return inner_f
</code></pre>
<p>And we only obtain a function 'func' which... | 2 | 2016-07-17T21:05:16Z | 38,425,944 | <p>You can do:</p>
<pre><code>import inspect
result = inspect.getclosurevars(func).nonlocals['some_callable']
</code></pre>
<p>Example:</p>
<pre><code>>>> from functools import wraps
>>>
>>> def outer_f(some_callable):
... def inner_f(v):
... return some_callable(v) + 1
... ... | 2 | 2016-07-17T21:09:31Z | [
"python",
"scope",
"traceback",
"inspect",
"free-variable"
] |
add labels to sklearn k-means | 38,425,990 | <p>I am trying to use kmeans in python.</p>
<pre><code>data = [[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]]
</code></pre>
<p>Each of this data have a label. Example:</p>
<pre><code>[1,2,3,4,5] -> Fiat1
[1,0,3,2,4] -> Fiat2
[4,3,234,5,5] -> Mercedes
[23,4,5,1,4] -> Opel
[23,5,2,3,5] -&... | 1 | 2016-07-17T21:15:01Z | 38,426,085 | <h3>Code</h3>
<pre><code>from sklearn.cluster import KMeans
import numpy as np
data = np.array([[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]])
labels = np.array(['Fiat1', 'Fiat2', 'Mercedes', 'Opel', 'BMW'])
N_CLUSTERS = 3
kmeans = KMeans(init='k-means++', n_clusters=N_CLUSTERS, n_init=10)
kmeans.... | 0 | 2016-07-17T21:25:56Z | [
"python",
"scikit-learn"
] |
add labels to sklearn k-means | 38,425,990 | <p>I am trying to use kmeans in python.</p>
<pre><code>data = [[1,2,3,4,5],[1,0,3,2,4],[4,3,234,5,5],[23,4,5,1,4],[23,5,2,3,5]]
</code></pre>
<p>Each of this data have a label. Example:</p>
<pre><code>[1,2,3,4,5] -> Fiat1
[1,0,3,2,4] -> Fiat2
[4,3,234,5,5] -> Mercedes
[23,4,5,1,4] -> Opel
[23,5,2,3,5] -&... | 1 | 2016-07-17T21:15:01Z | 38,426,123 | <p>If you put your labels in an array:</p>
<pre><code>labels=['Fiat1', 'Fiat2', 'Mercedes', 'Opel', 'bmw']
</code></pre>
<p>Then,</p>
<pre><code>n_clusters=3
pred_clusters=kmeans.fit(data).labels_
cluster_labels=[[] for i in range(n_clusters)]
for i, j in enumerate(pred_clusters):
cluster_labels[j].append(labels... | 0 | 2016-07-17T21:30:58Z | [
"python",
"scikit-learn"
] |
Python -- Issues with method as parameter? | 38,426,011 | <p>I am making a "Choose Your Adventure" game in Python. As you will see in the code below, I have a method temporarily called unnamedMethod that has three parameters: a method, m; a string, ans1; and another string, ans2. </p>
<p>This method is supposed to handle the user's input derived from m and check to see if ... | 2 | 2016-07-17T21:17:37Z | 38,426,083 | <p><code>g.intro()</code> returns a string, so all you need do is assign the returned value of the method which is passed as <code>m</code> to <code>ans</code>:</p>
<pre><code>ans = m
</code></pre>
<p>If you want <code>m</code> to be treated as callable, then consider passing <code>g.intro</code> instead:</p>
<pre><... | 4 | 2016-07-17T21:25:43Z | [
"python",
"methods",
"syntax",
"parameters"
] |
Python -- Issues with method as parameter? | 38,426,011 | <p>I am making a "Choose Your Adventure" game in Python. As you will see in the code below, I have a method temporarily called unnamedMethod that has three parameters: a method, m; a string, ans1; and another string, ans2. </p>
<p>This method is supposed to handle the user's input derived from m and check to see if ... | 2 | 2016-07-17T21:17:37Z | 38,426,091 | <p>You are using ans=m(), trying to call the string m as a function, when I think you mean to set the value of ans to that of m, which can be done with the code ans=m.</p>
| 0 | 2016-07-17T21:26:42Z | [
"python",
"methods",
"syntax",
"parameters"
] |
How can i do this using list comprehension? | 38,426,019 | <pre><code>a='abcdcdc'
list_=[x*3 for x in a]
print list_
</code></pre>
<p>This is printing this OK!!!! :</p>
<pre><code>['aaa', 'bbb', 'ccc', 'ddd', 'ccc', 'ddd', 'ccc']
</code></pre>
<p>But How can i print this ? :</p>
<pre><code>['abc','cdc','cdc']
</code></pre>
| 0 | 2016-07-17T21:18:17Z | 38,426,048 | <pre><code>[a[i]+a[i+1]+a[i+2] for i in range(0,len(a)-1,2)]
</code></pre>
| 0 | 2016-07-17T21:21:35Z | [
"python",
"python-2.7"
] |
How can i do this using list comprehension? | 38,426,019 | <pre><code>a='abcdcdc'
list_=[x*3 for x in a]
print list_
</code></pre>
<p>This is printing this OK!!!! :</p>
<pre><code>['aaa', 'bbb', 'ccc', 'ddd', 'ccc', 'ddd', 'ccc']
</code></pre>
<p>But How can i print this ? :</p>
<pre><code>['abc','cdc','cdc']
</code></pre>
| 0 | 2016-07-17T21:18:17Z | 38,426,049 | <p>You can use:</p>
<pre><code>>>> [a[i:i+3] for i in range(0,len(a) - 1,2)]
['abc', 'cdc', 'cdc']
</code></pre>
<p>This means <code>i</code> will get the following values:</p>
<pre><code>>>> list(range(0,len(a) - 1,2))
[0, 2, 4]
</code></pre>
<p>(as the list comprehension loops over <code>i</code... | 4 | 2016-07-17T21:21:44Z | [
"python",
"python-2.7"
] |
How can i do this using list comprehension? | 38,426,019 | <pre><code>a='abcdcdc'
list_=[x*3 for x in a]
print list_
</code></pre>
<p>This is printing this OK!!!! :</p>
<pre><code>['aaa', 'bbb', 'ccc', 'ddd', 'ccc', 'ddd', 'ccc']
</code></pre>
<p>But How can i print this ? :</p>
<pre><code>['abc','cdc','cdc']
</code></pre>
| 0 | 2016-07-17T21:18:17Z | 38,439,636 | <p>Using <code>list comprehension</code> here might actually be counter to the <em>zen of Python</em> ("simple is better than complex").</p>
<p>Though the other list comprehensions answers are correct, it takes a while to understand why they work.</p>
<p>On the other hand, a code like the following isn't hard to figu... | 0 | 2016-07-18T14:43:32Z | [
"python",
"python-2.7"
] |
String Mask in codeEval | 38,426,096 | <p><a href="https://www.codeeval.com/open_challenges/199/" rel="nofollow">https://www.codeeval.com/open_challenges/199/</a> here is description of an exercise. </p>
<p>It's my solution for me is correct, but in codeEval I have status 'Partially'. Maybe someone know what is wrong ?</p>
<pre><code>import sys
with ope... | 1 | 2016-07-17T21:27:24Z | 38,463,891 | <p>One big problem here is that when you need to uppercase a character based on its position in a string, you shouldn't be using replace, which in the way you are using it uppercases <em>all</em> occurrences of that character in the string, regardless of whether or not they are in positions that are supposed to be uppe... | 0 | 2016-07-19T16:25:25Z | [
"python",
"python-3.x"
] |
How to create a decision table for the following code | 38,426,105 | <p>I am attempting to create a decision table for a Triangle Classification Program, code shown below. <strong><em>UPDATE</em></strong></p>
<pre><code>def tritype(a, b, c):
if ((a ^ 2 + b ^ 2) == c^2):
return "Right Triangle"
if ((a + b) == c):
return "Isosceles Triangle"
if (a + b > c)... | 0 | 2016-07-17T21:28:22Z | 38,486,779 | <p>To generate a table similar to the one displayed above you simply need to use <code>\t</code> for spacing and some simple print commands.</p>
<pre><code>desc_table = [["C1", "A2 + B2 = C2"], ["C2", "A + B > C"]]
for entry in desc_table:
print(entry[0]+'\t'+entry[1])
</code></pre>
<p>To search for entries in... | 0 | 2016-07-20T17:12:16Z | [
"python",
"testing",
"decision-tree"
] |
Selenium Web-driver Click Button | 38,426,129 | <p>[Python 2.7, Selenium Web-driver]</p>
<p>So there's this Website:</p>
<pre><code><div class="flex-module-header">
<h3><span class="trend-location js-trend-location">Greece Trends</span></h3>
<span class="middot">·</span> <a role="button" href="#" data-modal="change-... | -2 | 2016-07-17T21:31:49Z | 38,427,896 | <p>As you didn't provide error stack trace and tried code, Assuming you didn't use <code>WebDriverWait</code> yet to wait until element visible and clickable. So I'm giving the example with this as below :-</p>
<pre><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWa... | 0 | 2016-07-18T02:42:53Z | [
"python",
"selenium"
] |
How to remove multiple columns that end with same text in Pandas? | 38,426,168 | <p>I'm trying to remove
a group of columns from a dataset. All of the variables to remove end with the text "prefix".</p>
<p>I did manage to "collect' them into a group using the following:
<a href="http://i.stack.imgur.com/w8AZ5.jpg"><img src="http://i.stack.imgur.com/w8AZ5.jpg" alt="enter image description here"></... | 5 | 2016-07-17T21:35:43Z | 38,426,183 | <p>I think you need:</p>
<pre><code>not_prefix_cols= [col for col in df.columns if not 'prefix' in col]
df2[not_prefix_cols]
</code></pre>
<p>But better is use:</p>
<pre><code>prefix_cols= [col for col in df.columns if not col.endswith('prefix')]
print (df[prefix_cols])
</code></pre>
<p>Sample:</p>
<pre><code>impo... | 4 | 2016-07-17T21:37:49Z | [
"python",
"pandas",
"dataframe"
] |
How to remove multiple columns that end with same text in Pandas? | 38,426,168 | <p>I'm trying to remove
a group of columns from a dataset. All of the variables to remove end with the text "prefix".</p>
<p>I did manage to "collect' them into a group using the following:
<a href="http://i.stack.imgur.com/w8AZ5.jpg"><img src="http://i.stack.imgur.com/w8AZ5.jpg" alt="enter image description here"></... | 5 | 2016-07-17T21:35:43Z | 38,426,188 | <pre><code>df2 = df.drop([col for col in df.columns if 'prefix' in col],axis=1)
</code></pre>
| 3 | 2016-07-17T21:38:10Z | [
"python",
"pandas",
"dataframe"
] |
How to remove multiple columns that end with same text in Pandas? | 38,426,168 | <p>I'm trying to remove
a group of columns from a dataset. All of the variables to remove end with the text "prefix".</p>
<p>I did manage to "collect' them into a group using the following:
<a href="http://i.stack.imgur.com/w8AZ5.jpg"><img src="http://i.stack.imgur.com/w8AZ5.jpg" alt="enter image description here"></... | 5 | 2016-07-17T21:35:43Z | 38,426,197 | <pre><code>df2 = df.ix[:, ~df.columns.str.endswith('prefix')]
</code></pre>
| 5 | 2016-07-17T21:40:32Z | [
"python",
"pandas",
"dataframe"
] |
How to remove multiple columns that end with same text in Pandas? | 38,426,168 | <p>I'm trying to remove
a group of columns from a dataset. All of the variables to remove end with the text "prefix".</p>
<p>I did manage to "collect' them into a group using the following:
<a href="http://i.stack.imgur.com/w8AZ5.jpg"><img src="http://i.stack.imgur.com/w8AZ5.jpg" alt="enter image description here"></... | 5 | 2016-07-17T21:35:43Z | 38,426,418 | <p>using <code>filter</code> and <code>regex</code></p>
<pre><code>df.filter(regex=r'^((?!prefix).)*$')
</code></pre>
<h3>Demo</h3>
<pre><code>df = pd.DataFrame(np.random.rand(2, 6),
columns=['oneprefix', 'one',
'twoprefix', 'two',
'threeprefix'... | 6 | 2016-07-17T22:11:16Z | [
"python",
"pandas",
"dataframe"
] |
How to remove multiple columns that end with same text in Pandas? | 38,426,168 | <p>I'm trying to remove
a group of columns from a dataset. All of the variables to remove end with the text "prefix".</p>
<p>I did manage to "collect' them into a group using the following:
<a href="http://i.stack.imgur.com/w8AZ5.jpg"><img src="http://i.stack.imgur.com/w8AZ5.jpg" alt="enter image description here"></... | 5 | 2016-07-17T21:35:43Z | 38,426,594 | <p>for the sake of completeness:</p>
<pre><code>In [306]: df
Out[306]:
prefixcol1 col2prefix col3prefix colN
0 1 1 1 1
1 2 2 2 2
2 3 3 3 3
In [307]: df.loc[:, ~df.columns.str.contains('prefix$')]
Out[307]:
p... | 5 | 2016-07-17T22:38:15Z | [
"python",
"pandas",
"dataframe"
] |
Can't send e-mail with attachement | 38,426,192 | <p>According to <a href="http://naelshiab.com/tutorial-send-email-python/" rel="nofollow">this article (section #V To send an email with attachment)</a>, I should be able to send an e-mail with attachement. However, I get the error, </p>
<pre><code> line 6, in <module>
from email.MIMEMultipart import MIMEMulti... | 0 | 2016-07-17T21:38:56Z | 38,426,204 | <p>The tutorial you're reading is for Python 2.x. In Python 3.x (which I assume is what you're using), I think you want this:</p>
<pre><code>from email.mime.multipart import MIMEMultipart
</code></pre>
<p>See also <a href="https://docs.python.org/3.5/library/email.mime.html" rel="nofollow">the email.mime documentatio... | 2 | 2016-07-17T21:41:49Z | [
"python",
"email"
] |
Python string to int for classification | 38,426,262 | <p>I am reading the book Machine Learning in Action. </p>
<p>One example in Chapter 2 converts string to int for classification use. For example, <code>'student' = 1, 'teacher' = 2, engineer = 3</code>.</p>
<p>See the code below in Line 12. While an error comes up while I execute it:</p>
<p>invalid literal for int()... | -1 | 2016-07-17T21:50:01Z | 38,426,413 | <p>You try to convert a string like "largeDose" to an int using the conversion function <code>int()</code>. But that's not how this works. The function <code>int()</code> converts only strings which look like integer numbers (e. g. <code>"123"</code>) to integers.</p>
<p>In your case you can use either an <code>if</... | 0 | 2016-07-17T22:10:28Z | [
"python"
] |
Deploy Pyramid Application on Elastic Beanstalk | 38,426,276 | <p>Does anyone have experience installing a <code>Pyramid</code> application via <code>Elastic Beanstalk</code>? My application deploys but I cannot configure the application's <code>application.py</code> (or <code>pyramid.wsgi</code>) file to work properly. Within <code>get_app</code> the following error occurs:</p>
... | 1 | 2016-07-17T21:52:24Z | 38,442,062 | <p>Thanks to a friend over on the "pylons-discuss" Google groups forum I now have a solution that works.</p>
<p>You will need to add a config command for your environment that runs the <code>setup.py develop</code> command. To do this, you will need to add a file to your .ebextensions folder named packages.config (or ... | 1 | 2016-07-18T16:47:29Z | [
"python",
"amazon-web-services",
"deployment",
"elastic-beanstalk",
"pyramid"
] |
mistake comparing datetime, python | 38,426,296 | <p>i wrote this code</p>
<pre><code>import time
import datetime
import os
import msvcrt as m
while True:
try:
os.system("cls")
delivery = input("Insert delivery date (dd/mm/aaaa): ")
dateDelivery = datetime.datetime.strptime(delivery, "%d%m%Y").strftime("%d/%m/%Y")
dateInput =... | 0 | 2016-07-17T21:55:22Z | 38,426,466 | <p>You're comparing between two dates converted to <strong>string</strong> type, so the comparation is lexicographic. You should use <strong>datetime</strong> type like this:</p>
<pre><code> dateDelivery = datetime.datetime.strptime(delivery,"%d%m%Y")
dateInput = datetime.datetime.now()
</code></pre>
<p>You ca... | 0 | 2016-07-17T22:18:44Z | [
"python",
"datetime"
] |
mistake comparing datetime, python | 38,426,296 | <p>i wrote this code</p>
<pre><code>import time
import datetime
import os
import msvcrt as m
while True:
try:
os.system("cls")
delivery = input("Insert delivery date (dd/mm/aaaa): ")
dateDelivery = datetime.datetime.strptime(delivery, "%d%m%Y").strftime("%d/%m/%Y")
dateInput =... | 0 | 2016-07-17T21:55:22Z | 38,426,474 | <p>Every time you obtain a datetime value, you covert it to a string using <code>strftime("%d/%m/%Y")</code>. So when you compare <code>dateDelivery</code> with <code>dateInput</code>, you are comparing two pieces of text, not datetime values.</p>
<p>When using a <code>dd-mm-yyyy</code> format, the ordering of text do... | 0 | 2016-07-17T22:20:18Z | [
"python",
"datetime"
] |
giving a name to a pandas dataframe? | 38,426,303 | <p>When I look to a pd df : </p>
<p><a href="http://i.stack.imgur.com/LTCFj.png" rel="nofollow"><img src="http://i.stack.imgur.com/LTCFj.png" alt="enter image description here"></a></p>
<p>I tell myself I would like to fill the upper left empty space by a dataframe name. Is that possible ? </p>
<p>(Here it would be ... | 2 | 2016-07-17T21:56:22Z | 38,426,333 | <p>It is possible if set columns names:</p>
<pre><code>df.columns.name = 'text'
</code></pre>
<p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p>
<pre><code>df = df.rename_axis('t... | 2 | 2016-07-17T22:00:06Z | [
"python",
"pandas"
] |
Fill an image with pre-defined pattern with Wand | 38,426,318 | <p>I have an image (like that: <a href="http://i.stack.imgur.com/bcu7J.png" rel="nofollow">mask</a>) and two integers, which represents a final image width & height. According to Wand's documentation <a href="http://docs.wand-py.org/en/0.4.3/guide/read.html#open-an-empty-image" rel="nofollow">Open empty image</a>:<... | 1 | 2016-07-17T21:58:22Z | 38,426,682 | <p>Well, after looking on ImageMagick's Composite <a href="https://github.com/ImageMagick/ImageMagick/blob/df0b2915c254e43ac809a58d5bba39e57d16012e/MagickWand/composite.c#L192" rel="nofollow">source code</a> itself, it became clear, that the Wand-driven solution should look like:</p>
<pre><code>with Image(width=x, hei... | 2 | 2016-07-17T22:55:58Z | [
"python",
"imagemagick",
"composite",
"wand"
] |
Fill an image with pre-defined pattern with Wand | 38,426,318 | <p>I have an image (like that: <a href="http://i.stack.imgur.com/bcu7J.png" rel="nofollow">mask</a>) and two integers, which represents a final image width & height. According to Wand's documentation <a href="http://docs.wand-py.org/en/0.4.3/guide/read.html#open-an-empty-image" rel="nofollow">Open empty image</a>:<... | 1 | 2016-07-17T21:58:22Z | 38,438,808 | <p>Building out the title iterator is <a href="http://stackoverflow.com/a/38426682/438117">the best solution</a> in my opinion. However another <em>hackish</em> method would be to invoke the <code>tile:</code> protocol, and allow the internal ImageMagick methods to handle composites. You'll lose the control inherited b... | 0 | 2016-07-18T14:05:27Z | [
"python",
"imagemagick",
"composite",
"wand"
] |
How to create random orthonormal matrix in python numpy | 38,426,349 | <p>Is there a method that I can call to create a random orthonormal matrix in python? Possibly using numpy? Or is there a way to create a orthonormal matrix using multiple numpy methods? Thanks.</p>
| 4 | 2016-07-17T22:01:23Z | 38,426,572 | <p>Version 0.18 of scipy--currently out as a release candidate, but not yet offically released--has <a href="http://scipy.github.io/devdocs/generated/scipy.stats.ortho_group.html" rel="nofollow"><code>scipy.stats.ortho_group</code></a> and <a href="http://scipy.github.io/devdocs/generated/scipy.stats.special_ortho_grou... | 5 | 2016-07-17T22:35:39Z | [
"python",
"numpy",
"linear-algebra",
"orthogonal"
] |
How to create random orthonormal matrix in python numpy | 38,426,349 | <p>Is there a method that I can call to create a random orthonormal matrix in python? Possibly using numpy? Or is there a way to create a orthonormal matrix using multiple numpy methods? Thanks.</p>
| 4 | 2016-07-17T22:01:23Z | 38,426,785 | <p>This is the <code>rvs</code> method pulled from the <a href="https://github.com/scipy/scipy/pull/5622/files" rel="nofollow">https://github.com/scipy/scipy/pull/5622/files</a>, with minimal change - just enough to run as a stand alone numpy function.</p>
<pre><code>def rvs(dim=3):
random_state = np.random
... | 1 | 2016-07-17T23:10:44Z | [
"python",
"numpy",
"linear-algebra",
"orthogonal"
] |
How to create random orthonormal matrix in python numpy | 38,426,349 | <p>Is there a method that I can call to create a random orthonormal matrix in python? Possibly using numpy? Or is there a way to create a orthonormal matrix using multiple numpy methods? Thanks.</p>
| 4 | 2016-07-17T22:01:23Z | 38,430,739 | <p>You can obtain a random <code>n x n</code> orthogonal matrix <code>Q</code>, (uniformly distributed over the manifold of <code>n x n</code> orthogonal matrices) by performing a <code>QR</code> factorization of an <code>n x n</code> matrix with elements i.i.d. Gaussian random variables of mean <code>0</code> and vari... | 0 | 2016-07-18T07:21:00Z | [
"python",
"numpy",
"linear-algebra",
"orthogonal"
] |
Filling in a completely empty list of lists in an arbitrary order | 38,426,359 | <p>I am trying to fill an <code>NxN</code> list of lists in python. In a way that if seen as a 2D array, first the main diagonal is filled and then other operations are done with other elements (not relevant here). So for example if we have <code>dyn_arr=[[[], [], []], [[], [], []], [[], [], []]]</code> in the beginnin... | 0 | 2016-07-17T22:02:18Z | 38,426,549 | <p>Be careful when creating lists using the multiplication operator. This way will multiply the <em>references</em> to the objects in the list; it will not create copies! So, if you create a list of lists using <code>a = [[]] * 3</code>, this will create a list of three elements which are all the same empty array. C... | 1 | 2016-07-17T22:31:43Z | [
"python",
"list"
] |
Filling in a completely empty list of lists in an arbitrary order | 38,426,359 | <p>I am trying to fill an <code>NxN</code> list of lists in python. In a way that if seen as a 2D array, first the main diagonal is filled and then other operations are done with other elements (not relevant here). So for example if we have <code>dyn_arr=[[[], [], []], [[], [], []], [[], [], []]]</code> in the beginnin... | 0 | 2016-07-17T22:02:18Z | 38,426,561 | <pre><code>import numpy as np
N = 3
z = np.zeros((N,N))
rng = np.arange(N)
z[rng, rng] = 1
print z
</code></pre>
<p>I hope this helps
:)</p>
| 0 | 2016-07-17T22:33:35Z | [
"python",
"list"
] |
Why there are more python processes than the number of cores in Spark? | 38,426,368 | <p>I am running a pyspark job in ipython console. I set spark master as <code>local[4]</code>. So I expect one core for the driver, which should be a Java process, and the other three cores each runs a Python process. However, this the the screen shot of my <code>top</code>, </p>
<p><a href="http://i.stack.imgur.com/b... | 1 | 2016-07-17T22:03:36Z | 38,439,060 | <p>Take a look at <a href="http://spark.apache.org/docs/latest/cluster-overview.html#components" rel="nofollow">here</a> if you haven't done so.</p>
<p>You have decided to use four workers, each with one executor by default. However, one executor is running a few tasks, each of which is a python process.</p>
<p>An ex... | 0 | 2016-07-18T14:18:12Z | [
"python",
"apache-spark",
"ipython",
"pyspark"
] |
Splitting a 1-d numpy array from tdms file, and plot shorter time series/intervalls from the original array | 38,426,385 | <p>Need help to pull out a spesific intervall from a 1-d numpy array from a tdms file. Im able to plot the file but are unable to spesify the sample intervall that I want to plot. As you can see on the picture I want to plot the intervall that is in green. </p>
<p><a href="http://i.stack.imgur.com/d4Fem.png" rel="nofo... | 1 | 2016-07-17T22:06:28Z | 38,428,991 | <p>Did you try using Python array <a href="http://pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/" rel="nofollow">slicing</a>?</p>
<p>To plot an array from element 6000 to 13000 you can use the following:</p>
<pre><code>a[6000:13000]
</code></pre>
<p>Note that the element with index 13000 will be exc... | 0 | 2016-07-18T05:12:19Z | [
"python",
"arrays",
"numpy",
"split",
"labview"
] |
Splitting a 1-d numpy array from tdms file, and plot shorter time series/intervalls from the original array | 38,426,385 | <p>Need help to pull out a spesific intervall from a 1-d numpy array from a tdms file. Im able to plot the file but are unable to spesify the sample intervall that I want to plot. As you can see on the picture I want to plot the intervall that is in green. </p>
<p><a href="http://i.stack.imgur.com/d4Fem.png" rel="nofo... | 1 | 2016-07-17T22:06:28Z | 38,440,436 | <p>You should be able to use the array-subset function, give it your array, an index, and length and you will get your sub-array.</p>
| 1 | 2016-07-18T15:19:10Z | [
"python",
"arrays",
"numpy",
"split",
"labview"
] |
Python __get__ differences between static instance and member | 38,426,390 | <p>I'm having trouble understanding what is going on to make a difference in static object and member objects (those created in constructor).</p>
<p>The following will run the overridden <strong>get</strong>():</p>
<pre><code>class A(object):
class B(object):
def __init__(self, initval=None, name='var'):
... | 0 | 2016-07-17T22:07:08Z | 38,426,513 | <p>Your <code>b</code> object is a descriptor. That means that Python treats it differently than most other objects when it is bound as a class variable. Specifically, in your class-variable code, <code>A().b</code> gets turned into the function call <code>A.__class__.__dict__["b"].__get__(A(), A)</code>. Python uses d... | 0 | 2016-07-17T22:25:32Z | [
"python"
] |
Python __get__ differences between static instance and member | 38,426,390 | <p>I'm having trouble understanding what is going on to make a difference in static object and member objects (those created in constructor).</p>
<p>The following will run the overridden <strong>get</strong>():</p>
<pre><code>class A(object):
class B(object):
def __init__(self, initval=None, name='var'):
... | 0 | 2016-07-17T22:07:08Z | 38,426,526 | <p>By implementing <code>__get__</code>, you turned your class <code>B</code> into a <a href="http://stackoverflow.com/questions/3798835/understanding-get-and-set-and-python-descriptors">descriptor class</a>. Descriptors are objects that take care of attribute access by performing custom logic on an instance.</p>
<p>I... | 2 | 2016-07-17T22:28:35Z | [
"python"
] |
Detect byte objects in python | 38,426,435 | <p>How do i detect <code><class 'bytes'></code> objects in Python?</p>
<p>I want something along the lines of</p>
<pre><code> if type(x) == bytes:
doesomething(x)
</code></pre>
| 0 | 2016-07-17T22:14:14Z | 38,426,450 | <p>You can simply do:</p>
<pre><code>if type(x) is bytes
</code></pre>
<p>Or:</p>
<pre><code>if isinstance(s, bytes)
</code></pre>
| 1 | 2016-07-17T22:17:00Z | [
"python",
"python-3.x"
] |
adjusting plot of a resetting time series in Python | 38,426,448 | <p>I would like to plot a vector that has values which are increments, and that reset to 0 each time they reach the value 100.</p>
<p>Is there an easy way to plot the values without drawing the line from top to bottom each time the value resets to 0 ?</p>
<p>am currently plotting using numpy.array and the following c... | 1 | 2016-07-17T22:16:47Z | 38,426,551 | <p>Split your data to separate series and plot these series individually:</p>
<pre><code>import matplotlib.pyplot as plt
X = [1,2,3,4,5,6,7,8]
Y = [0,50,100,0,25,50,75,100]
split = list()
for i,y in enumerate(Y):
if (y == 100): split += [i,]
prev = 0
for nxt in split:
plt.plot(X[prev:nxt+1],Y[prev:nxt+1],c=... | 1 | 2016-07-17T22:32:05Z | [
"python",
"matplotlib",
"plot"
] |
Expand macros & retrieve macro values | 38,426,460 | <p>I am trying to use <strong>libclang</strong> python bindings to parse my c++ source files. I am unable to get the value of macro or expand a macro.
<br> Here is my sample c++ code</p>
<pre><code>#define FOO 6001
#define EXPAND_MACR \
int \
foo = 61
int main()
{
EXPAND_MACR;
cout << f... | 1 | 2016-07-17T22:18:12Z | 38,454,849 | <p>No, line-by-line expansion using the extents seems to be the only way to extract the (expanded macros). </p>
<p>I suspect that the problem is that by the time libclang sees your code, the macros have already been removed by the preprocessor - the nodes you're seeing in the AST are more like annotations rather than ... | 2 | 2016-07-19T09:41:41Z | [
"python",
"c++",
"clang",
"libclang"
] |
Python-How to get rid of brackets, quotations, and commas | 38,426,555 | <p>I'm new to python, and I'm doing a program for a tic tac toe game. In order to be able to manipulate the board later on, I've made it an array.</p>
<pre><code>a=[["-","-","-"],["-","-","-"],["-","-","-"]]
def ttt(a):
for x in range (0,3):
print (a[x])
z=ttt(a)
print(z)
</code></pre>
<p>However, when it pri... | 0 | 2016-07-17T22:32:40Z | 38,426,580 | <p>You can join your sublists with space which makes it a string and then print:</p>
<pre><code>a=[["-","-","-"],["-","-","-"],["-","-","-"]]
def ttt(a):
for x in range (0,3):
print(" ".join(a[x]))
z=ttt(a)
- - -
- - -
- - -
</code></pre>
| 0 | 2016-07-17T22:36:15Z | [
"python",
"python-3.x"
] |
Python-How to get rid of brackets, quotations, and commas | 38,426,555 | <p>I'm new to python, and I'm doing a program for a tic tac toe game. In order to be able to manipulate the board later on, I've made it an array.</p>
<pre><code>a=[["-","-","-"],["-","-","-"],["-","-","-"]]
def ttt(a):
for x in range (0,3):
print (a[x])
z=ttt(a)
print(z)
</code></pre>
<p>However, when it pri... | 0 | 2016-07-17T22:32:40Z | 38,426,738 | <p>You may want to make these small changes. I'm sorry if I'm guessing wrong about your level of experience:</p>
<ul>
<li><p>You need to indent your code correctly. Python uses indention, instead of the braces in other languages, to determine the end of the function and for loops. </p></li>
<li><p>Decide where to... | 1 | 2016-07-17T23:04:45Z | [
"python",
"python-3.x"
] |
Python-How to get rid of brackets, quotations, and commas | 38,426,555 | <p>I'm new to python, and I'm doing a program for a tic tac toe game. In order to be able to manipulate the board later on, I've made it an array.</p>
<pre><code>a=[["-","-","-"],["-","-","-"],["-","-","-"]]
def ttt(a):
for x in range (0,3):
print (a[x])
z=ttt(a)
print(z)
</code></pre>
<p>However, when it pri... | 0 | 2016-07-17T22:32:40Z | 38,427,209 | <pre><code>from __future__ import print_function
def print_board(a):
for row in board:
for char in row:
print(' {}'.format(char), end='')
print('')
board = [["-","-","-"],["-","-","-"],["-","-","-"]]
print_board(board)
</code></pre>
| 0 | 2016-07-18T00:34:33Z | [
"python",
"python-3.x"
] |
List of tuple like independent data access | 38,426,570 | <p>I have some paired objects linked together in a same level priority basis. They can be grouped as fixed length tuples, all have to be in a list. Some objects type are unique, other can be common).
For example, in this data structure i have an object, an object name (both unique), an object type and a bool (both comm... | 0 | 2016-07-17T22:35:10Z | 38,442,441 | <p>I tried the solution in making a class. It does work and I believe it's fairly pythonic. It uses two dicts: one where each unique is a key for the commons and one dict containing the keys. Since no one has given an answer I thought I might as well share it.</p>
<pre><code>class Foo(object): # Didn't know how to na... | 0 | 2016-07-18T17:11:29Z | [
"python",
"list",
"python-2.7",
"data-structures"
] |
List of tuple like independent data access | 38,426,570 | <p>I have some paired objects linked together in a same level priority basis. They can be grouped as fixed length tuples, all have to be in a list. Some objects type are unique, other can be common).
For example, in this data structure i have an object, an object name (both unique), an object type and a bool (both comm... | 0 | 2016-07-17T22:35:10Z | 38,449,628 | <p>I came out with three different solutions, in the meantime.</p>
<p><strong>1. Common dictionary</strong></p>
<p>The first is a common dictionary that uses <em>every</em> unique field as a key and the full group tuple transformed in a dictionary as a value. This doesn't need a class, a function returning the common... | 0 | 2016-07-19T04:31:27Z | [
"python",
"list",
"python-2.7",
"data-structures"
] |
Can't import linreg in Jupiter | 38,426,641 | <p>I recently started teaching myself data analysis and was trying to replicate Python code on my Mac Book. I entered the following into Jupyter:</p>
<pre><code>%pylab inline
import linreg
import pandas as
</code></pre>
<p>However, I got the following error message:</p>
<pre><code>Populating the interactive namespa... | 0 | 2016-07-17T22:46:16Z | 38,426,723 | <p>The instruction "import linreg" imports another Python file as module from the current directory of the file you are running in Jupyter.</p>
<p>That means that the worksheet you are trying to replicate doesn't work on its own, but requires the module linreg to run. The module is provided by file linreg.py, you can ... | 1 | 2016-07-17T23:02:53Z | [
"python",
"jupyter"
] |
Can't import linreg in Jupiter | 38,426,641 | <p>I recently started teaching myself data analysis and was trying to replicate Python code on my Mac Book. I entered the following into Jupyter:</p>
<pre><code>%pylab inline
import linreg
import pandas as
</code></pre>
<p>However, I got the following error message:</p>
<pre><code>Populating the interactive namespa... | 0 | 2016-07-17T22:46:16Z | 38,426,725 | <p>You should download the github repo. linreg.py is a helper module. </p>
<p>Github repo:
<a href="https://github.com/nborwankar/LearnDataScience" rel="nofollow">https://github.com/nborwankar/LearnDataScience</a></p>
<p><a href="https://github.com/nborwankar/LearnDataScience/blob/master/notebooks/linreg.py" rel="no... | 0 | 2016-07-17T23:03:07Z | [
"python",
"jupyter"
] |
Static files aren't loading after changing STATIC_ROOT and STATICFILES_DIRS in django | 38,426,691 | <p>I was following a tutorial on setting STATIC_ROOT using a CDN for my satic files but I've decide I'd like to serve my static files on the same server where my django app is served. I tried changing to the new settings below and I ran manage.py collectstatic and now the static files aren't loading. What am I doing ... | 0 | 2016-07-17T22:57:30Z | 38,427,174 | <p>Where are you keeping your static files? </p>
<p>If you are keeping them in <code>BASE_DIR/static then it is important to include the same</code>STATICFILES_DIRS` as you have in the second settings file. </p>
<p>If you having your static files spread throughout your different apps then you want to make sure that <... | 1 | 2016-07-18T00:27:09Z | [
"python",
"django"
] |
Importing images for manifold Isomap | 38,426,871 | <p>There are 192 x 144 pixel images. They should be imported to a Python list so that the items in the list are NDArray instances. New dataframe should be created from the list and that dataframe should be given to Isomap. <code>iso.fit(df)</code> fails with the errors</p>
<pre><code>array = array.astype(np.float64)
... | 0 | 2016-07-17T23:25:06Z | 38,678,011 | <p>If those are gray scale images from the ALOI, you probably want to treat each pixel's brightness as a feature. Therefore, you should flatten the img array with img.reshape(-1). The revised code follows:</p>
<pre><code>import pandas as pd
from scipy import misc
import glob
from sklearn import manifold
samples = [... | 1 | 2016-07-30T20:03:44Z | [
"python",
"pandas",
"dataframe"
] |
Python string replace isn't working for me | 38,426,892 | <p>I'm trying to use string replace in python but it's not working. I'm trying to replace characters with a blank space. heres my code.</p>
<pre><code>def panties():
pan_url = 'http://www.panvideos.com'
html = requests.get(pan_url, headers=headers)
soup = BeautifulSoup(html.text, 'html5lib')
... | 0 | 2016-07-17T23:27:55Z | 38,426,999 | <p>I figured it out I had to convert entries to a string like so</p>
<pre><code>oldstring = str(entries)
removed = '<script type="text/javascript">jwplayer("video-setup").setup('
newstring = oldstring.replace(removed, "")
return newstring
</code></pre>
<p>it works. I guess what's returned isn't a string.</p>
| 0 | 2016-07-17T23:48:24Z | [
"python",
"django",
"function"
] |
Slicing array in python | 38,427,002 | <p>I have arrays of these shapes:</p>
<pre><code>q.shape #(28,40,100)
g.shape #(27,40,100)
for x in range (0,100):
for y in range (0,40):
qg = np.interp(100,g[:,y,x],q[:,y,x]) #how?
print qg
</code></pre>
<p>Of course it can't be interpolated because g and q don't have equal shapes. How should the... | 1 | 2016-07-17T23:48:52Z | 38,427,064 | <blockquote>
<p>only reads [1] to [27]</p>
</blockquote>
<p>I believe like so </p>
<pre><code>q[1:,y,x]
</code></pre>
<p>By the way, interpolation 4000 times might be really slow... You sure you are doing the right thing? </p>
| 1 | 2016-07-18T00:01:20Z | [
"python",
"numpy"
] |
How does Pandas treat the aggregate function sum versus diff | 38,427,040 | <p>I'm using python and pandas and I have a data set that looks something like:</p>
<pre><code> District Race/Ethnicity Value
3 Achievement First Academy District Black or African American 30.0
4 Achievement First Academy District White 0... | -1 | 2016-07-17T23:57:08Z | 38,427,111 | <p><code>sum</code> sums <em>all</em> the elements into a single number. <code>diff</code> takes the differences (plural) between element and the element before it and returns a sequence of all of them. You see them as parallel because your groups have only two elements, but in general they're not parallel at all. H... | 0 | 2016-07-18T00:10:32Z | [
"python",
"pandas"
] |
How to update an existing Rails model object via a JSON post operation? | 38,427,116 | <p>I'm writing data into a Rails model, using Python to send the JSON (to demonstrate I created a simple scaffold <code>Book</code> with a title and price):</p>
<pre><code>import json, urllib2
httpHeaders = {'Content-Type': 'application/json', 'Accept': 'application/json'}
bookData = {"title": "blah", "price":5} ... | 0 | 2016-07-18T00:11:41Z | 38,427,117 | <p><em>In the process of writing the question I stumbled on the answer, so rather than deleting it I decided to post the question and answer, since I can't see it asked elsewhere on SO.</em></p>
<p><code>rake routes</code> shows that the update method uses PATCH (rather than GET or PUT) so this answer to <a href="http... | 1 | 2016-07-18T00:11:41Z | [
"python",
"ruby-on-rails",
"json",
"activerecord",
"urllib2"
] |
heroku django app crashing | 38,427,121 | <p>I'm trying to have my app up and running but I keep on getting an application error. When I take a look at my dynos, I get the following message:</p>
<pre><code>Billys-MBP:gymmie-test BillyWu$ heroku ps
Free dyno hours quota remaining this month: 550h 0m (100%)
For more information on dyno sleeping and how to upgra... | 0 | 2016-07-18T00:11:59Z | 38,427,918 | <p>Does your wsgi file look something like this?</p>
<pre><code>import os
from django.core.wsgi import get_wsgi_application
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ebgymmie.settings")
application = get_wsgi_application()
if not settings.DEBUG:
try:
from dj_stat... | 0 | 2016-07-18T02:46:48Z | [
"python",
"django",
"heroku"
] |
Python/Pandas data alignment when using plot() | 38,427,206 | <p>I am using pandas to plot some data from a larger data set. I have the following code that sorts out specific columns (categories/description) and plots them from one large DF.</p>
<pre><code>df.amt[df.categ=='A'].cumsum().plot(legend=True,label='A',figsize=(11,5))
df.amt[df.descrip=='B'].cumsum().plot(legend=True,... | 1 | 2016-07-18T00:34:15Z | 38,428,358 | <p>Almost certainly, you've introduced data into</p>
<pre><code>df.amt[df.descrip=='B'].cumsum().plot(legend=True,label='B',figsize=(11,5))
</code></pre>
<p>prior to when you believe. The only way for us to really help is for you to take the time to provide more detail and more code.</p>
<p>consider the following:<... | 1 | 2016-07-18T03:54:42Z | [
"python",
"pandas",
"plot"
] |
Simulating top, bottom, left and right margins in tkinter pack geometry | 38,427,234 | <p>What should be done to have <strong>left_margin</strong> (<em>cyan</em>) and <strong>right_margin</strong> (<em>magenta</em>) frames taking all vertical height from <strong>top_margin</strong> to <strong>bottom_margin</strong>?</p>
<pre><code>import Tkinter as tk
root = tk.Tk()
top_margin = tk.Frame(root, height=... | 0 | 2016-07-18T00:40:29Z | 38,427,315 | <p>So I think I know what your problem is. You are packing the top and bottom margins before the left and right. without setting any specific size for the margins.</p>
<p>If you change your pack statements to look like this:</p>
<pre><code>left_margin.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH)
right_margin.pack(... | 0 | 2016-07-18T00:56:20Z | [
"python",
"tkinter"
] |
How can I access the dictionary returned from my results? | 38,427,285 | <p>I created a function using beutifulsoup that returns what looks like a dictionary of reults. but if I try </p>
<pre><code>results['file']
</code></pre>
<p>or </p>
<pre><code>results[0]
</code></pre>
<p>it doesn't return the results I want. I want the file and image. heres my code</p>
<pre><code> def panties(... | 0 | 2016-07-18T00:51:14Z | 38,427,333 | <p>dict.iteritems() method returns an iterator over the dictionaryâs (key, value) pairs.</p>
<pre><code>for k, v in yourdict.iteritems():
print(k ,v)
</code></pre>
| -1 | 2016-07-18T00:59:26Z | [
"python",
"django",
"dictionary"
] |
How can I access the dictionary returned from my results? | 38,427,285 | <p>I created a function using beutifulsoup that returns what looks like a dictionary of reults. but if I try </p>
<pre><code>results['file']
</code></pre>
<p>or </p>
<pre><code>results[0]
</code></pre>
<p>it doesn't return the results I want. I want the file and image. heres my code</p>
<pre><code> def panties(... | 0 | 2016-07-18T00:51:14Z | 38,427,383 | <pre><code>dict = {file:"http://www.youtube.com/watch?v=jucBuAzuZ0E",image:"http://i1.ytimg.com/vi/jucBuAzuZ0E/maxresdefault.jpg",primary:"html5",stretching:"fill","controlbar":"bottom",width:"100%",aspectratio:"16:9",autostart:"true",logo:{file:"http://www.panvideos.com/uploads/bien-png578aab16676e1.png",position:"bot... | 0 | 2016-07-18T01:09:26Z | [
"python",
"django",
"dictionary"
] |
How can I access the dictionary returned from my results? | 38,427,285 | <p>I created a function using beutifulsoup that returns what looks like a dictionary of reults. but if I try </p>
<pre><code>results['file']
</code></pre>
<p>or </p>
<pre><code>results[0]
</code></pre>
<p>it doesn't return the results I want. I want the file and image. heres my code</p>
<pre><code> def panties(... | 0 | 2016-07-18T00:51:14Z | 38,427,450 | <p>So you are getting back a dictionary, and in order to parse through a dictionary just use the names assigned to the values.</p>
<p>Example:
if you only want the file and image use:</p>
<pre><code>results["file"]
results["image"]
</code></pre>
<p>or you may need to use:</p>
<pre><code>entries["file"]
entries["ima... | 0 | 2016-07-18T01:24:40Z | [
"python",
"django",
"dictionary"
] |
Node.js vs. Python for parsing HTML | 38,427,324 | <p>I am so sorry if this is a repeat. I saw something on it, and then I couldn't find it again.</p>
<p>To be more concrete than other entries, say I have: </p>
<pre><code><h1>Hey, there.</h1>
h1 {
color: green
}
</code></pre>
<p>I want to change it to "blue". Can I do that more efficiently/with less... | 0 | 2016-07-18T00:57:53Z | 38,427,655 | <p>Luckily both python and node have nifty tools for that.</p>
<p>However, since you're just starting out, I agree that the question you should be asking is: "what do I want to learn from this?"</p>
<p>There is no point in choosing one over the other if your only goal is to just make a scraper/parser. Think about you... | 0 | 2016-07-18T02:02:38Z | [
"javascript",
"python",
"html",
"node.js"
] |
Tune parameters SVM | 38,427,358 | <p>I want to classify the data shown in the image:</p>
<p><a href="http://i.stack.imgur.com/Wd3Sh.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wd3Sh.png" alt="enter image description here"></a></p>
<p>To do so I'm trying to use a SVM:</p>
<pre><code>X = df[['score','word_lenght']].values
Y = df['is_correc... | 2 | 2016-07-18T01:04:29Z | 38,427,454 | <p>At first instance, if the data have a reasonable size you can try to perform a <a href="http://scikit-learn.org/stable/modules/grid_search.html" rel="nofollow">GridSearch</a>, Since apparently you are working with text, consider this example::</p>
<pre><code>def main():
pipeline = Pipeline([
('vect', Tf... | 4 | 2016-07-18T01:25:18Z | [
"python",
"machine-learning",
"scikit-learn",
"classification",
"svm"
] |
Error installing quandl with pip on ubuntu 14.04 | 38,427,430 | <p>here is the error that I keep getting. I keep trying to install the
quandl modulen and keep running into this same error. I have tried looking into some other questions but they do not provide any good solutions. I tried looking through the errors but I already have openssl installed. </p>
<pre><code>Collecting qu... | -1 | 2016-07-18T01:21:36Z | 38,427,455 | <p>I think you are just missing openssl</p>
<pre><code>sudo apt-get install libssl-dev
</code></pre>
<p>I don't think pip can get that dependency</p>
| 3 | 2016-07-18T01:25:51Z | [
"python",
"pip",
"ubuntu-14.04",
"quandl"
] |
division by repeated subtraction in python - What is wrong with this code? | 38,427,498 | <pre><code>quur = int(input('ENTER NUMBER : '))
quub = int(input('ENTER NUMBER : '))
def quureC (quur) :
while quur > 0 :
quur - quub
print(" The quotient of 10 is ", (quureC (quur))
</code></pre>
| 0 | 2016-07-18T01:33:12Z | 38,427,558 | <p>So python has this cool operator "% Modulus" that divides left hand operand by right hand operand and returns remainder. I think this is what you are looking for.</p>
<pre><code>quur = 10
quub = 3
print(quur % quub)
>>> 1
</code></pre>
<p>However, your code is working but it is getting stuck in an infin... | 2 | 2016-07-18T01:42:51Z | [
"python"
] |
division by repeated subtraction in python - What is wrong with this code? | 38,427,498 | <pre><code>quur = int(input('ENTER NUMBER : '))
quub = int(input('ENTER NUMBER : '))
def quureC (quur) :
while quur > 0 :
quur - quub
print(" The quotient of 10 is ", (quureC (quur))
</code></pre>
| 0 | 2016-07-18T01:33:12Z | 38,427,560 | <p>You aren't modifying the value of quur. You want to do this instead:</p>
<pre><code>while quur > 0:
quur = quur - quub
</code></pre>
| 1 | 2016-07-18T01:42:56Z | [
"python"
] |
division by repeated subtraction in python - What is wrong with this code? | 38,427,498 | <pre><code>quur = int(input('ENTER NUMBER : '))
quub = int(input('ENTER NUMBER : '))
def quureC (quur) :
while quur > 0 :
quur - quub
print(" The quotient of 10 is ", (quureC (quur))
</code></pre>
| 0 | 2016-07-18T01:33:12Z | 38,450,063 | <p>there are 2 thing wrong with your code: first you don't modify the value of <code>quur</code> and therefore you get stuck in a infinite loop, and second the algorithm is wrong, the correct one is subtracting the denominator from the numerator while this is greater than the denominator, whatever remains is the, well,... | 0 | 2016-07-19T05:17:00Z | [
"python"
] |
Creating modifiable GtkScale object in Glade | 38,427,503 | <p>I'm trying to develop a simple GTK application with <a href="https://github.com/doctormo/gtkme" rel="nofollow">gtkme (1.3.5) library</a> and I'm having trouble using <code>GtkScale</code> object in <a href="https://glade.gnome.org/" rel="nofollow">Glade (3.20.0-1)</a>. I created one of them and it's defined in <code... | 0 | 2016-07-18T01:34:22Z | 38,428,801 | <p>To get a completely working <code>Scale</code>, you need to define two elements: A <code>Gtk.Adjustment</code> (which does the math work and defines limits) and a <code>Gtk.Scale</code> which shows the element on the <code>Scale</code>. Without an <code>Adjustment</code>, the <code>Scale</code> shows as in your imag... | 1 | 2016-07-18T04:54:43Z | [
"python",
"python-3.x",
"gtk3",
"glade"
] |
Index Error, out of range Python | 38,427,552 | <p>I have created connect 4; it is a 7 by 6 grid. Below is an algorithm to test whether a diagonal connect 4 has won. Although, when the chips are in the positions shown in the image, an index error occurs. How do I fix this, and how do I get the diagonal algorithms to work?</p>
<p><a href="http://i.stack.imgur.com/9h... | 0 | 2016-07-18T01:41:18Z | 38,427,714 | <p>Since the board has 6 rows (0 -> 5), and you starting <code>x</code> from row 3 (0-based index) so <code>board[x+3][y-3]</code> will give <code>list index out of range</code> because x+3 = 6 > 5.</p>
| 1 | 2016-07-18T02:13:30Z | [
"python",
"python-3.x",
"multidimensional-array"
] |
Index Error, out of range Python | 38,427,552 | <p>I have created connect 4; it is a 7 by 6 grid. Below is an algorithm to test whether a diagonal connect 4 has won. Although, when the chips are in the positions shown in the image, an index error occurs. How do I fix this, and how do I get the diagonal algorithms to work?</p>
<p><a href="http://i.stack.imgur.com/9h... | 0 | 2016-07-18T01:41:18Z | 38,448,805 | <p>You're numbering your rows from 1 to 7 instead of 0 to 6. </p>
<p>Also, the loop you're doing should use a comma, not a hyphen.</p>
<pre><code> for x in range (4, 7): # This will count 4, 5, 6
</code></pre>
<p>If you use a hyphen, the computer will do subtraction. You end up with </p>
<pre><code> for x in ... | 0 | 2016-07-19T02:49:44Z | [
"python",
"python-3.x",
"multidimensional-array"
] |
Flask-MySQL gives "closing a closed connection" error the second time a view runs | 38,427,589 | <p>I am using Flask-MySQL to connect to my database in a view. The view works the first time I go to it, but when I go to it the second time it always crashes with the error:</p>
<pre><code>ProgrammingError: closing a closed connection
</code></pre>
<p>Why am I getting this error? How do I connect successfully the ... | 0 | 2016-07-18T01:50:01Z | 38,427,887 | <p>You should not be initializing the extension during every request. Create it during app setup, then use it during the requests. Setting configuration should also be done during app setup.</p>
<p>The extension adds a <a href="https://github.com/cyberdelia/flask-mysql/blob/2204ed2f3455bb89c5c86aa920c4174cefb5ecbb/f... | 0 | 2016-07-18T02:40:51Z | [
"python",
"mysql",
"flask",
"mysql-python"
] |
Why does Tweepy with Python 3 not return any data at all from a stream? | 38,427,597 | <p>Python 3.5.2, Tweepy 3.5.0, Windows 8.1</p>
<p>I'm following a tutorial made by sentdex that shows how to stream data from Twitter using tweepy. (His tutorial is in Python 2 but it is pretty easy to Python 3-ify it)</p>
<p>However, when I run the script, it doesn't spit out any data. It hangs until I get a 3-way I... | 0 | 2016-07-18T01:52:13Z | 38,427,964 | <p>Never mind, when I use on_status with status.text, it works, must be something I'm missing.</p>
| 0 | 2016-07-18T02:53:57Z | [
"python",
"api",
"tweepy"
] |
Why does Tweepy with Python 3 not return any data at all from a stream? | 38,427,597 | <p>Python 3.5.2, Tweepy 3.5.0, Windows 8.1</p>
<p>I'm following a tutorial made by sentdex that shows how to stream data from Twitter using tweepy. (His tutorial is in Python 2 but it is pretty easy to Python 3-ify it)</p>
<p>However, when I run the script, it doesn't spit out any data. It hangs until I get a 3-way I... | 0 | 2016-07-18T01:52:13Z | 39,707,877 | <pre><code>def on_date(self,data):
</code></pre>
<p>This should have been </p>
<pre><code>def on_data(self,data):
</code></pre>
| 1 | 2016-09-26T16:28:38Z | [
"python",
"api",
"tweepy"
] |
vectorize NumPy triple product on 2D array | 38,427,615 | <p>I am trying to vectorize the following triple product operation on an <code>N x N</code> array called <code>p</code> below:</p>
<pre><code>for j in range(len(p)):
for k in range(len(p)):
for l in range(len(p)):
h[j, k, l] = p[j, k] * p[k, l] * p[l, j] - p[j, l] * p[l, k] * p[k, j]
</code></p... | 2 | 2016-07-18T01:54:52Z | 38,427,870 | <p>Simply porting over those loop iterators as string notations, we would have an <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>einsum</code></a> based solution like so -</p>
<pre><code>h = np.einsum('jk,kl,lj->jkl',p,p,p) - np.einsum('jl,lk,kj->jkl',p,p,p)
... | 4 | 2016-07-18T02:37:50Z | [
"python",
"arrays",
"numpy",
"vectorization",
"numpy-einsum"
] |
how to vectorize this python code to make it more efficient? (in speed) | 38,427,619 | <p>I am trying to vectorize my code using numpy modules, the original code is like:</p>
<pre><code>m = [M[i,:9].dot(N[:9,i]) for i in xrange(9)]
</code></pre>
<p>and I have improved the code as:</p>
<pre><code>m = np.diagonal(M[:9,:9].dot(N[:9,:9]))
</code></pre>
<p>yet this will lead to some unnecessary calculat... | 4 | 2016-07-18T01:55:34Z | 38,427,785 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html"><code>np.einsum</code></a> as we need to keep the first axis of <code>M</code> aligned with the second axis of <code>N</code>, while reducing/losing the leftover axes from the inputs. Thus, we would have an <code>einsum</code... | 6 | 2016-07-18T02:24:39Z | [
"python",
"performance",
"numpy",
"vectorization",
"matrix-multiplication"
] |
how to vectorize this python code to make it more efficient? (in speed) | 38,427,619 | <p>I am trying to vectorize my code using numpy modules, the original code is like:</p>
<pre><code>m = [M[i,:9].dot(N[:9,i]) for i in xrange(9)]
</code></pre>
<p>and I have improved the code as:</p>
<pre><code>m = np.diagonal(M[:9,:9].dot(N[:9,:9]))
</code></pre>
<p>yet this will lead to some unnecessary calculat... | 4 | 2016-07-18T01:55:34Z | 38,427,801 | <p>Assuming that both matrices are square and have the same dimensions, this is what we can do:</p>
<ol>
<li><p>By the definition of matrix multiplication, the result you want to calculate is basically a vector of dot products. The first element of the result vector is the dot product of M's first row with N's first c... | 4 | 2016-07-18T02:26:31Z | [
"python",
"performance",
"numpy",
"vectorization",
"matrix-multiplication"
] |
Determining relative path in Perl Module | 38,427,627 | <p>First Module:</p>
<pre><code>package Compute;
our $sort_script= "/app/scripts/python_script.py";
</code></pre>
<p>Second Module:</p>
<pre><code>package ProcessRestart;
use Compute;
# This perl module is also in /app/scripts/
# host1.com is an argument or script parameter
$returnMsg= `$Compute::sort_script hos... | 1 | 2016-07-18T01:56:50Z | 38,428,060 | <p>I think you're asking how to execute a script that's located in the same dir as the module that executes it.</p>
<pre><code>use Path::Class qw( file );
my $qfn = file(__FILE__)->dir->file('python_script.py');
</code></pre>
<p>or</p>
<pre><code>use File::Basename qw( dirname );
my $qfn = dirname(__FILE__) ... | 3 | 2016-07-18T03:08:42Z | [
"python",
"perl",
"perl-module"
] |
Error trying to load data into Spyder | 38,427,684 | <p>I'm having issues trying to pull data from a .txt file in a certain directory into Spyder. The basic idea is that I have a table of data in a .txt file, and I want certain columns to be used as arrays in Python. I'm using the numpy function genfromtxt() to do this, and it works fine when I write it as a program and ... | 0 | 2016-07-18T02:07:54Z | 38,427,874 | <p>Turns out you can't just paste the directory and hit enter...there's a button next to the text box that says "set as current directory." So even if you paste a directory in there and press enter, it won't actually set that as the directory until you hit that button. Thanks for the replies everyone</p>
| 0 | 2016-07-18T02:38:24Z | [
"python",
"numpy",
"spyder"
] |
Is it okay to use python mock for production? | 38,427,751 | <p>A lot of my mock usage is in unit tests, but I am not sure if I can use the mock library for production, consider the following trivial example to get data from external source.</p>
<pre><code>class Receiver(object):
def get_data(self):
return _call_api(...)
</code></pre>
<p>Now, can I use <code>mock</... | 0 | 2016-07-18T02:19:47Z | 38,427,803 | <p>No. If a function is supposed to behave a certain way in production, then <em>code it to behave that way</em>. If you need fallback or retry behavior, mock is not the right way to do that.</p>
| 1 | 2016-07-18T02:27:00Z | [
"python"
] |
Is it okay to use python mock for production? | 38,427,751 | <p>A lot of my mock usage is in unit tests, but I am not sure if I can use the mock library for production, consider the following trivial example to get data from external source.</p>
<pre><code>class Receiver(object):
def get_data(self):
return _call_api(...)
</code></pre>
<p>Now, can I use <code>mock</... | 0 | 2016-07-18T02:19:47Z | 38,427,806 | <p>I would agree that for production use, a <code>Receiver</code> subclass that has an overridden <code>get_data</code> method would be much better.</p>
<p>The reason is simple -- if each type of receiver only receives data from a single source then your code will be much easier to read and maintain. If the same <cod... | 1 | 2016-07-18T02:27:11Z | [
"python"
] |
How to save a png file into database, FLASK? | 38,427,838 | <p>I have a small problem, i want to upload a (screenshot) image that have been taken by <code>selenium driver</code> and <code>PhantomJS</code> to my website and to put it into the database .</p>
<p>I'am using the <code>get_screenshot_as_file()</code> function to save the image in the current directory, this function... | -1 | 2016-07-18T02:32:34Z | 38,432,985 | <p>You pass the wanted filename into the <code>get_screenshot_as_file</code> method (as you are doing now). The <code>get_screenshot_as_file</code> method returns True if the file was successfully written, otherwise False.</p>
<p>Your code should be something like :</p>
<pre><code>image_filename = os.urandom(3).encod... | 1 | 2016-07-18T09:21:04Z | [
"python",
"selenium",
"flask",
"phantomjs"
] |
Scrapy Python loop to next unscraped link | 38,427,844 | <p>i'm trying to make my spider go over a list and scrape all the url's it can find following them scraping some data and returning to continue on the next unscraped link if i run the spider i can see that it returns back to the starting page but tries to scrape the same page again and just quits afterwards any code su... | -1 | 2016-07-18T02:33:36Z | 38,430,217 | <p>This should just work fine. Change the domain and xpath and see</p>
<pre><code> import scrapy
import re
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class ProdItems(scrapy.Item):
listurl = scrapy.Field()
title = scrapy.Field()
... | 1 | 2016-07-18T06:51:06Z | [
"python",
"scrapy",
"scrapy-spider"
] |
Scrapy Python loop to next unscraped link | 38,427,844 | <p>i'm trying to make my spider go over a list and scrape all the url's it can find following them scraping some data and returning to continue on the next unscraped link if i run the spider i can see that it returns back to the starting page but tries to scrape the same page again and just quits afterwards any code su... | -1 | 2016-07-18T02:33:36Z | 38,431,564 | <p>This is the line that's causing your problem:</p>
<pre><code>item['listurl'] = sel.xpath('//a[@id="link101"]/@href').extract()[0]
</code></pre>
<p>The "//" means "from the start of the document" which means that it scans from the very first tag and will always find the same first link. What you need to do is searc... | 1 | 2016-07-18T08:07:30Z | [
"python",
"scrapy",
"scrapy-spider"
] |
Raw HTTP client not returning any data | 38,427,872 | <pre><code>import socket
host = 'www.google.com'
port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try :
client.connect((host, port))
except socket.error:
print ("Err")
package = '00101'
package.encode('utf-8')
client.sendall(package.encode(encoding = 'utf-8'))
response = client.recv... | 0 | 2016-07-18T02:37:54Z | 38,427,987 | <p>You need to send a valid HTTP request. For example:</p>
<pre><code>package = b'''GET /HTTP/1.1
Host: www.google.com
'''
client.sendall(package)
</code></pre>
<p>Which correctly returns a redirect on my machine. Note the empty line at the end of <code>package</code>, which ends the request.</p>
<p>When you send ... | 1 | 2016-07-18T02:57:06Z | [
"python",
"sockets",
"http"
] |
How does canvas.bind(event, handler) pass event to the event handler? | 38,427,953 | <p>The primary way of passing arguments to a function in Python is this:</p>
<pre><code>def function(x):
# function definition
function(y)
</code></pre>
<p>That is, when we call <code>function</code> we pass a value to it inside parenthesis.</p>
<p>However, I am using tkinter, and the event <code>canvas.bind()<... | 0 | 2016-07-18T02:51:55Z | 38,428,008 | <p>It does it just like you expect. In the binding you are giving the <em>name</em> of the function to call. When the event fires, the internal tkinter code that processes the event actually calls it just as you would: <code>event_handler(event)</code>.</p>
| 1 | 2016-07-18T03:01:21Z | [
"python",
"canvas",
"tkinter",
"tkinter-canvas"
] |
Stopping a sequence of statements halfway while they are executing | 38,427,958 | <p>I have created a daemon thread which will be independently running once it is initiated with the main Object. I can push various functions that I want it to run through its stack. BUT I never want the daemon thread to have more than 2 functions in the stack (design choice for the project I'm building). So if a metho... | 0 | 2016-07-18T02:52:38Z | 38,428,880 | <p>Python has two threading APIs:</p>
<ul>
<li><a href="https://docs.python.org/2/library/threading.html" rel="nofollow"><strong>threading</strong></a></li>
<li><a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow"><strong>multiprocessing</strong></a></li>
</ul>
<p>Threads created using <str... | 0 | 2016-07-18T05:00:56Z | [
"python",
"multithreading"
] |
Python maximum execution time out or speeding up regex | 38,428,006 | <p>I have a regex matcher that inspects web traffic in Python. The issue is that sometimes, if the page is larger than 1MB and consists of a single string, the regex takes forever to complete. I'm wondering if there is a way to set a max execution timeout?</p>
<p>My script reads the regexes from a file and then proces... | 1 | 2016-07-18T03:01:07Z | 38,428,241 | <p>I'm going to focus on this part of one of your regexen:</p>
<pre><code>\s*(.*)?[A-Za-z0-9\/]{40}(.*)?.*
</code></pre>
<p>Firstly, <code>\s*(.*)?</code>. The problem with this is that the <code>\s*</code> can regurgitate whitespace and then have it consumed by the <code>(.*)?</code> (and the question mark is unnec... | 3 | 2016-07-18T03:37:37Z | [
"python",
"regex"
] |
Python "with" statement: __exit__() ignored | 38,428,025 | <p>Considering this small Python class, whenever I stop the script with <kbd>Ctrl</kbd>+<kbd>C</kbd>, the <code>__exit__</code> function is run before the exception is raised:</p>
<pre><code>import time
class MyClass(object):
def __init__(self):
pass
def __enter__(self):
return self
def... | 2 | 2016-07-18T03:03:48Z | 38,428,080 | <p>Notice that the traceback shows that you were still in the __init__() of your WebDriver object - in other words, the <strong>with</strong> statement had not yet executed, Python was still evaluating its parameter. I'm not sure of the exact rules, but I'm pretty sure that __exit__() will never be called if __enter__... | 5 | 2016-07-18T03:11:45Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver"
] |
Set Union in pandas | 38,428,108 | <p>I have two columns which I stored sets in my dataframe.</p>
<p>I want to perform set union on the two columns using fast vectorized operation</p>
<pre><code>df['union'] = df.set1 | df.set2
</code></pre>
<p>but the error <code>TypeError: unsupported operand type(s) for |: 'set' and 'bool'</code> is preventing me f... | 6 | 2016-07-18T03:16:08Z | 38,429,633 | <p>This is the best I could come up with:</p>
<pre><code># method 1
df.apply(lambda x: x.set1.union(x.set2), axis=1)
# method 2
df.applymap(list).sum(1).apply(set)
</code></pre>
<h3>Wow!</h3>
<p>I expected the method 2 to be quicker. Not so!</p>
<p><a href="http://i.stack.imgur.com/VKzIs.png" rel="nofollow"><img ... | 5 | 2016-07-18T06:10:54Z | [
"python",
"python-3.x",
"numpy",
"pandas",
"vectorization"
] |
Set Union in pandas | 38,428,108 | <p>I have two columns which I stored sets in my dataframe.</p>
<p>I want to perform set union on the two columns using fast vectorized operation</p>
<pre><code>df['union'] = df.set1 | df.set2
</code></pre>
<p>but the error <code>TypeError: unsupported operand type(s) for |: 'set' and 'bool'</code> is preventing me f... | 6 | 2016-07-18T03:16:08Z | 38,432,193 | <p>For these operations pure Python may be more efficient.</p>
<pre><code>%timeit pd.Series([set1.union(set2) for set1, set2 in zip(df['A'], df['B'])])
10 loops, best of 3: 43.3 ms per loop
%timeit df.apply(lambda x: x.A.union(x.B), axis=1)
1 loop, best of 3: 2.6 s per loop
</code></pre>
<p>If we could use <code>+</... | 5 | 2016-07-18T08:42:46Z | [
"python",
"python-3.x",
"numpy",
"pandas",
"vectorization"
] |
Variable assignment inside a function argument | 38,428,169 | <pre><code>def auto_detect_serial_unix(preferred_list=['*']):
</code></pre>
<p>What happens to the argument when this function gets called? </p>
| -1 | 2016-07-18T03:27:45Z | 38,428,221 | <p>If nothing is passed in to <code>auto_detect_serial_unix</code>, then preferred_list is set to <code>['*']</code>. Otherwise, what you pass in is set to <code>preferred_list</code>:</p>
<pre><code>>>> def auto_detect_serial_unix(preferred_list=['*']):
... print preferred_list
...
>>> auto_det... | 0 | 2016-07-18T03:35:14Z | [
"python",
"function"
] |
Variable assignment inside a function argument | 38,428,169 | <pre><code>def auto_detect_serial_unix(preferred_list=['*']):
</code></pre>
<p>What happens to the argument when this function gets called? </p>
| -1 | 2016-07-18T03:27:45Z | 38,428,222 | <p>If <code>auto_detect_serial_unix</code> is called with an argument, then <code>preferred_list</code> will have the value of that argument.</p>
<p>Otherwise, if <code>auto_detect_serial_unix</code> is called with no arguments, then <code>preferred_list</code> will have the given default value.</p>
| 0 | 2016-07-18T03:35:16Z | [
"python",
"function"
] |
gtk 2.7 package for python on windows | 38,428,209 | <p>How to install gtk 2.7 package gobject for python on windows 7?</p>
<p>I'm getting this error: </p>
<pre><code>ImportError: No module named gtk
</code></pre>
| 2 | 2016-07-18T03:33:28Z | 38,431,048 | <p>I presume you mean Gtk for Python 2.7. Gtk 2.7 is ancient. You would want to use pygobject:</p>
<p><a href="https://sourceforge.net/projects/pygobjectwin32/" rel="nofollow">https://sourceforge.net/projects/pygobjectwin32/</a></p>
<p>And then:</p>
<pre><code>from gi.repository import Gtk
</code></pre>
| 0 | 2016-07-18T07:37:44Z | [
"python",
"windows",
"gtk"
] |
How to get username of request from ModelViewSet class in Django rest API? | 38,428,228 | <p>I have the following code.
It allows uploading an Image using Rest API's in Django.
How ever due to the nature of this class I am unable to get the user the way it's usually done (request.user)</p>
<h1>view.py</h1>
<pre><code>class PhotoViewSet(viewsets.ModelViewSet, APIView):
permission_classes = (permissions... | 0 | 2016-07-18T03:35:56Z | 38,430,201 | <p>If you want to add the user to the <code>Photo</code> instance, either use the <a href="http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault" rel="nofollow"><code>CurrentUserDefault</code></a> in the PhotoSerializer (as read-only field) or <a href="http://www.django-rest-framework.org/api-gu... | 1 | 2016-07-18T06:49:44Z | [
"python",
"django",
"api",
"rest",
"django-rest-framework"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.