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 |
|---|---|---|---|---|---|---|---|---|---|
can't specify pip dependency in conda meta.yaml file | 37,541,084 | <p>I have the following meta.yaml file in order to build a conda package:</p>
<pre><code>package:
name: dsutils
version: 1.0
source:
git_rev: cat_files_bq_utils
git_url: https://**********.git
requirements:
build:
- python
- setuptools
run:
- python
- pandas
- scipy
- numpy
-... | 0 | 2016-05-31T08:52:42Z | 38,065,334 | <p>If <code>conda search</code> doesn't show any results, the easiest thing to do is go to anaconda.org and see if some other channel might have built the package for you already.</p>
<p><a href="https://anaconda.org/search?q=google-api-python-client&sort=ndownloads&sort_order=1&reverse=true" rel="nofollow... | 2 | 2016-06-28T00:41:37Z | [
"python",
"dependencies",
"package",
"anaconda",
"conda"
] |
Python script counting lines in multiple text files in one directory and producing simple report | 37,541,206 | <p>I need a python script counting lines in all text files in one directory and producing a general report on number of files with <em>n</em> number of lines.</p>
<p>The report should look like this:</p>
<pre><code>Files with 1 line: 636
Files with 2 lines: 346
Files with 3 lines: 234
Files with 4 lines: 723
Files wi... | -4 | 2016-05-31T08:59:04Z | 37,541,462 | <p>Your <code>names</code> dict looks like that:</p>
<pre><code>{
'file1.txt': 30,
'file2.txt': 26,
'file3.txt': 19,
'file4.txt': 19
}
</code></pre>
<p>So you'd just have to start from that and follow with:</p>
<pre><code>from collections import defaultdict
lines = defaultdict(int)
for val in names.... | 0 | 2016-05-31T09:10:51Z | [
"python",
"lines",
"counting"
] |
Python Cryptography Library fails to load_pem_public_key with my PEM Format | 37,541,248 | <p>We are currently working on a project where we have to take the public key of a user from the database and encrypt a string for said user. </p>
<p>Unfortunately, we are getting an error with our cryptography library (cryptography==1.2.1).</p>
<p>The Public Key:</p>
<pre><code>-----BEGIN PUBLIC KEY-----MIICIjANBgk... | 0 | 2016-05-31T09:01:03Z | 37,541,536 | <p>Ok, So after further googling I found the answer here:
<a href="http://crypto.stackexchange.com/questions/19043/can-i-remove-new-lines-in-a-public-key">http://crypto.stackexchange.com/questions/19043/can-i-remove-new-lines-in-a-public-key</a></p>
<p>Which resulted in:</p>
<pre><code>pem_public_key = pem_public_key... | 1 | 2016-05-31T09:13:58Z | [
"python",
"cryptography"
] |
Unique ID in html for generating Buttons | 37,541,311 | <p>sorry if the title is misleading.</p>
<p>I'm having the following problem. I am creating multiple rows in HTML using Genshi. For each row I have a button at the end of the row for delete purposes. </p>
<p>The code looks like this:</p>
<pre><code><form action="/deleteAusleihe" method="post">
<table&... | 0 | 2016-05-31T09:03:57Z | 37,541,464 | <p>The issue is that all the hidden inputs inside the <code><form></code> element get submitted at once.</p>
<p>There are various ways you could solve this. Probably the easiest would be to move the form tag inside the loop, so that there are multiple forms and each one only wraps a single input and button.</p>
| 2 | 2016-05-31T09:10:59Z | [
"python",
"html",
"python-2.7",
"turbogears2",
"genshi"
] |
Unique ID in html for generating Buttons | 37,541,311 | <p>sorry if the title is misleading.</p>
<p>I'm having the following problem. I am creating multiple rows in HTML using Genshi. For each row I have a button at the end of the row for delete purposes. </p>
<p>The code looks like this:</p>
<pre><code><form action="/deleteAusleihe" method="post">
<table&... | 0 | 2016-05-31T09:03:57Z | 37,541,729 | <pre><code><table>
<tr>
<th>ID</th>
<th>Person</th>
<th>Buch</th>
<th></th>
</tr>
<tr py:for="v in verleihen">
<form action="/deleteAusleihe" method="post">
<input type = "hidden" value="v.id" name="toDelete"/>
... | 1 | 2016-05-31T09:22:27Z | [
"python",
"html",
"python-2.7",
"turbogears2",
"genshi"
] |
Lua function returning tuple of values | 37,541,444 | <p>I have seen the following python code:</p>
<pre><code>W_grads, _ = backward_gradient(X, S, grad_out, wRec)
</code></pre>
<p>And in the function backward_gradient, I have the following return statement:</p>
<pre><code>return (wx_grad, wRec_grad), grad_over_time
</code></pre>
<p>How can I return a tuple similar to... | 1 | 2016-05-31T09:10:01Z | 37,543,014 | <p>Return a table:</p>
<pre><code>return {wx_grad, wRec_grad}, grad_over_time
</code></pre>
<p>Then access <code>W_grads[1]</code> and <code>W_grads[2]</code>.</p>
| 1 | 2016-05-31T10:21:00Z | [
"python",
"lua",
"torch"
] |
Lua function returning tuple of values | 37,541,444 | <p>I have seen the following python code:</p>
<pre><code>W_grads, _ = backward_gradient(X, S, grad_out, wRec)
</code></pre>
<p>And in the function backward_gradient, I have the following return statement:</p>
<pre><code>return (wx_grad, wRec_grad), grad_over_time
</code></pre>
<p>How can I return a tuple similar to... | 1 | 2016-05-31T09:10:01Z | 37,543,024 | <p>You can use a table for that.</p>
<pre><code>return {wx_grad, wRec_grad}, grad_over_time
</code></pre>
<p>Refer to for more information <a href="http://www.lua.org/manual/5.3/manual.html#2.1" rel="nofollow">http://www.lua.org/manual/5.3/manual.html#2.1</a></p>
<blockquote>
<p>Tables are the sole data-structurin... | 4 | 2016-05-31T10:21:34Z | [
"python",
"lua",
"torch"
] |
Converting an "If Else" statement to a JSON file | 37,541,565 | <p>I am having this as an <code>input</code>, let's call it <code>tree</code></p>
<pre><code>if ( device_type_id <= 1 )
39 Clicks - 0.61%
2135 Conversions - 33.32%
else ( device_type_id > 1 )
if ( country_id <= 216 )
1097 Clicks - 17.12%
else ( country_id > 216 )
if ( brows... | 0 | 2016-05-31T09:15:11Z | 37,559,497 | <p>Here is the modification I suggested:</p>
<pre><code>def parser(lines):
block = []
while lines :
if lines[0].startswith('if'):
bl = ' '.join(lines.pop(0).split()[1:]).replace('(', '').replace(')', '')
block.append({'name':bl, 'children':parser(lines)})
elif lines[0]... | 1 | 2016-06-01T04:33:45Z | [
"python",
"json",
"parsing"
] |
Python select with _mysql module without an error | 37,541,591 | <p>I need to use _mysql, but i don't know how to get all the output of my selection without an error.</p>
<pre><code>db = sql.connect(host=host,user=user,passwd=pw,db=dbName)
db.query(query)
rows = db.use_result()
while rows:
result = rows.fetch_row()[0]
print result
</code></pre>
<p>with this code i get all ... | 0 | 2016-05-31T09:16:14Z | 37,541,924 | <p>Try to remove <code>[0]</code> from <code>result = rows.fetch_row()[0]</code> like <code>result = rows.fetch_row()</code>.</p>
<p><strong>Edited:</strong></p>
<pre><code>db = sql.connect(host=host,user=user,passwd=pw,db=dbName)
cursor = db.cursor()
cursor.execute(query)
results = cursor.fetchall()
for result in re... | 0 | 2016-05-31T09:30:54Z | [
"python",
"mysql",
"mysql-python"
] |
Python select with _mysql module without an error | 37,541,591 | <p>I need to use _mysql, but i don't know how to get all the output of my selection without an error.</p>
<pre><code>db = sql.connect(host=host,user=user,passwd=pw,db=dbName)
db.query(query)
rows = db.use_result()
while rows:
result = rows.fetch_row()[0]
print result
</code></pre>
<p>with this code i get all ... | 0 | 2016-05-31T09:16:14Z | 37,544,011 | <p>A nicer way to do it is:</p>
<pre><code>while i < rows.num_rows():
i+=1
result = rows.fetch_row()[0]
</code></pre>
| 0 | 2016-05-31T11:06:59Z | [
"python",
"mysql",
"mysql-python"
] |
How to separate html pages and Python code in Web2py | 37,541,665 | <p>I am working on a new Web project (with Web2py) and I need to define organisation where page design and code will be separate and made by different peoples. Web designers will use tools like Pinegrow then give files to coders. I need to define rules where Web designers may update there work without coders' intervent... | -1 | 2016-05-31T09:19:18Z | 37,551,109 | <p>In web2py templates, all Python code goes in between the <code>{{...}}</code> template delimiters, so a simple rule would be "don't touch anything inside those delimiters." However, you will still run into two types of problems:</p>
<ol>
<li><p>Designers won't be able to see an accurate representation of their work... | 1 | 2016-05-31T16:31:17Z | [
"python",
"web",
"web2py"
] |
Python for - reference to last element | 37,541,709 | <p>Let's say I have this code:</p>
<pre><code>fields = ['a', 'b', 'c']
for field in fields:
d.pop(field)
d.append(field - 1) # Incorrect
</code></pre>
<p>In the incorrect line, if we are in the second iteration ('b'), how to reference to the last one ('a')?</p>
| -1 | 2016-05-31T09:21:42Z | 37,541,767 | <p>You can't, if you want to iterate over a list in this fashion, your can use:</p>
<pre><code>for i in range(len(fields)):
d.pop(fields[i])
d.append(fields[i-1])
</code></pre>
<p>And obviously, you have to think about what behaviour you want for the first loop.</p>
| 2 | 2016-05-31T09:23:56Z | [
"python"
] |
Python for - reference to last element | 37,541,709 | <p>Let's say I have this code:</p>
<pre><code>fields = ['a', 'b', 'c']
for field in fields:
d.pop(field)
d.append(field - 1) # Incorrect
</code></pre>
<p>In the incorrect line, if we are in the second iteration ('b'), how to reference to the last one ('a')?</p>
| -1 | 2016-05-31T09:21:42Z | 37,541,792 | <p>Use <code>enumerate</code></p>
<pre><code>for i,field in enumerate(fields):
d.pop(field)
if i > 0:
d.append(fields[i-1])
</code></pre>
| 5 | 2016-05-31T09:25:08Z | [
"python"
] |
Write Unicode character with integer value to text file in Python 2 | 37,541,793 | <ol>
<li>In Python 2, I want to write a Unicode character which integer value is <code>k</code> to text file. </li>
</ol>
<p>How should I do that?</p>
<p>(For instance, with ASCII, if I want to write the character with value 65, in text file it should appeared as 'A').</p>
<ol start="2">
<li><p>Afterwards, how shoul... | 0 | 2016-05-31T09:25:12Z | 37,558,683 | <ol>
<li>You can't write Unicode code points to text files. They must be encoded. UTF-8, UTF-16 and UTF-32 are encodings that support the full range of Unicode code points. <code>unichr()</code> is the function to turn an integer into a Unicode codepoint. Note that Python 2 will default to an encoding that depends ... | 1 | 2016-06-01T02:59:22Z | [
"python",
"unicode"
] |
How to change element in list from information in another list | 37,541,915 | <p>I want to create lists (named 'card') of two elements : 'NUMBER' and a number from the list 'numbers'. There will be as many cards as there are numbers in the list 'numbers'.
Why do I get cards with the same number using that code ?</p>
<pre><code>card=['NUMBER','']
numbers = [1,3,5]
All_cards=[]
for i in range(len... | 0 | 2016-05-31T09:30:33Z | 37,542,023 | <p>Something like this?</p>
<pre><code>numbers = [1, 3, 5]
all_cards = []
for number in numbers:
all_cards.append(['NUMBER', number])
print(all_cards)
</code></pre>
<p>You start with <code>card = ['NUMBER', '']</code>, and every iteration you assign the current number to the second position of the same <code>ca... | 1 | 2016-05-31T09:34:35Z | [
"python",
"list",
"range"
] |
How to change element in list from information in another list | 37,541,915 | <p>I want to create lists (named 'card') of two elements : 'NUMBER' and a number from the list 'numbers'. There will be as many cards as there are numbers in the list 'numbers'.
Why do I get cards with the same number using that code ?</p>
<pre><code>card=['NUMBER','']
numbers = [1,3,5]
All_cards=[]
for i in range(len... | 0 | 2016-05-31T09:30:33Z | 37,542,135 | <p>You can do this with a simple list comprehension:</p>
<pre><code>numbers = [1,3,5]
all_cards = [['NUMBER', i] for i in numbers]
</code></pre>
| 1 | 2016-05-31T09:39:07Z | [
"python",
"list",
"range"
] |
How to change element in list from information in another list | 37,541,915 | <p>I want to create lists (named 'card') of two elements : 'NUMBER' and a number from the list 'numbers'. There will be as many cards as there are numbers in the list 'numbers'.
Why do I get cards with the same number using that code ?</p>
<pre><code>card=['NUMBER','']
numbers = [1,3,5]
All_cards=[]
for i in range(len... | 0 | 2016-05-31T09:30:33Z | 37,542,301 | <p>If you add a print statement as last line of for loop, you would have got an idea what is happening.</p>
<p>It is as following:</p>
<pre><code>[['NUMBER', 1]]
[['NUMBER', 3], ['NUMBER', 3]]
[['NUMBER', 5], ['NUMBER', 5], ['NUMBER', 5]]
[['NUMBER', 5], ['NUMBER', 5], ['NUMBER', 5]]
</code></pre>
<p>which is basica... | 1 | 2016-05-31T09:46:54Z | [
"python",
"list",
"range"
] |
How to change element in list from information in another list | 37,541,915 | <p>I want to create lists (named 'card') of two elements : 'NUMBER' and a number from the list 'numbers'. There will be as many cards as there are numbers in the list 'numbers'.
Why do I get cards with the same number using that code ?</p>
<pre><code>card=['NUMBER','']
numbers = [1,3,5]
All_cards=[]
for i in range(len... | 0 | 2016-05-31T09:30:33Z | 37,542,512 | <p>You have already excellent answers that solve your immediate problem (I suggest that you try to understand the mechanism of <em>list comprehension</em>, introduced in Mr Roseman answer, because it's extra handy in too many situations) but maybe you would like to understand why you had that strange result.</p>
<p>Yo... | 0 | 2016-05-31T09:57:11Z | [
"python",
"list",
"range"
] |
clearing the console and viewing dataframes in rodeo | 37,541,937 | <p>I am using rodeo with jupyter however the keyboard shortcuts for switching to and clearing terminal are not working, and either is the ability to view and sort pandas dataframes by clicking on them in the top right panel.</p>
<p><a href="http://rodeo.yhat.com/docs/" rel="nofollow">http://rodeo.yhat.com/docs/</a></p... | 1 | 2016-05-31T09:31:18Z | 37,713,439 | <p>What version of Rodeo are you using? (You <em>should</em> be able to tell by clicking Rodeo > About Rodeo).</p>
<p>The Rodeo team has been working on a major re-write from version 1.3, the current downloadable version on yhat's website. I recommend upgrading to their latest release, <a href="https://github.com/yh... | 0 | 2016-06-08T21:42:20Z | [
"python",
"pandas",
"rodeo"
] |
Write a snippet that removes the initial variable at the end, leaving only the modified ones | 37,542,017 | <p>Let's say I have an UltiSnips snippet that shall replace all special characters with an underscore.</p>
<p>I have this:</p>
<pre><code>snippet us "replace specials with underscores" w
${1:${VISUAL}}
`!p
import re
snip.rv = re.sub("[^0-9a-zA-Z]", "_", t[1])
`
endsnippet
</code></pre>
<p>Now something like <code>He... | 1 | 2016-05-31T09:34:23Z | 37,548,418 | <p>You dont need to write any python code. Your snippet is as simple as the following:</p>
<pre><code>snippet us "replace specials with underscores" w
${1:${VISUAL/[^0-9a-zA-Z]/_/g}}
endsnippet
</code></pre>
<p>In a more general manner we are able to retrieve the text that was selected in visual mode through <code>sn... | 2 | 2016-05-31T14:25:29Z | [
"python",
"vim",
"ultisnips"
] |
python stacktrace at firefoxdriver.prototype.findelement internal | 37,542,230 | <p>I'm using <code>selenium</code> with <code>firefox</code> to load a webpage. The page uses <code>ajax</code> to load new content on clicking the <strong>Display More Results</strong> button.</p>
<p>However when I try to find this button and simulate a click, it gives the following <code>Stacktrace</code> error. Can... | 0 | 2016-05-31T09:43:36Z | 37,544,686 | <p>I'm not sure what the problem is because there is no error message. However, this syntax looks rather strange:</p>
<pre><code>elem = elem = WebDriverWait(...
</code></pre>
<p>Also, I noticed that when I went to that page the div with the id "scroll2" was not visible. The visible one was "scroll4". You'll probabl... | 0 | 2016-05-31T11:37:30Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver",
"selenium-firefoxdriver"
] |
Django - get foreign key field name in django template for if statement | 37,542,265 | <p>in my template i have an if statement to check the type of file, however the file_type field is a foreign key object. how can i get the file_type.type field to use in the if statement?</p>
<p>template:</p>
<pre><code>{% for file in Site.sitefiles_set.all %}
{% if file.file_type != 'Site Plan' %}
</code></pre>
... | -2 | 2016-05-31T09:45:21Z | 37,542,357 | <p>You just need to append <code>type</code> to the variable you have already (which is a <code>SiteFileType</code> object):</p>
<pre><code>{% for file in Site.sitefiles_set.all %}
{% if file.file_type.type != 'Site Plan' %}
...
{% endif %}
{% endfor %}
</code></pre>
| 2 | 2016-05-31T09:49:10Z | [
"python",
"django"
] |
Django - get foreign key field name in django template for if statement | 37,542,265 | <p>in my template i have an if statement to check the type of file, however the file_type field is a foreign key object. how can i get the file_type.type field to use in the if statement?</p>
<p>template:</p>
<pre><code>{% for file in Site.sitefiles_set.all %}
{% if file.file_type != 'Site Plan' %}
</code></pre>
... | -2 | 2016-05-31T09:45:21Z | 37,542,364 | <p>Just follow the dots one more level.</p>
<pre><code> {% if file.file_type.type != 'Site Plan' %}
</code></pre>
| 2 | 2016-05-31T09:49:47Z | [
"python",
"django"
] |
Numpy resize and fill with specific value | 37,542,436 | <p>How can i resize a numpy array and fill it with a specific value (if some dimension is extended) ?</p>
<p>I find a way to extend my array with <strong>np.pad</strong> but I can't shorten it:</p>
<pre class="lang-py prettyprint-override"><code>>>> import numpy as np
>>> a = np.ndarray((5, 5), dtyp... | -1 | 2016-05-31T09:53:31Z | 37,542,917 | <p>To shorten it, you can use negative values in slice :</p>
<pre><code>>>> import numpy as np
>>> a = np.ndarray((5, 5), dtype=np.uint16)
>>> a
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint16)
>>>... | 0 | 2016-05-31T10:16:26Z | [
"python",
"numpy",
"resize"
] |
Numpy resize and fill with specific value | 37,542,436 | <p>How can i resize a numpy array and fill it with a specific value (if some dimension is extended) ?</p>
<p>I find a way to extend my array with <strong>np.pad</strong> but I can't shorten it:</p>
<pre class="lang-py prettyprint-override"><code>>>> import numpy as np
>>> a = np.ndarray((5, 5), dtyp... | -1 | 2016-05-31T09:53:31Z | 37,552,754 | <p>Your array has a fixed size data buffer. You can reshape the array without changing that buffer. You can take a slice (<code>view</code>) without changing the buffer. But you can't add values to the array without changing the buffer.</p>
<p>In general <code>resize</code> returns an new array with a new data buff... | 1 | 2016-05-31T18:07:22Z | [
"python",
"numpy",
"resize"
] |
Dig into variables while debugging | 37,542,522 | <p>I am currently debugging code using Python. I have not been using Python for a while. I put some breakpoints on a variable which is an integer. Let's say this variable is <code>X = 10</code>. How can I:</p>
<ul>
<li>see what is in the variable? (I can highlight and a yellow case appears but if there are a lot of in... | 7 | 2016-05-31T09:57:51Z | 37,680,965 | <p>I'm sure everyone has their own opinion, but I find the python tools for Eclipse quite complex. If you aren't tied to an Eclipse IDE, try <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">PyCharm</a>. It has very good tools for doing exactly what you want, and many tutorial videos. This video shows you how... | 1 | 2016-06-07T13:35:38Z | [
"python",
"eclipse",
"debugging"
] |
Dig into variables while debugging | 37,542,522 | <p>I am currently debugging code using Python. I have not been using Python for a while. I put some breakpoints on a variable which is an integer. Let's say this variable is <code>X = 10</code>. How can I:</p>
<ul>
<li>see what is in the variable? (I can highlight and a yellow case appears but if there are a lot of in... | 7 | 2016-05-31T09:57:51Z | 37,688,904 | <p><em>As noted in the comments, there are many <a href="https://wiki.python.org/moin/IntegratedDevelopmentEnvironments" rel="nofollow">possible IDEs you can use</a> with Python. The original question was specifically about Eclipse and so my answer focuses on a solution using that IDE. Other solutions are possible if... | 2 | 2016-06-07T20:38:18Z | [
"python",
"eclipse",
"debugging"
] |
Dig into variables while debugging | 37,542,522 | <p>I am currently debugging code using Python. I have not been using Python for a while. I put some breakpoints on a variable which is an integer. Let's say this variable is <code>X = 10</code>. How can I:</p>
<ul>
<li>see what is in the variable? (I can highlight and a yellow case appears but if there are a lot of in... | 7 | 2016-05-31T09:57:51Z | 37,689,257 | <p>I don't think you can do this purely in Eclipse, not without extensive plugins. However, there are some very good python debugging tools out there. </p>
<p>If you're willing to get your hands dirty, the builtin python debugger <a href="https://docs.python.org/2/library/pdb.html" rel="nofollow">pdb</a> does everythi... | 1 | 2016-06-07T20:59:05Z | [
"python",
"eclipse",
"debugging"
] |
Dig into variables while debugging | 37,542,522 | <p>I am currently debugging code using Python. I have not been using Python for a while. I put some breakpoints on a variable which is an integer. Let's say this variable is <code>X = 10</code>. How can I:</p>
<ul>
<li>see what is in the variable? (I can highlight and a yellow case appears but if there are a lot of in... | 7 | 2016-05-31T09:57:51Z | 37,792,335 | <p>Try opensource, free <a href="https://code.visualstudio.com/" rel="nofollow">VS Code</a> (with Python plugin). It has a slick intellisense feature and you can watch, inspect the variables, debug them. The editor is node.js based and can work in every platform. Eclipse is overkill for python development IMHO.</p>
| 0 | 2016-06-13T14:27:24Z | [
"python",
"eclipse",
"debugging"
] |
Dig into variables while debugging | 37,542,522 | <p>I am currently debugging code using Python. I have not been using Python for a while. I put some breakpoints on a variable which is an integer. Let's say this variable is <code>X = 10</code>. How can I:</p>
<ul>
<li>see what is in the variable? (I can highlight and a yellow case appears but if there are a lot of in... | 7 | 2016-05-31T09:57:51Z | 37,801,482 | <p><a href="https://github.com/gotcha/ipdb" rel="nofollow"><code>ipdb</code></a> is a handy tool for python debugging:</p>
<blockquote>
<p>ipdb exports functions to access the IPython debugger, which features tab completion, syntax highlighting, better tracebacks, better introspection with the same interface as the ... | 0 | 2016-06-14T01:14:38Z | [
"python",
"eclipse",
"debugging"
] |
DRF POST object with FK | 37,542,700 | <p>First, my <strong>models</strong> : </p>
<pre><code>class Director(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Movie(models.Model):
title = models.CharField(max_length=150, unique=True)
director = models.ForeignKey(Director, relate... | 1 | 2016-05-31T10:06:02Z | 37,562,722 | <p>You are not able to add a new movie here because you have excluded the <code>director</code> field in your MovieSerializer. But the director field is required by the Movie model. Removing the exclude should work</p>
| 2 | 2016-06-01T07:57:28Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
Django: Using simple-history module I get auth_historicaluser doesn't exist error | 37,542,714 | <p>I'm using django 1.8 in windows 7 and I use <code>django-simple-history</code> module and it works properly.</p>
<p>Looking my tables in mysql on windows I have both <code>auth_historicaluser</code> and <code>auth_historicalgroup</code>.</p>
<p>Today I moved my project to ubuntu 14.04 LTS and I install all the <co... | 0 | 2016-05-31T10:06:43Z | 37,543,993 | <p>I have to run this actions as <code>sudo</code>:</p>
<pre><code>sudo python manage.py makemigrations app
sudo python manage.py syncdb
sudo python manage.py migrate auth
sudo python manage.py migrate
sudo python manage.py runserver
</code></pre>
| 0 | 2016-05-31T11:05:58Z | [
"python",
"django",
"ubuntu",
"django-admin"
] |
Save and load lists of strings in Python using JSON | 37,542,738 | <p>I am trying to save lists (one per line) in a file like </p>
<pre><code> w = meaningful_words
json.dump(w, outfile)
outfile.write("\n");
</code></pre>
<p>where w is a list of strings. Then I'm trying to load the lists, one at a time like</p>
<pre><code>with open('text.txt', 'r')... | 0 | 2016-05-31T10:08:07Z | 37,542,834 | <p>You should change <code>line.read()</code> to just <code>line</code>:</p>
<pre><code>with open('text.txt', 'r') as infile:
for line in infile:
data = json.loads(line)
</code></pre>
<p><a href="https://docs.python.org/2/library/stdtypes.html#bltin-file-objects" rel="nofollow">File objects</a> are iterat... | 1 | 2016-05-31T10:12:37Z | [
"python",
"json",
"list"
] |
Python: Finding the position of the first occurring difference between 2 strings. (Unequal lengths) | 37,542,743 | <p>I have been trying to solve this past final exam question.
I think I am getting close, but due to the unequal lengths of the two strings, I am getting an index out of range error which i can't figure out...</p>
<p>How would you try solve this question?
How can I solve the IndexError?</p>
<p>Thank you in advance :... | 0 | 2016-05-31T10:08:29Z | 37,542,877 | <p>Encapsulate your test in a <code>try/catch</code> in case of <code>IndexError</code>, which means that the second string is shorter than the first one, which means the two strings differ.</p>
<pre><code>for letter in range(len(string1)):
try:
if string1[letter] != string2[letter]:
print("Str... | 2 | 2016-05-31T10:14:22Z | [
"python",
"python-3.x"
] |
Python: Finding the position of the first occurring difference between 2 strings. (Unequal lengths) | 37,542,743 | <p>I have been trying to solve this past final exam question.
I think I am getting close, but due to the unequal lengths of the two strings, I am getting an index out of range error which i can't figure out...</p>
<p>How would you try solve this question?
How can I solve the IndexError?</p>
<p>Thank you in advance :... | 0 | 2016-05-31T10:08:29Z | 37,543,443 | <p>My solution would be:</p>
<pre><code>def print_first_difference(string1, string2):
aggr_strings = zip(string1, string2)
for index, tup in enumerate(aggr_strings):
if tup[0] != tup[1]:
print("Strings differ at position " + str(index))
break
else:
if len(aggr_string... | 0 | 2016-05-31T10:41:52Z | [
"python",
"python-3.x"
] |
Ansible python API 2.0: run a playbook in a python script for windows clients | 37,542,793 | <p>I am trying to re-write this script (<a href="http://stackoverflow.com/questions/35368044/how-to-use-ansible-2-0-python-api-to-run-a-playbook">How to use Ansible 2.0 Python API to run a Playbook?</a>) to call an ansible playbook within a python script that runs against windows clients. I have a test folder that cont... | 1 | 2016-05-31T10:10:42Z | 38,067,407 | <p>I have had same issue while using Ansible python APIs. After a long research and some dig into ansible code, i found the possible cause.
As per <a href="http://docs.ansible.com/ansible/become.html" rel="nofollow">Ansible Documentation</a> you should, set become_method when supplying become and become_user, you shoul... | 0 | 2016-06-28T05:01:53Z | [
"python",
"ansible"
] |
Django unit testing - assertRaises working when it shouldn't | 37,543,033 | <p>I was code reviewing an API and I found this in a unit test. The test passes but I can't understand why.</p>
<pre><code>class SomeTestCase(TestCase):
def setUp(self):
self.client = Client()
@mock.patch("patch.a.thing", mock_function)
def test_fail(self):
request_data = {
"s... | 0 | 2016-05-31T10:21:56Z | 37,543,369 | <p>You should pass a callable to <code>assertRaises</code>:</p>
<pre><code>self.assertRaises(Exception, self.client.post,
"/path/to/api",
json.dumps(request_data),
content_type="application/json",
HTTP_HEADERNAME=HEADER_VALUE
)
</code></pre>
<p>It might be clearer to use it as a contex... | 1 | 2016-05-31T10:38:10Z | [
"python",
"django",
"python-2.7",
"unit-testing"
] |
Pre-allocation of memory in sqlite | 37,543,060 | <p>I have a big file that I want to "pour" into table in sqlite.</p>
<p>I dont want that the program will need to allocate place at runtime.</p>
<p>How can I predefine the database's initial size?
(I use python)</p>
| 0 | 2016-05-31T10:22:55Z | 37,543,434 | <p>You can try to set a <code>SQLITE_FCNTL_SIZE_HINT</code> parameter:</p>
<blockquote>
<p>The SQLITE_FCNTL_SIZE_HINT opcode is used by SQLite to give the VFS layer a hint of how large the database file will grow to be during the current transaction. This hint is not guaranteed to be accurate but it is often close. ... | 0 | 2016-05-31T10:41:11Z | [
"python",
"database",
"memory",
"sqlite3",
"allocation"
] |
What do we mean by this Numpy shape? | 37,543,093 | <p>I came across this Python statement, but couldn't understand what it means, especially the part between parentheses:</p>
<pre><code>np.zeros(1+x.shape[1])
</code></pre>
<p>I tried to mimic its behavior by a simple example, but got a <code>tuple index out of range</code> error. </p>
<p>Can you clarify what the par... | 1 | 2016-05-31T10:24:00Z | 37,543,130 | <p>It means: Create a 1D numpy array with zeros whose length is equal to one more than the number of columns in the numpy array <code>x</code>. </p>
<pre><code>>>> a = np.array([[1,2,1],[3,4,5]])
>>> print a.shape
(2L, 3L)
>>> b = np.zeros(1+a.shape[1])
>>> print b
[ 0. 0. 0. 0.... | 2 | 2016-05-31T10:26:10Z | [
"python",
"numpy"
] |
What do we mean by this Numpy shape? | 37,543,093 | <p>I came across this Python statement, but couldn't understand what it means, especially the part between parentheses:</p>
<pre><code>np.zeros(1+x.shape[1])
</code></pre>
<p>I tried to mimic its behavior by a simple example, but got a <code>tuple index out of range</code> error. </p>
<p>Can you clarify what the par... | 1 | 2016-05-31T10:24:00Z | 37,543,208 | <p>Here's a toy code that can help you understand better</p>
<pre><code>>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> x.shape
(2, 3)
>>> x.shape[1]
3
>>> np.zeros(1+x.shape[1])
array([ 0., 0., 0., 0.])
</code></pre>
<p><code>x.shape</code> returns the shape of the array as a tupl... | 2 | 2016-05-31T10:30:19Z | [
"python",
"numpy"
] |
Django Rest Framework: 'estado' is an invalid keyword argument for this function | 37,543,137 | <p>I'm using DRF and i get this TypeError with a nested serialization. I have read the <a href="http://www.django-rest-framework.org/topics/3.0-announcement/#serializers" rel="nofollow">Documentation</a> but I still can't resolve my problem.</p>
<p><strong>Models:</strong></p>
<pre><code>class Estado(models.Model):
... | 1 | 2016-05-31T10:26:35Z | 37,544,448 | <p>Did not test this, but you probably need to set a related_name for estado.</p>
<pre><code>estado = models.ForeignKey(Estado, related_name='estado')
</code></pre>
| 2 | 2016-05-31T11:27:06Z | [
"python",
"django",
"django-rest-framework"
] |
Vector input gives output vector `[0,...,0]` in Python | 37,543,212 | <p>I'm trying to create a vector class in Python. I'm not so far yet, and stuck already. </p>
<p>This is my current code:</p>
<pre><code> class vector:
def __init__(self, n, l = []):
self.v = []
if(isinstance(n, int)):
x = int(n)
if (x < 0):
... | 0 | 2016-05-31T10:30:34Z | 37,543,427 | <p>You have <code>[0.0] * x</code>, but I think you mean <code>[l] * x</code>.</p>
<p>It really helps to clear up what kind of cases your code must support and write it down. It also helps to define a clear list of input and output combinations, you can use them as a test:</p>
<pre><code>class Vector(object):
def... | 2 | 2016-05-31T10:40:49Z | [
"python",
"vector"
] |
Differentiating a tuple from a tuple of tuples | 37,543,246 | <p>I have a tuple, and a tuple of tuples.</p>
<pre><code>import numpy as np
a = ("Control", "Group1")
b = (("Control", "Group1"), ("Control", "Group1", "Group2))
</code></pre>
<p>How can I tell that <code>a</code> is fundamentally different from <code>b</code>? Both</p>
<pre><code>print(len(a))
print(np.shape(a))
pr... | 1 | 2016-05-31T10:32:17Z | 37,543,269 | <p>Use the equality operator, <code>==</code>:</p>
<pre><code>>>> a = ("Control", "Group1")
>>> b = (("Control", "Group1"), ("Control", "Group1", "Group2"))
>>> a == b
False
</code></pre>
<p>If you just want a vague idea of the general structure, and the string elements won't contain parent... | 0 | 2016-05-31T10:33:29Z | [
"python",
"python-2.7",
"python-3.x"
] |
Differentiating a tuple from a tuple of tuples | 37,543,246 | <p>I have a tuple, and a tuple of tuples.</p>
<pre><code>import numpy as np
a = ("Control", "Group1")
b = (("Control", "Group1"), ("Control", "Group1", "Group2))
</code></pre>
<p>How can I tell that <code>a</code> is fundamentally different from <code>b</code>? Both</p>
<pre><code>print(len(a))
print(np.shape(a))
pr... | 1 | 2016-05-31T10:32:17Z | 37,543,298 | <p>You cannot, because they are not fundamentally different.</p>
<p>What should happen for the following?</p>
<pre><code>c = (("Foo", "bar"), "baz")
</code></pre>
<p>Itâs also a tuple, and it contains both "bare" values as well as another tuple.</p>
<p>If you need to detect tuples which only consist of tuples, us... | 4 | 2016-05-31T10:34:43Z | [
"python",
"python-2.7",
"python-3.x"
] |
Dictionary values starting with zero | 37,543,291 | <p>I want to build a dictionary for my contact's names and their phone number:</p>
<pre><code>contacts = {'name': 0500456}
</code></pre>
<p>but it shows error:</p>
<blockquote>
<p>contacts = {'name': 0500456} SyntaxError: invalid token</p>
</blockquote>
<p>Python3 think I want to write octal number, so the sugges... | 0 | 2016-05-31T10:34:28Z | 37,545,848 | <p>You need to choose between storing an integer object and storing a string object.</p>
<p>Choose an <strong>integer object</strong> (<code>500456</code>) if you need to perform calculations using the value of the integer. This will not store any leading zero information, but if you just need a fixed number of zeroes... | 3 | 2016-05-31T12:30:32Z | [
"python",
"python-3.x"
] |
Data represented in objects | 37,543,318 | <p><strong>Object-Oriented design</strong></p>
<p>I have a database storage with many different entries but each entry has potentially a different "object_type" (where the different attributes are stored in the database). For each "object_type" I have an own python class - see the simplified code example below. Typica... | 1 | 2016-05-31T10:35:44Z | 37,543,744 | <p>I may have misunderstood, but I think that your design is fundamentally broken if your super-class actually needs to 'know' which classes have been created as sub-classes - that is not how inheritance is meant to work.</p>
<p>Why do you think that your DataObject needs to import anything about your sub-classes ?</p... | 2 | 2016-05-31T10:55:18Z | [
"python",
"oop",
"inheritance"
] |
Data represented in objects | 37,543,318 | <p><strong>Object-Oriented design</strong></p>
<p>I have a database storage with many different entries but each entry has potentially a different "object_type" (where the different attributes are stored in the database). For each "object_type" I have an own python class - see the simplified code example below. Typica... | 1 | 2016-05-31T10:35:44Z | 37,545,209 | <p>I would definitely have another object such as <code>DataObjectStore</code> that would handle the responsibility of abstracting away the database and this <code>DataObjectStore</code> could use a <code>DataObjectFactory</code> to reconstitute an object from a DB resultset or any other representation. </p>
<p>The fa... | 0 | 2016-05-31T12:01:40Z | [
"python",
"oop",
"inheritance"
] |
Data represented in objects | 37,543,318 | <p><strong>Object-Oriented design</strong></p>
<p>I have a database storage with many different entries but each entry has potentially a different "object_type" (where the different attributes are stored in the database). For each "object_type" I have an own python class - see the simplified code example below. Typica... | 1 | 2016-05-31T10:35:44Z | 37,545,412 | <p><strong>How to let to superclass know about its subclasses</strong></p>
<p>In the general case, don't. Let a third-part handle this with</p>
<pre><code>SuperClass.__subclasses__()
</code></pre>
<p><strong>How would I outsource the subclasses in different files without creating circle import</strong></p>
<p><em>a... | 0 | 2016-05-31T12:10:23Z | [
"python",
"oop",
"inheritance"
] |
Error with utf-16 encoded data in python | 37,543,359 | <p>Here's a snippet of code where a string is to be UTF-16 encoded and sent on the wire:</p>
<pre><code># -*- coding: utf8-*-
import unit_test_utils
import os
import sys
...
...
def run():
test_dir = unit_test_utils.get_test_dir("test")
try:
file_name = u'débárquér.txt'
open_req = creater... | 0 | 2016-05-31T10:37:33Z | 37,543,752 | <p>try to replace:</p>
<pre><code>utf16_filename = file_name.decode('utf8').encode('UTF-16LE')
</code></pre>
<p>with</p>
<pre><code>utf16_filename = unicode(file_name.decode('utf8')).encode('UTF-16LE')
</code></pre>
| -1 | 2016-05-31T10:55:32Z | [
"python",
"unicode"
] |
Error with utf-16 encoded data in python | 37,543,359 | <p>Here's a snippet of code where a string is to be UTF-16 encoded and sent on the wire:</p>
<pre><code># -*- coding: utf8-*-
import unit_test_utils
import os
import sys
...
...
def run():
test_dir = unit_test_utils.get_test_dir("test")
try:
file_name = u'débárquér.txt'
open_req = creater... | 0 | 2016-05-31T10:37:33Z | 37,555,444 | <p>Do not assign text to byte strings. In Python 2 that means you have to use unicode literals:</p>
<pre><code>file_name = u'débárquér.txt' # <-- unicode literal
utf16_filename = file_name.encode('UTF-16LE')
</code></pre>
<p>Then make sure you accurately declare the encoding of your source file.</p>
| 2 | 2016-05-31T20:55:03Z | [
"python",
"unicode"
] |
Error with utf-16 encoded data in python | 37,543,359 | <p>Here's a snippet of code where a string is to be UTF-16 encoded and sent on the wire:</p>
<pre><code># -*- coding: utf8-*-
import unit_test_utils
import os
import sys
...
...
def run():
test_dir = unit_test_utils.get_test_dir("test")
try:
file_name = u'débárquér.txt'
open_req = creater... | 0 | 2016-05-31T10:37:33Z | 37,558,525 | <p>When working with Unicode text, convert incoming byte strings to Unicode as soon as you can, work with Unicode text in the script, then convert back to byte strings as late as you can.</p>
<p>You've got a mix of byte strings in different encodings and the likely cause of trouble is this line:</p>
<pre><code>open_r... | 2 | 2016-06-01T02:38:56Z | [
"python",
"unicode"
] |
updating a field in table A only by insert operation in table B | 37,543,366 | <p>i'm writing some sort of api for websites who can't access to banks payment gateways directly ... basically user would create a gateway on my website and uses that gateway to connect to banks and make transactions </p>
<p>here is my gateway model </p>
<pre><code>class Gateways(models.Model):
user = models.For... | 0 | 2016-05-31T10:37:59Z | 37,543,426 | <p>I think you can use django <code>post_save</code>
see this <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#post-save" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/signals/#post-save</a></p>
<p>Update your models.py with the below codes</p>
<pre><code>def update_money(sender, instance, creat... | 1 | 2016-05-31T10:40:48Z | [
"python",
"mysql",
"django",
"transactions"
] |
Python: Modify Values in eml file (email header) | 37,543,395 | <p>I would like to have a changes of "To" and "From" field's email addresses using Python. So far now I did following which is working for reading required field. Any one please suggest, How to make change in them.</p>
<pre><code>from email.parser import Parser
fp = open('2.eml', 'r+')
headers = Parser().parse(fp)
#... | 1 | 2016-05-31T10:39:02Z | 37,543,620 | <p>You should write the changed message back to the file:</p>
<pre><code>with open('2.eml', 'w') as outfile:
outfile.write(headers.as_string())
</code></pre>
<p>Note that your name <code>headers</code> is not completely accurate as the value returned by <a href="https://docs.python.org/2/library/email.parser.html... | 1 | 2016-05-31T10:49:34Z | [
"python",
"parsing",
"eml"
] |
How can I find out the PID of the affected process in signal handler | 37,543,526 | <p>I've got the following signal handler:</p>
<pre><code>def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
</code></pre>
<p>The signal handler registration is the following:</p>
<pre><code>signal.signal(signal.SIGINT, signal_handler)
</code></pre>
<p>How can I find out the affected... | 0 | 2016-05-31T10:45:49Z | 37,543,832 | <p>I suggest using <code>os.getpid()</code>:</p>
<pre><code>import os, sys, signal
def signal_handler(signal, frame):
pid = os.getpid()
print('You pressed Ctrl+C (pid = {0})'.format(pid))
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
</code></pre>
<p>Reference: <a href="https://docs.python.or... | 2 | 2016-05-31T10:59:05Z | [
"python",
"python-3.x",
"signals"
] |
How do I beautify (auto-format) a piece of code in Spyder IDE | 37,543,581 | <p>How can I select a piece of code and apply auto-format, aka beautification to it?</p>
<p>I especially mean correctly indenting lists broken into several lines, parentheses and square brackets.</p>
<p>Auto-indent does nothing.</p>
| 1 | 2016-05-31T10:48:01Z | 37,709,712 | <p>One possible solution is to use this plugin:
<a href="https://github.com/Nodd/spyder_autopep8" rel="nofollow">autopep8 for Spyder</a></p>
<p>Although since Python is a language where code functionality depends on the amount of whitespace, beautification tools can never really format the code in an unified way.</p>
... | 0 | 2016-06-08T18:01:09Z | [
"python",
"ide",
"spyder",
"beautifier",
"autoformat"
] |
Windows Batch start python script with pipe | 37,543,626 | <p>I'm trying to create a batch script or scheduled task that can run this:</p>
<pre><code>pythonw manage.py runserver >nul
</code></pre>
<p>This will run if I wrote it from a command prompt, and return me the prompt, but if I try to run it using a batch file or an scheduled task it will open a window and lock its... | 1 | 2016-05-31T10:50:00Z | 37,545,214 | <p>Ok, after testing more and more I found something that works. Sorry for making the Question without searching and testing more.</p>
<p>This is what has worked:</p>
<pre><code>CMD /c start "" /B path\to\pythonw.exe path\to\manage.py runserver > nul ^& exit
</code></pre>
<p>Inside a .cmd file.
Executing the ... | 0 | 2016-05-31T12:01:53Z | [
"python",
"windows",
"batch-file",
"cmd"
] |
How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0 | 37,543,647 | <p>I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.</p>
<p>Initially I tried for-loop on each value of the dataframe which was taking too much time.</p>
<p>Then I used <strong>data_new=data.subtract(data)</strong> which was meant to subtract al... | 1 | 2016-05-31T10:50:46Z | 37,543,707 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.notnull.html" rel="nofollow"><code>notnull</code></a> with casting boolean to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow"><code>astype</code></a>:</p... | 3 | 2016-05-31T10:53:44Z | [
"python",
"pandas",
"dataframe"
] |
How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0 | 37,543,647 | <p>I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.</p>
<p>Initially I tried for-loop on each value of the dataframe which was taking too much time.</p>
<p>Then I used <strong>data_new=data.subtract(data)</strong> which was meant to subtract al... | 1 | 2016-05-31T10:50:46Z | 37,543,737 | <p>You can take the return value of <code>df.notnull()</code>, which is <code>False</code> where the DataFrame contains <code>NaN</code> and <code>True</code> otherwise and cast it to integer, giving you <code>0</code> where the DataFrame is <code>NaN</code> and <code>1</code> otherwise:</p>
<pre><code>newdf = df.notn... | 3 | 2016-05-31T10:54:55Z | [
"python",
"pandas",
"dataframe"
] |
How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0 | 37,543,647 | <p>I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.</p>
<p>Initially I tried for-loop on each value of the dataframe which was taking too much time.</p>
<p>Then I used <strong>data_new=data.subtract(data)</strong> which was meant to subtract al... | 1 | 2016-05-31T10:50:46Z | 37,543,817 | <p>There is a method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>.fillna()</code></a> on DataFrames which does what you need. For example:</p>
<pre><code>df = df.fillna(0) # Replace all NaN values with zero, returning the modified DataFrame
</code>... | 0 | 2016-05-31T10:58:20Z | [
"python",
"pandas",
"dataframe"
] |
How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0 | 37,543,647 | <p>I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.</p>
<p>Initially I tried for-loop on each value of the dataframe which was taking too much time.</p>
<p>Then I used <strong>data_new=data.subtract(data)</strong> which was meant to subtract al... | 1 | 2016-05-31T10:50:46Z | 37,543,831 | <p>I'd advise making a new column rather than just replacing. You can always delete the previous column if necessary but its always helpful to have a source for a column populated via an operation on another.</p>
<p>e.g. if df['col1'] is the existing column</p>
<pre><code>df['col2'] = df['col1'].apply(lambda x: 1 if ... | 0 | 2016-05-31T10:59:03Z | [
"python",
"pandas",
"dataframe"
] |
How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0 | 37,543,647 | <p>I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.</p>
<p>Initially I tried for-loop on each value of the dataframe which was taking too much time.</p>
<p>Then I used <strong>data_new=data.subtract(data)</strong> which was meant to subtract al... | 1 | 2016-05-31T10:50:46Z | 37,543,931 | <p>Use: <code>df.fillna(0)</code></p>
<p>to fill NaN with 0.</p>
| 0 | 2016-05-31T11:02:47Z | [
"python",
"pandas",
"dataframe"
] |
How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0 | 37,543,647 | <p>I have a dataframe with 71 columns and 30597 rows. I want to replace all non-nan entries with 1 and the nan values with 0.</p>
<p>Initially I tried for-loop on each value of the dataframe which was taking too much time.</p>
<p>Then I used <strong>data_new=data.subtract(data)</strong> which was meant to subtract al... | 1 | 2016-05-31T10:50:46Z | 37,545,697 | <p>I do a lot of data analysis and am interested in finding new/faster methods of carrying out operations. I had never come across jezrael's method, so I was curious to compare it with my usual method (i.e. replace by indexing). NOTE: This is not an answer to the OP's question, rather it is an illustration of the eff... | 1 | 2016-05-31T12:24:01Z | [
"python",
"pandas",
"dataframe"
] |
Gzip error with django latest version | 37,543,731 | <p>I get an error when i include the line "django.middleware.gzip" under the middleware section in settings.py in the django framework. I checked the gzip file location in the nginx server , its present and looks correct.</p>
<p>I am getting a 500 internal server error. Can anyone help me with this?</p>
<p>I cant eve... | 0 | 2016-05-31T10:54:42Z | 37,544,234 | <p><code>django.middleware.gzip</code> is the module that contains the middleware, not the middleware class. To enable the gzip middleware, you should include:</p>
<pre><code>'django.middleware.gzip.GZipMiddleware',
</code></pre>
<p>Before enabling the gzip middleware, note the warning in <a href="https://docs.django... | 0 | 2016-05-31T11:17:46Z | [
"python",
"django",
"nginx",
"gzip",
"django-middleware"
] |
Python bluetooth returns nothing (Raspberry PI) | 37,543,802 | <p>I got the following code: </p>
<pre><code>import bluetooth
def apparaat():
nearby_devices = bluetooth.discover_devices(lookup_names = True, flush_cache = True, duration = 15)
for address in nearby_devices:
print("Gevonden apparaten: " + str(address))
print("Gevonden apparaten: " + str(nearby_d... | 0 | 2016-05-31T10:57:42Z | 37,544,579 | <p>Can you try to run this code? I found that someone ported this bluetooth package from python 2.7 to 3.x and it might have introduced some bugs when printing unicode strings. </p>
<pre><code>import bluetooth
x = bluetooth.discover_devices()
n = bluetooth.lookup_name(x[0])
print(n)
</code></pre>
<p>(source: <a href=... | 1 | 2016-05-31T11:32:52Z | [
"python",
"bluetooth"
] |
Plot different color for different categorical levels in ggplot | 37,543,852 | <p>I have this dataframe composed of sample IDs, PCA values and respective population.
<a href="http://i.stack.imgur.com/Hcmwt.png" rel="nofollow">my dataframe</a></p>
<p>I have generated the MDS plot for this data using ggplot in python using the following command:</p>
<pre><code>from ggplot import *
print ggplot(ae... | 1 | 2016-05-31T10:59:50Z | 37,545,561 | <p>This should do:</p>
<pre><code>from ggplot import *
p = ggplot(aes(x='C1', y='C2', color='Population'), data=mds)+ geom_point(alpha=0.6) + ggtitle('My plot')
print p
</code></pre>
<p>Make sure to have the quotes around your column names and to have the <code>color</code> argument inside your <code>aes</code> fun... | 3 | 2016-05-31T12:17:44Z | [
"python",
"pandas"
] |
How to choose an alternative name for sheet in xls file from python? | 37,543,975 | <p>I want to transfer my data from python to excel file in various sheets. So I need to change the name of the sheet to choose the proper sheet to write on. I have written this code but it does not accept me to give an alternative name to my sheet in <code>ws = wb.add_sheet("Patch Size %s",%(wo))</code> line. </p>
<pr... | 0 | 2016-05-31T11:05:02Z | 37,544,071 | <p>There are quite a few errors in your code. Try this:</p>
<pre><code>whch = 25
wb = xlwt.Workbook()
w0 = 0
while whch != patch[w0]:
w0 = w0+1
ws = wb.add_sheet("Patch Size %s" %(w0)) # no comma needed, changed wo to w0
for i, row in enumerate(DATA):
for j ,col in enumerate(row):
if j == 0:
... | 1 | 2016-05-31T11:09:43Z | [
"python",
"xls"
] |
How to choose an alternative name for sheet in xls file from python? | 37,543,975 | <p>I want to transfer my data from python to excel file in various sheets. So I need to change the name of the sheet to choose the proper sheet to write on. I have written this code but it does not accept me to give an alternative name to my sheet in <code>ws = wb.add_sheet("Patch Size %s",%(wo))</code> line. </p>
<pr... | 0 | 2016-05-31T11:05:02Z | 37,544,126 | <p>It seems like your error is on your sheet name string formatting (you have a misplaced comma), and not from xlwt :</p>
<pre><code>ws = wb.add_sheet("Patch Size %s",%(wo))
</code></pre>
<p>Should be </p>
<pre><code>ws = wb.add_sheet("Patch Size %s"%(wo))
</code></pre>
<p>or </p>
<pre><code>ws = wb.add_sheet("Pat... | 1 | 2016-05-31T11:12:34Z | [
"python",
"xls"
] |
Pytest text annotation for test with tuple of parameters | 37,544,195 | <p>I'm looking for more elegant solution for this kind of problem:</p>
<pre><code>def ids(x):
if isinstance(x, int):
return str(x)
elif isinstance(x, str):
return x[0]
@pytest.mark.parametrize("number, string",
[
(1, "One"),
... | 1 | 2016-05-31T11:15:47Z | 37,591,040 | <p>The only solution i've found is to use hook <code>pytest_collection_modifyitems(session, config, items)</code>
It has access to parameters values, and can be used to change test names. But it relies on internal details of pytest Function class implementation and thus is not very robust.</p>
<p>I add pytest.mark wit... | 1 | 2016-06-02T11:49:45Z | [
"python",
"py.test"
] |
Pytest text annotation for test with tuple of parameters | 37,544,195 | <p>I'm looking for more elegant solution for this kind of problem:</p>
<pre><code>def ids(x):
if isinstance(x, int):
return str(x)
elif isinstance(x, str):
return x[0]
@pytest.mark.parametrize("number, string",
[
(1, "One"),
... | 1 | 2016-05-31T11:15:47Z | 37,623,938 | <p>Pass a list of strings instead of a callable as <code>ids</code>:</p>
<pre><code>import pytest
PARAMS = [
(1, "One"),
(2, "Two"),
(3, "Three")
]
def my_id(number, string):
return '-'.join([str(number), string[0]])
@pytest.mark.parametrize("number, string",
PARAMS,
... | 1 | 2016-06-03T21:46:49Z | [
"python",
"py.test"
] |
Scrapy, how to extract h3 content? | 37,544,295 | <p>I want to extract the web content in every <code>div class="summary"</code>.
And in every <code>summary</code> div, I want to extract the data in every class in the div.</p>
<p>The following are my snippet.</p>
<pre><code>questions = Selector(response).xpath('//div[@class="summary"]')
for question in questions:
... | 0 | 2016-05-31T11:20:08Z | 37,544,853 | <p>Your 2nd XPath looks for <em><code>a</code> element that is direct child of <code>div[@class="summary"]</code> and has attribute <code>h3</code></em>, which doesn't exist in the HTML posted.</p>
<p>The correct XPath to get <code>a</code> element within <code>h3</code> from the <code>div</code> would be as follow :<... | 1 | 2016-05-31T11:45:26Z | [
"python",
"css",
"xpath",
"scrapy",
"web-crawler"
] |
Scrapy, how to extract h3 content? | 37,544,295 | <p>I want to extract the web content in every <code>div class="summary"</code>.
And in every <code>summary</code> div, I want to extract the data in every class in the div.</p>
<p>The following are my snippet.</p>
<pre><code>questions = Selector(response).xpath('//div[@class="summary"]')
for question in questions:
... | 0 | 2016-05-31T11:20:08Z | 37,550,701 | <p>Another way to put it may be:</p>
<pre><code>questions = Selector(response).xpath('div[@class="summary"]/h3')
</code></pre>
<p>and in order to grab the data from the <code><a></code>:</p>
<pre><code>item['title'] = question.xpath('/a/text()').extract()[0]
</code></pre>
<p>This is useful if all the data you... | 0 | 2016-05-31T16:08:47Z | [
"python",
"css",
"xpath",
"scrapy",
"web-crawler"
] |
What is the proper way to handle TypeError in Jinja2 | 37,544,416 | <p>I am doing some simple calculations in a jinja2 template (subtraction) and would like to find a solution to handle TypeErrors in Jinja2.</p>
<p>This is what I have tried so far: To ignore unavailable variables during rendering, I subclassed Undefined() like such. </p>
<pre><code>def silently(*args, **kwargs):
... | 0 | 2016-05-31T11:25:51Z | 37,544,647 | <p>At first approximation, it sounds more logical and more in the lines of Jinja2 to move your calculation functions out of Jinja and keep them in Python.</p>
<pre><code>def some_simple_calculation(*args, **kwargs):
# handle errors here
t = Template(reportEmailTemplateHTML)
t.globals['some_simple_calculation'] = ... | 0 | 2016-05-31T11:35:51Z | [
"python",
"jinja2"
] |
What is the difference between Authorization and Authentication in Django? | 37,544,543 | <p>I came over those two terms when reading the Django documentation and they were used to resemble seemingly different meanings. What is the difference?</p>
| 1 | 2016-05-31T11:31:27Z | 37,544,595 | <p>From the <a href="https://docs.djangoproject.com/en/1.9/topics/auth/" rel="nofollow">django docs</a>:</p>
<blockquote>
<p>authentication verifies a user is who they claim to be, and authorization determines what an authenticated user is allowed to do</p>
</blockquote>
| 0 | 2016-05-31T11:33:40Z | [
"python",
"django",
"django-authentication"
] |
What is the difference between Authorization and Authentication in Django? | 37,544,543 | <p>I came over those two terms when reading the Django documentation and they were used to resemble seemingly different meanings. What is the difference?</p>
| 1 | 2016-05-31T11:31:27Z | 37,544,597 | <p>Straight out of the <a href="https://docs.djangoproject.com/en/1.9/topics/auth/" rel="nofollow">Django Documentation</a>:</p>
<blockquote>
<p>The Django authentication system handles both authentication and authorization. Briefly, authentication verifies a user is who they claim to be, and authorization determine... | 4 | 2016-05-31T11:33:44Z | [
"python",
"django",
"django-authentication"
] |
Pandas: Approximate join on one column, exact match on other columns | 37,544,695 | <p>I have two pandas dataframes I want to join/merge exactly on a number of columns (say 3) and approximately, i.e nearest neighbour, on one (date) column. I also want to return the difference (days) between them. Each dataset is about 50,000 rows long. I'm most interested in an inner join, but the âleftoversâ are ... | 1 | 2016-05-31T11:37:56Z | 37,549,835 | <p>Hej mate,</p>
<p>I am not sure if this suits. It achieves more or less what you want but does not actually perform a merge. It follows the same idea as this <a href="http://stackoverflow.com/questions/33421551/how-to-merge-two-data-frames-based-on-nearest-date?lq=1">question</a> except instead of subsetting the <co... | 1 | 2016-05-31T15:29:22Z | [
"python",
"pandas",
"merge",
"nearest-neighbor",
"exact-match"
] |
python SQL statement with variables without using %s | 37,544,767 | <p>I hope i can be clear about my problem. thank you :)</p>
<p>I'm using impala connection (library: from impala.dbapi import connect).</p>
<p>In order to run a query i'm using the execute command:
<code>cursor.execute(query.value, (year_var, month_var,day_var))</code></p>
<p>Generally - it works just fine, also wi... | -1 | 2016-05-31T11:41:03Z | 37,545,517 | <p>You could escape literal percent signs in the query (e.g. <code>%%seo%%</code>), although it would be cleaner to pass the patterns as parameters to <code>execute()</code> as well:</p>
<pre><code>sql = """
create table bi_db.search_terms as
select search_query,search_contain,count(*) searches
from (
select search_q... | 0 | 2016-05-31T12:15:56Z | [
"python",
"sql",
"string",
"variables",
"impala"
] |
Incompatible dense layer error in keras | 37,544,894 | <p>My input is an series of videos, 8500 in number. Each video is fed to LSTM as a series of 50 frames, each frame having 960 pixels.
So the input dim is 8500,50,960
There are 487 possible output classes possible, so the output dimension is 8500,487.</p>
<p>But when I run the following code, I am getting these errors ... | 0 | 2016-05-31T11:46:56Z | 37,546,654 | <p>print("Adding second layer..")
model.add(LSTM(100, return_sequences=False))</p>
| 2 | 2016-05-31T13:08:03Z | [
"python",
"python-2.7",
"neural-network",
"deep-learning",
"keras"
] |
Linear Regression in TensorFlow: How to obtain all estimated y-values of y = m*x? | 37,545,175 | <p>I am working with the code for linear regression in TensorFlow from <a href="https://github.com/nlintz/TensorFlow-Tutorials/blob/master/1_linear_regression.py" rel="nofollow">https://github.com/nlintz/TensorFlow-Tutorials/blob/master/1_linear_regression.py</a></p>
<p>This code computes a regression-function that I ... | 0 | 2016-05-31T11:59:48Z | 37,552,865 | <p>The second approach points in the right direction. However, it is implemented slightly incorrect.</p>
<p>More specifically, the code only prints <code>y_model</code> for <strong>one</strong> <code>x</code> as the feed dictionary only passes one <code>x</code>.
Therefore, one has to just implement a for-loop to ensu... | 0 | 2016-05-31T18:14:54Z | [
"python",
"regression",
"tensorflow"
] |
(Python) Program to read specific data from many output files | 37,545,479 | <p>I recently ran a simulation that output temporal data in directories numbered <code>0</code>, <code>0.1</code>, <code>0.2</code>, ... , <code>10</code>. </p>
<p>Within each of these directories there is a text file called <code>rigidMotion</code> which contains a line I want to read.</p>
<p>The line looks like:</p... | 0 | 2016-05-31T12:13:28Z | 37,545,525 | <p>You can use <a href="https://docs.python.org/2/library/glob.html" rel="nofollow">glob</a> to find files according to a pattern, which in your case might be something like <code>*/rigidMotion</code>, then iterate over those files and collect the values, outputting them to a new file.</p>
| 2 | 2016-05-31T12:16:06Z | [
"python"
] |
(Python) Program to read specific data from many output files | 37,545,479 | <p>I recently ran a simulation that output temporal data in directories numbered <code>0</code>, <code>0.1</code>, <code>0.2</code>, ... , <code>10</code>. </p>
<p>Within each of these directories there is a text file called <code>rigidMotion</code> which contains a line I want to read.</p>
<p>The line looks like:</p... | 0 | 2016-05-31T12:13:28Z | 37,545,656 | <p>For the directory reading this worked for me the best in multiple directories:</p>
<pre><code>import os
for subdir, dirs, files in os.walk("your root directory"):
for file in files:
print os.path.join(subdir, file)
#processing the files
</code></pre>
<p>For the line processing i would use stri... | 1 | 2016-05-31T12:22:26Z | [
"python"
] |
Selecting csv row with the highest column value among rows with the same value of another column in python | 37,545,538 | <p>I created a topic model with 20 topics using Latent Dirichlet Allocation for 5000+ txt documents. I now have a .csv file which contains three columns: document number, topic number, and probability of topic in the document. It looks like this (for docs n°1 and n°2):</p>
<pre><code>1 1 0,113
1 4 0,2
1 7 ... | 1 | 2016-05-31T12:16:40Z | 37,545,640 | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>replace</code></a> <code>,</code> to <code>.</code> in column <code>probability</code> and convert to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/... | 1 | 2016-05-31T12:21:51Z | [
"python",
"csv",
"pandas"
] |
Dealing with a huge amount of threads and db connections (Python) What can I do to conserve resources? | 37,545,542 | <p>I'm playing around with a radio streaming project. Currently I'm creating a python backend. There are over 150,000 online radio station streams in the database. One feature I'm trying to add is to search the radio stations by their currently playing song. I'm using <a href="https://github.com/Dirble/streamscrobbler-... | 0 | 2016-05-31T12:16:53Z | 37,559,143 | <p>You don't need a real thread for each task since most of the time, the thread will be waiting on IO from a socket (the web-request).</p>
<p>What you could try is <a href="https://en.wikipedia.org/wiki/Green_threads" rel="nofollow">green threads</a> using something like <a href="http://www.gevent.org/" rel="nofollow... | 1 | 2016-06-01T03:54:41Z | [
"python",
"mysql",
"multithreading",
"concurrency",
"sqlalchemy"
] |
How to create pcolormesh with the mean of a set of data? | 37,545,607 | <p>How do I use this set of data and plot it using pcolormesh? the data is as follows:</p>
<pre><code>array([[ 0. , 0. , 0. , ...,
0. , 0. , 0. ],
[ 34.19227552, 34.19246389, 34.19265956, ...,
34.19284295, 34.19253446, 34.1923... | -3 | 2016-05-31T12:20:16Z | 37,545,730 | <p>Maybe you can follow this turorials:</p>
<p><a href="http://matplotlib.org/examples/pylab_examples/pcolor_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/pcolor_demo.html</a></p>
<p>or</p>
<p><a href="http://mlpy.sourceforge.net/docs/3.3/tutorial.html" rel="nofollow">http://mlpy.sourceforg... | 0 | 2016-05-31T12:25:14Z | [
"python",
"matplotlib"
] |
Can't instal Django on RedHat | 37,545,714 | <p>I try to download Django project with pip command :</p>
<pre><code>pip install django
</code></pre>
<p>But I get the following : </p>
<pre><code>Downloading/unpacking django
Cannot fetch index base URL https://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement django
Cleaning up... | 0 | 2016-05-31T12:24:36Z | 37,546,057 | <blockquote>
<p>can I choose the version of Django that I install?</p>
</blockquote>
<p>You can. Use <code>pip install Django==1.4.3</code> for example, to install a specific version.</p>
<p>Or <code>pip install "Django<1.9"</code> to get the latest stable <code>1.8</code> build.</p>
| 1 | 2016-05-31T12:41:13Z | [
"python",
"django",
"proxy",
"redhat"
] |
How to change DataFrame Series from price to percentage with pandas/python | 37,545,824 | <p>I have a pandas dataFrame with date,time and stock price like this:</p>
<pre><code>+------------+-------+-------+-------+
| | 08:01 | 08:02 | 08:03 |
+------------+-------+-------+-------+
| 01/01/2016 | 50 | 50.5 | 50.7 |
+------------+-------+-------+-------+
| 02/01/2016 | 49.6 | 49.5 | 49.6 |... | 0 | 2016-05-31T12:29:33Z | 37,545,960 | <p>Use difference by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a> with first column selected by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> and last substr... | 3 | 2016-05-31T12:36:23Z | [
"python",
"python-3.x",
"pandas"
] |
Send byte (0xFF) with Node.js through SerialPort | 37,545,844 | <p>I send command with an ending byte, it's : 0xFF three times. In python, this code is working :</p>
<pre><code>import time
import serial
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
while 1:
... | 0 | 2016-05-31T12:30:27Z | 37,563,533 | <p>The answer is : I need to use a buffer to send byte with Node.js</p>
<p>This is my function :</p>
<pre><code>function hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var ascii = str.charCodeAt(i);
arr.push(ascii);
}
arr.push... | 0 | 2016-06-01T08:38:26Z | [
"javascript",
"python",
"node.js",
"serial-port"
] |
Add spacer lines in a text file's list with Python | 37,545,901 | <p>I have a text file with a list of entries, like this:</p>
<pre><code>entry
entry
entry
entry
</code></pre>
<p>and I would like to open, change and then write the file like this</p>
<pre><code>entry
entry
entry
entry
</code></pre>
<p>Because there are several duplicates, I've used this method to remove... | 0 | 2016-05-31T12:33:13Z | 37,546,072 | <pre><code>open("uniqueenties.txt",'w').writelines([(f + '\n') for f in open("oldentries.txt",'r').readlines()])
</code></pre>
<p>Might be also a good idea to split your line in 2 and use variables like so :</p>
<pre><code>input_file = open("oldentries.txt",'r')
oldentries = input_file.readlines()
newentries = [(f + ... | 0 | 2016-05-31T12:42:05Z | [
"python",
"line-breaks"
] |
Add spacer lines in a text file's list with Python | 37,545,901 | <p>I have a text file with a list of entries, like this:</p>
<pre><code>entry
entry
entry
entry
</code></pre>
<p>and I would like to open, change and then write the file like this</p>
<pre><code>entry
entry
entry
entry
</code></pre>
<p>Because there are several duplicates, I've used this method to remove... | 0 | 2016-05-31T12:33:13Z | 37,546,150 | <h1>Use this code</h1>
<p>f = open("file.txt").read()</p>
<p>txt = t.replace("\n", "\n\n")</p>
<p>wf = open("changed.txt", "w")</p>
<p>wf.write(txt)</p>
| 0 | 2016-05-31T12:45:34Z | [
"python",
"line-breaks"
] |
Can I use select query in aws redshift python udf function | 37,546,159 | <p>How I can execute a select query in AWS Redshift UDF using plpythonu like oracle function with select into class in function like below.</p>
<pre><code>CREATE OR REPLACE FUNCTION udf(id varchar(50))
RETURNS VARCHAR(50)
STABLE
AS $$
result = plpy.execute("SELECT count(*) FROM abc")
return result
$$ LANGUAGE p... | 1 | 2016-05-31T12:45:43Z | 38,452,773 | <p>It's available on Postgresql (<a href="https://www.postgresql.org/docs/9.2/static/plpython-database.html" rel="nofollow">https://www.postgresql.org/docs/9.2/static/plpython-database.html</a>).</p>
<p>At present, Amazon Redshift is not supported.</p>
<p>Same question like yours on this url:
<a href="https://blogs.... | 0 | 2016-07-19T08:07:56Z | [
"python",
"amazon-web-services",
"amazon-redshift"
] |
pandas dataframe creation from dict or list too slow, any suggestions? | 37,546,180 | <p>Hello I am trying to create a pandas dataframe from (a list of dicts or a dict of dicts) that has an eventual shape of 60,000 rows and 10,000~ columns</p>
<p>Values of columns are 0 or 1 and really sparse. </p>
<p>The list/dict object creation is fast, but when I do from_dict or from_records I get memory errors. I... | 1 | 2016-05-31T12:46:53Z | 37,546,925 | <p>if you have only <code>0</code> and <code>1</code> as values you should use <code>np.bool</code> or <code>np.int8</code> as a dtype - this will reduce your memory consumption by at least 4 times.</p>
<p>Here is a small demonstration:</p>
<pre><code>In [34]: df = pd.DataFrame(np.random.randint(0,1,(60000, 10000)))
... | 0 | 2016-05-31T13:19:42Z | [
"python",
"pandas",
"dataframe",
"scikit-learn"
] |
Python - how to reduce a list and keep values? | 37,546,189 | <p>I have a list looking like that: </p>
<pre><code>[[12, 0.029], [12, 0.039], [12, 0.012], ...some hundreds more... [13, 0.04], [13, 0.01], ...]
</code></pre>
<p>The first values range from 3 to 15, with an overall count of about 3000 values</p>
<p>For boxplotting I would need a solution where a boxplot is created ... | 3 | 2016-05-31T12:47:22Z | 37,546,337 | <p>It seems like you want a dictionary with the first values as keys and the second values as elements of a list. You could do something like:</p>
<pre><code>data_dict = {}
for key, value in list:
if key not in data_dict:
data_dict.update({key: [value]})
else:
data_dict[key].append(value)
</co... | 2 | 2016-05-31T12:53:13Z | [
"python",
"list",
"merge",
"boxplot"
] |
Python - how to reduce a list and keep values? | 37,546,189 | <p>I have a list looking like that: </p>
<pre><code>[[12, 0.029], [12, 0.039], [12, 0.012], ...some hundreds more... [13, 0.04], [13, 0.01], ...]
</code></pre>
<p>The first values range from 3 to 15, with an overall count of about 3000 values</p>
<p>For boxplotting I would need a solution where a boxplot is created ... | 3 | 2016-05-31T12:47:22Z | 37,546,402 | <p>Use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>. Suppose your data (a list of lists) is sorted by the first value.</p>
<pre><code>import itertools
import operator
lists = [[12, 0.029], [12, 0.039], [12, 0.052], [13, 0.04], [13, 0.01... | 0 | 2016-05-31T12:55:57Z | [
"python",
"list",
"merge",
"boxplot"
] |
Python - how to reduce a list and keep values? | 37,546,189 | <p>I have a list looking like that: </p>
<pre><code>[[12, 0.029], [12, 0.039], [12, 0.012], ...some hundreds more... [13, 0.04], [13, 0.01], ...]
</code></pre>
<p>The first values range from 3 to 15, with an overall count of about 3000 values</p>
<p>For boxplotting I would need a solution where a boxplot is created ... | 3 | 2016-05-31T12:47:22Z | 37,546,420 | <p>Use a <code>defaultdict</code> with default as <code>list</code> so you don't need to check if a key already exists. Then collect values using the first items as keys:</p>
<pre><code>from collections import defaultdict
result = defaultdict(list)
lst = [[12, 0.029], [12, 0.039], [13, 0.04], [13, 0.01]]
for l in ls... | 1 | 2016-05-31T12:56:44Z | [
"python",
"list",
"merge",
"boxplot"
] |
Python - how to reduce a list and keep values? | 37,546,189 | <p>I have a list looking like that: </p>
<pre><code>[[12, 0.029], [12, 0.039], [12, 0.012], ...some hundreds more... [13, 0.04], [13, 0.01], ...]
</code></pre>
<p>The first values range from 3 to 15, with an overall count of about 3000 values</p>
<p>For boxplotting I would need a solution where a boxplot is created ... | 3 | 2016-05-31T12:47:22Z | 37,546,436 | <p>You can use iterators (but the list with pairs should have an even length):</p>
<pre><code>data = [[12, 0.029], [12, 0.039], [13, 0.04], [13, 0.01]]
iter_second = (x[1] for x in data)
#py2
data_to_plot = zip(*([iter_second]*2))
#py3
data_to_plot = tuple(zip(*([iter_second]*2)))
</code></pre>
<blockquote>
<p>But ... | 1 | 2016-05-31T12:57:44Z | [
"python",
"list",
"merge",
"boxplot"
] |
Python - how to reduce a list and keep values? | 37,546,189 | <p>I have a list looking like that: </p>
<pre><code>[[12, 0.029], [12, 0.039], [12, 0.012], ...some hundreds more... [13, 0.04], [13, 0.01], ...]
</code></pre>
<p>The first values range from 3 to 15, with an overall count of about 3000 values</p>
<p>For boxplotting I would need a solution where a boxplot is created ... | 3 | 2016-05-31T12:47:22Z | 37,546,548 | <p>Something like (the other answers weren't aware that you only want to have data points with 12 as the first value):</p>
<pre><code>data = [[12, 0.029], [12, 0.039], [13, 0.04], [13, 0.01]]
items = []
points = [point[1] for point in data if point[0] == 12]
for i in range(0, len(points), 2):
try:
items.a... | 0 | 2016-05-31T13:02:39Z | [
"python",
"list",
"merge",
"boxplot"
] |
multiple call body multicoreprocessing python | 37,546,255 | <p>I am using the module multiprocessing in python. Before I call my main function with the mapping function, I need to get some input from the user. My problem is that the code before the main function gets executed multiple times when I call the main function with pool.map
This very simple code illustrates my problem... | 0 | 2016-05-31T12:49:50Z | 37,546,439 | <p>It does not display "start" for me with python 3.4.</p>
<p>Don't know your version of Python, but it might be because in each process of the pool, your file is imported and then the test function is executed. It means that code written "globally", is executed once at start of the process.</p>
<p>I have to admit it... | 1 | 2016-05-31T12:57:51Z | [
"python",
"multiprocessing"
] |
Python get system environment variables on windows | 37,546,356 | <p>How can I get <strong>system</strong> environment variables on windows? With the below codes I <strong>only get the user</strong> environment variables:</p>
<pre><code>os.environ['PATH']
</code></pre>
<p>Or this returns the same:</p>
<pre><code>os.getenv('PATH')
</code></pre>
<p>Thank you!</p>
| 0 | 2016-05-31T12:53:51Z | 37,547,237 | <p>Based on a (deleted) comment I found the solution. System environment variables should be read from the registry if the python script is run by a user and not by administrator.</p>
<pre><code>import winreg
reg_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
reg_key = winreg.OpenKey(winreg.H... | 0 | 2016-05-31T13:32:12Z | [
"python",
"windows",
"environment-variables"
] |
How to print '%d' & '%s' in a class in python | 37,546,433 | <p>I'm writing a script which counts some specific words and gives me specific count of the words. </p>
<p>I'm currently stuck in printing data, from the class. </p>
<p>My next task would be put these values in a excel file using a data driven framework. </p>
<p>Here's what i have done until now:</p>
<pre><code>a =... | 1 | 2016-05-31T12:57:31Z | 37,546,582 | <p>You're applying the formatting with the <code>%</code> operator to just the last string, in this case <code>'%d'</code>. This won't work with the <code>title</code> argument.</p>
| 0 | 2016-05-31T13:04:11Z | [
"python",
"python-2.7",
"class",
"oop",
"beautifulsoup"
] |
How to print '%d' & '%s' in a class in python | 37,546,433 | <p>I'm writing a script which counts some specific words and gives me specific count of the words. </p>
<p>I'm currently stuck in printing data, from the class. </p>
<p>My next task would be put these values in a excel file using a data driven framework. </p>
<p>Here's what i have done until now:</p>
<pre><code>a =... | 1 | 2016-05-31T12:57:31Z | 37,546,585 | <p>You could start by removing the string concatenation from the format strings: <code>'%s' + ' ' + '%d'</code> -> <code>'%s %d'</code>. The problem with your syntax is that the string formatting is done first, before the concatenation happens, so in your case:</p>
<pre><code>'%s' + ' ' + '%d' % ('s', 2)
</code></pre>... | 0 | 2016-05-31T13:04:20Z | [
"python",
"python-2.7",
"class",
"oop",
"beautifulsoup"
] |
How to print '%d' & '%s' in a class in python | 37,546,433 | <p>I'm writing a script which counts some specific words and gives me specific count of the words. </p>
<p>I'm currently stuck in printing data, from the class. </p>
<p>My next task would be put these values in a excel file using a data driven framework. </p>
<p>Here's what i have done until now:</p>
<pre><code>a =... | 1 | 2016-05-31T12:57:31Z | 37,546,594 | <h1>Beware the operator precedence</h1>
<pre><code>'%s' + ' ' + '%d' %(tittle,blockcode_passed)
</code></pre>
<p>means</p>
<pre><code>'%s' + ' ' + ('%d' %(tittle,blockcode_passed))
</code></pre>
| 0 | 2016-05-31T13:04:52Z | [
"python",
"python-2.7",
"class",
"oop",
"beautifulsoup"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.