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 |
---|---|---|---|---|---|---|---|---|---|
How to Create a file at a specific path in python? | 39,853,660 | <p>I am writing below code which is not working:</p>
<pre><code>cwd = os.getcwd()
print (cwd)
log = path.join(cwd,'log.out')
os.chdir(cwd) and Path(log.out).touch() and os.chmod(log.out, 777)
</code></pre>
<p>how can I create a log.out into cwd ?</p>
| 0 | 2016-10-04T13:29:23Z | 39,853,849 | <p>you can call the usual linux <code>touch</code> command via <code>subprocess</code></p>
<pre><code>import subprocess
subprocess.call(["touch", cwd+"/log.out"])
</code></pre>
| 0 | 2016-10-04T13:38:32Z | [
"python"
]
|
How to Create a file at a specific path in python? | 39,853,660 | <p>I am writing below code which is not working:</p>
<pre><code>cwd = os.getcwd()
print (cwd)
log = path.join(cwd,'log.out')
os.chdir(cwd) and Path(log.out).touch() and os.chmod(log.out, 777)
</code></pre>
<p>how can I create a log.out into cwd ?</p>
| 0 | 2016-10-04T13:29:23Z | 39,853,906 | <p>To create an empty file:</p>
<pre><code>import os
cwd = os.getcwd()
os.chdir(cwd)
filename = 'log.out'
with open(os.path.join(cwd, filename), 'wb') as f:
f.write('')
os.chmod(filename, 777)
</code></pre>
<p>This will create an empty file called <code>log.out</code>, which of course will be content-empty, but that can easily change with the use of the <code>f.write(content)</code> function.</p>
| 0 | 2016-10-04T13:41:44Z | [
"python"
]
|
Is the index_db method from the SeqIO object in Biopython slow? | 39,853,677 | <p>I've got this:</p>
<pre><code>files = glob.glob(str(dir_path) + "*.fa")
index = SeqIO.index_db(index_filename, files, "fasta")
seq = index[accession] # Slow
index.close()
return seq
</code></pre>
<p>and i'm working on big files (gene sequences) but for some reasons, it takes about 4 secondes to get the sequence I'm looking for. I'm wondering if the index_db method is suppose to be that slow? Am I using the right method?</p>
<p>Thanks.</p>
| 0 | 2016-10-04T13:30:08Z | 39,856,519 | <p>The first time the database is created it can take some time. The next times, if you don't delete the <code>index_filename</code> created, it should go faster.</p>
<p>Lets say you have your 25 files each with some genes. This method creates a SQLite DB that helps locating the sequences among the files, like "Get me the gene XXX" and the SQLite/index_db <em>knows</em> that the gene is in the file <code>12.fasta</code> and its exact location inside the file. So Biopython opens the file and scans quickly to the gene position.</p>
<p>Without that index_db you have to load every Records into memory, which is fast but some files might not fit in the RAM.</p>
<hr>
<p>If you want speed to fetch regions you can use <a href="http://pysam.readthedocs.io/en/latest/api.html?highlight=fasta#fasta-files" rel="nofollow">FastaFile from pysam</a> and <a href="http://www.htslib.org/doc/samtools.html" rel="nofollow">samtools</a>. Like this:</p>
<ol>
<li><p>You have to index all the fasta files with <code>faidx</code>:</p>
<pre><code>$ samtools faidx big_fasta.fas
</code></pre></li>
<li><p>From your code write something like this:</p>
<pre><code>from pysam import FastaFile
rec = FastaFile("big_fasta.fas") # big_fasta.fas.fai must exist.
seq = rec.fetch(reference=gene_name, start=1000, end= 1200)
print(s)
</code></pre></li>
</ol>
<p>In my computer this times 2 orders of magnitude faster than Biopython for the same operation, but you only get the pure sequence of bases.</p>
| 1 | 2016-10-04T15:41:17Z | [
"python",
"biopython"
]
|
Setting values in one dataframe from the boolean values in another | 39,853,718 | <p>I have a MWE that can be reproduced with the following code:</p>
<pre><code>import pandas as pd
a = pd.DataFrame([[1,2],[3,4]], columns=['A', 'B'])
b = pd.DataFrame([[True,False],[False,True]], columns=['A', 'B'])
</code></pre>
<p>Which creates the following dataframes:</p>
<pre><code>In [8]: a
Out[8]:
A B
0 1 2
1 3 4
In [9]: b
Out[9]:
A B
0 True False
1 False True
</code></pre>
<p>My question is, how can I change the values for dataframe <code>A</code> based on the boolean values in dataframe <code>B</code>?</p>
<p>Say for example if I wanted to make <code>NAN</code> values in dataframe <code>A</code> where there's an instance of <code>False</code> in dataframe <code>B</code>?</p>
| 1 | 2016-10-04T13:32:01Z | 39,853,737 | <p>If need replace <code>False</code> to <code>NaN</code>:</p>
<pre><code>print (a[b])
A B
0 1.0 NaN
1 NaN 4.0
</code></pre>
<p>or:</p>
<pre><code>print (a.where(b))
A B
0 1.0 NaN
1 NaN 4.0
</code></pre>
<p>and if need replace <code>True</code> to <code>NaN</code>:</p>
<pre><code>print (a[~b])
A B
0 NaN 2.0
1 3.0 NaN
</code></pre>
<p>or:</p>
<pre><code>print (a.mask(b))
A B
0 NaN 2.0
1 3.0 NaN
</code></pre>
<p>Also you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow"><code>where</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html" rel="nofollow"><code>mask</code></a> with some scalar value:</p>
<pre><code>print (a.where(b, 7))
A B
0 1 7
1 7 4
print (a.mask(b, 7))
A B
0 7 2
1 3 7
print (a.where(b, 'TEST'))
A B
0 1 TEST
1 TEST 4
</code></pre>
| 1 | 2016-10-04T13:32:59Z | [
"python",
"pandas",
"indexing",
"dataframe",
"boolean"
]
|
Python script to check dir not working | 39,853,801 | <p>I am stuck with my script at a point. The script is this</p>
<pre><code>import subprocess
import os
def Windows():
SW_MINIMIZE = 6
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_MINIMIZE
print(os.path.isdir("C:\Program Files (x86)"))
while True:
try:
subprocess.Popen(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
else:
try:
subprocess.Popen(r'C:\Program Files\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files\Google\Chrome\Application\chrome.exe', startupinfo=info)
</code></pre>
<p>What I want to do is check if the computer is 64 bit or 32 bit (as I want to open the browser without a window using <code>subprocess</code>.) to locate the browsers <code>chrome</code> or <code>firefox</code>, depending on which one the user has ( I am assuming that they have either one of them). Since the path for chrome and firefox varies in 64 vs 32 bit computers (Program Files and Program Files (x84)), I came up with this script which detects if x86 folder exists or not. If it does, it continues on the folder for searching for the browsers. However, if it doesn't, it assumes it is 32-bit and searches for <code>Program Files</code> folder and in that folder it searches for the browsers.
However, when I run the script I get this error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Charchit\Desktop\via.py", line 29, in <module>
Windows()
File "C:\Users\Charchit\Desktop\via.py", line 13, in Windows
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code></pre>
<p>However, in my script it should not even go to <code>while True</code> Section because I have a 32 bit system and <code>x86</code> folder doesn't exist!</p>
| 0 | 2016-10-04T13:36:05Z | 39,853,913 | <p>for creating the path use the built-ins python functions that won't mess up the path</p>
<pre><code>if os.path.exists(os.path.join('C:', os.path.sep(), 'Program Files')):
# do your stuff
</code></pre>
| -1 | 2016-10-04T13:42:06Z | [
"python",
"python-2.7",
"subprocess"
]
|
Python script to check dir not working | 39,853,801 | <p>I am stuck with my script at a point. The script is this</p>
<pre><code>import subprocess
import os
def Windows():
SW_MINIMIZE = 6
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_MINIMIZE
print(os.path.isdir("C:\Program Files (x86)"))
while True:
try:
subprocess.Popen(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
else:
try:
subprocess.Popen(r'C:\Program Files\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files\Google\Chrome\Application\chrome.exe', startupinfo=info)
</code></pre>
<p>What I want to do is check if the computer is 64 bit or 32 bit (as I want to open the browser without a window using <code>subprocess</code>.) to locate the browsers <code>chrome</code> or <code>firefox</code>, depending on which one the user has ( I am assuming that they have either one of them). Since the path for chrome and firefox varies in 64 vs 32 bit computers (Program Files and Program Files (x84)), I came up with this script which detects if x86 folder exists or not. If it does, it continues on the folder for searching for the browsers. However, if it doesn't, it assumes it is 32-bit and searches for <code>Program Files</code> folder and in that folder it searches for the browsers.
However, when I run the script I get this error</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Charchit\Desktop\via.py", line 29, in <module>
Windows()
File "C:\Users\Charchit\Desktop\via.py", line 13, in Windows
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code></pre>
<p>However, in my script it should not even go to <code>while True</code> Section because I have a 32 bit system and <code>x86</code> folder doesn't exist!</p>
| 0 | 2016-10-04T13:36:05Z | 39,854,038 | <p>You're not actually checking if <code>os.path.isdir("C:\Program Files (x86)")</code>. You're just printing it.</p>
<p>Instead of </p>
<pre><code>print(os.path.isdir("C:\Program Files (x86)"))
while True:
</code></pre>
<p>You need to do</p>
<pre><code>if os.path.isdir(r"C:\Program Files (x86)"):
</code></pre>
<p>Side note: </p>
<p>Both chrome and firefox traditionally place themselves on the path, so there's a good chance you can just do <code>subprocess.Popen('firefox.exe')</code> / <code>subprocess.Popen('chrome.exe')</code>.</p>
| 1 | 2016-10-04T13:47:30Z | [
"python",
"python-2.7",
"subprocess"
]
|
Django Form Error: 'QueryDict' object has no attribute 'method' when POST assigned | 39,853,857 | <p>I'm having trouble with a specific form that is not permitting me to post data to a function I've defined. I'm very confused as to why this is giving me errors because I use an almost identical form to do another action in the same website.</p>
<p>When I post this data, Django throws "'QueryDict' object has no attribute 'method'" even though I've assigned the method as POST. It renders the form just fine when it's not posting, it's only when I submit I have a problem.\</p>
<p>The error that Django throws points to this line in views: if request.method == "POST":
this is the first line in the "cancel" function below.</p>
<p>Can anyone identify what I've done wrong here? I'm at a loss.</p>
<p>Here's the function in view.py:</p>
<pre><code>from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from .apps.instant import orderlist, orderdetails, cancel
from .forms import cancelorder
def cancel(request):
if request.method == "POST":
form = cancel(request.POST or None)
if form.is_valid():
response = cancel(request.session['token'],form.cleaned_data['orderId'], form.cleaned_data['reason'])
return render(request, 'instant/review.html', {'data':response})
else:
form = cancelorder()
return render(request, 'instant/cancel.html', {'form':form})
else:
form = cancelorder()
return render(request, 'instant/cancel.html', {'form':form})
</code></pre>
<p>here's the forms.py:</p>
<pre><code>from django import forms
class cancelorder(forms.Form):
orderId = forms.CharField(label='Order Id', max_length=5)
reason = forms.CharField(label='reason', widget=forms.Textarea)
</code></pre>
<p>here's the template it's rendering (instant/cancel.html):</p>
<pre><code>{% extends "main/header.html" %}
{% load widget_tweaks %}
{% block content %}
<div class = "row">
<div class ="col-sm-3">
</div>
<div class ="col-sm-6">
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<strong>Warning!</strong> When you cancel, the host gets an email notifiaction! Also, there are no confirmations. Only click cancel if you're sure!
</div>
</div>
</div>
<div class = "row">
<div class ="col-sm-3">
</div>
<div class ="col-sm-6">
<div class="well-lg" style="background-color:#efefef">
<center>
<h3> cancel an order</h3>
</center><br>
<!-- <h3>Login</h3> -->
<form action="/instant/cancel/" method="POST" class="post-form">{% csrf_token %}
<div class="form-group">
<label for="login_email">Order Id</label>
{{ form.orderId|add_class:"form-control"|attr:"placeholder:Enter numbers only"}}
</div>
<div class="form-group">
<label for="login_password">Reason</label>
{{ form.reason|add_class:"form-control"|attr:"placeholder:Why are you cancelling?"}}
</div>
<button type="submit" class="btn btn-danger btn-lg">Send Cancellation</button>
</form>
</div>
</div>
</div>
{% endblock %}
</code></pre>
<p>And finally here's the function that form collects data for. .apps.instant (I know the API I'm calling does function):</p>
<pre><code>from time import sleep
import requests
import logging
import json
LOG_FILENAME = 'transaction_log.log' #Production Log
logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO,format='%(asctime)s %(message)s')
url = APIURL (removed for stackoverflow)
def cancel(token,orderId,reason):
auth_token = {"Authorization" : "bearer " + str(token)}
raw = {'instabookingId':orderId,"reason":reason}
info = json.dumps(raw)
cancellation = requests.post(url, headers=auth_token,data=info)
response = cancellation.json()
return response
</code></pre>
<p>I appreciate any help you can offer, really would like to know why this isn't working.</p>
<p>here's the error for Django:</p>
<pre><code>Environment:
Request Method: POST
Request URL: http://164.132.48.154:8000/instant/cancel/
Django Version: 1.10.2
Python Version: 2.7.9
Installed Applications:
['main',
'instant',
'widget_tweaks',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/root/mysite/instant/views.py" in cancel
24. form = cancel(request.POST or None)
File "/root/mysite/instant/views.py" in cancel
23. if request.method == "POST":
Exception Type: AttributeError at /instant/cancel/
Exception Value: 'QueryDict' object has no attribute 'method'
</code></pre>
| 0 | 2016-10-04T13:38:51Z | 39,854,018 | <p>The error is in this line</p>
<pre><code>...
def cancel(request):
if request.method == "POST":
form = cancel(request.POST or None) # you call the function, its the same name, you would call your cancelform
if form.is_valid():
response = cancel(request.session['token'],form.cleaned_data['orderId'], form.cleaned_data['reason'])
return render(request, 'instant/review.html', {'data':response})
else:
...
</code></pre>
<p>is recursively, the second time, in the function cancel, request == request.POST, and request.POST has not attribute 'method'</p>
| 1 | 2016-10-04T13:46:38Z | [
"python",
"django",
"forms"
]
|
how to check if date is in certain interval python? | 39,853,900 | <p>I'm importing dates from yahoo finance and want to transform them in a format so that I can compare them with today to check if the date is between 3 and 9 months from now.</p>
<p>Here is what I have so far:</p>
<pre><code>today = time.strftime("%Y-%m-%d")
today = datetime.datetime.strptime(today, '%Y-%m-%d')
int_begin = today + datetime.timedelta(days=90)
int_end = today + datetime.timedelta(days=270)
for i in opt["Expiry"]:
transf_date = datetime.datetime.strptime(opt["Expiry"][1],'%b %d, %Y')
transf_date = datetime.datetime.strftime(transf_date,"%Y-%m-%d")
if int_begin <= transf_date and transf_date <= int_end:
print "True:",i
else:
print "False:",i
</code></pre>
<p>Here is the content of opt["Expiry"]</p>
<pre>
0 Jan 20, 2017
1 Jan 20, 2017
2 Jan 20, 2017
3 Jan 20, 2017
4 Jan 20, 2017
5 Jan 20, 2017
6 Jan 20, 2017
7 Jan 20, 2017
8 Jan 20, 2017
9 Jan 20, 2017
10 Jan 20, 2017
11 Jan 20, 2017
12 Jan 20, 2017
13 Jan 20, 2017
14 Jan 20, 2017
15 Jan 20, 2017
16 Jan 20, 2017
17 Jan 19, 2018
18 Jan 20, 2017
19 Jan 19, 2018
20 Jan 20, 2017
21 Mar 17, 2017
22 Jan 20, 2017
23 Mar 17, 2017
24 Jan 20, 2017
25 Mar 17, 2017
26 Apr 21, 2017
27 Jun 16, 2017
28 Jan 19, 2018
29 Jan 20, 2017
...
432 Jan 20, 2017
433 Jan 19, 2018
434 Oct 21, 2016
435 Jan 20, 2017
436 Jan 19, 2018
437 Oct 21, 2016
438 Jan 20, 2017
439 Jan 19, 2018
440 Oct 21, 2016
441 Jan 20, 2017
442 Jan 19, 2018
443 Oct 21, 2016
444 Jan 20, 2017
445 Jan 19, 2018
446 Oct 21, 2016
447 Jan 20, 2017
448 Oct 21, 2016
449 Jan 20, 2017
450 Oct 21, 2016
451 Jan 20, 2017
452 Oct 21, 2016
453 Jan 20, 2017
454 Oct 21, 2016
455 Jan 20, 2017
456 Oct 21, 2016
457 Jan 20, 2017
458 Jan 20, 2017
459 Jan 20, 2017
460 Jan 20, 2017
461 Jan 20, 2017
</pre>
<p>It seems like I have the same date format, which is "%Y-%m-%d", but I still get no values filtered out. All of them come out as true, being inside the interval.</p>
| 0 | 2016-10-04T13:41:21Z | 39,854,156 | <p>You're using <code>transf_date = datetime.datetime.strptime(opt["Expiry"][1],'%b %d, %Y')</code> instead of <code>transf_date = datetime.datetime.strptime(opt["Expiry"][i],'%b %d, %Y')</code>, meaning that even though you're iterating over the entire <code>opt["Expiry"]</code>, you're always processing the same entry.</p>
| 1 | 2016-10-04T13:53:12Z | [
"python",
"datetime"
]
|
Diff commit messages of two branches with gitpython | 39,854,111 | <p>At work, we have a workflow where each branch is "named" by date. During the week, at least once, the latest branch gets pushed to production. What we require now is the summary/commit messages of the changes between the latest branch in production vs the new branch via gitpython.</p>
<p>What I have tried to do:</p>
<pre><code>import git
g = git.Git("pathToRepo")
r = git.Repo("pathToRepo")
g.pull() # get latest
b1commits = r.git.log("branch1")
b2commits = r.git.log("branch2")
</code></pre>
<p>This give me all of the commit history from both branches but I can't figure out how to compare them to just get the newest commit messages.</p>
<p>Is this possible to do in gitPython? Or is there a better solution?</p>
| 0 | 2016-10-04T13:50:54Z | 39,856,321 | <p>I figured it out:</p>
<pre><code>import git
g = git.Git(repoPath+repoName)
g.pull()
commitMessages = g.log('%s..%s' % (oldBranch, newBranch), '--pretty=format:%ad %an - %s', '--abbrev-commit')
</code></pre>
<p>Reading through the Git documentation I found that I can compare two branches with this syntax <code>B1..B2</code>. I tried the same with gitpython and it worked, the other parameters are there for a custom format.</p>
| 0 | 2016-10-04T15:30:39Z | [
"python",
"git-commit",
"git-log",
"gitpython"
]
|
proxy error when using flask as a simple http proxy | 39,854,217 | <p>There my code:</p>
<p>main.py:</p>
<pre><code>from flask import Flask, request, Response
import requests
app = Flask(__name__)
@app.before_request
def before_request():
url = request.url
method = request.method
data = request.get_data()
headers = dict()
for name, value in request.headers:
if not value or name == 'Cache-Control':
continue
headers[name] = value
r = requests.request(method, url, headers=headers, data=data, stream=True)
response_headers = []
for name, value in r.headers.items():
if name.lower() in ('content-length', 'connection', 'content-encoding'):
continue
response_headers.append((name, value))
return Response(r, status=r.status_code, headers=response_headers)
if __name__ == '__main__':
app.run()
</code></pre>
<p>run.py:</p>
<pre><code>from main import app
app.run(host='127.0.0.1', port=6666, debug=True)
</code></pre>
<p>I run in console like :</p>
<pre><code>python run.py
</code></pre>
<p>It works fine for one request(finish one request and then next request).But it is stupid for it serves one request at a time.so I run is on gunicorn :</p>
<pre><code>gunicorn -c gun.conf main:app
</code></pre>
<p>I make 10 workers to run this app.But it fails.</p>
<pre><code>--File "/Users/xiazhibin/.pyenv/versions/2.7.11/envs/flask_study/lib/python2.7/site-packages/requests/api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
--File "/Users/xiazhibin/.pyenv/versions/2.7.11/envs/flask_study/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
--File "/Users/xiazhibin/.pyenv/versions/2.7.11/envs/flask_study/lib/python2.7/site-packages/requests/sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
--File "/Users/xiazhibin/.pyenv/versions/2.7.11/envs/flask_study/lib/python2.7/site-packages/requests/adapters.py", line 485, in send
raise ProxyError(e, request=request)
ProxyError: HTTPConnectionPool(host='127.0.0.1', port=6666): Max retries exceeded with url:http://www.some_web_site.com/
(Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x108363bd0>:
Failed to establish a new connection: [Errno 61] Connection refused',)))
</code></pre>
<p>I don't know why this is the case.</p>
| -1 | 2016-10-04T13:56:10Z | 39,866,791 | <p>Yes, it fails to connect to the proxy(127.0.0.1:6666)</p>
| 0 | 2016-10-05T06:24:59Z | [
"python",
"flask",
"python-requests"
]
|
python ObjectListView negate filter | 39,854,298 | <p>I need some help with negate this filter for the ObjectListView.</p>
<pre><code>def addFilter(self, text):
# OLV.Filter.Predicate()
meter_flt = OLV.Filter.TextSearch(self, text=text)
self.SetFilter(meter_flt)
</code></pre>
<p>This works great, but if i try to filter like "chicken" then it's only show chickens. I want it to be reversed, so if i type chicken, everything apart from chicken should be displayed.</p>
<p>Thanks for your help!</p>
| 0 | 2016-10-04T13:59:31Z | 39,872,312 | <p>You can use <a href="http://objectlistview.sourceforge.net/python/features.html#filtering" rel="nofollow"><code>Filter.Predicate</code></a></p>
<blockquote>
<p>Filter.Predicate(booleanCallable) Show only the model objects for
which the given callable returns true. The callable must accept a
single parameter, which is the model object to be considered.</p>
</blockquote>
<p>Following is a code snippet for handling multiple text to be excluded from the list of items.</p>
<pre><code>def __init__(self):
self.text_list = [] # list of text to be excluded
self.SetFilter(Filter.Predicate(self.filterMethod))
def addFilter(self, text):
self.text_list.append(text)
self.RepopulateList() # so that our filter_method is applied again
def filterMethod(self,obj):
for text in self.text_list:
if {YOUR EXCLUSION LOGIC HERE}:
return False
return True
</code></pre>
| 0 | 2016-10-05T11:06:54Z | [
"python",
"wxpython",
"filtering",
"objectlistview",
"objectlistview-python"
]
|
select name where id = "in the python list"? | 39,854,306 | <p>Let's say i have a python list of customer id like this:</p>
<pre><code>id = ('12','14','15','11',.......)
</code></pre>
<p>the array has 1000 values in it, and i need to insert the customer name to a table based on the ids from the list above.</p>
<p>my code is like:</p>
<pre><code>ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('ids')"
cursor.execute(sql)
</code></pre>
<p>after running the code, i get nothing inserted to the table. What mistake do i have?</p>
<p>Please help :(</p>
| 0 | 2016-10-04T13:59:53Z | 39,854,358 | <p>You need to format the string.</p>
<pre><code>ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('{ids}')"
cursor.execute(sql.format(ids= ids))
</code></pre>
| 0 | 2016-10-04T14:02:07Z | [
"python",
"mysql"
]
|
select name where id = "in the python list"? | 39,854,306 | <p>Let's say i have a python list of customer id like this:</p>
<pre><code>id = ('12','14','15','11',.......)
</code></pre>
<p>the array has 1000 values in it, and i need to insert the customer name to a table based on the ids from the list above.</p>
<p>my code is like:</p>
<pre><code>ids = ",".join(id)
sql = "insert into cust_table(name)values(names)where cust_id IN('ids')"
cursor.execute(sql)
</code></pre>
<p>after running the code, i get nothing inserted to the table. What mistake do i have?</p>
<p>Please help :(</p>
| 0 | 2016-10-04T13:59:53Z | 39,855,021 | <p>Simply writing the name of a variable into a string doesn't magically make its contents appear in the string.</p>
<pre><code>>>> p = 'some part'
>>> s = 'replace p of a string'
>>> s
'replace p of a string'
>>> s = 'replace %s of a string' % p
>>> s
'replace some part of a string'
>>> s = 'replace {} of a string'.format(p)
>>> s
'replace some part of a string'
</code></pre>
<p>In your case this would mean:</p>
<pre><code>>>> sql = "insert into cust_table (name) values (names) where cust_id IN ('%s')"
>>> ids = ", ".join(id)
>>> cursor.execute(sql % ids)
</code></pre>
<p>although I strongly suspect that you have a similar problem with <code>names</code>.</p>
<p>In order to avoid possible sql injection problems, it would be preferable to use a "parameterized statement". This would look something like:</p>
<pre><code>>>> sql = 'insert into ... where cust_id IN %s'
>>> cursor.execute(sql, (id,))
</code></pre>
<p>Some database connectors for python are capable of this, but yours probably isn't.</p>
<p>A workaround might be something like</p>
<pre><code>>>> params = ', '.join(['%s']*len(id))
>>> sql = 'insert into ... where cust_id IN (%s)' % params
>>> cursor.execute(sql, id)
</code></pre>
| 0 | 2016-10-04T14:32:59Z | [
"python",
"mysql"
]
|
Pandas time series comparison with missing data/records | 39,854,373 | <p>This question is somewhat related to an earlier question from me (<a href="http://stackoverflow.com/questions/38658811/remapping-numpy-array-with-missing-values">Remapping `numpy.array` with missing values</a>), where I was struggling with time series with missing data, and someone suggested <em>"use Pandas!"</em>. So here I go...</p>
<p>I'm dealing with large data sets, basically consisting of time series from different observation sites, where I would like to statistically compare the sites. These data sets are quite messy; lots of missing data (indicated with e.g. <code>-99</code>), missing time records (one station might have the time record, another not), and I only want to include/compare data where either (1) all sites have data for a certain variable, or (2) the two sites I would like to compare have data for that variable, ignoring whether the other sites (don't) have data. </p>
<p>Take this minimal example:</p>
<pre><code>import pandas as pd
from io import StringIO
data = StringIO("""\
1, 2001-01-01, 00:00, 1.0, 0.5, 1.0
1, 2001-01-01, 01:00, 1.1, 0.6, 2.0
1, 2001-01-01, 02:00, 1.2, 0.7, 3.0
1, 2001-01-01, 03:00, 1.3, 0.8, 4.0
2, 2001-01-01, 00:00, 2.0, -99, -99
2, 2001-01-01, 01:00, -99, 1.6, 2.0
2, 2001-01-01, 02:00, 2.2, 1.7, 3.0
2, 2001-01-01, 03:00, 2.3, 1.8, 4.0
3, 2001-01-01, 00:00, 3.0, 2.5, 1.0
3, 2001-01-01, 01:00, 3.1, 2.6, -99
3, 2001-01-01, 02:00, -99, -99, 3.0
3, 2001-01-01, 03:00, 3.3, 2.8, 4.0
3, 2001-01-01, 04:00, 3.4, 2.9, 5.0
""")
columns = ['id','date','time','T','Td','cc']
df = pd.read_table(data, header=None, names=columns, delimiter=',', na_values=-99, parse_dates=[['date','time']])
</code></pre>
<p>Where <code>-99</code> indicates a missing value. I would like to compare the data (columns <code>T</code>,<code>Td</code>,<code>cc</code>) from different sites (column <code>id</code>), but as mentioned, only if either two or all <code>id</code>'s have data for the variable I'm interested in (completely ignoring whether the data in other columns is missing).</p>
<p>So for this example, if all sites need to have data, comparing <code>T</code> would only result in comparing data from <code>2001-01-01, 00:00</code> and <code>03:00</code>, since for the other times, either <code>id=2</code> or <code>id=3</code> is missing <code>T</code>, and the last time record for <code>id=3</code> is completely absent in the other <code>id</code>'s. </p>
<p>I've been playing with this for hours now, but honestly I don't really know where to start. Is it possible to extract a <code>numpy.array</code>, using the criteria outlined above, of size <code>n_sites x n_valid_values</code> (<code>3x2</code>, for this example), which I could then use for further analysis?</p>
<p><em>EDIT</em> As a partial, but really (<em>really</em>) ugly solution, something like this seems to work:</p>
<pre><code># Loop over all indexes where T is nan:
for i in np.where(df['T'].isnull())[0]:
# For each of them, set records with the same date_time to nan
j = np.where(df['date_time'] == df['date_time'][i])[0]
df['T'][j] = np.nan
# Drop all records where T is nan
df2 = df.dropna(subset=['T'])
# Group by the different stations:
g = df2.groupby('id')
# Get the arrays (could automate this based on the unique id's):
v1 = g.get_group(1)['T']
v2 = g.get_group(2)['T']
v3 = g.get_group(3)['T']
</code></pre>
<p>But this still doesn't drop the record for <code>id=3</code>, <code>date_time=2001-01-01, 04:00</code>, and I guess/hope that there are more elegant methods with <code>Pandas</code>.</p>
| 2 | 2016-10-04T14:02:34Z | 39,866,299 | <p>One method (based on this: <a href="http://stackoverflow.com/a/34985243/3581217">http://stackoverflow.com/a/34985243/3581217</a> answer) which seems to work is to create a <code>Dataframe</code> where the observations from the different sites have different columns, then a <code>dropna()</code> with <code>subset</code> set to either all columns, or the two sites I want to compare, which drops all rows where data is missing. </p>
<pre><code>import pandas as pd
import numpy as np
from io import StringIO
data1 = StringIO("""\
1, 2001-01-01, 00:00, 1.0
1, 2001-01-01, 01:00, 1.1
1, 2001-01-01, 02:00, 1.2
1, 2001-01-01, 03:00, 1.3
""")
data2 = StringIO("""\
2, 2001-01-01, 00:00, 2.0
2, 2001-01-01, 01:00, -99
2, 2001-01-01, 02:00, 2.2
2, 2001-01-01, 03:00, 2.3
""")
data3 = StringIO("""\
3, 2001-01-01, 00:00, 3.0
3, 2001-01-01, 01:00, 3.1
3, 2001-01-01, 02:00, -99
3, 2001-01-01, 03:00, 3.3
3, 2001-01-01, 04:00, 3.4
""")
columns = ['id','date','time','T1']
df1 = pd.read_table(data1, header=None, names=columns, delimiter=',', na_values=-99, parse_dates=[['date','time']])
columns = ['id','date','time','T2']
df2 = pd.read_table(data2, header=None, names=columns, delimiter=',', na_values=-99, parse_dates=[['date','time']])
columns = ['id','date','time','T3']
df3 = pd.read_table(data3, header=None, names=columns, delimiter=',', na_values=-99, parse_dates=[['date','time']])
df = pd.concat([df1,df2,df3]).groupby('date_time').max()
df = df.dropna(subset=['T1','T2','T3'])
</code></pre>
<p>The resulting <code>Dataframe</code> looks like:</p>
<pre><code>In [232]: df
Out[232]:
T1 T2 T3 id
date_time
2001-01-01 00:00:00 1.0 2.0 3.0 3
2001-01-01 03:00:00 1.3 2.3 3.3 3
</code></pre>
<p>And if I want to compare only two sites, ignoring in this case <code>T3</code>, a <code>df.dropna(subset=['T1','T2'])</code> results in:</p>
<pre><code>In [234]: df
Out[234]:
T1 T2 T3 id
date_time
2001-01-01 00:00:00 1.0 2.0 3.0 3
2001-01-01 02:00:00 1.2 2.2 NaN 3
2001-01-01 03:00:00 1.3 2.3 3.3 3
</code></pre>
<p>Is this the way to go? Still feels a bit non-Panda-ish..?</p>
| 0 | 2016-10-05T05:50:01Z | [
"python",
"pandas",
"time-series"
]
|
Cannot access elements in a list in Python | 39,854,455 | <p>I working with bigrams and unigrams. </p>
<p>My bigrams are a counter of tuples and my unigrams are a list, where </p>
<pre><code> uni['some key']=count
</code></pre>
<p>I am trying to do the follwing</p>
<pre><code> for b,countB in bigrams.most_common()
key=b[0] # this is guaranteed to be a key for my unigrams
uniCount=uni[key]
</code></pre>
<p>The following error occurs:</p>
<pre><code> TypeError: tuple indeces must be integers or slices, not str
</code></pre>
<p>I am confused. Why should this be a problem? uni is essentially a hash, its key values are strings. How can I access u[key]?</p>
<p>edit: full code</p>
<pre><code> # corpus is a string containing my corpus
sp=corpus.split()
uni={}
for t in sp:
try:
uni[t]+=1
except:
uni[t]=0
prev=''
big=[]
for t in sp:
tup=(prev,t)
big.append(tup)
prev=t
bigrams=collections.Counter(big)
for b,countB in bigrams.most_common():
key=b[0]
uniCount=uni[key]
</code></pre>
| 1 | 2016-10-04T14:06:29Z | 39,854,538 | <p>You are making the mistake of using a tuple when you perhaps need a dictionary. As the error message state, tuples cannot be indexed by a string key - you are expected to use numeric indices.</p>
<p>A dict will let you use string keys as you appear to want to.</p>
<pre><code>d = {}
d['some key] = 23
</code></pre>
<p>Your updated code gives a much better idea of what you are doing. You start by creating a dict of word counts in <code>uni</code>. I think the line that reads</p>
<pre><code>uni[t] = 0
</code></pre>
<p>should in fact read</p>
<pre><code>uni[t] = 1
</code></pre>
<p>because when that branch is executed you are detecting the first occurrence of a word. Next you create a list of bigram tuples in <code>big</code>, and then you count those bigrams.</p>
<p>I get a bit lost with the final <code>for</code> loop, though, where <code>b</code> will be the key of a <code>Counter</code> item and <code>countB</code> to be the count. So <code>key</code> will be the first word of the bigram, and <code>uniCount</code> will be the number of times that word appeared in the corpus. Having established these value you then proceed to do nothing with them, and move on to the next most common bigram.</p>
<p>Perhaps it's time to do some printing in that final loop? The code as published otherwise looks reasonable.</p>
| 3 | 2016-10-04T14:10:03Z | [
"python",
"nlp",
"tuples",
"n-gram"
]
|
Cannot access elements in a list in Python | 39,854,455 | <p>I working with bigrams and unigrams. </p>
<p>My bigrams are a counter of tuples and my unigrams are a list, where </p>
<pre><code> uni['some key']=count
</code></pre>
<p>I am trying to do the follwing</p>
<pre><code> for b,countB in bigrams.most_common()
key=b[0] # this is guaranteed to be a key for my unigrams
uniCount=uni[key]
</code></pre>
<p>The following error occurs:</p>
<pre><code> TypeError: tuple indeces must be integers or slices, not str
</code></pre>
<p>I am confused. Why should this be a problem? uni is essentially a hash, its key values are strings. How can I access u[key]?</p>
<p>edit: full code</p>
<pre><code> # corpus is a string containing my corpus
sp=corpus.split()
uni={}
for t in sp:
try:
uni[t]+=1
except:
uni[t]=0
prev=''
big=[]
for t in sp:
tup=(prev,t)
big.append(tup)
prev=t
bigrams=collections.Counter(big)
for b,countB in bigrams.most_common():
key=b[0]
uniCount=uni[key]
</code></pre>
| 1 | 2016-10-04T14:06:29Z | 39,855,739 | <p>I have executed your code with <code>corpus = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore"</code> since you said the error was a related to <code>uni</code> being a tuple but it actually is a dictionary.</p>
<p>The error I got is different, it is a <code>KeyError</code> on <code>uniCount=uni[key]</code> because you are creating a list of tuples <code>(previous word, word)</code> and the first word of <code>corpus</code> has previous word set as an empty string (<code>prev=''</code> is the initial state). </p>
<p>The key at the <code>uniCount=uni[key]</code> line is equal to the first item of the tuple (<code>key=b[0]</code>) so as there is no key <code>''</code> in the <code>uni</code> dictionary it is throwing a <code>KeyError</code>.</p>
<p>You may want to get the word, not the previous word of the tuple to be the key used in <code>uni</code>.</p>
| 0 | 2016-10-04T15:03:40Z | [
"python",
"nlp",
"tuples",
"n-gram"
]
|
Cannot access elements in a list in Python | 39,854,455 | <p>I working with bigrams and unigrams. </p>
<p>My bigrams are a counter of tuples and my unigrams are a list, where </p>
<pre><code> uni['some key']=count
</code></pre>
<p>I am trying to do the follwing</p>
<pre><code> for b,countB in bigrams.most_common()
key=b[0] # this is guaranteed to be a key for my unigrams
uniCount=uni[key]
</code></pre>
<p>The following error occurs:</p>
<pre><code> TypeError: tuple indeces must be integers or slices, not str
</code></pre>
<p>I am confused. Why should this be a problem? uni is essentially a hash, its key values are strings. How can I access u[key]?</p>
<p>edit: full code</p>
<pre><code> # corpus is a string containing my corpus
sp=corpus.split()
uni={}
for t in sp:
try:
uni[t]+=1
except:
uni[t]=0
prev=''
big=[]
for t in sp:
tup=(prev,t)
big.append(tup)
prev=t
bigrams=collections.Counter(big)
for b,countB in bigrams.most_common():
key=b[0]
uniCount=uni[key]
</code></pre>
| 1 | 2016-10-04T14:06:29Z | 39,856,117 | <p>I tried your code and got a <code>KeyError: ''</code> which happens because your initial bigram has an empty string at position 0 and <code>''</code> is not in your unigrams dictionary. I didn't see a <code>TypeError</code> so that may be from somewhere else in your code. </p>
<p>That said, various other comments: </p>
<ol>
<li><p>You seem to understand what a <code>collections.Counter</code> does, but you're haphazardly trying to do it yourself while building <code>uni</code> -- you can replace your first chunk of code with:</p>
<p><code>unigrams = Counter(sp)</code></p></li>
<li><p>You can use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to iterate over pairs and construct your bigrams that way, instead of DIY looping it, which also gets rid of your <code>''</code> issue:</p>
<p><code>bigrams = Counter(zip(sp, sp[1:]))</code></p></li>
</ol>
<p>So your code becomes:</p>
<pre><code>sp = corpus.split()
unigrams = Counter(sp)
bigrams = Counter(zip(sp, sp[1:]))
for bigram, count in bigrams.most_common():
# etc.
</code></pre>
| 1 | 2016-10-04T15:20:20Z | [
"python",
"nlp",
"tuples",
"n-gram"
]
|
Python | delimited text file to csv format | 39,854,482 | <p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p>
<pre><code>import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile:
data = infile.read()
data = data.replace("|","")
outfile.write(data)
</code></pre>
<p>This code gets rid of the <strong>|</strong> to a blank but all the data is just in one column now. How can I format this correctly?
I appreciate your help in advance.</p>
| 0 | 2016-10-04T14:07:35Z | 39,854,561 | <p>The simplest way with your code would be to replace "|" with "," rather than removing "|"<br /></p>
<pre><code>data = data.replace("|", ",")
</code></pre>
| 1 | 2016-10-04T14:11:17Z | [
"python",
"python-3.x"
]
|
Python | delimited text file to csv format | 39,854,482 | <p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p>
<pre><code>import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile:
data = infile.read()
data = data.replace("|","")
outfile.write(data)
</code></pre>
<p>This code gets rid of the <strong>|</strong> to a blank but all the data is just in one column now. How can I format this correctly?
I appreciate your help in advance.</p>
| 0 | 2016-10-04T14:07:35Z | 39,854,583 | <p>You're importing the <code>csv</code> module, but aren't using it. Make use of <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow"><code>csv.reader</code></a></p>
<pre><code>with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile:
reader = csv.reader(infile, delimiter='|')
</code></pre>
| 1 | 2016-10-04T14:12:27Z | [
"python",
"python-3.x"
]
|
Python | delimited text file to csv format | 39,854,482 | <p>I'm new to python but I'm having trouble reading a text file which contains data separated by "|" as the delimiter. How would I separate the file into columns in a CSV format.</p>
<pre><code>import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
with open(my_file_name, 'r') as infile, open(cleaned_file, 'w') as outfile:
data = infile.read()
data = data.replace("|","")
outfile.write(data)
</code></pre>
<p>This code gets rid of the <strong>|</strong> to a blank but all the data is just in one column now. How can I format this correctly?
I appreciate your help in advance.</p>
| 0 | 2016-10-04T14:07:35Z | 39,854,585 | <p>The <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow"><code>csv</code> module</a> allows you to read csv files with practically arbitrary delimiters.</p>
<pre><code>with open(my_file_name, 'r', newline='') as infile:
for line in csv.reader(infile, delimiter='|'):
# do stuff
</code></pre>
<p>If you really want to reformat the file, you can use the <code>csv.writer</code> directly:</p>
<pre><code>with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w', newline='') as outfile:
writer = csv.writer(outfile)
for line in csv.reader(infile, delimiter='|'):
writer.writerow(line)
</code></pre>
<hr>
<p>Note that your approach doesn't work because you <em>remove</em> the separator instead of replacing it. <code>data.replace("|","")</code> will replace each <code>|</code> with the empty string, i.e. <code>"foo|bar"</code> becomes <code>"foobar"</code>. You must replace the old separator with a <em>new</em> one, e.g. <code>data.replace("|", ",")</code>.</p>
| 5 | 2016-10-04T14:12:30Z | [
"python",
"python-3.x"
]
|
Python: write numpy array (int) to binary file without padding | 39,854,637 | <p>I have a binary file that was created in Fortran consisting of integer values as records. I want to read these into Python, edit them as lists and save them back to binary as np-arrays. For some reason, however, Python inserts an additional "0" after every record in the file. I guess this is what they call "padding", right? How do I suppress this?</p>
<p>Here's a standalone example:</p>
<pre><code>import numpy as np
content = np.array(range(20))
# Write:
with open('D:/bin_test.dat', 'wb') as write_binary:
write_binary.writelines(content)
# Read:
with open('D:/bin_test.dat', 'rb') as read_binary:
content = np.fromfile(read_binary, dtype=np.int16)
print content
Out:
[ 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11
0 12 0 13 0 14 0 15 0 16 0 17 0 18 0 19 0]
</code></pre>
<p>If I read the Fortran binary file via <code>np.fromfile</code> and save it back to binary directly, it works just fine. That's why I guess the problem occurs after conversion from list to numpy array.</p>
<p>Thanks!</p>
| 0 | 2016-10-04T14:14:51Z | 39,855,050 | <p>Check <code>content.dtype</code>. It looks like it is <code>np.int32</code>, which is generally the default integer type on Windows. You are writing 32 bit integers, but then trying to read them back as 16 bit integers. So every other value in the result is 0.</p>
| 1 | 2016-10-04T14:34:12Z | [
"python",
"python-2.7",
"numpy",
"io",
"binary"
]
|
peewee DateField property is None with MySQL database | 39,854,677 | <p>Via <code>pwiz</code> on my MySQL database, I get:</p>
<pre><code>class BaseModel(Model):
class Meta:
database = database
class Pub(BaseModel):
...
author = TextField(null=True)
...
publish_date = DateField(null=True)
...
</code></pre>
<p>Then, when iterating <code>entry in Pub.select()</code>, <code>entry.publish_date</code> is always <code>None</code>, although all entries in the database have the date set (or at least part of it, such as year, i.e. an entry like <code>2016-00-00</code>).</p>
<p>(There is a <a href="http://stackoverflow.com/questions/12089590/datefield-always-return-none-value">related question</a> but that problem is different: it is not set, and thus the solution was <code>auto_now_add</code>.)</p>
<p>Why is that? Maybe <code>formats</code> is wrong? How to fix this?</p>
<p>How to debug this?</p>
<hr>
<p>Some debugging:</p>
<p>I guess that <code>peewee</code> will use <code>pymsql</code> under the hood. So I tried to do this simple thing:</p>
<pre><code>import pymysql
conn = pymysql.connect(...)
cur = conn.cursor()
cur.execute("SELECT publish_date FROM pub")
</code></pre>
<p>And then iterating <code>row in cur</code>, I will only get <code>row == (None,)</code>.</p>
<p>When casting the value beforehand to <code>char</code>, it works, i.e. I get the value as a string:</p>
<pre><code>cur.execute("SELECT CAST(publish_date AS char) FROM pub")
</code></pre>
<p>I think this is a bug now. I reported this <a href="https://github.com/coleifer/peewee/issues/1086" rel="nofollow">here for peewee</a> and <a href="https://github.com/PyMySQL/PyMySQL/issues/520" rel="nofollow">here for pymysql</a>.</p>
| 1 | 2016-10-04T14:16:54Z | 39,868,401 | <p>This is a <a href="https://github.com/PyMySQL/PyMySQL/issues/520" rel="nofollow">problem/bug in pymysql</a> although it is not clear yet how pymysql should handle it.</p>
<p>For now, this monkey-patch-method fixes the problem to some degree; it will return the date as a string if it is not representable as a <code>datetime</code> object.</p>
<pre><code>def monkey_patch_pymysql_date_fix():
import pymysql
orig_convert_date = pymysql.converters.convert_date
def fixed_convert_date(obj):
res = orig_convert_date(obj)
if res is None:
return obj
return res
pymysql.converters.convert_date = fixed_convert_date
from pymysql.constants import FIELD_TYPE
pymysql.converters.decoders[FIELD_TYPE.DATE] = fixed_convert_date
pymysql.converters.conversions[FIELD_TYPE.DATE] = fixed_convert_date
</code></pre>
| 0 | 2016-10-05T07:57:30Z | [
"python",
"mysql",
"peewee"
]
|
Is there any way to generate list exponentially in Python? | 39,854,722 | <p>I have a dictionary:</p>
<p>D = {1:[1,2,3], 2:[4,5], 3: [6,7]}</p>
<p>What I wish to do is to find all 3*2*2 combinations,</p>
<pre><code> [[1,4,6], [1,4,7],
[1,5,6], [1,5,7],
[2,4,6], [2,4,6],
[2,5,6], [2,5,7],
[3,4,6], [3,4,7],
[3,5,6], [3,5,7] ]
</code></pre>
<p>Is there any way, just doing loop like</p>
<pre><code>for key in D:
for num in D[key]:
for xxxxx
</code></pre>
<p>and then carry out the all combination? Thanks! </p>
| 0 | 2016-10-04T14:18:54Z | 39,854,776 | <p>Use <a href="https://docs.python.org/3/library/itertools.html#itertools.product"><strong><code>itertools.product</code></strong></a>:</p>
<pre><code>itertools.product(*D.values())
</code></pre>
<p>Example:</p>
<pre><code>>>> import itertools
>>> D = {1:[1,2,3], 2:[4,5], 3: [6,7]}
>>> list(itertools.product(*D.values()))
[(1, 4, 6), (1, 4, 7), (1, 5, 6), (1, 5, 7), (2, 4, 6), (2, 4, 7),
(2, 5, 6), (2, 5, 7), (3, 4, 6), (3, 4, 7), (3, 5, 6), (3, 5, 7)]
</code></pre>
| 6 | 2016-10-04T14:21:47Z | [
"python",
"list",
"hashtable"
]
|
Access nested key-values in Python dictionary | 39,854,726 | <p>I have the following dictionary structure and Iam trying to access the <code>total_payments</code> field. It is like accessing key of keys in Python dictionary:</p>
<pre><code>d = {'METTS MARK': {'bonus': 600000,
'deferral_payments': 'NaN',
'deferred_income': 'NaN',
'director_fees': 'NaN',
'email_address': 'a@b.com',
'exercised_stock_options': 'NaN',
'expenses': 94299,
'from_messages': 29,
'from_poi_to_this_person': 38,
'from_this_person_to_poi': 1,
'loan_advances': 'NaN',
'long_term_incentive': 'NaN',
'other': 1740,
'poi': False,
'restricted_stock': 585062,
'restricted_stock_deferred': 'NaN',
'salary': 365788,
'shared_receipt_with_poi': 702,
'to_messages': 807,
'total_payments': 1061827,
'total_stock_value': 585062}}
</code></pre>
| -3 | 2016-10-04T14:19:14Z | 39,854,812 | <p>Hard to read your dictionary, but there's an example:</p>
<pre><code>dic = {'abc': {'123': '2'}}
print(dic['abc']['123'])
#prints 2
</code></pre>
<p>and if your dictionary had two sub dictionaries: </p>
<pre><code>dic = {'abc': [{'123': '2'}, {'456': '4'}]}
print(dic['abc'][1]['456'])
# prints 4
</code></pre>
<p>in your case:</p>
<pre><code>value['total_payments']
#returns 1061827
</code></pre>
| 1 | 2016-10-04T14:23:32Z | [
"python",
"dictionary"
]
|
Access nested key-values in Python dictionary | 39,854,726 | <p>I have the following dictionary structure and Iam trying to access the <code>total_payments</code> field. It is like accessing key of keys in Python dictionary:</p>
<pre><code>d = {'METTS MARK': {'bonus': 600000,
'deferral_payments': 'NaN',
'deferred_income': 'NaN',
'director_fees': 'NaN',
'email_address': 'a@b.com',
'exercised_stock_options': 'NaN',
'expenses': 94299,
'from_messages': 29,
'from_poi_to_this_person': 38,
'from_this_person_to_poi': 1,
'loan_advances': 'NaN',
'long_term_incentive': 'NaN',
'other': 1740,
'poi': False,
'restricted_stock': 585062,
'restricted_stock_deferred': 'NaN',
'salary': 365788,
'shared_receipt_with_poi': 702,
'to_messages': 807,
'total_payments': 1061827,
'total_stock_value': 585062}}
</code></pre>
| -3 | 2016-10-04T14:19:14Z | 39,854,852 | <p>It rather seems that values of your dictionay are dict, and not that the keys are dict.
So you can just access as follows:</p>
<pre><code>your_dict[KEY1]['total_payments']
</code></pre>
<p>Please also anonymize the email address in your example.</p>
| 1 | 2016-10-04T14:24:59Z | [
"python",
"dictionary"
]
|
find index of equal values in an array | 39,854,834 | <p>So I have an array that I read from a file with several numbers. I need to find all the indices of the array equal to a certain value, and I do it in a loop (it's different values each time). It works perfect if I do it one by one, but when I do the loop, I get 0 matches in some cases, and I know the answer shouldn't be zero. It's a long array, but this is the example:</p>
<pre><code>array = [0.2 0.2 0.4 .... 1.0]
m=20
for i in xrange(mbins):
mg = 0.2*i
for j in xrange(iterations):
w = np.where(list == mg)
print w
</code></pre>
<p>But I get w empty for i = 3,4,7, and some other numbers. I really don't understand what's going on. I tried without np.where, but still doesn't work.</p>
<p>(the real code is a bit more complicated than this, but this is where it fails)</p>
<p>Thanks!</p>
| -4 | 2016-10-04T14:24:06Z | 39,855,424 | <p>Is this what you want, getting all indices of a value from a list through iteration:</p>
<pre><code>mg = # some value
start = lst.index(mg)
# first occurrence of mg
print (start)
for i in range(lst.count(mg)-1):
start += lst[start+1:].index(mg)+1
print (start)
</code></pre>
<p>This will return all indices of <code>mg</code> in <code>lst</code>.</p>
| 0 | 2016-10-04T14:50:22Z | [
"python"
]
|
Does this method returns a url? | 39,854,945 | <p>Sorry, I'm learning so forgive me if this is a stupid question.
I got this method (updated):</p>
<pre><code> def get_photo(self, photo_reference):
print(self.photourl)
print(photo_reference)
resp = requests.get(
url='{}{}'.format(self.photourl, photo_reference),
params={'key': self.api_key}
)
try:
return resp.json()
except ValueError:
print('Invalid JSON')
</code></pre>
<p>I built the requests.get with <a href="https://developers.google.com/places/web-service/photos" rel="nofollow">Google Places API - Place Photo</a>.
In my <code>__init__(self):</code></p>
<pre><code>self.place_detail_url = 'https://maps.googleapis.com/maps/api/place/'
self.ref = 'photo?maxwidth=200&photoreference='
self.photourl = self.place_detail_url + self.ref
</code></pre>
<p>I want to get photo from google place API but I tried and it returns None.
I wonder what the <code>get_photo</code> method returns and if it isnt a url. How can I encode it to a url?</p>
| 0 | 2016-10-04T14:29:11Z | 39,856,880 | <p>Maybe try this (Based on your seemingly preferred approach above of building the URL yourself):</p>
<pre><code>def get_photo(self, photo_reference):
request_url = (self.place_detail_url + self.ref + photo_reference + '&key=' + self.api_key)
output_file = (/path/to/image/here/file.png)
with open(output_file, 'wb') as output:
output.write(requests.get(request_url).content)
</code></pre>
| 0 | 2016-10-04T15:58:27Z | [
"python",
"json",
"url",
"request",
"google-places-api"
]
|
Does this method returns a url? | 39,854,945 | <p>Sorry, I'm learning so forgive me if this is a stupid question.
I got this method (updated):</p>
<pre><code> def get_photo(self, photo_reference):
print(self.photourl)
print(photo_reference)
resp = requests.get(
url='{}{}'.format(self.photourl, photo_reference),
params={'key': self.api_key}
)
try:
return resp.json()
except ValueError:
print('Invalid JSON')
</code></pre>
<p>I built the requests.get with <a href="https://developers.google.com/places/web-service/photos" rel="nofollow">Google Places API - Place Photo</a>.
In my <code>__init__(self):</code></p>
<pre><code>self.place_detail_url = 'https://maps.googleapis.com/maps/api/place/'
self.ref = 'photo?maxwidth=200&photoreference='
self.photourl = self.place_detail_url + self.ref
</code></pre>
<p>I want to get photo from google place API but I tried and it returns None.
I wonder what the <code>get_photo</code> method returns and if it isnt a url. How can I encode it to a url?</p>
| 0 | 2016-10-04T14:29:11Z | 39,868,670 | <p>I got my answer, <code>resp</code> is a object and according to HTTP status 200, my URL is good. So I just need to do <code>return resp.url</code> to get the right URL link. It's a small problem but I made it big. Sorry and thank you to all your answer!</p>
| 0 | 2016-10-05T08:12:56Z | [
"python",
"json",
"url",
"request",
"google-places-api"
]
|
how i can go in admin panel is it possible when use sqlite | 39,854,974 | <p>I'm trying to access the sqlite admin at <a href="http://127.0.0.1:8000/admin" rel="nofollow">http://127.0.0.1:8000/admin</a>, but I don't know the user and pass. During <strong>python manage.py migrate</strong>, it did not ask about new user. </p>
<p>Config:</p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.DEC_DB'),
}
</code></pre>
| 0 | 2016-10-04T14:30:35Z | 39,855,151 | <p>Run <code>python manage.py createsuperuser</code> and create Django administrator first. Then you will be able to log-in to admin site using this account.</p>
| 2 | 2016-10-04T14:38:48Z | [
"python",
"django",
"sqlite"
]
|
issue with count variable in Python while loop | 39,855,020 | <p>I have an array of values:</p>
<pre><code>increase_pop = [500, -300, 200, 100]
</code></pre>
<p>I am trying to find the index of the lowest and highest values. Most of my code works and everything seems to be going well except for one problem. The rest of my code looks like the following:</p>
<pre><code>max_value = increase_pop[0]
min_value = increase_pop[0]
count = 0
while count < len(increase_pop):
if increase_pop[count] > max_value:
max_year = count
max_value = increase_pop[count]
elif increase_pop[count] < min_value:
min_value = increase_pop[count]
count += 1
print(min_value)
print(max_value)
</code></pre>
<p>This code gets me the values of the min and max exactly what I want. However, I also want the index values of those positions. So for the max value I have the variable max_year = count assigned to it. Thus, I would think that max_year would be assigned to the count at the position where max_value was found. However, when I do a print(max_year) I get the following error:</p>
<pre><code>UnboundLocalError: local variable 'max_year' referenced before assignment
</code></pre>
<p>Does anyone know what my (probably) small/minor issue is? What am I forgetting?</p>
| 0 | 2016-10-04T14:32:53Z | 39,855,084 | <p><code>max_year</code> is assigned when the first <code>if</code> conditional is satisfied. But if that never happens, <code>max_year</code> will never be assigned. That situation will occur when <code>increase_pop[0]</code> (and hence the initial value of <code>max_value</code>) is the largest value in <code>increase_pop</code>: then <code>increase_pop[count] > max_value</code> will never be true.</p>
<p>In your code, you could simply initialize <code>max_year = count = 0</code></p>
<p>However, IMO the neatest, most Pythonic solution is the one from Patrick Haugh's comment:</p>
<pre><code>max_year, max_value = max( enumerate(increase_pop), key=lambda x: x[1] )
</code></pre>
<p>To unpack that: <code>enumerate(increase_pop)</code> generates a sequence of pairs:</p>
<pre><code>(0, increase_pop[0]), (1, increase_pop[1]), ...
</code></pre>
<p>and the <code>max</code> operator takes the "maximum" such pair according to the criterion specified by the <code>key</code> (and that particular key function just says "only consider the second value in each pair").</p>
| 2 | 2016-10-04T14:35:29Z | [
"python",
"loops"
]
|
issue with count variable in Python while loop | 39,855,020 | <p>I have an array of values:</p>
<pre><code>increase_pop = [500, -300, 200, 100]
</code></pre>
<p>I am trying to find the index of the lowest and highest values. Most of my code works and everything seems to be going well except for one problem. The rest of my code looks like the following:</p>
<pre><code>max_value = increase_pop[0]
min_value = increase_pop[0]
count = 0
while count < len(increase_pop):
if increase_pop[count] > max_value:
max_year = count
max_value = increase_pop[count]
elif increase_pop[count] < min_value:
min_value = increase_pop[count]
count += 1
print(min_value)
print(max_value)
</code></pre>
<p>This code gets me the values of the min and max exactly what I want. However, I also want the index values of those positions. So for the max value I have the variable max_year = count assigned to it. Thus, I would think that max_year would be assigned to the count at the position where max_value was found. However, when I do a print(max_year) I get the following error:</p>
<pre><code>UnboundLocalError: local variable 'max_year' referenced before assignment
</code></pre>
<p>Does anyone know what my (probably) small/minor issue is? What am I forgetting?</p>
| 0 | 2016-10-04T14:32:53Z | 39,855,178 | <p>You can make your codes more pythonic by using the feature of list:</p>
<pre><code>min_value = min(increase_pop)
max_value = max(increase_pop)
min_value_index = increase_pop.index(min_value)
max_value_index = increase_pop.index(max_value)
</code></pre>
| 2 | 2016-10-04T14:40:07Z | [
"python",
"loops"
]
|
matplotlib selecting wrong font style/weight | 39,855,124 | <p>I want to change the default font used in matplotlib plots to be Segoe UI under Windows. I can do so by altering <code>rcParams</code> like so</p>
<pre><code>import matplotlib
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['Segoe UI'] + matplotlib.rcParams['font.sans-serif']
matplotlib.rcParams['font.weight'] = 'normal'
</code></pre>
<p>This works, however the weight of the font appears to be wrong. Using the following code I can confirm that matplotlib is picking up the 'Semibold' version of the font rather than the 'Regular' variant that I would expect from setting <code>matplotlib.rcParams['font.weight'] = 'normal'</code>.</p>
<pre><code>from matplotlib.font_manager import findfont, FontProperties
font = findfont(FontProperties(family=['sans-serif']))
print font
>>> c:\windows\fonts\seguisb.ttf
</code></pre>
<p>How can I force matplotlib to use the 'Regular' variant? Is this possible with <code>rcParams</code>?</p>
| 0 | 2016-10-04T14:37:00Z | 39,858,940 | <p>It seems that matplotlib selects out of all the "Segoe UI" fonts the bold one for no reason. I fear that you cannot do much about this on the rcParams level.</p>
<p>If someone finds a solution to this issue I'd really appreciate it as well. </p>
<p>Until then, here is a workaround using the <code>fontproperties</code> kwarg.</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
fig, ax = plt.subplots()
path = r'C:\Windows\Fonts\segoeui.ttf'
path1 = r'C:\Windows\Fonts\seguisb.ttf'
path2 = r'C:\Windows\Fonts\arial.ttf'
for i, p in enumerate([path,path1,path2]):
prop = font_manager.FontProperties(fname=p)
tx = 'Text in {font},\n{path}\nweight {weight}\nvariant {var}'
tx = tx.format(font=prop.get_name(), weight=prop.get_weight(), var=prop.get_variant(), path=p)
ax.text(0.1,0.1+i*0.3,tx, fontproperties=prop, size=18)
plt.show()
</code></pre>
<p>The disadvantage clearly is that you need to manually put it everywhere, instead of putting it once in the header.</p>
| 1 | 2016-10-04T18:03:28Z | [
"python",
"matplotlib",
"fonts"
]
|
Repeating characters results in wrong repetition counts | 39,855,170 | <p>My function looks like this:</p>
<pre><code>def accum(s):
a = []
for i in s:
b = s.index(i)
a.append(i * (b+1))
x = "-".join(a)
return x.title()
</code></pre>
<p>with the expected input of:</p>
<pre><code>'abcd'
</code></pre>
<p>the output should be and is:</p>
<pre><code>'A-Bb-Ccc-Dddd'
</code></pre>
<p>but if the input has a recurring character:</p>
<pre><code>'abccba'
</code></pre>
<p>it returns:</p>
<pre><code>'A-Bb-Ccc-Ccc-Bb-A'
</code></pre>
<p>instead of:</p>
<pre><code>'A-Bb-Ccc-Cccc-Bbbbb-Aaaaaa'
</code></pre>
<p>how can I fix this?</p>
| 0 | 2016-10-04T14:39:43Z | 39,855,231 | <p>Don't use <code>str.index()</code>, it'll return the <em>first match</em>. Since <code>c</code> and <code>b</code> and a appear early in the string you get <code>2</code>, <code>1</code> and <code>0</code> back regardless of the position of the <em>current</em> letter.</p>
<p>Use the <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code> function</a> to give you position counter instead:</p>
<pre><code>for i, letter in enumerate(s, 1):
a.append(i * letter)
</code></pre>
<p>The second argument is the starting value; setting this to 1 means you can avoid having to <code>+ 1</code> later on. See <a href="https://stackoverflow.com/questions/22171558/what-does-enumerate-mean">What does enumerate mean?</a> if you need more details on what <code>enumerate()</code> does.</p>
<p>You can use a list comprehension here rather than use <code>list.append()</code> calls:</p>
<pre><code>def accum(s):
a = [i * letter for i, letter in enumerate(s, 1)]
x = "-".join(a)
return x.title()
</code></pre>
<p>which could, at a pinch, be turned into a one-liner:</p>
<pre><code>def accum(s):
a = '-'.join([i * c for i, c in enumerate(s, 1)]).title()
</code></pre>
| 2 | 2016-10-04T14:42:53Z | [
"python"
]
|
Repeating characters results in wrong repetition counts | 39,855,170 | <p>My function looks like this:</p>
<pre><code>def accum(s):
a = []
for i in s:
b = s.index(i)
a.append(i * (b+1))
x = "-".join(a)
return x.title()
</code></pre>
<p>with the expected input of:</p>
<pre><code>'abcd'
</code></pre>
<p>the output should be and is:</p>
<pre><code>'A-Bb-Ccc-Dddd'
</code></pre>
<p>but if the input has a recurring character:</p>
<pre><code>'abccba'
</code></pre>
<p>it returns:</p>
<pre><code>'A-Bb-Ccc-Ccc-Bb-A'
</code></pre>
<p>instead of:</p>
<pre><code>'A-Bb-Ccc-Cccc-Bbbbb-Aaaaaa'
</code></pre>
<p>how can I fix this?</p>
| 0 | 2016-10-04T14:39:43Z | 39,855,242 | <p>This is because <code>s.index(a)</code> returns the first index of the character. You can use <code>enumerate</code> to pair elements to their indices:</p>
<p>Here is a Pythonic solution:</p>
<pre><code>def accum(s):
return "-".join(c*(i+1) for i, c in enumerate(s)).title()
</code></pre>
| 2 | 2016-10-04T14:43:14Z | [
"python"
]
|
Repeating characters results in wrong repetition counts | 39,855,170 | <p>My function looks like this:</p>
<pre><code>def accum(s):
a = []
for i in s:
b = s.index(i)
a.append(i * (b+1))
x = "-".join(a)
return x.title()
</code></pre>
<p>with the expected input of:</p>
<pre><code>'abcd'
</code></pre>
<p>the output should be and is:</p>
<pre><code>'A-Bb-Ccc-Dddd'
</code></pre>
<p>but if the input has a recurring character:</p>
<pre><code>'abccba'
</code></pre>
<p>it returns:</p>
<pre><code>'A-Bb-Ccc-Ccc-Bb-A'
</code></pre>
<p>instead of:</p>
<pre><code>'A-Bb-Ccc-Cccc-Bbbbb-Aaaaaa'
</code></pre>
<p>how can I fix this?</p>
| 0 | 2016-10-04T14:39:43Z | 39,855,290 | <p>simple:</p>
<pre><code>def accum(s):
a = []
for i in range(len(s)):
a.append(s[i]*(i+1))
x = "-".join(a)
return x.title()
</code></pre>
| 0 | 2016-10-04T14:45:24Z | [
"python"
]
|
How to implement momentum-based stochastic gradient descent (SGD) | 39,855,184 | <p>I am using the python code network3.py (<a href="http://neuralnetworksanddeeplearning.com/chap6.html" rel="nofollow">http://neuralnetworksanddeeplearning.com/chap6.html</a>) for developing convolutional neural networks. Now I want to modify the code a little bit by adding a momentum learning rule as follows:</p>
<pre><code>velocity = momentum_constant * velocity - learning_rate * gradient
params = params + velocity
</code></pre>
<p>Is there anyone knowing how to do that? In particular, how to set up or initialize the velocity? I post the codes for SGD below:</p>
<pre><code>def __init__(self, layers, mini_batch_size):
"""Takes a list of `layers`, describing the network architecture, and
a value for the `mini_batch_size` to be used during training
by stochastic gradient descent.
"""
self.layers = layers
self.mini_batch_size = mini_batch_size
self.params = [param for layer in self.layers for param in layer.params]
self.x = T.matrix("x")
self.y = T.ivector("y")
init_layer = self.layers[0]
init_layer.set_inpt(self.x, self.x, self.mini_batch_size)
for j in xrange(1, len(self.layers)):
prev_layer, layer = self.layers[j-1], self.layers[j]
layer.set_inpt(
prev_layer.output, prev_layer.output_dropout, self.mini_batch_size)
self.output = self.layers[-1].output
self.output_dropout = self.layers[-1].output_dropout
def SGD(self, training_data, epochs, mini_batch_size, eta,
validation_data, test_data, lmbda=0.0):
"""Train the network using mini-batch stochastic gradient descent."""
training_x, training_y = training_data
validation_x, validation_y = validation_data
test_x, test_y = test_data
# compute number of minibatches for training, validation and testing
num_training_batches = size(training_data)/mini_batch_size
num_validation_batches = size(validation_data)/mini_batch_size
num_test_batches = size(test_data)/mini_batch_size
# define the (regularized) cost function, symbolic gradients, and updates
l2_norm_squared = sum([(layer.w**2).sum() for layer in self.layers])
cost = self.layers[-1].cost(self)+\
0.5*lmbda*l2_norm_squared/num_training_batches
grads = T.grad(cost, self.params)
updates = [(param, param-eta*grad)
for param, grad in zip(self.params, grads)]
# define functions to train a mini-batch, and to compute the
# accuracy in validation and test mini-batches.
i = T.lscalar() # mini-batch index
train_mb = theano.function(
[i], cost, updates=updates,
givens={
self.x:
training_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],
self.y:
training_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
validate_mb_accuracy = theano.function(
[i], self.layers[-1].accuracy(self.y),
givens={
self.x:
validation_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],
self.y:
validation_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
test_mb_accuracy = theano.function(
[i], self.layers[-1].accuracy(self.y),
givens={
self.x:
test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],
self.y:
test_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
self.test_mb_predictions = theano.function(
[i], self.layers[-1].y_out,
givens={
self.x:
test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size]
})
# Do the actual training
best_validation_accuracy = 0.0
for epoch in xrange(epochs):
for minibatch_index in xrange(num_training_batches):
iteration = num_training_batches*epoch+minibatch_index
if iteration % 1000 == 0:
print("Training mini-batch number {0}".format(iteration))
cost_ij = train_mb(minibatch_index)
if (iteration+1) % num_training_batches == 0:
validation_accuracy = np.mean(
[validate_mb_accuracy(j) for j in xrange(num_validation_batches)])
print("Epoch {0}: validation accuracy {1:.2%}".format(
epoch, validation_accuracy))
if validation_accuracy >= best_validation_accuracy:
print("This is the best validation accuracy to date.")
best_validation_accuracy = validation_accuracy
best_iteration = iteration
if test_data:
test_accuracy = np.mean(
[test_mb_accuracy(j) for j in xrange(num_test_batches)])
print('The corresponding test accuracy is {0:.2%}'.format(
test_accuracy))
</code></pre>
| 0 | 2016-10-04T14:40:32Z | 39,855,990 | <p>I have only ever coded up SDG from scratch (not using theano), but judging from your code you need to </p>
<p>1) initiate the <code>velocities</code> with a bunch of zeros (one per gradient),</p>
<p>2) include the velocity in your updates; something like </p>
<pre><code>updates = [(param, param-eta*grad +momentum_constant*vel)
for param, grad, vel in zip(self.params, grads, velocities)]
</code></pre>
<p>3) amend your training function to return the gradients on each iteration so that you can update the <code>velocities</code>. </p>
| 1 | 2016-10-04T15:15:14Z | [
"python",
"momentum"
]
|
Looking to emulate the functionality of socat in Python | 39,855,187 | <p>I need to send a string to a particular port on localhost using python.</p>
<p>I can achieve this by using socat on the command line like such:</p>
<pre><code>cat <text file containing string to send> | socat stdin tcp-connect:127.0.0.1:55559
</code></pre>
<p>I don't want to run the socat command as a subcommand so I'd like to know how to get this working using a python module.</p>
<p>My attempts at using sockets failed. Below is a script I was using which wasn't achieving the desired effect.</p>
<pre><code> import socket
HOST, PORT = "127.0.0.1", 55559
jsonString = '{"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Attempting connection"
sock.connect((HOST, PORT))
print "Sending json string"
sock.sendall(jsonString)
print "String sent"
finally:
sock.close()
print "Sent: {}".format(jsonString)
</code></pre>
<p>The python script was executing without any errors but there wasn't any effect on the process which was receiving the socat data. Python script output below:</p>
<pre><code> Attempting connection
Sending json string
Sent: {"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}
</code></pre>
<p>Is there something I'm doing wrong in the socket script or is there a different method I can use in Python? I'd appreciate any advice. Thanks.</p>
<p>Edit: The server I'm trying to send strings to is part of a C++ program using boost asio acceptor to listen for tcp connections on a specific address and port.</p>
| 0 | 2016-10-04T14:40:50Z | 39,856,617 | <p>According to <a href="https://linux.die.net/man/1/socat" rel="nofollow">the socat man page</a>,</p>
<blockquote>
<p>When one channel has reached EOF, the write part of the other channel is shut down. Then, socat waits <code>timeout</code> seconds before terminating. Default is 0.5 seconds. </p>
</blockquote>
<p>Perhaps you need to defer your close by 0.5 seconds, like so:</p>
<pre><code>finally:
#sock.close()
sock.shutdown(socket.SHUT_WR)
time.sleep(0.5)
sock.close()
</code></pre>
<p>Or, perhaps you need to absorb the server's shutdown message, like so:</p>
<pre><code>finally:
#sock.close()
sock.shutdown(socket.SHUT_WR)
sock.recv(999999)
sock.close()
</code></pre>
| 0 | 2016-10-04T15:46:12Z | [
"python",
"socketserver",
"socat"
]
|
Looking to emulate the functionality of socat in Python | 39,855,187 | <p>I need to send a string to a particular port on localhost using python.</p>
<p>I can achieve this by using socat on the command line like such:</p>
<pre><code>cat <text file containing string to send> | socat stdin tcp-connect:127.0.0.1:55559
</code></pre>
<p>I don't want to run the socat command as a subcommand so I'd like to know how to get this working using a python module.</p>
<p>My attempts at using sockets failed. Below is a script I was using which wasn't achieving the desired effect.</p>
<pre><code> import socket
HOST, PORT = "127.0.0.1", 55559
jsonString = '{"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Attempting connection"
sock.connect((HOST, PORT))
print "Sending json string"
sock.sendall(jsonString)
print "String sent"
finally:
sock.close()
print "Sent: {}".format(jsonString)
</code></pre>
<p>The python script was executing without any errors but there wasn't any effect on the process which was receiving the socat data. Python script output below:</p>
<pre><code> Attempting connection
Sending json string
Sent: {"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}
</code></pre>
<p>Is there something I'm doing wrong in the socket script or is there a different method I can use in Python? I'd appreciate any advice. Thanks.</p>
<p>Edit: The server I'm trying to send strings to is part of a C++ program using boost asio acceptor to listen for tcp connections on a specific address and port.</p>
| 0 | 2016-10-04T14:40:50Z | 39,857,096 | <p>You shall never close a socket immediately after writing into a socket: the close could swallow still unsent data.</p>
<p>The correct workflow is what is called a <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms738547%28v=vs.85%29.aspx" rel="nofollow">graceful shutdown</a>:</p>
<ul>
<li>the part that wants to close the connection uses a shutdown-write on the socket and keeps on reading</li>
<li>the other part detects a 0 bytes read from the socket which is sees as an end of file. It closes its socket</li>
<li>the initiator detects a 0 bytes read and can safely close the socket</li>
</ul>
<p>So the <code>finally</code> part becomes:</p>
<pre><code>finally:
try:
sock.shutdown(socket.SHUT_WR)
while True:
dummy = sock.recv(1024)
if len(dummy) == 0: break
finally:
sock.close()
</code></pre>
| 0 | 2016-10-04T16:09:26Z | [
"python",
"socketserver",
"socat"
]
|
Looking to emulate the functionality of socat in Python | 39,855,187 | <p>I need to send a string to a particular port on localhost using python.</p>
<p>I can achieve this by using socat on the command line like such:</p>
<pre><code>cat <text file containing string to send> | socat stdin tcp-connect:127.0.0.1:55559
</code></pre>
<p>I don't want to run the socat command as a subcommand so I'd like to know how to get this working using a python module.</p>
<p>My attempts at using sockets failed. Below is a script I was using which wasn't achieving the desired effect.</p>
<pre><code> import socket
HOST, PORT = "127.0.0.1", 55559
jsonString = '{"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}'
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Attempting connection"
sock.connect((HOST, PORT))
print "Sending json string"
sock.sendall(jsonString)
print "String sent"
finally:
sock.close()
print "Sent: {}".format(jsonString)
</code></pre>
<p>The python script was executing without any errors but there wasn't any effect on the process which was receiving the socat data. Python script output below:</p>
<pre><code> Attempting connection
Sending json string
Sent: {"name":"VideoStreamStatus","parameters":{"name":"video_0_0"}}
</code></pre>
<p>Is there something I'm doing wrong in the socket script or is there a different method I can use in Python? I'd appreciate any advice. Thanks.</p>
<p>Edit: The server I'm trying to send strings to is part of a C++ program using boost asio acceptor to listen for tcp connections on a specific address and port.</p>
| 0 | 2016-10-04T14:40:50Z | 39,875,265 | <p>Turned out to be something really simple. The string I was sending using socat (which the server was receiving and processing successfully) had a newline on the end of it. The string I was sending over the python socket didn't have a new line. After adding a new line to the end of the python script the server receives the string as expected.</p>
<p>I only realised that there was a newline after one and not the other after running a python server script listening on a different port and sending the string using both methods.</p>
| 0 | 2016-10-05T13:26:33Z | [
"python",
"socketserver",
"socat"
]
|
Why round(4.5) == 4 and round(5.5) == 6 in Python 3.5? | 39,855,258 | <p>Looks like both 4.5 and 5.5 have exact float representations in Python 3.5:</p>
<pre><code>>>> from decimal import Decimal
>>> Decimal(4.5)
Decimal('4.5')
>>> Decimal(5.5)
Decimal('5.5')
</code></pre>
<p>If this is the case, then why</p>
<pre><code>>>> round(4.5)
4
>>> round(5.5)
6
</code></pre>
<p>?</p>
| 0 | 2016-10-04T14:43:43Z | 39,855,303 | <p>Python 3 uses Bankers Rounding, which rounds <code>.5</code> values to the closest even number.</p>
| 3 | 2016-10-04T14:46:08Z | [
"python",
"floating-point",
"floating-accuracy"
]
|
Why round(4.5) == 4 and round(5.5) == 6 in Python 3.5? | 39,855,258 | <p>Looks like both 4.5 and 5.5 have exact float representations in Python 3.5:</p>
<pre><code>>>> from decimal import Decimal
>>> Decimal(4.5)
Decimal('4.5')
>>> Decimal(5.5)
Decimal('5.5')
</code></pre>
<p>If this is the case, then why</p>
<pre><code>>>> round(4.5)
4
>>> round(5.5)
6
</code></pre>
<p>?</p>
| 0 | 2016-10-04T14:43:43Z | 39,855,329 | <p>In Python 3, exact half way numbers are rounded to the nearest even result. This <a href="https://docs.python.org/3/whatsnew/3.0.html#builtins">behavior changed in Python 3</a></p>
<blockquote>
<p>The <a href="https://docs.python.org/3/library/functions.html#round"><code>round()</code></a> function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example, round(2.5) now returns 2 rather than 3.) round(x[, n]) now delegates to x.<strong>round</strong>([n]) instead of always returning a float. It generally returns an integer when called with a single argument and a value of the same type as x when called with two arguments.</p>
</blockquote>
| 5 | 2016-10-04T14:46:49Z | [
"python",
"floating-point",
"floating-accuracy"
]
|
what's the difference between GTK 3.14 and 3.18 on the css load | 39,855,273 | <p>I finish a GTK interface with GTK3.18,and it works well,but when i change to GTK3.14 version,the interface turn out to be very bad,the size and the colore of the widgets is changed,and i find there is no enough information about the GTK3.14 version.</p>
| 0 | 2016-10-04T14:44:21Z | 39,872,085 | <p>The CSS 'api' was basically undocumented and unstable before 3.20 so there isn't really any reasonable way to support all versions before it unless you make a separate theme for each version.</p>
| 1 | 2016-10-05T10:55:35Z | [
"python",
"css",
"gtk"
]
|
access item in JSON result | 39,855,294 | <p>I am a bit confused as to how access <code>artists</code> <strong>name</strong> in this <code>json</code> result:</p>
<pre><code>{
"tracks" : {
"href" : "https://api.spotify.com/v1/search?query=karma+police&offset=0&limit=20&type=track&market=BR",
"items" : [ {
"album" : {
"album_type" : "album",
"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TR", "TW", "US", "UY" ],
"external_urls" : {
"spotify" : "https://open.spotify.com/album/7dxKtc08dYeRVHt3p9CZJn"
},
"href" : "https://api.spotify.com/v1/albums/7dxKtc08dYeRVHt3p9CZJn",
"id" : "7dxKtc08dYeRVHt3p9CZJn",
"images" : [ {
"height" : 640,
"url" : "https://i.scdn.co/image/f89c1ecdd0cc5a23d5ad7303d4ae231d197dde98",
"width" : 640
}, {
"height" : 300,
"url" : "https://i.scdn.co/image/1b898f0b8e3ce499d0fc629a1918c144d982e475",
"width" : 300
}, {
"height" : 64,
"url" : "https://i.scdn.co/image/faf295a70a6531826a8c25d33aad7d2cd9c75c7a",
"width" : 64
} ],
"name" : "OK Computer",
"type" : "album",
"uri" : "spotify:album:7dxKtc08dYeRVHt3p9CZJn"
},
"artists" : [ {
"external_urls" : {
"spotify" : "https://open.spotify.com/artist/4Z8W4fKeB5YxbusRsdQVPb"
},
"href" : "https://api.spotify.com/v1/artists/4Z8W4fKeB5YxbusRsdQVPb",
"id" : "4Z8W4fKeB5YxbusRsdQVPb",
"name" : "Radiohead",
"type" : "artist",
"uri" : "spotify:artist:4Z8W4fKeB5YxbusRsdQVPb"
} ],
</code></pre>
<p>starting form : <code>results = sp.search(q=track, type='track')</code>,</p>
<p>I've tried <code>items = results['tracks']['items']['artists']['name']</code>, to no avail. </p>
<p>can someone please help?</p>
<p>EDIT: this is part of my <code>print (result)</code>:</p>
<p><code>{u'tracks': {u'items': [{u'album': {u'album_type': u'single', u'name': u"Told You I'd Be with the Guys", u'external_urls': {u'spotify': u'https://open.spotify.com/album/5T3yXvWzj9LOFjUNu3s6Sp'}, u'uri': u'spotify:album:5T3yXvWzj9LOFjUNu3s6Sp', u'href': u'https://api.spotify.com/v1/albums/5T3yXvWzj9LOFjUNu3s6Sp', u'images': [{u'url': u'https://i.scdn.co/image/520d8039048ea52c917f73360983678b7699e48e', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/ab137f85737b9109944bbd65b73d13cb9969fc1c', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/49018040279b8f68ff74fc940257e6ced4c72508', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'5T3yXvWzj9LOFjUNu3s6Sp', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u"Told You I'd Be with the Guys", u'uri': u'spotify:track:2GeIr050NcweBQzsabIYfB', u'external_urls': {u'spotify': u'https://open.spotify.com/track/2GeIr050NcweBQzsabIYfB'}, u'popularity': 45, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/16e7af443fa59b8be61385ca71d5f76c7a7f1f8a', u'track_number': 1, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/2GeIr050NcweBQzsabIYfB', u'artists': [{u'name': u'Cherry Glazerr', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/3pIGm1omCcHIb1juBNHspg'}, u'uri': u'spotify:artist:3pIGm1omCcHIb1juBNHspg', u'href': u'https://api.spotify.com/v1/artists/3pIGm1omCcHIb1juBNHspg', u'type': u'artist', u'id': u'3pIGm1omCcHIb1juBNHspg'}], u'duration_ms': 273946, u'external_ids': {u'isrc': u'US38W1634501'}, u'type': u'track', u'id': u'2GeIr050NcweBQzsabIYfB', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}], u'next': None, u'href': u'https://api.spotify.com/v1/search?query=Told+You+I%27d+Be+With+the+Guys&offset=0&limit=10&type=track', u'limit': 10, u'offset': 0, u'total': 1, u'previous': None}}
2016-10-04 11:55:05 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-04 11:55:06 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Blood+on+Me&limit=10&type=track&offset=0 HTTP/1.1" 200 None
{u'tracks': {u'items': [{u'album': {u'album_type': u'single', u'name': u'Blood On Me', u'external_urls': {u'spotify': u'https://open.spotify.com/album/43hQRnuVUstKeV2uc3DJXv'}, u'uri': u'spotify:album:43hQRnuVUstKeV2uc3DJXv', u'href': u'https://api.spotify.com/v1/albums/43hQRnuVUstKeV2uc3DJXv', u'images': [{u'url': u'https://i.scdn.co/image/a9d6864491cf8c544bd53f532cdc265b3d7ffd77', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/8834ac4ea759929a5cb9c80505a30672cce0daaa', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/ef39d8bdc8df5915679a97b6b8fb6295f9e45bdd', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'43hQRnuVUstKeV2uc3DJXv', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u'Blood On Me', u'uri': u'spotify:track:4JJIj448WHVYw2kEYfIj94', u'external_urls': {u'spotify': u'https://open.spotify.com/track/4JJIj448WHVYw2kEYfIj94'}, u'popularity': 61, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/a217661593e88e4c3363e5bb48f9b3668be36cb3', u'track_number': 1, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/4JJIj448WHVYw2kEYfIj94', u'artists': [{u'name': u'Sampha', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/2WoVwexZuODvclzULjPQtm'}, u'uri': u'spotify:artist:2WoVwexZuODvclzULjPQtm', u'href': u'https://api.spotify.com/v1/artists/2WoVwexZuODvclzULjPQtm', u'type': u'artist', u'id': u'2WoVwexZuODvclzULjPQtm'}], u'duration_ms': 246951, u'external_ids': {u'isrc': u'UK7MC1600028'}, u'type': u'track', u'id': u'4JJIj448WHVYw2kEYfIj94', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, {u'album': {u'album_type': u'album', u'name': u'Blood On The Tracks', u'external_urls': {u'spotify': u'https://open.spotify.com/album/4WD4pslu83FF6oMa1e19mF'}, u'uri': u'spotify:album:4WD4pslu83FF6oMa1e19mF', u'href': u'https://api.spotify.com/v1/albums/4WD4pslu83FF6oMa1e19mF', u'images': [{u'url': u'https://i.scdn.co/image/2facdd8d670a99db33fe829ea917ef95f526a5cc', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/1544214291d2b37d2aad603941e3f89eb05a1f2e', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/1372d865672d6c97048fdb151ed49586718cfa01', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'4WD4pslu83FF6oMa1e19mF', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u'Meet Me in the Morning', u'uri': u'spotify:track:53ygARQf1f30Z0EmXPHWGT', u'external_urls': {u'spotify': u'https://open.spotify.com/track/53ygARQf1f30Z0EmXPHWGT'}, u'popularity': 45, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/9331724efc1c504580759f192699d78d4f6cba44', u'track_number': 6, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/53ygARQf1f30Z0EmXPHWGT', u'artists': [{u'name': u'Bob Dylan', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/74ASZWbe4lXaubB36ztrGX'}, u'uri': u'spotify:artist:74ASZWbe4lXaubB36ztrGX', u'href': u'https://api.spotify.com/v1/artists/74ASZWbe4lXaubB36ztrGX', u'type': u'artist', u'id': u'74ASZWbe4lXaubB36ztrGX'}], u'duration_ms': 258973, u'external_ids': {u'isrc': u'USSM19906473'}, u'type': u'track', u'id': u'53ygARQf1f30Z0EmXPHWGT', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, {u'album': {u'album_type': u'album', u'name': u'Blood On The Tracks', u'external_urls':</code> </p>
| 0 | 2016-10-04T14:45:35Z | 39,855,365 | <p>You should do <code>items = results['tracks']['items'][0]['artists'][0]['name']</code>(although this is technically hardcoded)</p>
<p>As your artist and items object are arrays (with only one, so we reference the first with [0])</p>
| 0 | 2016-10-04T14:48:15Z | [
"python",
"json"
]
|
access item in JSON result | 39,855,294 | <p>I am a bit confused as to how access <code>artists</code> <strong>name</strong> in this <code>json</code> result:</p>
<pre><code>{
"tracks" : {
"href" : "https://api.spotify.com/v1/search?query=karma+police&offset=0&limit=20&type=track&market=BR",
"items" : [ {
"album" : {
"album_type" : "album",
"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TR", "TW", "US", "UY" ],
"external_urls" : {
"spotify" : "https://open.spotify.com/album/7dxKtc08dYeRVHt3p9CZJn"
},
"href" : "https://api.spotify.com/v1/albums/7dxKtc08dYeRVHt3p9CZJn",
"id" : "7dxKtc08dYeRVHt3p9CZJn",
"images" : [ {
"height" : 640,
"url" : "https://i.scdn.co/image/f89c1ecdd0cc5a23d5ad7303d4ae231d197dde98",
"width" : 640
}, {
"height" : 300,
"url" : "https://i.scdn.co/image/1b898f0b8e3ce499d0fc629a1918c144d982e475",
"width" : 300
}, {
"height" : 64,
"url" : "https://i.scdn.co/image/faf295a70a6531826a8c25d33aad7d2cd9c75c7a",
"width" : 64
} ],
"name" : "OK Computer",
"type" : "album",
"uri" : "spotify:album:7dxKtc08dYeRVHt3p9CZJn"
},
"artists" : [ {
"external_urls" : {
"spotify" : "https://open.spotify.com/artist/4Z8W4fKeB5YxbusRsdQVPb"
},
"href" : "https://api.spotify.com/v1/artists/4Z8W4fKeB5YxbusRsdQVPb",
"id" : "4Z8W4fKeB5YxbusRsdQVPb",
"name" : "Radiohead",
"type" : "artist",
"uri" : "spotify:artist:4Z8W4fKeB5YxbusRsdQVPb"
} ],
</code></pre>
<p>starting form : <code>results = sp.search(q=track, type='track')</code>,</p>
<p>I've tried <code>items = results['tracks']['items']['artists']['name']</code>, to no avail. </p>
<p>can someone please help?</p>
<p>EDIT: this is part of my <code>print (result)</code>:</p>
<p><code>{u'tracks': {u'items': [{u'album': {u'album_type': u'single', u'name': u"Told You I'd Be with the Guys", u'external_urls': {u'spotify': u'https://open.spotify.com/album/5T3yXvWzj9LOFjUNu3s6Sp'}, u'uri': u'spotify:album:5T3yXvWzj9LOFjUNu3s6Sp', u'href': u'https://api.spotify.com/v1/albums/5T3yXvWzj9LOFjUNu3s6Sp', u'images': [{u'url': u'https://i.scdn.co/image/520d8039048ea52c917f73360983678b7699e48e', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/ab137f85737b9109944bbd65b73d13cb9969fc1c', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/49018040279b8f68ff74fc940257e6ced4c72508', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'5T3yXvWzj9LOFjUNu3s6Sp', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u"Told You I'd Be with the Guys", u'uri': u'spotify:track:2GeIr050NcweBQzsabIYfB', u'external_urls': {u'spotify': u'https://open.spotify.com/track/2GeIr050NcweBQzsabIYfB'}, u'popularity': 45, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/16e7af443fa59b8be61385ca71d5f76c7a7f1f8a', u'track_number': 1, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/2GeIr050NcweBQzsabIYfB', u'artists': [{u'name': u'Cherry Glazerr', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/3pIGm1omCcHIb1juBNHspg'}, u'uri': u'spotify:artist:3pIGm1omCcHIb1juBNHspg', u'href': u'https://api.spotify.com/v1/artists/3pIGm1omCcHIb1juBNHspg', u'type': u'artist', u'id': u'3pIGm1omCcHIb1juBNHspg'}], u'duration_ms': 273946, u'external_ids': {u'isrc': u'US38W1634501'}, u'type': u'track', u'id': u'2GeIr050NcweBQzsabIYfB', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}], u'next': None, u'href': u'https://api.spotify.com/v1/search?query=Told+You+I%27d+Be+With+the+Guys&offset=0&limit=10&type=track', u'limit': 10, u'offset': 0, u'total': 1, u'previous': None}}
2016-10-04 11:55:05 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-04 11:55:06 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Blood+on+Me&limit=10&type=track&offset=0 HTTP/1.1" 200 None
{u'tracks': {u'items': [{u'album': {u'album_type': u'single', u'name': u'Blood On Me', u'external_urls': {u'spotify': u'https://open.spotify.com/album/43hQRnuVUstKeV2uc3DJXv'}, u'uri': u'spotify:album:43hQRnuVUstKeV2uc3DJXv', u'href': u'https://api.spotify.com/v1/albums/43hQRnuVUstKeV2uc3DJXv', u'images': [{u'url': u'https://i.scdn.co/image/a9d6864491cf8c544bd53f532cdc265b3d7ffd77', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/8834ac4ea759929a5cb9c80505a30672cce0daaa', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/ef39d8bdc8df5915679a97b6b8fb6295f9e45bdd', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'43hQRnuVUstKeV2uc3DJXv', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u'Blood On Me', u'uri': u'spotify:track:4JJIj448WHVYw2kEYfIj94', u'external_urls': {u'spotify': u'https://open.spotify.com/track/4JJIj448WHVYw2kEYfIj94'}, u'popularity': 61, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/a217661593e88e4c3363e5bb48f9b3668be36cb3', u'track_number': 1, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/4JJIj448WHVYw2kEYfIj94', u'artists': [{u'name': u'Sampha', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/2WoVwexZuODvclzULjPQtm'}, u'uri': u'spotify:artist:2WoVwexZuODvclzULjPQtm', u'href': u'https://api.spotify.com/v1/artists/2WoVwexZuODvclzULjPQtm', u'type': u'artist', u'id': u'2WoVwexZuODvclzULjPQtm'}], u'duration_ms': 246951, u'external_ids': {u'isrc': u'UK7MC1600028'}, u'type': u'track', u'id': u'4JJIj448WHVYw2kEYfIj94', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, {u'album': {u'album_type': u'album', u'name': u'Blood On The Tracks', u'external_urls': {u'spotify': u'https://open.spotify.com/album/4WD4pslu83FF6oMa1e19mF'}, u'uri': u'spotify:album:4WD4pslu83FF6oMa1e19mF', u'href': u'https://api.spotify.com/v1/albums/4WD4pslu83FF6oMa1e19mF', u'images': [{u'url': u'https://i.scdn.co/image/2facdd8d670a99db33fe829ea917ef95f526a5cc', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/1544214291d2b37d2aad603941e3f89eb05a1f2e', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/1372d865672d6c97048fdb151ed49586718cfa01', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'4WD4pslu83FF6oMa1e19mF', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u'Meet Me in the Morning', u'uri': u'spotify:track:53ygARQf1f30Z0EmXPHWGT', u'external_urls': {u'spotify': u'https://open.spotify.com/track/53ygARQf1f30Z0EmXPHWGT'}, u'popularity': 45, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/9331724efc1c504580759f192699d78d4f6cba44', u'track_number': 6, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/53ygARQf1f30Z0EmXPHWGT', u'artists': [{u'name': u'Bob Dylan', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/74ASZWbe4lXaubB36ztrGX'}, u'uri': u'spotify:artist:74ASZWbe4lXaubB36ztrGX', u'href': u'https://api.spotify.com/v1/artists/74ASZWbe4lXaubB36ztrGX', u'type': u'artist', u'id': u'74ASZWbe4lXaubB36ztrGX'}], u'duration_ms': 258973, u'external_ids': {u'isrc': u'USSM19906473'}, u'type': u'track', u'id': u'53ygARQf1f30Z0EmXPHWGT', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, {u'album': {u'album_type': u'album', u'name': u'Blood On The Tracks', u'external_urls':</code> </p>
| 0 | 2016-10-04T14:45:35Z | 39,855,372 | <p><code>artists</code> is a <em>list</em> of dicts, because a track can have many artists. Similarly <code>items</code> is also a list. So for example you can do <code>results['tracks']['items'][0]['artists'][0]['name']</code>, but that will only get you the first artist of the first track.</p>
| 1 | 2016-10-04T14:48:39Z | [
"python",
"json"
]
|
access item in JSON result | 39,855,294 | <p>I am a bit confused as to how access <code>artists</code> <strong>name</strong> in this <code>json</code> result:</p>
<pre><code>{
"tracks" : {
"href" : "https://api.spotify.com/v1/search?query=karma+police&offset=0&limit=20&type=track&market=BR",
"items" : [ {
"album" : {
"album_type" : "album",
"available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TR", "TW", "US", "UY" ],
"external_urls" : {
"spotify" : "https://open.spotify.com/album/7dxKtc08dYeRVHt3p9CZJn"
},
"href" : "https://api.spotify.com/v1/albums/7dxKtc08dYeRVHt3p9CZJn",
"id" : "7dxKtc08dYeRVHt3p9CZJn",
"images" : [ {
"height" : 640,
"url" : "https://i.scdn.co/image/f89c1ecdd0cc5a23d5ad7303d4ae231d197dde98",
"width" : 640
}, {
"height" : 300,
"url" : "https://i.scdn.co/image/1b898f0b8e3ce499d0fc629a1918c144d982e475",
"width" : 300
}, {
"height" : 64,
"url" : "https://i.scdn.co/image/faf295a70a6531826a8c25d33aad7d2cd9c75c7a",
"width" : 64
} ],
"name" : "OK Computer",
"type" : "album",
"uri" : "spotify:album:7dxKtc08dYeRVHt3p9CZJn"
},
"artists" : [ {
"external_urls" : {
"spotify" : "https://open.spotify.com/artist/4Z8W4fKeB5YxbusRsdQVPb"
},
"href" : "https://api.spotify.com/v1/artists/4Z8W4fKeB5YxbusRsdQVPb",
"id" : "4Z8W4fKeB5YxbusRsdQVPb",
"name" : "Radiohead",
"type" : "artist",
"uri" : "spotify:artist:4Z8W4fKeB5YxbusRsdQVPb"
} ],
</code></pre>
<p>starting form : <code>results = sp.search(q=track, type='track')</code>,</p>
<p>I've tried <code>items = results['tracks']['items']['artists']['name']</code>, to no avail. </p>
<p>can someone please help?</p>
<p>EDIT: this is part of my <code>print (result)</code>:</p>
<p><code>{u'tracks': {u'items': [{u'album': {u'album_type': u'single', u'name': u"Told You I'd Be with the Guys", u'external_urls': {u'spotify': u'https://open.spotify.com/album/5T3yXvWzj9LOFjUNu3s6Sp'}, u'uri': u'spotify:album:5T3yXvWzj9LOFjUNu3s6Sp', u'href': u'https://api.spotify.com/v1/albums/5T3yXvWzj9LOFjUNu3s6Sp', u'images': [{u'url': u'https://i.scdn.co/image/520d8039048ea52c917f73360983678b7699e48e', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/ab137f85737b9109944bbd65b73d13cb9969fc1c', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/49018040279b8f68ff74fc940257e6ced4c72508', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'5T3yXvWzj9LOFjUNu3s6Sp', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u"Told You I'd Be with the Guys", u'uri': u'spotify:track:2GeIr050NcweBQzsabIYfB', u'external_urls': {u'spotify': u'https://open.spotify.com/track/2GeIr050NcweBQzsabIYfB'}, u'popularity': 45, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/16e7af443fa59b8be61385ca71d5f76c7a7f1f8a', u'track_number': 1, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/2GeIr050NcweBQzsabIYfB', u'artists': [{u'name': u'Cherry Glazerr', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/3pIGm1omCcHIb1juBNHspg'}, u'uri': u'spotify:artist:3pIGm1omCcHIb1juBNHspg', u'href': u'https://api.spotify.com/v1/artists/3pIGm1omCcHIb1juBNHspg', u'type': u'artist', u'id': u'3pIGm1omCcHIb1juBNHspg'}], u'duration_ms': 273946, u'external_ids': {u'isrc': u'US38W1634501'}, u'type': u'track', u'id': u'2GeIr050NcweBQzsabIYfB', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}], u'next': None, u'href': u'https://api.spotify.com/v1/search?query=Told+You+I%27d+Be+With+the+Guys&offset=0&limit=10&type=track', u'limit': 10, u'offset': 0, u'total': 1, u'previous': None}}
2016-10-04 11:55:05 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-04 11:55:06 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Blood+on+Me&limit=10&type=track&offset=0 HTTP/1.1" 200 None
{u'tracks': {u'items': [{u'album': {u'album_type': u'single', u'name': u'Blood On Me', u'external_urls': {u'spotify': u'https://open.spotify.com/album/43hQRnuVUstKeV2uc3DJXv'}, u'uri': u'spotify:album:43hQRnuVUstKeV2uc3DJXv', u'href': u'https://api.spotify.com/v1/albums/43hQRnuVUstKeV2uc3DJXv', u'images': [{u'url': u'https://i.scdn.co/image/a9d6864491cf8c544bd53f532cdc265b3d7ffd77', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/8834ac4ea759929a5cb9c80505a30672cce0daaa', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/ef39d8bdc8df5915679a97b6b8fb6295f9e45bdd', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'43hQRnuVUstKeV2uc3DJXv', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u'Blood On Me', u'uri': u'spotify:track:4JJIj448WHVYw2kEYfIj94', u'external_urls': {u'spotify': u'https://open.spotify.com/track/4JJIj448WHVYw2kEYfIj94'}, u'popularity': 61, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/a217661593e88e4c3363e5bb48f9b3668be36cb3', u'track_number': 1, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/4JJIj448WHVYw2kEYfIj94', u'artists': [{u'name': u'Sampha', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/2WoVwexZuODvclzULjPQtm'}, u'uri': u'spotify:artist:2WoVwexZuODvclzULjPQtm', u'href': u'https://api.spotify.com/v1/artists/2WoVwexZuODvclzULjPQtm', u'type': u'artist', u'id': u'2WoVwexZuODvclzULjPQtm'}], u'duration_ms': 246951, u'external_ids': {u'isrc': u'UK7MC1600028'}, u'type': u'track', u'id': u'4JJIj448WHVYw2kEYfIj94', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, {u'album': {u'album_type': u'album', u'name': u'Blood On The Tracks', u'external_urls': {u'spotify': u'https://open.spotify.com/album/4WD4pslu83FF6oMa1e19mF'}, u'uri': u'spotify:album:4WD4pslu83FF6oMa1e19mF', u'href': u'https://api.spotify.com/v1/albums/4WD4pslu83FF6oMa1e19mF', u'images': [{u'url': u'https://i.scdn.co/image/2facdd8d670a99db33fe829ea917ef95f526a5cc', u'width': 640, u'height': 640}, {u'url': u'https://i.scdn.co/image/1544214291d2b37d2aad603941e3f89eb05a1f2e', u'width': 300, u'height': 300}, {u'url': u'https://i.scdn.co/image/1372d865672d6c97048fdb151ed49586718cfa01', u'width': 64, u'height': 64}], u'type': u'album', u'id': u'4WD4pslu83FF6oMa1e19mF', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, u'name': u'Meet Me in the Morning', u'uri': u'spotify:track:53ygARQf1f30Z0EmXPHWGT', u'external_urls': {u'spotify': u'https://open.spotify.com/track/53ygARQf1f30Z0EmXPHWGT'}, u'popularity': 45, u'explicit': False, u'preview_url': u'https://p.scdn.co/mp3-preview/9331724efc1c504580759f192699d78d4f6cba44', u'track_number': 6, u'disc_number': 1, u'href': u'https://api.spotify.com/v1/tracks/53ygARQf1f30Z0EmXPHWGT', u'artists': [{u'name': u'Bob Dylan', u'external_urls': {u'spotify': u'https://open.spotify.com/artist/74ASZWbe4lXaubB36ztrGX'}, u'uri': u'spotify:artist:74ASZWbe4lXaubB36ztrGX', u'href': u'https://api.spotify.com/v1/artists/74ASZWbe4lXaubB36ztrGX', u'type': u'artist', u'id': u'74ASZWbe4lXaubB36ztrGX'}], u'duration_ms': 258973, u'external_ids': {u'isrc': u'USSM19906473'}, u'type': u'track', u'id': u'53ygARQf1f30Z0EmXPHWGT', u'available_markets': [u'AD', u'AR', u'AT', u'AU', u'BE', u'BG', u'BO', u'BR', u'CA', u'CH', u'CL', u'CO', u'CR', u'CY', u'CZ', u'DE', u'DK', u'DO', u'EC', u'EE', u'ES', u'FI', u'FR', u'GB', u'GR', u'GT', u'HK', u'HN', u'HU', u'ID', u'IE', u'IS', u'IT', u'JP', u'LI', u'LT', u'LU', u'LV', u'MC', u'MT', u'MX', u'MY', u'NI', u'NL', u'NO', u'NZ', u'PA', u'PE', u'PH', u'PL', u'PT', u'PY', u'SE', u'SG', u'SK', u'SV', u'TR', u'TW', u'US', u'UY']}, {u'album': {u'album_type': u'album', u'name': u'Blood On The Tracks', u'external_urls':</code> </p>
| 0 | 2016-10-04T14:45:35Z | 39,855,742 | <p>Defensively written, this might look something like:</p>
<pre><code>artist_names = set() # using a set avoids adding the same name more than once
if 'tracks' in results and 'items' in results['tracks']:
for item in results['tracks']['items']:
for artist in item.get('artists', ()):
if 'name' in artist:
artist_names.add(artist['name'])
for name in artist_names:
print "Found artist:", name
</code></pre>
| 0 | 2016-10-04T15:03:43Z | [
"python",
"json"
]
|
How to ask a string again if the wrong answer is entered? | 39,855,326 | <p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
</code></pre>
| 1 | 2016-10-04T14:46:46Z | 39,855,435 | <p>There are a couple of things wrong with your code. Firstly, you are only asking for the answer once at the moment. You need to put <code>answer = input()</code> in a <code>while</code> loop. Secondly, you need to use <code>==</code> instead of <code>is</code>:</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = 0
while answer != '4':
answer = input()
if answer == '4':
print("Great job!")
else:
print ("Nope! please try again.")
</code></pre>
<p>There are a number of ways you can arrange this code. This is just one of them</p>
| 2 | 2016-10-04T14:50:49Z | [
"python"
]
|
How to ask a string again if the wrong answer is entered? | 39,855,326 | <p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
</code></pre>
| 1 | 2016-10-04T14:46:46Z | 39,855,464 | <p>You only need the wrong-answer check as loop condition and then output the "great job" message when the loop is over (no <code>if</code> is needed):</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
while answer != '4':
print ("Nope! please try again.")
print ("What is 2 + 2?")
answer = input()
print("Great job!")
</code></pre>
| 1 | 2016-10-04T14:51:42Z | [
"python"
]
|
How to ask a string again if the wrong answer is entered? | 39,855,326 | <p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
</code></pre>
| 1 | 2016-10-04T14:46:46Z | 39,855,483 | <pre><code>print('Guess 2 + 2: ')
answer = int(input())
while answer != 4:
print('try again')
answer = int(input())
print('congrats!')
</code></pre>
<p>I think this is the simplest solution. </p>
| 1 | 2016-10-04T14:52:41Z | [
"python"
]
|
How to ask a string again if the wrong answer is entered? | 39,855,326 | <p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
</code></pre>
| 1 | 2016-10-04T14:46:46Z | 39,855,767 | <p>Here is my two cents for python2 : </p>
<pre><code>#!/usr/bin/env python
MyName = raw_input("Hello there, what is your name ? ")
print("Nice to meet you " + MyName)
answer = raw_input('What is 2 + 2 ? ')
while answer != '4':
print("Nope ! Please try again")
answer = raw_input('What is 2 + 2 ? ')
print("Great job !")
</code></pre>
| 0 | 2016-10-04T15:04:52Z | [
"python"
]
|
How to ask a string again if the wrong answer is entered? | 39,855,326 | <p>I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.</p>
<pre><code>print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
</code></pre>
| 1 | 2016-10-04T14:46:46Z | 39,855,831 | <p>By now you've got more answers than you can handle, but here are another couple of subtleties, with notes:</p>
<pre><code>while True: # loop indefinitely until we hit a break...
answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming: Don't Repeat Yourself)
try:
answer = float(answer) # let's convert to float rather than int so that both '4' and '4.0' are valid answers
except: # we hit this if the user entered some garbage that cannot be interpreted as a number...
pass # ...but don't worry: answer will remain as a string, so it will fail the test on the next line and be considered wrong like anything else
if answer == 4.0:
print("Correct!")
break # this is the only way out of the loop
print("Wrong! Try again...")
</code></pre>
| 1 | 2016-10-04T15:07:27Z | [
"python"
]
|
Python passing variable dates to function | 39,855,342 | <p>Hello: making progress but still struggling. I have the following json:</p>
<pre><code>json =
{
"emeter": {
"get_daystat": {
"day_list": [
{ "year": 2016, "month": 10, "day": 1, "energy": 0.651000 },
{ "year": 2016, "month": 10, "day": 2, "energy": 0.349000 },
{ "year": 2016, "month": 10, "day": 3, "energy": 0.481000 }
],
"err_code": 0
}
}
}
</code></pre>
<p>I am using a linear search to find the energy value from a specific day with this function:</p>
<pre><code>parsed_json = json.loads(json)
def get_energy_value_by_date(obj, year, month, day):
for value in obj['emeter']['get_daystat']['day_list']:
if value['year'] == year and value['month'] == month and value['day'] == day:
return value['energy']
energy = get_energy_value_by_date(parsed_json, 2016, 10, 2)
</code></pre>
<p>So far so good. What I need to do next is find the energy value for various days. For example today (assume json is valid):</p>
<pre><code>import datetime
day_now = datetime.datetime.now().strftime("%d")
month_now = datetime.datetime.now().strftime("%m")
year_now = datetime.datetime.now().strftime("%Y")
parsed_json = json.loads(json)
def get_energy_value_by_date(obj, year, month, day):
for value in obj['emeter']['get_daystat']['day_list']:
if value['year'] == year and value['month'] == month and value['day'] == day:
return value['energy']
energy_today = get_energy_value_by_date(parsed_json, year_now, month_now, day_now)
print energy_today
</code></pre>
<p>When I run this script it returns</p>
<pre><code>None
</code></pre>
<p>I must be missing something basic here. What I need is the ability to pull the energy value for any day of any month of any year for further processing.</p>
<p>Thanks!</p>
<p>Baobab</p>
| 1 | 2016-10-04T14:47:16Z | 39,855,529 | <p>There is a simple issue with your script: <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>strftime</code></a>, according to the docs, will</p>
<blockquote>
<p>return a string representing the date, controlled by an explicit format string.</p>
</blockquote>
<p>The keyword here being "string." See the following:</p>
<pre><code>>>> import datetime
>>> day_now = datetime.datetime.now().strftime("%d")
>>> day_now
'04'
</code></pre>
<p>This does not equal the integer value of the day in your JSON file:</p>
<pre><code>>>> '04' == 4
False
</code></pre>
<p>Therefore, the equality check will always fail and <code>None</code> will be returned. One way is to use <code>int</code> to convert this value to an integer. A better way is to use the attributes of a <code>datetime</code> object to get the integer values:</p>
<pre><code>>>> datetime.datetime.now().year
2016
>>> datetime.datetime.now().month
10
>>> datetime.datetime.now().day
4
</code></pre>
<p>I would also advise passing just a <code>date</code> object to the function and unpacking it there: it prevents redundancy and cleans up the function signature. You should also use <code>date.today()</code> instead of <code>datetime.now()</code> (since time is irrelevant) and then make the comparison in one operation. The full function could be something like this:</p>
<pre><code>def get_energy_value_by_date(obj, current_day):
for value in obj['emeter']['get_daystat']['day_list']:
if current_day == datetime.date(value['year'], value['month'], value['day']):
return value['energy']
current_day = datetime.date.today()
energy_today = get_energy_value_by_date(parsed_json, current_day)
print (energy_today)
</code></pre>
| 2 | 2016-10-04T14:54:40Z | [
"python",
"function"
]
|
Is python tuple assignment order fixed? | 39,855,410 | <p>Will</p>
<pre><code>a, a = 2, 1
</code></pre>
<p>always result in a equal to 1? In other words, is tuple assignment guaranteed to be left-to-right?</p>
<p>The matter becomes relevant when we don't have just a, but a[i], a[j] and i and j may or may not be equal.</p>
| 2 | 2016-10-04T14:49:58Z | 39,855,581 | <p>How it works :</p>
<pre><code>a, a = 2, 1
--> a does not exist, create variable a and set value to 2
--> a already exists, value of a changed to 1
</code></pre>
<p>When you have different variables, it works exactly the same way :</p>
<pre><code>a, b, a = 1, 2, 3
--> a does not exist, create variable a and set value to 1
--> b does not exist, create variable b and set value to 2
--> a already exists, value of a changed to 3
</code></pre>
| 0 | 2016-10-04T14:56:45Z | [
"python",
"tuples",
"variable-assignment"
]
|
Is python tuple assignment order fixed? | 39,855,410 | <p>Will</p>
<pre><code>a, a = 2, 1
</code></pre>
<p>always result in a equal to 1? In other words, is tuple assignment guaranteed to be left-to-right?</p>
<p>The matter becomes relevant when we don't have just a, but a[i], a[j] and i and j may or may not be equal.</p>
| 2 | 2016-10-04T14:49:58Z | 39,855,637 | <p>Yes, it is part of the python language reference that tuple assignment must take place left to right. </p>
<p><a href="https://docs.python.org/2.3/ref/assignment.html">https://docs.python.org/2.3/ref/assignment.html</a></p>
<blockquote>
<p>An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of
the target lists, from left to right.</p>
</blockquote>
<p>So all Python implementations should follow this rule (as confirmed by the experiments in the other answer). </p>
<p>Personally, I would still be hesitant to use this as it seems unclear to a future reader of the code. </p>
| 7 | 2016-10-04T14:58:56Z | [
"python",
"tuples",
"variable-assignment"
]
|
Django in sub-directory | 39,855,488 | <p>When i build my django application, i'll use the runserver command in order to test my website, but in deploy, let's say that i'll publish my website under: www.test.com/django.</p>
<p>My IIS it's configure with an application under my default website called "django".</p>
<p>I'm expecting that everything will works fine, but django doesn't recognize my url schema, that is the following one:</p>
<pre><code>urlpatterns = [
# Examples:
url(r'^$', app.views.home, name='home'),
url(r'^contact$', app.views.contact, name='contact'),
url(r'^about', app.views.about, name='about'),
]
</code></pre>
<p>and in this case, i need to modify my urlpatterns like this, in order to serve the application via www.test.com/django:</p>
<pre><code>urlpatterns = [
url(r'^(?i)django/', include([ #Application name
# Examples:
url(r'^$', app.views.home, name='home'),
url(r'^contact$', app.views.contact, name='contact'),
url(r'^about', app.views.about, name='about'),
])),
]
</code></pre>
<p>It's a good approach? it's working but i'm not sure about the quality of this solution.</p>
| 1 | 2016-10-04T14:52:58Z | 39,856,091 | <p>The preferred method to fix this is to have your webserver pass the <code>SCRIPT_NAME</code> wsgi variable. Django will automatically use this variable as a prefix when constructing urls, without the need to change your url configuration. I'm unfamiliar with IIS, so I can't tell you how to do this. It does have the advantage that your code is completely agnostic to the actual mount point of your WSGI application, as the script name is passed to Django rather than configured in its settings. </p>
<p>Alternatively, you can set the <a href="https://docs.djangoproject.com/en/1.10/ref/settings/#force-script-name" rel="nofollow"><code>FORCE_SCRIPT_NAME</code></a> setting to <code>/django/</code>. </p>
| 0 | 2016-10-04T15:19:15Z | [
"python",
"django",
"url"
]
|
Using Select queries in python mysql as parameters for if/else block | 39,855,508 | <p>Can I use the results of a python SQL select query as parameters for an if/else statement in a function? If I have a DB with one column, and want to append the values of that column to a list for each row in the Select Query...I can't reference those queries in a function. For example:</p>
<pre><code>db = MySQLdb.connect(host="localhost", user="root", passwd="****", db="****")
cur = db.cursor()
selectArray1 = []
cur.execute("SELECT * FROM tableName WHERE value = 'x'")
for row in cur.fetchall():
selectArray1.append(str(row[0]))
selectArray2 = []
cur.execute("SELECT * FROM tableName WHERE value = 'y'")
for row in cur.fetchall():
selectArray2.append(str(row[0]))
def function(x):
#----Question-----
#if I try to print out selectArray1[x] or selectArray2[x], why don't I get
# a return value?
#Following conditionals do not work, why not?
if selectArray1[x] == "some string":
print "The first array equals the x query"
if selectArray2[x] == "different string":
print "The second array equals the y query"
if __name__ == '__main__':
function(1)
function(2)
</code></pre>
| 0 | 2016-10-04T14:53:41Z | 39,855,651 | <p>Please see this link: <a href="http://stackoverflow.com/questions/14835852/convert-sql-result-to-list-python">Convert sql result to list python</a></p>
<p>Basically, you want something similar to this:</p>
<p><code>list(cur.fetchall())</code></p>
| 0 | 2016-10-04T14:59:33Z | [
"python",
"mysql",
"database",
"list",
"function"
]
|
List comprehension confusion | 39,855,525 | <p>I'm slightly confused by a problem that I'm having and wondered if anyone could help (it seems trivial in my mind so I hope that it genuinely is!)</p>
<p>Basically, I have filtered by a list via the following list comprehension:</p>
<pre><code>depfilt = [s for s in department if 'author' not in s]
</code></pre>
<p>(where department had 154 elements and the resulting depfilt has 72 elements)</p>
<p>Now, I also had a separate list of iD values with 154 elements (<code>subj</code>), for which the indices of this list match those in <code>department</code>. I wanted to retain the correct iD values after the filtering process so used the following line of code:</p>
<pre><code>subfilt = [s for s in subj if 'author' not in department[subj.index(s)]]
</code></pre>
<p>In my mind, I feel this should've worked, but subfilt is actually returning 106 list elements, rather than 72.</p>
<p>Does anybody have any idea why?</p>
<p>Thanks</p>
| 2 | 2016-10-04T14:54:25Z | 39,855,576 | <p>Use <code>enumerate</code> instead of <code>index</code> in case of duplicate values</p>
<pre><code>[s for i, s in enumerate(subj) if 'author' not in department[i]]
</code></pre>
| 6 | 2016-10-04T14:56:37Z | [
"python"
]
|
List comprehension confusion | 39,855,525 | <p>I'm slightly confused by a problem that I'm having and wondered if anyone could help (it seems trivial in my mind so I hope that it genuinely is!)</p>
<p>Basically, I have filtered by a list via the following list comprehension:</p>
<pre><code>depfilt = [s for s in department if 'author' not in s]
</code></pre>
<p>(where department had 154 elements and the resulting depfilt has 72 elements)</p>
<p>Now, I also had a separate list of iD values with 154 elements (<code>subj</code>), for which the indices of this list match those in <code>department</code>. I wanted to retain the correct iD values after the filtering process so used the following line of code:</p>
<pre><code>subfilt = [s for s in subj if 'author' not in department[subj.index(s)]]
</code></pre>
<p>In my mind, I feel this should've worked, but subfilt is actually returning 106 list elements, rather than 72.</p>
<p>Does anybody have any idea why?</p>
<p>Thanks</p>
| 2 | 2016-10-04T14:54:25Z | 39,855,609 | <p>If <code>department</code> and <code>subj</code> are definitely in the same order ie. corresponding elements of each match up, then use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to iterate over both lists simultaneously:</p>
<pre><code>[(d, s) for d, s in zip(department, subject) if 'author' not in d]
</code></pre>
<p>(using <code>d</code> for department and <code>s</code> for subject).</p>
<p>And this way you don't need to reference each element by index. Just standard iteration.</p>
<p>Edit: If you want keep lists separate then you can do the first step for <code>dept</code> as you already have and then modify the second loop for subject like so, still filtering against 'author' while looping over both:</p>
<pre><code>[s for d, s in zip(department, subject) if 'author' not in d]
</code></pre>
<p>(so the value of <code>d</code> is ignored in the 2nd loop)</p>
<p>Example of output:</p>
<pre><code>>>> department = ['something', 'else', 'author', 'okay']
>>> subject = ['some_subj', 'else_subj', 'author_subj', 'okay_subj']
>>> [(d, s) for d, s in zip(department, subject) if 'author' not in d]
[('something', 'some_subj'), ('else', 'else_subj'), ('okay', 'okay_subj')]
>>>
>>> # and if you MUST do them seprately:
... [s for s in department if 'author' not in s] # that's your `deepfilt`
['something', 'else', 'okay']
>>> [s for d, s in zip(department, subject) if 'author' not in d] # this is for `subfilt`
['some_subj', 'else_subj', 'okay_subj']
</code></pre>
| 0 | 2016-10-04T14:57:52Z | [
"python"
]
|
manipulation of a list of strings containing digits to output a list of of digits | 39,855,632 | <p>I looking for help in manipulating a list of strings where I want to extract the digits such has :</p>
<pre><code> x = ['aa bb qq 2 months 60%', 'aa bb qq 3 months 70%', 'aa bb qq 1 month 80%']
</code></pre>
<p>I am trying to get to :</p>
<pre><code>[[2.0,60.0],[3.0,70.0],[1.0,80.0]]
</code></pre>
<p>in a elegant fashion.</p>
<p>The first number should always be an integer but the second number can be a float with a decimal value</p>
<p>my dirty work around is this:</p>
<pre><code>x_split = [y.replace("%", "").split() for y in x]
x_float = [[float(s) for s in x if s.isdigit()] for x in x_split]
Out[100]: [[2.0, 60.0], [3.0, 70.0], [1.0, 80.0]]
</code></pre>
| 1 | 2016-10-04T14:58:44Z | 39,855,722 | <p>Use a <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expression</a> to match integers and floats.</p>
<pre><code>import re
[[float(n) for n in re.findall(r'\d+\.?\d*', s)] for s in x]
</code></pre>
<p>Explanation for the regex (<code>r'\d+\.?\d*'</code>): </p>
<pre><code>r # a raw string so that back slashes are not converted
\d # digit 0 to 9
+ # one or more of the previous pattern (\d)
\. # a decimal point
? # zero or one of the previous pattern (\.)
\d # digit 0 to 9
* # zero or more of the previous pattern (\d)
</code></pre>
| 7 | 2016-10-04T15:02:53Z | [
"python",
"string",
"list",
"python-2.7"
]
|
Django server killed frequently | 39,855,652 | <p>I'm developing a Django project and testing it on a dedicated server.
The project is running on:</p>
<ul>
<li>django 1.9.6</li>
<li>virtualenv</li>
<li>python 2.7</li>
<li>cx_Oracle 5.2.1</li>
</ul>
<hr>
<p><strong>Running</strong> </p>
<pre><code>python manage.py runserver 192.168.30.17:8080 &
</code></pre>
<p>all goes well. Project running and with <code>ps aux</code> I get, for example:</p>
<pre><code>root 8437 0.0 0.9 461108 39036 pts/0 S 15:17 0:00 python manage.py runserver 192.168.30.17:8080
root 8861 3.5 1.5 1319364 64232 pts/0 Sl 15:24 0:14 /new_esmart/esmart_env/bin/python manage.py runserver 192.168.30.17:8080
</code></pre>
<hr>
<p><strong>THE PROBLEM: Frequently server goes down with no error showed on shell</strong>. I simply receive:
<code>Killed</code></p>
<p>How can I retrieve more information to find the cause of this killing?</p>
<p><strong>NOTE</strong>: No gunicorn et similia solution right now. I have to use django server for the next hours</p>
<p><strong>Temporary solution</strong></p>
<p>A script that respawns the server when killed</p>
<pre><code>until python manage.py runserver 192.168.30.17:8080; do
echo "Server Django crashed with exit code $. Respawning ...">&2
sleep 2
done
</code></pre>
| 0 | 2016-10-04T14:59:34Z | 39,855,716 | <p>From the documentation on the django development server
<a href="https://docs.djangoproject.com/en/1.10/ref/django-admin/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/django-admin/</a></p>
<blockquote>
<p>DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone
through security audits or performance tests. (And thatâs how itâs
gonna stay. Weâre in the business of making Web frameworks, not Web
servers, so improving this server to be able to handle a production
environment is outside the scope of Django.)</p>
</blockquote>
<p>Of course it get's killed frequently, it's not designed to be kept running for long hours. Set up one of the standard solutions such as gunicorn+nginx or apache+uswgi etc.</p>
| 1 | 2016-10-04T15:02:47Z | [
"python",
"linux",
"django",
"virtualenv"
]
|
Pandas : Apply function on multiple columns | 39,855,692 | <p>I'm trying to add a new column calculated from first quartile of all columns.
something like this:</p>
<pre><code>df['Q25']=df[col].apply(lambda x: np.percentile(x, 25) ,axis =1)
#col = ['1', '2','3',..'29'] days in one month
</code></pre>
<p>and this is the error I receive:</p>
<pre><code>KeyError: "['1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11' '12' '13' '14' '15' '16'\n '17' '18' '19' '20' '21' '22' '23' '24' '25' '26' '27' '28' '29'] not in index"
</code></pre>
<p>I understand that error shows python is trying to find passed list (col) in the index, instead of columns itself but I don't know how should I fix it. I already added axis=1 but with no luck.</p>
<p>PS. I can't add column manually like <code>df['1'], df['2']</code> since the total number (in this case 29) changes in other cases.</p>
| 0 | 2016-10-04T15:01:14Z | 39,855,877 | <p>Try this out :</p>
<pre><code>df['Q25']= [np.percentile(df.loc[i,:], 25) for i in df.index]
</code></pre>
| 1 | 2016-10-04T15:09:35Z | [
"python",
"pandas"
]
|
Python sum array of objects into objects | 39,855,697 | <p>I have a list (name=carpet) of objects type mini_carpet.
Mini_carpet contains a list of objects called packages.
Packages has various properties, the one interesting to me is nr_buys.</p>
<p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet.
This is what I have done so far:</p>
<pre><code>for d in range(0, carpet.__len__() - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages)
</code></pre>
<p>This is giving me an error because list indices must be integers.
Any help?</p>
<p>Thanks! </p>
| 2 | 2016-10-04T15:01:38Z | 39,855,733 | <p>When you've already coded the __len__ method, u dont need to call it by <code>carpet.__len__()</code>. Instead of use <code>len(carpet)</code>.</p>
| -1 | 2016-10-04T15:03:22Z | [
"python"
]
|
Python sum array of objects into objects | 39,855,697 | <p>I have a list (name=carpet) of objects type mini_carpet.
Mini_carpet contains a list of objects called packages.
Packages has various properties, the one interesting to me is nr_buys.</p>
<p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet.
This is what I have done so far:</p>
<pre><code>for d in range(0, carpet.__len__() - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages)
</code></pre>
<p>This is giving me an error because list indices must be integers.
Any help?</p>
<p>Thanks! </p>
| 2 | 2016-10-04T15:01:38Z | 39,855,760 | <pre><code>for d in range(0, len(carpet) - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i, _ in enumerate(carpet[d].packages))
</code></pre>
<p>You want to get the <code>indexes</code> of a <code>dict</code>, so use <code>enumerate</code>, which returns a <code>tuple</code>: <code>(index, item)</code>.
Also, why are you using <code>dict.__len__</code>?</p>
| 0 | 2016-10-04T15:04:37Z | [
"python"
]
|
Python sum array of objects into objects | 39,855,697 | <p>I have a list (name=carpet) of objects type mini_carpet.
Mini_carpet contains a list of objects called packages.
Packages has various properties, the one interesting to me is nr_buys.</p>
<p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet.
This is what I have done so far:</p>
<pre><code>for d in range(0, carpet.__len__() - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages)
</code></pre>
<p>This is giving me an error because list indices must be integers.
Any help?</p>
<p>Thanks! </p>
| 2 | 2016-10-04T15:01:38Z | 39,855,917 | <p>Another method of doing this, which I feel is more Pythonic, is:</p>
<pre><code>nr_total = sum(package.nr_buys for package in carpet[d].packages)
</code></pre>
<p>The difference, as stated above, is that calling <code>for x in list</code> in python gives you the items of the list, and not their indices. That means that the <code>i</code> in your answer is not the integer index in <code>packages</code> of your item, but your item from <code>packages</code> itself, which you can use directly.</p>
<p>Now this can be done from the start:</p>
<pre><code>nr_total = sum(package.nr_buys for mini_carpet in carpet for package in mini_carpet)
</code></pre>
<p>(don't ask me why Python uses that order, it confuses me as well, but that's how list comprehensions work.)</p>
| 0 | 2016-10-04T15:11:46Z | [
"python"
]
|
Python sum array of objects into objects | 39,855,697 | <p>I have a list (name=carpet) of objects type mini_carpet.
Mini_carpet contains a list of objects called packages.
Packages has various properties, the one interesting to me is nr_buys.</p>
<p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet.
This is what I have done so far:</p>
<pre><code>for d in range(0, carpet.__len__() - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages)
</code></pre>
<p>This is giving me an error because list indices must be integers.
Any help?</p>
<p>Thanks! </p>
| 2 | 2016-10-04T15:01:38Z | 39,855,991 | <blockquote>
<p>sum the <em>various</em> <code>nr_buys</code> that are within a mini_carpet, within a carpet</p>
</blockquote>
<p>Asides what others have said about trying to index your list with a non integer object, you're also throwing away the result of previous iterations. </p>
<p>You can use a mapping/dictionary to keep these results using the carpet index as the key, which can later be used to access the result of the sums of <code>nr_buys</code> values of the packages in that carpet:</p>
<pre><code>nr_total = {}
for i, c in enumerate(carpet):
nr_total[i] = sum(package.nr_buys for package in c.packages)
</code></pre>
<p>To get the total <code>nr_buys</code> for all the carpets, you'll simply do:</p>
<pre><code>total = sum(nr_total.values())
</code></pre>
| 0 | 2016-10-04T15:15:15Z | [
"python"
]
|
Python sum array of objects into objects | 39,855,697 | <p>I have a list (name=carpet) of objects type mini_carpet.
Mini_carpet contains a list of objects called packages.
Packages has various properties, the one interesting to me is nr_buys.</p>
<p>What I want to do is to sum the various nr_buys that are within a mini_carpet, within a carpet.
This is what I have done so far:</p>
<pre><code>for d in range(0, carpet.__len__() - 1, +1):
nr_total = sum(carpet[d].packages[i].nr_buys for i in carpet[d].packages)
</code></pre>
<p>This is giving me an error because list indices must be integers.
Any help?</p>
<p>Thanks! </p>
| 2 | 2016-10-04T15:01:38Z | 39,856,029 | <p>In Python, it's generally better to loop directly over the items in a list, rather than looping indirectly using indices. It's easier to read, and more efficient not to muck around with indices that you don't really need.</p>
<p>To get a total for each <code>mini_carpet</code> you can do this:</p>
<pre><code>for mini in carpet:
nr_total = sum(package.nr_buys for package in mini)
# Do something with nr_total
</code></pre>
<p>To get a single grand total, do a double <code>for</code> loop in the generator expression:</p>
<pre><code>nr_total = sum(package.nr_buys for mini in carpet for package in mini)
</code></pre>
| 2 | 2016-10-04T15:17:20Z | [
"python"
]
|
Python - Change variable outside function without return | 39,855,732 | <p>I just started learning Python and I ran into this problem. I want to set a variable from inside a method, but the variable is outside the method. </p>
<p>The method gets activated by a button. Then I want to get the value from that variable that I set when I press another button. The problem is that the value that I put inside a variable from inside the method doesn't stay. How would I solve this? </p>
<p>The code is underneath. <code>currentMovie</code> is the variable I try to change. When I press the button with the method <code>UpdateText()</code>, it prints out a random number like it is supposed to. But when I press the button that activates <code>UpdateWatched()</code> it prints out 0. So I am assuming the variable never gets set.</p>
<pre><code>import random
from tkinter import *
currentMovie = 0
def UpdateText():
currentMovie = random.randint(0, 100)
print(currentMovie)
def UpdateWatched():
print(currentMovie)
root = Tk()
root.title("MovieSelector9000")
root.geometry("900x600")
app = Frame(root)
app.grid()
canvas = Canvas(app, width = 300, height = 75)
canvas.pack(side = "left")
button1 = Button(canvas, text = "SetRandomMovie", command = UpdateText)
button2 = Button(canvas, text = "GetRandomMovie", command = UpdateWatched)
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
root.mainloop()
</code></pre>
| 3 | 2016-10-04T15:03:18Z | 39,855,755 | <p>Use <code>global</code> to modify a variable outside of the function:</p>
<pre><code>def UpdateText():
global currentMovie
currentMovie = random.randint(0, 100)
print(currentMovie)
</code></pre>
<p>However, don't use <code>global</code>. It's generally a <a href="https://en.wikipedia.org/wiki/Code_smell" rel="nofollow">code smell</a>.</p>
| 3 | 2016-10-04T15:04:22Z | [
"python"
]
|
Python - Change variable outside function without return | 39,855,732 | <p>I just started learning Python and I ran into this problem. I want to set a variable from inside a method, but the variable is outside the method. </p>
<p>The method gets activated by a button. Then I want to get the value from that variable that I set when I press another button. The problem is that the value that I put inside a variable from inside the method doesn't stay. How would I solve this? </p>
<p>The code is underneath. <code>currentMovie</code> is the variable I try to change. When I press the button with the method <code>UpdateText()</code>, it prints out a random number like it is supposed to. But when I press the button that activates <code>UpdateWatched()</code> it prints out 0. So I am assuming the variable never gets set.</p>
<pre><code>import random
from tkinter import *
currentMovie = 0
def UpdateText():
currentMovie = random.randint(0, 100)
print(currentMovie)
def UpdateWatched():
print(currentMovie)
root = Tk()
root.title("MovieSelector9000")
root.geometry("900x600")
app = Frame(root)
app.grid()
canvas = Canvas(app, width = 300, height = 75)
canvas.pack(side = "left")
button1 = Button(canvas, text = "SetRandomMovie", command = UpdateText)
button2 = Button(canvas, text = "GetRandomMovie", command = UpdateWatched)
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
root.mainloop()
</code></pre>
| 3 | 2016-10-04T15:03:18Z | 39,894,555 | <p>Here's a simple (python 2.x) example of how to 1 <em>not</em> use globals and 2 use a (simplistic) domain model class. </p>
<p>The point is: you should first design your domain model independently from your user interface, then write the user interface code calling on your domain model. In this case your UI is a Tkinter GUI, but the same domain model should be able to work with a command line UI, a web UI or whatever.</p>
<p>NB : for python 3.x, replace <code>Tkinter</code> with <code>tkinter</code> (lowercase) and you can't get rid of the <code>object</code> base class for <code>Model</code>.</p>
<pre><code>import random
from Tkinter import *
class Model(object):
def __init__(self):
self.currentMovie = 0
def UpdateCurrentMovie(self):
self.currentMovie = random.randint(0, 100)
print(self.currentMovie)
def UpdateWatched(self):
print(self.currentMovie)
def ExampleWithArgs(self, arg):
print("ExampleWithArg({})".format(arg))
def main():
model = Model()
root = Tk()
root.title("MovieSelector9000")
root.geometry("900x600")
app = Frame(root)
app.grid()
canvas = Canvas(app, width = 300, height = 75)
canvas.pack(side = "left")
button1 = Button(canvas, text = "SetRandomMovie", command=model.UpdateCurrentMovie)
button2 = Button(canvas, text = "GetRandomMovie", command=model.UpdateWatched)
button3 = Button(canvas, text = "ExampleWithArg", command=lambda: model.ExampleWithArgs("foo"))
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
button3.pack(anchor = NW, side = "left")
root.mainloop()
if __name__ == "__main__":
main()
</code></pre>
| 3 | 2016-10-06T11:16:49Z | [
"python"
]
|
How to clone a git repo using python? | 39,855,775 | <p>I am looking for equivalent way to clone a repo in python</p>
<pre><code>clone_start=`date +%s%N` && git clone --quiet ssh://$USER@$host:29418/git_performance_check >& /dev/null && c
lone_end=`date +%s%N`
Time_clone=`echo "scale=2;($clone_end - $clone_start) / 1000000000" | bc`
</code></pre>
<p>How can I do it ?</p>
| 0 | 2016-10-04T15:05:11Z | 39,855,859 | <p>You can use <a href="https://pypi.python.org/pypi/GitPython/" rel="nofollow">GitPyhton</a> lib</p>
<p>Clone from existing repositories or initialize new empty ones:</p>
<pre><code>import git
host = 'github'
user = 'root'
git.Git().clone("ssh://{0}@{1}:29418/git_performance_check".format(user, host))
</code></pre>
| 2 | 2016-10-04T15:08:45Z | [
"python",
"git"
]
|
How to clone a git repo using python? | 39,855,775 | <p>I am looking for equivalent way to clone a repo in python</p>
<pre><code>clone_start=`date +%s%N` && git clone --quiet ssh://$USER@$host:29418/git_performance_check >& /dev/null && c
lone_end=`date +%s%N`
Time_clone=`echo "scale=2;($clone_end - $clone_start) / 1000000000" | bc`
</code></pre>
<p>How can I do it ?</p>
| 0 | 2016-10-04T15:05:11Z | 39,855,898 | <p>You could use <a href="https://pypi.python.org/pypi/GitPython/" rel="nofollow"><code>GitPython</code></a>. Something like this:</p>
<pre><code> from git import Repo
repo = Repo.init('/tmp/git_performance_check')
repo.create_remote('origin', url='ssh://user@host:29418/git_performance_check')
repo.remotes.origin.fetch()
</code></pre>
| 0 | 2016-10-04T15:10:50Z | [
"python",
"git"
]
|
Regex: can't understand the endpos | 39,855,791 | <p>Could you help me understand why <code>print(truth(prog.match(text, 0, 6)))</code> equals true?</p>
<pre><code>import re
from operator import truth
prog = re.compile(r'<HTML>$')
text = "<HTML> "
print("Last symbol: {}".format(len('<HTML>')-1))
print(truth(prog.match(text, 0, 6)))
print(truth(prog.match(text)))
</code></pre>
| 0 | 2016-10-04T15:05:55Z | 39,855,924 | <p>If you use the <code>match(text, startpos, endpos)</code> method of a compiled regex, it will act as if you've passed <code>match(text[startpos:endpos])</code> (well, <a href="https://docs.python.org/3/library/re.html#re.regex.search" rel="nofollow">not exactly</a>, but for the purposes of <code>$</code>, it is). This means that it'll think <code><HTML></code> is at the end of the input (which is what <code>$</code> matches).</p>
<p>However, when this is not the case the extra whitespace at the end of <code>text</code> will prevent <code>$</code> from matching, so no match is found.</p>
| 1 | 2016-10-04T15:12:09Z | [
"python",
"python-3.x"
]
|
Replacing Empty Cells with 0 in Python 3 | 39,855,838 | <p>I am using the csv module to read in csv files to do data analysis. </p>
<pre><code>data = []
c1 = []
c2 = []
c3 = []
data_file = csv.reader(open('file.csv'))
for row in data_file:
data.append(row)
for i in data:
c1.append(data[i][0])
c2.append(data[i][1])
c3.append(data[i][2])
</code></pre>
<p>How do I replace the empty cells with 0?</p>
| 0 | 2016-10-04T15:07:46Z | 39,855,909 | <p>before appending your data you could do a check similar to what is found here : </p>
<p><a href="http://stackoverflow.com/questions/34192705/python-how-to-check-if-cell-in-csv-file-is-empty">Python: How to check if cell in CSV file is empty?</a></p>
<p>When the condition is true, simply append 0 to your corresponding cell (c1, c2, c3)</p>
| 0 | 2016-10-04T15:11:15Z | [
"python",
"csv"
]
|
Readable Time Format (w/ Good Grammar!) | 39,855,889 | <p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> seconds should read as <code>"1 minute and 2 seconds"</code> as opposed to <code>120</code> seconds which is simply <code>"2 minutes"</code>.</p>
<p>One other criteria is that it should return <code>"now"</code> if the seconds is <code>0</code>. </p>
<p>Here's my code so far: </p>
<pre><code>def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
else:
return "now"
return ','.join(human_time[:granularity])
</code></pre>
<p>Please help! Thanks! </p>
<p>MJ</p>
| 1 | 2016-10-04T15:10:11Z | 39,856,175 | <p>Your code already works quite nicely, you just have one problem with your <code>return "now"</code> that I fixed in the code below. What else do you want your code to do?</p>
<pre><code>def prettyList(human_time):
if len(human_time) > 1:
return ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]])
elif len(human_time) == 1:
return human_time[0]
else:
return ""
def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
if not human_time:
return "now"
human_time = human_time[:granularity]
return prettyList(human_time)
</code></pre>
<p>Edit: so I added a function to prettify the output, the last terms in the list will be separed by a "and" and all the others before by a comma. This will still work even if you add more intervals in your code (like <code>('days', 86400)</code>). The output now looks like <code>2 hours, 1 minute and 43 seconds</code> or <code>25 minutes and 14 seconds</code>.</p>
| 2 | 2016-10-04T15:23:31Z | [
"python",
"time",
"control-flow"
]
|
Readable Time Format (w/ Good Grammar!) | 39,855,889 | <p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> seconds should read as <code>"1 minute and 2 seconds"</code> as opposed to <code>120</code> seconds which is simply <code>"2 minutes"</code>.</p>
<p>One other criteria is that it should return <code>"now"</code> if the seconds is <code>0</code>. </p>
<p>Here's my code so far: </p>
<pre><code>def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
else:
return "now"
return ','.join(human_time[:granularity])
</code></pre>
<p>Please help! Thanks! </p>
<p>MJ</p>
| 1 | 2016-10-04T15:10:11Z | 39,857,046 | <p>Made some tweaks for readability :</p>
<pre><code>def pretty_list(human_time):
return human_time[0] if len(human_time) == 1 else ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]])
def get_intervals(seconds):
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return (
("hour", h),
("minute", m),
("second", s)
)
def format_duration(seconds, granularity=3):
intervals = get_intervals(seconds)
human_time = []
for name, value in intervals:
if value == 0:
continue
elif value == 1:
human_time.append("{} {}".format(value, name))
else:
human_time.append("{} {}s".format(value, name))
return (pretty_list(human_time[:granularity])) if len(human_time) != 0 else "now"
</code></pre>
| 2 | 2016-10-04T16:07:26Z | [
"python",
"time",
"control-flow"
]
|
Readable Time Format (w/ Good Grammar!) | 39,855,889 | <p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> seconds should read as <code>"1 minute and 2 seconds"</code> as opposed to <code>120</code> seconds which is simply <code>"2 minutes"</code>.</p>
<p>One other criteria is that it should return <code>"now"</code> if the seconds is <code>0</code>. </p>
<p>Here's my code so far: </p>
<pre><code>def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
else:
return "now"
return ','.join(human_time[:granularity])
</code></pre>
<p>Please help! Thanks! </p>
<p>MJ</p>
| 1 | 2016-10-04T15:10:11Z | 39,857,391 | <p>I found it! I actually needed more intervals - the durations asked for were lengthier than I thought...</p>
<pre><code>def prettyList(human_time):
if len(human_time) > 1:
return ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]])
elif len(human_time) == 1:
return human_time[0]
else:
return ""
def format_duration(seconds, granularity = 4):
intervals = (('years', 29030400), ('months', 2419200), ('weeks', 604800),('days', 86400),('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
if not human_time:
return "now"
human_time = human_time[:granularity]
return prettyList(human_time)
</code></pre>
| 0 | 2016-10-04T16:25:51Z | [
"python",
"time",
"control-flow"
]
|
Readable Time Format (w/ Good Grammar!) | 39,855,889 | <p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> seconds should read as <code>"1 minute and 2 seconds"</code> as opposed to <code>120</code> seconds which is simply <code>"2 minutes"</code>.</p>
<p>One other criteria is that it should return <code>"now"</code> if the seconds is <code>0</code>. </p>
<p>Here's my code so far: </p>
<pre><code>def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
else:
return "now"
return ','.join(human_time[:granularity])
</code></pre>
<p>Please help! Thanks! </p>
<p>MJ</p>
| 1 | 2016-10-04T15:10:11Z | 39,858,068 | <p>You can try to code for each variation:</p>
<pre><code>def timestamp(ctime):
sec = int(ctime)
if sec == 0:
return "Now"
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
if h == 1: hr_t = 'Hour'
else: hr_t = 'Hours'
if m == 1: mn_t = 'Minute'
else: mn_t = 'Minutes'
if s == 1: sc_t = 'Second'
else: sc_t = 'Seconds'
time_stamp = ""
if h > 0 and m ==0 and s ==0:
time_stamp = "%02d %s " % (h, hr_t)
elif h > 0:
time_stamp = "%02d %s, " % (h, hr_t)
if m > 0 and s !=0:
time_stamp = time_stamp +"%02d %s and %02d %s" % (m, mn_t, s, sc_t)
elif m > 0 and s == 0:
time_stamp = time_stamp +"%02d %s" % (m, mn_t)
elif m == 0 and s != 0:
time_stamp = time_stamp +"%02d %s" % (s, sc_t)
return time_stamp
print (timestamp(11024))
print (timestamp(0))
print (timestamp(31))
print (timestamp(102))
print (timestamp(61))
print (timestamp(60))
print (timestamp(3600))
print (timestamp(3632))
03 Hours, 03 Minutes and 44 Seconds
Now
31 Seconds
01 Minute and 42 Seconds
01 Minute and 01 Second
01 Minute
01 Hour
01 Hour, 32 Seconds
</code></pre>
<p>Or you can use the <code>relativedelta</code> option in <code>dateutil</code> and then pick the bones out of it.</p>
<pre><code>from dateutil.relativedelta import relativedelta
attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
human_readable = lambda delta: ['%d %s ' % (getattr(delta, attr), getattr(delta, attr) != 1 and attr or attr[:-1]) for attr in attrs if getattr(delta, attr) or attr == attrs[-1]]
readable=''
for i in human_readable(relativedelta(seconds=1113600)):
readable += i
print readable
print human_readable(relativedelta(seconds=13600))
print human_readable(relativedelta(seconds=36))
print human_readable(relativedelta(seconds=60))
print human_readable(relativedelta(seconds=3600))
12 days 21 hours 20 minutes 0 seconds
['3 hours ', '46 minutes ', '40 seconds ']
['36 seconds ']
['1 minute ', '0 seconds ']
['1 hour ', '0 seconds ']
</code></pre>
<p>For more examples of the second example see: <a href="http://code.activestate.com/recipes/578113-human-readable-format-for-a-given-time-delta/" rel="nofollow">http://code.activestate.com/recipes/578113-human-readable-format-for-a-given-time-delta/</a>
which is where I stole almost all the second set of code from</p>
| 1 | 2016-10-04T17:09:14Z | [
"python",
"time",
"control-flow"
]
|
Readable Time Format (w/ Good Grammar!) | 39,855,889 | <p>I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, <code>62</code> seconds should read as <code>"1 minute and 2 seconds"</code> as opposed to <code>120</code> seconds which is simply <code>"2 minutes"</code>.</p>
<p>One other criteria is that it should return <code>"now"</code> if the seconds is <code>0</code>. </p>
<p>Here's my code so far: </p>
<pre><code>def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
else:
return "now"
return ','.join(human_time[:granularity])
</code></pre>
<p>Please help! Thanks! </p>
<p>MJ</p>
| 1 | 2016-10-04T15:10:11Z | 39,870,249 | <p>I think that I have covered all of the bases here but I'm sure someone will let me know if I have made an error (large or small) :)</p>
<pre><code>from dateutil.relativedelta import relativedelta
def convertdate(secs):
raw_date = relativedelta(seconds=secs)
years, days = divmod(raw_date.days, 365) # To crudely cater for leap years / 365.2425
hours = raw_date.hours
minutes = raw_date.minutes
seconds = raw_date.seconds
full = [years,days,hours,minutes,seconds]
date_text=['','','','','']
if years == 1: date_text[0] = "Year"
else: date_text[0] = "Years"
if days == 1: date_text[1] = "Day"
else: date_text[1] = "Days"
if hours == 1: date_text[2] = "Hour"
else: date_text[2] = "Hours"
if minutes == 1: date_text[3] = "Minute"
else: date_text[3] = "Minutes"
if seconds == 1: date_text[4] = "Second"
else: date_text[4] = "Seconds"
first_pos = 0
final_pos = 0
element_count = 0
# Find the first and final set positions and the number of returned values
for i in range(5):
if full[i] != 0:
final_pos = i
element_count +=1
if first_pos == 0:
first_pos = i
# Return "now" and any single value
if element_count == 0:
return "Now"
if element_count == 1:
return "%02d %s" % (full[final_pos],date_text[final_pos])
# Initially define the separators
separators=['','','','','']
ret_str=''
for i in range(4):
if full[i] != 0:
separators[i] = ', '
separators[final_pos] = ''
# Redefine the final separator
for i in range(4,-1,-1):
if separators[i] == ', ':
separators[i] = ' and '
break
#Build the readable formatted time string
for i in range(5):
if full[i] != 0:
ret_str += "%02d %s%s" % (full[i],date_text[i],separators[i])
return ret_str
print convertdate(1111113601)
print convertdate(1111113635)
print convertdate(1111113600)
print convertdate(1111111200)
print convertdate(1111104000)
print convertdate(1111104005)
print convertdate(11113240)
print convertdate(11059240)
print convertdate(11113600)
print convertdate(36)
print convertdate(60)
print convertdate(61)
print convertdate(121)
print convertdate(122)
print convertdate(120)
print convertdate(3600)
print convertdate(3601)
35 Years, 85 Days, 02 Hours, 40 Minutes and 01 Second
35 Years, 85 Days, 02 Hours, 40 Minutes and 35 Seconds
35 Years, 85 Days, 02 Hours and 40 Minutes
35 Years, 85 Days and 02 Hours
35 Years and 85 Days
35 Years, 85 Days and 05 Seconds
128 Days, 15 Hours and 40 Seconds
128 Days and 40 Seconds
128 Days, 15 Hours, 06 Minutes and 40 Seconds
36 Seconds
01 Minute
01 Minute and 01 Second
02 Minutes and 01 Second
02 Minutes and 02 Seconds
02 Minutes
01 Hour
01 Hour and 01 Second
</code></pre>
| 0 | 2016-10-05T09:28:51Z | [
"python",
"time",
"control-flow"
]
|
How to force execution of next function | 39,855,968 | <p>I am attempting execute multiple functions defined by the twitterbot library. I need the code to execute one function, then the next, and then the next, or in a random order. The function, however, is designed to run in a loop.</p>
<p>I rather stay away from editing the actual library, so I am looking for a solution that will allow me to execute the function just once, continue on to the next and loop from the top. </p>
<p>Is there a way in Python to do this?</p>
<pre><code>from TwitterFollowBot import TwitterBot
my_bot = TwitterBot()
my_bot.sync_follows()
# Start of loop
my_bot.auto_fav("@asco", count=1000)
# The above function persists to execute without continuing down
# Need bottom functions to also execute.
my_bot.auto_fav("ATSO", count=1000)
my_bot.auto_fav("BCY3", count=1000)
my_bot.auto_fav("ESIO", count=1000)
# End of loop
</code></pre>
| 0 | 2016-10-04T15:14:29Z | 39,856,045 | <p>You can use the reference to the functions in a list then use <code>random.shuffle</code>. And you can use <code>threading.Thread</code> to run all of your functions. I am using <code>time.sleep</code> and <code>for</code> just as an example to illustrate how each thread is being executed even though the <code>for</code> loop isn't finished: </p>
<pre><code>import random
import time
from threading import Thread
def a():
for i in range(10000):
print(i)
time.sleep(1)
def b():
for i in range(10000):
print(i)
time.sleep(2)
def c():
for i in range(10000):
print(i)
time.sleep(3)
def d():
for i in range(10000):
print(i)
time.sleep(4)
def e():
for i in range(10000):
print(i)
time.sleep(5)
listOfFunctions = [a, b, c, d, e]
random.shuffle(listOfFunctions)
for i in listOfFunctions:
Thread(target = i).start() # Use args=(your args) if you want to run each function with arguments
</code></pre>
| 1 | 2016-10-04T15:17:56Z | [
"python",
"twitter"
]
|
django 1.10 get individual objects out of query | 39,856,025 | <p>I have a model set up for subscribers to get on our mailing list. Whenever a new blog post is created I want to email the user. How do I get individual email addresses and first names from the model to use to email, each person individually? I want their first name to be in the email.</p>
<p>Here is my models.py:</p>
<pre><code>class EmailUpdates(models.Model):
email = models.EmailField(max_length=100, blank=True, unique=True)
first_name = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.email
def __unicode__(self):
return self.email
</code></pre>
<p>Here is my views.py:</p>
<pre><code>def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404()
notification_subscribers = EmailUpdates.objects.all()
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
messages.success(request, "Successfully Created")
for user in notification_subscribers:
user.first_name = notification_subscribers.filter('first_name')
user.email = notification_subscribers.filter('email')
user_data = {
'user_email': user.email,
'user_first_name': user.first_name,
}
plaintext = get_template('email/post_create_email/email_text.txt')
htmly = get_template('email/post_create_email/email_template.html')
text_content = plaintext.render(user_data)
html_content = htmly.render(user_data)
subject = "{0}, a new blog post has been made, Hurray!".format(user.first_name)
from_email = 'xx@gmail.com'
to_email = user.email
msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "posts/post_form.html", context)
</code></pre>
| 0 | 2016-10-04T15:17:10Z | 39,856,236 | <p>You're doing some bizarre unnecessary things in your loop. <code>user</code> is already the relevant instance of EmailSubscriber; it <em>already</em> has <code>first_name</code> and <code>email</code> attributes. You don't need to set them, you just use them.</p>
| 1 | 2016-10-04T15:26:06Z | [
"python",
"django",
"django-email"
]
|
Different behaviour when operating on equivalent multidimensional lists | 39,856,037 | <p>When I operate on two, I think equivalent multidimensional lists, I have different outcomes. The only difference between the lists is how they are created. I'm using Python 3.4.3</p>
<pre><code>>>> b = [[1,2],[1,2]]
>>> b[0][0] += 1
>>> b
[[2, 2], [1, 2]]
>>> b = [[1,2]] * 2
>>> b
[[1, 2], [1, 2]]
>>> b[0][0] += 1
>>> b
[[2, 2], [2, 2]]
</code></pre>
<p>As you can see, both b's and the operations on them are the same, but the outcome is not. I'm guessing that it has something to do with the way they are created since that is the only difference, but I don't see how.</p>
<p>Its the same with Python 2.7.6</p>
<pre><code>>>> b = [[1,2],[1,2]]
>>> b
[[1, 2], [1, 2]]
>>> c = [[1,2]] * 2
>>> c
[[1, 2], [1, 2]]
>>> c == b
True
>>> b[0][0] += 1
>>> b
[[2, 2], [1, 2]]
>>> c[0][0] += 1
>>> c
[[2, 2], [2, 2]]
>>> c == b
False
>>>
</code></pre>
| 1 | 2016-10-04T15:17:45Z | 39,856,103 | <pre><code>b = [[1,2],[1,2]]
print(id(b[0])) # 139948012160968
print(id(b[1])) # 139948011731400
b = [[1,2]]*2
print(id(b[0])) # 139948012161032
print(id(b[1])) # 139948012161032
</code></pre>
<p><a href="https://docs.python.org/3/library/functions.html#id" rel="nofollow">`id() shows the object's ID or the memory location in Python.</a></p>
<p>When you do <code>b = [[1,2]]*2</code> you are basically saying let's point to the same object twice and store it in b in a list.</p>
<p>When you do <code>b = [[1,2],[1,2]]</code> you are basically saying let me get two different objects and put them in a list and let b reference the list.</p>
<p>So for the latter example, of course you are going to get that output since they are the same object you are changing. You can think of it as me giving you the same address to a house and I have the same address I gave you. We end up at the same place and what ever changes we make to the house, we see it together. </p>
<p>Edited for comment:</p>
<p>Correct! They are changing how the memory is handled but the values are the same.</p>
<p><code>==</code> tests if the values are the same. <code>is</code> tests if the objects are the same. so in our case:</p>
<pre><code>#First case:
print(b[0] == b[1]) #true
print(b[0] is b[1]) #false
#second case:
print(b[0] == b[1]) #true
print(b[0] is b[1]) #true
</code></pre>
<p>Edited second time for second comment!~</p>
<pre><code>import copy
x = [1,2]
b = [copy.copy(x) for i in range(3)]
print(id(b[0])) #140133864442248
print(id(b[1])) #140133864586120
print(id(b[2])) #140133864568008
print(b) #[[1, 2], [1, 2], [1, 2]] you can extend range to 256.
</code></pre>
<p>If you want a unique object and want to copy it from another object, try using <a href="https://docs.python.org/3.5/library/copy.html" rel="nofollow">copy</a>. It makes a new object with the same values.</p>
<p>Edited again using one of my favorite function <code>sum</code>:</p>
<p>This is more or less redundant and it might confuse you some more, but <code>sum</code> also works too.</p>
<pre><code> x = [1,2]
b = [sum([x],[]) for i in range(3)]
print(id(b[0])) #140692560200008
print(id(b[1])) #140692559012744
print(b) #[[1, 2], [1, 2], [1, 2]]
</code></pre>
<p>Will return different instances in the object. I only point this is just in case you don't want to import copy or import anything. </p>
| 1 | 2016-10-04T15:19:48Z | [
"python",
"list"
]
|
Different behaviour when operating on equivalent multidimensional lists | 39,856,037 | <p>When I operate on two, I think equivalent multidimensional lists, I have different outcomes. The only difference between the lists is how they are created. I'm using Python 3.4.3</p>
<pre><code>>>> b = [[1,2],[1,2]]
>>> b[0][0] += 1
>>> b
[[2, 2], [1, 2]]
>>> b = [[1,2]] * 2
>>> b
[[1, 2], [1, 2]]
>>> b[0][0] += 1
>>> b
[[2, 2], [2, 2]]
</code></pre>
<p>As you can see, both b's and the operations on them are the same, but the outcome is not. I'm guessing that it has something to do with the way they are created since that is the only difference, but I don't see how.</p>
<p>Its the same with Python 2.7.6</p>
<pre><code>>>> b = [[1,2],[1,2]]
>>> b
[[1, 2], [1, 2]]
>>> c = [[1,2]] * 2
>>> c
[[1, 2], [1, 2]]
>>> c == b
True
>>> b[0][0] += 1
>>> b
[[2, 2], [1, 2]]
>>> c[0][0] += 1
>>> c
[[2, 2], [2, 2]]
>>> c == b
False
>>>
</code></pre>
| 1 | 2016-10-04T15:17:45Z | 39,856,142 | <p>This is very-well understood behavior in Python.</p>
<pre><code>a = [[], []] # two separate references to two separate lists
b = [] * 2 # two references to the same list object
a[0].append(1) # does not affect a[1]
b[0].append(1) # affects b[0] and b[1]
</code></pre>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/python/3553/common-pitfalls/12259/list-multiplication-and-common-references#t=201610041521133519857">See this documentation</a></p>
| 0 | 2016-10-04T15:21:34Z | [
"python",
"list"
]
|
Different behaviour when operating on equivalent multidimensional lists | 39,856,037 | <p>When I operate on two, I think equivalent multidimensional lists, I have different outcomes. The only difference between the lists is how they are created. I'm using Python 3.4.3</p>
<pre><code>>>> b = [[1,2],[1,2]]
>>> b[0][0] += 1
>>> b
[[2, 2], [1, 2]]
>>> b = [[1,2]] * 2
>>> b
[[1, 2], [1, 2]]
>>> b[0][0] += 1
>>> b
[[2, 2], [2, 2]]
</code></pre>
<p>As you can see, both b's and the operations on them are the same, but the outcome is not. I'm guessing that it has something to do with the way they are created since that is the only difference, but I don't see how.</p>
<p>Its the same with Python 2.7.6</p>
<pre><code>>>> b = [[1,2],[1,2]]
>>> b
[[1, 2], [1, 2]]
>>> c = [[1,2]] * 2
>>> c
[[1, 2], [1, 2]]
>>> c == b
True
>>> b[0][0] += 1
>>> b
[[2, 2], [1, 2]]
>>> c[0][0] += 1
>>> c
[[2, 2], [2, 2]]
>>> c == b
False
>>>
</code></pre>
| 1 | 2016-10-04T15:17:45Z | 39,856,158 | <p>In the second case you're making what's known as a shallow copy of the <code>[1,2]</code> list. Essentially what that means is that somewhere in memory you have the list <code>[1,2]</code>, and when you write <code>[[1,2]]*2</code> you're saying you want two references to that same list. Thus, when you change one of the lists, you're actually changing the list that both items in <code>b</code> are referring to.</p>
| 0 | 2016-10-04T15:22:29Z | [
"python",
"list"
]
|
Python script to parse a big workbook | 39,856,092 | <p>I have an extra sized excel file and I need to automate a task I do everyday: Add rows to the bottom with the day's date, save a new workbook, crop the old ones and save as a new file with the day's date.</p>
<p>An example is today only having rows with date 04-10-2016 and the filename would be <code>[sheetname]04102016H12</code> or <code>[sheetname]04102016H16</code>if it has passed 12 pm.</p>
<p>I've tried xldr, doing this in VBA and so on but I can't get along with VBA and it is slow. So I'd rather use Python here - lightweight, does the job and so on.</p>
<p>Anyway, so far, I have done the follwing:</p>
<pre><code>import xlsxwriter, datetime, xlrd
import pandas as pd
# Parsing main excel sheet to save the correct
with xlrd.open_workbook(r'D:/path/to/file/file.xlsx', on_demand=True) as xls:
for sheet in xls.parse(xls.sheet_names([0])):
dfs = pd.read_excel(xls, sheet, header = 1)
now = datetime.date.today()
df[df['Data'] != now]
if datetime.time()<datetime.time(11,0,0,0):
df.to_excel(r'W:\path\I\need'+str(sheet)+now+'H12.xlsx', index=False)
else:
df.to_excel(r'W:\path\I\need'+str(sheet)+now+'H16.xlsx', index=False)
</code></pre>
<p>Unfortunately, this does not separate the main file into as many files as worksheets the workbook contains. It outputs <code>TypeError: 'list' object is not callable</code>, regarding this <code>in xls.parse(xls.sheet_names([0]))</code>.</p>
| 0 | 2016-10-04T15:19:17Z | 39,856,346 | <p>Based on comments below I am updating my answer. Just do:</p>
<pre><code>xls.sheet_names()[0]
</code></pre>
<p>However, if you want to loop through the sheets, then you may want all sheet names instead of just the first one.</p>
| 0 | 2016-10-04T15:32:12Z | [
"python",
"excel",
"filtering"
]
|
Does scons customized decider function require to be class member? | 39,856,184 | <p>I searched from internet on how to write our own decider function in scons, as to how/when a source file should be rebuilt, like this:</p>
<pre><code>Program('hello.c')
def decide_if_changed(dependency,target,prev_ni):
if self.get_timestamp()!=prev_ni.timestamp:
dep=str(dependency)
tgt=str(target)
if specific_part_of_file_has_changed(dep,tgt):
return true;
return false;
Decider(decide_if_changed)
</code></pre>
<p>I've got a hello.c, no problem, but when running scons it prompts a python error:</p>
<pre><code>$ scons -Q
scons: *** [o.o] NameError : global name 'self' is not defined
</code></pre>
<p>self is the python keyword to mention a class member function. Here in SContruct file, there's a class but just a decide_if_changed function. Question:</p>
<blockquote>
<p>Do I have to add a class here? Why it prompts python error saying 'self' is not defined?</p>
<p>This example script a function call of specific_part_of_file_has_changed, is it a scons's own file that can be called by any pythong statement?</p>
</blockquote>
| 0 | 2016-10-04T15:23:47Z | 39,873,940 | <p>The name <code>self</code> is not defined because there is a typo in the documentation. The second line of the decider should read:</p>
<pre><code>if dependency.get_timestamp()!=prev_ni.timestamp:
</code></pre>
<p>Implementing the <code>specific_part_of_file_has_changed()</code> method (or any similar series of steps to determine whether the file has changed) is completely up to you...the "customer". After all you do want a "custom decider", right? ;)</p>
| 1 | 2016-10-05T12:26:42Z | [
"python",
"class",
"member",
"scons",
"self"
]
|
Django - Variable not being set properly | 39,856,324 | <p>So I am trying to run my users input through if elif statements in some arrays I setup. The goal is to have the variable set to a value if the input is found in the array. Right now the values are staying <code>None</code>. I am sure this is something silly that I am missing on my part, but any help would be greatly appreciated.</p>
<p>views.py</p>
<pre><code>def fit_guide(request):
if request.method == 'POST':
form = FitGuideSizingForm(request.POST)
chest = request.POST['chest']
waist = request.POST['waist']
hip = request.POST['hip']
if form.is_valid():
chest_size = None
if chest in chest_size_0():
chest_size = 0
elif chest in chest_size_2():
chest_size = 2
elif chest in chest_size_4():
chest_size = 4
elif chest in chest_size_6():
chest_size = 6
elif chest in chest_size_8():
chest_size = 8
elif chest in chest_size_10():
chest_size = 10
elif chest in chest_size_12():
chest_size = 12
elif chest in chest_size_14():
chest_size = 14
elif chest in chest_size_16():
chest_size = 16
elif chest in chest_size_18():
chest_size = 18
elif chest in chest_size_20():
chest_size = 20
elif chest in chest_size_22():
chest_size = 22
elif chest in chest_size_24():
chest_size = 24
elif chest in chest_size_26():
chest_size = 26
elif chest in chest_size_28():
chest_size = 28
print(chest_size)
form = FitGuideSizingForm()
c = {}
c.update(csrf(request))
c.update({'form': form})
return render(request, 'main/fit_guide.html', c)
</code></pre>
<p>forms.py</p>
<pre><code>class FitGuideSizingForm(forms.Form):
chest = forms.DecimalField(min_value=29, max_value=60, required=True)
waist = forms.DecimalField(min_value=23, max_value=50, required=True)
hip = forms.DecimalField(min_value=34.5, max_value=58, required=True)
def __init__(self, *args, **kwargs):
super(FitGuideSizingForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'id-fitGuideForm'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.form_action = 'submit_survey'
self.helper.add_input(Submit('submit', 'Get Fit Guide!'))
</code></pre>
<p>size_arrays.py example</p>
<pre><code>def chest_size_0():
return [29, 29.1, 29.2, 29.3, 29.4, 29.5, 29.6, 29.7, 29.8, 29.9,
30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9,
31, 31.1, 31.2, 31.3, 31.4, 31.5, 31.6, 31.7, 31.8, 31.9]
def chest_size_2():
return [32, 32.1, 32.2, 32.3, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9,
33, 33.1, 33.2, 33.3, 33.4]
def chest_size_4():
return [33.5, 33.6, 33.7, 33.8, 33.9, 34, 34.1, 34.2, 34.3, 34.4]
def chest_size_6():
return [34.5, 34.6, 34.7, 34.8, 34.9, 35, 35.1, 35.2, 35.3, 35.4]
etc
etc
</code></pre>
| 0 | 2016-10-04T15:30:49Z | 39,856,579 | <p>You have a few problems here.</p>
<p>Firstly, you are using the values directly from <code>request.POST</code>. Those will always be strings. To get the values in the type specified in your form, you should use the <code>form.cleaned_data</code> dict.</p>
<p>Secondly, your fields are decimals, but your arrays contain floats. Due to floating-point imprecision, <code>29.1</code> for example is not the same as <code>decimal.Decimal("29.1")</code>. You should use consistent types; Decimal is probably the most appropriate here.</p>
<p>Thirdly, this isn't really the best way to do it. It would be much easier to use comparisons:</p>
<pre><code>if Decimal("29.0") <= chest < Decimal("32.0"):
...
elif Decimal("32.0") <= chest < Decimal("33.5"):
...
</code></pre>
<p>and so on.</p>
| 1 | 2016-10-04T15:44:15Z | [
"python",
"django"
]
|
Django - Variable not being set properly | 39,856,324 | <p>So I am trying to run my users input through if elif statements in some arrays I setup. The goal is to have the variable set to a value if the input is found in the array. Right now the values are staying <code>None</code>. I am sure this is something silly that I am missing on my part, but any help would be greatly appreciated.</p>
<p>views.py</p>
<pre><code>def fit_guide(request):
if request.method == 'POST':
form = FitGuideSizingForm(request.POST)
chest = request.POST['chest']
waist = request.POST['waist']
hip = request.POST['hip']
if form.is_valid():
chest_size = None
if chest in chest_size_0():
chest_size = 0
elif chest in chest_size_2():
chest_size = 2
elif chest in chest_size_4():
chest_size = 4
elif chest in chest_size_6():
chest_size = 6
elif chest in chest_size_8():
chest_size = 8
elif chest in chest_size_10():
chest_size = 10
elif chest in chest_size_12():
chest_size = 12
elif chest in chest_size_14():
chest_size = 14
elif chest in chest_size_16():
chest_size = 16
elif chest in chest_size_18():
chest_size = 18
elif chest in chest_size_20():
chest_size = 20
elif chest in chest_size_22():
chest_size = 22
elif chest in chest_size_24():
chest_size = 24
elif chest in chest_size_26():
chest_size = 26
elif chest in chest_size_28():
chest_size = 28
print(chest_size)
form = FitGuideSizingForm()
c = {}
c.update(csrf(request))
c.update({'form': form})
return render(request, 'main/fit_guide.html', c)
</code></pre>
<p>forms.py</p>
<pre><code>class FitGuideSizingForm(forms.Form):
chest = forms.DecimalField(min_value=29, max_value=60, required=True)
waist = forms.DecimalField(min_value=23, max_value=50, required=True)
hip = forms.DecimalField(min_value=34.5, max_value=58, required=True)
def __init__(self, *args, **kwargs):
super(FitGuideSizingForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'id-fitGuideForm'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.form_action = 'submit_survey'
self.helper.add_input(Submit('submit', 'Get Fit Guide!'))
</code></pre>
<p>size_arrays.py example</p>
<pre><code>def chest_size_0():
return [29, 29.1, 29.2, 29.3, 29.4, 29.5, 29.6, 29.7, 29.8, 29.9,
30, 30.1, 30.2, 30.3, 30.4, 30.5, 30.6, 30.7, 30.8, 30.9,
31, 31.1, 31.2, 31.3, 31.4, 31.5, 31.6, 31.7, 31.8, 31.9]
def chest_size_2():
return [32, 32.1, 32.2, 32.3, 32.4, 32.5, 32.6, 32.7, 32.8, 32.9,
33, 33.1, 33.2, 33.3, 33.4]
def chest_size_4():
return [33.5, 33.6, 33.7, 33.8, 33.9, 34, 34.1, 34.2, 34.3, 34.4]
def chest_size_6():
return [34.5, 34.6, 34.7, 34.8, 34.9, 35, 35.1, 35.2, 35.3, 35.4]
etc
etc
</code></pre>
| 0 | 2016-10-04T15:30:49Z | 39,856,607 | <p>You are setting <code>chest</code> from <code>request.POST</code> which will give you a string value. Convert it to a <code>float</code> and it should work.</p>
| 0 | 2016-10-04T15:45:48Z | [
"python",
"django"
]
|
Medium Pandas Panel to hdf5 | 39,856,341 | <p>I'm struggling with stupid problem; until now I was working with pandas panel that fits in to the memory. Now I've to scale up the process and I run out of the memory.
The solution proposed on the panda's documentation is to save everything on a hdf5 file. Well it works if your panel is smaller than the memory... otherwise it's impossible.
Here the code</p>
<pre><code>import pandas as pd
store = pd.HDFStore('test.h5')
yrs = list(range(1999, 2014))
xsize = 15680
ysize = 40320
slPanel = pd.Panel(np.nan, items=yrs, major_axis=list(range(0, xsize)), minor_axis=list(range(0, ysize)))
store['SP'] = slPanel
</code></pre>
<p>Have you any ideas how to workaround this problem?<br>
By the way I'm using python 3.5 x64
Thank you </p>
| 0 | 2016-10-04T15:32:03Z | 39,856,889 | <p>I <em>think</em> this should work</p>
<p>To write to the file:</p>
<pre><code>store = pd.HDFStore(âtest.h5â, âwâ, append = True)
for partofpanel in panelparts:
store.append('SP', partofpanel, data_columns = True, index = True)
</code></pre>
<p>To read from file:</p>
<pre><code>x = pd.HDFStore(âtest.h5â, ârâ)
for df in x.select(âSPâ, chunksize = 10):
#Do some stuff
</code></pre>
<p>Separately, <a href="http://dask.pydata.org/en/latest/" rel="nofollow" title="dask">dask</a> may be your friend.</p>
| 0 | 2016-10-04T15:58:42Z | [
"python",
"pandas",
"panel",
"hdf5"
]
|
unindent does not match any outer indentation level Coursera assignment | 39,856,409 | <p>Hi guys i just started with Python (3.5) trying to complete an assignment on Coursera and i keep getting the above error </p>
<pre><code>Age = 15
if Age >=15 :
print ("Highschool")
else if
print ("No HighSchool")
</code></pre>
| 0 | 2016-10-04T15:34:47Z | 39,856,556 | <p>Python, unlike many programming languages, relies on indentation to dictate scope. In particular, it permits tabs or certain number of spaces to indicate scope. Contiguous lines with the same indentation level are all in the same scope.</p>
<p>Your code:</p>
<pre><code>Age = 15
if Age >=15 :
print ("Highschool")
else if
print ("No HighSchool")
</code></pre>
<p>Has indentation that is uneven, which confuses the python interpreter. You seem to be using 4 spaces to indicate indentation, but your <code>else if</code> statement (should be <code>else:</code> by the way) is not at any indentation level that makes sense. You use 3 spaces before the <code>else if</code> statement. You should actually be using 0 spaces, as it is operating at the same scope/level of the <code>if</code> statement.</p>
<pre><code>Age = 15
if Age >=15 :
print ("Highschool")
else:
print ("No HighSchool")
</code></pre>
<p>Read more about Python's whitespace <a href="http://www.secnetix.de/olli/Python/block_indentation.hawk" rel="nofollow">here</a>.</p>
| 1 | 2016-10-04T15:43:15Z | [
"python",
"python-3.x"
]
|
unindent does not match any outer indentation level Coursera assignment | 39,856,409 | <p>Hi guys i just started with Python (3.5) trying to complete an assignment on Coursera and i keep getting the above error </p>
<pre><code>Age = 15
if Age >=15 :
print ("Highschool")
else if
print ("No HighSchool")
</code></pre>
| 0 | 2016-10-04T15:34:47Z | 39,856,568 | <p>The problem is that the <code>else</code> matching an <code>if</code> MUST occur at exactly the same indentation level as the <code>if</code>. Also, there's no need for another <code>if</code> following the <code>else</code>. Try</p>
<pre><code>Age = 15
if Age >=15:
print ("Highschool")
else:
print ("No HighSchool")
</code></pre>
<p>You should find that works better· Remember the colons - they are important!</p>
| 0 | 2016-10-04T15:43:52Z | [
"python",
"python-3.x"
]
|
Execute subprocess sequentially in python | 39,856,419 | <p>I am trying to the following 2 commands in python one after another.</p>
<pre><code>runmqsc <Queuem manager name>
Display QL (<queue name>)
</code></pre>
<p>I can execute the rumqsc command using subprocess. </p>
<pre><code>subprocess.call("runmqsc <queue manager name>", shell= True)
</code></pre>
<p>Now this commands seems like taking the control from python. If i try to execute the next command using subprocess its not working as expected.
I am not even sure how to execute the second(for which i have to pass an argument). </p>
<p>Adding the code snippet:</p>
<pre><code>subprocess.call("runmqsc Qmgrname", shell= True)
subprocess.call("DISPLAY QL(<quename>)",shell=True)
</code></pre>
<p>Now the first line executes fine and as mentioned by tdelaney in the comment runmqsc waits for input from stdin. And after executing the first line the program hangs without even executing the second line.</p>
<p>Any help or references to any of the related document would help.
Thanks</p>
| 0 | 2016-10-04T15:35:03Z | 39,863,043 | <p>On Unix, Linux or Windows, you can simply do:</p>
<pre><code>runmqsc QMgrName < some_mq_cmds.mqsc > some_mq_cmds.out
</code></pre>
<p>In the 'some_mq_cmds.mqsc' file, put your MQSC commands like: </p>
<pre><code>DISPLAY QL("TEST.Q1")
</code></pre>
| 0 | 2016-10-04T23:01:44Z | [
"python",
"unix",
"subprocess",
"websphere-mq-fte"
]
|
Execute subprocess sequentially in python | 39,856,419 | <p>I am trying to the following 2 commands in python one after another.</p>
<pre><code>runmqsc <Queuem manager name>
Display QL (<queue name>)
</code></pre>
<p>I can execute the rumqsc command using subprocess. </p>
<pre><code>subprocess.call("runmqsc <queue manager name>", shell= True)
</code></pre>
<p>Now this commands seems like taking the control from python. If i try to execute the next command using subprocess its not working as expected.
I am not even sure how to execute the second(for which i have to pass an argument). </p>
<p>Adding the code snippet:</p>
<pre><code>subprocess.call("runmqsc Qmgrname", shell= True)
subprocess.call("DISPLAY QL(<quename>)",shell=True)
</code></pre>
<p>Now the first line executes fine and as mentioned by tdelaney in the comment runmqsc waits for input from stdin. And after executing the first line the program hangs without even executing the second line.</p>
<p>Any help or references to any of the related document would help.
Thanks</p>
| 0 | 2016-10-04T15:35:03Z | 39,866,007 | <p>You don't want to run to subprocess commands sequentially. When you run <code>runmqsc</code> on the command line, it takes over <code>stdin</code>, executes the commands you enter and then finally exits when you tell it to. From <a href="http://www.ibm.com/support/knowledgecenter/SSFKSJ_9.0.0/com.ibm.mq.ref.adm.doc/q083460_.htm" rel="nofollow">the docs</a>:</p>
<blockquote>
<p>By taking stdin from the keyboard, you can enter MQSC commands interactively.
By redirecting the input from a file, you can run a sequence of
frequently used commands contained in the file. You can also redirect
the output report to a file.</p>
</blockquote>
<p>But I think there's a third way. Start <code>runmqsc</code>, write your command(s) to <code>stdin</code> then close <code>stdin</code>. It should execute the commands and exit. It turns out that <a href="https://docs.python.org/3.6/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow"><code>Popen.communicate</code></a> does this for you. I don't know if you want to capture the output but in this example I'm letting it go to the screen.</p>
<pre><code># start msg queue manager
mqsc = subprocess.Popen(["runmqsc", "QMAGTRAQ01"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# pass command(s) to manager and capture the result
out, err = mqsc.communicate("DISPLAY QL(BP.10240.012.REQUEST)")
# wait for command to complete and deal with errors
retcode = mqsc.wait()
if retcode != 0:
print("-- ERROR --") # fancy error handling here
print("OUTPUT: ", out)
print()
print("ERROR: ", err)
</code></pre>
<p>In python3, <code>out</code> and <code>err</code> are <code>bytes</code> objects, not strings. Similar to using an encoding when you read a text file, you may have to decode them based on whatever language your program uses. Lets say the file was UTF8, then you would</p>
<pre><code>out = out.decode('utf-8')
</code></pre>
| 0 | 2016-10-05T05:26:12Z | [
"python",
"unix",
"subprocess",
"websphere-mq-fte"
]
|
SWIG general questions | 39,856,524 | <p>I'm learning SWIG and I'm trying to understand some c++ possible situations which i haven't been able to figure out after looking the docs&examples, here's my content:</p>
<p>usecase1.h</p>
<pre><code>#ifndef __USECASE1_H__
#define __USECASE1_H__
namespace foo_namespace {
int usecase1_f1( float b, float c, float *res );
}
#endif
</code></pre>
<p>usecase1.cpp</p>
<pre><code>int usecase1_f1( float b, float c, float *res )
{
return 1;
}
</code></pre>
<p>usecase2.h</p>
<pre><code>#ifndef __USECASE2_H__
#define __USECASE2_H__
extern double usecase2_v1;
int usecase2_f1(int n);
char *usecase2_f2();
#endif
</code></pre>
<p>usecase2.cpp</p>
<pre><code>#include <time.h>
double usecase2_v1 = 3.0;
int usecase2_f1(int n) {
if (n <= 1) return 1;
else return n * usecase2_f1(n - 1);
}
char *usecase2_f2()
{
time_t ltime;
time(&ltime);
return ctime(&ltime);
}
</code></pre>
<p>usecase3.h</p>
<pre><code>#ifndef __USECASE3_h__
#define __USECASE3_h__
#include <math.h>
namespace foo_namespace {
static inline float usecase3_f1( float x )
{
return 31.0f;
}
}
#endif
</code></pre>
<p>example1_working.i</p>
<pre><code>%module example
%{
int usecase1_f1( float b, float c, float *res );
#include "usecase2.h"
%}
int usecase1_f1( float b, float c, float *res );
%include "usecase2.h"
</code></pre>
<p>example2_not_working.i</p>
<pre><code>%module example
%{
#include "usecase1.h"
#include "usecase2.h"
%}
%include "usecase1.h"
%include "usecase2.h"
</code></pre>
<p>QUESTIONS</p>
<ul>
<li>Declaring explicitely namespaced functions like in <code>example1_working.i</code> will work but I'd like to use the headers instead, it seems swig messes up with namespaces, is there any workaround?</li>
<li>How can i wrap namespaced functions declared as static inline in the swig file (usecase3.h)?</li>
</ul>
| 1 | 2016-10-04T15:41:23Z | 39,868,588 | <p>Make sure you're passing -c++ to swig when you run it, C++ support isn't enabled by default.
See here for more details on wrapping C++ - <a href="http://www.swig.org/Doc1.3/SWIGPlus.html" rel="nofollow">http://www.swig.org/Doc1.3/SWIGPlus.html</a></p>
| 0 | 2016-10-05T08:08:25Z | [
"python",
"c++",
"namespaces",
"inline",
"swig"
]
|
how to compare two objects in class using __cmp__ method in Python? | 39,856,601 | <pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return
elif self.value > other:
return 1
else:return 0
</code></pre>
<p>But when I wanna test the program with :</p>
<pre><code>Box(2) < Box(2)
Box(2) <= Box(2)
Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
Box(0) != Box(0)
</code></pre>
<p>Part of the code below:</p>
<pre><code>Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
</code></pre>
<p>has shown </p>
<blockquote>
<p>TypeError: an integer is required</p>
</blockquote>
<p>Anyone knows why?</p>
<p>EDITED :I added the -1 before but somehow I deleted it -.-
sorry for asking such careless question!</p>
| -1 | 2016-10-04T15:45:29Z | 39,856,645 | <p>You have to compare <code>self.value</code> to <code>other.value</code>:</p>
<pre><code>def __cmp__(self,other):
if self.value < other.value:
return -1
elif self.value > other.value:
return 1
else:return 0
</code></pre>
<p>otherwise you're comparing an integer to an object</p>
| 1 | 2016-10-04T15:47:14Z | [
"python",
"python-2.7"
]
|
how to compare two objects in class using __cmp__ method in Python? | 39,856,601 | <pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return
elif self.value > other:
return 1
else:return 0
</code></pre>
<p>But when I wanna test the program with :</p>
<pre><code>Box(2) < Box(2)
Box(2) <= Box(2)
Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
Box(0) != Box(0)
</code></pre>
<p>Part of the code below:</p>
<pre><code>Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
</code></pre>
<p>has shown </p>
<blockquote>
<p>TypeError: an integer is required</p>
</blockquote>
<p>Anyone knows why?</p>
<p>EDITED :I added the -1 before but somehow I deleted it -.-
sorry for asking such careless question!</p>
| -1 | 2016-10-04T15:45:29Z | 39,856,674 | <p><a href="https://docs.python.org/2/library/functions.html#cmp" rel="nofollow">Doc reference</a> on <code>__cmp__</code>:</p>
<blockquote>
<p>Should <em>return</em> a <strong>negative integer</strong> if <code>self < other</code>, <strong>zero</strong> if <code>self == other</code>, a <strong>positive integer</strong> if <code>self > other</code></p>
</blockquote>
<p>So all your branches should return an integer but the <code>if</code> branch is returning <code>None</code>.</p>
| 0 | 2016-10-04T15:48:27Z | [
"python",
"python-2.7"
]
|
how to compare two objects in class using __cmp__ method in Python? | 39,856,601 | <pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return
elif self.value > other:
return 1
else:return 0
</code></pre>
<p>But when I wanna test the program with :</p>
<pre><code>Box(2) < Box(2)
Box(2) <= Box(2)
Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
Box(0) != Box(0)
</code></pre>
<p>Part of the code below:</p>
<pre><code>Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
</code></pre>
<p>has shown </p>
<blockquote>
<p>TypeError: an integer is required</p>
</blockquote>
<p>Anyone knows why?</p>
<p>EDITED :I added the -1 before but somehow I deleted it -.-
sorry for asking such careless question!</p>
| -1 | 2016-10-04T15:45:29Z | 39,856,711 | <p>Note that the <code>__cmp__</code> method id deprecated now - you should really use the so-called "rich comparison" methods - <code>__eq__</code> and friends.</p>
<p>The error is being caused because you are attempting to compare an integer with a <code>Box</code> object, and no such comparison is defined. Perhaps what you need is more like</p>
<pre><code> if self.value < other.value:
return -1
elif self.value > other.value:
return 1
else:
return 0
</code></pre>
<p>but then you might need to take into account whether <code>other</code> is a <code>Box</code> or not. If it's not, what does the comparison mean?</p>
| 0 | 2016-10-04T15:50:23Z | [
"python",
"python-2.7"
]
|
how to compare two objects in class using __cmp__ method in Python? | 39,856,601 | <pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return
elif self.value > other:
return 1
else:return 0
</code></pre>
<p>But when I wanna test the program with :</p>
<pre><code>Box(2) < Box(2)
Box(2) <= Box(2)
Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
Box(0) != Box(0)
</code></pre>
<p>Part of the code below:</p>
<pre><code>Box(1) >= Box(2)
Box(3) > Box(2)
Box(0) == Box(1)
</code></pre>
<p>has shown </p>
<blockquote>
<p>TypeError: an integer is required</p>
</blockquote>
<p>Anyone knows why?</p>
<p>EDITED :I added the -1 before but somehow I deleted it -.-
sorry for asking such careless question!</p>
| -1 | 2016-10-04T15:45:29Z | 39,856,728 | <p>Python's __cmp__ magic method returns an integer > 0 if greater, 0 if equal, and < 0 if less. You can see that in the <a href="https://docs.python.org/2/reference/datamodel.html#object.__cmp__" rel="nofollow">docs</a>.</p>
<p>Your __cmp__ function returns None for the 'less than' comparison.</p>
<pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return # return None <--------- bad
elif self.value > other:
return 1
else:return 0
</code></pre>
<p>It should be:</p>
<pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other:
return -1 # <--------- yay!
elif self.value > other:
return 1
else:
return 0
</code></pre>
<p>As others pointed out, if you are seeking to compare a Box to another Box, you should modify your __cmp__ method to compare <code>other.value</code>, not just <code>other</code>.</p>
<pre><code>class Box(object):
def __init__(self, ival):
self.value = ival
def __cmp__(self,other):
if self.value < other.value:
return -1
elif self.value > other.value:
return 1
else:
return 0
</code></pre>
| 2 | 2016-10-04T15:50:58Z | [
"python",
"python-2.7"
]
|
sending the value of HTML checkbox to django view | 39,856,699 | <p>I have the following HTML page</p>
<pre><code><input type="checkbox" name="checks[]" value="1">REG_AGREED_SUITE01
</label>
<hr>
<label class="checkbox">
<input type="checkbox" name="checks[]" value="2">REG_AGREED_SUITE02
</label>
<hr>
<label class="checkbox">
<input type="checkbox" name="checks[]" value="3">REG_AGREED_SUITE03
</label>
</code></pre>
<p>I have a Django view like this</p>
<pre><code>cd1 = "<command>"
cd2 = "</command>"
test_runner_path = "Abc - C:\git_new\evo_automation\ tests\TestRunner"
test_runner_path2 = "Def - C:\git_new\evo_automation\ tests\TestRunner"
STB = "VMS_01"
TestSuite = "REG_AGREED_SUITE02"
</code></pre>
<p>Right now I am passing TestSuite value manually from views. But I am trying like, If I select the checkbox from html page, It should replace the hard coded value in views and pass the parameter. Is there any way I can do it?</p>
| 0 | 2016-10-04T15:49:49Z | 39,857,010 | <p>Use Jquery and ajax request to pass data to view:</p>
<pre><code> $("checkbox").change(function(){
$.post("path/to/url",
{
checkBoxValue: $("#CheckboxID").val()
}
});
</code></pre>
| 1 | 2016-10-04T16:05:04Z | [
"python",
"html",
"django",
"jenkins"
]
|
Why Python's RotatingFileHandler of logging module will rename log file instead of create a new one? | 39,856,709 | <p>I have read the <code>handlers.py</code>of Python's logging module, and found that the logic of rotating log is unreasonable. The follow picture is its comments:
<a href="http://i.stack.imgur.com/0n3Ul.png" rel="nofollow"><img src="http://i.stack.imgur.com/0n3Ul.png" alt="enter image description here"></a></p>
<p>I think this logic is unreasonable especially in Windows: If some other processes hold the handler of the log file, then the renaming will fail. For example, I have two processes, one process find it is time to rotate file, so it close its own handler and rename the log. But this time, the log file's handler is held by another process, so an IO Exception will be raised because the log file can not be renamed now. That is why we say logging module is unsafe in multi-process.</p>
<p>My question is: Why not create another log file directly? Why does it need to rename the log file?</p>
<p>Suppose the log named <code>console.log</code>, I think the logic should be like this:</p>
<pre><code>if there is not console.log in destination folder:
create console.log and logging info
else:
add the suffix to the log file name.(e.g.: console.log.1)
create the file and logging info
if the log file gets filled up:
close the handler of the log file
increase the suffix number
create console.log.`newsuffix`(e.g.:console.log.2) and continue to logging info
</code></pre>
<p>In this logic, there is no need to rename the file, so there will not raise the IO Exception.</p>
<p>Can you find some bugs if the rotatingFileHandler of Python's logging module use my logic?</p>
| -1 | 2016-10-04T15:50:10Z | 39,857,090 | <p>This is so that <code>console.log</code> will always be the latest log file, you don't need any extra logic to find the newest log file. This has been standard practice for ages.</p>
<p>I know that, at least on Linux/Unix, when a process opens a file, it's filename gets translated to a inode value, and that is used as a reference, not it's filename.</p>
<p>Any processes that had the file open previously will still be pointed to that inode, until their own lock is refreshed or closed. With this in mind, moving or deleting a file does nothing to any processes that previously had the file handle open, but everybody else will not see the old file (at least by filename).</p>
| 1 | 2016-10-04T16:09:10Z | [
"python",
"logging"
]
|
Why Python's RotatingFileHandler of logging module will rename log file instead of create a new one? | 39,856,709 | <p>I have read the <code>handlers.py</code>of Python's logging module, and found that the logic of rotating log is unreasonable. The follow picture is its comments:
<a href="http://i.stack.imgur.com/0n3Ul.png" rel="nofollow"><img src="http://i.stack.imgur.com/0n3Ul.png" alt="enter image description here"></a></p>
<p>I think this logic is unreasonable especially in Windows: If some other processes hold the handler of the log file, then the renaming will fail. For example, I have two processes, one process find it is time to rotate file, so it close its own handler and rename the log. But this time, the log file's handler is held by another process, so an IO Exception will be raised because the log file can not be renamed now. That is why we say logging module is unsafe in multi-process.</p>
<p>My question is: Why not create another log file directly? Why does it need to rename the log file?</p>
<p>Suppose the log named <code>console.log</code>, I think the logic should be like this:</p>
<pre><code>if there is not console.log in destination folder:
create console.log and logging info
else:
add the suffix to the log file name.(e.g.: console.log.1)
create the file and logging info
if the log file gets filled up:
close the handler of the log file
increase the suffix number
create console.log.`newsuffix`(e.g.:console.log.2) and continue to logging info
</code></pre>
<p>In this logic, there is no need to rename the file, so there will not raise the IO Exception.</p>
<p>Can you find some bugs if the rotatingFileHandler of Python's logging module use my logic?</p>
| -1 | 2016-10-04T15:50:10Z | 39,857,169 | <p>The main problem with your proposal is that the actual logging file always will be changing (first will be console.log, later will be console.log.1, after that console.log.2 etc...) so, all the programs that will read the logs, they will have to implement logic to find what is the newer file, the main problem is that the software reading logs will need to constantly scan the logs folder to find if a new file is created and start to read logs from it.</p>
| 1 | 2016-10-04T16:13:14Z | [
"python",
"logging"
]
|
Python (2.*) Tkinter - Advanced Event Handling Formatting | 39,856,795 | <p>I'm writing a test program to detect mouse motion within a Tkinter Window using Python 2.*. I can create the necessary widgets and bind the appropriate event handler function to the root widget as needed:</p>
<pre><code>import Tkinter as tk
class App:
def __init__(self, master=None):
self.root = master
self.frame = tk.Frame(master)
self.frame.pack()
self.create_widgets()
self.setup_handlers()
def create_widgets(self):
...
def setup_handlers(self):
self.root.bind('<Motion>', self.update) # This is the line I wish to look at
def update(self, event):
...
root = tk.Tk()
app = App(master=root)
root.mainloop()
</code></pre>
<p>What I want to do now is be able to activate the event handler with a combined input. I want to be able, for instance, to only activate the event handler when I move the mouse with the 'r' key held down. What event string would I need for this? Where can I find a full rundown on the event-string formatting for binding event handlers?</p>
| 1 | 2016-10-04T15:53:54Z | 39,857,937 | <p>for the combined event handling, you can do something like:</p>
<pre><code>class App:
holding = False
def __init__(self, master):
self.root = master
self.root.bind("<KeyPress>", self.holdkey)
self.root.bind("<KeyRelease>", self.releasekey)
def holdkey(self, e):
if e.char == "r" and not self.holding:
self.root.bind("<Motion>", self.combined_update)
self.holding = True
def releasekey(self, e):
if e.char == "r" and self.holding:
self.root.unbind("<Motion>")
self.holding = False
def combined_update(self, e):
# Event handling for the combined event.
print ("yo")
</code></pre>
<p>This will "probably" work.</p>
| 1 | 2016-10-04T17:00:36Z | [
"python",
"tkinter",
"event-handling"
]
|
How to define class variables using the functions and variables of an instance in Python | 39,856,861 | <p>Is there a way to define a class variable using the variables and functions of the instance? Thanks</p>
<p>The simplified code looks like this:</p>
<pre><code>def ClassA():
X = self.func(self.a)
def __init__(self, avalue):
self.a = avalue
def func(self):
return self.a + 5
</code></pre>
<p>NameError: name 'self' is not defined</p>
| -3 | 2016-10-04T15:57:17Z | 39,856,921 | <p>Firstly, you define a Class using <code>class</code>, not <code>def</code>.</p>
<p><code>self</code> only needs to be used inside of the class' function definitions, because they change the scope. Outside of them you don't need it:
<code>x = func(a)</code>.</p>
<p>But your code wouldn't work anyways because the instance doesn't exist yet.</p>
| 0 | 2016-10-04T16:00:25Z | [
"python",
"class",
"scope"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.