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 |
|---|---|---|---|---|---|---|---|---|---|
Variable step in a for loop | 37,845,872 | <p>I am trying to loop between 0.01 and 10, but between 0.01 and 0.1 use 0.01 as the step, then between 0.1 and 1.0 use 0.1 as step, and between 1.0 and 10.0 use 1.0 as step.</p>
<p>I have the while loop code written, but want to make it more pythonic.</p>
<pre><code>i = 0.01
while i < 10:
# do something
pri... | 17 | 2016-06-15T21:14:00Z | 37,846,358 | <p>Just a single line of code through list comprehension - </p>
<pre><code>for k in [i*j for j in (0.01, 0.1, 1) for i in range(1, 10)]
</code></pre>
<p>Can't be more pythonic!</p>
| 3 | 2016-06-15T21:47:41Z | [
"python",
"for-loop"
] |
Variable step in a for loop | 37,845,872 | <p>I am trying to loop between 0.01 and 10, but between 0.01 and 0.1 use 0.01 as the step, then between 0.1 and 1.0 use 0.1 as step, and between 1.0 and 10.0 use 1.0 as step.</p>
<p>I have the while loop code written, but want to make it more pythonic.</p>
<pre><code>i = 0.01
while i < 10:
# do something
pri... | 17 | 2016-06-15T21:14:00Z | 37,847,024 | <p>Just in case you wished to replace the loop with <strong>vectorized</strong> code...</p>
<pre><code>In [63]: np.ravel(10.**np.arange(-2, 1)[:,None] * np.arange(1, 10)[None,:])
Out[64]:
array([ 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
0.1 , 0.2 , 0.3 , 0.4 , 0.5 , 0.6 , 0.7 , 0.8... | 0 | 2016-06-15T22:41:36Z | [
"python",
"for-loop"
] |
Variable step in a for loop | 37,845,872 | <p>I am trying to loop between 0.01 and 10, but between 0.01 and 0.1 use 0.01 as the step, then between 0.1 and 1.0 use 0.1 as step, and between 1.0 and 10.0 use 1.0 as step.</p>
<p>I have the while loop code written, but want to make it more pythonic.</p>
<pre><code>i = 0.01
while i < 10:
# do something
pri... | 17 | 2016-06-15T21:14:00Z | 37,848,235 | <p>I'd recommend a generator function as well, but if the steps are not such convenient powers of each other I'd write it like</p>
<pre><code>def my_range():
i = 0
while i < 0.1:
i += 0.01
yield i
while i < 1:
i += 0.1
yield i
while i < 10:
i += 1
... | 1 | 2016-06-16T01:03:37Z | [
"python",
"for-loop"
] |
Pandas setting column subset slow | 37,845,884 | <p>I had to cast a subset of columns of a big DataFrame in pandas... it was very slow. So I made a few tests and discovered that the casting itself is done very fast. But Pandas seems to be slow when attributing the newly casted values to the old DataFrame. </p>
<p>I then came up with another solution performing a joi... | 1 | 2016-06-15T21:14:38Z | 37,847,177 | <p>There was just a doc note added about this - see <a href="http://pandas-docs.github.io/pandas-docs-travis/basics.html#astype" rel="nofollow">here</a>.</p>
<p>Basically you don't want to use <code>loc</code> when casting - instead do:</p>
<pre><code>df[f] = df[f].astype(float)
</code></pre>
<p>Also, fyi the <code>... | 1 | 2016-06-15T22:56:41Z | [
"python",
"performance",
"pandas",
"dataframe"
] |
Use GitPython to Checkout a new branch and push to remote | 37,845,888 | <p>Given a repo(GitPython) - how can i create a new local branch, add some files, and push it to remote using GitPython?</p>
<p>repo example:</p>
<pre><code>from git import *
curr_dir = os.path.dirname(os.path.realpath(__file__))
repo = Repo(curr_dir)
</code></pre>
<p>for now i'm just using subprocess:</p>
<pre><c... | 1 | 2016-06-15T21:14:54Z | 37,848,510 | <p>gitypython looks like it provides both low and level access to git but you can invoke git commands, see <a href="http://gitpython.readthedocs.io/en/stable/reference.html#module-git.cmd" rel="nofollow">http://gitpython.readthedocs.io/en/stable/reference.html#module-git.cmd</a>. </p>
<p>Alternately, consider using <a... | 0 | 2016-06-16T01:37:47Z | [
"python",
"git",
"github",
"gitpython"
] |
Cross-validation on XGBClassifier for multiclass classification in python | 37,845,920 | <p>I'm trying to perform cross-validation on a XGBClassifier for a multi-class classification problem using the following code adapted from <a href="http://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/" rel="nofollow">http://www.analyticsvidhya.com/blog/2016/03/complete... | 1 | 2016-06-15T20:54:23Z | 37,846,661 | <p>You have to add the parameter ânum_classâ to the xgb_param dictionary. This is also mentioned in the parameters description and in a comment from the link you provided above.</p>
| 3 | 2016-06-15T22:11:18Z | [
"python",
"classification",
"cross-validation",
"xgboost"
] |
how to compute emd flow by using cv.CalcEMD2 (opencv)? | 37,845,944 | <p>I know MATLAB and C can compute EMD flow. However, I am trying to use python (opencv) to compute the EMD flow by using function cv.CalcEMD2. Is there any chance if anyone can give me an example using cv.CalcEMD2 or any function to get EMD flow please?</p>
| 0 | 2016-06-15T21:18:28Z | 39,143,571 | <p>Here is some python code that computes EMD and the flow for two mixtures of Gaussians. I hope that helps.</p>
<pre><code>"""
Compute earth mover's distance (EMD) to compare two mixtures of Gaussians
Requires: numpy, cv2, csb
"""
import numpy as np, cv2
from csb.numeric import log_sum_exp
class GMM(object):
""... | 0 | 2016-08-25T11:04:32Z | [
"python",
"opencv",
"flow"
] |
How to check for unfound value with add_xpath in scrapy and set item value to a default value? | 37,846,006 | <p>Let's say I have this code:</p>
<pre><code>def parse(self, response)
l = ItemLoader(item=MyItem(), response=response
l.add_xpath('title', '//*[@id="title"]/text()', MapCompose(str.strip, str.title)
l.add_xpath('price', '//*[@id="price"]/text()', MapCompose(lambda i: i.replace(',', ''), float), re = '[,.... | 0 | 2016-06-15T21:22:23Z | 37,846,324 | <p>The source for <code>ItemLoader</code> is <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/loader/__init__.py" rel="nofollow">here</a>. The <code>add_xpath</code> method doesn't return anything (and so by default it returns <code>None</code>, so your <code>if</code> statement will always be <code>False<... | 1 | 2016-06-15T21:45:57Z | [
"python",
"scrapy"
] |
Python unzip large file - NotImplementedError: compression type 98 | 37,846,085 | <p>I am using following Python code to unzip the files</p>
<pre><code>import zipfile
zfile = zipfile.ZipFile(input_file_path)
zfile.extractall(output_path)
</code></pre>
<p>However, when I try to unzip a larger file. It throws the following error.</p>
<blockquote>
<p>NotImplementedError: compression type 98 (ppmd)... | 0 | 2016-06-15T21:27:55Z | 37,846,187 | <p>Python's <code>zipfile</code> module does not support PPMd compression--see <a href="http://bugs.python.org/issue14366" rel="nofollow">issue 14366</a> (emphasis added):</p>
<blockquote>
<p>I think we should add the ability to register new codecs. <strong>Support for PPMd, jpeg and WavPack is unlikely to emerge in... | 0 | 2016-06-15T21:35:27Z | [
"python",
"unzip",
"zipfile"
] |
Loop over a directory and run easy_install on packages in a particular order | 37,846,093 | <p>I am fairly new to bash scripting.</p>
<p>I have a bash script which must run offline (should work without internet). The script untars a xyz.tar.gz file and performs easy_install on a bunch of python packages which are .tar.gz files themselves. The 4 packages I am installing are:</p>
<pre><code>multi_key_dict-2.0... | 0 | 2016-06-15T21:28:53Z | 37,846,157 | <p>Something like this might work:</p>
<pre><code>for package in m* pb* s* py*; do
easy_install "$package"
done
</code></pre>
<p>The above assumes that you are in a directory that contains those four files, and that <code>easy_install</code> requires a filename as first and only argument. </p>
<p>Basically the v... | 0 | 2016-06-15T21:33:18Z | [
"python",
"bash",
"jenkins"
] |
Generate token for an action | 37,846,097 | <p>I need to generate a token that will allow someone to do a unique action.
The difficulty is that nobody must find this token and do the action of someone else. Using python i would like to know if generating a random token is enough or not ? Can someone tell me what is necessary for generating a strong token that ca... | 0 | 2016-06-15T21:29:10Z | 37,846,257 | <p>What you can do is have a code that generates a random 32 bit string from just letters (Upper case and lower case) and numbers and save it in the DB with a expire time (A few hours will be enough).</p>
<p>This way even if the "hacker" starts brute force by the time he is even close, the token will be expired and he... | 1 | 2016-06-15T21:41:08Z | [
"python",
"security",
"token"
] |
Generate token for an action | 37,846,097 | <p>I need to generate a token that will allow someone to do a unique action.
The difficulty is that nobody must find this token and do the action of someone else. Using python i would like to know if generating a random token is enough or not ? Can someone tell me what is necessary for generating a strong token that ca... | 0 | 2016-06-15T21:29:10Z | 37,846,347 | <blockquote>
<pre><code>def generate_key(number=20):
result = binascii.hexlify(os.urandom(number))
return result
</code></pre>
</blockquote>
<p>md5(username + password_hash + a_random_string) + generate_key(). I think it's strong as you expected. Actually I usually use generate_key only. I find it strong... | 1 | 2016-06-15T21:47:08Z | [
"python",
"security",
"token"
] |
Generate token for an action | 37,846,097 | <p>I need to generate a token that will allow someone to do a unique action.
The difficulty is that nobody must find this token and do the action of someone else. Using python i would like to know if generating a random token is enough or not ? Can someone tell me what is necessary for generating a strong token that ca... | 0 | 2016-06-15T21:29:10Z | 37,869,630 | <p>Thanks for your responses.
In fact i can't have an expire time.
This is something someone can buy, we give him a token and with this token he will be able to do an action. So i can't use a expiry time. I think i need something very strong and unique. </p>
<pre><code>inascii.hexlify(os.urandom(number))
</code></pre>... | 0 | 2016-06-16T21:28:37Z | [
"python",
"security",
"token"
] |
NGINX - Python - UWSGI kill issue | 37,846,202 | <p>Hello fellow engineers attempting to change the world!
... and anyone who is willing to help : )</p>
<p>After adding a runloop code in python, uwsgi seems to be taking longer to kill</p>
<hr>
<h2>setup</h2>
<ul>
<li>python flask</li>
<li>running on nginx with uwsgi </li>
<li>using a psql database</li>
</ul>
<hr... | 0 | 2016-06-15T21:36:40Z | 38,905,953 | <p>I know the question is a bit old, but I had the same problem and Google got me here, so I will answer for anyone who gets here in the same boat.</p>
<p>The problem seems to be caused by the "--enable-threads" option, we have several applications running with uwsgi and flask and only the one with this option has the... | 1 | 2016-08-11T20:53:21Z | [
"python",
"multithreading",
"nginx",
"flask",
"uwsgi"
] |
Python intersection with custom equality | 37,846,222 | <p>I want to build the intersection of two python sets, but i need to have a custom equality to do this.
Is there a way to specify "equaliy" directly when doing the intersection? For example due to a lambda-expressions?</p>
<p>I know there is way by overriding <strong>eq</strong>, but i have to do several intersection... | 3 | 2016-06-15T21:38:09Z | 37,847,563 | <p>One approach would be to write your own subclass of <code>Set</code> and implement custom comparisons that way. Then, you'd just have to create a new instance of the custom "keyed set" per "equality" that you want to get an intersection of your elements using.</p>
<p>For instance: <a href="http://code.activestate.c... | 1 | 2016-06-15T23:41:36Z | [
"python",
"lambda",
"intersection"
] |
Python intersection with custom equality | 37,846,222 | <p>I want to build the intersection of two python sets, but i need to have a custom equality to do this.
Is there a way to specify "equaliy" directly when doing the intersection? For example due to a lambda-expressions?</p>
<p>I know there is way by overriding <strong>eq</strong>, but i have to do several intersection... | 3 | 2016-06-15T21:38:09Z | 37,855,480 | <p><strong>Preface</strong></p>
<p>What you are trying to do makes perfect mathematical sense by using the right terms. The "equalities" you are referring to are actually <a href="https://en.wikipedia.org/wiki/Equivalence_relation" rel="nofollow">equivalence relations</a>. Basically an equicalenve relation describes a... | 2 | 2016-06-16T09:41:41Z | [
"python",
"lambda",
"intersection"
] |
How encode strings using python | 37,846,237 | <p>I have lists with element</p>
<pre><code>[u'\xd0\xbc\xd1\x82\xd1\x81 \xd0\xbe\xd1\x84\xd0\xb8\xd1\x86\xd0\xb8\xd0\xb0\xd0\xbb\xd1\x8c\xd0\xbd\xd1\x8b\xd0\xb9 \xd1\x81\xd0\xb0\xd0\xb9\xd1\x82']
[u'\xd0\xbc\xd1\x82\xd1\x81 \xd0\xbe\xd1\x84\xd0\xb8\xd1\x86\xd0\xb8\xd0\xb0\xd0\xbb\xd1\x8c\xd0\xbd\xd1\x8b\xd0\xb9 \xd1\x... | 1 | 2016-06-15T21:39:33Z | 37,846,334 | <p>You have a <a href="https://en.wikipedia.org/wiki/Mojibake" rel="nofollow">Mojibake</a>; text decoded using the wrong codec.</p>
<p>You have what looks like it was decoded or Latin-1 or Windows codepage 1252, while it should have been decoded as UTF-8 instead.</p>
<p>Either reverse the encoding manually, or use th... | 3 | 2016-06-15T21:46:32Z | [
"python",
"unicode",
"utf-8",
"encode"
] |
Why does text representation as a list consume so much memory? | 37,846,284 | <p>I have a 335 MB large text file. The entire text is tokenized. Each token is separated by a whitespace. I want to represent each sentence as a list of words while the entire text is a list of sentences. This means that I'll get a list of lists.</p>
<p>I use this simple peace of code to load the text into my main me... | 2 | 2016-06-15T21:43:08Z | 37,846,507 | <p>Lists and strings are objects and objects have properties that take memory space. You can check the size of the objects and the overhead with <code>sys.getsizeof</code>:</p>
<pre><code>>>> sys.getsizeof('')
49
>>> sys.getsizeof('abcd')
53
>>> sys.getsizeof([])
64
>>> sys.getsizeo... | 1 | 2016-06-15T21:58:20Z | [
"python",
"memory"
] |
Why does text representation as a list consume so much memory? | 37,846,284 | <p>I have a 335 MB large text file. The entire text is tokenized. Each token is separated by a whitespace. I want to represent each sentence as a list of words while the entire text is a list of sentences. This means that I'll get a list of lists.</p>
<p>I use this simple peace of code to load the text into my main me... | 2 | 2016-06-15T21:43:08Z | 37,846,654 | <p>You are keeping multiple representations of the data in memory at the same time. The file buffer in <code>readlines()</code>, also <code>sentences</code> and again when you are building the list to return. To reduce memory, process the file a line at a time. Only <code>words</code> will then hold the entire contents... | 0 | 2016-06-15T22:10:50Z | [
"python",
"memory"
] |
Why does text representation as a list consume so much memory? | 37,846,284 | <p>I have a 335 MB large text file. The entire text is tokenized. Each token is separated by a whitespace. I want to represent each sentence as a list of words while the entire text is a list of sentences. This means that I'll get a list of lists.</p>
<p>I use this simple peace of code to load the text into my main me... | 2 | 2016-06-15T21:43:08Z | 37,846,659 | <blockquote>
<p>Why? The text should occupy about 335 MB.</p>
</blockquote>
<p>Supposing that the text is encoded in UTF-8 or one of the various single-byte encodings -- which is likely -- the text itself does occupy a bit more than 335 MB in Python 2, but at least twice as much and maybe four times as much in Pytho... | 1 | 2016-06-15T22:11:12Z | [
"python",
"memory"
] |
Why does text representation as a list consume so much memory? | 37,846,284 | <p>I have a 335 MB large text file. The entire text is tokenized. Each token is separated by a whitespace. I want to represent each sentence as a list of words while the entire text is a list of sentences. This means that I'll get a list of lists.</p>
<p>I use this simple peace of code to load the text into my main me... | 2 | 2016-06-15T21:43:08Z | 37,852,246 | <p>My first answer attempted to reduce memory usage by not keeping intermediate lists in memory at the same time.
But that still did not manage to squeeze the whole data structure into 4GB of RAM. </p>
<p>With this approach, using a 40MB text file made up of Project Gutenberg books as test data, the data requirement ... | 0 | 2016-06-16T07:12:37Z | [
"python",
"memory"
] |
I am building a caesar cipher for my school project and would like to know how the decryption part would work | 37,846,301 | <p>I am writing in Python 3.4 and have so far programmed this:</p>
<pre><code>plaintext = ""
print ("Do you want to encrypt or decrypt a phrase?")
answer = input("Type e for encrypt or d for decrypt and hit 'Enter'.").lower()
if answer == ("e") or answer == ("encrypt"):
plaintext = input("Enter the phrase you woul... | 1 | 2016-06-15T21:44:31Z | 37,846,371 | <p>Caesar cyphers are symmetric - you just need to apply the same logic backwards - find the index in the ciphered text and get that index from the plain alphabet:</p>
<pre><code>plain = ''
for eachletter in cipertext:
position = shiftedAlphabet.index(eachletter)
shiftedLetter = alphabet[position]
plain = ... | 1 | 2016-06-15T21:48:39Z | [
"python",
"python-3.x",
"cryptography",
"caesar-cipher"
] |
I am building a caesar cipher for my school project and would like to know how the decryption part would work | 37,846,301 | <p>I am writing in Python 3.4 and have so far programmed this:</p>
<pre><code>plaintext = ""
print ("Do you want to encrypt or decrypt a phrase?")
answer = input("Type e for encrypt or d for decrypt and hit 'Enter'.").lower()
if answer == ("e") or answer == ("encrypt"):
plaintext = input("Enter the phrase you woul... | 1 | 2016-06-15T21:44:31Z | 37,846,464 | <p>So there are a couple issues with the code you've posted already. There are some minor syntax errors I can overlook, but there are also some logical errors. </p>
<p>Your second prompt to the user asks how many shifts they would like to make, yet the shifted alphabet you use for your program always shifts from <code... | 1 | 2016-06-15T21:55:07Z | [
"python",
"python-3.x",
"cryptography",
"caesar-cipher"
] |
preventing conflict between math symbols and html code | 37,846,355 | <p>I want to present text out of math publications and every now and then I get something like </p>
<pre><code>O(1/N_f) Corrections to the Thirring Model in 2<d<4<
</code></pre>
<p>The last part will be misinterpreted as html. I have to paste this text directly on the website allowing html. The reason why I ... | 0 | 2016-06-15T21:47:30Z | 37,846,536 | <p>Use <code>xml.sax.saxutils.escape</code> function:</p>
<pre><code>import xml.sax.saxutils
escaped = xml.sax.saxutils.escape(text)
</code></pre>
<p>This will Escape '&', '<', and '>' in the text string.</p>
| 2 | 2016-06-15T22:00:30Z | [
"python",
"html"
] |
preventing conflict between math symbols and html code | 37,846,355 | <p>I want to present text out of math publications and every now and then I get something like </p>
<pre><code>O(1/N_f) Corrections to the Thirring Model in 2<d<4<
</code></pre>
<p>The last part will be misinterpreted as html. I have to paste this text directly on the website allowing html. The reason why I ... | 0 | 2016-06-15T21:47:30Z | 37,846,586 | <p>HTML has several characters with special meanings (including angle brackets), and is also usually represented in ASCII, so a good way to represent these types of special characters are needed. </p>
<p>In HTML, escape sequences are used to represent them. For example, a <code>&</code> character is represented by... | 0 | 2016-06-15T22:04:58Z | [
"python",
"html"
] |
Why Does this DataFrame Modification within Function Change Global Outside Function? | 37,846,357 | <p>Why does the function below change the global <code>DataFrame</code> named <code>df</code>? Shouldn't it just change a local <code>df</code> within the function, but not the global <code>df</code>?</p>
<pre><code>import pandas as pd
df = pd.DataFrame()
def adding_var_inside_function(df):
df['value'] = 0
prin... | 2 | 2016-06-15T21:47:40Z | 37,846,522 | <p>from <a href="http://pandas.pydata.org/pandas-docs/stable/overview.html#mutability-and-copying-of-data" rel="nofollow">docs</a>:</p>
<blockquote>
<p><strong>Mutability and copying of data</strong></p>
<p>All pandas data structures are value-mutable (the values they contain can be altered) but not always
si... | 1 | 2016-06-15T21:59:18Z | [
"python",
"pandas",
"global",
"local"
] |
How to join a consecutive tuples by comma in nested list? | 37,846,381 | <p>I have a four inputs values from user as follows:</p>
<pre><code>numbers[1, 2]
numbersLetters={'E': 1,'K': 2}
RandomFrequency="0.5"
</code></pre>
<p>Here, My aim is to randomize the numbers list and get the random no which has > 0.5.</p>
<p>Then, get the letter of selected random no from numbersLetters dictionary... | 0 | 2016-06-15T21:49:35Z | 37,846,397 | <p>You are appending a tuple <em>inside a list</em>:</p>
<pre><code>mut.append([tuple(str(pos)+res)])
</code></pre>
<p>Remove the <code>[...]</code> brackets; these create your nested list objects, you don't need it:</p>
<pre><code>mut.append(tuple(str(pos)+res))
</code></pre>
<p>Rather than concatenate characters ... | 0 | 2016-06-15T21:50:27Z | [
"python",
"list",
"dictionary",
"random",
"tuples"
] |
SymPy cannot lambdify Product | 37,846,492 | <p>I'm using SymPy 1.0 and Python 2.7. I want to compute the sum of first 100 integer numbers:</p>
<p>This code runs succesfully</p>
<pre class="lang-py prettyprint-override"><code>import sympy as sy
from sympy.tensor import IndexedBase, Idx
import numpy as np
x = sy.IndexedBase('x')
i = sy.symbols('i', cls=Idx)
s =... | 3 | 2016-06-15T21:57:11Z | 37,848,326 | <h2>When the limits of the <code>Product</code> are known in advance</h2>
<p>You could work around the problem by calling <code>.doit()</code> to expand the <code>Product</code> into its component parts:</p>
<pre><code>In [104]: s = sy.Product(x[i], (i, 1, 10)); s
Out[104]: Product(x[i], (i, 1, 10))
In [105]: s.doit... | 3 | 2016-06-16T01:15:02Z | [
"python",
"sympy"
] |
SQLAlchemy Rollback in MSSQL on Inserts | 37,846,515 | <p>I am trying to do multiple inserts to a MSSQL database by directly using the SqlAlchemy engine. </p>
<pre><code>table = metadata.tables['TestTable']
ins = table.insert()
with engine.begin() as conn:
conn.execute(ins, data)
</code></pre>
<p>The first insert will work not problem. The second insert will attempt ... | 0 | 2016-06-15T21:58:53Z | 38,003,430 | <p>It turns out that when there is an error in the transaction SQLAlchemy will still rollback, whether you set reset_on_return to "commit" or not. I was attempting to insert np.nan values from a pandas dataframe, causing the error.</p>
| 0 | 2016-06-23T23:25:26Z | [
"python",
"sqlalchemy"
] |
Celery: Received unregistered task of type <AsyncResult: [hash]> | 37,846,630 | <p>In all of the similar problems I've seen on stackOverflow:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/9769496/celery-received-unregistered-task-of-type-run-example">Celery Received unregistered task of type (run example)</a></li>
<li><a href="http://stackoverflow.com/questions/12108639/getting-error-r... | 0 | 2016-06-15T22:08:53Z | 37,847,830 | <p>I've determined the problem, and it's from using group.</p>
<p>By passing the chain signature an argument, it's automatically applied asynchronously. By using group, I'm grouping the asyncResult object, which doesn't make any sense. I've altered the execution thusly:</p>
<pre><code>def run_process(self, resource_g... | 1 | 2016-06-16T00:13:08Z | [
"python",
"redis",
"rabbitmq",
"celery"
] |
sort nested defaultdict within a list of dictionaries | 37,846,632 | <p>Having trouble wrapping my head around how to order this list which consists of nested defaultdicts. I was able to sort by 'registration' key and the 'classes' value with this;</p>
<pre><code>sorted(dict1.items(), key=itemgetter(1), reverse=True)
</code></pre>
<p>Which produced;</p>
<p><code>[('registration', {'c... | 0 | 2016-06-15T22:09:05Z | 37,846,746 | <p>The <code>key</code>parameter to sort or sorted can be any callable. This callable should return objects taht are directly comparable with Python's <code>==</code> and <code><=</code> operators. There is no need for the object passed as <code>key</code> to be the callable returned by <code>itemgetter</code> or so... | 0 | 2016-06-15T22:17:56Z | [
"python",
"sorting",
"dictionary",
"nested",
"defaultdict"
] |
Phase at which peak of interference pattern occurs after adding 2 sine waves | 37,846,664 | <p>Given 2 sine waves, I calculate the resultant sine waves by adding them. Now I want to calculate phase at which peaks of the interference pattern occurs.</p>
<p>here is the plot generated by me:
<img src="http://i.stack.imgur.com/3HFnr.png" alt="enter image description here"> </p>
<p>and here is the image I am try... | 0 | 2016-06-15T22:11:27Z | 37,909,857 | <p>Use the <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.signal.hilbert.html" rel="nofollow">Hilbert Transform</a> to calculate the <em>Analytic Signal</em> and hence the <a href="https://en.wikipedia.org/wiki/Analytic_signal#Envelope_and_instantaneous_phase" rel="nofollow">envelope and inst... | 2 | 2016-06-19T17:21:07Z | [
"python",
"signal-processing"
] |
Vectorization - Adding numpy arrays without loops? | 37,846,676 | <p>So I have the following numpy arrays:</p>
<pre><code>c = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
X = array([[10, 15, 20, 5],
[ 1, 2, 6, 23]])
y = array([1, 1])
</code></pre>
<p>I am trying to add each <code>1x4</code> row in the <code>X</code> ... | 2 | 2016-06-15T22:12:26Z | 37,846,968 | <p>Firstly, your code seems to work in general if you transpose <code>X</code>. For example:</p>
<pre><code>c = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
X = array([[10, 15, 20, 5],
[ 1, 2, 6, 23]]).transpose()
y = array([1, 2])
c[:,y] += X
print c
... | 0 | 2016-06-15T22:37:40Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
Vectorization - Adding numpy arrays without loops? | 37,846,676 | <p>So I have the following numpy arrays:</p>
<pre><code>c = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
X = array([[10, 15, 20, 5],
[ 1, 2, 6, 23]])
y = array([1, 1])
</code></pre>
<p>I am trying to add each <code>1x4</code> row in the <code>X</code> ... | 2 | 2016-06-15T22:12:26Z | 37,847,591 | <p>My first thought when I saw your desired calculation, was to just sum the 2 rows of <code>X</code>, and add that to the 2nd column of <code>c</code>:</p>
<pre><code>In [636]: c = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
In [637]: c[:,1]+=X.sum(axis=0)
In [63... | 3 | 2016-06-15T23:44:14Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
Vectorization - Adding numpy arrays without loops? | 37,846,676 | <p>So I have the following numpy arrays:</p>
<pre><code>c = array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
X = array([[10, 15, 20, 5],
[ 1, 2, 6, 23]])
y = array([1, 1])
</code></pre>
<p>I am trying to add each <code>1x4</code> row in the <code>X</code> ... | 2 | 2016-06-15T22:12:26Z | 37,848,351 | <p>This is the solution I came up with:</p>
<pre><code>def my_func(c, X, y):
cc = np.zeros((len(y), c.shape[0], c.shape[1]))
cc[range(len(y)), :, y] = X
return c + np.sum(cc, 0)
</code></pre>
<p>The following interactive session demonstrates how it works:</p>
<pre><code>>>> my_func(c, X, y)
arra... | 0 | 2016-06-16T01:17:56Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
how to create periodictask in celery and django for an specific model instance | 37,846,683 | <p>I have a Django model Person:</p>
<pre><code>class Person(models.Model):
first_name = models.CharField(max_length=100, blank=False, null=False)
last_name = models.CharField(max_length=100, blank=False, null=False)
cellphone = models.CharField(max_length=20)
phone = models.CharField(max_length=15)
... | 0 | 2016-06-15T22:13:19Z | 37,847,305 | <p>You can try the following:</p>
<p>1) Add a field 'last_activity' to your model which automatically updates the timestamp of the last activity day of the user.</p>
<p>2) Now create a task which will run after 45 days of the first instance. It will check for all the users whether the timestamp of last_activity_day i... | 0 | 2016-06-15T23:09:10Z | [
"python",
"django",
"celery"
] |
Getting dependencies in a Python development environment | 37,846,702 | <p>When working with JVM languages a pattern commonly followed is to use a build system (ant+ivy / maven / gradle), where using a build file, the dependencies of your code can be defined. The build system is able to fetch these dependencies when you build your code. Moreover IDEs like Eclipse/IntelliJ are also able to ... | 0 | 2016-06-15T22:14:22Z | 37,846,965 | <p>I guess <a href="https://pip.pypa.io/en/stable/user_guide/#requirements-files" rel="nofollow">requirements.txt</a> is what you are looking for. For example, PyCharm IDE will definitely see it as a dependency list.</p>
| 1 | 2016-06-15T22:37:19Z | [
"python",
"dependencies",
"build-process"
] |
Getting dependencies in a Python development environment | 37,846,702 | <p>When working with JVM languages a pattern commonly followed is to use a build system (ant+ivy / maven / gradle), where using a build file, the dependencies of your code can be defined. The build system is able to fetch these dependencies when you build your code. Moreover IDEs like Eclipse/IntelliJ are also able to ... | 0 | 2016-06-15T22:14:22Z | 37,846,989 | <p>This is managed by <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">virtualenv</a> and the <code>pip install -r requirements.txt</code> command. More info here: <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">Virtual Environments</a></p>
| 1 | 2016-06-15T22:39:04Z | [
"python",
"dependencies",
"build-process"
] |
Django TypeError: 'ModelBase' object is not iterable | 37,846,721 | <p>I'm struggling to debug a vague error message in <strong>Django</strong> when executing any migration command:</p>
<pre><code>Operations to perform:
Synchronize unmigrated apps: rest_framework_docs, staticfiles, django_coverage, django_extensions, storages, corsheaders, gis, templated_email, rest_framework, djang... | 0 | 2016-06-15T22:15:44Z | 37,855,526 | <p>In your first migration:</p>
<pre><code>migrations.CreateModel(
name='ReputationAction',
...
bases=(models.Model),
),
</code></pre>
<p>You need to change <code>bases=(models.Model),</code> to <code>bases=(models.Model,),</code> (note the extra comma). This will make <code>bases</code> a tuple containin... | 1 | 2016-06-16T09:43:23Z | [
"python",
"django",
"python-3.x"
] |
python`setup.py upload` error code on Linux | 37,846,755 | <p>I'm trying to publish a python package from jenkins. When publishing to an already published version, I see:</p>
<p><code>Submitting dist/mylib-0.2.13.tar.gz to http://mypypiserver/api/pypi/pypi-release-local
Upload failed (403): Forbidden</code></p>
<p>However, the shell script that calls this is unable to determ... | 1 | 2016-06-15T22:18:37Z | 37,847,174 | <p>After some research, I discovered this is a bug in <code>distutils</code>. See <a href="https://bugs.python.org/issue21722" rel="nofollow">https://bugs.python.org/issue21722</a> <code>teach distutils "upload" to exit with code != 0 when error occurs</code></p>
<p>This was patched and backported to python 2.7.7</p>
... | 0 | 2016-06-15T22:56:28Z | [
"python",
"jenkins",
"setuptools"
] |
Unsupported operands for range and float, what am I doing wrong? | 37,846,771 | <p>I'm trying to pass a range of numbers to a function and have that function then give me an array of numbers back. This is my code and the error I've received.
I'm brand new to python, so this might be a silly question.
<img src="http://i.stack.imgur.com/TwIwp.jpg" alt="This is my snippet of code"></p>
| 0 | 2016-06-15T22:20:02Z | 37,846,794 | <p><code>t</code> is a range type. Python is telling you that you can't subtract a <code>range</code> and a float. In other words, <code>t-152.5</code> is what's causing your problem.</p>
| 0 | 2016-06-15T22:22:03Z | [
"python",
"arrays"
] |
Unsupported operands for range and float, what am I doing wrong? | 37,846,771 | <p>I'm trying to pass a range of numbers to a function and have that function then give me an array of numbers back. This is my code and the error I've received.
I'm brand new to python, so this might be a silly question.
<img src="http://i.stack.imgur.com/TwIwp.jpg" alt="This is my snippet of code"></p>
| 0 | 2016-06-15T22:20:02Z | 37,846,817 | <p>As the error states, the binary <code>-</code> operator needs to numbers and can't work with a iterable.</p>
<p>Use <strong>list comprehension</strong> to achieve this behaviour:</p>
<pre><code>V_esc = [232+15*math.cos((2*math.pi)*(t-152.5/365.25)) for t in range(5)]
</code></pre>
| 1 | 2016-06-15T22:24:30Z | [
"python",
"arrays"
] |
Unsupported operands for range and float, what am I doing wrong? | 37,846,771 | <p>I'm trying to pass a range of numbers to a function and have that function then give me an array of numbers back. This is my code and the error I've received.
I'm brand new to python, so this might be a silly question.
<img src="http://i.stack.imgur.com/TwIwp.jpg" alt="This is my snippet of code"></p>
| 0 | 2016-06-15T22:20:02Z | 37,847,537 | <p>The main thing to keep in mind here is that
<code>t = range(5)</code> returns an iterable object. That is, it basically contains the ability to return numbers from 0 to 4.</p>
<p>You can verify this by the following piece of code:</p>
<pre><code>for i in t:
print(i)
0
1
2
3
4
</code></pre>
<p>So you cann... | 0 | 2016-06-15T23:38:22Z | [
"python",
"arrays"
] |
Python: static class variables like in Java? | 37,846,814 | <p>In Java, I can give a class a static variable, here it's counter.
I'm incrementing it in the constructor, which gives it the purpose of keeping track of how many objects have been instantiated from this class</p>
<pre><code>class Thing
{
private static int counter;
public Thing()
{
counter++;
... | 2 | 2016-06-15T22:24:12Z | 37,846,900 | <pre><code>class Thing:
counter = 0
def __init__(self):
Thing.counter += 1
def getCounter():
return Thing.counter
</code></pre>
<p>Example</p>
<pre><code>>>> a = Thing()
>>> b = Thing()
>>> Thing.getCounter()
2
</code></pre>
| 2 | 2016-06-15T22:32:05Z | [
"java",
"python",
"class",
"oop"
] |
Create continuous graph using matplotlib and pandas | 37,846,945 | <p>I have a dataframe like this.</p>
<pre><code> column1 column2 column3
MyIndexes
7 22 90 98
8 50 06 56
23 60 58 44
49 30 62 00
</code></pre>
<p>I am using df.plot to plot a line cha... | 1 | 2016-06-15T22:35:56Z | 37,847,100 | <p>When I construct the dataframe as such:</p>
<pre><code>df = pd.DataFrame([[22, 90, 98],
[50, 06, 56],
[60, 58, 44],
[30, 62, 00]],
index=pd.Index([7, 8, 23, 49], name='MyIndexex'),
columns=['column1', 'column2', 'column3'])... | 1 | 2016-06-15T22:49:43Z | [
"python",
"pandas",
"matplotlib",
"plot",
"dataframe"
] |
ConnectionResetError: [WinError 10054] while trying to access a website using Selenium Webdriver Python code | 37,847,004 | <p>i am new to Selenium Web Driver and I am trying to access a specific website via Selenium Webdriver using python. i am getting the below error:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 9, in <module>
driver = webdriver.Firefox()
File "C:\Python34\lib\site-packages\seleniu... | 0 | 2016-06-15T22:39:42Z | 38,004,470 | <p>I had the same problem. Then I use the other versions of Firefox like this:</p>
<p><a href="http://i.stack.imgur.com/9iRq7.png" rel="nofollow"><img src="http://i.stack.imgur.com/9iRq7.png" alt="enter image description here"></a></p>
<p>Then solve the problem.</p>
| 0 | 2016-06-24T01:48:11Z | [
"python",
"sockets",
"selenium",
"selenium-webdriver"
] |
Changing Active Directory user password in Python 3.x | 37,847,042 | <p>I am trying to make a Python script that will open an LDAP connection to a server running AD, take a search entry (in this case a name), search for that entry and change that users password to a randomly generated password (as well as set the option to change password on logon) and then send them an automated secure... | 2 | 2016-06-15T22:43:52Z | 37,890,705 | <p>ldap3 contains a specific method for changing AD password, just add the following after you generated a new password:</p>
<p><code>
dn = conn.entries[0].entry_get_dn() # supposing you got back a single entry
conn.extend.microsoft.modify_password(dn, None, new_password)
</code></p>
<p>This should properly encode t... | 1 | 2016-06-17T21:36:18Z | [
"python",
"active-directory",
"passwords",
"ldap",
"python-3.5"
] |
uniquify an array/list with a tolerance in python (uniquetol equivalent) | 37,847,053 | <p>I want to find the unique elements of an array in a certain range of tolerance</p>
<p>For instance, for an array/list</p>
<pre><code>[1.1 , 1.3 , 1.9 , 2.0 , 2.5 , 2.9]
</code></pre>
<p>Function will return </p>
<pre><code>[1.1 , 1.9 , 2.5 , 2.9]
</code></pre>
<p>If the tolerance is <code>0.3</code></p>
<p>at ... | 3 | 2016-06-15T22:44:41Z | 37,847,116 | <p>With <code>A</code> as the input array and <code>tol</code> as the tolerance value, we could have a vectorized approach with <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a>, like so -</p>
<pre><code>A[~(np.triu(np.abs(A[:,None] - A) &... | 3 | 2016-06-15T22:51:16Z | [
"python",
"numpy",
"unique"
] |
uniquify an array/list with a tolerance in python (uniquetol equivalent) | 37,847,053 | <p>I want to find the unique elements of an array in a certain range of tolerance</p>
<p>For instance, for an array/list</p>
<pre><code>[1.1 , 1.3 , 1.9 , 2.0 , 2.5 , 2.9]
</code></pre>
<p>Function will return </p>
<pre><code>[1.1 , 1.9 , 2.5 , 2.9]
</code></pre>
<p>If the tolerance is <code>0.3</code></p>
<p>at ... | 3 | 2016-06-15T22:44:41Z | 37,865,218 | <p>In pure Python 2, I wrote the following:</p>
<pre><code>a = [1.1, 1.3, 1.9, 2.0, 2.5, 2.9]
# Per http://fr.mathworks.com/help/matlab/ref/uniquetol.html
tol = max(map(lambda x: abs(x), a... | 1 | 2016-06-16T16:57:36Z | [
"python",
"numpy",
"unique"
] |
Pandas: Getting the distance to the row used to fill the missing/na values | 37,847,150 | <p>I will do my best to explain this.</p>
<p>I have a pandas dataframe and I am trying to get the distance to the row which was used to fill a row of <code>nan</code> values in the same dataframe.</p>
<p>To elaborate, say I have the following dataframe (<code>df</code>) that contains 2 rows of <code>nan</code> values... | 2 | 2016-06-15T22:54:02Z | 37,847,299 | <p>You can use this:</p>
<pre><code>def prox(series):
groupby_idx = series.notnull().cumsum()
groupby = series.groupby(groupby_idx)
return groupby.apply(lambda x: pd.Series(range(len(x)))).values
prox(df1.A)
array([0, 0, 1, 2], dtype=int64)
</code></pre>
<p>then assign to df1:</p>
<pre><code>df1['Proxi... | 1 | 2016-06-15T23:08:04Z | [
"python",
"pandas",
"dataframe",
null
] |
Pandas: Getting the distance to the row used to fill the missing/na values | 37,847,150 | <p>I will do my best to explain this.</p>
<p>I have a pandas dataframe and I am trying to get the distance to the row which was used to fill a row of <code>nan</code> values in the same dataframe.</p>
<p>To elaborate, say I have the following dataframe (<code>df</code>) that contains 2 rows of <code>nan</code> values... | 2 | 2016-06-15T22:54:02Z | 37,847,422 | <p>May be something like this:</p>
<pre><code>In[1]: df = pd.DataFrame({"A": [1, np.nan, np.nan], "B": [2, np.nan, np.nan]})
In[2]: df.ix[df.B.isnull(), 'distance'] = 1
In[3]: df.distance = df.distance.cumsum()
In[4]: df
Out[4]:
A B distance
0 1.0 2.0 NaN
1 NaN NaN 1.0
2 NaN NaN 2.... | 1 | 2016-06-15T23:21:31Z | [
"python",
"pandas",
"dataframe",
null
] |
Pandas: Getting the distance to the row used to fill the missing/na values | 37,847,150 | <p>I will do my best to explain this.</p>
<p>I have a pandas dataframe and I am trying to get the distance to the row which was used to fill a row of <code>nan</code> values in the same dataframe.</p>
<p>To elaborate, say I have the following dataframe (<code>df</code>) that contains 2 rows of <code>nan</code> values... | 2 | 2016-06-15T22:54:02Z | 37,848,183 | <p>You could use <code>.cumsum()</code> so that each <code>notnull</code> block value gets a unique 'id', <code>.groupby()</code> the result and use <code>.cumcount()</code>, which assigns <code>0</code> to all <code>notnull</code> values and consecutive counts to <code>null</code> values::</p>
<pre><code>df['proximit... | 1 | 2016-06-16T00:56:47Z | [
"python",
"pandas",
"dataframe",
null
] |
mqtt between python and node.js sends only one message | 37,847,157 | <p>I am new to mqtt and python system and I am trying to do some heavy computations in python and send the results to a node.js server.</p>
<p>Every time I run node.js script i get only one result. Here is my simple
code:</p>
<p>simple_mqtt.py</p>
<pre><code>message = "Hello"
x=0
def add():
global x
x = x +... | 0 | 2016-06-15T22:54:33Z | 37,854,081 | <p>You're using the same topic for both control and output.</p>
<p>So after receiving a message with <code>Start</code> your code publishes <code>1</code> to the <code>main/app</code> topic and this is immediately received by the python code in <code>on_message</code> and sets <code>message</code> to <code>1</code></p... | 0 | 2016-06-16T08:41:07Z | [
"python",
"node.js",
"mqtt"
] |
Programmatic Requests to Google Identity Toolkit | 37,847,164 | <p>I'm working on a webapp that uses Google Identity Toolkit for login. We're coming to a point where we need to perform load tests and we definitely want our tests to encompass the whole of our system flow; we want to make sure GITKit doesn't end up being a bottleneck. </p>
<p>However, since GITKit seems to be only u... | 0 | 2016-06-15T22:55:20Z | 37,851,551 | <p>Google Identity Toolkit has a REST API that you can call from your server: <a href="https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyPassword" rel="nofollow">https://developers.google.com/identity/toolkit/web/reference/relyingparty/verifyPassword</a>. A Google server API Key is needed ... | 0 | 2016-06-16T06:35:52Z | [
"python",
"google-app-engine",
"curl",
"google-identity-toolkit"
] |
OpenCV, DMatch objects in Python and Julia don't match | 37,847,201 | <p>I'm trying to implement a feature matching method using OpenCV, but the translation from a Python version to Julia does not match up:</p>
<p>The methods are exactly the same and use the same images for processing. (<code>[:method]</code> is just standard convention for accessing a specific type of method in Julia, ... | 1 | 2016-06-15T22:58:32Z | 37,872,032 | <p>PyCall will convert nested lists in Python to two-dimensional arrays in Julia. For instance,</p>
<pre><code>julia> pyeval("[[1, 2], [3, 4]]")
2Ã2 Array{Any,2}:
1 2
3 4
</code></pre>
<p>This means that to access the first row, as you tried <code>matches[1]</code> for, you need <code>matches[1,:]</code>. To ... | 1 | 2016-06-17T02:07:50Z | [
"python",
"c++",
"opencv",
"julia-lang",
"feature-detection"
] |
plotting a sequence results in: "ValueError: x and y must have same first dimension" | 37,847,297 | <p>I'm a beginner here and I'm experiencing a problem when I'm trying to plot a sequence:</p>
<p>My code gives me this error message:
"ValueError: x and y must have same first dimension"</p>
<pre><code>hold(True)
x=[0.5]
for r in arange(2,4,0.1):
for i in range(170):
xn= x[-1]
xnp1 = r*xn*(1-xn)
... | 1 | 2016-06-15T23:07:58Z | 37,847,411 | <p>You're trying to plot <code>xn</code> (the dependent variable, aka "the y-data") versus <code>rplot</code> (the independent variable, aka "the x-data").</p>
<p>From your code, you'll see that <code>xn</code> refers to the last item in the array <code>x</code>, so it is a <em>single</em> scalar. <code>rplot</code> h... | 0 | 2016-06-15T23:20:11Z | [
"python",
"python-3.x",
"matplotlib"
] |
Trying to identify the errors and provide the python code that accomplishes the task | 37,847,312 | <pre><code>age = 3
name = age
if age = "Bob"
print(name is: age)
</code></pre>
<p>I have to find the errors in this such as "<code>if age =</code> should be <code>if age ==</code>" and finish the code to accomplish the task. </p>
<p>For the errors I have located the following "<code>if age =</code> should be <code>if... | -3 | 2016-06-15T23:09:55Z | 37,847,360 | <p>You're doing fine, except that I expect the last line should read</p>
<pre><code>print ("name is:", name)
</code></pre>
<p>The original checks to see whether the name is "Bob", printing either <strong>True</strong> or <strong>False</strong>.</p>
| 0 | 2016-06-15T23:14:40Z | [
"python"
] |
Trying to identify the errors and provide the python code that accomplishes the task | 37,847,312 | <pre><code>age = 3
name = age
if age = "Bob"
print(name is: age)
</code></pre>
<p>I have to find the errors in this such as "<code>if age =</code> should be <code>if age ==</code>" and finish the code to accomplish the task. </p>
<p>For the errors I have located the following "<code>if age =</code> should be <code>if... | -3 | 2016-06-15T23:09:55Z | 37,847,377 | <p>You have invalid syntax in the print statement. <code>print(name is "Bob")</code> will evaluate to false if name is not Bob because the name is part is not wrapped in quotes. <code>is</code> is a reserved keyword that checks equality and will evaluate to either a true or a false.</p>
<pre><code>print("Name is: ", n... | 0 | 2016-06-15T23:16:09Z | [
"python"
] |
Trying to identify the errors and provide the python code that accomplishes the task | 37,847,312 | <pre><code>age = 3
name = age
if age = "Bob"
print(name is: age)
</code></pre>
<p>I have to find the errors in this such as "<code>if age =</code> should be <code>if age ==</code>" and finish the code to accomplish the task. </p>
<p>For the errors I have located the following "<code>if age =</code> should be <code>if... | -3 | 2016-06-15T23:09:55Z | 37,847,523 | <p>print ("name is: ", name) is the correct syntax</p>
| 0 | 2016-06-15T23:37:04Z | [
"python"
] |
Unicode API response throwing error ''ascii' codec can't encode character u'\u2019' in position 22462' | 37,847,386 | <p>I am making an API call and the response does have unicode characters. Loading this response into a file throws the following error:</p>
<pre><code>'ascii' codec can't encode character u'\u2019' in position 22462
</code></pre>
<p>Tried all combinations of decode and encode ('utf-8').</p>
<p>Here is the code:</p>
... | 0 | 2016-06-15T23:17:49Z | 37,870,511 | <pre><code>inter = resp.text
string_e = inter#.decode('utf-8')
encoded_data = final.encode('utf-8')
</code></pre>
<p>The <code>text</code> property is a Unicode character string, decoded from the original bytes using whatever encoding the Requests module guessed might be in use from the HTTP headers.</p>
<p>You proba... | 0 | 2016-06-16T22:39:39Z | [
"python",
"unicode",
"utf-8"
] |
Viewing dicom image with Bokeh | 37,847,414 | <p>I'm trying to set the graph background to a dicom image. I followed <a href="http://bokeh.pydata.org/en/0.11.1/docs/gallery/image_rgba.html" rel="nofollow">this example</a>, but the image data given from <code>dicom.pixel_array</code> isn't RGBA. I'm not sure how to convert it, either. I'm also not sure what exactly... | 2 | 2016-06-15T23:20:30Z | 37,936,986 | <p>Not being an expert in python, I have had a glance at pydicom's capabilities in handling pixel data. I figured out that pixel_array is the value of the pixel-data attribute of the DICOM dataset <strong>as is</strong> and pydicom does not offer any functionality to convert it into some standard format which can be ha... | 0 | 2016-06-21T06:27:19Z | [
"python",
"dicom",
"bokeh"
] |
Viewing dicom image with Bokeh | 37,847,414 | <p>I'm trying to set the graph background to a dicom image. I followed <a href="http://bokeh.pydata.org/en/0.11.1/docs/gallery/image_rgba.html" rel="nofollow">this example</a>, but the image data given from <code>dicom.pixel_array</code> isn't RGBA. I'm not sure how to convert it, either. I'm also not sure what exactly... | 2 | 2016-06-15T23:20:30Z | 38,341,405 | <p>What you need to do is map the pixel data returned from pixel_array to RGB space. Usually that is done using a look up table (LUT). Take a look at the functions GetImage and GetLUTValue in the <a href="https://github.com/dicompyler/dicompyler-core/blob/master/dicompylercore/dicomparser.py" rel="nofollow">dicomparser... | 0 | 2016-07-13T01:48:10Z | [
"python",
"dicom",
"bokeh"
] |
Starting jupyter notebook programmatically from another notebook | 37,847,440 | <p>Is it possible to start another notebook from the current notebook? I know how to create and save the current notebook but I cannot launch another notebook from the current one.
%run does not work while starting another notebook</p>
| 0 | 2016-06-15T23:24:06Z | 37,858,179 | <p>If I suppose you know the url for the notebook you want to open you could open it in the following way:</p>
<p>This code should be a code cell in your notebook:</p>
<pre><code>%%javascript
window.open('http://localhost:8888/notebooks/Name_of_the_notebook.ipynb')
</code></pre>
<p>If you don't know the complete pat... | 2 | 2016-06-16T11:43:06Z | [
"python",
"ipython",
"jupyter"
] |
Use level of pandas index as a part of an output file name | 37,847,499 | <p>I am trying to loop through a data frame using </p>
<pre><code>for index, row in df.iterrows():
#Do Stuff
</code></pre>
<p>I have a pandas data frame that looks like:</p>
<pre><code> pt_ID Easting Northing Attribute
Site Survey_Date
M006R 2004-... | 0 | 2016-06-15T23:33:48Z | 37,847,518 | <p>run this to get a better idea:</p>
<pre><code>for index, row in df.head().iterrows():
print "Site: {}, Survey_Date {}".format(*index)
</code></pre>
<p>Essentially, the <code>index</code> variable is a tuple with each level of the multiindex. Access the level you want with <code>index[0]</code> for <code>'Site... | 0 | 2016-06-15T23:36:57Z | [
"python",
"pandas",
"multi-index"
] |
reindex sorted pandas dataframe | 37,847,521 | <p>I have a dataframe like so:</p>
<pre><code> Column A Column B Date Value
1 A 1 2011-01-01 10
2 B 1 2011-01-01 10
3 A 2 2011-01-01 10
4 B 2 2011-01-01 10
5 A 1 2011-01-02 10
6 B ... | 1 | 2016-06-15T23:37:01Z | 37,847,638 | <p>Try this:</p>
<pre><code>df.set_index(['Column A', 'Column B', 'Date']).unstack().stack(dropna=False).sort_index(level=[2, 0]).reset_index()
Column A Column B Date Value
0 A 1 2011-01-01 10.0
1 B 1 2011-01-01 10.0
2 A 2 2011-01-01 10.0
3 ... | 3 | 2016-06-15T23:50:54Z | [
"python",
"pandas"
] |
gender input loop keeps repeating even if I enter "m" or "f" | 37,847,531 | <p>If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why? </p>
<pre><code>gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender... | 0 | 2016-06-15T23:37:42Z | 37,847,551 | <p>Just say <code>gender</code> is <code>m</code>. Look at this statement:</p>
<pre><code>while gender != 'm' or gender != 'f':
</code></pre>
<p>Is <code>gender!='m'</code>? No. <code>Or</code>... Is <code>gender!='f'</code>? Yes! OK, keep <code>while</code>ing!</p>
<p>You don't want <code>or</code>, you want <code>... | 3 | 2016-06-15T23:40:26Z | [
"python"
] |
gender input loop keeps repeating even if I enter "m" or "f" | 37,847,531 | <p>If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why? </p>
<pre><code>gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender... | 0 | 2016-06-15T23:37:42Z | 37,847,559 | <p>Because of this line :
<code>while gender != 'm' or gender != 'f':</code></p>
<p>Use instead :
<code>while gender != 'm' and gender != 'f':</code> </p>
<p><code>gender</code> cannot simultaneously contain 'm' and 'f'</p>
| 0 | 2016-06-15T23:41:16Z | [
"python"
] |
gender input loop keeps repeating even if I enter "m" or "f" | 37,847,531 | <p>If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why? </p>
<pre><code>gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender... | 0 | 2016-06-15T23:37:42Z | 37,847,571 | <p>The basic fundamental </p>
<p>True or True : True</p>
<p><strong>True or False : True</strong></p>
<p><strong>False or True : True</strong></p>
<p>False or False : False</p>
<p>You have to continue asking for input as long as both the conditions are not satisfied.</p>
<p>Or has to be replaced by 'and'.</p>
| 0 | 2016-06-15T23:42:16Z | [
"python"
] |
gender input loop keeps repeating even if I enter "m" or "f" | 37,847,531 | <p>If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why? </p>
<pre><code>gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender... | 0 | 2016-06-15T23:37:42Z | 37,847,635 | <p>Try: </p>
<pre><code>gender = raw_input('m/f?')
while True:
print("Type 'm' or 'f'")
gender = raw_input('m/f? ')
if gender=='m' or gender=='f':
break
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender = 'her'
</code></pre>
<p>print("It read {}".format(gender))</p>
| 0 | 2016-06-15T23:50:29Z | [
"python"
] |
gender input loop keeps repeating even if I enter "m" or "f" | 37,847,531 | <p>If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why? </p>
<pre><code>gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender... | 0 | 2016-06-15T23:37:42Z | 37,847,661 | <p>There's a number of answers already, but I think the most Pythonic way, which also eliminates the AND/OR confusion is, and is easily extendable if you want to add, say, <code>o</code> for <code>other</code></p>
<pre><code>while gender not in 'mf':
</code></pre>
<p>That is, while <code>gender</code> is not present ... | 0 | 2016-06-15T23:53:21Z | [
"python"
] |
gender input loop keeps repeating even if I enter "m" or "f" | 37,847,531 | <p>If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why? </p>
<pre><code>gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender... | 0 | 2016-06-15T23:37:42Z | 37,847,687 | <p>In your while, you are checking to see if either the string gender does not equal 'm' OR 'f', which will always be the case because it cannot be both.</p>
<p>Change or to and to fix this.</p>
| 0 | 2016-06-15T23:56:43Z | [
"python"
] |
How can I access the elements of a foreign set for a model in Django's get_context_data method? | 37,847,610 | <p>I have a generic <code>DetailView</code> in Django 1.9.7, which uses my model <code>Quiz</code> to show a super-time-saving no-hassle view (thank you Django). However, I'm struggling to access a related foreign key set on my <code>Quiz</code> object (a set of <code>QuizQuestion</code> objects). My model is as follow... | 1 | 2016-06-15T23:47:42Z | 37,848,160 | <p>You are referring to the <em>model</em>, you need to refer to the <em>instance</em> (the object for which the view is showing the details) as relations are for instances and not models. You can get the instance with <code>self.get_object()</code>:</p>
<pre><code>def get_context_data(self, **kwargs):
context = s... | 2 | 2016-06-16T00:54:35Z | [
"python",
"django",
"generics",
"view",
"model"
] |
String slicing not working for accented characters | 37,847,647 | <p>String slicing in Python 2.7 is very useful to get a substring. This works nicely for ASCII characters, for example</p>
<pre><code>>>> s = "Antonio"
>>> s[5:7]
'io'
</code></pre>
<p>but fails in the presence of accented characters, for example</p>
<pre><code>>>> s = "António"
>>&... | 0 | 2016-06-15T23:51:34Z | 37,847,672 | <p>In Python 2.7, strings and unicode strings are different objects. To declare a Unicode string literal, prefix it with a <code>u</code>:</p>
<pre><code>Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" ... | 2 | 2016-06-15T23:54:53Z | [
"python",
"string"
] |
String slicing not working for accented characters | 37,847,647 | <p>String slicing in Python 2.7 is very useful to get a substring. This works nicely for ASCII characters, for example</p>
<pre><code>>>> s = "Antonio"
>>> s[5:7]
'io'
</code></pre>
<p>but fails in the presence of accented characters, for example</p>
<pre><code>>>> s = "António"
>>&... | 0 | 2016-06-15T23:51:34Z | 37,848,028 | <p>I finally found the answer to my problem. I just have to read the text file like this:</p>
<pre><code>import codecs
with codecs.open(ficheiro, encoding='utf-8') as fin:
for line in fin:
... # then here line[5:7] will work correctly for "António" and "Antonio"
</code></pre>
<p>Thanks to Derek Dohler wh... | 1 | 2016-06-16T00:37:24Z | [
"python",
"string"
] |
Including external shared intel's mkl library in c extension for python | 37,847,760 | <p>I wrote a python c extension that uses routine from Intel's math kernel library (mkl). This is the first time that I write a c extension. I just learned that today.</p>
<p>The c extension compiled. But when I import it in python, it says undefined symbol, and can't find a function that is defined in the mkl.</p>
<... | 0 | 2016-06-16T00:06:38Z | 37,863,286 | <p>oopcode's answer in <a href="http://stackoverflow.com/questions/27149849/python-importerror-undefined-symbol-g-utf8-skip">Python, ImportError: undefined symbol: g_utf8_skip</a> works.
The situation improved with the following.</p>
<p>importing the c extension into python has no error.
Calling the c extension from ... | 0 | 2016-06-16T15:21:20Z | [
"python",
"numpy",
"python-c-api",
"intel-mkl",
"python-c-extension"
] |
web scraping a webpage which has dynamic contents loaded via ajax | 37,847,797 | <p>Say I wish to scrape products on this <a href="http://shop.coles.com.au/online/national/bread-bakery/fresh/bread#pageNumber=2&currentPageSize=20">page</a>(<a href="http://shop.coles.com.au/online/national/bread-bakery/fresh/bread#pageNumber=2&currentPageSize=20">http://shop.coles.com.au/online/national/bread... | 5 | 2016-06-16T00:10:09Z | 37,848,086 | <p>You can get the <code>catalogId</code> and other parameter values needed to make the POST request from the <code>form</code> with <code>id="search"</code>:</p>
<pre><code><form id="search" name="search" action="http://shop.coles.com.au/online/SearchDisplay?pageView=image&amp;catalogId=10576&amp;beginInde... | 2 | 2016-06-16T00:44:11Z | [
"python",
"web-scraping",
"scrapy"
] |
Django form, view, and forms.py not working together | 37,847,799 | <p>My first foray into Django, allows the user to input a day of the week, and searches my database for restaurants open on that given day. Right now, the restaurant objects (<code>Resto</code>) have a <code>days_open</code> attribute, with each day separated by a comma (Monday, Tuesday, etc...).</p>
<p>When I input a... | 2 | 2016-06-16T00:10:23Z | 37,848,022 | <p>I presume what you are trying to show is the <code>RestoForm</code> in that case the index method is not correct. It should be</p>
<pre><code>def index(request):
form = RestoForm()
return render(request, 'form.html', {'form': form })
</code></pre>
<p>And then your template should change as</p>
<pre><code>... | 1 | 2016-06-16T00:36:57Z | [
"python",
"django",
"django-forms"
] |
Django form, view, and forms.py not working together | 37,847,799 | <p>My first foray into Django, allows the user to input a day of the week, and searches my database for restaurants open on that given day. Right now, the restaurant objects (<code>Resto</code>) have a <code>days_open</code> attribute, with each day separated by a comma (Monday, Tuesday, etc...).</p>
<p>When I input a... | 2 | 2016-06-16T00:10:23Z | 37,848,066 | <p>The <code>[]</code> means that your <code>.filter()</code> returned no results, its not surprising as you have a few issues with your code, lets start from the top:</p>
<ol>
<li>You are declaring a form that you never use.</li>
<li>You are trying to catch an exception that is never raised by <code>.filter()</code><... | 0 | 2016-06-16T00:41:31Z | [
"python",
"django",
"django-forms"
] |
Why is my Sieve of Eratosthenes removing the non-prime numbers? | 37,847,853 | <p>My code: </p>
<pre><code>def sieve(list1):
not_prime = set()
primes = []
for i in range(2, list1+1):
if i in not_prime:
continue
for x in range(i*2, list1+1, i):
not_prime.add(x)
primes.append(i)
return primes
</code></pre>
<p>I am trying to keep the... | 0 | 2016-06-16T00:16:13Z | 37,848,051 | <p>Well in that case, cant you just append zero instead of continue in the no_prime clause? </p>
<pre><code>def sieve(list1):
not_prime = set()
primes = []
for i in range(2, list1+1):
if i in not_prime:
primes.append(0);
continue;
for x in range(i*2, list1+1, i):
... | 0 | 2016-06-16T00:39:56Z | [
"python",
"sieve-of-eratosthenes"
] |
variable not setting correctly? | 37,847,863 | <p>Anyone have any idea what is wrong with my code? I keep receiving an getting an empty <code>source</code> variable (AKA filled with spaces) when I run it: (If it helps, I'm running on 2.7.11 on Linux, trying to run Befunge-93 programs receiving one character at a time)</p>
<pre><code>import readchar
RIGHT = 0
DOWN... | 0 | 2016-06-16T00:17:26Z | 37,847,992 | <p>The issue is in line 194:</p>
<pre><code>def current_char():
return source[position[0]][position[1]]
</code></pre>
<p>You're treating this as you're certain position is not None, position[0] and position[1] are not None, but python isn't aware of this and there's no value, so you have to check position, position... | 0 | 2016-06-16T00:32:52Z | [
"python",
"python-2.7"
] |
variable not setting correctly? | 37,847,863 | <p>Anyone have any idea what is wrong with my code? I keep receiving an getting an empty <code>source</code> variable (AKA filled with spaces) when I run it: (If it helps, I'm running on 2.7.11 on Linux, trying to run Befunge-93 programs receiving one character at a time)</p>
<pre><code>import readchar
RIGHT = 0
DOWN... | 0 | 2016-06-16T00:17:26Z | 37,848,482 | <p>I think your problem is in <code>move</code> function, there you go add some value to your position list but you don't correct it in to still be in range</p>
<p>in your original function</p>
<pre><code>def move():
position[0]+=delta(direction)[0] % 80
position[1]+=delta(direction)[1] % 25
</code></pre>
<p... | 0 | 2016-06-16T01:34:27Z | [
"python",
"python-2.7"
] |
Python Array index is out of range but works after printing | 37,847,959 | <p>Here is my code:</p>
<pre><code>pixel = pixels[pixel_position * pixel_byte_width :(pixel_position + 1) * pixel_byte_width]
r = pixel[0]
g = pixel[1]
b = pixel[2]
</code></pre>
<p>Here is the error:</p>
<pre><code>line 25, in wr
g = pixel[1]
IndexError: array index out of range
</code></pre>
<p>Now let's say I do... | 0 | 2016-06-16T00:29:26Z | 37,911,919 | <p>I'm not certain about how that <code>array</code> object requires its indexing, but you can avoid indexing by unpacking your values directly from the array: </p>
<pre><code>r, g, b = pixel
</code></pre>
<p>If it does contain three elements, you're sure to have your values without any errors.</p>
| 0 | 2016-06-19T21:15:32Z | [
"python",
"arrays"
] |
Extract multiple strings between hot characters from a paragraph | 37,847,967 | <p>Now I cant really find a way to title this but I can explain what I am going for in code.</p>
<p>So I am able to take a users comment and check to see if it has these "[[Keyword]]" modifiers. Now I want to expand it further to allow more than one. </p>
<p>This is what happens if a user inputs more than one modifie... | 2 | 2016-06-16T00:30:35Z | 37,848,012 | <p>The <code>.*</code> is <em>greedy</em> by default. You want it to match in <em>non-greedy</em> mode so it matches as little as possible. You can do that by using <code>.*?</code> instead of <code>.*</code>. You should also use <code>re.findall</code> to get all the matches instead of <code>re.search</code>, which ... | 1 | 2016-06-16T00:35:23Z | [
"python",
"python-3.x"
] |
Extract multiple strings between hot characters from a paragraph | 37,847,967 | <p>Now I cant really find a way to title this but I can explain what I am going for in code.</p>
<p>So I am able to take a users comment and check to see if it has these "[[Keyword]]" modifiers. Now I want to expand it further to allow more than one. </p>
<p>This is what happens if a user inputs more than one modifie... | 2 | 2016-06-16T00:30:35Z | 37,848,047 | <pre><code>import re
text = 'comment in this case is "I want to [[find]] [[this]] [[Special]] word.'
result = re.findall("(?:\[\[(.*?)\]\])", text)
for term in result:
print(term + "\n")
</code></pre>
| 0 | 2016-06-16T00:39:15Z | [
"python",
"python-3.x"
] |
How to get latest objects from SQLAlchemy | 37,848,018 | <p>I have a single table that contains a number of revisions for an entity in another table (Tasks). So each TaskRevision row has a unique autoincremented id and a reference to the Task id.</p>
<p>How do I find the latest revision of all tasks? I have tried:</p>
<pre><code>session.query(TaskRevision.id).order_by(Task... | 1 | 2016-06-16T00:36:17Z | 37,848,319 | <p>This is slightly annoying to do, but taken from <a href="http://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group">this question</a>:</p>
<pre><code>subq = session.query(TaskRevision.task_id, func.max(TaskRevision.id).label("max_id")) \
.group_by(TaskRevision.task_id).subquer... | 1 | 2016-06-16T01:14:06Z | [
"python",
"sqlalchemy"
] |
Mock_open CSV file not getting any data | 37,848,020 | <p>I am trying to unit test a piece of code:</p>
<pre><code>def _parse_results(self, file_name):
results_file = open(file_name)
results_data = list(csv.reader(results_file))
index = len(results_data[1])-1
results_file.close()
return float(results_data[1][index])
</code></pre>
<p>by using mock_open... | 3 | 2016-06-16T00:36:34Z | 38,135,849 | <p>This really got me too, and was a nightmare to pinpoint. To use your example code, this works</p>
<pre><code>results_data = list(csv.reader(results_file.read()))
</code></pre>
<p>and this works</p>
<pre><code>results_data = list(csv.reader(results_file.readlines()))
</code></pre>
<p>but this doesn't work</p>
<... | 0 | 2016-07-01T01:57:02Z | [
"python",
"csv",
"mocking"
] |
Python: Pandas: Rolling Windows - mean() works but variance() doesn't? | 37,848,021 | <p>I have the following data which is recorded in seconds: <a href="http://pastebin.com/wBSJWYn2" rel="nofollow">http://pastebin.com/wBSJWYn2</a></p>
<p>I want to capture various summery statistics like the mean, variance, etc on it for 1 minute intervals. So I'm running these functions on <code>sensor_data.rolling(w... | 1 | 2016-06-16T00:36:53Z | 37,848,093 | <p>for starters, this will get you going.</p>
<pre><code>sensor_data.groupby(pd.Grouper(level=0, freq='Min')).describe()
</code></pre>
<p>you can build a custom function:</p>
<pre><code>def stats(df):
kurt = pd.DataFrame(df.kurt(), columns=['kurt']).T
skew = pd.DataFrame(df.skew(), columns=['skew']).T
va... | 1 | 2016-06-16T00:45:39Z | [
"python",
"pandas",
"dataframe",
"time-series",
null
] |
MySQL Connector/Python as Django Engine? | 37,848,035 | <p>Can't find an answer for this even after hours and hours of googling & searching stack overflow. I assure you I've seen all answers that could be deemed relevant and none of those have solved the issue I'm facing. Without further ado - </p>
<p>currently in shell I can do this:</p>
<pre><code>Python 2.7.11+ (de... | 2 | 2016-06-16T00:37:51Z | 37,848,756 | <blockquote>
<p>What would be the difference between using 'mysql.connector.django'
vs. using 'django.db.backends.mysql' ?</p>
</blockquote>
<p>To begin with the former is the recommended method while the latter is not. The former is fully supported but the latter you need version 1.1.x and there is also a caveat ... | 1 | 2016-06-16T02:08:07Z | [
"python",
"mysql",
"django",
"mysql-connector-python"
] |
converting a file of numbers in to a list | 37,848,101 | <p>to put it simply i am trying to read a file that will eventually have nothing but numbers in them either seperated by spaces, commas, or new lines. I have read through alot of these post and fixed somethings. I learned they are imported as strings first. however i am running into an issue where its importing the num... | 0 | 2016-06-16T00:47:04Z | 37,848,159 | <p>To have all the numbers in a single, flattened list, do this:</p>
<pre><code>fo1 = open('mach_uID_3.txt', 'a+')
number_list = list(map(int, fo1.read().split())
fo1.close()
</code></pre>
<p>But it's better to open the file like this:</p>
<pre><code>with open('mach_uID_3.txt', 'a+') as fo1:
number_list = list... | 0 | 2016-06-16T00:54:24Z | [
"python"
] |
converting a file of numbers in to a list | 37,848,101 | <p>to put it simply i am trying to read a file that will eventually have nothing but numbers in them either seperated by spaces, commas, or new lines. I have read through alot of these post and fixed somethings. I learned they are imported as strings first. however i am running into an issue where its importing the num... | 0 | 2016-06-16T00:47:04Z | 37,848,163 | <p>Use <code>extend</code> instead of <code>append</code>:</p>
<pre><code>t2.extend(int(n) for n in x.split())
</code></pre>
| 0 | 2016-06-16T00:55:08Z | [
"python"
] |
Python Module Printing | 37,848,248 | <p>My functions are printing when they are run, but I want to either print from my master file or create a separate print function. I don't know how to pass the return value to my print.</p>
<p>Master.py:</p>
<pre><code>import main
import split
import password
</code></pre>
<p>main.py:</p>
<pre><code>import split
... | 0 | 2016-06-16T01:06:02Z | 37,848,382 | <p>Your functions look ok, but be careful about creating modules that share the same names with common functions and methods. "split" is a method of string. I tested out your code with minor changes and it printed fine (here's what I got):</p>
<blockquote>
<p>login -> BenMon100</p>
</blockquote>
<pre><code>#msplit.... | 0 | 2016-06-16T01:21:01Z | [
"python"
] |
Python BeautifulSoup Returning Top Row Only | 37,848,303 | <p>I have been learning to scrape websites with BeautifulSoup, and it has been going well. Borrowing code, I have managed to scrape certain websites. When I reached the website below, however, I am only returning the top row of the table. I noticed in the html that the website coder has made the header row a td tag i... | 0 | 2016-06-16T01:12:14Z | 37,848,478 | <p>The actual data in the table is being populated using javascript, which is why it is not visible to BeautifulSoup.</p>
<p>Luckily for you, this coder has hard-coded the username and password for the remote service that is returning the data being used to populate the table:</p>
<pre><code><script>
var br... | -1 | 2016-06-16T01:33:51Z | [
"python",
"html",
"beautifulsoup"
] |
How to find X elements from a list in a string and both elements are same | 37,848,325 | <p>I want to find if a string has two elements from a list which are the same, (one element appeared two times).</p>
<p>Here is my code:</p>
<pre><code>List = ['XZ', 'AB', 'CD', ]
string1 = 'helloXZ worldXZ'
string2 = 'hello world'
string3 = 'hello wordCD'
string4 = 'helloXZ worldCD'
if any(s in string for s in Lis... | 0 | 2016-06-16T01:14:51Z | 37,848,417 | <p>Use </p>
<pre><code> if string1.count(str) > 1:
...
if string2.count(str) > 1:
...
</code></pre>
<p>instead of any()</p>
| 0 | 2016-06-16T01:25:42Z | [
"python",
"list",
"python-3.x"
] |
How to find X elements from a list in a string and both elements are same | 37,848,325 | <p>I want to find if a string has two elements from a list which are the same, (one element appeared two times).</p>
<p>Here is my code:</p>
<pre><code>List = ['XZ', 'AB', 'CD', ]
string1 = 'helloXZ worldXZ'
string2 = 'hello world'
string3 = 'hello wordCD'
string4 = 'helloXZ worldCD'
if any(s in string for s in Lis... | 0 | 2016-06-16T01:14:51Z | 37,858,211 | <pre><code> if any(s in string and string.count(run) > 1 for s in list) :
print('true')
else:
print('false')
</code></pre>
<p>That works!</p>
| 0 | 2016-06-16T11:44:20Z | [
"python",
"list",
"python-3.x"
] |
Show accuracy for each class in every given test data using sklearn | 37,848,349 | <p>I have something to ask.</p>
<p>I've trained my sklearn Logistic Regression classifier with 10 thousand training data in Python.
I have 2 thousand test data and I use accuracy score to show the accuracy and confusion matrix.. but both only show overall accuracy of all test data.</p>
<p>what I want is for example:... | 0 | 2016-06-16T01:17:44Z | 37,851,861 | <p>Based on the example provided by you, I think what you are asking is probabilistic prediction for each of your test data points. You can do it easily by using the <code>predict_proba</code> method of the LogisticRegression class (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Logisti... | 0 | 2016-06-16T06:53:52Z | [
"python",
"machine-learning",
"scikit-learn",
"classification",
"text-classification"
] |
Group by a dataframe in Pandas with common values across columns | 37,848,376 | <p>I have a dataframe in Pandas for example:</p>
<pre><code>Col1 Col2 Col3
A B 10/10/2016
B A 09/12/2016
A C 08/11/2016
</code></pre>
<p>I would like for each unique entry in Col1 and Col2 to get their Col3 values. The problem is that a user can either be in Col1 or Col2, so a groupby Col1 will miss... | 1 | 2016-06-16T01:20:26Z | 37,848,475 | <p>You could:</p>
<pre><code>df.set_index(['Col3']).stack().reset_index(-1, drop=True)
</code></pre>
<p>to get:</p>
<pre><code>Col3
10/10/2016 A
10/10/2016 B
09/12/2016 B
09/12/2016 A
08/11/2016 A
08/11/2016 C
</code></pre>
<p>which you could further process, for instance using (assuming the above... | 0 | 2016-06-16T01:32:55Z | [
"python",
"pandas"
] |
How can I filter `filter(lambda x:len(x[1])>=2)` in dataframe? | 37,848,388 | <p>I am not sure about how to <code>filter(lambda x:len(x[1])>=2)</code> in dataframe. I would like to improve the speed of my spark app.
Thanks for your help!</p>
<p>This some context from my spark app:</p>
<pre><code>article_ids = sqlContext.read.format("org.apache.spark.sql.cassandra").options(table="article_b... | 0 | 2016-06-16T01:22:20Z | 37,848,771 | <p>If you're just looking to filter rows in your dataframe that are greater than or equal to two, you can use an index:</p>
<pre><code>speed_df = speed_df[speed_df.column >= 2]
</code></pre>
| 1 | 2016-06-16T02:10:10Z | [
"python",
"apache-spark",
"cassandra",
"datastax",
"datastax-enterprise"
] |
Learning Python; don't know why my function works improperly | 37,848,445 | <p>I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to fi... | 0 | 2016-06-16T01:29:13Z | 37,848,519 | <p>The issue you have is that you're iterating over your list <code>letters</code> and modifying it at the same time. This causes the iteration to skip certain letters in the input without checking them.</p>
<p>For instance, if your <code>text</code> string was <code>'aex'</code>, the <code>letters</code> list would b... | 3 | 2016-06-16T01:39:01Z | [
"python"
] |
Learning Python; don't know why my function works improperly | 37,848,445 | <p>I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to fi... | 0 | 2016-06-16T01:29:13Z | 37,848,550 | <p>You'll always get unexpected results if you modify the thing that you are looping over, inside the loop - and this explains why you are getting strange values from your function.</p>
<p>In your for loop, you are modifying the object that you are supposed to be looping over; create a new object instead.</p>
<p>Here... | 2 | 2016-06-16T01:42:49Z | [
"python"
] |
Learning Python; don't know why my function works improperly | 37,848,445 | <p>I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to fi... | 0 | 2016-06-16T01:29:13Z | 37,848,551 | <p>I think @Blckknght hit the nail on the head. If I were presented with this problem, I'd try something like this:</p>
<pre><code>def anti_vowel(text):
no_vowels = ''
vowels = 'aeiouAEIOU'
for a in text:
if a not in vowels:
no_vowels += a
return no_vowels
</code></pre>
| 1 | 2016-06-16T01:43:02Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.