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 |
|---|---|---|---|---|---|---|---|---|---|
Repeat each elements based on a list of values | 38,758,708 | <p>Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example <code>A</code> in list <code>x</code> position 0 is repeated 2 times because of the value <code>2</code> at position 0 in the list <code>y</code>.</p>
<pre><code>>>> x = ['A', 'B', 'C... | 2 | 2016-08-04T04:52:24Z | 38,758,795 | <p>Just use a simple list comprehension:</p>
<pre><code>>>> x = ['A', 'B', 'C']
>>> y = [2, 1, 3]
>>> [x[i] for i in range(len(x)) for j in range(y[i])]
['A', 'A', 'B', 'C', 'C', 'C']
>>>
</code></pre>
| 3 | 2016-08-04T05:01:14Z | [
"python",
"list"
] |
Django model on_update=models.CASCADE related object reference | 38,758,723 | <p>I have looked for <code>django</code> doc in their official site but i can't find the article about the <code>on_update</code> model function here in <a href="https://docs.djangoproject.com/ja/1.9/ref/models/relations/" rel="nofollow">Related objects reference</a> except for <code>on_delete</code>.</p>
<p>Here is a... | 0 | 2016-08-04T04:53:32Z | 38,793,704 | <p>It's normally adviseable to completely leave the primary key alone when setting up your Django models, as these are used by Django in a number of ways to maintain relationships between objects. Django will set them up and use them automatically.</p>
<p>Instead, create a separate field in your model to keep track of... | 1 | 2016-08-05T16:15:25Z | [
"python",
"mysql",
"django"
] |
How to remove pattern from items in an array | 38,758,763 | <p>I'm trying to make a new array from an already existing array, where all the items in the array has a pattern in it. </p>
<p>For example</p>
<pre><code>my_array=['A_1.gi.kl','BC_1.gi.kl','FGKX_1.gi.kl']
</code></pre>
<p>What I want is a function that can automatically make </p>
<pre><code>my_new_array=['A','BC',... | 0 | 2016-08-04T04:58:08Z | 38,758,792 | <p>Use <code>split</code> with a comprehension:</p>
<pre><code>my_array = ['A_1.gi.kl', 'BC_1.gi.kl', 'FGKX_1.gi.kl']
my_new_array = [item.split('_')[0] for item in my_array]
</code></pre>
| 2 | 2016-08-04T05:01:02Z | [
"python",
"list",
"python-3.x"
] |
How to remove pattern from items in an array | 38,758,763 | <p>I'm trying to make a new array from an already existing array, where all the items in the array has a pattern in it. </p>
<p>For example</p>
<pre><code>my_array=['A_1.gi.kl','BC_1.gi.kl','FGKX_1.gi.kl']
</code></pre>
<p>What I want is a function that can automatically make </p>
<pre><code>my_new_array=['A','BC',... | 0 | 2016-08-04T04:58:08Z | 38,758,813 | <p>Define the suffix:</p>
<pre><code>>>> suffix = '_1.gi.kl'
</code></pre>
<p>Then just split by the suffix:</p>
<pre><code>>>> [item.split(suffix)[0] for item in my_array]
['A', 'BC', 'FGKX']
>>>
</code></pre>
| 0 | 2016-08-04T05:03:04Z | [
"python",
"list",
"python-3.x"
] |
How to remove pattern from items in an array | 38,758,763 | <p>I'm trying to make a new array from an already existing array, where all the items in the array has a pattern in it. </p>
<p>For example</p>
<pre><code>my_array=['A_1.gi.kl','BC_1.gi.kl','FGKX_1.gi.kl']
</code></pre>
<p>What I want is a function that can automatically make </p>
<pre><code>my_new_array=['A','BC',... | 0 | 2016-08-04T04:58:08Z | 38,758,876 | <p>You can get element up to certain character by using <code>list.index</code> if all of your elements have that character( as you have mentioned)</p>
<pre><code>[v[:v.index('_')] for v in my_array]
['A', 'BC', 'FGKX']
</code></pre>
| 1 | 2016-08-04T05:07:48Z | [
"python",
"list",
"python-3.x"
] |
Python: subprocess call doesn't recognize * wildcard character? | 38,758,830 | <p>I want to remove all the *.ts in file. <code>os.remove</code> didn't work.</p>
<p>And this doesn't expand <code>*</code></p>
<pre><code>>>> args = ['rm', '*.ts']
>>> p = subprocess.call(args)
rm: *.ts No such file or directory
</code></pre>
| 0 | 2016-08-04T05:05:02Z | 38,758,859 | <p>The <code>rm</code> program takes a list of filenames, but <code>*.ts</code> isn't a list of filenames, it's a pattern for matching filenames. You have to name the actual files for <code>rm</code>. When you use a shell, the shell (but not <code>rm</code>!) will expand patterns like <code>*.ts</code> for you. In P... | 8 | 2016-08-04T05:06:59Z | [
"python",
"linux",
"shell",
"subprocess"
] |
Looking for a regex matching apostrophe only within string | 38,758,873 | <p>I'm looking for a Python regex that can match <code>'didn't'</code> and returns only the character that is immediately preceded by an apostrophe, like <code>'t</code>, but not the <code>'d</code> or <code>t'</code> at the beginning and end.</p>
<p>I have tried <code>(?=.*\w)^(\w|')+$</code> but it only matches the ... | -2 | 2016-08-04T05:07:42Z | 38,866,676 | <p>Here is a <a href="https://ideone.com/LDVyia" rel="nofollow">bunch of possible solutions</a>:</p>
<pre><code>import re
s = "'didn't'"
print(s.strip("'")[s.strip("'").find("'")+1])
print(re.search(r'\b\'(\w)', s).group(1))
print(re.search(r'\b\'([^\W\d_])', s).group(1))
print(re.search(r'\b\'([a-z])', s, flags=re.I... | 1 | 2016-08-10T07:20:24Z | [
"python",
"regex"
] |
Lists and pop() not working as I'd expect | 38,758,884 | <p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or che... | 0 | 2016-08-04T05:08:38Z | 38,759,108 | <p>What you could do is when they drink it do this</p>
<pre><code>potions = 1
if potions > 0:
drink potion
potions = potions - 1
else:
print "There are no potions left."
</code></pre>
| 1 | 2016-08-04T05:29:23Z | [
"python",
"list",
"pop"
] |
Lists and pop() not working as I'd expect | 38,758,884 | <p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or che... | 0 | 2016-08-04T05:08:38Z | 38,759,155 | <p>You can simply write your code as follows:</p>
<pre><code>if potions: # same as len(potions) > 0
# drink potion
potions.pop()
else:
print "There are no potions to drink."
</code></pre>
<p>So check if any potion is left, if it is left drink it and remove from list otherwise show there is no potion le... | 0 | 2016-08-04T05:33:30Z | [
"python",
"list",
"pop"
] |
Lists and pop() not working as I'd expect | 38,758,884 | <p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or che... | 0 | 2016-08-04T05:08:38Z | 38,759,828 | <p><a href="https://docs.python.org/2/glossary.html" rel="nofollow">EAFP</a> approach:</p>
<pre><code>try:
potions.pop()
except IndexError:
print "No potion left"
</code></pre>
<blockquote>
<p>Easier to ask for forgiveness than permission. This common Python
coding style assumes the existence of valid key... | 0 | 2016-08-04T06:20:13Z | [
"python",
"list",
"pop"
] |
Lists and pop() not working as I'd expect | 38,758,884 | <p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or che... | 0 | 2016-08-04T05:08:38Z | 38,760,911 | <p>OK. I was tempted... :) Of course, should exist a hierarchy of potions and the <code>print()</code> method could be a message to the 'world'. And so forth...</p>
<pre><code>import random
class Potion:
"""Define the Potion class. Could be explosive and provoke a damage"""
def __init__(self, explosive=None, ... | 0 | 2016-08-04T07:22:10Z | [
"python",
"list",
"pop"
] |
Pass a scoring function from sklearn.metrics to GridSearchCV | 38,758,925 | <p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html" rel="nofollow">GridSearchCV's documentations</a> states that I can pass a scoring function.</p>
<blockquote>
<p>scoring : string, callable or None, default=None</p>
</blockquote>
<p>I would like to use a native <a hr... | 0 | 2016-08-04T05:12:20Z | 38,759,297 | <p>It will work if you change <code>scoring=accuracy_score</code> to <code>scoring='accuracy'</code> (see the doco at <a href="http://scikit-learn.org/stable/modules/model_evaluation.html" rel="nofollow">http://scikit-learn.org/stable/modules/model_evaluation.html</a> for the full list of scorers you can use by name in... | 2 | 2016-08-04T05:45:33Z | [
"python",
"scikit-learn",
"grid-search"
] |
smtplib: Why do the recipients in "To" field receive the mail twice? | 38,758,956 | <p>I searched about this quite a lot, but could not fix the issue in my script. So finally, I decided to post it here.</p>
<p>Here's the code snippet:</p>
<pre><code>fromaddr = "someValidAddress@xyz.com"
cc = ['SomeEmailAlias@xyz.com']
toaddr = ""
msg = MIMEMultipart()
toaddrlist = list(toaddr.split(',')) #As... | 0 | 2016-08-04T05:15:05Z | 38,765,645 | <p>When the line <code>toaddrlist += (cc,)</code> is evaluated, the value of <code>toaddrlist</code> in your case is : </p>
<pre><code>["", ["SomeEmailAlias@xyz.com"]]
</code></pre>
<p>and it's wrong because <code>toaddrlist</code> must be a list of strings not a list containing some lists.</p>
<p>So the solution is... | 0 | 2016-08-04T11:06:57Z | [
"python",
"sendmail",
"smtplib"
] |
python list value make a list | 38,758,958 | <p>I want to make my list value as list.</p>
<p>example : </p>
<pre><code>abc = [1,2,3,4]
</code></pre>
<p>result : </p>
<pre><code>abc = [[1], [2], [3], [4]]
</code></pre>
<p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
| 0 | 2016-08-04T05:15:12Z | 38,758,983 | <p>I don't think you need numpy. A list comprehension should do.</p>
<pre><code>abc = [[x] for x in abc]
</code></pre>
| 8 | 2016-08-04T05:17:13Z | [
"python",
"list",
"numpy"
] |
python list value make a list | 38,758,958 | <p>I want to make my list value as list.</p>
<p>example : </p>
<pre><code>abc = [1,2,3,4]
</code></pre>
<p>result : </p>
<pre><code>abc = [[1], [2], [3], [4]]
</code></pre>
<p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
| 0 | 2016-08-04T05:15:12Z | 38,759,029 | <p>Try This:-</p>
<pre><code>abc = map(lambda x:[x], abc)
</code></pre>
| 2 | 2016-08-04T05:22:09Z | [
"python",
"list",
"numpy"
] |
python list value make a list | 38,758,958 | <p>I want to make my list value as list.</p>
<p>example : </p>
<pre><code>abc = [1,2,3,4]
</code></pre>
<p>result : </p>
<pre><code>abc = [[1], [2], [3], [4]]
</code></pre>
<p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
| 0 | 2016-08-04T05:15:12Z | 38,759,067 | <p>A non <code>list comprehension</code> or <code>lambda function</code> version would be </p>
<pre><code>abc = [1,2,3]
arr = []
for x in abc:
arr.append([x])
print arr
</code></pre>
<p>I believe this is more intuitive for beginners but less pythonic.</p>
| 1 | 2016-08-04T05:25:47Z | [
"python",
"list",
"numpy"
] |
python list value make a list | 38,758,958 | <p>I want to make my list value as list.</p>
<p>example : </p>
<pre><code>abc = [1,2,3,4]
</code></pre>
<p>result : </p>
<pre><code>abc = [[1], [2], [3], [4]]
</code></pre>
<p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
| 0 | 2016-08-04T05:15:12Z | 38,759,087 | <p>With numpy, you can add a new axis:</p>
<pre><code>import numpy as np
np.array(abc)[:, np.newaxis]
Out:
array([[1],
[2],
[3],
[4]])
</code></pre>
| 1 | 2016-08-04T05:27:31Z | [
"python",
"list",
"numpy"
] |
python list value make a list | 38,758,958 | <p>I want to make my list value as list.</p>
<p>example : </p>
<pre><code>abc = [1,2,3,4]
</code></pre>
<p>result : </p>
<pre><code>abc = [[1], [2], [3], [4]]
</code></pre>
<p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
| 0 | 2016-08-04T05:15:12Z | 38,761,704 | <pre><code>import numpy as np
arr = np.array([[x] for x in abc])
</code></pre>
| 0 | 2016-08-04T08:02:12Z | [
"python",
"list",
"numpy"
] |
Expanding sys.path via __init__.py | 38,758,965 | <p>There're a lot of threads on importing modules from sibling directories, and majority recommends to either simply add <strong>init</strong>.py to source tree, or modify sys.path from inside those init files.</p>
<p>Suppose I have following project structure:</p>
<pre><code>project_root/
__init__.py
wrapper... | 0 | 2016-08-04T05:15:43Z | 38,759,254 | <p>Do not run <code>sampleX.py</code> directly, execute as module instead:</p>
<pre><code># (in project root directory)
python -m samples.sample1
</code></pre>
<p>This way you do not need to fiddle with <code>sys.path</code> at all (which is generally discouraged). It also makes it much easier to use the samples/ pac... | 1 | 2016-08-04T05:41:18Z | [
"python"
] |
What are the best ways to write a derived query to Apache SOLR core through python ? | 38,759,111 | <p>I am using solrpy to access the core and indices in the SOLR server. I wanted to build some some queries. i.e example to find all companies which have an average sales of particular product less than/ more than some amount? </p>
<p>What are the ways in which i can pass such query to solr server using python ? </p>
| 0 | 2016-08-04T05:29:47Z | 38,761,193 | <p>The documentation is always the best place to look for examples. <a href="https://cwiki.apache.org/confluence/display/solr/Using+Python" rel="nofollow">Here</a> you can find examples for simple Python and Python with JSON that is more robust.</p>
| 0 | 2016-08-04T07:35:44Z | [
"python",
"apache",
"solr"
] |
Updating metadata for gridfs file object | 38,759,131 | <p>I use GridFS as follows:</p>
<pre><code>connection = MongoClient(host='localhost')
db = connection.gridfs_example
fs = gridfs.GridFS(db)
fileId = fs.put("Contents of my file", key='s1')
</code></pre>
<p>After files are originally stored in GridFS, I have a process that computes additional metadata respective to th... | 0 | 2016-08-04T05:31:35Z | 38,760,294 | <p>GridFS stores files in two collections:
1. files collection: store files' metadata
2. chunks collection: store files' binary data</p>
<p>You can hack into the files collection. The name of the files collection is 'fs.files' where 'fs' is the default bucket name.</p>
<p>So, to update the QC result, you can do like ... | 2 | 2016-08-04T06:49:24Z | [
"python",
"mongodb",
"pymongo",
"gridfs"
] |
select doesn't work for pipe in python? | 38,759,184 | <p>When using <code>check_parent_select</code>, after the reader side is closed, exception list is not filled.</p>
<p>But using <code>check_parent_poll</code>, after the reader side is closed, it can detects the pipe disconnection.</p>
<p>Does someone know the root cause?</p>
<pre><code>#!/usr/bin/python2.7
import... | 3 | 2016-08-04T05:35:36Z | 38,761,046 | <p>It is somewhat hidden, but if you follow <a href="http://pubs.opengroup.org/onlinepubs/007908799/xsh/select.html" rel="nofollow">the documentation</a>, it becomes clearer: <code>select()</code> checks for <em>pending error conditions</em>, i.e. error conditions that make the file descriptor unusable, but only after ... | 1 | 2016-08-04T07:29:02Z | [
"python",
"linux"
] |
select doesn't work for pipe in python? | 38,759,184 | <p>When using <code>check_parent_select</code>, after the reader side is closed, exception list is not filled.</p>
<p>But using <code>check_parent_poll</code>, after the reader side is closed, it can detects the pipe disconnection.</p>
<p>Does someone know the root cause?</p>
<pre><code>#!/usr/bin/python2.7
import... | 3 | 2016-08-04T05:35:36Z | 38,761,387 | <p>A quick fix for mitigating this unexpected result is to listen for read events in the writer. A better fix would be to use pselect() and listen for SIG_PIPE as well but afaik python doesn't have a pselect()</p>
<p>I call it "unexpected" because the first thing which comes to your mind is that the closing of the rea... | 0 | 2016-08-04T07:46:05Z | [
"python",
"linux"
] |
RecursionError in Project Euler #5 | 38,759,256 | <p>I'm receiving a "maximum recursion depth exceeded" error when executing my program to solve this problem. Project Euler's <a href="https://projecteuler.net/problem=5" rel="nofollow">question #5</a> asks to find:</p>
<blockquote>
<p>The smallest positive number that is evenly divisible by all of the numbers from 1... | 0 | 2016-08-04T05:41:22Z | 38,759,317 | <p>In you defined function, you could you a loop even if you do not know math functions. However, your code is not efficient as program has to keep checking the values to see if it matches the condition. Recursion is not recommended as it should be flexible to be used with other values not just for this question. Euler... | -1 | 2016-08-04T05:46:50Z | [
"python",
"recursion"
] |
RecursionError in Project Euler #5 | 38,759,256 | <p>I'm receiving a "maximum recursion depth exceeded" error when executing my program to solve this problem. Project Euler's <a href="https://projecteuler.net/problem=5" rel="nofollow">question #5</a> asks to find:</p>
<blockquote>
<p>The smallest positive number that is evenly divisible by all of the numbers from 1... | 0 | 2016-08-04T05:41:22Z | 38,759,451 | <p>The reason for this is that Python (or CPython, at least) has a limited stack size and no tail call optimization. So you cannot use unbounded recursion in Python, unlike Scheme (for example).</p>
<p>The solution is to use a regular loop:</p>
<pre><code>x = 0
while True:
x += 1
# Put loop body here
</code>... | 4 | 2016-08-04T05:55:10Z | [
"python",
"recursion"
] |
create index based on condition in python | 38,759,357 | <p>I have data of <strong>5 weeks(35 days)</strong> with me where the <strong>start_date</strong> (1-AUG-2016) is the first date of first week and end_date( ) is the last date on the 5th week. Also i have the hourly data from (say <strong>0 - 23</strong>). </p>
<pre><code>day date(dd-mm-yyyy) hour
1 01-01-2016 ... | 1 | 2016-08-04T05:49:50Z | 38,759,645 | <p>You can do a counter that should look like this, depending on how your data is structured. I would assume that you have made a list of the hours?</p>
<pre> hours = [0,1,2,3,4,5...,23] </pre>
<p>You could make a list of what you want to find like this</p>
<pre> select = [3,4,5] //This is your selection list.</pre... | 0 | 2016-08-04T06:08:32Z | [
"python",
"loops",
"python-3.x",
"pandas"
] |
create index based on condition in python | 38,759,357 | <p>I have data of <strong>5 weeks(35 days)</strong> with me where the <strong>start_date</strong> (1-AUG-2016) is the first date of first week and end_date( ) is the last date on the 5th week. Also i have the hourly data from (say <strong>0 - 23</strong>). </p>
<pre><code>day date(dd-mm-yyyy) hour
1 01-01-2016 ... | 1 | 2016-08-04T05:49:50Z | 38,759,999 | <p>IIUC you can use:</p>
<pre><code>print (df)
day date(dd-mm-yyyy) hour
0 1 01-01-2016 0
1 1 01-01-2016 1
2 1 01-01-2016 2
3 1 01-01-2016 3
4 1 01-01-2016 4
5 1 01-01-2016 5
6 1 01-01-2016 6
7 1 01-01-2016... | 1 | 2016-08-04T06:31:55Z | [
"python",
"loops",
"python-3.x",
"pandas"
] |
Python pickle's data can't update in tkinter | 38,759,422 | <p>here's a part of my code from recent game i've try to make</p>
<p>i'm confused about the data loaded from [pickle] cannot apply to the Label in [tkinter]</p>
<p>it works when i'm saving and loading the data</p>
<pre><code>from tkinter import *
import pickle
Prvs_controll = [3,3,3,3,3]
Prvs_size = [1,1,1,1,1]
Gam... | 0 | 2016-08-04T05:53:39Z | 38,759,681 | <p>The problem is this line in the <code>load()</code> function:</p>
<pre><code>Label_size_b.configure(text = Prvs_size[0])
</code></pre>
<p>Here <code>Prvs_size</code> refers to the global variable that is initialised to <code>[1,1,1,1,1]</code> when the script starts, and is never updated. You need to access the va... | 2 | 2016-08-04T06:11:17Z | [
"python",
"tkinter",
"label",
"pickle"
] |
Efficiently find the n-ring of every node in a graph in python | 38,759,462 | <p>I have a numpy array of M edge definitions that is Mx2 and contains node indexes. For every node, I would like to find edges inside the n-ring (in my case 3-ring) of the node. I have N=250K nodes from a medium dense computational mesh for a numercial model, so I'm looking for something appropriately efficient and sp... | -3 | 2016-08-04T05:56:08Z | 38,765,016 | <pre><code>import numpy as np
import networkx as nx
G = nx.dorogovtsev_goltsev_mendes_graph(4)
edges_list = G.edges()
edges_list = np.array(edges_list)
one_ring = []
for n in G.nodes():
first = edges_list[edges_list[:, 0] == n, 1]
second = edges_list[edges_list[:, 1] == n, 0]
one_ring.append(np.hstack([firs... | 0 | 2016-08-04T10:37:05Z | [
"python",
"numpy",
"graph"
] |
converting char to list in R | 38,760,090 | <p>I wrote a python script for reading mails' content and append to list and calling this python script in R. The problem is R is considering the list as one instead of two elements in it.</p>
<p>Here is my python script:</p>
<pre><code>{
import sys
import string
import glob
def parseOutText(f):
f.seek(0)
al... | 1 | 2016-08-04T06:36:56Z | 38,760,295 | <pre><code>l = as.list(cbind(text1, text2))
</code></pre>
<p>Gives me the following output:</p>
<pre><code>[[1]]
[1] " From: xxx@xxx.com\nTo: xyz@xxx.com\nSubject: Hi\nCc: abc@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\nBcc: test@xxx.com\n\nHi,\n\nYour problem is resolved. \n\nPlease reply to this em... | 0 | 2016-08-04T06:49:25Z | [
"python",
"list",
"email"
] |
place python script in chef cookbook | 38,760,128 | <p>I have a python script which deploys ear file on a server, how do I execute this script using chef to bootstrap a linux node?</p>
<p>Tried a recipe like below, but it couldn't identify my python script which is present inside "mycookbook\files\default\deploy.py" folder of my cookbook.</p>
<pre><code>execute 'execu... | 0 | 2016-08-04T06:39:23Z | 38,760,995 | <p>Using the <code>poise-python</code> cookbook's <code>python_execute</code> resource:</p>
<pre><code>cookbook_file "/root/deploy.py" do
source "deploy.py"
end
python_execute "/root/deploy.py"
</code></pre>
<p>You could also use a normal <code>execute</code> resource if you tweak the command line. The important b... | 2 | 2016-08-04T07:26:43Z | [
"python",
"chef",
"chef-recipe"
] |
Need help understanding index_col in read_excel (pandas) | 38,760,429 | <p>I have an excel file where the first column is "ID" and the items are of the form IDXXX. </p>
<p>This code</p>
<pre><code>s = pd.read_excel('error4.xlsx', keep_default_na = False, index_col = 0)
</code></pre>
<p>Comes up with the error</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#324>... | 0 | 2016-08-04T06:56:32Z | 38,761,274 | <p>The error is coming due to the option:</p>
<pre><code>keep_default_na = False
</code></pre>
<p>According to the documentation:</p>
<pre><code>na_values : str or list-like or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values... | 0 | 2016-08-04T07:40:01Z | [
"python",
"pandas"
] |
Why template path is different and rendered content is different in mezzanine? | 38,760,510 | <p>I have two free themes in mezzanine - <code>solid & moderna</code> taken from - <a href="https://github.com/thecodinghouse/mezzanine-themes" rel="nofollow">HERE</a>.</p>
<p>I simply want to run the <code>HOST_THEMES</code> feature of <code>mezzanine</code>. So I went ahead and loaded both the themes in my <code... | 0 | 2016-08-04T07:01:30Z | 38,764,690 | <p>Hey Guys I was able to solve this by -
1. Making custom <code>Hosts</code> in <code>/etc/hosts</code></p>
<p>Made two custom hosts and bind them to my IP and voila it worked</p>
<p>I don't know why this doesn't work with <code>localhost</code> or <code>127.0.0.1</code></p>
| 0 | 2016-08-04T10:20:56Z | [
"python",
"django",
"multi-tenant",
"mezzanine",
"django-sites"
] |
imap not allowing use of gmail folders - mail.select folder other than 'inbox' | 38,760,698 | <p>Basically as stated in the title, I'm using</p>
<pre><code>mail.select("inbox")
result, data = mail.search(None, "ALL")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
</code></pre>
<p>To get the most recent email from the inbox... | 1 | 2016-08-04T07:12:09Z | 38,811,028 | <p>Add quotes around your folder name. Imaplib should do this for you, but it doesn't: <code>mail.select('"folder with space"')</code></p>
| 0 | 2016-08-07T05:01:25Z | [
"python",
"email",
"gmail",
"imap"
] |
How Apache manages HTTP request when it is python which is going to response? it is thread based or process based? | 38,760,716 | <p>What i mean is when some one makes a http request, does it like apache spawn a <strong>new process or thread</strong>.
My configuration is <code>apache + python with wsgi module</code>. </p>
| 0 | 2016-08-04T07:13:01Z | 38,760,814 | <p>Neither. Requests will be handled by the already running single thread, or a thread from a preallocated thread pool. For more information about how it works with mod_wsgi read:</p>
<ul>
<li><a href="http://modwsgi.readthedocs.io/en/develop/user-guides/processes-and-threading.html" rel="nofollow">http://modwsgi.read... | 1 | 2016-08-04T07:17:35Z | [
"python",
"multithreading",
"apache",
"process",
"wsgi"
] |
How to index a Cartesian product | 38,760,783 | <p>Suppose that the variables <code>x</code> and <code>theta</code> can take the possible values <code>[0, 1, 2]</code> and <code>[0, 1, 2, 3]</code>, respectively.</p>
<p>Let's say that in one realization, <code>x = 1</code> and <code>theta = 3</code>. The natural way to represent this is by a tuple <code>(1,3)</code... | 0 | 2016-08-04T07:16:30Z | 38,760,928 | <p>If you always store your <code>states</code> lexicographically and the possible values for <code>x</code> and <code>theta</code> are always the complete range from <code>0</code> to some maximum as your examples suggests, you can use the formula</p>
<pre><code>index = x * N_theta + theta
</code></pre>
<p>where <co... | 3 | 2016-08-04T07:23:18Z | [
"python"
] |
How to index a Cartesian product | 38,760,783 | <p>Suppose that the variables <code>x</code> and <code>theta</code> can take the possible values <code>[0, 1, 2]</code> and <code>[0, 1, 2, 3]</code>, respectively.</p>
<p>Let's say that in one realization, <code>x = 1</code> and <code>theta = 3</code>. The natural way to represent this is by a tuple <code>(1,3)</code... | 0 | 2016-08-04T07:16:30Z | 38,762,634 | <p>I think it depends on the data you have. If they are sparse, the best solution is a dictionary. And works for any tuple's dimension. <br></p>
<pre><code>import itertools
import random
n = 100
m = 100
l1 = [i for i in range(n)]
l2 = [i for i in range(m)]
a = {}
prod = [element for element in itertools.product(l1, ... | 0 | 2016-08-04T08:48:09Z | [
"python"
] |
How to index a Cartesian product | 38,760,783 | <p>Suppose that the variables <code>x</code> and <code>theta</code> can take the possible values <code>[0, 1, 2]</code> and <code>[0, 1, 2, 3]</code>, respectively.</p>
<p>Let's say that in one realization, <code>x = 1</code> and <code>theta = 3</code>. The natural way to represent this is by a tuple <code>(1,3)</code... | 0 | 2016-08-04T07:16:30Z | 38,765,852 | <p>For the sake of completeness I'll include my implementation of Julian Kniephoff's solution, <code>get_box3</code>, with a slightly adapted version of the original implementation, <code>get_box2</code>:</p>
<pre><code># 'Brute-force' method
def get_box2(p, N):
states = list(itertools.product(*[range(n) for n in ... | 0 | 2016-08-04T11:16:00Z | [
"python"
] |
How do you transpose a dask dataframe (convert columns to rows) to approach tidy data principles | 38,760,864 | <p><strong>TLDR</strong>: I created a dask dataframe from a dask bag. The dask dataframe treats every observation (event) as a column. So, instead of having rows of data for each event, I have a column for each event. The goal is to transpose the columns to rows in the same way that pandas can transpose a dataframe ... | 1 | 2016-08-04T07:19:40Z | 38,799,815 | <p>I think you can get the result you want by bypassing bag altogether, with code like</p>
<pre><code>import glob
import pandas as pd
import dask.dataframe as dd
from dask.delayed import delayed
filenames = glob.glob('sampleTwitter*.json')
dfs = [delayed(pd.read_json)(fn, 'records') for fn in filenames]
ddf = dd.fro... | 1 | 2016-08-06T01:41:54Z | [
"python",
"twitter",
"dataframe",
"transpose",
"dask"
] |
Cannot create entry | 38,760,988 | <p>Django version 1.10, python version 3.4</p>
<p>I type and execute this code in manage.py shell:</p>
<pre><code>from tweet.models import Tweet
tweet = Tweet("Parse JSON like a boss", "Admin")
tweet.save()
</code></pre>
<p>and receive message with error:</p>
<blockquote>
<p>invalid literal for int() with base 10... | 2 | 2016-08-04T07:26:22Z | 38,761,016 | <p>When you are not specifying values for all the fields in a model, you should send in the values that you do have as name value pairs.</p>
<pre><code>Tweet(text="Parse JSON like a boss", author="admin")
</code></pre>
<p>in fact, it's a best practice to do this all the time so that changes to the model in the future... | 4 | 2016-08-04T07:27:41Z | [
"python",
"django",
"sqlite"
] |
Cannot create entry | 38,760,988 | <p>Django version 1.10, python version 3.4</p>
<p>I type and execute this code in manage.py shell:</p>
<pre><code>from tweet.models import Tweet
tweet = Tweet("Parse JSON like a boss", "Admin")
tweet.save()
</code></pre>
<p>and receive message with error:</p>
<blockquote>
<p>invalid literal for int() with base 10... | 2 | 2016-08-04T07:26:22Z | 38,761,102 | <p>If you're not using kwargs, then django iterates over the args you provide in the same order that the fields are inside the internal fields dictionary (<a href="https://github.com/django/django/blob/master/django/db/models/base.py#L478" rel="nofollow">Source Code</a>),</p>
<p>What it appears to be doing is trying t... | 0 | 2016-08-04T07:31:43Z | [
"python",
"django",
"sqlite"
] |
Get source code containing all information in google feedback box? | 38,761,009 | <p>I want to parse all the text in Google feedback cards using BeautifulSoup. </p>
<p>For query "<em>define apple</em>" Google shows info card with a
<a href="http://i.stack.imgur.com/xCbTZ.png" rel="nofollow">drop down menu</a>. I want to parse all the text in <a href="http://i.stack.imgur.com/69QIH.png" rel="nofoll... | 0 | 2016-08-04T07:27:31Z | 38,764,542 | <p>You do get all the source back using <em>requests</em>, the only issue you may have is some of the output are images:</p>
<pre><code>headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36",
}
soup = BeautifulSoup(requests.get("https:/... | 0 | 2016-08-04T10:14:48Z | [
"python",
"beautifulsoup",
"python-requests"
] |
How to pass current directory as argument to a script? | 38,761,013 | <p>Is this possible in Python? I'm working on linux so I'm wondering if there is a way to combine bash commands when invoking the script (something like pwd).</p>
| 0 | 2016-08-04T07:27:35Z | 38,761,070 | <p>To get the current working directory, you can use:</p>
<pre><code>import os
os.getcwd()
</code></pre>
<p>If you want to run bash commands, @DeepSpace notes that <code>subprocess</code> is preferred to <code>os.system</code>, syntax like this:</p>
<pre><code>import subprocess
subprocess.call("pwd")
</code></pre>
... | 3 | 2016-08-04T07:30:14Z | [
"python",
"arguments"
] |
How to pass current directory as argument to a script? | 38,761,013 | <p>Is this possible in Python? I'm working on linux so I'm wondering if there is a way to combine bash commands when invoking the script (something like pwd).</p>
| 0 | 2016-08-04T07:27:35Z | 38,761,087 | <p>Yes. You can use <a href="https://docs.python.org/3.5/library/os.html#os.curdir" rel="nofollow">os.curdir</a>, combined with <a href="https://docs.python.org/3.5/library/os.path.html#os.path.abspath" rel="nofollow">os.path.abspath</a></p>
<pre><code>>>> import os
>>> os.path.abspath(os.path.curdir... | 3 | 2016-08-04T07:31:00Z | [
"python",
"arguments"
] |
boost python list get item causing error when i use operator[] | 38,761,141 | <p>i use boost 1.57 and boost python. here is my code example:</p>
<pre><code>list records = call_method<list>(...);
object attr = records.attr("__len__")();
int n = extract<long>(attr);
for (int i = 0; i < n; ++i)
{
records[i];
}//here cause error
</code></pre>
<p>in this list i have stored some t... | 3 | 2016-08-04T07:33:28Z | 38,783,690 | <p>It seems that some operator[] may cause these phenomenon, so I have to avoid it and use following solution:</p>
<pre><code>#include <boost/python/stl_iterator.hpp>
list records = call_method<list>(...);
stl_input_iterator<tuple> end;
for (stl_input_iterator<tuple> it... | 0 | 2016-08-05T07:36:51Z | [
"python",
"c++",
"list",
"boost"
] |
How to update all rows in particular column of pandas dataframe in python? | 38,761,142 | <p>I want to read a csv file and store this file in pandas data-frame, after that I want to check one column value is equal to constant variable and that equal rows should be kept in separate data-frame.</p>
<p>Next step is to update one column from the separate data-frame. In this step I'm iterating through whole dat... | 1 | 2016-08-04T07:33:29Z | 38,761,685 | <p>IIUC you can use first:</p>
<pre><code>match_df = pd_dataframe[pd_dataframe['line_no'] == int(input_line_no)].copy()
print (match_df)
line_no time
0 205 1467099122677889
1 205 1467099122677889
</code></pre>
<p>You can use <code>apply</code>, because <a href="http://pandas.pydata.org/pan... | 1 | 2016-08-04T08:01:03Z | [
"python",
"csv",
"pandas",
"indexing",
"dataframe"
] |
SSL bad Handshake Error 10054 "WSAECONNRESET" | 38,761,166 | <p><strong>Notes:</strong></p>
<pre><code>versions
Python 2.7.11 and my requests version is '2.10.0'
'OpenSSL 1.0.2d 9 Jul 2015'
Please read the below comment by Martijn Pieters before reproducing
</code></pre>
<p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20_... | 10 | 2016-08-04T07:34:30Z | 38,827,932 | <p>I use python 2.7.6 and this simple example still working on my ubuntu 14.04</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
with open('out.docx',... | 0 | 2016-08-08T11:21:36Z | [
"python",
"python-2.7",
"ssl",
"python-requests"
] |
SSL bad Handshake Error 10054 "WSAECONNRESET" | 38,761,166 | <p><strong>Notes:</strong></p>
<pre><code>versions
Python 2.7.11 and my requests version is '2.10.0'
'OpenSSL 1.0.2d 9 Jul 2015'
Please read the below comment by Martijn Pieters before reproducing
</code></pre>
<p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20_... | 10 | 2016-08-04T07:34:30Z | 38,883,759 | <p>This snippet works for me (py2.7.11 64bits + requests==2.10.0) on windows7:</p>
<pre><code>import requests
import ssl
import traceback
import shutil
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
class MyAdapter(HTTPAdapter):
def init_poolmanager(self,... | 1 | 2016-08-10T21:19:21Z | [
"python",
"python-2.7",
"ssl",
"python-requests"
] |
SSL bad Handshake Error 10054 "WSAECONNRESET" | 38,761,166 | <p><strong>Notes:</strong></p>
<pre><code>versions
Python 2.7.11 and my requests version is '2.10.0'
'OpenSSL 1.0.2d 9 Jul 2015'
Please read the below comment by Martijn Pieters before reproducing
</code></pre>
<p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20_... | 10 | 2016-08-04T07:34:30Z | 38,884,883 | <p>First of all, I confirm that the host, <code>www.neco.navy.mil</code>, is not accessible from everywhere. From some networks (geography) it works*, from others connection just hangs:</p>
<pre><code>$ curl www.neco.navy.mil
curl: (7) couldn't connect to host
$ curl https://www.neco.navy.mil
curl: (7) couldn't connec... | 4 | 2016-08-10T23:00:31Z | [
"python",
"python-2.7",
"ssl",
"python-requests"
] |
Boxplots from count table in Python | 38,761,192 | <p>I have a count table as dataframe in Python and I want to plot my distribution as a boxplot. E.g.:</p>
<pre><code>df=pandas.DataFrame.from_items([('Quality',[29,30,31,32,33,34,35,36,37,38,39,40]), ('Count', [3,38,512,2646,9523,23151,43140,69250,107597,179374,840596,38243])])
</code></pre>
<p>I 'solved' it by repea... | 2 | 2016-08-04T07:35:39Z | 38,762,768 | <p>What are you trying to look at here? The boxplot hereunder will return the following figure.</p>
<p><a href="http://i.stack.imgur.com/elcbo.png" rel="nofollow"><img src="http://i.stack.imgur.com/elcbo.png" alt="enter image description here"></a></p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
%m... | 0 | 2016-08-04T08:53:49Z | [
"python",
"python-3.x",
"pandas",
"matplotlib",
"ggplot2"
] |
I want to perform some task whenever the install button is pressed in Odoo 9 for a module | 38,761,244 | <p>I tried overriding the <code>button_install()</code> method of the model <code>ir.module.module</code></p>
<pre><code>class module(models.Model):
_inherit = 'ir.module.module'
@api.multi
def button_install(self):
raise Warning("----Cannot Install---")
</code></pre>
<p>But the above method does... | 1 | 2016-08-04T07:38:14Z | 38,761,749 | <p>On the module formular <code>button_immediate_install()</code> is used, try to override this method.</p>
| 0 | 2016-08-04T08:04:07Z | [
"python",
"openerp",
"odoo-9"
] |
Pandas - printing limited rows based on a value in one column | 38,761,357 | <p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p>
<p>For instance:</p>
<pre><code>Column1, Column2, Column3
aaa, bbb, ccc
none, ddd, ggg
</code></pre>
<p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p>
<p>Here is my code:... | 1 | 2016-08-04T07:44:07Z | 38,761,412 | <pre><code>for row in table:
if row[0] is none:
print row
</code></pre>
| 1 | 2016-08-04T07:47:14Z | [
"python",
"csv",
"pandas",
"indexing",
"dataframe"
] |
Pandas - printing limited rows based on a value in one column | 38,761,357 | <p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p>
<p>For instance:</p>
<pre><code>Column1, Column2, Column3
aaa, bbb, ccc
none, ddd, ggg
</code></pre>
<p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p>
<p>Here is my code:... | 1 | 2016-08-04T07:44:07Z | 38,761,660 | <p>You could subset the rows of the dataframe using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> to restrict rows containing <code>"none"</code> in <code>Column 1</code> as shown:</p>
<p><strong>Data Preparation</strong></p>
<pre><code>I... | 1 | 2016-08-04T07:59:35Z | [
"python",
"csv",
"pandas",
"indexing",
"dataframe"
] |
Pandas - printing limited rows based on a value in one column | 38,761,357 | <p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p>
<p>For instance:</p>
<pre><code>Column1, Column2, Column3
aaa, bbb, ccc
none, ddd, ggg
</code></pre>
<p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p>
<p>Here is my code:... | 1 | 2016-08-04T07:44:07Z | 38,761,721 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with mask:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Column2': {0: 'bbb', 1: 'ddd'},
'Column1': {0: 'aaa', 1: 'none'},
... | 1 | 2016-08-04T08:03:13Z | [
"python",
"csv",
"pandas",
"indexing",
"dataframe"
] |
Pandas - printing limited rows based on a value in one column | 38,761,357 | <p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p>
<p>For instance:</p>
<pre><code>Column1, Column2, Column3
aaa, bbb, ccc
none, ddd, ggg
</code></pre>
<p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p>
<p>Here is my code:... | 1 | 2016-08-04T07:44:07Z | 38,762,117 | <p>Here is one additional approach which first manually strips out the whitespace, and then feeds the processed file contents to pandas.</p>
<pre><code>import pandas as pd
from io import StringIO
# First strip out the whitespace
contents = open('Input.txt').read().splitlines()
contents = "\n".join([",".join([x.strip(... | 1 | 2016-08-04T08:22:59Z | [
"python",
"csv",
"pandas",
"indexing",
"dataframe"
] |
add json objects to specific index - python | 38,761,414 | <p>Today, I started with json an Python 3.x... So there are sill some problems. This is now my first important problem I have. </p>
<p>I'm looking for a fuction wich can insert (for example) this:</p>
<pre><code>{
'Current': '3A',
'Voltage': '11V'
}
</code></pre>
<p>In to here:</p>
<pre><code>{
'Measure': [
... | 0 | 2016-08-04T07:47:19Z | 38,761,499 | <p>Did you mean to something like this?</p>
<pre><code>>>> measureDict = {'Measure': []}
>>> measureDict['Measure'].append({'Current': '2A', 'Voltage': '11V'})
>>> measureDict['Measure'].append({'Current': '3A', 'Voltage': '11V'})
>>> measureDict
{'Measure': [{'Current': '2A', 'Volt... | 0 | 2016-08-04T07:52:14Z | [
"python",
"json"
] |
add json objects to specific index - python | 38,761,414 | <p>Today, I started with json an Python 3.x... So there are sill some problems. This is now my first important problem I have. </p>
<p>I'm looking for a fuction wich can insert (for example) this:</p>
<pre><code>{
'Current': '3A',
'Voltage': '11V'
}
</code></pre>
<p>In to here:</p>
<pre><code>{
'Measure': [
... | 0 | 2016-08-04T07:47:19Z | 38,762,113 | <p>My solution for your problem is to Keep the data as Python- Dictionary then do operations on it, later you can get JSON Objects.</p>
<pre><code>import json
j = {'Measure': [ {'Current': '2A', 'Voltage': '11V'}]}
d = {'Current': '3A', 'Voltage': '11V'}
j['Measure'].append(d) # as it is list use append otherwise upda... | 0 | 2016-08-04T08:22:45Z | [
"python",
"json"
] |
Markup ending without empty line. But markup is only thing in comment | 38,761,546 | <p>When documenting my python code I have a decorator to mark functions deprecated that also updates the docstring. This works fine if the function has documentation but when it doesn't sphinx complains and the documentation for <code>deprecated</code> does not look correct.</p>
<p>I have narrowed the problem down to ... | 0 | 2016-08-04T07:54:08Z | 38,762,633 | <p>jonrsharpe pointed me to the right direction with the dedent.</p>
<p>The documentation string must be exactly like this:</p>
<pre><code>def func():
"""
.. deprecated:: 0.1.0
Please use :func:`func_new`
"""
</code></pre>
<p>Two spaces in the next line, and <code>.. deprecated</code> must be alig... | 0 | 2016-08-04T08:48:09Z | [
"python",
"python-2.7",
"python-sphinx"
] |
Can`t load files for pygame project using pyqt resource system | 38,761,578 | <p>I have .qrc file:</p>
<pre><code><!DOCTYPE RCC>
<RCC version="1.0">
<qresource prefix="/data">
<file alias="key.png">resources/blocks/key.png</file>
</qresource>
</RCC>
</code></pre>
<p>I generate resources_rc.py by pyrcc5, than in my main script:</p>
<pre... | 0 | 2016-08-04T07:55:40Z | 38,763,223 | <p>The <code>:/foo/bar</code> filenames are special filenames used by Qt's (and thus PyQt's) ressource system.</p>
<p>pygame is not PyQt- you won't be able to do that outside of Qt.</p>
| 0 | 2016-08-04T09:15:12Z | [
"python",
"pyqt",
"pygame"
] |
Indexing a large 3D HDF5 dataset for subsetting based on 2D condition | 38,761,878 | <p>I have a large 3D HDF5 dataset that represents location (X,Y) and time for a certain variable. Next, I have a 2D numpy array containing a classification for the same (X,Y) location. What I would like to achieve is that I can extract all time series from the 3D HDF5 dataset that fall under a certain class in the 2D a... | 1 | 2016-08-04T08:11:07Z | 38,775,157 | <p>Advanced/fancy indexing in <code>h5py</code> is not nearly as general as with <code>np.ndarray</code>.</p>
<p>Set up a small test case:</p>
<pre><code>import h5py
f=h5py.File('test.h5','w')
dset=f.create_dataset('data',(5,3,2),dtype='i')
dset[...]=np.arange(5*3*2).reshape(5,3,2)
x=np.arange(5*3*2).reshape(5,3,2)
... | 1 | 2016-08-04T18:47:03Z | [
"python",
"arrays",
"numpy",
"indexing",
"hdf5"
] |
Tensorflow loss is diverging in my RNN | 38,762,104 | <p>I'm trying to get my hand wet with Tensorflow by solving this challenge: <a href="https://www.kaggle.com/c/integer-sequence-learning" rel="nofollow">https://www.kaggle.com/c/integer-sequence-learning</a>.</p>
<p>My work is based on these blog posts: </p>
<ul>
<li><a href="https://danijar.com/variable-sequence-leng... | 0 | 2016-08-04T08:22:09Z | 38,790,860 | <p>RNNs suffer from an exploding gradient, so you should clip the gradients for the RNN parameters. Look at this post:</p>
<p><a href="http://stackoverflow.com/questions/36498127/how-to-effectively-apply-gradient-clipping-in-tensor-flow">How to effectively apply gradient clipping in tensor flow?</a></p>
| 0 | 2016-08-05T13:46:29Z | [
"python",
"neural-network",
"tensorflow",
"sequence",
"deep-learning"
] |
Django - Single post view, Prev / Next links | 38,762,146 | <p>I have built a blog app as part of a django tutorial and I can paginate the blog list view using the code from djangoproject - <a href="https://docs.djangoproject.com/en/1.9/topics/pagination/#using-paginator-in-a-view" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/pagination/#using-paginator-in-a-view... | 0 | 2016-08-04T08:24:39Z | 38,763,229 | <p>The <code>{{ film.get_next_by_date_published }}</code> returns a <code>film</code> object. To turn it into a url, you need to access <code>film.get_next_by_date_published.slug</code>. </p>
<p>You could hardcode the url in the template</p>
<pre><code><a href="/films/{{ film.get_next_by_date_published }}">Next... | 0 | 2016-08-04T09:15:25Z | [
"python",
"django"
] |
Django dynamic inputs | 38,762,214 | <p>I'd like to create dynamic input system, for example when I enter the folder name - the list of files inside automatically show up another input ChoiceField below, so I can choose the file. The methods are already written, the problem is - How can I make it in Django view? </p>
<p>Here is my view:</p>
<pre><code>... | 0 | 2016-08-04T08:28:43Z | 38,764,905 | <p>So basically you are doing it right. You already know that you need the <code>on(change)</code> function for the <code>datepicker</code></p>
<p>Now as soon as the user changes a date, your <code>on(change)</code> function is triggered. So all you need to do now is to the get the new date value, which you already ha... | 0 | 2016-08-04T10:31:55Z | [
"python",
"django",
"django-templates",
"django-views",
"python-3.5"
] |
How to show buttons text in a calculator screen | 38,762,227 | <p>I've made a simple calculator with buttons like 1, 2 ,3 and so on..but i am unable to put those button text like 1 or 2 etc onto the calculator screen.
It would be very helpful if you guys give me some hints..</p>
<pre><code>from tkinter import *
root = Tk()
buttons = '1', '2', '3', '4', '5', '6', '7', '8', '9', '0... | -2 | 2016-08-04T08:29:08Z | 38,762,992 | <p>There are couple problems in here. </p>
<p>1) Variable <code>button</code> is used for two different purposes which makes one of them override the other. You need to rename one of them. </p>
<p>2) When <a href="http://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda">using l... | 0 | 2016-08-04T09:04:07Z | [
"python",
"tkinter"
] |
Django not responding to ajax autocomplete | 38,762,247 | <p>I searched for term "bi" which should return a username with initial "bi..."
but nothing is displayed, No dropdown Here are my codes.</p>
<p><strong>search.html</strong></p>
<pre><code><html>
<div class="ui-widget">
<label for="search4">search4: </label>
<input id="search4">
</... | 0 | 2016-08-04T08:29:55Z | 38,764,239 | <p>Okay so technically you are doing it all wrong.</p>
<p>The <code>source</code> attribute of <code>autocomplete</code> requires an array of strings or data that you want to provide the user as autocomplete options in an input field.</p>
<p>Now what you are trying to do is to simply give the <code>url</code> corresp... | 0 | 2016-08-04T10:01:16Z | [
"javascript",
"jquery",
"python",
"ajax",
"django"
] |
Pandas column name of the max cell value | 38,762,290 | <p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p>
<p>df1:</p>
<pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \
0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065
1 222 0.000000 0.00... | 2 | 2016-08-04T08:32:03Z | 38,762,426 | <p>You can use <code>argmax</code> on the row to return the column name with the largest value for the 2nd column if you temporarily replace <code>0</code> with <code>NaN</code> then you can use <code>last_valid_index</code> to return the column with the last non-zero value:</p>
<pre><code>In [117]:
df['max_tp'], df['... | 2 | 2016-08-04T08:39:05Z | [
"python",
"pandas",
"dataframe",
"max",
"cumsum"
] |
Pandas column name of the max cell value | 38,762,290 | <p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p>
<p>df1:</p>
<pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \
0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065
1 222 0.000000 0.00... | 2 | 2016-08-04T08:32:03Z | 38,762,500 | <p>Faster is use:</p>
<pre><code>print (df.ix[:,'tp1':].idxmax(axis=1))
0 tp4
1 tp10
2 tp2
3 tp3
4 tp1
5 tp8
dtype: object
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>df = pd.concat([df]*1000).reset_index(drop=True)
In [128]: %timeit (df.ix[:,'tp1':].idxmax(axis=1))
100 loops, b... | 1 | 2016-08-04T08:42:14Z | [
"python",
"pandas",
"dataframe",
"max",
"cumsum"
] |
Pandas column name of the max cell value | 38,762,290 | <p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p>
<p>df1:</p>
<pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \
0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065
1 222 0.000000 0.00... | 2 | 2016-08-04T08:32:03Z | 38,762,508 | <p>Knowing that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html">idxmax</a> returns the index of the <em>first</em> maximum, you can use cumsum to find the column after which there are only zeros:</p>
<pre><code>df.ix[:, 'tp1':].cumsum(axis=1).idxmax(axis=1)
Out[61]:
0 ... | 5 | 2016-08-04T08:42:47Z | [
"python",
"pandas",
"dataframe",
"max",
"cumsum"
] |
Need program to keep restarting itself after a certain amount of time | 38,762,405 | <p>I need this program to restart after15 minutes and repeat its process over again. I need it to be on a timer so example it starts ever 15 minutes dynamically without any user imput it will just reset and start over and restart in the Python shell.</p>
<pre><code>from twython import Twython, TwythonError
import time... | 1 | 2016-08-04T08:38:08Z | 38,767,091 | <p>Unless you have very specific requirements, it is always better to put the logic of restarting the script outside the script itself:</p>
<ul>
<li>the script is simpler to write and test (one functionality less)</li>
<li>if (for any reason including program bugs) the script crashes it will be automatically restarte... | 0 | 2016-08-04T12:16:02Z | [
"python",
"loops",
"time"
] |
Convert possibly incorrect time to seconds | 38,762,515 | <p>Having such string <code>12:65:84</code> and told that it represents time in <code>h:m:s</code> AND
values there can be not correct, e.g. <code>65</code> minutes that should be translated to <code>1</code> hour and <code>5</code> minutes</p>
<p>I need to reduce these numbers to total amount of seconds.</p>
<p>Naiv... | 0 | 2016-08-04T08:43:06Z | 38,766,451 | <p>You can also use <code>timedelta</code> for the same as:</p>
<pre><code>s='12:65:84'
h,m,s=[int(i) for i in s.split(':')]
t=timedelta(hours=h, seconds=s, minutes=m)
res=t.total_seconds()
</code></pre>
| 1 | 2016-08-04T11:44:53Z | [
"python",
"time"
] |
How to get dict of lists from relationship in sqlalchemy? | 38,762,607 | <p>I've found out that you can use collections in relationship in order to change the type of return value, specifically I was interested in dictionaries.
Documentation gives an example:</p>
<pre><code>class Item(Base):
__tablename__ = 'item'
id = Column(Integer, primary_key=True)
notes = relationship("Not... | 1 | 2016-08-04T08:47:09Z | 38,767,424 | <p>So, it turns out you can simply inherit MappedCollection and do whatever you like in <strong>setitem</strong> there.</p>
<pre><code>from sqlalchemy.orm.collections import (MappedCollection,
_SerializableAttrGetter,
collection,
... | 0 | 2016-08-04T12:31:19Z | [
"python",
"dictionary",
"sqlalchemy",
"relationships"
] |
MAC : bash script which invokes a Python script , both these scripts are in the same directory | 38,762,615 | <p>I have written a bash script in MAC , which is placed in a directory say xyz.
Now i have a python file in the same directory xyz</p>
<p>We can also say that this python script will always be in the directory where this bash script is</p>
<p>So i want this bash script to be general</p>
<p>/Library/Frameworks/Pytho... | 1 | 2016-08-04T08:47:26Z | 38,762,671 | <p>In a Bash script, the path to the script is stored in the <code>$0</code> variable.</p>
<p>The <code>dirname</code> command returns the directory portion of a path (filename removed).</p>
<p>You can use the <code>dirname</code> with <code>$0</code> to get the script's base directory, and <code>cd</code> to that pa... | 0 | 2016-08-04T08:49:26Z | [
"python",
"bash",
"osx",
"shell"
] |
Extracting numbers in text file | 38,762,783 | <p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p>
<p>I want to take only five digits after <code>#ACA</code> in a text file.</p>
<p>my text is like:</p>
<pre><code>ERROR_MESSAGE
(((#ACA16018)|(#ACA16019))&(#AQV71767='')&(#AQV71765='2'))?1:((#AQV7... | 2 | 2016-08-04T08:54:39Z | 38,762,837 | <p>This should do it </p>
<pre><code>import re
print(re.findall("#ACA(\d+)",str_var))
</code></pre>
<p>If you have the whole text in the variable <code>str_var</code></p>
<p>Output: </p>
<pre><code>['16018', '16019', '17660', '16560', '15623', '17804', '17602', '17604', '56169', '17606', '17608', '18635']
</cod... | 2 | 2016-08-04T08:56:49Z | [
"python",
"bash",
"powershell",
"text",
"extract"
] |
Extracting numbers in text file | 38,762,783 | <p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p>
<p>I want to take only five digits after <code>#ACA</code> in a text file.</p>
<p>my text is like:</p>
<pre><code>ERROR_MESSAGE
(((#ACA16018)|(#ACA16019))&(#AQV71767='')&(#AQV71765='2'))?1:((#AQV7... | 2 | 2016-08-04T08:54:39Z | 38,762,858 | <p><code>re.findall(r'#ACA(\d{5})', str_var)</code></p>
| 2 | 2016-08-04T08:57:55Z | [
"python",
"bash",
"powershell",
"text",
"extract"
] |
Extracting numbers in text file | 38,762,783 | <p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p>
<p>I want to take only five digits after <code>#ACA</code> in a text file.</p>
<p>my text is like:</p>
<pre><code>ERROR_MESSAGE
(((#ACA16018)|(#ACA16019))&(#AQV71767='')&(#AQV71765='2'))?1:((#AQV7... | 2 | 2016-08-04T08:54:39Z | 38,762,874 | <p>PowerShell solution:</p>
<pre><code>$contet = Get-Content -Raw 'your_file'
$match = [regex]::Matches($contet, '#ACA(\d{5})')
$match | ForEach-Object {
$_.Groups[1].Value
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>16018
16019
17660
16560
15623
17804
17602
17604
56169
17606
17608
18635
</code></... | 1 | 2016-08-04T08:58:41Z | [
"python",
"bash",
"powershell",
"text",
"extract"
] |
Extracting numbers in text file | 38,762,783 | <p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p>
<p>I want to take only five digits after <code>#ACA</code> in a text file.</p>
<p>my text is like:</p>
<pre><code>ERROR_MESSAGE
(((#ACA16018)|(#ACA16019))&(#AQV71767='')&(#AQV71765='2'))?1:((#AQV7... | 2 | 2016-08-04T08:54:39Z | 38,762,878 | <p><code>[x[:5] for x in content.split("#ACA")[1:]]</code></p>
| 2 | 2016-08-04T08:59:00Z | [
"python",
"bash",
"powershell",
"text",
"extract"
] |
Extracting numbers in text file | 38,762,783 | <p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p>
<p>I want to take only five digits after <code>#ACA</code> in a text file.</p>
<p>my text is like:</p>
<pre><code>ERROR_MESSAGE
(((#ACA16018)|(#ACA16019))&(#AQV71767='')&(#AQV71765='2'))?1:((#AQV7... | 2 | 2016-08-04T08:54:39Z | 38,762,904 | <pre><code>grep -oP '#ACA\K[0-9]{5}' file.txt
</code></pre>
<ul>
<li><code>#ACA\K</code> will match <code>#ACA</code> but not printed as part of output</li>
<li><code>[0-9]{5}</code> five digits following <code>#ACA</code></li>
</ul>
<p>If variable number of digits are needed, use</p>
<pre><code>grep -oP '#ACA\K[0-9... | 4 | 2016-08-04T08:59:55Z | [
"python",
"bash",
"powershell",
"text",
"extract"
] |
Extracting numbers in text file | 38,762,783 | <p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p>
<p>I want to take only five digits after <code>#ACA</code> in a text file.</p>
<p>my text is like:</p>
<pre><code>ERROR_MESSAGE
(((#ACA16018)|(#ACA16019))&(#AQV71767='')&(#AQV71765='2'))?1:((#AQV7... | 2 | 2016-08-04T08:54:39Z | 38,762,905 | <p>If you don't know or don't like regular expressions, you can do this, although the code is a bit longer :</p>
<pre><code>if __name__ == '__main__':
pattern = '#ACA'
filename = 'yourfile.txt'
res = list()
with open(filename, 'rb') as f: # open 'yourfile.txt' in byte-reading mode
for line in ... | 3 | 2016-08-04T08:59:58Z | [
"python",
"bash",
"powershell",
"text",
"extract"
] |
Trace Function Calls in Python | 38,762,815 | <p>I need to trace Function Calls based on called functions from a root file
It should show the function call sequence without including system functions
What is the best approach for this problem
What I have tried so far
Using AST to get function calls on root page and then opening all imports file and searching for... | 0 | 2016-08-04T08:55:50Z | 38,846,913 | <p>You can set use the trace function with sys.settrace(). In principle, you can it on every line of your code, but it also helps you to check the function calls. Look at this link for examples.
<a href="http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html" rel="nofollow">http://w... | 0 | 2016-08-09T09:27:43Z | [
"python",
"python-2.7",
"stack-trace",
"abstract-syntax-tree",
"trace"
] |
get a certain request url during Loading a web page | 38,762,836 | <p>During Loading <a href="http://www.le.com/ptv/vplay/1417484.html" rel="nofollow">this web page</a> , the browser makes many requests,
<a href="http://i.stack.imgur.com/shSOu.png" rel="nofollow"><img src="http://i.stack.imgur.com/shSOu.png" alt="enter image description here"></a>
now I need a certain request url (e.... | 1 | 2016-08-04T08:56:48Z | 38,772,763 | <p>Scrapy doesn't handle requests while the page is being processed, you either know specifically the url you want and directly request it </p>
<p>or</p>
<p>You have to use something like <a href="https://github.com/scrapy-plugins/scrapy-splash" rel="nofollow">scrapy-splash</a> which can return a <code>HAR</code> fil... | 0 | 2016-08-04T16:27:34Z | [
"python",
"qt",
"browser",
"web-scraping",
"scrapy"
] |
Python - dig ANY equivalent with scapy module | 38,762,870 | <p>I want to use the python module scapy to perform an equivalent command of</p>
<pre><code>dig ANY google.com @8.8.4.4 +notcp
</code></pre>
<p>I've made a simple example code:</p>
<pre><code>from scapy.all import *
a = sr(IP(dst="8.8.4.4")/UDP(sport=RandShort(),dport=53)/DNS(qd=DNSQR(qname="google.com",qtype="ALL"... | 1 | 2016-08-04T08:58:31Z | 38,780,922 | <p>Got the Python code working with scapy..</p>
<pre><code>srp(Ether()/IP(src="192.168.1.101",dst="8.8.8.8")/UDP(sport=RandShort(),dport=53)/DNS(rd=1,qd=DNSQR(qname="google.com",qtype="ALL",qclass="IN"),ar=DNSRROPT(rclass=3000)),timeout=1,verbose=0)
</code></pre>
<p>In Wireshark we can see now a correct response:
<a ... | 0 | 2016-08-05T04:04:33Z | [
"python",
"dns",
"scapy",
"any",
"dig"
] |
parsing python file with re | 38,762,928 | <p>I have a python file as </p>
<pre><code>test.py
import os
class test():
def __init__(self):
pass
def add(num1, num2):
return num1+num2
</code></pre>
<p>I am reading this file in a string as :</p>
<pre><code>with open('test.py', 'r') as myfile:
data=myfile.read()
print data
</code>... | 1 | 2016-08-04T09:01:20Z | 38,763,134 | <p>So if you need to find all <code>def</code> and <code>class</code> lines it is much easier to avoid regex. </p>
<p>You read the whole content of the file here </p>
<pre><code>with open('test.py', 'r') as myfile:
data=myfile.read()
print data
</code></pre>
<p>Why don't you just find the answer right there?</p... | 2 | 2016-08-04T09:10:57Z | [
"python",
"regex"
] |
parsing python file with re | 38,762,928 | <p>I have a python file as </p>
<pre><code>test.py
import os
class test():
def __init__(self):
pass
def add(num1, num2):
return num1+num2
</code></pre>
<p>I am reading this file in a string as :</p>
<pre><code>with open('test.py', 'r') as myfile:
data=myfile.read()
print data
</code>... | 1 | 2016-08-04T09:01:20Z | 38,763,306 | <pre><code>with open('test.py', 'r') as myfile:
data=myfile.read().split('\n')
for line in data:
if re.search("(\s+)?class ", line) or re.search("^\s+def ", line):
print line
</code></pre>
| 1 | 2016-08-04T09:18:56Z | [
"python",
"regex"
] |
parsing python file with re | 38,762,928 | <p>I have a python file as </p>
<pre><code>test.py
import os
class test():
def __init__(self):
pass
def add(num1, num2):
return num1+num2
</code></pre>
<p>I am reading this file in a string as :</p>
<pre><code>with open('test.py', 'r') as myfile:
data=myfile.read()
print data
</code>... | 1 | 2016-08-04T09:01:20Z | 38,763,506 | <p>If you want to follow a regex approach, use</p>
<pre><code>re.findall(r'(?m)^[ \t]*((?:class|def)[ \t].*)', data)
</code></pre>
<p>or</p>
<pre><code>re.findall(r'^[ \t]*((?:class|def)[ \t].*)', data, flags=re.M)
</code></pre>
<p>See <a href="https://regex101.com/r/xY8qU4/2" rel="nofollow">regex demo</a></p>
<p>... | 2 | 2016-08-04T09:27:29Z | [
"python",
"regex"
] |
Function which take as input variable result from other function | 38,762,933 | <p>As I'm new in python coding, I stuck on defining a function which take as input variable from other function. Generally my code is : </p>
<pre><code>#!/usr/bin/python
import configparser
import re
var="abc"
class Config:
def getSources(var):
config = configparser.ConfigParser()
config.read("C\\... | -4 | 2016-08-04T09:01:31Z | 38,763,109 | <p>You need to return the value or raise an exception:</p>
<pre>
<code>
if source in connection_source:
return (connection_connectstr)
else:
raise configparser.NoSectionError('Something wrong')
</code>
</pre>
| 0 | 2016-08-04T09:09:48Z | [
"python",
"function"
] |
Write dictionary to csv with one line per value | 38,762,960 | <p>I am quite new to Python so please excuse me if this is a really basic question. I have a Python dictionary such as this one:</p>
<p><code>foo = {'bar1':['a','b','c'], 'bar2':['d','e']}</code></p>
<p>I would like to write it to a csv file, with one line per <strong>value</strong> and the key as first element of ea... | 0 | 2016-08-04T09:02:49Z | 38,763,027 | <p>This is because <code>[key, value]</code> contains multiple "values" within <code>value</code>. Try iterating over this like this:</p>
<pre><code>for key, values in foo.items()
for value in values:
writer.writerow([key, value])
</code></pre>
| 5 | 2016-08-04T09:05:33Z | [
"python",
"file",
"csv",
"dictionary",
"key"
] |
how to use spacy lemmatizer to get a word into basic form | 38,763,007 | <p>I am new to know spacy and I want to use his lemmatizer founction, but I don't know how to use it, like I into strings of word, which will return the string which have the basic form the words. like 'words'=> word, 'did' => 'do',
thank you.</p>
| 0 | 2016-08-04T09:04:54Z | 38,770,601 | <p><strong>Code :</strong> </p>
<pre><code>import os
from spacy.en import English, LOCAL_DATA_DIR
data_dir = os.environ.get('SPACY_DATA', LOCAL_DATA_DIR)
nlp = English(data_dir=data_dir)
doc3 = nlp(u"this is spacy lemmatize testing. programming books are more better than others")
for token in doc3:
print token... | 1 | 2016-08-04T14:46:18Z | [
"python",
"nltk",
"spacy"
] |
DjangoCMS NavigationNode - custom node | 38,763,038 | <p>The default NavigationNode in <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/menus.html?highlight=navigationnode" rel="nofollow">DjangoCMS</a> has nodes as: </p>
<ul>
<li>children</li>
<li>title</li>
<li>get_menu_title</li>
<li>get_attribute</li>
<li>etc.</li>
</ul>
<p>In the same context, I want to a... | 0 | 2016-08-04T09:06:03Z | 38,764,377 | <p>I finally found the solution. The answer is: Yes! It is possible. </p>
<p>As it states in the documentation, you can use <strong>modify()</strong> method.</p>
<p>But it did not work for me, because I got confused with <code>node.attr["changed_by"]</code> . In templates, I wanted to use something like this: <code>... | 0 | 2016-08-04T10:07:26Z | [
"python",
"django",
"django-cms"
] |
Python TCP Sockets: How to know if a specific connection has sent information | 38,763,044 | <p>I have a multi-threaded Python 3 application that on thread #1 accepts TCP socket communications. Thread #2 will check all current connections if they have anything to receive, then act accordingly.</p>
<p>So, currently I have a list called <code>all_connections</code> which is a list of accepted socket connection ... | 1 | 2016-08-04T09:06:23Z | 38,763,586 | <p>Yes, <code>read()</code> will block; this is the default behaviour. Calling <code>socket.setblocking(1)</code> actually enables blocking, which is opposite of what you wanted. <code>setblocking(False)</code> will set non-blocking mode. I/O on non-blocking sockets requires that you use exception handling.</p>
<p>A b... | 2 | 2016-08-04T09:30:51Z | [
"python",
"multithreading",
"sockets",
"tcp"
] |
Is it safe to delete these python files from /usr/bin? | 38,763,495 | <p><a href="http://i.stack.imgur.com/rmvb0.png" rel="nofollow"><img src="http://i.stack.imgur.com/rmvb0.png" alt="enter image description here"></a></p>
<p>I've installed python 2x and 3x with <strong>Homebrew</strong> at <code>/usr/local/Cellar/</code>, and again with <strong>pydev</strong> at <code>~/.pyenv</code> f... | 0 | 2016-08-04T09:27:06Z | 38,764,069 | <p>don't delete files on /usr/bin, if you want to remove some python, like python2: <code>brew uninstall python2</code>.</p>
<p>The <code>pyenv</code> is a very good tool. I'm use it betw on py2 or py3 very well.
And there is another good tool for python devï¼<code>virtualenv</code></p>
| 1 | 2016-08-04T09:52:52Z | [
"python",
"osx",
"pycharm",
"homebrew",
"pyenv"
] |
python edge detector - mask the area were it's completly black | 38,763,530 | <p>I have used canny edge detector on an image.
It detected some areas in the image and other areas it displays nothing.
Now, I want that on the original image it would mask the areas that were completely black.
How can I do it?</p>
<p>I am using python and skimage or opencv (doesn't matter which one)</p>
<pre><code>... | -2 | 2016-08-04T09:28:42Z | 38,768,036 | <p>You can simply apply a binary mask on a RGB image using:</p>
<pre><code>close_BGR = cv2.cvtColor(close, cv2.COLOR_GRAY2BGR)
# Assuming that the img is of RGB format
masked_image = cv2.min(close_BGR, img)
</code></pre>
| 1 | 2016-08-04T12:58:25Z | [
"python",
"opencv",
"image-processing",
"skimage"
] |
importing modules in application, not package | 38,763,557 | <p>I am writing a Python (Python3) application (not a package) and have some doubts about the correct directory structure. At the moment I have this:</p>
<pre><code>myapp/
__init__.py
launch.py
core/
__init__.py
some_core_class.py
other_core_class.py
gui/
__init__.py
... | 1 | 2016-08-04T09:30:00Z | 38,764,049 | <p>I have just found, I can solve it by prepending </p>
<pre><code>import os
import sys
app_parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(app_parent_dir)
</code></pre>
<p>at the very beginning of my <code>launch.py</code>. But this is so ugly and feels like a hack. There mus... | 0 | 2016-08-04T09:51:46Z | [
"python",
"python-3.x"
] |
How to handle errors in Mercurial extension | 38,763,626 | <p>What is the recommended approach to handling errors in a Mercurial extension? We could not find any docs for this aspect online.</p>
<p>The following example will print <code>Hello world</code> and set <code>errorlevel</code> to <code>1</code> in a Windows shell. </p>
<pre><code>@command('print-parents', [('','', ... | 0 | 2016-08-04T09:33:07Z | 38,763,724 | <p>In a <code>@command</code> function, use <code>ui.warn()</code> to display an error message, then return an <em>integer</em> value to set the exit code:</p>
<pre><code>if something_is_wrong:
ui.warn(_('Something is wrong, please correct this'))
return 1
</code></pre>
<p>However, using <code>raise mercurial... | 0 | 2016-08-04T09:37:28Z | [
"python",
"mercurial",
"mercurial-extension"
] |
Quarter out of datetime64 | 38,763,766 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>In [119]: df1
Out[119]:
DATES
0 2014-01-01
1 2014-01-24
2 2014-03-11
3 2014-04-09
4 2014-04-21
5 2014-05-02
6 2014-05-13
7 2014-06-11
8 2014-06-21
9 2014-07-22
10 2014-08-04
In [120]: df1.dtypes
Out[120]:
DATES datetime6... | 1 | 2016-08-04T09:39:11Z | 38,763,795 | <p>you can do using <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow">dt</a> accessor :</p>
<pre><code>df1['QUARTER'] = df1['DATES'].dt.quarter
</code></pre>
| 1 | 2016-08-04T09:40:39Z | [
"python",
"pandas"
] |
Quarter out of datetime64 | 38,763,766 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>In [119]: df1
Out[119]:
DATES
0 2014-01-01
1 2014-01-24
2 2014-03-11
3 2014-04-09
4 2014-04-21
5 2014-05-02
6 2014-05-13
7 2014-06-11
8 2014-06-21
9 2014-07-22
10 2014-08-04
In [120]: df1.dtypes
Out[120]:
DATES datetime6... | 1 | 2016-08-04T09:39:11Z | 38,763,872 | <pre><code>In [30]: df['QUARTER'] = pd.PeriodIndex(df['DATES'], freq='Q')
In [31]: df
Out[31]:
DATES QUARTER
0 2014-01-01 2014Q1
1 2014-01-24 2014Q1
2 2014-03-11 2014Q1
3 2014-04-09 2014Q2
4 2014-04-21 2014Q2
5 2014-05-02 2014Q2
6 2014-05-13 2014Q2
7 2014-06-11 2014Q2
8 2014-06-21 2014Q2
9 ... | 3 | 2016-08-04T09:43:12Z | [
"python",
"pandas"
] |
How do I remove double back slash from a bytes object? | 38,763,771 | <p>For example,
t = str.encode(msg)</p>
<p>print(t)
I am getting the double slashes.</p>
<p>b'\\xda\\xad\\x94\\xb4\\x0bg\\x92]R\\x9a1y\\x9d\\xed\\x04\\xd5\\x8e+\\x07\\xf8\\x03\\x1bm\\xd6\\x96\\x10\\xca80\\xe26\\x8a</p>
<p>I would like to get the result as</p>
<p>b'\xda\xad\x94\xb4\x0bg\x92]R\x9a1y\x9d\xed\x04\xd5\... | 0 | 2016-08-04T09:39:22Z | 38,764,466 | <p>You can't do that because
'\\'
represent a slash, not a double slash.
For example, if you will convert the msg to a string and use the print function to print the msg, you will see only one slash.</p>
| 0 | 2016-08-04T10:11:32Z | [
"python",
"byte",
"backslash"
] |
How do I remove double back slash from a bytes object? | 38,763,771 | <p>For example,
t = str.encode(msg)</p>
<p>print(t)
I am getting the double slashes.</p>
<p>b'\\xda\\xad\\x94\\xb4\\x0bg\\x92]R\\x9a1y\\x9d\\xed\\x04\\xd5\\x8e+\\x07\\xf8\\x03\\x1bm\\xd6\\x96\\x10\\xca80\\xe26\\x8a</p>
<p>I would like to get the result as</p>
<p>b'\xda\xad\x94\xb4\x0bg\x92]R\x9a1y\x9d\xed\x04\xd5\... | 0 | 2016-08-04T09:39:22Z | 38,765,098 | <p>I wanted to place this as a comment to Adrian Gherasims answer, but it got too long so I put it as a separate "answer". </p>
<p>For normal symbols you can use the <code>replace</code>-function</p>
<pre><code>In [1]: temp = 'aa1aa2aa3aa4aa5'
In [2]: temp
Out[2]: 'aa1aa2aa3aa4aa5'
In [3]: temp.replace('aa', 'a')
Out... | 0 | 2016-08-04T10:41:14Z | [
"python",
"byte",
"backslash"
] |
Overriding the division operator when lambdifying symbolic expressions in sympy | 38,763,772 | <p>I'm using Sympy to evaluate symbolic expressions provided by users, but the division operator isn't behaving like any other mathematical operator. When evaluating an expression on objects with overridden operators, I get the expected result for addition, subtraction, and multiplication, but not division. The code be... | 2 | 2016-08-04T09:39:23Z | 38,766,026 | <p>Your cause is certainly not completely hopeless. Here are a few options to get you started.</p>
<p>First off, it seems as if you understand the difference between __div__ __truediv__ and __floordiv__ but if you didn't already, <a href="https://docs.python.org/2/library/operator.html" rel="nofollow">here</a> is some... | -1 | 2016-08-04T11:23:22Z | [
"python",
"sympy",
"symbolic-math"
] |
Is it common to write a lot of code under if __name__ == '__main__': statement | 38,763,775 | <p>my current coding style is like </p>
<pre><code>import xxx
def fun1()
def fun2()
...
if __name__ == '__main__':
task = sys.argv[1]
if task =='task1':
do task1
elif task == 'task2':
do task2
...
</code></pre>
<p>my problem is that the part of the code under </p>
<pre><code>if __... | 2 | 2016-08-04T09:39:40Z | 38,763,865 | <p>Like BusyAnt said, the common way to do it is </p>
<pre><code>import xxx
def fun1()
def fun2()
...
def main():
task = sys.argv[1]
if task =='task1':
do task1
elif task == 'task2':
do task2
...
if __name__ == '__main__':
main()
</code></pre>
<p>The upside of this is it does ... | 3 | 2016-08-04T09:42:59Z | [
"python"
] |
Is it common to write a lot of code under if __name__ == '__main__': statement | 38,763,775 | <p>my current coding style is like </p>
<pre><code>import xxx
def fun1()
def fun2()
...
if __name__ == '__main__':
task = sys.argv[1]
if task =='task1':
do task1
elif task == 'task2':
do task2
...
</code></pre>
<p>my problem is that the part of the code under </p>
<pre><code>if __... | 2 | 2016-08-04T09:39:40Z | 38,763,909 | <p><strong>It is not forbidden</strong> to write a lot of things under <code>if __name__ == '__main__'</code>, though it is considered better and more readable to <strong>wrap everything up in a <code>main()</code> function</strong>. This way, the code in <code>main()</code> isn't executed when you <code>import</code> ... | 3 | 2016-08-04T09:44:55Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.