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 |
|---|---|---|---|---|---|---|---|---|---|
unexpected kawrgs ,TypeError at /courses/course/1/1/ | 39,493,533 | <p>I'm getting type error for the pk.
Something like:</p>
<p>step_detail() got an unexpected keyword argument 'pk' for the second one in /courses/course/1/1, where as it has been taken care in the following method of step_detail. What am I doing wrong? </p>
<p>views.py</p>
<pre><code>from django.shortcuts import ren... | 0 | 2016-09-14T14:50:58Z | 39,493,664 | <p>You are using 2 different variable names:</p>
<ul>
<li><code>pk</code> in <code>urls.py</code></li>
<li><code>step_pk</code> in <code>views.py</code></li>
</ul>
<p>You should use the same name.</p>
| 1 | 2016-09-14T14:56:44Z | [
"python",
"django"
] |
Flask : how to pass variables between html pages app route | 39,493,606 | <p>I have a getvlanconfig.html page with a form that collects information like vlanid and vlannetwork. I want to be able to pass that information over to the page showvlanconfig.html that loads when the form is submitted.
I am new to Flask and from whatever lookup i could do, I was unable to find out the best way to d... | -1 | 2016-09-14T14:54:07Z | 39,493,863 | <p>Use the session to store data between requests from the same client.</p>
<pre><code>from flask import session
def getvlan():
session['vlanid'] = request.form['vlanid']
return redirect(url_for('showvlan'))
def showvlan():
vlanid = session['vlanid']
...
</code></pre>
<p>Use a database (or other ext... | 0 | 2016-09-14T15:04:34Z | [
"python",
"html",
"flask"
] |
Json data not reaching Django properly | 39,493,607 | <p>In my project, the frontend is in Angular2,
I'm making a POST request to a Django url like this:</p>
<pre><code>let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(this.myMetadata);
let req = this.http.post(this.url,bo... | 0 | 2016-09-14T14:54:10Z | 39,493,697 | <blockquote>
<p>Is there a way to convert a string to a dictionary?</p>
</blockquote>
<p>Yes just use the json module</p>
<pre><code>import json
...
if request.method == 'POST':
data = json.loads(request.body)
logger.info(type(data))
</code></pre>
| 0 | 2016-09-14T14:58:08Z | [
"python",
"json",
"django"
] |
I need to add a '$' to my output of denominations used | 39,493,699 | <p><a href="http://ideone.com/QxPDFh" rel="nofollow">http://ideone.com/QxPDFh</a></p>
<p>This is my program that I am working on but I need the <code>amount_denom</code> to display the $ with the number. How would I get this done? I need to fix the print statement but how? I am new to coding so sometimes I can't see t... | 0 | 2016-09-14T14:58:13Z | 39,494,080 | <p>Can you add a <code>$</code> to your <code>print</code> statement?</p>
<pre><code>print("${0: 2d}{1:8.2f}".format(amount_denom[i],used_denom[i]),end = "")
</code></pre>
<p>or:</p>
<pre><code>print("{0: 2d} ${1:8.2f}".format(amount_denom[i],used_denom[i]),end = "")
</code></pre>
<p>You can place the <code>$</code... | 0 | 2016-09-14T15:16:04Z | [
"python"
] |
Generate unique alphanumeric ID such as in the UK NINO (SN-60-70-45-B) format | 39,493,709 | <p>How can I generate unique alphanumeric ID such as in the UK NINO (SN-60-70-45-B) format? I want to use this ID to uniquely identify the applications and also to be able to associate these IDs to their medical, tax records and so on.</p>
| -1 | 2016-09-14T14:58:33Z | 39,513,501 | <p>Assuming the question is for python, start here:
<a href="https://docs.python.org/2/library/uuid.html#module-uuid" rel="nofollow">uuid</a></p>
<p>There is most likely a nicer way to do it but this should help:</p>
<pre><code>import uuid, re
myUID = uuid.uuid1()
myNum = str(myUID.int).replace("-", "")[:6]
myLet = r... | 0 | 2016-09-15T14:19:02Z | [
"python"
] |
Python how does == work for float/double? | 39,493,732 | <p>I know using <code>==</code> for float is generally not safe. But does it work for the below scenario?</p>
<ol>
<li>Read from csv file A.csv, save first half of the data to csv file B.csv without doing anything.</li>
<li>Read from both A.csv and B.csv. Use <code>==</code> to check if data match everywhere in the fi... | 0 | 2016-09-14T14:59:24Z | 39,493,833 | <p>The same string representation will become the same float representation when put through the same parse routine. The float inaccuracy issue occurs either when mathematical operations are performed on the values or when high-precision representations are used, but equality on low-precision values is no reason to wor... | 3 | 2016-09-14T15:03:34Z | [
"python",
"pandas",
"floating-point"
] |
Python how does == work for float/double? | 39,493,732 | <p>I know using <code>==</code> for float is generally not safe. But does it work for the below scenario?</p>
<ol>
<li>Read from csv file A.csv, save first half of the data to csv file B.csv without doing anything.</li>
<li>Read from both A.csv and B.csv. Use <code>==</code> to check if data match everywhere in the fi... | 0 | 2016-09-14T14:59:24Z | 39,498,946 | <p>No, you cannot assume that this will work all the time.</p>
<p>For this to work, you need to know that the text value written out by Pandas when it's writing to a CSV file recovers the exact same value when read back in (again using Pandas). But by default, the Pandas <code>read_csv</code> function sacrifices accur... | 3 | 2016-09-14T20:16:48Z | [
"python",
"pandas",
"floating-point"
] |
Make nested dictionary, unflatten | 39,493,783 | <p>I have a list of lists containing key and value like so:</p>
<pre><code>[
['mounts:device', '/dev/sda3'],
['mounts:fstype:[0]', 'ext1'],
['mounts:fstype:[1]', 'ext3']
]
</code></pre>
<p>Well I can easily change the list to this </p>
<h1>(Lists arent seperated by ':')</h1>
<pre><code>[
['mounts:device', ... | 0 | 2016-09-14T15:01:23Z | 39,494,221 | <pre><code>input1=[
['mounts:device', '/dev/sda3'],
['mounts:fstype:[0]', 'ext1'],
['mounts:fstype:[1]', 'ext3']
]
input2={x[1]:x[0].split(':')[1] for x in input1}
input3=['ext3', 'ext1', '/dev/sda3']
input4=['fstype', 'fstype', 'device']
res={}
for x,y in zip(input3, input4):
res.setdefault(y,[]).append(x)
r... | 0 | 2016-09-14T15:23:44Z | [
"python",
"python-3.x",
"dictionary"
] |
Make nested dictionary, unflatten | 39,493,783 | <p>I have a list of lists containing key and value like so:</p>
<pre><code>[
['mounts:device', '/dev/sda3'],
['mounts:fstype:[0]', 'ext1'],
['mounts:fstype:[1]', 'ext3']
]
</code></pre>
<p>Well I can easily change the list to this </p>
<h1>(Lists arent seperated by ':')</h1>
<pre><code>[
['mounts:device', ... | 0 | 2016-09-14T15:01:23Z | 39,494,699 | <p>Here is a solution using a <strong>tree</strong> of <code>dict</code>:</p>
<pre><code>import collections
def tree():
return collections.defaultdict(tree)
def unflatten(pair_list):
root = tree()
for mount, path in pair_list:
parts = mount.split(":")
curr = root
for part in part... | 1 | 2016-09-14T15:46:05Z | [
"python",
"python-3.x",
"dictionary"
] |
SQLAlchemy ThreadPoolExecutor "Too many clients" | 39,493,785 | <p>I wrote a script with this sort of logic in order to insert many records into a PostgreSQL table as they are generated.</p>
<pre><code>#!/usr/bin/env python3
import asyncio
from concurrent.futures import ProcessPoolExecutor as pool
from functools import partial
import sqlalchemy as sa
from sqlalchemy.ext.declarati... | 0 | 2016-09-14T15:01:35Z | 39,508,857 | <p>It looks like you're opening a lot of new connections without closing them, try to add engine.dispose() after:</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor as pool
session_maker = sa.orm.sessionmaker(bind=engine, autocommit=True)
Session = sa.orm.scoped_session(session_maker)
def task(value):... | 0 | 2016-09-15T10:31:27Z | [
"python",
"multithreading",
"postgresql",
"sqlalchemy",
"python-asyncio"
] |
SQLAlchemy ThreadPoolExecutor "Too many clients" | 39,493,785 | <p>I wrote a script with this sort of logic in order to insert many records into a PostgreSQL table as they are generated.</p>
<pre><code>#!/usr/bin/env python3
import asyncio
from concurrent.futures import ProcessPoolExecutor as pool
from functools import partial
import sqlalchemy as sa
from sqlalchemy.ext.declarati... | 0 | 2016-09-14T15:01:35Z | 39,760,228 | <p>It turns out that the problem is <code>engine.dispose()</code>, which, in the words of Mike Bayer (zzzeek) "is leaving PG connections lying open to be garbage collected."</p>
<p>Source: <a href="https://groups.google.com/forum/#!topic/sqlalchemy/zhjCBNebnDY" rel="nofollow">https://groups.google.com/forum/#!topic/sq... | 1 | 2016-09-29T02:01:55Z | [
"python",
"multithreading",
"postgresql",
"sqlalchemy",
"python-asyncio"
] |
Tkinter class module reference exception | 39,493,805 | <p>I'm having some trouble calling a module(updateUI) within a class (Eventsim).</p>
<p>The line Sim = EventSim() throws an exception because it's missing an argument (parent). I can't figure out how to fix this / reference the parent object.</p>
<p>This is my first attempt wit Tkinter and my python knowledge is also... | 0 | 2016-09-14T15:02:19Z | 39,494,069 | <p>The <code>parent</code> should be <code>root</code>. So, replacing:</p>
<pre><code>def main():
root = Tk()
root.geometry("300x300+750+300")
app = EventSim(root)
root.mainloop()
Sim = EventSim()
Sim.updateUI('1','1','1')
main()
</code></pre>
<p>with:</p>
<pre><code>root = Tk()
root.geometry("300x... | 2 | 2016-09-14T15:15:15Z | [
"python",
"class",
"tkinter"
] |
Tkinter class module reference exception | 39,493,805 | <p>I'm having some trouble calling a module(updateUI) within a class (Eventsim).</p>
<p>The line Sim = EventSim() throws an exception because it's missing an argument (parent). I can't figure out how to fix this / reference the parent object.</p>
<p>This is my first attempt wit Tkinter and my python knowledge is also... | 0 | 2016-09-14T15:02:19Z | 39,494,169 | <p>Remove <code>Sim = EventSim()</code> and move <code>Sim.updateUI('1','1','1')</code> to <code>main</code>: </p>
<pre><code>def main():
root = Tk()
root.geometry("300x300+750+300")
app = EventSim(root)
app.updateUI('1','1','1')
root.mainloop()
main()
</code></pre>
| 1 | 2016-09-14T15:20:59Z | [
"python",
"class",
"tkinter"
] |
Pandas DataFrame with levels of graph nodes and edges to square matrix | 39,493,963 | <p>My Googlefu has failed me!</p>
<p>I have a Pandas <code>DataFrame</code> of the form:</p>
<pre><code>Level 1 Level 2 Level 3 Level 4
-------------------------------------
A B C NaN
A B D E
A B D F
G H NaN NaN
G ... | 1 | 2016-09-14T15:09:22Z | 39,494,660 | <p>Try this code:</p>
<pre><code>df = pd.DataFrame({'level_1':['A', 'A', 'A', 'G', 'G'], 'level_2':['B', 'B', 'B', 'H', 'I'],
'level_3':['C', 'D', 'D', np.nan, 'J'], 'level_4':[np.nan, 'E', 'F', np.nan, 'K']})
</code></pre>
<p>Your input dataframe is:</p>
<pre><code> level_1 level_2 level_3 level_4
0 A ... | 1 | 2016-09-14T15:43:42Z | [
"python",
"pandas",
"graph",
"digraphs"
] |
Using LabelEncoder for a series in scikitlearn | 39,494,001 | <p>I have a Column in a Dataset which has categorical values and I want to convert them in Numerical values. I am trying to use LabelEncoder but get errors doing so.</p>
<pre><code>from sklearn.preprocessing import LabelEncoder
m = hsp_train["Alley"]
m_enc = LabelEncoder()
j = m_enc.fit_transform(m)
</code></pre>
<p>... | 1 | 2016-09-14T15:11:30Z | 39,495,062 | <p>It's obviously clear that you have missing values in your series. If you want to remove <code>NaN</code> values from your series, just do <code>hsp_train["Alley"].dropna()</code></p>
<p><strong>Illustration:</strong></p>
<pre><code>df = pd.DataFrame({'Categorical': ['apple', 'mango', 'apple',
... | 2 | 2016-09-14T16:06:54Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn"
] |
Custom distribution in scipy with pdf given | 39,494,046 | <p>I try to define a custom distribution with pdf given via scipy.stats</p>
<pre><code>import numpy as np
from scipy.stats import rv_continuous
class CustomDistribution(rv_continuous):
def __init__(self, pdf=None):
super(CustomDistribution, self).__init__()
self.custom_pdf = pdf
print "Ini... | 1 | 2016-09-14T15:14:07Z | 39,495,944 | <p>This seems to do what you want. An instance of the class must be given a value for the lambda parameter each time the instance is created. rv_continuous is clever enough to infer items that you do not supply but you can, of course, offer more definitions that I have here.</p>
<pre><code>from scipy.stats import rv_c... | 0 | 2016-09-14T16:58:23Z | [
"python",
"scipy",
"statistics"
] |
Progress bar for pandas.DataFrame.to_sql | 39,494,056 | <p>I want to migrate data from a large csv file to sqlite3 database.</p>
<p>My code on Python 3.5 using pandas:</p>
<pre><code>con = sqlite3.connect(DB_FILENAME)
df = pd.read_csv(MLS_FULLPATH)
df.to_sql(con=con, name="MLS", if_exists="replace", index=False)
</code></pre>
<p>Is it possible to print current status (pr... | 2 | 2016-09-14T15:14:41Z | 39,495,229 | <p>Unfortuantely <code>DataFrame.to_sql</code> does not provide a chunk-by-chunk callback, which is needed by tqdm to update its status. However, you can process the dataframe chunk by chunk:</p>
<pre><code>import sqlite3
import pandas as pd
from tqdm import tqdm
DB_FILENAME='/tmp/test.sqlite'
def chunker(seq, size)... | 2 | 2016-09-14T16:15:34Z | [
"python",
"sqlite",
"pandas",
"dataframe",
"tqdm"
] |
Boto3 - Delete_snapshot not evaluating variables | 39,494,092 | <p>I'm trying to run boto3 to loop through snapshots older than 14 days.
It can find all the snapshots older than 14 days fine, and I've verified that all that works okay. The problem is when it runs through the dictionary trying to delete, it looks like the function isn't correctly evaluating the variable (See below).... | 1 | 2016-09-14T15:16:57Z | 39,506,812 | <p>As it turns out, referencing straight from the dictionary is a bad idea. It needs to be wrapped in str() and provided with the DryRun=False option too.</p>
| 0 | 2016-09-15T08:52:28Z | [
"python",
"boto3",
"amazon-api"
] |
Boto3 - Delete_snapshot not evaluating variables | 39,494,092 | <p>I'm trying to run boto3 to loop through snapshots older than 14 days.
It can find all the snapshots older than 14 days fine, and I've verified that all that works okay. The problem is when it runs through the dictionary trying to delete, it looks like the function isn't correctly evaluating the variable (See below).... | 1 | 2016-09-14T15:16:57Z | 39,529,383 | <p>I would doubt that the SnapshotId might not be passing as a string.
Change the SnapshotId to a string format and pass it for deletion.
<code>str(snapshot['SnapshotId'])</code></p>
| 0 | 2016-09-16T10:36:11Z | [
"python",
"boto3",
"amazon-api"
] |
Is there any column match or row match function in python? | 39,494,152 | <p>I have two data frame lets say:</p>
<p>dataframe A with column 'name'</p>
<pre><code> name
0 4
1 2
2 1
3 3
</code></pre>
<p>Another dataframe B with two columns i.e. name and value</p>
<pre><code> name value
0 3 5
1 2 6
2 4 7
3 1 8
</code></pre>
<p>I want to rearrange the va... | 0 | 2016-09-14T15:19:59Z | 39,494,321 | <p>Here are two options:</p>
<pre><code>dfB.set_index('name').loc[dfA.name].reset_index()
Out:
name value
0 4 7
1 2 6
2 1 8
3 3 5
</code></pre>
<p>Or, </p>
<pre><code>dfA['value'] = dfA['name'].map(dfB.set_index('name')['value'])
dfA
Out:
name value
0 4 7
1 ... | 1 | 2016-09-14T15:28:27Z | [
"python",
"pandas",
"dataframe"
] |
PEP8 import conventions | 39,494,192 | <p>I'm trying to stick to the best practices when it comes to import modules, I'm trying to understand what <a href="https://www.python.org/dev/peps/pep-0008/#imports" rel="nofollow">PEP8</a> says about this. </p>
<p>Let's say my framework has hundred of classes and few dozen of packages. For instance, PyQt5 or sympy ... | 0 | 2016-09-14T15:22:19Z | 39,494,309 | <p>There is no recommendation because it depends too much on your project, and what potential name clashes you may experience. If you don't already have a <code>QPoint</code> object (either of your own, or potentially from a different package), you may find it easier to read and write just the <code>QPoint</code> symbo... | 0 | 2016-09-14T15:28:02Z | [
"python",
"pyqt",
"pep8"
] |
How to plot data after groupby | 39,494,246 | <p>I have a data frame similar to this</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['1','3','1','2','3','1','2','2','1','1'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['age','data']]
print(df) #printing dataframe.
</code></pre>
<p>I performed the groupby function o... | 1 | 2016-09-14T15:25:10Z | 39,494,317 | <p>Try:</p>
<pre><code>group_data = group_data.reset_index()
</code></pre>
<p>in order to get rid of the multiple index that the <code>groupby()</code> has created for you.</p>
<p>Your <code>print(group_data)</code> will give you this:</p>
<pre><code>In [24]: group_data = df.groupby(['age','data'])['COUNTER'].sum()... | 2 | 2016-09-14T15:28:22Z | [
"python",
"pandas",
"matplotlib"
] |
How to plot data after groupby | 39,494,246 | <p>I have a data frame similar to this</p>
<pre><code>import pandas as pd
df = pd.DataFrame([['1','3','1','2','3','1','2','2','1','1'], ['ONE','TWO','ONE','ONE','ONE','TWO','ONE','TWO','ONE','THREE']]).T
df.columns = [['age','data']]
print(df) #printing dataframe.
</code></pre>
<p>I performed the groupby function o... | 1 | 2016-09-14T15:25:10Z | 39,495,809 | <p>Try with this:</p>
<pre><code># This is a great tool to add plots to jupyter notebook
% matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
# Params get plot bigger
plt.rcParams["axes.labelsize"] = 16
plt.rcParams["xtick.labelsize"] = 14
plt.rcParams["ytick.labelsize"] = 14
plt.rcParams["legend.f... | 0 | 2016-09-14T16:49:52Z | [
"python",
"pandas",
"matplotlib"
] |
too many legend with array column data in matplotlib | 39,494,254 | <p>I try to plot simple rotation matrix result with list data. but My figure with result array have so many index as screen dump image. and the second plot is not exact with my attribute(line style, etc.)
I guess that I do mistake array handling to plot but don't know what.
Any comments are welcome. Thanks in advance.... | -1 | 2016-09-14T15:25:28Z | 39,501,403 | <p>The issue is that you are trying to plot the two rows of <code>result_a</code> as if they were 1-dimensional <code>np.ndarray</code>s, when in fact they are <code>np.matrix</code> which are always 2-dimensional. See for yourself:</p>
<pre><code>>>> result_a[0].shape
(1, 19)
</code></pre>
<p>To remedy thi... | 0 | 2016-09-15T00:10:13Z | [
"python",
"arrays",
"matplotlib",
"legend"
] |
Multiple jsons to csv | 39,494,294 | <p>I have multiple files, each containing multiple highly nested json <em>rows</em>. The two first rows of one such file look like:</p>
<pre><code>{
"u":"28",
"evv":{
"w":{
"1":400,
"2":{
"i":[{
"l":14,
"c":"7",
... | 1 | 2016-09-14T15:27:19Z | 39,496,177 | <p>Please check if this (python3) solution works for you. </p>
<pre><code>import json
import csv
with open('test.json') as data_file:
with open('output.csv', 'w', newline='') as fp:
for line in data_file:
data = json.loads(line)
output = [[data['u'], data['evv']['w'].get('1'), data... | 1 | 2016-09-14T17:14:09Z | [
"python",
"json",
"excel",
"csv"
] |
Multiple jsons to csv | 39,494,294 | <p>I have multiple files, each containing multiple highly nested json <em>rows</em>. The two first rows of one such file look like:</p>
<pre><code>{
"u":"28",
"evv":{
"w":{
"1":400,
"2":{
"i":[{
"l":14,
"c":"7",
... | 1 | 2016-09-14T15:27:19Z | 39,496,778 | <p>No, there is no general-purpose program that does precisely what you ask for. </p>
<p>You can, however, write a Python program that does it.</p>
<p>This program might do what you want. It does not have any code specific to your key names, but it is specific to your file format.</p>
<ul>
<li>It can take several fi... | 1 | 2016-09-14T17:53:47Z | [
"python",
"json",
"excel",
"csv"
] |
What are the requirements of a protocol factory in python asyncio? | 39,494,332 | <p>I am looking at the example of the <a href="https://docs.python.org/3/library/asyncio-protocol.html#udp-echo-server-protocol" rel="nofollow">UDP echo server</a>:</p>
<pre><code>import asyncio
class EchoServerProtocol:
def connection_made(self, transport):
self.transport = transport
def datagram_re... | 1 | 2016-09-14T15:29:08Z | 39,495,859 | <h3>What defines a <em>protocol instance</em>?</h3>
<p>A protocol is a class you define that implements one of the interfaces defined in the <a href="https://docs.python.org/3/library/asyncio-protocol.html#protocol-classes" rel="nofollow">Protocols section</a>, i.e. provides implementations for a set of callbacks, e.g... | 2 | 2016-09-14T16:53:49Z | [
"python",
"python-3.5",
"python-asyncio"
] |
Drop Item If More Than 1 Item Present | 39,494,356 | <p>I'm working on a piece of code, and it is for a little AI creature to randomly come into a room, and look to see if there is anything there. If there is anything that the player has touched before, then it takes the item. The next room it goes to it drops that item and may pick up a new one. So far, I have:</p>
<pr... | 0 | 2016-09-14T15:30:20Z | 39,494,682 | <p><code>goblininventory.remove([0])</code> is incorrect. You should use <code>goblininventory.pop()</code> to remove the first element from the list.</p>
<p>See here for more info on <code>remove</code> and <code>pop</code>: <a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow... | 0 | 2016-09-14T15:45:24Z | [
"python"
] |
GAE Python code MUCH slower in production than locally | 39,494,684 | <p>In my Python GAE app, the following snippet of code is MUCH slower in production than when run locally. The processing goes like this:</p>
<ol>
<li>A text file of about 1 MB is loaded in a POST. Each line of the text file is an "item".</li>
<li>My code creates a list of items from the text file and checks for dup... | 2 | 2016-09-14T15:45:26Z | 39,516,803 | <p>It's not at all unexpected that GAE production would run slower than locally -- Depending on your <a href="https://cloud.google.com/appengine/docs/about-the-standard-environment#instance_classes" rel="nofollow">instance class</a>, your production CPU can be throttled as low as 600MHz which is significantly slower th... | 4 | 2016-09-15T17:15:46Z | [
"python",
"performance",
"google-app-engine"
] |
Converting time string 11:00am/pm into UTC in 24 hour format | 39,494,737 | <p>I have time string <code>11:15am</code> or <code>11:15pm</code>.
I am trying to convert this string into UTC timezone with 24 hour format.</p>
<p>FROM EST to UTC</p>
<p>For example: When I pass <code>11:15am</code> It should convert into <code>15:15</code> and when I pass <code>11:15pm</code> then it should conver... | 1 | 2016-09-14T15:48:25Z | 39,494,831 | <p>To convert the time from 12 hours to 24 hours format, you may use below code:</p>
<pre><code>from datetime import datetime
new_time = datetime.strptime('11:15pm', '%I:%M%p').strftime("%H:%M")
# new_time: '23:15'
</code></pre>
<p>In order to convert time from <code>EST</code> to <code>UTC</code>, the most reliable ... | 1 | 2016-09-14T15:53:05Z | [
"python",
"python-2.x"
] |
Converting time string 11:00am/pm into UTC in 24 hour format | 39,494,737 | <p>I have time string <code>11:15am</code> or <code>11:15pm</code>.
I am trying to convert this string into UTC timezone with 24 hour format.</p>
<p>FROM EST to UTC</p>
<p>For example: When I pass <code>11:15am</code> It should convert into <code>15:15</code> and when I pass <code>11:15pm</code> then it should conver... | 1 | 2016-09-14T15:48:25Z | 39,496,107 | <p>Developed the following script using provided options/solutions to satisfy my requirement. </p>
<p>def appointment_time_string(time_str):</p>
<pre><code> import datetime
import pytz
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.s... | 0 | 2016-09-14T17:08:08Z | [
"python",
"python-2.x"
] |
How to get bandwidth from eth0 use python script? | 39,494,766 | <p>Python in ubuntu ifconfig : How to get bandwidth value from device eth0 use os modules ifconfig in python script, like this: </p>
<pre><code>$python script.py eth0
UP: 5 KB/sec
DOWN: 30.5 KB/sec
</code></pre>
<p>where output script can change every second time and value bandwidth use Kb/s
?</p>
| 1 | 2016-09-14T15:49:54Z | 39,495,392 | <p>You can use <a href="https://pythonhosted.org/psutil/" rel="nofollow">Psutil</a> to get information about network interfaces like this:</p>
<pre><code>psutil.net_io_counters(pernic=True)
</code></pre>
<p>This will return something like the following</p>
<pre><code>{'awdl0': snetio(bytes_sent=0L, bytes_recv=0L, pa... | 0 | 2016-09-14T16:25:39Z | [
"python",
"ubuntu",
"module",
"bandwidth"
] |
How to import .e00 ArcGIS file in GeoPandas | 39,494,787 | <p>I'm trying to work with files from this site:</p>
<p><a href="ftp://ftp.epa.gov/castnet/tdep/grids/" rel="nofollow">NADP Website</a></p>
<p>The files are <code>.e00</code> format. When I attempt to open them with GeoPandas, I get a message that they appear to be compressed.</p>
<p>If I try using e00conv or AVCE0... | 0 | 2016-09-14T15:51:21Z | 39,500,205 | <p>I finally figured this out. In this instance, even though the .e00 format is not usually used to store raster file, these files are raster images. They open fine with rasterio. </p>
| 0 | 2016-09-14T21:52:04Z | [
"python",
"gis",
"arcgis",
"geopandas",
"fiona"
] |
Pass file descriptor via a dbus function call from Python (aka call flatpak's HostCommand) | 39,494,813 | <p>I want to call Flatpak's <a href="https://github.com/flatpak/flatpak/commit/c8df0e6208e96e2743aa63a824d2ea7d19ce4cde" rel="nofollow">new Development DBus service to spawn a process on the host</a>, rather than in the sandbox.</p>
<p>To call the DBus service, I've come up with the following piece of code:</p>
<pre>... | 2 | 2016-09-14T15:52:19Z | 39,677,775 | <p>To investigate whether my code is causing the same messages to be sent over the bus, I started <code>dbus-monitor</code> to check what happens if a known-good client sends that message. I got the following:</p>
<pre><code>method call time=14743.5 sender=:1.6736 -> destination=org.freedesktop.Flatpak serial=8 pa... | 1 | 2016-09-24T15:02:41Z | [
"python",
"file-descriptor",
"dbus",
"flatpak"
] |
Django: How to put existing fields when displaying form for UpdateView? | 39,494,896 | <p>I'm making an episode tracker website and when I want the user to edit a show, the form provided starts with empty fields. How do I fill the form with already existing fields? For example, when a user is watching a show and is originally at episode 5, how do I call the update form with the Episode field already at 5... | 0 | 2016-09-14T15:57:03Z | 39,495,040 | <p>You can fill a form with the values in an UpdateView with</p>
<pre><code>def get_initial(self):
return { 'field1': 'something', 'field2': 'more stuff' }
</code></pre>
<p>Also the UpdateView inherits from the SingleObjectMixin, which provides <code>get_object</code> and <code>get_queryset</code>, so you could u... | 0 | 2016-09-14T16:05:41Z | [
"python",
"django"
] |
How to divide two dataframes with different length and duplicated indexs in Python | 39,494,981 | <p>Here is my code and I want to get the expected output, but, division of dataframes does not work, what is wrong here? </p>
<pre><code>import pandas as pd
data1 = {'name':['A', 'C', 'D'], 'cond_a':['B','B','B'], 'value':[10,12,14]}
data2 = {'name':['A', 'C', 'D','D','A'], 'cond_a':['G','G','G','G','G'], 'value':[... | 2 | 2016-09-14T16:01:35Z | 39,495,296 | <p>As long as <code>df1</code> has a unique index, you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> it on <code>df2</code> when performing the division:</p>
<pre><code>df2['new_col'] = df2['value'] / df1['value'].reindex(df2.i... | 4 | 2016-09-14T16:19:28Z | [
"python",
"pandas"
] |
How to divide two dataframes with different length and duplicated indexs in Python | 39,494,981 | <p>Here is my code and I want to get the expected output, but, division of dataframes does not work, what is wrong here? </p>
<pre><code>import pandas as pd
data1 = {'name':['A', 'C', 'D'], 'cond_a':['B','B','B'], 'value':[10,12,14]}
data2 = {'name':['A', 'C', 'D','D','A'], 'cond_a':['G','G','G','G','G'], 'value':[... | 2 | 2016-09-14T16:01:35Z | 39,495,300 | <p>What doesn't work in your case is not DataFrame division, which you can easily check:</p>
<pre><code>df2['value'] / df1['value']
Out[]:
name
A 0.500000
A 0.200000
C 0.500000
D 0.500000
D 0.214286
Name: value, dtype: float64
</code></pre>
<p>The problem is that in the process of this division <code>... | 1 | 2016-09-14T16:19:44Z | [
"python",
"pandas"
] |
when trying to run celery local I get an error message | 39,495,003 | <p>This is my file structure</p>
<pre><code>venv/
|-src/
|-gettingstarted/
| |-settings/
| |-__init__.py
| |-base.py
| |-local.py
| |-production.py
|
|-blog/
| |-__init__.py
| |-admin.py
| |-forms.py
| |-models.py
| |-tasks.py
| |-urls.py
| |-views.... | 0 | 2016-09-14T16:02:59Z | 39,495,595 | <p>You're getting a long warning, telling you not to use <em>pickle</em> in case <a href="http://docs.celeryproject.org/en/latest/faq.html#isn-t-using-pickle-a-security-concern" rel="nofollow">you're not familiar with it's possible side effects</a>. So it's better to set celery serializer to use json.</p>
<pre><code>C... | 0 | 2016-09-14T16:36:34Z | [
"python",
"django",
"celery",
"relativelayout",
"file-structure"
] |
Persistent history in python cmd module | 39,495,024 | <p>Is there any way to configure the <a href="https://docs.python.org/2/library/cmd.html" rel="nofollow">CMD module from Python</a> to keep a persistent history even after the interactive shell has been closed?</p>
<p>When I press the up and down keys I would like to access commands that were previously entered into t... | 2 | 2016-09-14T16:04:19Z | 39,495,060 | <p><code>readline</code> automatically keeps a history of everything you enter. All you need to add is hooks to load and store that history.</p>
<p>Use <a href="https://docs.python.org/2/library/readline.html#readline.read_history_file" rel="nofollow"><code>readline.read_history_file(filename)</code></a> to read a his... | 1 | 2016-09-14T16:06:50Z | [
"python",
"readline",
"python-module",
"python-cmd"
] |
Making Plot of Numpy Array Values | 39,495,146 | <p>I have a large numpy.ndarray that I want to make a plot of, where the x axis has to do with the values in the array and the y axis shows how often that value has appeared in the array. To be clear, I don't care about the order of the data in the array or if their order gets screwed up, I just want to take the numbe... | 1 | 2016-09-14T16:10:56Z | 39,496,906 | <p>'Binning' is definitely a histogram feature but I get the impression you want a simple pivot table. How about:</p>
<ol>
<li>Remove undesired value</li>
<li>Convert your numpy array to dataframe</li>
<li>Create pivot table from dataframe</li>
<li>Plot results</li>
</ol>
<hr>
<pre><code>import numpy as np
import p... | 0 | 2016-09-14T18:03:40Z | [
"python",
"arrays",
"numpy",
"matplotlib"
] |
Making Plot of Numpy Array Values | 39,495,146 | <p>I have a large numpy.ndarray that I want to make a plot of, where the x axis has to do with the values in the array and the y axis shows how often that value has appeared in the array. To be clear, I don't care about the order of the data in the array or if their order gets screwed up, I just want to take the numbe... | 1 | 2016-09-14T16:10:56Z | 39,497,035 | <p>The same thing Nick Braunage proposed, but without pandas:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
a = np.random.randint(10, size=100) # or use yourarray.ravel() here to make it flat
num, bins, _ = plt.hist(a)
plt.show()
</code></pre>
<p>or</p>
<pre><code>num, bins = np.histogram(a)
... | 0 | 2016-09-14T18:12:31Z | [
"python",
"arrays",
"numpy",
"matplotlib"
] |
Python3 for-loop even or odd | 39,495,160 | <p>Hi i got stuck in an exercise i have in school. and could use some help. </p>
<p>Create a for-loop that goes through the numbers:</p>
<pre><code>67,2,12,28,128,15,90,4,579,450
</code></pre>
<p>If the current number is even, you should add it to a variable and if the
current number is odd, you should subtract it f... | 1 | 2016-09-14T16:11:43Z | 39,495,285 | <p>It looks like you need to adjust your condition mostly.</p>
<pre><code>def listSum(a):
for num in [67, 2, 12, 28, 128, 15, 90, 4, 579, 450]:
if(num % 2 == 0): #subtle difference here.
a += num
else:
a -= num
return a
</code></pre>
<p>this will see just a subtle difference. </p>
| 0 | 2016-09-14T16:18:50Z | [
"python",
"python-3.x",
"for-loop"
] |
Python3 for-loop even or odd | 39,495,160 | <p>Hi i got stuck in an exercise i have in school. and could use some help. </p>
<p>Create a for-loop that goes through the numbers:</p>
<pre><code>67,2,12,28,128,15,90,4,579,450
</code></pre>
<p>If the current number is even, you should add it to a variable and if the
current number is odd, you should subtract it f... | 1 | 2016-09-14T16:11:43Z | 39,495,542 | <p>I think it would make more sense if your function input is the list and not the return value. Also (as others have noted) you need <code>num % 2 == 0</code> and your indentation is not quite right. Try this instead:</p>
<pre><code>def listSum(l):
ans = 0
for num in l:
if num % 2 == 0:
ans += num
e... | 0 | 2016-09-14T16:32:44Z | [
"python",
"python-3.x",
"for-loop"
] |
Immediate vs load-on-first-access availability | 39,495,181 | <p>The <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#adding-and-updating-objects" rel="nofollow">docs say</a> (at the end of the linked section):</p>
<blockquote>
<p>After the Session inserts new rows in the database, all newly generated identifiers and database-generated defaults become available... | 0 | 2016-09-14T16:12:52Z | 39,499,583 | <p>SQLAlchemy uses <code>INSERT .. RETURNING</code> for DBs that support it to fetch primary keys, or special functions like <a href="http://dev.mysql.com/doc/refman/5.7/en/mysql-insert-id.html" rel="nofollow"><code>mysql_insert_id</code></a> for DBs that don't.</p>
<p>For default values, it tries to use <code>RETURNI... | 1 | 2016-09-14T21:01:16Z | [
"python",
"sqlalchemy"
] |
Immediate vs load-on-first-access availability | 39,495,181 | <p>The <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/tutorial.html#adding-and-updating-objects" rel="nofollow">docs say</a> (at the end of the linked section):</p>
<blockquote>
<p>After the Session inserts new rows in the database, all newly generated identifiers and database-generated defaults become available... | 0 | 2016-09-14T16:12:52Z | 39,506,678 | <p><strong>immediately:</strong> SQLAlchemy gets a primary key from the database for each session object inserted and assigns it to the session object. The session object needs the primary key immediately since, prior to the transaction snapshot being committed, the object enters the persistent state and is added to th... | 1 | 2016-09-15T08:45:31Z | [
"python",
"sqlalchemy"
] |
Noise removal in spatial data | 39,495,287 | <p>I have an array with two different values that characterize this image:
<a href="http://i.stack.imgur.com/rnOYu.png" rel="nofollow"><img src="http://i.stack.imgur.com/rnOYu.png" alt="enter image description here"></a></p>
<p>I would like to keep the linear trends in red and remove the "noise" (single red points). I... | 0 | 2016-09-14T16:19:05Z | 39,508,198 | <p>If there is no way to determine the noise from the signal based on a threshold value (i.e. all the red point have the same value or are just a 1/0 flag), a relatively simple but easy to implement approach could be to look at removing the noise based on the size of the clumps. </p>
<p>Take a look at <a href="http://... | 1 | 2016-09-15T09:58:16Z | [
"python",
"numpy",
"scipy",
"noise-reduction"
] |
Creating Multiple Plots Using Matplotlib | 39,495,298 | <p>I'm trying to create multiple separate plots using Matplotib, then save these to a single PDF document. Here's my code:</p>
<pre><code>pdf = matplotlib.backends.backend_pdf.PdfPages('Activity_Report.pdf')
fig1 = plt.figure(1)
fig1.figure(figsize=(11.69, 8.27))
ax1 = fig1.add_subplot(111)
# ******** product 1 **... | 1 | 2016-09-14T16:19:35Z | 39,495,530 | <p>Your code is a bit over-complicated. These two lines are redundant:</p>
<pre><code>fig1 = plt.figure(1)
fig1.figure(figsize=(11.69, 8.27))
</code></pre>
<p>I would just do:</p>
<pre><code>FIGSIZE = (11.69, 8.27)
fig1, ax1 = plt.subplots(figsize=FIGSIZE)
# plot things
fig2, ax2 = plt.subplots(figsize=FIGSIZE)
#... | 2 | 2016-09-14T16:32:22Z | [
"python",
"matplotlib"
] |
passing arguments python script | 39,495,309 | <p>I am trying to know haw can I pass these files as arguments in a py file, and construct dataframe from these files</p>
<pre><code>pd.read_csv('C:/Users/Demonstrator/Downloads/file1.csv',delimiter=';', parse_dates=[0], infer_datetime_format = True)
df_energy2=pd.read_csv('C:/Users/Demonstrator/Downloads/file2.csv', ... | -3 | 2016-09-14T16:20:02Z | 39,495,444 | <p>Passing arguments is simple. You can have a look at <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">https://docs.python.org/3/library/argparse.html</a></p>
<p>The most easiest way to pass argument to a python script is by adding these line to you python script and modifying them as per need... | 1 | 2016-09-14T16:28:19Z | [
"python",
"pandas"
] |
Sort input file according to first column, no delimiters but spaces | 39,495,312 | <p>I'm a Python beginner and trying to post process the a long txt file which is a list without delimiters, only spaces. I wanna sort it according to the first column. </p>
<p>The code compiles fine, but it only sorts my output file according to the very first value in the first column, but not according to the number... | 0 | 2016-09-14T16:20:08Z | 39,495,330 | <p>you have to sort as numerical, not alphanumerical, so convert your string to integer or float (I don't have all your data, I'm not sure if they're all integers):</p>
<pre><code>lines = sorted(lines, key=lambda line: float(line[0]))
</code></pre>
<p>but it would be even better to sort on all the values by returning... | 1 | 2016-09-14T16:21:43Z | [
"python",
"sorting",
"split",
"lines"
] |
Python - How to choose line in console to read from | 39,495,407 | <p>As I understand it, input() reads a new line every time it's called, but is there a way for me to make it read, say, the third line of input and then read the second line of input without first storing the second line?</p>
| 0 | 2016-09-14T16:26:31Z | 39,495,935 | <p>No. The <code>input()</code> function takes data from standard input stream and returns it somewhere in your code. Then the contents of standard input stream is forgotten. </p>
| 0 | 2016-09-14T16:57:42Z | [
"python",
"input"
] |
How do I install scipy & its optimization module (using Python 2.7.10) | 39,495,417 | <p>I've run the following optimization example code (and alternatives) and it keeps giving me the following error(s) -- </p>
<blockquote>
<p>"Input Error: cannot import optimize" OR "No module named optimize"</p>
</blockquote>
<pre><code>import numpy as np
from scipy import optimize
from scipy.optimize import fmi... | -1 | 2016-09-14T16:27:13Z | 39,496,105 | <p>Can you upgrade <code>scipy</code> to version 0.17? I can't reproduce the error with version 0.17:</p>
<p><code>pip install scipy==0.17.0</code></p>
| 0 | 2016-09-14T17:07:42Z | [
"python",
"numpy",
"optimization",
"scipy"
] |
MySQL python setup error | 39,495,498 | <p>I am following <a href="https://www.tutorialspoint.com/python/python_database_access.htm" rel="nofollow">https://www.tutorialspoint.com/python/python_database_access.htm</a> to connect Python with SQL. </p>
<pre><code>gunzip MySQL-python-1.2.2.tar.gz
tar -xvf MySQL-python-1.2.2.tar
cd MySQL-python-1.2.2
python setu... | 0 | 2016-09-14T16:30:49Z | 39,496,442 | <p>Using Anaconda, you should use <code>conda install <package-name></code></p>
<p><strong>Linux / Windows:</strong> <code>conda install mysql-python</code></p>
<p><strong>Mac OS:</strong> <code>conda install --channel https://conda.anaconda.org/coursera mysql-python</code></p>
<p>Then it will check for depend... | 1 | 2016-09-14T17:31:40Z | [
"python",
"mysql",
"sql",
"python-2.7"
] |
Writing cross-compatible python2/python3 code in pycharm | 39,495,557 | <p>I've taken care to make sure library works on both python2 and python3, but pycharm adds some vexatious red squiggles as seen below </p>
<p><a href="http://i.stack.imgur.com/EBCpC.png"><img src="http://i.stack.imgur.com/EBCpC.png" alt="enter image description here"></a></p>
<p>If I switch the project interpreter t... | 9 | 2016-09-14T16:33:45Z | 40,065,652 | <p>Although it doesn't solve the issue for all cases, you can solve this particular problem by using the <code>future</code> package.</p>
<p>As you can see <a href="http://python-future.org/imports.html#imports-of-builtins">here</a>, the <code>future</code> package provides its own version of <code>builtins</code> for... | 6 | 2016-10-16T00:35:14Z | [
"python",
"pycharm"
] |
How to evaluate an expression in for loop using Python? | 39,495,700 | <p>I want to evaluate an expression inside for loop. I am doing:</p>
<pre><code>for i in range(0,255):
Q[i+1,1] = (np.floor_divide(i, q) * q + q/2)
</code></pre>
<p>but this returns an error saying </p>
<blockquote>
<p>IndexError: index 1 is out of bounds for axis 1 with size 1". </p>
</blockquote>
| 1 | 2016-09-14T16:42:37Z | 39,495,741 | <p>The size is 256x1 but still you have to index with starting at 0. So you need <code>Q[i,0]</code> </p>
| 2 | 2016-09-14T16:45:39Z | [
"python"
] |
How to evaluate an expression in for loop using Python? | 39,495,700 | <p>I want to evaluate an expression inside for loop. I am doing:</p>
<pre><code>for i in range(0,255):
Q[i+1,1] = (np.floor_divide(i, q) * q + q/2)
</code></pre>
<p>but this returns an error saying </p>
<blockquote>
<p>IndexError: index 1 is out of bounds for axis 1 with size 1". </p>
</blockquote>
| 1 | 2016-09-14T16:42:37Z | 39,495,768 | <p><em>python</em> (and <em>numpy</em>) uses <a href="https://en.wikipedia.org/wiki/Zero-based_numbering" rel="nofollow">zero-based indexing</a>, so the first position is 0. You should change your loop to:</p>
<pre><code>for i in range(0,255):
Q[i,0] = (np.floor_divide(i, q) * q + q/2)
# ---^-^---
</code></pre>
| 0 | 2016-09-14T16:47:22Z | [
"python"
] |
How to handle output with Luigi | 39,495,757 | <p>I'm trying to grasp how luigi works, and I get the idea, but actual implementation is a bit harder ;) This is what i have:</p>
<pre><code>class MyTask(luigi.Task):
x = luigi.IntParameter()
def requires(self):
return OtherTask(self.x)
def run(self):
print(self.x)
class OtherTask(luigi... | 0 | 2016-09-14T16:46:35Z | 39,502,239 | <blockquote>
<p>What if I need to output an object to another task?</p>
</blockquote>
<p>Luigi tasks can run in different processes. Therefore you do usually have to write to disk, a database, pickle, or some external mechanism that allows data to be exchanged between the processes (and the existence of which can be... | 2 | 2016-09-15T02:16:22Z | [
"python",
"luigi"
] |
validation of python script for extracting values based on regex | 39,495,815 | <p>I have data of the form: </p>
<pre><code>submission #,scores
882,"Overall evaluation: 1
Invite to interview: 1
Strength or novelty of the idea (1): 4
Strength or novelty of the idea (2): 4
Strength or novelty of the idea (3): 3
Use or provision of open data (1): 3
Use or provision of open data (2): 3
""Open by defa... | -2 | 2016-09-14T16:50:29Z | 39,495,940 | <p>Your <code>map</code> values are each tuples corresponding with the number of items seen and the total of all values seen for the same item.</p>
<p>Dividing the two does indeed return the average (though since they're integers, that result is rounded -- consider casting one or both to floating-point if you want a f... | 1 | 2016-09-14T16:57:59Z | [
"python",
"regex"
] |
How to convert python list of tuples into tree? | 39,495,924 | <p>I have a list of tuples like</p>
<pre><code>list_of_tuples = [(number, name, id, parent_id),
(number, name, id, parent_id),
]
</code></pre>
<p>I am trying to sort it into an ordered structure like:</p>
<pre><code>{
parent: [(id, name), (id, name)],
parent: {parent: [(id, name)]
{
</code></pre>
<... | 2 | 2016-09-14T16:57:21Z | 39,497,141 | <p>I propose to represent the tree nodes as tuples ((id, name), dict_of_children).</p>
<pre><code>list_of_tuples = [(1, 'name1', 1, None),
(2, 'name2', 2, 1),
(3, 'name3', 3, 1),
(4, 'name4', 4, 2),
(5, 'name5', 5, 2),
(6, 'name5', 6, None),
(7, 'name5', 7, 6),
]
def build_tree(list_... | 1 | 2016-09-14T18:20:41Z | [
"python",
"algorithm",
"tree",
"binary-search-tree"
] |
NoReverseMatch at /courses/course/1/1/ | 39,495,962 | <p>I was editing the template to include a hyperlink. But when I do I get NoReverseMatch error.</p>
<p>Reverse for 'views.hello_world' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []</p>
<p>The template file: </p>
<p>layout.html</p>
<pre><code>{% load static from staticfiles %}
<... | 0 | 2016-09-14T16:59:12Z | 39,496,039 | <p>You need to give the URL a name, and refer to that name in the url tag.</p>
<pre><code>url(r'^$', views.hello_world, name='hello_world')
</code></pre>
<p>...</p>
<pre><code><a href="{% url 'hello_world' %}">
</code></pre>
| 0 | 2016-09-14T17:03:45Z | [
"python",
"django"
] |
Uploading files using Browse Button in Jupyter and Using/Saving them | 39,495,994 | <p>I came across <a href="https://github.com/peteut/ipython-file-upload/blob/master/README.rst" rel="nofollow">this snippet</a> for uploading files in Jupyter however I don't know how to save this file on the machine that executes the code or how to show the first 5 lines of the uploaded file. Basically I am looking fo... | 0 | 2016-09-14T17:01:45Z | 39,506,795 | <p><code>_cb</code> is called when the upload finishes. As described in the comment above, you can write to a file there, or store it in a variable. For example:</p>
<pre><code>from IPython.display import display
import fileupload
uploader = fileupload.FileUploadWidget()
def _handle_upload(change):
w = change['o... | 0 | 2016-09-15T08:51:39Z | [
"python",
"file-upload",
"ipython",
"jupyter-notebook",
"ipywidgets"
] |
TypeError in python 3.x ('int' object is not subscriptable) | 39,495,998 | <pre><code>GTIN0 = int(GTIN[0])
</code></pre>
<p>brings up the error</p>
<pre><code>TypeError: 'int' object is not subscriptable
</code></pre>
<p>can someone explain to me why this happens, can you use simple terms as I'm not too experienced at coding so I'm not "in" with the code terms</p>
| -4 | 2016-09-14T17:01:55Z | 39,496,045 | <p>whatever <code>GTIN</code> is, it's not a list or string and it seems to be an integer so therefore there is no subscripting available. The <code>TypeError</code> states that.</p>
| 0 | 2016-09-14T17:04:04Z | [
"python",
"python-3.x",
"typeerror"
] |
TypeError in python 3.x ('int' object is not subscriptable) | 39,495,998 | <pre><code>GTIN0 = int(GTIN[0])
</code></pre>
<p>brings up the error</p>
<pre><code>TypeError: 'int' object is not subscriptable
</code></pre>
<p>can someone explain to me why this happens, can you use simple terms as I'm not too experienced at coding so I'm not "in" with the code terms</p>
| -4 | 2016-09-14T17:01:55Z | 39,496,095 | <p>It looks like GTIN is an integer rather than a list or tuple, so the interpreter is trying to tell you that you can't take element 0 of an integer because it's not a container type.</p>
<p>How did <code>GTIN</code> acquire its value, and why do you think it should be subscriptable?</p>
| 0 | 2016-09-14T17:07:13Z | [
"python",
"python-3.x",
"typeerror"
] |
How to get model instance's attribute in UpdateView (Django)? | 39,496,041 | <p>I have an UpdateView for a model. I want to get the 'car_owner' attribute (of the Newcars model) in the UpdateView. Here's the code.</p>
<p><strong><em>models.py</em></strong></p>
<pre><code>class Newcars(models.Model):
shop_no = models.ForeignKey(Shop, on_delete=models.CASCADE, default=0, related_name='newcar... | 1 | 2016-09-14T17:03:47Z | 39,496,846 | <p>add this method to your view:</p>
<pre><code>def dispatch(self, request, *args, **kwargs):
if self.get_object().car_owner != "sometext":
raise Http404('Car owner does not match.')
return super(NewcarUpdate, self).dispatch(
request, *args, **kwargs)
</code></pre>
<p>You will need to import <... | 1 | 2016-09-14T17:58:20Z | [
"python",
"django",
"python-2.7",
"python-3.x"
] |
How to get model instance's attribute in UpdateView (Django)? | 39,496,041 | <p>I have an UpdateView for a model. I want to get the 'car_owner' attribute (of the Newcars model) in the UpdateView. Here's the code.</p>
<p><strong><em>models.py</em></strong></p>
<pre><code>class Newcars(models.Model):
shop_no = models.ForeignKey(Shop, on_delete=models.CASCADE, default=0, related_name='newcar... | 1 | 2016-09-14T17:03:47Z | 39,496,850 | <p>You could that in the <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_object" rel="nofollow">get_object</a> method:</p>
<pre><code>from django.http import Http404
# ...
class NewcarUpdate(UpdateView):
# ...
def ge... | 1 | 2016-09-14T17:58:47Z | [
"python",
"django",
"python-2.7",
"python-3.x"
] |
Transform a locale-aware unicode string in a valid Decimal number in Python/Django | 39,496,068 | <p>In my <strong>Django 1.7.11</strong> app, I get data formatted with a spanish locale via HTTP. So, in my view, I get a unicode string representing a decimal number in spanish locale:</p>
<pre><code>spanish_number = request.GET.get('some_post_value', 0)
# spanish_number may be u'12,542' now, for example. And may com... | 0 | 2016-09-14T17:05:43Z | 39,496,692 | <p>You're on the right track looking at form <code>DecimalField</code>. If you check its source, you'll see that when set to localize it runs the string through <code>formats.sanitize_separators</code>. You can call this directly to convert to the format <code>Decimal()</code> expects:</p>
<pre><code>import django.uti... | 1 | 2016-09-14T17:47:37Z | [
"python",
"django",
"unicode",
"localization"
] |
Python Groupby omitting columns | 39,496,086 | <p>I have a dataframe that looks like this</p>
<p>dg:</p>
<pre><code>thing1 thing2 thing3 thing4 thing5 thing6 thing7 ID
NAN 1 NAN NAN NAN NAN NAN 222
NAN NAN 3 NAN NAN NAN NAN 222
NAN NAN NAN 2 NAN NAN NAN 222
3 NAN NAN NAN NAN N... | 2 | 2016-09-14T17:06:50Z | 39,496,363 | <p>I found out I had a string "N/A" value in the midst of my np.nan values. Lesson is strings with integers can cause columns to disappear when doing groupby functions. The columns that didn't have "N/A" string didn't disappear upon doing groupby functions. When I replaced "N/A" strings with np.nan the columns didn't d... | 0 | 2016-09-14T17:26:07Z | [
"python",
"pandas",
"dataframe"
] |
Understanding dictionary.get in Python | 39,496,096 | <p>I was reading this really helpful SO post on <a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">sorting dictionaries</a>. One of the most popular answers suggests this:</p>
<pre><code>sorted(dict1, key=dict1.get)
</code></pre>
<p>While this seems to work perfectly fine, I don't g... | 1 | 2016-09-14T17:07:18Z | 39,496,153 | <p>As you have found, <code>get</code> just gets the value corresponding to a given key. <code>sorted</code> will iterate through the iterable it's passed. In this case that iterable is a <code>dict</code>, and iterating through a <code>dict</code> just iterates through its keys. If you want to sort based on the values... | 2 | 2016-09-14T17:12:08Z | [
"python",
"dictionary"
] |
Understanding dictionary.get in Python | 39,496,096 | <p>I was reading this really helpful SO post on <a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">sorting dictionaries</a>. One of the most popular answers suggests this:</p>
<pre><code>sorted(dict1, key=dict1.get)
</code></pre>
<p>While this seems to work perfectly fine, I don't g... | 1 | 2016-09-14T17:07:18Z | 39,496,195 | <pre><code>sorted(dict1, key=dict1.get)
</code></pre>
<p>is a less verbose and more pythonic way of saying:</p>
<pre><code>sorted(dict1, key=lambda x: dict1[x] if x in dict1 else None)
</code></pre>
<p>Bear in mind that iterating on a dictionary will return its keys, therefore the <code>get</code> method takes argum... | 2 | 2016-09-14T17:15:16Z | [
"python",
"dictionary"
] |
Understanding dictionary.get in Python | 39,496,096 | <p>I was reading this really helpful SO post on <a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">sorting dictionaries</a>. One of the most popular answers suggests this:</p>
<pre><code>sorted(dict1, key=dict1.get)
</code></pre>
<p>While this seems to work perfectly fine, I don't g... | 1 | 2016-09-14T17:07:18Z | 39,496,240 | <p>The <code>key</code> argument to <code>sorted</code> is a <em>callable</em> (e.g. a function) which takes one argument.</p>
<p>By default, <code>sorted</code> sorts the values by comparing them to each other. For example:</p>
<pre><code>sorted([2, 3, 1]) # returns [1, 2, 3]
</code></pre>
<p>This is because 1 &l... | 6 | 2016-09-14T17:18:43Z | [
"python",
"dictionary"
] |
Understanding dictionary.get in Python | 39,496,096 | <p>I was reading this really helpful SO post on <a href="http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value">sorting dictionaries</a>. One of the most popular answers suggests this:</p>
<pre><code>sorted(dict1, key=dict1.get)
</code></pre>
<p>While this seems to work perfectly fine, I don't g... | 1 | 2016-09-14T17:07:18Z | 39,496,400 | <p>the second parameter of <code>sorted([dictionnary],[function])</code> is a function and not a value:</p>
<p>This means the method will compare the keys according to the value returned by the function applied to the items.</p>
<p>the parenthesis added after a function call mean you are passing a value, while withou... | 1 | 2016-09-14T17:28:42Z | [
"python",
"dictionary"
] |
search and replace a space with a tab at a specific location in a string | 39,496,234 | <p>I need some help replacing a space with a tab on a string with multiple spaces.
I need to search the string for a time format such as 08:20:10 and replace the space on the end with a tab.
My code is the following:</p>
<pre><code>alert = '9/14/2016 08:20:10 CH1 This is a test.'
str = re.sub (r'(/d{2}:\d{2}:\d{2})(\s... | 2 | 2016-09-14T17:18:31Z | 39,496,320 | <p>First, don't name your variable <code>str</code>, as this masks the built-in function of that name.</p>
<p>Second, I don't see the need for regex here. Simply <code>split</code> the string and then rejoin it however you like.</p>
<pre><code>>>> alert = '9/14/2016 08:20:10 CH1 This is a test.'
>>>... | 0 | 2016-09-14T17:23:51Z | [
"python"
] |
search and replace a space with a tab at a specific location in a string | 39,496,234 | <p>I need some help replacing a space with a tab on a string with multiple spaces.
I need to search the string for a time format such as 08:20:10 and replace the space on the end with a tab.
My code is the following:</p>
<pre><code>alert = '9/14/2016 08:20:10 CH1 This is a test.'
str = re.sub (r'(/d{2}:\d{2}:\d{2})(\s... | 2 | 2016-09-14T17:18:31Z | 39,496,321 | <p>How about a <em>positive lookbehind</em> without a line terminator:</p>
<pre><code>>>> import re
>>>
>>> re.sub(r'(?<=\d{2}:\d{2}:\d{2})\s', '\t', alert)
'9/14/2016 08:20:10\tCH1 This is a test.'
>>>
>>> print(_)
9/14/2016 08:20:10 CH1 This is a test.
</code></pr... | 1 | 2016-09-14T17:23:51Z | [
"python"
] |
search and replace a space with a tab at a specific location in a string | 39,496,234 | <p>I need some help replacing a space with a tab on a string with multiple spaces.
I need to search the string for a time format such as 08:20:10 and replace the space on the end with a tab.
My code is the following:</p>
<pre><code>alert = '9/14/2016 08:20:10 CH1 This is a test.'
str = re.sub (r'(/d{2}:\d{2}:\d{2})(\s... | 2 | 2016-09-14T17:18:31Z | 39,496,323 | <p>Couple things to fix in your expression:</p>
<ul>
<li><code>/d</code> should have been <code>\d</code></li>
<li>no need for the end of the string match <code>$</code></li>
</ul>
<p>Also, I would use a <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">positive look behind</a> instead of a... | 2 | 2016-09-14T17:23:58Z | [
"python"
] |
"Undeclared variable" declaration in python | 39,496,411 | <p>The following code is an example:</p>
<pre><code>class A(object):
def f(self):
pass
A.f.b = 42
</code></pre>
<p>How is this variable being allocated? If I declare A.f.a, A.f.b, and A.f.c variables am I creating 3 different objects of A? Can someone explain what's going on in memory (as this does not ap... | 0 | 2016-09-14T17:29:25Z | 39,496,898 | <p><code>A.b = 42</code> adds a class variable to <code>A</code>, and thus makes it visible instantly for each instance of <code>A</code> (but only 1 entry in memory)</p>
<p>You can add attributes to classes and instances anytime you like in Python. The cleanest way would be to do it a declare time or this could be mi... | 0 | 2016-09-14T18:03:00Z | [
"python"
] |
"Undeclared variable" declaration in python | 39,496,411 | <p>The following code is an example:</p>
<pre><code>class A(object):
def f(self):
pass
A.f.b = 42
</code></pre>
<p>How is this variable being allocated? If I declare A.f.a, A.f.b, and A.f.c variables am I creating 3 different objects of A? Can someone explain what's going on in memory (as this does not ap... | 0 | 2016-09-14T17:29:25Z | 39,497,181 | <p>The following only works in Python 3:</p>
<pre><code>class A(object):
def f(self):
pass
A.f.a = 41
A.f.b = 42
A.f.c = 43
</code></pre>
<p><code>A.f</code> is an object of type <code>function</code>, and you have always been able to add new attributes to a <code>function</code> object. No instances of <... | 0 | 2016-09-14T18:22:58Z | [
"python"
] |
remove duplicate values from items in a dictionary in Python | 39,496,440 | <p>How can I check and remove duplicate values from items in a dictionary?
I have a large data set so I'm looking for an efficient method. The following is an example of values in a dictionary that contains a duplicate:</p>
<pre><code>'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
</code></pre>
<... | 1 | 2016-09-14T17:31:33Z | 39,496,449 | <pre><code>your_list = [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
new = []
for x in your_list:
if x not in new: new.append(x)
print(new)
>>>[('769817', [6]), ('769819', [4, 10])]
</code></pre>
| 0 | 2016-09-14T17:32:26Z | [
"python",
"dictionary"
] |
remove duplicate values from items in a dictionary in Python | 39,496,440 | <p>How can I check and remove duplicate values from items in a dictionary?
I have a large data set so I'm looking for an efficient method. The following is an example of values in a dictionary that contains a duplicate:</p>
<pre><code>'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
</code></pre>
<... | 1 | 2016-09-14T17:31:33Z | 39,496,507 | <p>You have a list, not a dictionary. Python dictionaries may have only one value for each key. Try</p>
<pre><code>my_dict = dict([('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])])
</code></pre>
<p>result:</p>
<pre><code>{'769817': [6], '769819': [4, 10]}
</code></pre>
<p>a Python dictionary. For more ... | 0 | 2016-09-14T17:36:16Z | [
"python",
"dictionary"
] |
remove duplicate values from items in a dictionary in Python | 39,496,440 | <p>How can I check and remove duplicate values from items in a dictionary?
I have a large data set so I'm looking for an efficient method. The following is an example of values in a dictionary that contains a duplicate:</p>
<pre><code>'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
</code></pre>
<... | 1 | 2016-09-14T17:31:33Z | 39,496,560 | <p>Strikethrough applied to original question before edits, left for posterity:
<s>You're not using a <code>dict</code> at all, just a <code>list</code> of two-<code>tuple</code>s, where the second element in each <code>tuple</code> is itself a <code>list</code>. If you actually want a <code>dict</code>, </p>
<pre><co... | 0 | 2016-09-14T17:39:46Z | [
"python",
"dictionary"
] |
remove duplicate values from items in a dictionary in Python | 39,496,440 | <p>How can I check and remove duplicate values from items in a dictionary?
I have a large data set so I'm looking for an efficient method. The following is an example of values in a dictionary that contains a duplicate:</p>
<pre><code>'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
</code></pre>
<... | 1 | 2016-09-14T17:31:33Z | 39,496,608 | <p>How about this:
I am just focusing on the list part:</p>
<pre><code>>>> s = [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
>>> [(x,y) for x,y in {key: value for (key, value) in s}.items()]
[('769817', [6]), ('769819', [4, 10])]
>>>
</code></pre>
| 0 | 2016-09-14T17:42:24Z | [
"python",
"dictionary"
] |
remove duplicate values from items in a dictionary in Python | 39,496,440 | <p>How can I check and remove duplicate values from items in a dictionary?
I have a large data set so I'm looking for an efficient method. The following is an example of values in a dictionary that contains a duplicate:</p>
<pre><code>'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
</code></pre>
<... | 1 | 2016-09-14T17:31:33Z | 39,496,609 | <p>This problem essentially boils down to removing duplicates from a list of <strong>unhashable</strong> types, for which converting to a set does not possible.</p>
<p>One possible method is to check for membership in the current value while building up a new list value.</p>
<pre><code>d = {'word': [('769817', [6]), ... | 2 | 2016-09-14T17:42:25Z | [
"python",
"dictionary"
] |
remove duplicate values from items in a dictionary in Python | 39,496,440 | <p>How can I check and remove duplicate values from items in a dictionary?
I have a large data set so I'm looking for an efficient method. The following is an example of values in a dictionary that contains a duplicate:</p>
<pre><code>'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]
</code></pre>
<... | 1 | 2016-09-14T17:31:33Z | 39,496,976 | <p>You can uniqify the items based on the hash they generate. Hash could be anything, a sorted <code>json.dumps</code>, or <code>cPickle.dumps</code>.
This one liner can uniqify your dict as required.</p>
<pre><code>>>> d = {'word': [('769817', [6]), ('769819', [4, 10]), ('769819', [4, 10])]}
>>> im... | 0 | 2016-09-14T18:08:28Z | [
"python",
"dictionary"
] |
how to filter by iloc | 39,496,476 | <p>I have a dataframe that has 2 columns. the second column is one of only a few values. I want to make a method that returns a dataframe where only the rows where that column had a specific value are included.</p>
<p>I had this working with this this code:</p>
<pre><code>def filterOnName(df1):
d1columns = df1.co... | 2 | 2016-09-14T17:34:14Z | 39,498,176 | <p>First argument of <code>.iloc</code> is for rows. To get the second column, you'll need:</p>
<pre><code>df.iloc[:, 1]
</code></pre>
<p>where <code>:</code> means "all rows". </p>
| 3 | 2016-09-14T19:25:43Z | [
"python",
"pandas",
"dataframe"
] |
web scraping with beautifulsoup getting error | 39,496,531 | <p>I'm pretty new to Python and mainly need it for getting information from website. </p>
<pre><code>def spider(max_pages):
page = 1
while page <= max_pages:
url = 'https://www.example.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(pla... | 0 | 2016-09-14T17:38:01Z | 39,499,544 | <p>The data you want is in the div attribute <em>data-itemdata</em>, you can call <code>json.loads</code> and it will give you a dict that you can access to get what you want:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
import json
soup = BeautifulSoup(requests.get("https://www.bhphotovideo.com/c/buy... | 1 | 2016-09-14T20:58:14Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Cannot subclass multiprocessing Queue in Python 3.5 | 39,496,554 | <p>My eventual goal is to redirect the <code>stdout</code> from several subprocesses to some queues, and print those out somewhere (maybe in a little GUI).</p>
<p>The first step is to subclass <code>Queue</code> into an object that behaves much like the <code>stdout</code>. But that is where I got stuck. Subclassing t... | 0 | 2016-09-14T17:39:23Z | 39,496,873 | <pre><code>>>> import multiprocessing
>>> type(multiprocessing.Queue)
<class 'method'>
AttributeError: module 'multiprocessing' has no attribute 'queues'
>>> import multiprocessing.queues
>>> type(multiprocessing.queues.Queue)
<class 'type'>
</code></pre>
<p>So as you ca... | 1 | 2016-09-14T18:01:01Z | [
"python",
"python-3.x",
"multiprocessing",
"python-multiprocessing"
] |
printing a int variable in a sqlite3 update query | 39,496,562 | <p>I am trying to update a sqlite3 db once I get a true statement but I can't feed my variable, which is an int, to the query which is a str.
Here is the database </p>
<pre><code>CREATE TABLE STATICIPS(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
IP CHAR(50) NOT NULL,
CITY CHAR(50) NOT NULL,
... | 0 | 2016-09-14T17:39:52Z | 39,496,655 | <p>You need to leverage backticks.</p>
<pre><code>conn.execute("UPDATE STATICIPS set INCOMPLETE = 0 where ID = " + `row[0]`)
</code></pre>
| -1 | 2016-09-14T17:45:04Z | [
"python",
"sqlite3"
] |
printing a int variable in a sqlite3 update query | 39,496,562 | <p>I am trying to update a sqlite3 db once I get a true statement but I can't feed my variable, which is an int, to the query which is a str.
Here is the database </p>
<pre><code>CREATE TABLE STATICIPS(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
IP CHAR(50) NOT NULL,
CITY CHAR(50) NOT NULL,
... | 0 | 2016-09-14T17:39:52Z | 39,496,730 | <p>Don't use concatenation at all when constructing SQL queries. Use <em>SQL parameters</em> instead. These are placeholders in the query where the database will fill in the values for you.</p>
<p>This ensures that those values are properly escaped (avoiding SQL injection attacks), and allows the database to re-use qu... | 1 | 2016-09-14T17:50:31Z | [
"python",
"sqlite3"
] |
Pandas long to wide without losing timezone awareness | 39,496,573 | <p>I'm trying to reshape a pandas dataframe from long to wide format and the timestamps lose the timezone.</p>
<p>Here is a reproducible example:</p>
<pre><code>import pandas as pd
long = pd.DataFrame(dict(
ind=[1,1,2, 2],
events=['event1', 'event2', 'event1', 'event2'],
time=[pd.Timestamp('2015-03-30 00:... | 3 | 2016-09-14T17:40:18Z | 39,497,481 | <p><code>pandas</code> is tracking the timezone. When, you <code>unstack</code>, that reshaping must be happening in <code>numpy</code> which loses track. This is proven by</p>
<pre><code>df = pd.concat([long.time, pd.Series(long.time.values)],
axis=1, keys=['pandas', 'numpy'])
df
</code></pre>
<p><... | 1 | 2016-09-14T18:40:15Z | [
"python",
"pandas",
"timezone",
"reshape"
] |
Not able to save captured image in right directory | 39,496,694 | <p>I am working on a project related to image processing. I would like to capture an image from a webcam and want to display it on webpage. I am using django framework for web stuff. </p>
<p>Program to capture image from webcam in views.py:</p>
<pre><code>from django.shortcuts import render
from django.views.decorato... | -2 | 2016-09-14T17:47:48Z | 39,497,220 | <p>Use the fullpath from / or the relative path from your current dir, using a dot ('.') before the first '/' in the filepath.</p>
<pre><code>file = "./detect/static/test_image.png"
</code></pre>
| 3 | 2016-09-14T18:25:13Z | [
"python",
"django",
"opencv"
] |
How to create a numpy dtype from other dtypes? | 39,496,726 | <p>I normally create numpy dtypes like this: </p>
<pre><code>C = np.dtype([('a',int),('b',float)])
</code></pre>
<p>However in my code I also use the fields <code>a</code> and <code>b</code> individually elsewhere: </p>
<pre><code>A = np.dtype([('a',int)])
B = np.dtype([('b',float)])
</code></pre>
<p>For maintain... | 2 | 2016-09-14T17:50:05Z | 39,496,839 | <p>You can combine the fields using the <code>.descr</code> attribute of the dtypes. For example, here are your <code>A</code> and <code>B</code>. Note that the <code>.descr</code> attrbute is a list containing an entry for each field:</p>
<pre><code>In [44]: A = np.dtype([('a',int)])
In [45]: A.descr
Out[45]: [('a... | 3 | 2016-09-14T17:58:05Z | [
"python",
"numpy",
"numpy-dtype"
] |
How to create a numpy dtype from other dtypes? | 39,496,726 | <p>I normally create numpy dtypes like this: </p>
<pre><code>C = np.dtype([('a',int),('b',float)])
</code></pre>
<p>However in my code I also use the fields <code>a</code> and <code>b</code> individually elsewhere: </p>
<pre><code>A = np.dtype([('a',int)])
B = np.dtype([('b',float)])
</code></pre>
<p>For maintain... | 2 | 2016-09-14T17:50:05Z | 39,496,843 | <p>According to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html" rel="nofollow">dtype documentation</a>, dtypes have an attribute <code>descr</code> which provides an "<em>Array-interface compliant full description of the data-type</em>". Therefore: </p>
<pre><code>A = np.dtype([('a',int... | 4 | 2016-09-14T17:58:15Z | [
"python",
"numpy",
"numpy-dtype"
] |
How to create a numpy dtype from other dtypes? | 39,496,726 | <p>I normally create numpy dtypes like this: </p>
<pre><code>C = np.dtype([('a',int),('b',float)])
</code></pre>
<p>However in my code I also use the fields <code>a</code> and <code>b</code> individually elsewhere: </p>
<pre><code>A = np.dtype([('a',int)])
B = np.dtype([('b',float)])
</code></pre>
<p>For maintain... | 2 | 2016-09-14T17:50:05Z | 39,497,303 | <p>There is a backwater module in <code>numpy</code> that has a bunch of structured/rec array utilities.</p>
<p><code>zip_descr</code> does this sort of <code>descr</code> concatenation, but it starts with arrays rather than the <code>dtypes</code>:</p>
<pre><code>In [77]: import numpy.lib.recfunctions as rf
In [78]:... | 0 | 2016-09-14T18:29:31Z | [
"python",
"numpy",
"numpy-dtype"
] |
How can I make this program ignore punctuation | 39,496,745 | <p>I'm new to python and I'm not sure how I can make this program ignore punctuation; I know it's really inefficient but I'm not bothered about it at this moment in time.</p>
<pre><code>while True:
y="y"
n="n"
Sentence=input("Please enter your sentence: ").upper()
print("Your sentence is:",Sentence)
Correct=input("Is... | 1 | 2016-09-14T17:52:00Z | 39,497,093 | <p>You can use Python's <code>string</code> module to help test for punctuation.</p>
<pre><code>>> import string
>> print string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
>> sentence = "I am a sentence, and; I haven't been punctuated well.!"
</code></pre>
<p>You can <code>split</code> t... | 1 | 2016-09-14T18:17:13Z | [
"python"
] |
kill a task with name containing whitespace using python os.system | 39,496,858 | <p>From a python script, I am trying to terminate a task.
The task name contains whitespace. </p>
<p>Like "My Program.exe" for instance.</p>
<p>I use the following line but it complains about invalid argument because the name contains a whitespace.</p>
<pre><code>os.system("TASKKILL /F /IM My Program.exe")
</code></... | 1 | 2016-09-14T17:59:28Z | 39,497,130 | <p>This worked for me:</p>
<pre><code>os.system("TASKKILL /F /IM \"My Program.exe\"")
</code></pre>
<p>Check if your application is really named 'My Program.exe' on task manager. Also, check if you have privileges to be killing that process.</p>
| 1 | 2016-09-14T18:20:12Z | [
"python",
"whitespace",
"taskkill"
] |
"Name Error: name 'get_ipython' is not defined" while preparing a debugging session via "import ipdb" | 39,496,891 | <p>I'm trying to install and use ipdb (IPython-enabled pdb) on Python 3.3.5 32 bit on Win10 using PIP 8.1.2.
I've installed via PIP (had to install it seprately) in windows cmd with no errors:</p>
<pre><code> pip install ipdb
</code></pre>
<p>I wrote a simple test script expecting to stop in debugger before printing ... | 0 | 2016-09-14T18:02:06Z | 39,501,284 | <p>As the issue seemed to be related to IPython, I've checked that the version installed while resolving ipdb dependencies was: "ipython-5.1.0". </p>
<p>The WA solution for the issue occured to be a fallback to version 4.2.1 of IPython:</p>
<pre><code>pip install "ipython<5"
(...)
Successfully uninstalled ... | 0 | 2016-09-14T23:51:22Z | [
"python",
"python-3.x",
"ipython",
"ipdb"
] |
I am having trouble using or importing matplotlib. This is the first line of my code: import matplotlib.pyplot as plt | 39,496,987 | <p>These are the messages I'm receiving and I have no idea what any of them mean.</p>
<p>I have <code>python 2.7.12</code> and have imported <code>matplotlib</code>.</p>
<p>In the command prompt window, the last update I installed was <strong>conda install matplotlib</strong> which seemed to update some stuff (<code>... | 0 | 2016-09-14T18:09:07Z | 39,497,074 | <p>It looks like there may be a conflicting module named calendar. Are there any other packages (files) called "calendar" (<code>calendar.py</code>) in your python path? Try opening up a new python console and type <code>from calendar import monthrange</code>.</p>
| 1 | 2016-09-14T18:15:58Z | [
"python",
"python-2.7",
"matplotlib"
] |
Error reinstalling python3 in ubuntu 16.04 | 39,497,017 | <p>I am using ubuntu 16.04 and I removed the preinstalled python3 and want to install it again. However, I'm getting an error when using <code>sudo apt-get -f install python3</code> :</p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
python3.5 is already the... | 0 | 2016-09-14T18:10:59Z | 39,497,413 | <p>Anaconda supports multiple environments for your Python installations. You should use:</p>
<pre><code>conda create -n py35 python=3.5 anaconda
</code></pre>
<p>Then, to use the Python 3.5 environment, use:</p>
<pre><code>activate py35
</code></pre>
<p>from the command line. You can refer to:</p>
<p><a href="htt... | 0 | 2016-09-14T18:36:29Z | [
"python",
"ubuntu",
"ubuntu-16.04"
] |
Error reinstalling python3 in ubuntu 16.04 | 39,497,017 | <p>I am using ubuntu 16.04 and I removed the preinstalled python3 and want to install it again. However, I'm getting an error when using <code>sudo apt-get -f install python3</code> :</p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
python3.5 is already the... | 0 | 2016-09-14T18:10:59Z | 39,497,529 | <p>Clearly looks like a packaging error in the Ubuntu <code>python3</code> package. Report it to Launchpad if it's not already there.</p>
| 0 | 2016-09-14T18:43:14Z | [
"python",
"ubuntu",
"ubuntu-16.04"
] |
Not able to pass an array into another array within a for loop | 39,497,038 | <p>I want to evaluate an expression inside for loop. I am doing:</p>
<pre><code> for i in range(1,height+1):
for j in range(1,width+1):
y[i,j] = Q[img[i,j]+1]
</code></pre>
<p>but this returns an error saying </p>
<pre><code> y[i,j] = Q[img[i,j]+1]
TypeError: 'numpy.ndarray' object is not callable
<... | 1 | 2016-09-14T18:12:42Z | 39,497,087 | <p>Q(x) is trying to call Q with x as an argument. Use Q[x] to access index x.</p>
<p>EDIT:</p>
<p>Your big block of code has the Q[x] syntax. Do you still get the error message?</p>
| 0 | 2016-09-14T18:16:50Z | [
"python",
"numpy",
"matplotlib"
] |
Django+heroku: django logs appear, app logs don't | 39,497,040 | <p>I read all the StackOverflow answers, all the blog posts on the subject, and tried everything twice, but I still can't get my Django app's log messsages to appear in the heroku log (Django's own messages do appear).</p>
<p>Can anyone please paste a full LOGGING config that works in heroku?</p>
<pre><code># views.p... | 2 | 2016-09-14T18:12:43Z | 39,499,703 | <p>Here is a configuration that worked for me (OP):</p>
<pre><code>LOGGING = {
"version": 1,
"disable_existing_loggers": False,
'formatters': {
'simple': {
'format': '%(levelname)s [%(name)s:%(lineno)s] %(message)s'
},
},
'handlers': {
'console': {
'l... | 2 | 2016-09-14T21:11:43Z | [
"python",
"django",
"logging",
"heroku"
] |
Python during runtime does not consider a number entered as a int or float | 39,497,067 | <p>I am a beginner and it might feel like a silly question. </p>
<p>I am trying to create a simple program,a temperature converter from Celsius to F*.</p>
<p>Which takes:</p>
<ol>
<li>'quit' for stopping program</li>
<li>int values for providing the correct result</li>
</ol>
<p>Problem: any text value entered by... | 0 | 2016-09-14T18:15:09Z | 39,497,165 | <p>Not sure if I understand the problem correctly, but usually it is better to use <code>raw_input</code> instead of <code>input</code> in case like this.</p>
| 0 | 2016-09-14T18:21:46Z | [
"python",
"input"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.