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 |
|---|---|---|---|---|---|---|---|---|---|
Adding paths to arguments in popen | 40,128,783 | <p>I want to execute a Linux command through Python. This works in the terminal:</p>
<p><code>/usr/bin/myprogram --path "/home/myuser"</code></p>
<p>I've tried this:</p>
<pre><code>path = "/home/myuser"
args = ['/usr/bin/myprogram', '--path ' + path]
proc = subprocess.Popen(args)
</code></pre>
<p>And this:</p>
<pr... | 0 | 2016-10-19T10:29:53Z | 40,128,949 | <p>Here's something to try:</p>
<pre><code>import subprocess
import shlex
p = subprocess.Popen(shlex.split("/usr/bin/myprogram --path /home/myuser")
</code></pre>
<p>Mind the forward slashes ("/"). From what I read, Python doesn't like backslashes ("\") even when running on Windows (I've never used it on Windows mys... | 0 | 2016-10-19T10:35:41Z | [
"python",
"linux",
"python-2.7"
] |
Adding paths to arguments in popen | 40,128,783 | <p>I want to execute a Linux command through Python. This works in the terminal:</p>
<p><code>/usr/bin/myprogram --path "/home/myuser"</code></p>
<p>I've tried this:</p>
<pre><code>path = "/home/myuser"
args = ['/usr/bin/myprogram', '--path ' + path]
proc = subprocess.Popen(args)
</code></pre>
<p>And this:</p>
<pr... | 0 | 2016-10-19T10:29:53Z | 40,129,140 | <p>The problem comes from your string literal, <code>'\usr\bin\myprogram'</code>. According to <a href="https://docs.python.org/2.0/ref/strings.html" rel="nofollow">escaping rules</a>, <code>\b</code> is replaced by <code>\x08</code>, so your executable is not found.</p>
<p>Pun an <code>r</code> in front of your strin... | -1 | 2016-10-19T10:43:30Z | [
"python",
"linux",
"python-2.7"
] |
Cannot anchor to an item that isn't a parent or sibling QML QtQuick | 40,128,852 | <p>I'm working on a python desktop app.</p>
<p>And currently have this in my QML file.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> SplitView {
anchors.... | 1 | 2016-10-19T10:32:18Z | 40,129,883 | <pre><code>SplitView {
anchors.fill: parent
orientation: Qt.Horizontal
Rectangle {
color: "#272822"
id: cameraRectangle
width: window.width / 2
Item {
//more stuff
}
Item {
// The parent of this Item is 'cameraRectangle'
// T... | 1 | 2016-10-19T11:14:19Z | [
"python",
"qt",
"pyqt",
"qml",
"qtquick2"
] |
Where to find the source code for pandas DataFrame __add__ | 40,128,884 | <p>I am trying to understand what (how) happens when two <code>pandas.DataFrame</code>s are added/subtracted.</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame([[1,2], [3,4]])
df2 = pd.DataFrame([[11,12], [13,14]])
df1 + df2 # Which function is called?
</code></pre>
<p>My understanding is <code>__add__</code... | 0 | 2016-10-19T10:33:39Z | 40,129,565 | <p>I think you need check <a href="https://github.com/pandas-dev/pandas/blob/master/pandas/core/ops.py#L166" rel="nofollow">this</a>:</p>
<pre><code>def add_special_arithmetic_methods(cls, arith_method=None,
comp_method=None, bool_method=None,
use_n... | 0 | 2016-10-19T11:01:15Z | [
"python",
"pandas"
] |
Numpy conversion of column values in to row values | 40,128,895 | <p>I take 3 values of a column (third) and put these values into a row on 3 new columns. And merge the new and old columns into a new matrix A</p>
<p>Input timeseries in col nr3 values in col nr 1 and 2</p>
<pre><code>[x x 1]
[x x 2]
[x x 3]
</code></pre>
<p>output : matrix A</p>
<pre><code>[x x 1 0 0 0]
[x x 2 0 0... | 3 | 2016-10-19T10:34:04Z | 40,129,109 | <p>Here's an approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> to get those sliding windowed elements and then just some stacking to get <code>A</code> -</p>
<pre><code>col2 = matrix[:,2]
nrows = col2.size-nr+1
out = np.zeros((nr-1+nrow... | 2 | 2016-10-19T10:42:16Z | [
"python",
"performance",
"numpy",
"matrix"
] |
Finding holes in a binary image | 40,128,985 | <p>Assume we have following binary image</p>
<pre><code>0010
0101
0101
0010
0100
1010
0100
0000
</code></pre>
<p>0 represents background pixels and 1 represents image pixels.As you can see there are two holes in this image.Is there a way to obtain the number of holes in this image using algorithms?(Java or Python but... | -3 | 2016-10-19T10:37:14Z | 40,130,348 | <p>Here is some idea presented as code (and it might be not what you need).</p>
<p>The problem is, that i don't understand your example. Depending on the neighborhood-definition, there are different results possible.</p>
<ul>
<li>If you have a 8-neighborhood, all zeros are connected somehow (what does that mean about... | 2 | 2016-10-19T11:36:36Z | [
"java",
"python",
"algorithm",
"binary-image"
] |
argparse: Emulating GCC's "-fno-<option>" semantics | 40,129,203 | <p>One nice feature of GCC's command line parsing is that most flags of the form "-fmy-option" have a negative version called "-fno-my-option". The rightmost occurrence takes precedence, so you can just append "-fno-my-option" to your CFLAGS or similar in a Makefile to disable an option without clobbering the other fla... | 0 | 2016-10-19T10:46:27Z | 40,136,954 | <p>Without any fancy foot work I can setup a pair of arguments that write to the same <code>dest</code>, and take advantage of the fact that the last write is the one that sticks:</p>
<pre><code>In [765]: parser=argparse.ArgumentParser()
In [766]: a1=parser.add_argument('-y',action='store_true')
In [767]: a2=parser.ad... | 2 | 2016-10-19T16:30:15Z | [
"python",
"command-line-arguments",
"argparse"
] |
Getting Data in Wrong Sequence Order from DynamoDB | 40,129,365 | <p>I am facing problem in downloading the Data from DynamoDB. I tried with Python SDK as well as with the AWS CLI (aws dynamodb scan --table-name Alarms) but every time, I am getting the same problem. Does anyone have any idea that what is the cause for that.</p>
<p>Output Get</p>
<pre><code> {
"FRE": {
... | 0 | 2016-10-19T10:53:42Z | 40,129,987 | <p>When you creating dictionary object, that having problem of to maintain order, it doesn't iterate in order with respect to element added in it.</p>
<pre><code>#So we have to create Ordered dict you can use collection package as follow's
from collections import OrderedDict
data_dict = OrderedDict()
</code></pre>
... | 0 | 2016-10-19T11:19:11Z | [
"python",
"amazon-web-services",
"amazon-dynamodb"
] |
Pandas Create Column with Groupby and Sum with additional condition | 40,129,410 | <p>I'm trying to add a new column in pandas DataFrame after grouping and with additional conditions </p>
<pre><code>df = pd.DataFrame({
'A' :[4,5,7,8,2,3,5,2,1,1,4,4,2,4,5,1,3,9,7,9],
'B' :[9,5,7,8,3,3,5,2,1,1,4,4,2,4,5,1,3,5,7,9],
'C' :[9,5,7,8,3,3,5,2,1,1,4,4,2,4,5,1,3,5,7,9],
'D' :[1,0,1,0,1,... | 1 | 2016-10-19T10:55:20Z | 40,129,503 | <p>You can add <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>mask = df['D'] == 1
df1 = df[mask].join(df[mask].groupby(['A'])['C'].sum(), on='A', rsuffix='_inward')
print (df1)
A B C D C_inward
0 4 9 9 ... | 0 | 2016-10-19T10:58:45Z | [
"python",
"pandas",
"dataframe"
] |
How to check the percentile of each row based on a column in pandas? | 40,129,428 | <p>I have a dataset with a <code>id</code> column for each event and a <code>value</code> column (among other columns) in a dataframe. What I want to do is categorize each <code>id</code> based on whether it is on the 90th percentile, 50th percentile, 25th percentile etc. of the frequency distribution of the value colu... | 0 | 2016-10-19T10:56:18Z | 40,130,836 | <p>You're looking for the <code>quantile</code> method. For instance, assigning to <code>0.0, 0.25, 0.5, 0.75</code> quantiles could be done this way:</p>
<pre><code>df['quantile'] = 0.0
for q in [0.25, 0.5, 0.75]:
df.loc[df['value'] >= df['value'].quantile(q), 'quantile'] = q
</code></pre>
| 0 | 2016-10-19T11:59:26Z | [
"python",
"pandas",
"statistics"
] |
Using alphabet as counter in a loop | 40,129,447 | <p>I am looking for the most efficient way to count the number of letters in a list. I need something like</p>
<pre><code>word=[h e l l o]
for i in alphabet:
for j in word:
if j==i:
## do something
</code></pre>
<p>Where <em>alphabet</em> should be the <strong>spanish</strong> alphabet, that is the... | 1 | 2016-10-19T10:56:52Z | 40,129,596 | <p>This is pretty easy:</p>
<pre><code>import collections
print collections.Counter("señor")
</code></pre>
<p>This prints:</p>
<pre><code>Counter({'s': 1, 'r': 1, 'e': 1, '\xa4': 1, 'o': 1})
</code></pre>
| 0 | 2016-10-19T11:02:30Z | [
"python",
"list",
"character"
] |
Using alphabet as counter in a loop | 40,129,447 | <p>I am looking for the most efficient way to count the number of letters in a list. I need something like</p>
<pre><code>word=[h e l l o]
for i in alphabet:
for j in word:
if j==i:
## do something
</code></pre>
<p>Where <em>alphabet</em> should be the <strong>spanish</strong> alphabet, that is the... | 1 | 2016-10-19T10:56:52Z | 40,129,771 | <p>It is not actually a dupe as you want to filter to only count characters from a certain set, you can use a <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow">Counter</a> dict to do the counting and a set of allowed characters to filter by:</p>
<pre><code>word = ["h", "e... | 2 | 2016-10-19T11:09:48Z | [
"python",
"list",
"character"
] |
How to create HDF5 file (mutli label classification) out of txt file to use in Caffe | 40,129,454 | <p>I have the following structure in a .txt file:</p>
<blockquote>
<pre><code>/path/to/image x y
/path/to/image x y
</code></pre>
</blockquote>
<p>where x and y are integers.</p>
<p>What I want to do now is: Create a hdf5 file to use in Caffe (<code>'train.prototxt'</code>)</p>
<p>My Python code looks like this:</p... | 0 | 2016-10-19T10:57:01Z | 40,132,734 | <p>It does not work because your <code>'data'</code> is <code>/path/to/image</code> instead of the image itself.</p>
<p>See <a href="http://stackoverflow.com/a/31808324/1714410">this answer</a>, and <a class='doc-link' href="http://stackoverflow.com/documentation/caffe/5344/prepare-data-for-training/19117/prepare-arbi... | 1 | 2016-10-19T13:25:19Z | [
"python",
"neural-network",
"deep-learning",
"caffe",
"multilabel-classification"
] |
AttributeError: 'module' object has no attribute 'io' in caffe | 40,129,633 | <p>I am trying to do a gender recognition program, below is the code..</p>
<pre><code>import caffe
import os
import numpy as np
import sys
import cv2
import time
#Models root folder
models_path = "./models"
#Loading the mean image
mean_filename=os.path.join(models_path,'./mean.binaryproto')
proto_data = open(mean_fi... | 1 | 2016-10-19T11:03:54Z | 40,139,374 | <p><code>io</code> is a module in <code>caffe</code> package. Basically when you type <code>import caffe</code>, it will not automatically try to import all modules in <code>caffe</code> package including <code>io</code>. There are two solutions.</p>
<p>First one: import caffe.io manually</p>
<pre><code>import caffe
... | 0 | 2016-10-19T18:52:30Z | [
"python",
"machine-learning",
"computer-vision",
"caffe"
] |
Initializing Class instance within a class | 40,129,792 | <p>the entire counter list of methods in side counter class do not work. I want setcap to set of cap, and check cap to see if each counter have reached their limit as hr min sec are what a clock should know i would like to initialize them inside the clock.</p>
<pre><code>import time
class counter():
count = 0
... | -1 | 2016-10-19T11:10:48Z | 40,130,195 | <p>One of the problems in your code is that your init functions are <em>init</em>.
Try using</p>
<pre><code>def __init__(self):
pass
</code></pre>
<p>This should solve one of your problems</p>
| 0 | 2016-10-19T11:29:12Z | [
"python",
"clock"
] |
Text to Zip to base64 and vice versa, in Python | 40,129,895 | <p>I have a 'text' that is converted to zip then converted to base64. How do I convert it back to plain text in python if I have that base64 value. ?</p>
| 0 | 2016-10-19T11:14:56Z | 40,129,912 | <p>You convert the base 64 back, using <a href="https://docs.python.org/3.5/library/base64.html" rel="nofollow">base64 module</a>, and then the zip, using the <a href="https://docs.python.org/3.5/library/zipfile.html" rel="nofollow">zipfile module</a>.</p>
<p>Assuming <code>file.txt</code> was zipped into <code>file.z... | 0 | 2016-10-19T11:15:49Z | [
"python",
"zip",
"base64",
"zlib"
] |
Dynamic class creation - Python | 40,129,989 | <p>Here is the scenario:</p>
<p>I have two classes:</p>
<pre><code>class A:
pass:
class B:
pass
</code></pre>
<p>Now I want to create a client, in that I need to have a small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility e.g <code... | 0 | 2016-10-19T11:19:13Z | 40,130,129 | <p>Standard library function <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow"><code>namedtuple</code></a> creates and returns a class. Internally it uses <code>exec</code>. It may be an inspiration for what you need.</p>
<p>Source code: <a href="https://github.com/pyth... | 0 | 2016-10-19T11:26:58Z | [
"python",
"oop",
"inheritance"
] |
Dynamic class creation - Python | 40,129,989 | <p>Here is the scenario:</p>
<p>I have two classes:</p>
<pre><code>class A:
pass:
class B:
pass
</code></pre>
<p>Now I want to create a client, in that I need to have a small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility e.g <code... | 0 | 2016-10-19T11:19:13Z | 40,130,275 | <p>Here is a possible implementation. All the code is contained in a single '.py' file</p>
<pre><code>class A:
pass
class B: ... | 2 | 2016-10-19T11:33:06Z | [
"python",
"oop",
"inheritance"
] |
Dynamic class creation - Python | 40,129,989 | <p>Here is the scenario:</p>
<p>I have two classes:</p>
<pre><code>class A:
pass:
class B:
pass
</code></pre>
<p>Now I want to create a client, in that I need to have a small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility e.g <code... | 0 | 2016-10-19T11:19:13Z | 40,131,753 | <p><code>globals()</code> returns a dictionary containing all symbols defined in the global scope of the module (including classes <code>A</code> and <code>B</code>):</p>
<p><em>a_and_b_module.py</em></p>
<pre class="lang-py prettyprint-override"><code>class A: pass
class B: pass
def get_cls(cls_name):
return gl... | 0 | 2016-10-19T12:44:03Z | [
"python",
"oop",
"inheritance"
] |
python pandas dataframe merge or join dataframe | 40,130,122 | <p>I want to help yours</p>
<p>if i have a pandas dataframe merge</p>
<p>first dataframe is</p>
<pre><code>D = { Year, Age, Location, column1, column2... }
2013, 20 , america, ..., ...
2013, 35, usa, ..., ...
2011, 32, asia, ..., ...
2008, 45, japan, ..., ...
</code></pre>
<p>shape is 38654r... | 1 | 2016-10-19T11:26:42Z | 40,130,150 | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> with parameter <code>how='left'</code> if need left join on column <code>Year</code> and <code>Location</code>:</p>
<pre><code>print (df1)
Year Age Location column1 column2
0 ... | 1 | 2016-10-19T11:27:46Z | [
"python",
"pandas",
"join",
"dataframe",
"merge"
] |
Labels show up interactively on click in python matplotlib | 40,130,126 | <p>I am plotting the following numpy array (plotDataFirst), which has 40 x 160 dimensions (and contains double values).</p>
<p>I would like to be able to hover over a plot (one of the 40 that are drawn) and see the label of that particular plot. </p>
<p>I have an array (1x40) that contains all of the labels. Is there... | 0 | 2016-10-19T11:26:49Z | 40,134,122 | <p>I'm not sure exactly how you want to show the label (tooltip, legend, title, label, ...), but something like this might be a first step:</p>
<pre><code>import numpy as np
import matplotlib.pylab as pl
pl.close('all')
def line_hover(event):
ax = pl.gca()
for line in ax.get_lines():
if line.contains... | 1 | 2016-10-19T14:21:55Z | [
"python",
"numpy",
"matplotlib"
] |
Python matplotlib.pyplot: How to make a histogram with bins counts including right bin edge? | 40,130,128 | <p>could you please help me, how to modify the code so to get a histogram with bins counts including right bin edge i.e. <code>bins[i-1] < x <= bins[i]</code> (and no the Left as by default) ? </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
data = [0,1,2,3,4]
binwidth = 1
plt.hist(data, bins=... | 0 | 2016-10-19T11:26:56Z | 40,130,412 | <p>I do not think there is an option to do it explicitly in either matplotlib or numpy.</p>
<p>However, you may use <code>np.histogram()</code> with negative value of your <code>data</code> (and bins), then negate the output and plot it with <code>plt.bar()</code> function.</p>
<pre><code>bins = np.arange(min(data), ... | 0 | 2016-10-19T11:39:43Z | [
"python",
"matplotlib",
"histogram"
] |
Python Scrapy: Skip Xpath if it's not there | 40,130,194 | <p>I have this code which scrapes a few hundred pages for me. But sometimes the xpath for <code>a</code> doesn't exist at all, how can I edit this so the script doesn't stop and keeps running to get the <code>b</code> and just give me that for that specific page?</p>
<pre><code>`a = response.xpath("//div[@class='heade... | 0 | 2016-10-19T11:29:08Z | 40,130,496 | <p>Just check the result of <code>extract()</code>.</p>
<pre><code>nodes = response.xpath("//div[@class='headerDiv']/a/@title").extract()
a = nodes[0] if nodes else ""
nodes = response.xpath("//div[@class='headerDiv']/text()").extract()
b = nodes[0].strip() if nodes else ""
items['title'] = a + " " + b
yield items
<... | 1 | 2016-10-19T11:43:31Z | [
"python",
"xpath",
"scrapy"
] |
Python Scrapy: Skip Xpath if it's not there | 40,130,194 | <p>I have this code which scrapes a few hundred pages for me. But sometimes the xpath for <code>a</code> doesn't exist at all, how can I edit this so the script doesn't stop and keeps running to get the <code>b</code> and just give me that for that specific page?</p>
<pre><code>`a = response.xpath("//div[@class='heade... | 0 | 2016-10-19T11:29:08Z | 40,130,963 | <p>You can use as follow:</p>
<pre><code>import lxml.etree as etree
parser = etree.XMLParser(strip_cdata=False, remove_comments=True)
root = etree.fromstring(data, parser)
#Take Hyperlink as per xpath:
#But Xpath returns list of element so we have to take 0 index of it if it has element
a = root.xpath("//div[@class... | 0 | 2016-10-19T12:06:00Z | [
"python",
"xpath",
"scrapy"
] |
Django: Complex Permission Model | 40,130,205 | <p>Suppose I have users, projects, memberships and in every membership a role is specified (for example: admin, read-only, user, etc.). The memberships define the relation between users and projects and the corresponding role.</p>
<p>Now I have a problem: how can I use the permission system of Django to assure that on... | 0 | 2016-10-19T11:29:34Z | 40,130,921 | <p>You need to build your own permission system. </p>
<p>Django's built-in permission system is not suited for what you want to do.</p>
<p>Build models for the <code>Project</code>. Create a ManyToMany relationship between a <code>User</code> and a <code>Project</code> <code>through</code> a <code>Membership</code> m... | 1 | 2016-10-19T12:03:53Z | [
"python",
"django",
"permissions",
"acl"
] |
Python How can i use buffer | 40,130,413 | <p>I have to solve this question :</p>
<p>We have a text file like this :</p>
<pre><code>"imei": "123456789",
"sim_no": "+90 xxx xxx xx xx",
"device_type": "standart",
"hw_version": "1.01",
"sw_version": "1.02"
</code></pre>
<p>And we should read this JSON data, then we should read this data each 1 min and put to bu... | -1 | 2016-10-19T11:39:44Z | 40,130,799 | <p>What you want are the last 5 values, so you should just append the new one to a list and if it is bigger than 5, delete the first one.</p>
<pre><code>my_list.append(my_dict)
if len(my_list) > 5:
my_list.pop(0)
</code></pre>
<p>So, after that you just sleep for 60 seconds and nothing else</p>
| 0 | 2016-10-19T11:57:27Z | [
"python",
"arrays",
"python-3.x"
] |
Creating nested dict from dict with nested tuples as keys using comprehension | 40,130,443 | <p>I got a very useful answer for this problem here earlier this year, but there I could use pandas. Now I have to do it with pure Python.</p>
<p>There is a dict like this:</p>
<pre><code>inp = {((0, 0), 0): -99.94360791266038,
((0, 0), 1): -1.1111111111107184,
((1, 0), 0): -1.111111111107987,
((... | -2 | 2016-10-19T11:40:57Z | 40,130,494 | <p>I'd not do this with a dict comprenhesion. Just use a simple loop:</p>
<pre><code>out = {}
for key, value in inp.items():
k1, k2 = key
out.setdefault(k1, {})[k2] = value
</code></pre>
<p>Demo:</p>
<pre><code>>>> inp = {((0, 0), 0): -99.94360791266038,
... ((0, 0), 1): -1.1111111111107184,
... | 3 | 2016-10-19T11:43:27Z | [
"python",
"dictionary",
"nested",
"tuples",
"list-comprehension"
] |
Creating nested dict from dict with nested tuples as keys using comprehension | 40,130,443 | <p>I got a very useful answer for this problem here earlier this year, but there I could use pandas. Now I have to do it with pure Python.</p>
<p>There is a dict like this:</p>
<pre><code>inp = {((0, 0), 0): -99.94360791266038,
((0, 0), 1): -1.1111111111107184,
((1, 0), 0): -1.111111111107987,
((... | -2 | 2016-10-19T11:40:57Z | 40,130,679 | <p>Naive solution:</p>
<pre><code>my_dict = {
((0, 0), 0): -99.94360791266038,
((0, 0), 1): -1.1111111111107184,
((1, 0), 0): -1.111111111107987,
((1, 0), 1): -1.1111111111079839,
((1, 0), 3): -1.111111111108079
}
def get_formatted_dict(my_dict):
... | 1 | 2016-10-19T11:52:10Z | [
"python",
"dictionary",
"nested",
"tuples",
"list-comprehension"
] |
How to use header key from the api to authenticate URL in iOS Swift? | 40,130,468 | <p>I am using Alamofire for the HTTP networking in my app. But in my api which is written in python have an header key for getting request, if there is a key then only give response. Now I want to use that header key in my iOS app with Alamofire, I am not getting it how to implement. Below is my code of normal without ... | 0 | 2016-10-19T11:42:13Z | 40,130,704 | <p>This should work</p>
<pre><code>let headers = [
"appkey": "test"
]
Alamofire.request(.GET, "http://name/user_data/\(userName)@someURL.com", parameters: nil, encoding: .URL, headers: headers).responseJSON {
response in
//handle response
}
</code></pre>
| 1 | 2016-10-19T11:53:33Z | [
"python",
"ios",
"swift",
"alamofire"
] |
How to use header key from the api to authenticate URL in iOS Swift? | 40,130,468 | <p>I am using Alamofire for the HTTP networking in my app. But in my api which is written in python have an header key for getting request, if there is a key then only give response. Now I want to use that header key in my iOS app with Alamofire, I am not getting it how to implement. Below is my code of normal without ... | 0 | 2016-10-19T11:42:13Z | 40,130,729 | <pre><code>let headers: HTTPHeaders = [
"Accept": "application/json",
"appkey": "test"
]
Alamofire.request("http://name/user_data/\(userName)@someURL.com", headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(re... | 0 | 2016-10-19T11:54:39Z | [
"python",
"ios",
"swift",
"alamofire"
] |
IndexError: " pop index out of range" with a for loop | 40,130,482 | <p>Goodmorning,
I just wrote this program in python and this <code>IndexError</code> keeps showing up. I don't know how to resolve it, I even tried by using a while loop but nothing changed...I hope someone can help me with this problem!</p>
<p>Here is my code, it should check the length of the object of two lists (la... | 1 | 2016-10-19T11:42:50Z | 40,130,930 | <p><strong>Assuming your lists are of equal lengths</strong></p>
<p>As has been pointed out in the comments, the <code>IndexError</code> happens due to your lists' length changing when you <code>pop()</code> an item. </p>
<p>Since you're iterating over your list using a <code>range(len(l))</code> in a <code>for</code... | 2 | 2016-10-19T12:04:28Z | [
"python"
] |
IndexError: " pop index out of range" with a for loop | 40,130,482 | <p>Goodmorning,
I just wrote this program in python and this <code>IndexError</code> keeps showing up. I don't know how to resolve it, I even tried by using a while loop but nothing changed...I hope someone can help me with this problem!</p>
<p>Here is my code, it should check the length of the object of two lists (la... | 1 | 2016-10-19T11:42:50Z | 40,131,296 | <p>Try with that:</p>
<pre><code>def rmv(la,lb):
for i in range(len(la)):
if len(la[i])<len(lb[i]):
la[i]=None
elif len(la[i])>len(lb[i]):
lb[i]=None
else:
la[i]=lb[i]=None
la = [i for i in la if i is not None]
lb = [i for i in lb if i i... | 0 | 2016-10-19T12:22:29Z | [
"python"
] |
IndexError: " pop index out of range" with a for loop | 40,130,482 | <p>Goodmorning,
I just wrote this program in python and this <code>IndexError</code> keeps showing up. I don't know how to resolve it, I even tried by using a while loop but nothing changed...I hope someone can help me with this problem!</p>
<p>Here is my code, it should check the length of the object of two lists (la... | 1 | 2016-10-19T11:42:50Z | 40,132,492 | <p>You can traverse the lists backwards, so that when you remove an item from the list the indices of the elements that you have not examined yet won't be affected</p>
<pre><code>def f(a, b):
l = len(a) if len(a)<len(b) else len(b)
for i in range(l):
j = l-i-1
la, lb = len(a[j]), len(b[j])
... | 0 | 2016-10-19T13:16:10Z | [
"python"
] |
Python large array comparison | 40,130,491 | <p>I have a large array containing URL (it can contains 100 000 URL strings), and I would like to know if my actual URL is one of the URL from the array. For that, I have to compare the actual URL string with all the URL string in the array. Is there any way to compare with this large array but with less time than I do... | 0 | 2016-10-19T11:43:19Z | 40,130,557 | <p>To check if a <code>list</code> contains an <code>item</code>, use: <code>item in list</code>.</p>
<p>So, you can write:</p>
<pre><code>error = oldUrl in urlList
</code></pre>
| 1 | 2016-10-19T11:46:16Z | [
"python",
"arrays",
"performance",
"python-2.7",
"compare"
] |
Python large array comparison | 40,130,491 | <p>I have a large array containing URL (it can contains 100 000 URL strings), and I would like to know if my actual URL is one of the URL from the array. For that, I have to compare the actual URL string with all the URL string in the array. Is there any way to compare with this large array but with less time than I do... | 0 | 2016-10-19T11:43:19Z | 40,131,229 | <p>Don't use a list for this. Lookups in lists have a worst case complexity of O(n).</p>
<p>Use a set (or dictionary if you have other metadata) instead. This has a lookup of roughly O(1). See <a href="http://stackoverflow.com/q/3489071/1048539">here</a> for comparisons between a set, dictionary, and list.</p>
<p>Usi... | 0 | 2016-10-19T12:18:55Z | [
"python",
"arrays",
"performance",
"python-2.7",
"compare"
] |
Python large array comparison | 40,130,491 | <p>I have a large array containing URL (it can contains 100 000 URL strings), and I would like to know if my actual URL is one of the URL from the array. For that, I have to compare the actual URL string with all the URL string in the array. Is there any way to compare with this large array but with less time than I do... | 0 | 2016-10-19T11:43:19Z | 40,136,206 | <p>As already mentioned by @Laurent and @sisanared, you can use the <code>in</code> operator for either <code>lists</code> or <code>sets</code> to check for membership. For example:</p>
<pre><code>found = x in some_list
if found:
#do stuff
else:
#other stuff
</code></pre>
<p>However, you mentioned that speed... | 1 | 2016-10-19T15:49:46Z | [
"python",
"arrays",
"performance",
"python-2.7",
"compare"
] |
Instantiate nested Cmd Interpreter in Python | 40,130,559 | <p>Hi I'm looking to create a nested interpreter in Python using the Cmd module.</p>
<p>I set up a dynamic module loading because I want my project to be easily expandable (i.e. add a new python file into a folder and without changing the main code being able to load it).</p>
<p>My nested interpreter is currently set... | 0 | 2016-10-19T11:46:20Z | 40,131,481 | <p>When you say "pass the MainConsole as a second variable" you appear to mean "make the new SubConsole a subclass of the MainConsole". You are effectively defining a class factory that takes the base class as an argument.</p>
<p>You say "create classes inside this method", but <code>instantiateConsole</code> in a fun... | 0 | 2016-10-19T12:31:09Z | [
"python",
"python-cmd"
] |
How to convert/rename categories in dask | 40,130,562 | <p>I'm trying to rename categories of a dtype 'category' column of a dask dataframe to a series of numbers from 1 to len(categories).</p>
<p>In pandas I was doing it like this:</p>
<pre><code>df['name'] = dd.Categorical(df.name).codes
</code></pre>
<p>but in dask this does not work:</p>
<pre><code>Traceback (most r... | 1 | 2016-10-19T11:46:30Z | 40,131,052 | <p>You probably want to look at <code>df.column.cat.codes</code>, which has the numbers you're looking for. Lets work through an example:</p>
<h3>Create Toy dataset in Pandas</h3>
<pre><code>In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'x': ['a', 'b', 'a']})
In [3]: df['x'] = df.x.astype('category')
In ... | 0 | 2016-10-19T12:10:31Z | [
"python",
"dask"
] |
python exception message formating | 40,130,632 | <p>Why don't I get an exception message when formating the message with <code>%s</code> but I do with <code>format</code>?</p>
<p>Fails:</p>
<pre><code>>>> Exception('foo %s', 'bar').message
''
</code></pre>
<p>Works:</p>
<pre><code>>>> Exception('foo {}'.format('bar')).message
'foo bar'
</code></... | 0 | 2016-10-19T11:49:41Z | 40,130,725 | <p>Your syntax for the %-substitution in <code>Exception</code> is incorrect. You need to use <code>%</code> to specify the replacement string:</p>
<pre><code>>>> Exception('foo %s' % 'bar').message
'foo bar'
</code></pre>
| 3 | 2016-10-19T11:54:19Z | [
"python",
"exception"
] |
python 2 [Error 32] The process cannot access the file because it is being used by another process | 40,130,958 | <p>I'm working with python 2 and have read several posts about this error i.e(<a href="http://stackoverflow.com/questions/28396759/os-remove-in-windows-gives-error-32-being-used-by-another-process">this post</a>).
However, I'm still getting the error.
What I do is:
I read the files in a directory, if any of the files ... | 0 | 2016-10-19T12:05:50Z | 40,131,114 | <p>it happens here :</p>
<pre><code>with open(os.path.join(root, documento), 'r') as fin:
</code></pre>
<p>So you have your file open and locked, that is why you are not able delete this folder using:</p>
<pre><code>shutil.rmtree(root)
</code></pre>
<p>within this statement, you have to do outside of <code>with</co... | 1 | 2016-10-19T12:13:50Z | [
"python",
"windows",
"python-2.7",
"loops",
"shutil"
] |
Elasticsearch how to query on ID field higher than x | 40,131,140 | <p>I am trying to apply pagination to results by querying multiple times to get past the 10k barrier of Elasticsearch. Since the results of Elasticsearch can differ during multiple queries I want to use the generated ID to get the next results. </p>
<p>So for example, I run a query that returns 1000 results. Then I wa... | 1 | 2016-10-19T12:14:50Z | 40,131,289 | <p>The best way to achieve what you want is to use the scroll/can API. However, if you still want to proceed that way, you can do it like this:</p>
<pre><code>last_id = ...
search.filter('range', id={'gt': last_id + 1, 'lt': last_id + 1000})
</code></pre>
| 1 | 2016-10-19T12:22:13Z | [
"python",
"elasticsearch",
"range",
"elasticsearch-dsl",
"elasticsearch-py"
] |
sympy.count_roots: type mismatch when working with real polynomial | 40,131,211 | <p>I am using sympy and trying to compute number of roots of a polynomial</p>
<pre><code>from sympy.abc import x
from sympy import Poly
p = Poly(x**4+0.1,x)
</code></pre>
<p>At this point, p is polynomial with domain 'RR': <code>Poly(1.0*x**4 + 0.1, x, domain='RR')</code></p>
<p>If I try to compute number of roots i... | 0 | 2016-10-19T12:18:22Z | 40,131,700 | <p>When possible, use exact (instead of floating point) numbers in your symbolic expressions (this principle is true for all symbolic math software, not only sympy). </p>
<p>In this case, the constant term <code>0.1</code> in the definition of <code>p</code> can be replaced by the (exact) ratio representation <code>1/... | 1 | 2016-10-19T12:41:49Z | [
"python",
"sympy",
"symbolic-math",
"polynomial-math"
] |
Issue when imoporting GDAL : ImportError, Library not loaded, Image not found | 40,131,266 | <p>Since yesterday I struggle to import some libraries such as GDAL (or iris) and I allways get the same type of outputs.</p>
<pre><code>>>> import gdal
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gdal.py", line 28, in <module>
_gdal = swig_import_hel... | 0 | 2016-10-19T12:20:23Z | 40,138,550 | <p>I found a solution to my problem <a href="https://github.com/conda-forge/gdal-feedstock/issues/111" rel="nofollow">here</a>.</p>
<p>Thank you for the clear explanation of "ocefpaf":</p>
<blockquote>
<p>You problem seems like the usuall mismatch between conda-forge and
defaults. Can you try the following instru... | 0 | 2016-10-19T18:02:20Z | [
"python",
"anaconda",
"importerror",
"gdal"
] |
Comparing pandas dataframes of different length | 40,131,281 | <p>I have two dataframes of different lengths both indexed by date. I need both dataframes to have the same dates, ie. delete the extra entries in the longest dataframe. </p>
<p>I have found that I can reset index and make it another another column then call that column as a pandas dataseries and compare to the other ... | 1 | 2016-10-19T12:21:46Z | 40,131,308 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.intersection.html" rel="nofollow"><code>Index.intersection</code></a> and then select data in <code>df2</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</c... | 1 | 2016-10-19T12:23:21Z | [
"python",
"pandas",
"dataframe"
] |
Why df[[2,3,4]][2:4] works and df[[2:4]][2:4] does not in Python | 40,131,360 | <p>suppose we have a datarame</p>
<pre><code>import pandas as pd
df = pd.read_csv('...')
df
0 1 2 3 4
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
</code></pre>
<p>Why one approach is working and other returns syntax error?</p>
| 2 | 2016-10-19T12:25:53Z | 40,131,402 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p>
<pre><code>print (df.ix[2:4,2:4])
2 3
2 3 4
3 3 4
4 3 4
</code></pre>
| 1 | 2016-10-19T12:27:40Z | [
"python",
"pandas",
"dataframe",
"subset"
] |
Why df[[2,3,4]][2:4] works and df[[2:4]][2:4] does not in Python | 40,131,360 | <p>suppose we have a datarame</p>
<pre><code>import pandas as pd
df = pd.read_csv('...')
df
0 1 2 3 4
0 1 2 3 4 5
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
</code></pre>
<p>Why one approach is working and other returns syntax error?</p>
| 2 | 2016-10-19T12:25:53Z | 40,131,492 | <p>It fails because <code>2:4</code> is invalid syntax for accessing the keys/columns of a df:</p>
<pre><code>In [73]:
df[[2:4]]
File "<ipython-input-73-f0f09617b349>", line 1
df[[2:4]]
^
SyntaxError: invalid syntax
</code></pre>
<p>This is no different to if you defined a dict and tried the same... | 1 | 2016-10-19T12:31:52Z | [
"python",
"pandas",
"dataframe",
"subset"
] |
Making a for loop print with an index | 40,131,479 | <p>I made a program which displays a user-provided number of the fibonacci series. I wanted to format it into an indexed list, but I don't what could I use to do so. I found the enumerate() function, but seems it only works for premade lists, whereas mine is generated accordingly to the user. </p>
<p>Do I use a for lo... | 0 | 2016-10-19T12:31:01Z | 40,132,221 | <pre><code>def fib(n):
x = 0
y = 1
for i in range(n):
yield y
tmp = x
x = y
y += tmp
def main():
n = input('How many do you want: ')
for i, f in enumerate(fib(n)):
print("{0}. {1}".format(i, f)
</code></pre>
<p>Make a generator that yields the values you... | 0 | 2016-10-19T13:03:44Z | [
"python",
"python-3.x",
"object",
"format",
"string-formatting"
] |
How to get a well-scaled table in python using matplotlib | 40,131,556 | <p>I have been trying to present a table of data in python. I've been generating the table using the matplotlib pyplot module. Unfortunately the data sets I want to present are quite large. Hence when the table displays I either get it showing the entire table, but the data is too tiny to read, or it shows the data at ... | 0 | 2016-10-19T12:34:41Z | 40,131,984 | <p>Try with Tabulate module, which is very simple to use and support numpy:</p>
<p><a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">tabulate module</a></p>
<p>sample code to start with:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from tabulate import tabulate
data=np.random.rand(... | 1 | 2016-10-19T12:54:12Z | [
"python",
"matplotlib",
"formatting"
] |
Running the sample code in pytesseract | 40,131,630 | <p>I am running python 2.6.6 and want to install the <a href="https://pypi.python.org/pypi/pytesseract" rel="nofollow">pytesseract</a> package. After extraction and installation, I can call the pytesseract from the command line. However I want to run the tesseract within python. I have the following code (ocr.py):</p>
... | 0 | 2016-10-19T12:38:11Z | 40,132,819 | <p><code>tesseract_cmd</code> should point to the command line program <a href="https://github.com/tesseract-ocr/tesseract" rel="nofollow"><code>tesseract</code></a>, not <code>pytesseract</code>.</p>
<p>For instance on Ubuntu you can install the program using:</p>
<pre><code>sudo apt install tesseract-ocr
</code></p... | 0 | 2016-10-19T13:29:28Z | [
"python",
"tesseract",
"python-tesseract"
] |
Python - Recursive way to return a list of the divisors of an integer | 40,131,643 | <p>I was trying to write a function that would return the list of a divisors of some positive integer </p>
<p>divisors(12) => [1,2,3,4,6,12]</p>
<p>I did it with a for loop, and then tried to do it with a recursion, but I couldn't figure out how to do it and found no example of it online in any language.</p>
<pre><c... | 1 | 2016-10-19T12:39:13Z | 40,131,882 | <p>You can try something like this.</p>
<pre><code>x=12
l=[]
def fun(n, l):
if x%n==0:
l.append(n)
if n==1:
return None
fun(n-1, l)
fun(x, l)
print l
</code></pre>
| 3 | 2016-10-19T12:50:27Z | [
"python",
"recursion"
] |
Python - Recursive way to return a list of the divisors of an integer | 40,131,643 | <p>I was trying to write a function that would return the list of a divisors of some positive integer </p>
<p>divisors(12) => [1,2,3,4,6,12]</p>
<p>I did it with a for loop, and then tried to do it with a recursion, but I couldn't figure out how to do it and found no example of it online in any language.</p>
<pre><c... | 1 | 2016-10-19T12:39:13Z | 40,131,926 | <p>How about this,</p>
<pre><code>>>> n = 12
>>> l = [i for i in range(1, n+1) if n%i==0]
>>> l
[1, 2, 3, 4, 6, 12]
</code></pre>
| 1 | 2016-10-19T12:52:01Z | [
"python",
"recursion"
] |
Random Forest with bootstrap = False in scikit-learn python | 40,131,893 | <p>What does RandomForestClassifier() do if we choose bootstrap = False?</p>
<p>According to the definition in this link </p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier" rel="nofollow">http://scikit-learn.org/stable... | 2 | 2016-10-19T12:50:54Z | 40,133,130 | <p>It seems like you're conflating the bootstrap of your observations with the sampling of your features. <a href="http://www-bcf.usc.edu/~gareth/ISL/ISLR%20Sixth%20Printing.pdf" rel="nofollow">An Introduction to Statistical Learning</a> provides a really good introduction to Random Forests.</p>
<p>The benefit of rand... | 0 | 2016-10-19T13:42:31Z | [
"python",
"machine-learning",
"scikit-learn"
] |
SyntaxError in setup.py with pip to install module | 40,131,953 | <p>So my teacher in python showed the turtle module, so I want to try it myself, but when I try to install the turtle module on my PC I have an error :
I'm using "pip" to install modules, so when I do "pip install turtle" on a console
(not python console) I have an error :</p>
<pre><code>Collecting turtle
using cached... | 0 | 2016-10-19T12:52:58Z | 40,132,028 | <p>Turtle is already included in the Python standard library; you don't need to install anything.</p>
<p>The library you were installing is a completely different thing (an HTTP proxy, apparently) which looks like it's not compatible with any recent Python version.</p>
| 2 | 2016-10-19T12:55:59Z | [
"python"
] |
Python user input inside infinite loop too slow, easily confused | 40,132,067 | <p>I have a Python script running on a Raspberry Pi that sits waiting for user input and records the input in a SQLite database:</p>
<pre><code>#!/usr/bin/env python
import logging
import db
while True:
barcode = raw_input("Scan ISBN: ")
if ( len(barcode) > 1 ):
logging.info("Recording scanned ISB... | 3 | 2016-10-19T12:57:50Z | 40,132,759 | <p>Don't build SQL strings from user input. Ever. </p>
<p><em>Always</em> use parameterized queries.</p>
<pre><code># Adds an item to queue
def recordScan(isbn, shop_id):
insert = "INSERT INTO scans ( isbn, shop_id ) VALUES ( ?, ? )"
conn = connect()
conn.cursor().execute(insert, [isbn, shop_id])
conn... | 1 | 2016-10-19T13:26:23Z | [
"python",
"python-2.7",
"sqlite",
"raspberry-pi"
] |
Python user input inside infinite loop too slow, easily confused | 40,132,067 | <p>I have a Python script running on a Raspberry Pi that sits waiting for user input and records the input in a SQLite database:</p>
<pre><code>#!/usr/bin/env python
import logging
import db
while True:
barcode = raw_input("Scan ISBN: ")
if ( len(barcode) > 1 ):
logging.info("Recording scanned ISB... | 3 | 2016-10-19T12:57:50Z | 40,134,174 | <p>You appear to be opening and closing the database each and every time. That will clearly add a huge overhead, especially as you are "hammering" away at it.<br>
Connect to the database once at the beginning and close it upon exit.<br>
In between, simply perform your <code>insert</code>, <code>update</code> and <code>... | 1 | 2016-10-19T14:23:57Z | [
"python",
"python-2.7",
"sqlite",
"raspberry-pi"
] |
Python user input inside infinite loop too slow, easily confused | 40,132,067 | <p>I have a Python script running on a Raspberry Pi that sits waiting for user input and records the input in a SQLite database:</p>
<pre><code>#!/usr/bin/env python
import logging
import db
while True:
barcode = raw_input("Scan ISBN: ")
if ( len(barcode) > 1 ):
logging.info("Recording scanned ISB... | 3 | 2016-10-19T12:57:50Z | 40,138,071 | <p>After much experimenting based on helpful advice from users @tomalak, @rolf-of-saxony and @hevlastka my conclusion is that <strong>yes, this <em>is</em> an inevitability that I just have to live with.</strong> </p>
<p>Even if you strip the example down to the basics by removing the database write process and making... | 1 | 2016-10-19T17:37:19Z | [
"python",
"python-2.7",
"sqlite",
"raspberry-pi"
] |
Selenium get rendered php captcha image | 40,132,107 | <p>I trying to parse web page that has captcha. Captcha is generated by PHP:</p>
<pre><code><img src="/captcha.php" border="0" align="absmiddle">
</code></pre>
<p>What i do:</p>
<pre><code> self.driver = webdriver.Chrome()
img = self.driver.find_element_by_xpath('//table/tbody/tr/td/img')
scr = img.get... | 0 | 2016-10-19T12:59:21Z | 40,133,009 | <p>from <a href="http://stackoverflow.com/questions/17361742/download-image-with-selenium-python" title="this answer">this answer</a> you can download the image:</p>
<pre><code># download the image
urllib.urlretrieve(src, "captcha.png")
</code></pre>
| 0 | 2016-10-19T13:38:18Z | [
"python",
"selenium"
] |
python pandas: Reallocate index, columns and values within dataframe | 40,132,128 | <p>I have a dataframe that looks as follows. x is the index</p>
<pre><code> y value
x
1 0 0.016175
1 1 0.017832
1 2 0.021536
1 3 0.024777
2 0 0.027594
2 1 0.029950
2 ... | 1 | 2016-10-19T13:00:21Z | 40,132,166 | <p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> and last <a href="htt... | 3 | 2016-10-19T13:01:51Z | [
"python",
"pandas",
"dataframe",
"pivot"
] |
Python: how to make parallelize processing | 40,132,288 | <p>I need to divide the task to 8 processes.
I use <code>multiprocessing</code> to do that.
I try to describe my task:
I have dataframe and there are column with urls. Some urls have a captcha and I try to use proxies from other file to get page from every url.
It takes a lot of time and I want to divide that. I want t... | 0 | 2016-10-19T13:07:06Z | 40,132,432 | <p>Something like that might help:</p>
<pre><code>def get_page(url):
m = re.search(r'avito.ru\/[a-z]+\/avtomobili\/[a-z0-9_]+$', url)
if m is not None:
url = 'https://www.' + url
print url
proxy = pd.read_excel('proxies.xlsx')
proxies = proxy.proxy.values.tolist()
for i, proxy in enumerate(proxies)... | 0 | 2016-10-19T13:13:30Z | [
"python",
"multithreading",
"proxy",
"multiprocessing"
] |
Kivy Installation Error | 40,132,289 | <p>I was trying to install kivy, but I overcame this problem and I couldn't solve it. Does anyone know how to solve it?</p>
<p>kivy error
<a href="https://i.stack.imgur.com/dVXsd.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/dVXsd.jpg" alt="enter image description here"></a></p>
<p>I am informed that I need... | 0 | 2016-10-19T13:07:09Z | 40,132,458 | <p>You need to install libglew-dev first.The problem is because it is already not installed on your system.</p>
<p>For installing it,see <a href="https://www.youtube.com/watch?v=u_NI7KOzyFM" rel="nofollow">This Video</a></p>
| 0 | 2016-10-19T13:14:25Z | [
"python",
"package",
"install",
"kivy"
] |
Kivy Installation Error | 40,132,289 | <p>I was trying to install kivy, but I overcame this problem and I couldn't solve it. Does anyone know how to solve it?</p>
<p>kivy error
<a href="https://i.stack.imgur.com/dVXsd.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/dVXsd.jpg" alt="enter image description here"></a></p>
<p>I am informed that I need... | 0 | 2016-10-19T13:07:09Z | 40,133,968 | <p>This video explains how to install pygame and kivy in detail.</p>
<p><a href="https://www.youtube.com/watch?v=CYNWK2GpwgA&list=PLQVvvaa0QuDe_l6XiJ40yGTEqIKugAdTy" rel="nofollow">Installing Kivy</a></p>
| 0 | 2016-10-19T14:16:43Z | [
"python",
"package",
"install",
"kivy"
] |
python filter 2d array by a chunk of data | 40,132,352 | <pre><code>import numpy as np
data = np.array([
[20, 0, 5, 1],
[20, 0, 5, 1],
[20, 0, 5, 0],
[20, 1, 5, 0],
[20, 1, 5, 0],
[20, 2, 5, 1],
[20, 3, 5, 0],
[20, 3, 5, 0],
[20, 3, 5, 1],
[20, 4, 5, 0],
[20, 4, 5, 0],
[20, 4, 5, 0]
])
</cod... | 4 | 2016-10-19T13:10:04Z | 40,132,462 | <p>code: </p>
<pre><code>import numpy as np
my_list = [[20,0,5,1],
[20,0,5,1],
[20,0,5,0],
[20,1,5,0],
[20,1,5,0],
[20,2,5,1],
[20,3,5,0],
[20,3,5,0],
[20,3,5,1],
[20,4,5,0],
[20,4,5,0],
[20,4,5,0]]
all_ids = np.array(my_list)[:,1]
unique_ids = np.unique(all_ids)
indices =... | 0 | 2016-10-19T13:14:34Z | [
"python",
"arrays",
"numpy"
] |
python filter 2d array by a chunk of data | 40,132,352 | <pre><code>import numpy as np
data = np.array([
[20, 0, 5, 1],
[20, 0, 5, 1],
[20, 0, 5, 0],
[20, 1, 5, 0],
[20, 1, 5, 0],
[20, 2, 5, 1],
[20, 3, 5, 0],
[20, 3, 5, 0],
[20, 3, 5, 1],
[20, 4, 5, 0],
[20, 4, 5, 0],
[20, 4, 5, 0]
])
</cod... | 4 | 2016-10-19T13:10:04Z | 40,132,496 | <p>This gets rid of all rows with 1 in the second position:</p>
<pre><code>[sublist for sublist in list_ if sublist[1] != 1]
</code></pre>
<p>This get's rid of all rows with 1 in the second position unless the fourth position is also 1:</p>
<pre><code>[sublist for sublist in list_ if not (sublist[1] == 1 and sublist... | 0 | 2016-10-19T13:16:29Z | [
"python",
"arrays",
"numpy"
] |
python filter 2d array by a chunk of data | 40,132,352 | <pre><code>import numpy as np
data = np.array([
[20, 0, 5, 1],
[20, 0, 5, 1],
[20, 0, 5, 0],
[20, 1, 5, 0],
[20, 1, 5, 0],
[20, 2, 5, 1],
[20, 3, 5, 0],
[20, 3, 5, 0],
[20, 3, 5, 1],
[20, 4, 5, 0],
[20, 4, 5, 0],
[20, 4, 5, 0]
])
</cod... | 4 | 2016-10-19T13:10:04Z | 40,134,398 | <p><strong>Generic approach :</strong> Here's an approach using <a href="https://numeric.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a>... | 3 | 2016-10-19T14:32:19Z | [
"python",
"arrays",
"numpy"
] |
python filter 2d array by a chunk of data | 40,132,352 | <pre><code>import numpy as np
data = np.array([
[20, 0, 5, 1],
[20, 0, 5, 1],
[20, 0, 5, 0],
[20, 1, 5, 0],
[20, 1, 5, 0],
[20, 2, 5, 1],
[20, 3, 5, 0],
[20, 3, 5, 0],
[20, 3, 5, 1],
[20, 4, 5, 0],
[20, 4, 5, 0],
[20, 4, 5, 0]
])
</cod... | 4 | 2016-10-19T13:10:04Z | 40,134,524 | <p>Let's assume the following:</p>
<ul>
<li><code>b >= 0</code></li>
<li><code>b</code> is an integer</li>
<li><code>b</code> is fairly dense, ie <code>max(b) ~= len(unique(b))</code></li>
</ul>
<p>Here's a solution using <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ufunc.at.html" rel... | 0 | 2016-10-19T14:37:34Z | [
"python",
"arrays",
"numpy"
] |
python filter 2d array by a chunk of data | 40,132,352 | <pre><code>import numpy as np
data = np.array([
[20, 0, 5, 1],
[20, 0, 5, 1],
[20, 0, 5, 0],
[20, 1, 5, 0],
[20, 1, 5, 0],
[20, 2, 5, 1],
[20, 3, 5, 0],
[20, 3, 5, 0],
[20, 3, 5, 1],
[20, 4, 5, 0],
[20, 4, 5, 0],
[20, 4, 5, 0]
])
</cod... | 4 | 2016-10-19T13:10:04Z | 40,136,593 | <p>Untested since in a hurry, but this should work:</p>
<pre><code>import numpy_indexed as npi
g = npi.group_by(data[:, 1])
ids, valid = g.any(data[:, 3])
result = data[valid[g.inverse]]
</code></pre>
| 0 | 2016-10-19T16:09:35Z | [
"python",
"arrays",
"numpy"
] |
Mark as unseen on Gmail (imaplib) | 40,132,420 | <p>I'm trying to mark email as unseen on Gmail server.</p>
<p>I'm using this command:</p>
<pre><code>res, data = mailbox.uid('STORE', uid, '-FLAGS', '(\Seen)')
</code></pre>
<p>Everything goes OK but when I check it using web browser it's still marked as seen.
When I check flags here's what I got:</p>
<pre><code> b... | 0 | 2016-10-19T13:12:59Z | 40,138,902 | <p>It appears you've misunderstood flags on APPEND a bit.</p>
<p>By doing <code>APPEND folder (-FLAGS \Seen) ...</code> you've actually created a message with two flags: The standard <code>\Seen</code> flag, and a nonstandard <code>-FLAGS</code> flag.</p>
<p>To create a message without the \Seen flag, just use <code>... | 2 | 2016-10-19T18:23:14Z | [
"python",
"email",
"gmail",
"imap",
"imaplib"
] |
How do I schedule a job in Django? | 40,132,576 | <p>I have to schedule a job using <a href="https://pypi.python.org/pypi/schedule" rel="nofollow">Schedule</a> on my <a href="https://www.djangoproject.com/" rel="nofollow">django</a> web application.</p>
<pre><code>def new_job(request):
print("I'm working...")
file=schedulesdb.objects.filter (user=request.us... | -1 | 2016-10-19T13:19:16Z | 40,139,508 | <p>Django is a web framework. It receives a request, does whatever processing is necessary and sends out a response. It doesn't have any persistent process that could keep track of time and run scheduled tasks, so there is no good way to do it using just Django.</p>
<p>That said, Celery (<a href="http://www.celeryproj... | 0 | 2016-10-19T19:00:07Z | [
"python",
"django"
] |
Python cprofiler a function | 40,132,630 | <p>How to profile one function with cprofiler?</p>
<pre><code>label = process_one(signature)
</code></pre>
<p>become</p>
<pre><code>import cProfile
label = cProfile.run(process_one(signature))
</code></pre>
<p>but it didn't work :/</p>
| 0 | 2016-10-19T13:21:22Z | 40,133,433 | <p>according to documentation (<a href="https://docs.python.org/2/library/profile.html" rel="nofollow">https://docs.python.org/2/library/profile.html</a>) it should be <code>cProfile.run('process_one(signature)')</code></p>
<p>also, look at the answer <a href="http://stackoverflow.com/a/17259420/1966790">http://stacko... | 1 | 2016-10-19T13:55:36Z | [
"python",
"profiling"
] |
Python cprofiler a function | 40,132,630 | <p>How to profile one function with cprofiler?</p>
<pre><code>label = process_one(signature)
</code></pre>
<p>become</p>
<pre><code>import cProfile
label = cProfile.run(process_one(signature))
</code></pre>
<p>but it didn't work :/</p>
| 0 | 2016-10-19T13:21:22Z | 40,134,116 | <p>You can write some decorator which will be helpful for profiling any function in general with cProfile. This helps me to quickly get stats when I need them.</p>
<pre><code>import cProfile
import pstats
import StringIO
import commands
def qprofile(func):
def profiled_func(*args, **kwargs):
if 'profile'... | 1 | 2016-10-19T14:21:48Z | [
"python",
"profiling"
] |
Rename python click argument | 40,132,771 | <p>I have this chunk of code:</p>
<pre><code>import click
@click.option('--delete_thing', help="Delete some things columns.", default=False)
def cmd_do_this(delete_thing=False):
print "I deleted the thing."
</code></pre>
<p>I would like to rename the option variable in <code>--delete-thing</code>. But python doe... | 3 | 2016-10-19T13:26:49Z | 40,135,726 | <p>By default, click will intelligently map intra-option commandline hyphens to underscores so your code should work as-is. This is used in the click documentation, e.g., in the <a href="http://click.pocoo.org/5/options/#choice-options" rel="nofollow">Choice example</a>. If --delete-thing is intended to be a boolean op... | 2 | 2016-10-19T15:27:30Z | [
"python",
"command-line-arguments",
"python-click"
] |
msgpack unpacks the number '10' between each item | 40,132,832 | <p>I'm trying to use <a href="https://pypi.python.org/pypi/msgpack-python" rel="nofollow">msgpack</a> to write a list of dictionaries to a file. However, when I iterate over an instance of <code>Unpacker</code>, it seems like the number <code>10</code> is unpacked between each 'real' document.</p>
<p>The test script I... | 1 | 2016-10-19T13:30:19Z | 40,133,035 | <p>This is coming from the contents of unpacker. You can replicate yourself like this:</p>
<pre><code>In [23]: unpacker = msgpack.Unpacker(open(data_file))
In [24]: unpacker.next()
Out[24]: {'name': 'Edward Ruiz'}
In [25]: unpacker.next()
Out[25]: 10
</code></pre>
| 2 | 2016-10-19T13:39:34Z | [
"python"
] |
Sort xml with python by tag | 40,132,918 | <p>I have an xml</p>
<pre><code><root>
<node1>
<B>text</B>
<A>another_text</A>
<C>one_more_text</C>
</node1>
<node2>
<C>one_more_text</C>
<B>text</B>
<A>another_text</A>
</node2>
</root>
</code><... | 1 | 2016-10-19T13:34:23Z | 40,133,028 | <p>From a similar question : </p>
<pre><code>from lxml import etree
data = """<X>
<X03>3</X03>
<X02>2</X02>
<A>
<A02>Y</A02>
<A01>X</A01>
<A03>Z</A03>
</A>
<X01>1</X01>
<B>
... | 1 | 2016-10-19T13:39:21Z | [
"python",
"xml",
"sorting"
] |
Sort xml with python by tag | 40,132,918 | <p>I have an xml</p>
<pre><code><root>
<node1>
<B>text</B>
<A>another_text</A>
<C>one_more_text</C>
</node1>
<node2>
<C>one_more_text</C>
<B>text</B>
<A>another_text</A>
</node2>
</root>
</code><... | 1 | 2016-10-19T13:34:23Z | 40,133,057 | <p>You need to:</p>
<ul>
<li>get the children elements for every top-level "node"</li>
<li>sort them by the <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tag" rel="nofollow"><code>tag</code> attribute</a> (node's name)</li>
<li>reset the child nodes of each top-lev... | 1 | 2016-10-19T13:40:16Z | [
"python",
"xml",
"sorting"
] |
Set specific values in a mixed valued DataFrame to fixed value? | 40,132,927 | <p>I have a data frame with response and predictor variables in the columns and observations in the rows. Some of the values in the responses are below a given limit of detection (LOD). As I am planing to apply a rank transformation on the responses, I would like to set all those values equal to LOD. Say, the data fram... | 1 | 2016-10-19T13:34:44Z | 40,133,189 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow"><code>DataFrame.mask</code></a>:</p>
<pre><code>import numpy as np
import pandas as pd
np.random.seed(123)
x = pd.Series(np.random.randint(0,2,10), dtype='category')
x.cat.categories = ['no', 'yes'... | 0 | 2016-10-19T13:45:02Z | [
"python",
"pandas",
"dataframe"
] |
How to group pandas DataFrame by varying dates? | 40,133,016 | <p>I am trying to roll up daily data into fiscal quarter data. For example, I have a table with fiscal quarter end dates:</p>
<pre><code>Company Period Quarter_End
M 2016Q1 05/02/2015
M 2016Q2 08/01/2015
M 2016Q3 10/31/2015
M 2016Q4 01/30/2016
WFM 2015Q2 04/12/2015
WFM 2015Q3 07/05/201... | 4 | 2016-10-19T13:38:33Z | 40,133,488 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge_ordered.html" rel="nofollow"><code>merge_ordered</code></a>:</p>
<pre><code>#first convert columns to datetime
df1.Quarter_End = pd.to_datetime(df1.Quarter_End)
df2.Date = pd.to_datetime(df2.Date)
df = pd.merge_ordered... | 5 | 2016-10-19T13:57:53Z | [
"python",
"pandas",
"numpy"
] |
How to group pandas DataFrame by varying dates? | 40,133,016 | <p>I am trying to roll up daily data into fiscal quarter data. For example, I have a table with fiscal quarter end dates:</p>
<pre><code>Company Period Quarter_End
M 2016Q1 05/02/2015
M 2016Q2 08/01/2015
M 2016Q3 10/31/2015
M 2016Q4 01/30/2016
WFM 2015Q2 04/12/2015
WFM 2015Q3 07/05/201... | 4 | 2016-10-19T13:38:33Z | 40,133,589 | <ul>
<li><code>set_index</code></li>
<li><code>pd.concat</code> to align indices</li>
<li><code>groupby</code> with <code>agg</code></li>
</ul>
<hr>
<pre><code>prd_df = period_df.set_index(['Company', 'Quarter_End'])
prc_df = price_df.set_index(['Company', 'Date'], drop=False)
df = pd.concat([prd_df, prc_df], axis=... | 3 | 2016-10-19T14:02:16Z | [
"python",
"pandas",
"numpy"
] |
Python: logging and TCP handler | 40,133,059 | <p>I wrote my TCP handler as follows (adapted from: <a href="https://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-example" rel="nofollow">https://docs.python.org/2/library/socketserver.html#socketserver-tcpserver-example</a>):</p>
<pre><code>#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import S... | 0 | 2016-10-19T13:40:22Z | 40,133,612 | <p><code>MyHandler</code> is a subclass of <code>SocketServer.StreamRequestHandler</code> which is a subclass of <code>BaseRequestHandler</code>. The <a href="https://github.com/python/cpython/blob/2.7/Lib/SocketServer.py#L201" rel="nofollow">call signature of <code>BaseRequestHandler.__init__</code></a> is </p>
<pre>... | 2 | 2016-10-19T14:03:08Z | [
"python",
"python-2.7",
"logging",
"tcp"
] |
How to return JSON from Python REST API | 40,133,216 | <p>I have a Python API that receives data from mysql select query. The data looks like this:</p>
<pre><code>| val | type | status |
|-----|------|--------|
| 90 | 1 | a |
</code></pre>
<p>That data was received well in python. Now I want to present that data as JSON to my REST client - how?</p>
<p>Here is m... | 2 | 2016-10-19T13:46:03Z | 40,138,988 | <p>You will first need to get the mysql query to return a dict object instead of a list. If your library is MySQLdb then this answer: <a href="http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary">Python - mysqlDB, sqlite result as dictionary</a> is what you need.</p>
<p>Here is a link... | 1 | 2016-10-19T18:27:58Z | [
"python",
"mysql",
"json",
"rest",
"python-3.x"
] |
python: multiple .dat's in multiple arrays | 40,133,288 | <p>I'm trying to sort some data into (np.)arrays and get stuck with a problem.</p>
<p>I have 1000 .dat files and I need to put the data from them in 1000 different arrays. Further, every array should contain data depend on coordinates [i] [j] [k] (this part I've done already and the code looks like this (this is kind ... | 0 | 2016-10-19T13:48:50Z | 40,135,989 | <p>I think building arrays like this is going to make things more complicated for you. It would be easier to build a dictionary using tuples as keys. In the example file you sent me, each <code>(x, y, z)</code> pair was repeated twice, making me think that each file contains data on <em>two</em> iterations of a total s... | 0 | 2016-10-19T15:40:00Z | [
"python",
"arrays"
] |
Reading files with hdfs3 fails | 40,133,440 | <p>I am trying to read a file on HDFS with Python using the hdfs3 module. </p>
<pre><code>import hdfs3
hdfs = hdfs3.HDFileSystem(host='xxx.xxx.com', port=12345)
hdfs.ls('/projects/samplecsv/part-r-00000')
</code></pre>
<p>This produces</p>
<pre><code>[{'block_size': 134345348,
'group': 'supergroup',
'kind': 'fil... | 0 | 2016-10-19T13:55:52Z | 40,134,304 | <p>if You want any operation on files then you have to pass full File path .</p>
<pre><code>import hdfs3
hdfs = hdfs3.HDFileSystem(host='xxx.xxx.com', port=12345)
hdfs.ls('/projects/samplecsv/part-r-00000')
#you have to add file to location
hdfs.put('local-file.txt', '/projects/samplecsv/part-r-00000')
with hdfs.o... | 0 | 2016-10-19T14:28:50Z | [
"python",
"hadoop",
"hdfs"
] |
Bokeh Python: Laying out multiple plots | 40,133,688 | <p>I want to array plots horizontally, use the hplot() function.
My problem is that I generate my plot names dinamically.
Dfdict is a dictionary of dataframes</p>
<pre><code>for key in dfdict.keys():
plot[key] = BoxPlot(dfdict[key], values='oex', ...)
filename = '{}.html'.format(str(key))
output_file(filen... | 0 | 2016-10-19T14:06:18Z | 40,135,411 | <p>I do it, intead of this</p>
<pre><code>p = hplot(plot.values())
</code></pre>
<p>I am using this</p>
<pre><code>p = hplot(*plot.values())
</code></pre>
| 0 | 2016-10-19T15:13:13Z | [
"python",
"dictionary",
"bokeh"
] |
Bokeh Python: Laying out multiple plots | 40,133,688 | <p>I want to array plots horizontally, use the hplot() function.
My problem is that I generate my plot names dinamically.
Dfdict is a dictionary of dataframes</p>
<pre><code>for key in dfdict.keys():
plot[key] = BoxPlot(dfdict[key], values='oex', ...)
filename = '{}.html'.format(str(key))
output_file(filen... | 0 | 2016-10-19T14:06:18Z | 40,136,450 | <p>Please note that <code>hplot</code> is deprecated in recent releases. You should use <code>bokeh.layout.row</code>:</p>
<pre><code>from bokeh.layouts import row
# define some plots p1, p2, p3
layout = row(p1, p2, p3)
show(layout)
</code></pre>
<p>Functions like <code>row</code> (and previously <code>hplot</code... | 1 | 2016-10-19T16:02:02Z | [
"python",
"dictionary",
"bokeh"
] |
find repeated element in list of list python | 40,133,720 | <p>I have been struggling with this problem for two days and I need help with it. I need to find repeated element in a list of lists
<code>list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)]</code> where "a" and "b" elements are integers and "c" elements are floats.</p>
<p>So if for example <code>a1 == a2</... | -1 | 2016-10-19T14:07:13Z | 40,134,148 | <p>You can count occurrences of specific list elements and take lists with counts > 1. Something like this, using <code>collections.defaultdict()</code>:</p>
<pre><code>>>> from collections import defaultdict
>>> count = defaultdict(int)
>>> for lst in list_of_list:
... count[lst[0]] += ... | 0 | 2016-10-19T14:22:43Z | [
"python",
"list",
"element"
] |
find repeated element in list of list python | 40,133,720 | <p>I have been struggling with this problem for two days and I need help with it. I need to find repeated element in a list of lists
<code>list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)]</code> where "a" and "b" elements are integers and "c" elements are floats.</p>
<p>So if for example <code>a1 == a2</... | -1 | 2016-10-19T14:07:13Z | 40,134,478 | <p>And this is how i would do it since i was not aware of the <code>collections.defaultdict()</code>.</p>
<pre><code>list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ]
results = []
for i_sub, subset in enumerate(list_of_list):
# test if ai == aj
rest = list_of_list[:i_sub] + lis... | 0 | 2016-10-19T14:35:40Z | [
"python",
"list",
"element"
] |
find repeated element in list of list python | 40,133,720 | <p>I have been struggling with this problem for two days and I need help with it. I need to find repeated element in a list of lists
<code>list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)]</code> where "a" and "b" elements are integers and "c" elements are floats.</p>
<p>So if for example <code>a1 == a2</... | -1 | 2016-10-19T14:07:13Z | 40,136,216 | <p>Using your idea, you can try this:</p>
<pre><code>MI_network = []
complete_net = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99)]
genesis = list(complete_net)
while genesis != []:
for x in genesis:
for gen in genesis:
if x[0] in gen and x[1] not in gen:
... | 0 | 2016-10-19T15:50:19Z | [
"python",
"list",
"element"
] |
can you help me to optimize this code | 40,133,742 | <p>can you help me to optimize this code </p>
<pre><code>def calc_potential(time, firstsale, lastsale, sold, supplied):
retval = []
for t, f, l, c, s in zip(time, firstsale, lastsale, sold, supplied):
try:
if s > c:
retval.append(c)
else:
s = (... | -5 | 2016-10-19T14:08:04Z | 40,133,990 | <p>Keeping in mind some of the comments i.e. this is not for optimizing but rather fixing broken code, I can point you in the right direction:</p>
<p>To replace this section of code: </p>
<pre><code>if s > c:
retval.append(c)
</code></pre>
<p>For something more efficient, try list comprehension:</p>
<pre><code... | 1 | 2016-10-19T14:17:51Z | [
"python"
] |
is there any way to split Spark Dataset in given logic | 40,133,761 | <p>i am looking for Spark Dataset split application which is similar to bellow mentioned logic. </p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>> df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
>>> df1
a b c ... | 1 | 2016-10-19T14:08:41Z | 40,135,957 | <p>Preserving order is very difficult in Spark applications due to the assumptions of the RDD abstraction. The best approach you can take is to translate the pandas logic using the Spark api, like I've done here. Unfortunately, I do not think you can apply the same filter criteria to every column, so I had to manually ... | 0 | 2016-10-19T15:38:36Z | [
"python",
"pandas",
"apache-spark"
] |
JSON combined with python loop to only print integers | 40,133,806 | <p>I'm trying to loop through integers that are in the json list based on a variable provided before. Here is my JSON list:</p>
<pre><code> tracks =[
{
'album_name':'Nevermind',
1:'Smells like teen spirit',
2:'In Bloom',
3:'Come as you are',
4:'Breed',
5:'Lithium',
6:'Po... | 0 | 2016-10-19T14:10:17Z | 40,134,624 | <pre><code>In [15]: from django.template import Template,Context
In [16]: tracks =[
...: {
...: 'album_name':'Nevermind',
...: 1:'Smells like teen spirit',
...: 2:'In Bloom',
...: 3:'Come as you are',
...: 4:'Breed',
...: ... | 0 | 2016-10-19T14:41:35Z | [
"python",
"loops",
"count",
"increment"
] |
Python save list and read data from file | 40,133,826 | <p>Basically I would like to save a list to python and then when the program starts I would like to retrieve the data from the file and put it back into the list.
<br>
So far this is the code I am using</p>
<pre><code>mylist = pickle.load("save.txt")
...
saveToList = (name, data)
mylist.append(saveList)
import pickle... | 3 | 2016-10-19T14:10:53Z | 40,133,930 | <p>You need a file object, not just a file name. Try this for saving:</p>
<pre><code>pickle.dump(mylist, open("save.txt", "wb"))
</code></pre>
<p>or better, to guarantee the file is closed properly:</p>
<pre><code>with open("save.txt", "wb") as f:
pickle.dump(mylist, f)
</code></pre>
<p>and then this for loadin... | 3 | 2016-10-19T14:14:53Z | [
"python"
] |
Python save list and read data from file | 40,133,826 | <p>Basically I would like to save a list to python and then when the program starts I would like to retrieve the data from the file and put it back into the list.
<br>
So far this is the code I am using</p>
<pre><code>mylist = pickle.load("save.txt")
...
saveToList = (name, data)
mylist.append(saveList)
import pickle... | 3 | 2016-10-19T14:10:53Z | 40,133,939 | <pre><code>with open("save.txt", "w") as f:
pickle.dump(f, mylist)
</code></pre>
<p>Refer to python pickle documentation for usage.</p>
| 1 | 2016-10-19T14:15:16Z | [
"python"
] |
Python save list and read data from file | 40,133,826 | <p>Basically I would like to save a list to python and then when the program starts I would like to retrieve the data from the file and put it back into the list.
<br>
So far this is the code I am using</p>
<pre><code>mylist = pickle.load("save.txt")
...
saveToList = (name, data)
mylist.append(saveList)
import pickle... | 3 | 2016-10-19T14:10:53Z | 40,133,995 | <p>pickle.dump accept file object as argument instead of filename string</p>
<pre><code>pickle.dump(mylist, open("save.txt", "wb"))
</code></pre>
| 1 | 2016-10-19T14:18:00Z | [
"python"
] |
Reading Database Queries into a Specific format in Python | 40,133,863 | <p>Hi I'm connecting to sqlite database using python and fetching some results. However to input these results to another file I need it to be in the following format.</p>
<pre><code> x={
(1,1):1, (1,2):0,
(2,1):1, (2,2):0,
(3,1):0, (3,2):1,
(4,1):0, (4,2):1,}
</code></pre>
<p>My database ... | -1 | 2016-10-19T14:12:33Z | 40,138,945 | <p>In this code the commented lines at the top indicate what's needed to access the sqlite database. Since I didn't want to build and populate such a database I created the object <strong>C</strong> to emulate its approximate behaviour. I used <strong>defaultdict</strong> because I don't know how many possible combinat... | 0 | 2016-10-19T18:25:55Z | [
"python"
] |
Obey the Testing Goat - Traceback | 40,133,865 | <p>So I'm going through this book called "Obey the Testing Goat" and I'm running into an issue in the sixth chapter while learning Python. It says that I should be able to run the functional_tests we've set up throughout the chapter and previous one with no errors; however, I keep getting a Traceback that I don't know ... | 1 | 2016-10-19T14:12:39Z | 40,139,646 | <p>Found the error in my work. I was apparently missing an s in list.html</p>
<pre><code><form method="POST" action="/lists/{{ list.id }}/add_item">
</code></pre>
| 1 | 2016-10-19T19:09:34Z | [
"python",
"traceback"
] |
Adding data to a Python list | 40,134,026 | <p>I've just started playing around with python lists, I've written the simple code below expecting the printed file to display the numbers [12,14,16,18,20,22] but only 22 is displayed. Any help would be great.</p>
<pre><code>a=10
b=14
while a <= 20:
a=a+2
b=b-1
datapoints=[]
datapoints.insert(0,a)
... | 0 | 2016-10-19T14:19:00Z | 40,134,242 | <pre><code>a=10
b=14
datapoints=[] # this needs to be established outside of your loop
while a <= 20:
a=a+2
b=b-1
datapoints.append(a)
print datapoints
</code></pre>
<p>You need to set up datapoints outside your loop, and then inside your loop, append each additional datum to datapoints</p>
| 1 | 2016-10-19T14:26:38Z | [
"python",
"python-2.7"
] |
Adding data to a Python list | 40,134,026 | <p>I've just started playing around with python lists, I've written the simple code below expecting the printed file to display the numbers [12,14,16,18,20,22] but only 22 is displayed. Any help would be great.</p>
<pre><code>a=10
b=14
while a <= 20:
a=a+2
b=b-1
datapoints=[]
datapoints.insert(0,a)
... | 0 | 2016-10-19T14:19:00Z | 40,134,542 | <p>Joel already answered but if you want a more compact code you can use range</p>
<pre><code>numbers = []
for number in range(12,24,2):
# do whatevery you want with b
numbers.append(number)
print numbers
</code></pre>
<p>or if you only want to print the numbers you can do</p>
<pre><code>print [number for n... | 1 | 2016-10-19T14:38:20Z | [
"python",
"python-2.7"
] |
Adding data to a Python list | 40,134,026 | <p>I've just started playing around with python lists, I've written the simple code below expecting the printed file to display the numbers [12,14,16,18,20,22] but only 22 is displayed. Any help would be great.</p>
<pre><code>a=10
b=14
while a <= 20:
a=a+2
b=b-1
datapoints=[]
datapoints.insert(0,a)
... | 0 | 2016-10-19T14:19:00Z | 40,134,717 | <p>you can achieve the expected list as output by using the <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">range()</a> method. It takes three parameters, start, stop and step. </p>
<pre><code>data_points = range(12, 23, 2) # range returns list in python 2
print data_points
</code></pr... | 0 | 2016-10-19T14:45:07Z | [
"python",
"python-2.7"
] |
Python read dedicated rows from csv file | 40,134,149 | <p>need some help to read dedicated rows in python. The txt file content is defined as the following:</p>
<pre><code>A;Maria;1.5;20.0;FFM;
B;2016;20;1;2017;20;1;
</code></pre>
<p>I read the file n python as defined below:</p>
<pre><code>import csv
with open('C:/0001.txt', newline='') as csvfile:
filereader = ... | -2 | 2016-10-19T14:22:45Z | 40,139,790 | <p>Thanks for the answers. I defined a class and want to fill every value to the dedicated function:</p>
<pre><code>class Class(object):
def __init__(self, name, years, age, town):
self.name = name
self.years = years
self.age = age
self.town = town
def GetName(self):
r... | 0 | 2016-10-19T19:17:13Z | [
"python"
] |
Conditionally calculated column for a Pandas DataFrame | 40,134,313 | <p>I have a calculated column in a Pandas DataFrame which needs to be assigned base upon a condition. For example:</p>
<pre><code>if(data['column_a'] == 0):
data['column_c'] = 0
else:
data['column_c'] = data['column_b']
</code></pre>
<p>However, that returns an error:</p>
<pre>
ValueError: The truth value o... | 0 | 2016-10-19T14:29:09Z | 40,134,459 | <p>You can do:</p>
<pre><code>data['column_c'] = data['column_a'].where(data['column_a'] == 0, data['column_b'])
</code></pre>
<p>this is vectorised your attempts failed because the comparison with <code>if</code> doesn't understand how to treat an array of boolean values hence the error</p>
<p>Example:</p>
<pre><c... | 0 | 2016-10-19T14:34:47Z | [
"python",
"pandas",
"dataframe"
] |
Conditionally calculated column for a Pandas DataFrame | 40,134,313 | <p>I have a calculated column in a Pandas DataFrame which needs to be assigned base upon a condition. For example:</p>
<pre><code>if(data['column_a'] == 0):
data['column_c'] = 0
else:
data['column_c'] = data['column_b']
</code></pre>
<p>However, that returns an error:</p>
<pre>
ValueError: The truth value o... | 0 | 2016-10-19T14:29:09Z | 40,134,518 | <p>use where() and notnull() </p>
<pre><code> data['column_c'] = data['column_b'].where(data['column_a'].notnull(), 0)
</code></pre>
| 0 | 2016-10-19T14:37:14Z | [
"python",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.