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 |
|---|---|---|---|---|---|---|---|---|---|
IDLE (Python 3.4) - Execute a script on launch | 39,686,711 | <p>I've been spending the last week or so creating a simple touch friendly GUI in python3.4 (on the raspberry pi). Now I setup python to run my script on launch, but I ran into the problem, that I couldn't open other programs from within my program (such as the web browser or calculator). However if I use IDLE to execu... | 1 | 2016-09-25T12:17:47Z | 39,687,206 | <h3>Use Idle's cli options</h3>
<p>You have a few options, of which the best one is to use the <code>-r</code> option. From <code>man idle</code>:</p>
<pre><code> -r file
Run script from file.
</code></pre>
<p>This will however only open the <em>interpreter</em> window. Since you also want the editor, th... | 0 | 2016-09-25T13:11:29Z | [
"python",
"linux",
"shell",
"raspberry-pi",
"python-idle"
] |
Python function that behaves differently depending on the input object types | 39,686,720 | <p>In Python, can I write a function that takes objects as inputs and performs different calculations depending on the types of the objects?</p>
<p>For example, say I have two classes: "circle" and "line". I define a circle object A with a radius and centre position, and a circle object B with a different radius and c... | 0 | 2016-09-25T12:18:32Z | 39,686,774 | <p>Yes, you can certainly detect the types of your Python objects and execute different behaviour based on that. The built-in <code>type()</code> method will provide the information you need.</p>
<p>I should stress that this is rather reverting to the procedural paradigm whereas what you may be better off doing in loo... | 1 | 2016-09-25T12:24:24Z | [
"python",
"oop",
"linear-algebra"
] |
How can I find and remove elements that have a specific pattern from a list? | 39,686,755 | <p>I have a list that is something like this:</p>
<pre><code>output=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G... | -1 | 2016-09-25T12:22:26Z | 39,686,797 | <pre><code>l=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot', '/dev/mapper/vg00-lvol_data']
filtered = [ x for x in l if "/dev/mapper/" not ... | 1 | 2016-09-25T12:27:34Z | [
"python",
"python-2.7",
"python-3.x"
] |
How can I find and remove elements that have a specific pattern from a list? | 39,686,755 | <p>I have a list that is something like this:</p>
<pre><code>output=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G... | -1 | 2016-09-25T12:22:26Z | 39,686,941 | <p>if you have multiple strings need to be check, you may need this.</p>
<pre><code>regex=re.compile('^/dev/mapper|^/usr/a')
filtered_list = [s for s in my_list if not re.match(regex, s)]
</code></pre>
| 0 | 2016-09-25T12:42:12Z | [
"python",
"python-2.7",
"python-3.x"
] |
Unable to import csv file to python using the pd.read_csv command | 39,686,784 | <p>I am trying to read a csv file in Python 3.5 having imported pandas using the pd.read_csv command. However the system returns the following error message:</p>
<blockquote>
<blockquote>
<blockquote>
<p>Lung = pd.read_csv('c:\users\LungCapData.csv')
SyntaxError: (unicode error) 'unicodeescape' code... | 0 | 2016-09-25T12:25:43Z | 39,687,044 | <p>You can try prefix the string with r <code>Lung = pd.read_csv(r'c:\users\LungCapData.csv')</code></p>
| 1 | 2016-09-25T12:51:58Z | [
"python",
"csv",
"pandas"
] |
Unable to import csv file to python using the pd.read_csv command | 39,686,784 | <p>I am trying to read a csv file in Python 3.5 having imported pandas using the pd.read_csv command. However the system returns the following error message:</p>
<blockquote>
<blockquote>
<blockquote>
<p>Lung = pd.read_csv('c:\users\LungCapData.csv')
SyntaxError: (unicode error) 'unicodeescape' code... | 0 | 2016-09-25T12:25:43Z | 39,973,698 | <p>You can try the following:</p>
<pre><code>Lung = pd.read_csv(r'c:\users\LungCapData.csv', sep=';')
</code></pre>
<p>this should split the columns seeing as you seem to have semi-colons as separators.</p>
| 1 | 2016-10-11T08:57:53Z | [
"python",
"csv",
"pandas"
] |
Unable to import csv file to python using the pd.read_csv command | 39,686,784 | <p>I am trying to read a csv file in Python 3.5 having imported pandas using the pd.read_csv command. However the system returns the following error message:</p>
<blockquote>
<blockquote>
<blockquote>
<p>Lung = pd.read_csv('c:\users\LungCapData.csv')
SyntaxError: (unicode error) 'unicodeescape' code... | 0 | 2016-09-25T12:25:43Z | 39,974,631 | <p>not familiar with windows platform ,but you can try this with encoding option:</p>
<pre><code>Lung = pd.read_csv(r'c:\users\LungCapData.csv', encoding="utf8")
</code></pre>
| 0 | 2016-10-11T09:50:52Z | [
"python",
"csv",
"pandas"
] |
Getting Column Headers from multiple html 'tbody' | 39,686,830 | <p>I need to get the column headers from the second tbody in this url.</p>
<p><a href="http://bepi.mpob.gov.my/index.php/statistics/price/daily.html" rel="nofollow">http://bepi.mpob.gov.my/index.php/statistics/price/daily.html</a></p>
<p>Specifically, i would like to see "september, october"... etc.</p>
<p>I am gett... | 0 | 2016-09-25T12:30:13Z | 39,687,111 | <p>When you click "View Price" button a POST request is sent to the <code>http://bepi.mpob.gov.my/admin2/price_local_daily_view3.php</code> endpoint. Simulate this POST request and parse the resulting HTML:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
with requests.Session() as session:
session.g... | 1 | 2016-09-25T12:59:36Z | [
"python",
"html",
"web-scraping",
"html-table"
] |
Parallelize groupby with multiple arguments | 39,686,957 | <p>I found this <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">question</a> on parallelizing groupby. However, it can't be translated one-to-one into the case where there's multiple arguments - unless I'm mistaken.</p>
<p>Is the following a correct way of doing it? Is ther... | 0 | 2016-09-25T12:43:41Z | 39,688,494 | <p>First caveat, unless your data is fairly large, you may not see much (or any) benefit to parallelization.</p>
<p>Rather than working directly with a multiprocessing pool, the easiest way to do this now would be to try <a href="http://dask.pydata.org/en/latest/dataframe-overview.html" rel="nofollow"><code>dask</code... | 1 | 2016-09-25T15:18:49Z | [
"python",
"pandas"
] |
scrapy-splash returns its own headers and not the original headers from the site | 39,687,101 | <p>I use scrapy-splash to build my spider. Now what I need is to maintain the session, so I use the scrapy.downloadermiddlewares.cookies.CookiesMiddleware and it handles the set-cookie header. I know it handles the set-cookie header because i set COOKIES_DEBUG=True and this causes the printouts by CookeMiddleware regar... | 1 | 2016-09-25T12:57:35Z | 39,691,344 | <p>To get original response headers you can write a <a href="http://splash.readthedocs.io/en/stable/scripting-tutorial.html" rel="nofollow">Splash Lua script</a>; see <a href="https://github.com/scrapy-plugins/scrapy-splash#examples" rel="nofollow">examples</a> in scrapy-splash README:</p>
<blockquote>
<p>Use a Lua ... | 1 | 2016-09-25T20:10:33Z | [
"python",
"scrapy",
"scrapy-splash"
] |
python: [try + except] How to make sure all command under try is executed? | 39,687,112 | <p>This is a very beginners' question. But I cannot find answer...</p>
<p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p>
<p>For example, I have some codes like this...</p>
<pre><code>for i in range(0,100):
try:
... | 1 | 2016-09-25T12:59:43Z | 39,687,158 | <p>You could alter the code so that it only prints when all expressions are valid:</p>
<pre><code>for i in range(0,3):
try:
print ("a" + "\n" +
"b" + "\n" +
C + "\n" +
"d")
except:
print (i, "fail")
</code></pre>
<p>Another variation to the same ... | 3 | 2016-09-25T13:05:38Z | [
"python"
] |
python: [try + except] How to make sure all command under try is executed? | 39,687,112 | <p>This is a very beginners' question. But I cannot find answer...</p>
<p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p>
<p>For example, I have some codes like this...</p>
<pre><code>for i in range(0,100):
try:
... | 1 | 2016-09-25T12:59:43Z | 39,687,198 | <p>This is very similar to what @trincot posted, not sure if it would meet your requirements.</p>
<p>Basically, move all of your prints to a separate function and call that in your try.</p>
<pre><code>def printer(i=None, C=None):
print "a"
print "b"
print i, C
print "d"
for i in range(0,100):
... | 0 | 2016-09-25T13:10:31Z | [
"python"
] |
python: [try + except] How to make sure all command under try is executed? | 39,687,112 | <p>This is a very beginners' question. But I cannot find answer...</p>
<p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p>
<p>For example, I have some codes like this...</p>
<pre><code>for i in range(0,100):
try:
... | 1 | 2016-09-25T12:59:43Z | 39,687,283 | <p>You could temporarily redirect stdout and only print in the except: </p>
<pre><code>import sys
from StringIO import StringIO
for i in range(0,100):
sys.stdout = StringIO()
try:
print "a"
print "b"
print i, C
print "d"
except Exception as e:
sys.stdout = sys.__st... | 1 | 2016-09-25T13:21:22Z | [
"python"
] |
Populating SQLite table with JSON data, getting: sqlite3.OperationalError: near "x": syntax error | 39,687,292 | <p>I have a SQLite database with four tables named restaurants, bars, attractions, and lodging. Each table has 3 columns named id, name, and description. I am trying to populate the database with data from a JSON file that looks like this:</p>
<pre><code>{
"restaurants": [
{"id": "ChIJ8xR18JUn5IgRfwJJByM-quU", "... | 0 | 2016-09-25T13:22:10Z | 39,687,329 | <p>Your current problem is the <em>missing quotes</em> around the string values in the query.</p>
<p>You need to <em>properly parameterize your query</em> letting the database driver worry about the type conversions, putting quotes properly and escaping the parameters:</p>
<pre><code>query = """
INSERT OR IGNORE ... | 3 | 2016-09-25T13:26:05Z | [
"python",
"sql",
"json",
"python-3.x",
"sqlite3"
] |
python dicom -- getting pixel value from dicom file | 39,687,295 | <p>I was trying to get the pixelvalues of a dicom file in python using the dicom library.</p>
<p>But it returns only an array with zeros. </p>
<p>My code was like this:</p>
<pre><code>import dicom
import numpy
ds=pydicom.read_file("sample.dcm")
print(ds.pixel_array)
</code></pre>
<p>and the results is</p>
<pre... | 1 | 2016-09-25T13:22:24Z | 39,689,711 | <p>The code as written should work. It is possible that the beginning and end of the array are truly zeros.</p>
<p>It is usually more meaningful to look at something in the middle of the image.</p>
<p>E.g.:</p>
<pre><code>midrow = ds.Rows // 2
midcol = ds.Columns // 2
print(ds.pixel_array[midrow-20:midrow+20, midco... | 1 | 2016-09-25T17:25:59Z | [
"python",
"numpy",
"pixel",
"dicom"
] |
Receiving the 404 error in getting of static django files | 39,687,314 | <p>Please help to understand what I do wrong.</p>
<p>I have in my settings.py :</p>
<pre><code>PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/'
</code></pre>
<p>And in index.html :</p>
<pre><code>{% load static %}
<link rel="styleshe... | 0 | 2016-09-25T13:24:42Z | 39,687,376 | <p>Read this <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow">Django_Docs</a><br>
You must also have a <code>STATIC_ROOT</code> option set before you can use the static files, heres some help
add this to your code:</p>
<pre><code>STATIC_URL = os.path.join(PROJECT_ROOT, 'static').repl... | 1 | 2016-09-25T13:33:20Z | [
"python",
"html",
"css",
"django",
"static"
] |
Find difference in list with identical values | 39,687,380 | <p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p>
<p>example</p>
<pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y']
b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y']
</code></pre>
<p>How m... | 0 | 2016-09-25T13:33:32Z | 39,687,410 | <p>For <strong>simple list</strong> - what you ask is simply searching for that next item in the list:</p>
<pre><code>>>> a = ['cool task', 'b', 'another task', 'j', 'better task', 'y']
>>> b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y']
>>> c = [[x, b[b.index(... | 1 | 2016-09-25T13:36:57Z | [
"python"
] |
Find difference in list with identical values | 39,687,380 | <p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p>
<p>example</p>
<pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y']
b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y']
</code></pre>
<p>How m... | 0 | 2016-09-25T13:33:32Z | 39,687,513 | <p>Depending on your purposes, you could possibly use <code>Counter</code> from the <a href="https://docs.python.org/3.6/library/collections.html" rel="nofollow">collections module</a>:</p>
<pre><code>>>> from collections import Counter
>>> a = Counter(['cool task', 'b', 'another task', 'j', 'better ... | 0 | 2016-09-25T13:46:31Z | [
"python"
] |
Find difference in list with identical values | 39,687,380 | <p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p>
<p>example</p>
<pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y']
b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y']
</code></pre>
<p>How m... | 0 | 2016-09-25T13:33:32Z | 39,687,534 | <p>You could use the <a href="https://docs.python.org/3/library/difflib.html#sequencematcher-objects" rel="nofollow"><code>difflib.SequenceMatcher()</code> class</a> to enumerate added, removed and changed entries:</p>
<pre><code>>>> from difflib import SequenceMatcher
>>> matcher = SequenceMatcher(a... | 1 | 2016-09-25T13:47:37Z | [
"python"
] |
Find difference in list with identical values | 39,687,380 | <p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p>
<p>example</p>
<pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y']
b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y']
</code></pre>
<p>How m... | 0 | 2016-09-25T13:33:32Z | 39,687,769 | <p>it works as you want:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def difference(a, b):
a, b = (lambda x, y: (y, x) if len(set(x)) > len(set(y)) else (x, y)) (a, b)
a_result = list(a)
b_result = list(b)
for z in range(len(a)):
if a[z] in b:
a_result.remove(... | 0 | 2016-09-25T14:10:45Z | [
"python"
] |
Tornado: How to get and return large data with less memory usage? | 39,687,451 | <p>I have web-crawler and http interface for it.</p>
<p>Crawler gets grouped urls as dictionary. I need to return a result in the same format in JSON. But I was faced with a large memory usage, which is not returned to the operating system. How can I implement this solution without large memory usage?</p>
<p>Code:
</... | 0 | 2016-09-25T13:40:26Z | 39,691,452 | <p>It looks to me like most of the memory usage is devoted to <code>self.responses</code>. Since you seem to be ordering responses by "group" before writing them to a file, I can understand why you do it this way. One idea is to store them in a database (MySQL or MongoDB or whatever) with the "group" as column or field... | 0 | 2016-09-25T20:21:06Z | [
"python",
"tornado"
] |
python error in decoding base64 string | 39,687,484 | <p>I'm trying to unzip a base64 string,</p>
<p>this is the code I'm using</p>
<pre><code>def unzip_string(s) :
s1 = base64.decodestring(urllib.unquote(s))
sio = StringIO.StringIO(s1)
gzf = gzip.GzipFile(fileobj=sio)
guff = gzf.read()
return json.loads(guff)
</code></pre>
<p>i'm getting error Erro... | 1 | 2016-09-25T13:43:51Z | 39,687,677 | <p>This worked for me (Python 3). The padding is indeed important, as you've seen in other answers:</p>
<pre><code>import base64
import zlib
import json
s = b'H4sIAAAAAAAAA22PW0/CQBCF/8s81wQosdA3TESJhhhb9cHwMN1O6Ybtbt0LhDT97+5yU4yPc+bMnO90YCyyDaSfHRimieQSG4IUaldABC1qbAykHbQsrzWZWokSUumEiMCQ3nJGCy9ADH0EFvWarJ+eHv11v4q... | 0 | 2016-09-25T14:01:49Z | [
"python",
"base64",
"gzip"
] |
Weird behavior of send() and recv() | 39,687,586 | <p>SORRY FOR BAD ENGLISH</p>
<p>Why if I have two <strong><code>send()</code></strong>-s on the server, and two <strong><code>recv()</code></strong>-s on the client, sometimes the first <code>recv()</code> will get the content of the 2nd <code>send()</code> from the server, without taking just the content of the first... | 1 | 2016-09-25T13:53:17Z | 39,687,703 | <p>Most probably you use SOCK_STREAM type socket. This is a TCP socket and that means that you push data to one side and it gets from the other side in the same order and without missing chunks, but there are no delimiters. So <code>send()</code> just sends data and <code>recv()</code> receives all the data available t... | 0 | 2016-09-25T14:05:36Z | [
"python"
] |
Weird behavior of send() and recv() | 39,687,586 | <p>SORRY FOR BAD ENGLISH</p>
<p>Why if I have two <strong><code>send()</code></strong>-s on the server, and two <strong><code>recv()</code></strong>-s on the client, sometimes the first <code>recv()</code> will get the content of the 2nd <code>send()</code> from the server, without taking just the content of the first... | 1 | 2016-09-25T13:53:17Z | 39,687,709 | <p>This is by design.</p>
<p>A TCP stream is a channel on which you can send bytes between two endpoints but the transmission is stream-based, not message based.</p>
<p>If you want to send messages then you need to encode them... for example by prepending a "size" field that will inform the receiver how many bytes to... | 1 | 2016-09-25T14:05:49Z | [
"python"
] |
Python parsing html mismatched tag error | 39,687,612 | <pre><code>30 <li class="start_1">
31 <input type="checkbox" name="word_ids[]" value="34" class="list_check">
32 </li>
</code></pre>
<p>This is a part of html file that I want to parse. But when I applied </p>
<pre><code>uh = open('1.htm','r')
data = uh.read()
print data
... | 0 | 2016-09-25T13:55:32Z | 39,687,645 | <p>You are trying to parse HTML with an <em>XML parser</em>; the latter doesn't have a concept of <code><input></code> not having a closing tag.</p>
<p>Use an actual HTML parser; if you want to access the result with an ElementTree-compatible API, use the <code>lxml</code> project, which <a href="http://lxml.de/... | 0 | 2016-09-25T13:59:07Z | [
"python",
"html",
"parsing"
] |
Python parsing html mismatched tag error | 39,687,612 | <pre><code>30 <li class="start_1">
31 <input type="checkbox" name="word_ids[]" value="34" class="list_check">
32 </li>
</code></pre>
<p>This is a part of html file that I want to parse. But when I applied </p>
<pre><code>uh = open('1.htm','r')
data = uh.read()
print data
... | 0 | 2016-09-25T13:55:32Z | 39,687,962 | <p>To parse HTML in Python i use lxml:</p>
<pre><code>import lxml.html
// html string
dom = '<li class="start_1">...</li>'
// get the root node
root_node = lxml.html.fromstring(dom)
</code></pre>
<p>after that you can play with it, for example using xpath:</p>
<pre><code>nodes = root_node.xpath("//*")
</... | 0 | 2016-09-25T14:28:44Z | [
"python",
"html",
"parsing"
] |
What the difference between dict_proxy in python2 and mappingproxy in python3? | 39,687,713 | <p>I notice when I create class in python2 it stores attributes in <code>dict_proxy</code> object: </p>
<pre><code>>>> class A(object):
... pass
>>> A.__dict__
dict_proxy({....})
</code></pre>
<p>But in python3 <code>__dict__</code> returns <code>mappingproxy</code>: </p>
<pre><code>>>&... | 2 | 2016-09-25T14:06:09Z | 39,687,741 | <p>There is no real difference, it <a href="https://hg.python.org/cpython/diff/c3a0197256ee/Objects/descrobject.c" rel="nofollow">just got renamed</a>.</p>
<p>When it was proposed to expose the type in the <code>typing</code> module in <a href="http://bugs.python.org/issue14386" rel="nofollow">issue #14386</a>, the ob... | 4 | 2016-09-25T14:08:22Z | [
"python",
"python-3.x",
"python-2.x",
"python-internals"
] |
finding variable in list | 39,687,768 | <p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p>
<pre><code>list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
</code></pre>
<p>With these lists, if the user inputs "a" then the computer ... | 0 | 2016-09-25T14:10:43Z | 39,687,817 | <pre><code>list1 = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
needle = "c"
for item1, item2 in zip(list1, list2):
if item1 == needle:
print(item2)
</code></pre>
| 0 | 2016-09-25T14:15:52Z | [
"python",
"list",
"python-3.x"
] |
finding variable in list | 39,687,768 | <p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p>
<pre><code>list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
</code></pre>
<p>With these lists, if the user inputs "a" then the computer ... | 0 | 2016-09-25T14:10:43Z | 39,687,843 | <h2>Option 1</h2>
<p>This is probably the simplest solution:</p>
<pre><code>>>> list1 = ["a", "b", "c", "d"]
>>> list2 = [1, 2, 3, 4]
>>>
>>> mapping = dict(zip(list1, list2))
>>>
>>> mapping['b']
2
</code></pre>
<p>BTW, to understand what happened:</p>
<pre><co... | 0 | 2016-09-25T14:17:39Z | [
"python",
"list",
"python-3.x"
] |
finding variable in list | 39,687,768 | <p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p>
<pre><code>list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
</code></pre>
<p>With these lists, if the user inputs "a" then the computer ... | 0 | 2016-09-25T14:10:43Z | 39,687,848 | <p>Here's a simple version of what I think you're trying to accomplish:</p>
<pre><code>a = ['a', 'b', 'c', 'd']
b = [1, 2, 3, 4]
ret = input("Search: ")
try:
idx = a.index(ret)
print(b[idx])
except ValueError:
print("Item not found")
</code></pre>
| 0 | 2016-09-25T14:17:54Z | [
"python",
"list",
"python-3.x"
] |
finding variable in list | 39,687,768 | <p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p>
<pre><code>list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
</code></pre>
<p>With these lists, if the user inputs "a" then the computer ... | 0 | 2016-09-25T14:10:43Z | 39,687,919 | <pre><code>list1 = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
x = input()
if x in list1 :
print list2[list1.index(x)]
else :
print "Error"
</code></pre>
| 0 | 2016-09-25T14:25:10Z | [
"python",
"list",
"python-3.x"
] |
How to replace properly certain matches on QScintilla widget? | 39,687,797 | <p>I got this little mcve code:</p>
<pre><code>import sys
import re
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.Qsci import QsciScintilla
from PyQt5 import Qsci
class FloatSlider(QtWidgets.QWidget):
value_changed = QtCore.pyqtSignal(float)
def __init__(self, value=0.0... | 1 | 2016-09-25T14:13:21Z | 39,689,109 | <p>On the second bullet point: I think you should give up the idea of having a separate window/dialog for the slider. It should instead be a popup that stays on top of the editor until you click outside it or press escape (i.e. like a tooltip, or context menu).</p>
<p>To give you an idea of how this might look (but wi... | 1 | 2016-09-25T16:22:12Z | [
"python",
"python-3.x",
"pyqt",
"qscintilla"
] |
How to replace properly certain matches on QScintilla widget? | 39,687,797 | <p>I got this little mcve code:</p>
<pre><code>import sys
import re
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import Qt
from PyQt5.Qsci import QsciScintilla
from PyQt5 import Qsci
class FloatSlider(QtWidgets.QWidget):
value_changed = QtCore.pyqtSignal(float)
def __init__(self, value=0.0... | 1 | 2016-09-25T14:13:21Z | 39,732,180 | <ul>
<li>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#setFixedWidth" rel="nofollow">setFixedWidth</a> to avoid either the slider or label changing width on every change</li>
<li>You shouldn't use <code>on_cursor_position_changed</code> event, instead just use <code>mouseReleaseEvent</code></li>
<li>... | 0 | 2016-09-27T18:46:49Z | [
"python",
"python-3.x",
"pyqt",
"qscintilla"
] |
XPath returns empty list. Why is it ignoring targeted div element? | 39,687,878 | <p>I'm a newbee to XPath and Scrapy. I'm trying to target a node which does not have a unique class (i.e. <code>class="pubBody"</code>). </p>
<p>Already tried:
<a href="http://stackoverflow.com/questions/28163626/xpath-not-contains-a-and-b">xpath not contains A and B</a></p>
<p>This should be a simple task but XPath... | 1 | 2016-09-25T14:20:32Z | 39,688,035 | <p>I suspect the problem is that the source for the page you'r trying to parse (<a href="http://www.sciencedirect.com/science/journal/00221694/" rel="nofollow">http://www.sciencedirect.com/science/journal/00221694/</a>) is not valid XML due to the <code><link ...></code> nodes/elements/tags not having closing tag... | 0 | 2016-09-25T14:35:38Z | [
"python",
"html",
"xpath",
"scrapy",
"html-parsing"
] |
XPath returns empty list. Why is it ignoring targeted div element? | 39,687,878 | <p>I'm a newbee to XPath and Scrapy. I'm trying to target a node which does not have a unique class (i.e. <code>class="pubBody"</code>). </p>
<p>Already tried:
<a href="http://stackoverflow.com/questions/28163626/xpath-not-contains-a-and-b">xpath not contains A and B</a></p>
<p>This should be a simple task but XPath... | 1 | 2016-09-25T14:20:32Z | 39,688,065 | <p>The problem is that the <em>HTML is very far from being well-formed on this page</em>. To demonstrate, see how the same exact CSS selector is producing 0 results with Scrapy and producing 94 in <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code></a>:</p>
<pre><... | 1 | 2016-09-25T14:38:15Z | [
"python",
"html",
"xpath",
"scrapy",
"html-parsing"
] |
calculating result of a function for a column of a dataframe in python | 39,687,917 | <p>I am working on a dataframe in python to calculate the distance between a location and <code>LATITUDE</code> and <code>LONGITUDE</code> column in the dataframe. When I run the code below, there is no error:</p>
<pre><code>lLat= 43.679194
lLon= -79.633352
LCentroid= (lLat, lLon)
# getDistanceBetween gets two centro... | 1 | 2016-09-25T14:24:40Z | 39,688,383 | <p>Because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow"><code>get_level_values</code></a> return a "vector" of labels. In your first example, you access the vector and appropriately retrieve the value. In your second example, you pass the entire vecto... | 1 | 2016-09-25T15:06:57Z | [
"python",
"function",
"pandas",
"dataframe"
] |
PyInstaller lib not found | 39,687,975 | <p>I made a simple python[3.5.2] program using tkinter. When I use pyinstaller[3.2] on it it gives me a ton of 'lib not found' warnings.
Example:</p>
<blockquote>
<p>2999 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\python\python.exe</p>
<p>3031 WARNING: lib not found: api-ms-win-c... | 0 | 2016-09-25T14:29:37Z | 40,001,914 | <p>Just had this problem myself. The problem is that pyinstaller is not fully compatible Windows 10. The only solution currently is to download the Windows 10 SDK (a 2GB download). </p>
<p>See more here:
<a href="https://github.com/pyinstaller/pyinstaller/issues/1566" rel="nofollow">https://github.com/pyinstaller/pyin... | 0 | 2016-10-12T14:59:44Z | [
"python",
"python-3.x",
"dll",
"tkinter",
"pyinstaller"
] |
Drawing on tkinter canvas from command line | 39,688,049 | <p>I read some tutorial (basic) on tkinter and learned how to create a mainloop and add gui elements to that. Also learned how to bind actions to button widgets.</p>
<p>Now I would like to do this: </p>
<ol>
<li>launch the tkinter canvas</li>
<li>be able to read command from the console and update the canvas after th... | -1 | 2016-09-25T14:36:33Z | 39,688,374 | <p>Here's a simple demo of grabbing user input from the console via the standard <code>input</code> function. This technique is a little clunky, since we have to explicitly tell Tkinter to fetch the input string by clicking on a Button (or some other GUI event), but that might not be a big deal for your application.</p... | 0 | 2016-09-25T15:06:25Z | [
"python",
"canvas",
"tkinter"
] |
Drawing on tkinter canvas from command line | 39,688,049 | <p>I read some tutorial (basic) on tkinter and learned how to create a mainloop and add gui elements to that. Also learned how to bind actions to button widgets.</p>
<p>Now I would like to do this: </p>
<ol>
<li>launch the tkinter canvas</li>
<li>be able to read command from the console and update the canvas after th... | -1 | 2016-09-25T14:36:33Z | 39,688,717 | <p>Came up with this:</p>
<pre><code>from Tkinter import *
import random
root = Tk()
width = 800
height = 600
def key(event):
s = raw_input("CMD: ")
if s == 'quit':
root.destroy()
if s == 'l':
x1 = random.randint(0,width)
x2 = random.randint(0,width)
y1 = random.randint(... | 0 | 2016-09-25T15:41:59Z | [
"python",
"canvas",
"tkinter"
] |
Downloading pdf from a site after submitting a form with beautifulsoup | 39,688,059 | <p>I am currently writing a crawler script with python.I am aware of beautifulsoup packages and have did some simple crawlers.currently am writing a crawler for a site which has four dropdown, after select the four dropdown if I press the download button a pdf will be downloaded.I have tried it by requests with this sc... | 0 | 2016-09-25T14:37:46Z | 39,688,129 | <p>In general, yes, it is possible, but this really depends on a target web-site and what is involved in submitting a form. </p>
<p>If this is a regular HTML form with no javascript involved, you can use packages like <a href="https://github.com/jmcarp/robobrowser" rel="nofollow"><code>RoboBrowser</code></a> or <a hre... | 1 | 2016-09-25T14:45:18Z | [
"python",
"pdf",
"beautifulsoup"
] |
asyncio: prevent task from being cancelled twice | 39,688,070 | <p>Sometimes, my coroutine cleanup code includes some blocking parts (in the <code>asyncio</code> sense, i.e. they may yield).</p>
<p>I try to design them carefully, so they don't block indefinitely. So "by contract", coroutine must never be interrupted once it's inside its cleanup fragment.</p>
<p>Unfortunately, I c... | 0 | 2016-09-25T14:38:52Z | 39,692,502 | <p>I ended up writing a simple function that provides a stronger shield, so to speak.</p>
<p>Unlike <code>asyncio.shield</code>, which protects the callee, but raises <code>CancelledError</code> in its caller, this function suppresses <code>CancelledError</code> altogether.</p>
<p>The drawback is that this function d... | 1 | 2016-09-25T22:42:19Z | [
"python",
"python-asyncio",
"coroutine"
] |
Flushing PyGaze keypress | 39,688,123 | <p><code>self.keyboard.get_key()</code> (from <a href="http://www.pygaze.org/" rel="nofollow">the PyGaze library</a>) holds a screen until a key is pressed.</p>
<p>How can I flush/clear the contents of the a key press prior to this call? </p>
<p>At the moment a previous key press is carried into the function where I ... | 0 | 2016-09-25T14:44:36Z | 39,726,363 | <p>In order to flush any keypresses in PyGaze the following should be added to the <code>get_key</code> function <code>self.keyboard.get_key(flush=True)</code>.</p>
| 0 | 2016-09-27T13:45:09Z | [
"python",
"keypress"
] |
Cleanest way to combine reduce and map in Python | 39,688,133 | <p>I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:</p>
<pre><code>def forward_pass(x, ws, bs):
activations = []
u = x
for w, b in zip(ws, bs):
u = np.maximum(0, u.dot(w)+b)
activations.append(u)
return activ... | 1 | 2016-09-25T14:45:29Z | 39,688,465 | <p>In general, <a href="https://docs.python.org/3/library/itertools.html#module-itertools" rel="nofollow"><em>itertools.accumulate()</em></a> will do what <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow"><em>reduce()</em></a> does but will give you the intermediate values as we... | 2 | 2016-09-25T15:15:59Z | [
"python",
"numpy",
"deep-learning",
"reduce"
] |
Cleanest way to combine reduce and map in Python | 39,688,133 | <p>I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:</p>
<pre><code>def forward_pass(x, ws, bs):
activations = []
u = x
for w, b in zip(ws, bs):
u = np.maximum(0, u.dot(w)+b)
activations.append(u)
return activ... | 1 | 2016-09-25T14:45:29Z | 39,689,554 | <p>The <code>dot</code> tells me you are using one or more numpy arrays. So I'll try:</p>
<pre><code>In [28]: b=np.array([1,2,3])
In [29]: x=np.arange(9).reshape(3,3)
In [30]: ws=[x,x,x]
In [31]: forward_pass(x,ws,bs)
Out[31]:
[array([[ 16, 19, 22],
[ 43, 55, 67],
[ 70, 91, 112]]),
array([[ 1... | 2 | 2016-09-25T17:07:17Z | [
"python",
"numpy",
"deep-learning",
"reduce"
] |
Cleanest way to combine reduce and map in Python | 39,688,133 | <p>I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:</p>
<pre><code>def forward_pass(x, ws, bs):
activations = []
u = x
for w, b in zip(ws, bs):
u = np.maximum(0, u.dot(w)+b)
activations.append(u)
return activ... | 1 | 2016-09-25T14:45:29Z | 40,133,207 | <p>In Python 2.x, there is no clean one-liner for this. </p>
<p>In Python 3, there is itertools.accumulate, but it is still not really clean because it doesn't accept an "initial" input, as reduce does. </p>
<p>Here is a function that, while not as nice as a built-in comprehension syntax, does the job.</p>
<pre><c... | 0 | 2016-10-19T13:45:44Z | [
"python",
"numpy",
"deep-learning",
"reduce"
] |
I'm having trouble converting a Raster to an Array | 39,688,318 | <p>I'm currently having some trouble converting a raster to an array. Ultimately I would like to convert a raster from an integer to a float32 so that I can run a gdal_calc however, I could not change the type properly in order to do this. </p>
<p>SO, I would appreciate any help that someone could provide. Here is my ... | 0 | 2016-09-25T15:01:02Z | 39,820,842 | <p>The method ReadAsArray() will create a numpy.ndarray with a dtype of the raster dataset. Your goal is to transform an integer dtype to a float32. The simplest way to do this is to use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow">astype()</a> method for nd... | 2 | 2016-10-02T19:32:25Z | [
"python",
"arrays",
"numpy",
"raster",
"gdal"
] |
Django - Can't import app names - Unresolved Reference | 39,688,351 | <p>I'm starting with a project and I suddenly can't import App names. <strong>PyCharm</strong> says that app is <code>Unresolved Reference</code> and when I try to start shell and import app, it says that it's unrecognized. </p>
<p>Do you know where could be the problem? I've checked whether the correct <code>venv</co... | 1 | 2016-09-25T15:04:11Z | 39,689,785 | <p>You probably want to use <code>import Api</code> - the same way you just have <code>Api</code> in <code>INSTALLED_APPS</code> instead of <code>ProductSpyWeb.Api</code>.</p>
<p>Assuming that you aren't doing anything strange with your Python path, when you use <code>from ProductSpyWeb import Api</code> from the Djan... | 2 | 2016-09-25T17:33:16Z | [
"python",
"django"
] |
Spotipy - list index out of range | 39,688,358 | <p>Writing a Spotipy script to return album tracks from a given album I'm occasionally getting the error: </p>
<pre><code> album_id = results["albums"]["items"][0]["uri"]
IndexError: list index out of range
</code></pre>
<p>The error tends to happen for more popular artists looping over all of their albums. I'm gu... | 4 | 2016-09-25T15:05:04Z | 39,688,379 | <p><code>results["albums"]["items"]</code> is simply an empty list, so there is no element at index <code>0</code>. You could test for that before trying to index into it:</p>
<pre><code>if not results["albums"]["items"]:
# no albums found, so no tracks either
return []
album_id = results["albums"]["items"][0... | 4 | 2016-09-25T15:06:38Z | [
"python",
"list",
"python-2.7",
"spotipy"
] |
Marking certain days in date indexed pandas dataframes | 39,688,434 | <p>I've got a dataframe which is date indexed (d-m-y). I wanted to create a binary feature column which denotes if a date is the second Saturday of the month.<br>
What I've got so far is this: </p>
<pre><code>def get_second_true(x):
second = None
for index, is_true in enumerate(x):
if is_true and seco... | 1 | 2016-09-25T15:12:21Z | 39,688,532 | <p>The day is second Saturday of the month if weekday == 6 and day of the moth > 7 and day of the month <= 14</p>
| 2 | 2016-09-25T15:22:41Z | [
"python",
"pandas",
"dataframe"
] |
Marking certain days in date indexed pandas dataframes | 39,688,434 | <p>I've got a dataframe which is date indexed (d-m-y). I wanted to create a binary feature column which denotes if a date is the second Saturday of the month.<br>
What I've got so far is this: </p>
<pre><code>def get_second_true(x):
second = None
for index, is_true in enumerate(x):
if is_true and seco... | 1 | 2016-09-25T15:12:21Z | 39,688,666 | <p>There is a special frequency in pandas like <code>WOM-2SUN</code> (Week-Of-Month: 2nd Sunday), so you can do it this way:</p>
<pre><code>In [88]: df = pd.DataFrame({'date':pd.date_range('2000-01-01', periods=365)})
In [89]: df
Out[89]:
date
0 2000-01-01
1 2000-01-02
2 2000-01-03
3 2000-01-04
4 ... | 3 | 2016-09-25T15:37:02Z | [
"python",
"pandas",
"dataframe"
] |
How to get class name of the WebElement in Python Selenium? | 39,688,512 | <p>I use Selenium webdriver to scrap a table taken from web page, written in JavaScript.
I am iterating on a list of table rows. Each row may be of different class. I want to get the name of this class, so that I can choose appropriate action for each row.</p>
<pre><code>table_body=table.find_element_by_tag_name('tbod... | 0 | 2016-09-25T15:20:19Z | 39,688,529 | <p><a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.get_attribute" rel="nofollow"><code>.get_attribute()</code> method</a> is what you are looking for:</p>
<pre><code>row.get_attribute("class")
</code></pre>
| 2 | 2016-09-25T15:22:31Z | [
"python",
"selenium-webdriver"
] |
How to Webscrape data from a classic asp website using python. I am having trouble getting the result after submitting the POST form | 39,688,562 | <p>I am beginner in Web scraping and I have become very much interested in the process.
I set for myself a Project that can keep me motivated till I completed the project.</p>
<h1>My Project</h1>
<p>My Aim is to write a Python Program that goes to my university results page(which happens to be a " xx.asp") and enters... | 1 | 2016-09-25T15:26:44Z | 39,692,270 | <p>You are way over complicating it and you have <em>carriage returns</em> in your post data so that could never work:</p>
<pre><code>In [1]: s = "BTHEE~\BTHEE\result.mdb"
In [2]: print(s) # where did "\result.mdb" go?
esult.mdbHEE
In [3]: s = r"BTHEE~\BTHEE\result.mdb" # raw string
In [4]: print(s)
BTHEE~\BTHEE\re... | 1 | 2016-09-25T22:03:17Z | [
"python",
"html",
"forms",
"web",
"web-scraping"
] |
How to Webscrape data from a classic asp website using python. I am having trouble getting the result after submitting the POST form | 39,688,562 | <p>I am beginner in Web scraping and I have become very much interested in the process.
I set for myself a Project that can keep me motivated till I completed the project.</p>
<h1>My Project</h1>
<p>My Aim is to write a Python Program that goes to my university results page(which happens to be a " xx.asp") and enters... | 1 | 2016-09-25T15:26:44Z | 39,692,721 | <p>To add to the answer already given, you can use bs4.BeautifulSoup to find the data you need in the result page afterwards.</p>
<pre><code>#!\usr\bin\env python
import requests
from bs4 import BeautifulSoup
payload = {'txtregno': '15te1218',
'cmbdegree': r'BTHEE~\BTHEE\result.mdb',
'cmbexamno': 'B',
'... | -1 | 2016-09-25T23:16:40Z | [
"python",
"html",
"forms",
"web",
"web-scraping"
] |
python - How to avoid multiple running instances of the same function | 39,688,594 | <p>In my python script I have a <code>core dumped</code>, and I think it's because the same function is called twice at the same time.</p>
<p>The function is the reading of a Vte terminal in a gtk window</p>
<pre><code>def term(self, dPluzz, donnees=None):
text = str(self.v.get_text(lambda *a: True).rstrip())
... | 0 | 2016-09-25T15:29:07Z | 39,688,880 | <p>The double execution must be the consequence of the <code>contents-changed</code> event triggering twice.</p>
<p>You could just check in your <code>term</code> function whether it has already been executed before, and exit if so.</p>
<p>Add these two lines at the start of the <code>term</code> function:</p>
<pre>... | 1 | 2016-09-25T15:57:16Z | [
"python",
"function"
] |
Python: heapq.heappop() gives strange result | 39,688,599 | <p>I'm trying to use the Python module <code>heapq</code> in my program but I ran into a strange problem using <code>heapq.heappop()</code>. The function does not appear to return the smallest element in the heap. Take a look at the following code:</p>
<pre><code>Python 2.7.12 (default, Jul 1 2016, 15:12:24)
[GCC 5.... | 1 | 2016-09-25T15:29:43Z | 39,688,627 | <p>You should <a href="https://docs.python.org/2/library/heapq.html#heapq.heapify" rel="nofollow">"heapify"</a> the list first (an in-place operation):</p>
<pre><code>In [1]: import heapq
In [2]: l = [[1326, 'a'], [654, 'b']]
In [3]: heapq.heapify(l)
In [4]: heapq.heappop(l)
Out[4]: [654, 'b']
In [5]: heapq.heappo... | 1 | 2016-09-25T15:33:09Z | [
"python",
"heap",
"result",
"pop"
] |
Django: import Topic Issue, word Topic shows instead of title? | 39,688,618 | <p>Hey guys I just began working through the Django section in the Python Crash Course. I'm making a learning log in which you can add entries. I followed the book but I'm having one odd issue. When I add a new topic instead of the title for a new topic I literally get the word Topic</p>
<p><a href="http://i.stack.img... | 0 | 2016-09-25T15:32:28Z | 39,688,718 | <p>You need two underscores for the str method, not one:</p>
<pre><code># No
def _str_(self):
pass
# Yes
def __str__(self):
pass
</code></pre>
| 2 | 2016-09-25T15:42:01Z | [
"python",
"django",
"django-models"
] |
How to perform tensor production in Python/numpy? | 39,688,774 | <p>I have two numpy 2D-arrays and I want to perform this:</p>
<pre><code>a_ij * b_ik = c_ijk
</code></pre>
<p>How can I make it with numpy?</p>
| 1 | 2016-09-25T15:46:50Z | 39,688,953 | <p>c_ijk = numpy.tensordot(a_ij,b_ik, axes=0)</p>
| -1 | 2016-09-25T16:04:41Z | [
"python",
"numpy"
] |
How to perform tensor production in Python/numpy? | 39,688,774 | <p>I have two numpy 2D-arrays and I want to perform this:</p>
<pre><code>a_ij * b_ik = c_ijk
</code></pre>
<p>How can I make it with numpy?</p>
| 1 | 2016-09-25T15:46:50Z | 39,688,962 | <p><code>einsum</code> is tailor made for this task</p>
<pre><code>a_ij * b_ik = c_ijk
c = np.einsum('ij,ik->ijk', a, b)
</code></pre>
<p>===================</p>
<p>But as Divakar shows, no summation is implied, so plain multiplication works just as well, <code>a[...,None]*b[:,None,:]</code>.</p>
| 4 | 2016-09-25T16:05:35Z | [
"python",
"numpy"
] |
How to take input from stdin, display something using curses and output to stdout? | 39,688,790 | <p>I'm trying to make a python script that takes input from stdin, displays GUI in terminal using curses and then when user finishes interaction outputs the result to the stdout. Good example of this behaviour is <a href="https://github.com/garybernhardt/selecta" rel="nofollow">selecta</a> but it's written in ruby.</p>... | 1 | 2016-09-25T15:48:53Z | 40,069,233 | <p>It doesn't work because the <code>print</code> statement is writing to the same standard output as <a href="https://docs.python.org/2/library/curses.html#curses.wrapper" rel="nofollow"><code>curses.wrapper</code></a>. You can either defer that <code>print</code> until after you have restored <code>sys.stdout</code>... | 1 | 2016-10-16T10:24:28Z | [
"python",
"curses",
"python-curses"
] |
Django REST Framework Serializer returning object instead of data | 39,688,876 | <p>I am writing a simple database for the condo I live in which has a list of people, units, unit type (home vs parking space), and unitholder (join table for many-to-many relationship between a person and a unit) - one person can be the owner of a unit type of "home" while renting a parking space.</p>
<p>This is my m... | 1 | 2016-09-25T15:57:01Z | 39,689,102 | <p>Perhaps you must doing somethings so:</p>
<pre><code>class UnitHolderViewSet(viewsets.ModelViewSet):
queryset = UnitHolder.objects.all()
unitholders = UnitHolderSerializer(read_only=True, many=True)
</code></pre>
<p><a href="http://stackoverflow.com/questions/33182092/django-rest-framework-serializing-many... | 0 | 2016-09-25T16:21:07Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
Django REST Framework Serializer returning object instead of data | 39,688,876 | <p>I am writing a simple database for the condo I live in which has a list of people, units, unit type (home vs parking space), and unitholder (join table for many-to-many relationship between a person and a unit) - one person can be the owner of a unit type of "home" while renting a parking space.</p>
<p>This is my m... | 1 | 2016-09-25T15:57:01Z | 39,689,779 | <p>An easy solution would be using <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization" rel="nofollow"><code>depth</code></a> option:</p>
<pre><code>class UnitSerializer(serializers.ModelSerializer):
unit_type = serializers.SlugRelatedField(
queryset=UnitTyp... | 2 | 2016-09-25T17:32:21Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
Python - tf-idf predict a new document similarity | 39,688,927 | <p>Inspired by <strong><a href="http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity">this</a></strong> answer, I'm trying to find cosine similarity between a trained trained tf-idf vectorizer and a new document, and return the similar documents.</p>
<p>The code below finds the ... | 3 | 2016-09-25T16:02:15Z | 39,689,190 | <p>For huge data sets, there is a solution called <strong>Text Clustering By Concept</strong>. search engines use this Technic,</p>
<p>At first step, you cluster your documents to some groups(e.g 50 cluster), then each cluster has a representative document(that contain some words that have some useful information abo... | 0 | 2016-09-25T16:29:57Z | [
"python",
"machine-learning",
"scikit-learn",
"tf-idf",
"document-classification"
] |
Python - tf-idf predict a new document similarity | 39,688,927 | <p>Inspired by <strong><a href="http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity">this</a></strong> answer, I'm trying to find cosine similarity between a trained trained tf-idf vectorizer and a new document, and return the similar documents.</p>
<p>The code below finds the ... | 3 | 2016-09-25T16:02:15Z | 39,698,351 | <p>You should take a look at <a href="https://radimrehurek.com/gensim/tutorial.html" rel="nofollow">gensim</a>. Example starting code looks like this:</p>
<pre><code>from gensim import corpora, models, similarities
dictionary = corpora.Dictionary(line.lower().split() for line in open('corpus.txt'))
corpus = [dictiona... | 1 | 2016-09-26T08:48:00Z | [
"python",
"machine-learning",
"scikit-learn",
"tf-idf",
"document-classification"
] |
Python - tf-idf predict a new document similarity | 39,688,927 | <p>Inspired by <strong><a href="http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity">this</a></strong> answer, I'm trying to find cosine similarity between a trained trained tf-idf vectorizer and a new document, and return the similar documents.</p>
<p>The code below finds the ... | 3 | 2016-09-25T16:02:15Z | 39,700,863 | <p>This problem can be partially addressed by combining the <strong>vector space model</strong> (which is the tf-idf & cosine similarity) together with the <strong>boolean model</strong>. These are concepts of information theory and they are used (and nicely explained) in <a href="https://www.elastic.co/guide/en/el... | 2 | 2016-09-26T10:49:39Z | [
"python",
"machine-learning",
"scikit-learn",
"tf-idf",
"document-classification"
] |
Set bias in CNN | 39,688,985 | <p>I have two massive numpy arrays of weights and biases for a CNN. I can set weights for each layer (using <code>set_weights</code>) but I don't see a way to set the bias for each layer. How do I do this?</p>
| 2 | 2016-09-25T16:08:13Z | 39,691,438 | <p>You do this by using <code>layer.set_weights(weights)</code>. From the documentation:</p>
<blockquote>
<pre><code>weights: a list of Numpy arrays. The number
of arrays and their shape must match
number of the dimensions of the weights
of the layer (i.e. it should match the
output... | 0 | 2016-09-25T20:20:12Z | [
"python",
"deep-learning",
"keras"
] |
How can i take the output of one python script as user input for another python script | 39,689,012 | <p>i have written a code (python 2.7) that goes to a website <a href="http://www.cricbuzz.com/live-cricket-scorecard/16822/ind-vs-nz-1st-test-new-zealand-tour-of-india-2016" rel="nofollow">Cricket score</a> and then takes out some data out of it to display just its score .It also periodically repeats and keeps running ... | 1 | 2016-09-25T16:10:13Z | 39,689,306 | <p>If you want to call a completly independed python script in via your python script take a look at <code>subprocess</code> module. You could use <code>subprocess.call</code> or <code>subprocess.Popen</code>.</p>
| 0 | 2016-09-25T16:43:06Z | [
"python",
"python-2.7",
"windows-10"
] |
How can i take the output of one python script as user input for another python script | 39,689,012 | <p>i have written a code (python 2.7) that goes to a website <a href="http://www.cricbuzz.com/live-cricket-scorecard/16822/ind-vs-nz-1st-test-new-zealand-tour-of-india-2016" rel="nofollow">Cricket score</a> and then takes out some data out of it to display just its score .It also periodically repeats and keeps running ... | 1 | 2016-09-25T16:10:13Z | 39,689,391 | <p>It is hard to answer without having a look at your code. But it seems that using piping with subprocess would be an appropriate solution. </p>
<p>See the answer on this post: <a href="http://stackoverflow.com/questions/32812157/python-subprocess-stdout-readline-doesnt/32812754#32812754">python subprocess.stdout.rea... | 0 | 2016-09-25T16:51:26Z | [
"python",
"python-2.7",
"windows-10"
] |
Tkinter: Only allow one Toplevel window instance | 39,689,046 | <p>I have a tkinter program with multiple windows. Here is the full code in case it's entirety is needed.</p>
<pre><code>import tkinter as tk
import tkinter.scrolledtext as tkst
from tkinter import ttk
import logging
import time
def popupmsg(msg):
popup = tk.Toplevel()
popup.wm_title("!")
label = ttk.Lab... | 1 | 2016-09-25T16:14:44Z | 39,689,243 | <p><code>tkinter</code>'s <code>grab_set()</code> is exactly made for that.</p>
<p>Change the code section below into:</p>
<pre><code>class Settings(tk.Toplevel):
def __init__(self, master=None):
tk.Toplevel.__init__(self, master)
self.wm_title("Settings")
# added grab_set()
self.... | 1 | 2016-09-25T16:36:05Z | [
"python",
"tkinter"
] |
Can someone explain this expression: a[len(a):] = [x] equivalent to list.append(x) | 39,689,099 | <p>I'm at the very beginning of learning Python 3. Getting to know the language basics. There is a method to the list data type:</p>
<pre><code>list.append(x)
</code></pre>
<p>and in the tutorial it is said to be equivalent to this expression:</p>
<pre><code>a[len(a):] = [x]
</code></pre>
<p>Can someone please expl... | 2 | 2016-09-25T16:20:52Z | 39,689,182 | <p>Think back to how slices work: <code>a[beginning:end]</code>.
If you do not supply one of them, then you get all the list from <code>beginning</code> or all the way to <code>end</code>.</p>
<p>What that means is if I ask for <code>a[2:]</code>, I will get the list from the index <code>2</code> all the way to the en... | 9 | 2016-09-25T16:28:57Z | [
"python",
"list",
"python-3.x"
] |
Can someone explain this expression: a[len(a):] = [x] equivalent to list.append(x) | 39,689,099 | <p>I'm at the very beginning of learning Python 3. Getting to know the language basics. There is a method to the list data type:</p>
<pre><code>list.append(x)
</code></pre>
<p>and in the tutorial it is said to be equivalent to this expression:</p>
<pre><code>a[len(a):] = [x]
</code></pre>
<p>Can someone please expl... | 2 | 2016-09-25T16:20:52Z | 39,689,210 | <p>One could generally state that <code>l[len(l):] = [1]</code> is similar to <code>append</code>, <em><a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">and that is what is stated in the docs</a></em>, but, that is a <em>special case</em> that holds true only when the right hand side <em>h... | 5 | 2016-09-25T16:32:12Z | [
"python",
"list",
"python-3.x"
] |
python: using output from method's class inside another class | 39,689,134 | <p>I am trying to develop my first app with PyQt5 (a memory game).</p>
<p>I have created two classes: <strong>MainApplication</strong>, which inherits from QMainWindow, and <strong>GridWidget</strong>, which inherits from QWidget. My aim is to let the user specify a folder with some images (jpg) using the fileMenu of ... | 0 | 2016-09-25T16:24:41Z | 39,689,457 | <p>I think it will be simpler if you keep everything in one class. You should make each child widget an attribute of the class, so you can access them later using <code>self</code> within the methods of the class. All the program logic will go in the methods - so it's just a matter of calling methods in response to sig... | 1 | 2016-09-25T16:57:58Z | [
"python",
"python-3.x",
"oop",
"pyqt",
"pyqt5"
] |
How to check for multiple values in dict in Python | 39,689,143 | <pre><code>dict1 = {'galaxy': 5, 'apple': 6, 'nokia': 5}
</code></pre>
<p>Is there is a way to show the keys in a dict with the same values in a dict?</p>
<pre><code>target_value = 5
new_dict = {}
for key, value in dict1:
if value == target_value:
new_dict[key] = value
</code></pre>
<p>desired output:</... | -2 | 2016-09-25T16:25:13Z | 39,689,217 | <p>If I understand you correctly, you're looking for something like that:</p>
<pre><code>>>> d = {'galaxy': 5, 'apple': 6, 'nokia': 5}
>>> { k:v for k,v in d.items() if v==5 }
{'nokia': 5, 'galaxy': 5}
</code></pre>
| 2 | 2016-09-25T16:33:00Z | [
"python",
"dictionary"
] |
Update a null values in countryside column in a data frame with reference to valid countrycode column from another data frame using python | 39,689,145 | <p>I have two data frames: Disaster, CountryInfo
Disaster has a column country code which has some null values
for example:
Disaster:</p>
<pre><code> 1.**Country** - **Country_code**
2.India - Null
3.Afghanistan - AFD
4.India - IND
5.United States - Null
</code></pre>
<p>CountryInfo:... | 0 | 2016-09-25T16:25:18Z | 39,690,406 | <p>You can simply use <code>map</code> with a <code>Series</code>. </p>
<p>With this approach all values are overwritten not only non <code>NaN</code>.</p>
<pre><code># Test data
disaster = pd.DataFrame({'Country': ['India', 'Afghanistan', 'India', 'United States'],
'Country_code': [np.na... | 0 | 2016-09-25T18:35:54Z | [
"python",
"python-2.7",
"pandas"
] |
Python 'Object has no attribute' | 39,689,268 | <p>Code gives the following error:</p>
<p>"'module' Object has no attribute 'checkNone'"</p>
<p>Dir setup:</p>
<pre><code>+main.py
Sorcery
+Check.py
</code></pre>
<p>main.py</p>
<pre><code>from Sorcery import Check
check = Check.checkNone(None);
</code></pre>
<p>Check.py</p>
<pre><code>class Check:
d... | -3 | 2016-09-25T16:38:06Z | 39,691,440 | <p>First, rename the <code>Check.py</code> to anything you like, e.g.,<code>jacs.py</code>. Inside <code>jacs.py</code>, change <code>Class Check: def checkNone(content):</code> to <code>Class Check(object): def checkNone(self, content):</code>.<br>
Then, in <code>main.py</code>, begin with </p>
<pre><code>from Sor... | 1 | 2016-09-25T20:20:21Z | [
"python",
"object",
"module"
] |
How to clear a cached query? | 39,689,315 | <p>I'm using the following method to cache the result of a SQL query:</p>
<pre><code>db(my_query).select(cache=(cache.ram, 3600), cacheable=True)
</code></pre>
<p>In some cases I want to clear this cache before it expires, which could be done by using <code>cache.ram.clear(key)</code> but I actually don't know the ke... | 1 | 2016-09-25T16:44:06Z | 39,689,987 | <p>The cache key is a bit complicated to replicate (it is the MD5 hash of the database URI plus the SQL generated for the query). As an alternative, since you have <code>cacheable=True</code>, you can call <code>cache.ram</code> directly with your own key:</p>
<pre><code>rows = cache.ram('my_query', lambda: db(my_quer... | 2 | 2016-09-25T17:56:55Z | [
"python",
"python-2.7",
"web2py",
"pydal"
] |
Anaconda install Matlab Engine on Linux | 39,689,320 | <p>I'm trying to install <code>Matlab Engine for Python</code> on CentOS 7 for Matlab R2016a using anaconda python 3.4.</p>
<p>I executed the following commands:</p>
<pre><code>source activate py34 # Default is python 3.5
python setup.py install
</code></pre>
<p>The output is:</p>
<pre><code>running install
running... | 1 | 2016-09-25T16:44:30Z | 39,759,581 | <p>After so many tortures I finally solved this in a simple way. Instead of configure system to use anaconda's python by modifying .bash_profile, you can add an alternative to python command:</p>
<pre><code> sudo update-alternatives --install /usr/bin/python python ~/anaconda3/envs/py34/bin/python 2
update-alternat... | 1 | 2016-09-29T00:30:57Z | [
"python",
"matlab",
"anaconda"
] |
Python function/argument 'not defined' error | 39,689,329 | <p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br>
Thanks in advance. </p>
<pre><code>hourly_pay_rate = 7.50
commission_rate = 0.05
withholding_rate = 0.25
def startup_message():
print('''Thi... | -2 | 2016-09-25T16:45:44Z | 39,689,353 | <p>Your <code>display_result</code> is unindented. Correct the indentation and it should work</p>
<pre><code>def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_w... | 1 | 2016-09-25T16:47:47Z | [
"python",
"undefined"
] |
Python function/argument 'not defined' error | 39,689,329 | <p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br>
Thanks in advance. </p>
<pre><code>hourly_pay_rate = 7.50
commission_rate = 0.05
withholding_rate = 0.25
def startup_message():
print('''Thi... | -2 | 2016-09-25T16:45:44Z | 39,689,373 | <p>First, to call <code>display_results</code>, you need to provide an empty set of parentheses:</p>
<pre><code>display_results()
</code></pre>
<p>It appears you have an indentation error as well, as it seems you intended to call <code>display_results()</code> from <em>inside</em> the call to <code>main</code>:</p>
... | 2 | 2016-09-25T16:49:13Z | [
"python",
"undefined"
] |
Python function/argument 'not defined' error | 39,689,329 | <p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br>
Thanks in advance. </p>
<pre><code>hourly_pay_rate = 7.50
commission_rate = 0.05
withholding_rate = 0.25
def startup_message():
print('''Thi... | -2 | 2016-09-25T16:45:44Z | 39,689,378 | <p>Indent and execute <code>()</code> the function.</p>
<pre><code>def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amo... | 1 | 2016-09-25T16:50:13Z | [
"python",
"undefined"
] |
Python function/argument 'not defined' error | 39,689,329 | <p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br>
Thanks in advance. </p>
<pre><code>hourly_pay_rate = 7.50
commission_rate = 0.05
withholding_rate = 0.25
def startup_message():
print('''Thi... | -2 | 2016-09-25T16:45:44Z | 39,689,686 | <p>Look at this very short program:</p>
<pre><code>def main():
r = 2 + 2
show_result
def show_result():
print("The result of 2+2 is {}", format(r))
main()
</code></pre>
<p><strong>This program will not work!!</strong> However, if you can fix all the bugs in this program you will have understood how to fix ... | 0 | 2016-09-25T17:23:01Z | [
"python",
"undefined"
] |
Plotting bar plot in Seaborn Python with rotated xlabels | 39,689,352 | <p>How can I plot a simple bar graph in Seaborn without any statistics? The data set is simply names and values.</p>
<pre><code>import pandas
df = pandas.DataFrame({"name": ["Bob Johnson", "Mary Cramer", "Joe Ellis"], "vals": [1,2,3]})
</code></pre>
<p>I would like to plot this as a bar graph with xlabels pulled from... | -1 | 2016-09-25T16:47:46Z | 39,689,464 | <p>You mean like that (<strong>set_xticklabels</strong> approach):</p>
<pre><code>import pandas
df = pandas.DataFrame({"name": ["Bob Johnson", "Mary Cramer", "Joe Ellis"], "vals": [1,2,3]})
g = sns.barplot(x='name', y='vals', data=df)
g.set_xticklabels(g.get_xticklabels(), rotation=45)
</code></pre>
<hr>
<p>Or prob... | 1 | 2016-09-25T16:58:32Z | [
"python",
"matplotlib",
"bar-chart",
"seaborn"
] |
How to add characters to a variable/integer name - Python | 39,689,407 | <p>There might be a question like this but I can't find it.
I want to be to add the name of a variable/integer. e.g.</p>
<pre><code>num = 5
chr(0x2075)
</code></pre>
<p>Now the 2nd line would return 5 in superscript but I want to put the word num into the Unicode instead so something like <code>chr(0x207+num)</code> ... | -2 | 2016-09-25T16:52:36Z | 39,689,833 | <pre><code>chr(0x2070 + num)
</code></pre>
<p>As given in the comment, if you want to get the character at U+207x, this is correct. </p>
<p>But this is <strong><em>not</em></strong> the proper way to find the superscript of a number, because U+2071 is <code>â±</code> (superscript "i") while U+2072 and U+2073 are not... | 1 | 2016-09-25T17:38:34Z | [
"python",
"variables",
"unicode"
] |
How to access Local variables of functions when the function call has finished in python? | 39,689,434 | <p>I found on the net that local variables of functions can't be accessed from outside when the function call has finished.I try to execute the program but it throws an error that variable is not defined. My code is</p>
<pre><code>xyz=list()
n=0
def length(g):
i=0
n=g
v=input("no of")
while i<v:
... | -1 | 2016-09-25T16:55:47Z | 39,689,541 | <p>I guess this is what you would want to do</p>
<pre><code>xyz=list()
n=0
def length(g):
i=0
n=g
v=input("no of")
global xyz
while i<v:
c=input("Enter the 1st dimension:")
j=input("Enter the 2nd dimension:")
i=i+1
xyz.append(c)
xyz.append(j)
retur... | 0 | 2016-09-25T17:06:20Z | [
"python",
"function",
"global-variables",
"local-variables"
] |
Applying condition and update on same column | 39,689,504 | <p>I have written the following statement to update a column in DataFrame (df)</p>
<pre><code> score
0 6800
1 7200
2 580
3 6730
</code></pre>
<p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p>
<p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is... | 1 | 2016-09-25T17:03:13Z | 39,689,615 | <p>The value for index 2 will not satisfy your filter condition (i.e. <code>> 999</code>) and will yield a <code>NaN</code>, as per the <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#series" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>Note: <code>NaN</code> (not a number) is the stand... | -1 | 2016-09-25T17:13:36Z | [
"python",
"pandas"
] |
Applying condition and update on same column | 39,689,504 | <p>I have written the following statement to update a column in DataFrame (df)</p>
<pre><code> score
0 6800
1 7200
2 580
3 6730
</code></pre>
<p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p>
<p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is... | 1 | 2016-09-25T17:03:13Z | 39,689,659 | <p>Use the <code>other</code> argument to the method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow"><code>where</code></a>:</p>
<pre><code>(df["score"]/10).where(df["score"] > 999, other=df["score"])
0 680.0
1 720.0
2 580.0
3 673.0
</code></pre... | 1 | 2016-09-25T17:19:19Z | [
"python",
"pandas"
] |
Applying condition and update on same column | 39,689,504 | <p>I have written the following statement to update a column in DataFrame (df)</p>
<pre><code> score
0 6800
1 7200
2 580
3 6730
</code></pre>
<p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p>
<p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is... | 1 | 2016-09-25T17:03:13Z | 39,690,749 | <p>The following worked for me</p>
<p>df["score"] = np.where(df["score"] > 999, df["score"]/10, df["score"]).astype(int)</p>
| 0 | 2016-09-25T19:10:00Z | [
"python",
"pandas"
] |
Applying condition and update on same column | 39,689,504 | <p>I have written the following statement to update a column in DataFrame (df)</p>
<pre><code> score
0 6800
1 7200
2 580
3 6730
</code></pre>
<p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p>
<p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is... | 1 | 2016-09-25T17:03:13Z | 39,691,661 | <h2>Solution</h2>
<p>Do as in <code>numpy</code>, and use <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">masks</a>:</p>
<pre><code>df['score'][df['score']>999] /= 10
</code></pre>
<p>For legibility you could do:</p>
<pre><code>f = df['score']
f[f&g... | 3 | 2016-09-25T20:44:47Z | [
"python",
"pandas"
] |
From perl to python | 39,689,510 | <p>I've got some code that I've translated from perl into python, but I am having a time trying to figure out this last part. </p>
<pre><code>my $bashcode=<<'__bash__';
. /opt/qip/etc/qiprc;
. /opt/sybase/sybase.sh
perl -mdata::dumper -e 'print dumper \%env';
__bash__
my $var1;
eval qx(bash -c "$bashcode");
</co... | 0 | 2016-09-25T17:03:45Z | 39,689,580 | <p>Your program is generating a script and running it.</p>
<p>A first python approximation is:</p>
<pre><code>import os
script=""". /opt/qip/etc/qiprc;
. /opt/sybase/sybase.sh
perl -mdata::dumper -e 'print dumper \%env';
"""
os.system(script)
</code></pre>
<p>As you can see, perl is still being u... | 1 | 2016-09-25T17:11:13Z | [
"python",
"perl"
] |
From perl to python | 39,689,510 | <p>I've got some code that I've translated from perl into python, but I am having a time trying to figure out this last part. </p>
<pre><code>my $bashcode=<<'__bash__';
. /opt/qip/etc/qiprc;
. /opt/sybase/sybase.sh
perl -mdata::dumper -e 'print dumper \%env';
__bash__
my $var1;
eval qx(bash -c "$bashcode");
</co... | 0 | 2016-09-25T17:03:45Z | 39,689,599 | <p>This part:</p>
<pre><code>my $bashcode=<<'__bash__';
. /opt/qip/etc/qiprc;
. /opt/sybase/sybase.sh
perl -mdata::dumper -e 'print dumper \%env';
__bash__
</code></pre>
<p>Is a here doc and you would do this in Python:</p>
<pre><code>bashcode="""\
. /opt/qip/etc/qiprc;
. /opt/sybase/sybase.sh
perl -mdata::dum... | 0 | 2016-09-25T17:12:43Z | [
"python",
"perl"
] |
Simple image rotation with Python and DOM using RapydScript | 39,689,555 | <p>I have this code write in Python and works fine with Brython.
This code rotate image in this case a cog.
How Can I change it, and what change to work with RapydScript? I am new at programming so please have patience :D</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- load Brython -->
<... | 2 | 2016-09-25T17:07:28Z | 39,690,411 | <p>I'm not too familiar with Brython, but right away I can tell you that to port it to RapydScript you simply need to drop most of the unnecessary abstractions that I see the code importing, since RapydScript is closer to native JavaScript. As far as having the RapydScript code in the browser, you have a couple options... | 2 | 2016-09-25T18:36:30Z | [
"python",
"rapydscript"
] |
Why do I get a 'list index out of range' error for the below code using a for loop: | 39,689,662 | <p>Problem Statement: Given a nested list nl consisting of a set of integers, write a python script to find the sum of alternate elements of the sub-lists.</p>
<pre><code>nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
sum = 0
n = 0
j=[]
for ele in nl:
for i in ele:
j.append(i)
for a in j:
... | -2 | 2016-09-25T17:19:46Z | 39,689,836 | <p>Your outer loops look like this:</p>
<pre><code>for ele in nl:
for i in ele:
j.append(i)
# inner loop.
</code></pre>
<p>The first time the inner loop is reached, only one element has been appended to the list <code>j</code>. The second time the inner loop is reached, two elements have been appe... | 0 | 2016-09-25T17:38:44Z | [
"python",
"python-3.x"
] |
Why do I get a 'list index out of range' error for the below code using a for loop: | 39,689,662 | <p>Problem Statement: Given a nested list nl consisting of a set of integers, write a python script to find the sum of alternate elements of the sub-lists.</p>
<pre><code>nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
sum = 0
n = 0
j=[]
for ele in nl:
for i in ele:
j.append(i)
for a in j:
... | -2 | 2016-09-25T17:19:46Z | 39,689,847 | <p>This is how it's usually done in Python:</p>
<pre><code>nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
total = sum(number for sublist in nl for number in sublist)
</code></pre>
<p>Don't name the variable <code>sum</code> - that would "hide" a built-in function. Exactly the function you need in fact.</p>
<hr>
<p>Any... | 2 | 2016-09-25T17:39:57Z | [
"python",
"python-3.x"
] |
Snake game in pygame: body growth function | 39,689,667 | <p>I am writing the Snake in pygame, but I not have a very clear idea of how to implement the growing functionality of the snake. I made a list ("lista_cobra") containing the head coordinates (which is about 30x30 pixels), and thought about making another list from this, containing the last positions of the head, exclu... | 0 | 2016-09-25T17:20:22Z | 39,691,311 | <p>I couldn't read your source, but I'd give it a try.</p>
<p>The body of the snake consists of the positions in <code>lista_cobra</code>. Let the length of the snake be stored in a variable <code>len_cobra</code>. Now when the head moves on, the new position of the head has to be added at the top of <code>lista_cobra... | 0 | 2016-09-25T20:07:24Z | [
"python",
"python-2.7",
"pygame"
] |
Python make a number loop within a range | 39,689,676 | <p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p>
<p>Is there a way to do this like so:</p>
<p><code>variable = 25</code></p>
<p>If your range is 1-20, can <code>variable</code> become 5?</p>... | -1 | 2016-09-25T17:21:38Z | 39,689,723 | <p>One option would be to set <code>variable = (|variable| % (MAX - MIN + 1)) + MIN</code>. This will give you a number that is between <code>MIN</code> and <code>MAX</code>, inclusively.</p>
<p>Note that this only works consistently if <code>variable</code>, <code>MAX</code> and <code>MIN</code> are non-negative inte... | 0 | 2016-09-25T17:27:16Z | [
"python"
] |
Python make a number loop within a range | 39,689,676 | <p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p>
<p>Is there a way to do this like so:</p>
<p><code>variable = 25</code></p>
<p>If your range is 1-20, can <code>variable</code> become 5?</p>... | -1 | 2016-09-25T17:21:38Z | 39,689,865 | <p>Just figured it out.</p>
<pre><code>def loop(n, minn, maxn):
while n > maxn:
n = n - (maxn - minn)
while n < minn:
n = n + (maxn - minn)
return n
</code></pre>
<p>I think that should work for most cases, including negative numbers and ranges.</p>
| 0 | 2016-09-25T17:43:07Z | [
"python"
] |
Python make a number loop within a range | 39,689,676 | <p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p>
<p>Is there a way to do this like so:</p>
<p><code>variable = 25</code></p>
<p>If your range is 1-20, can <code>variable</code> become 5?</p>... | -1 | 2016-09-25T17:21:38Z | 39,695,430 | <p>Loops can potentially take a long time to run. This happens when <code>maxn</code> and <code>minn</code> are close together and <code>n</code> is far from either.</p>
<p>To flat out calculate it:</p>
<pre><code>def loop(n, maxn, minn):
# maxn must be greater than minn
maxn += 1 # rang... | 0 | 2016-09-26T05:44:32Z | [
"python"
] |
Python serialize HTTPFlow object (MITM) | 39,689,678 | <p>I am using <a href="http://docs.mitmproxy.org/en/stable/introduction.html" rel="nofollow">mitmproxy</a>, a python man-in-the-middle (MITM) proxy for HTTP, to modify on the fly the HTTP request of a certain website.</p>
<p><strong>Goal:</strong></p>
<p>For test purposes, when it receives an HTTP request, it should ... | 0 | 2016-09-25T17:21:57Z | 39,918,745 | <p>Found solution (the HTTPFlow obj has a method to get the state)</p>
<p>Imports</p>
<pre><code>from mitmproxy.models import HTTPFlow
from mitmproxy.models import HTTPResponse
</code></pre>
<p>Save state:</p>
<pre><code>cached_state = http_flow_response.response.get_state()
</code></pre>
<p>Load state:</p>
<pre>... | 0 | 2016-10-07T13:42:43Z | [
"python",
"serialization",
"ipc",
"mitmproxy"
] |
Python While Loops Asterisk | 39,689,746 | <p>Re-type and run, note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks.</p>
<pre><code>while num_printed != num_stars:
print('*')
</code></pre>
<p>Below is the code which I have entered. I am getting an infinite loop hence no answer. Please help me out! Thanks!</p>
<pre>... | -1 | 2016-09-25T17:29:18Z | 39,689,808 | <p>You'll want either:</p>
<pre><code>num_stars = 3
print(num_stars * '*')
</code></pre>
<p>or:</p>
<pre><code>num_stars = 3
num_printed = 0
while(num_printed < num_stars):
print('*')
num_printed += 1
</code></pre>
<p>Depending on what you're trying to do.</p>
| 1 | 2016-09-25T17:36:04Z | [
"python",
"loops",
"while-loop"
] |
Install mac : 1 error generated (error: '_GStaticAssertCompileTimeAssertion_0' declared as an array) | 39,689,752 | <p>I'm trying to install kivy on mac OSX 10.11.2 for a couple of hours now.
What I did (as explained here: <a href="https://kivy.org/docs/installation/installation-osx.html" rel="nofollow">https://kivy.org/docs/installation/installation-osx.html</a>):</p>
<pre><code>$ brew install sdl2 sdl2_image sdl2_ttf sdl2_mixer g... | 0 | 2016-09-25T17:29:35Z | 39,957,871 | <p>I had the same problem trying to install with CLI. It appears kivy installation with .app file worked. Follow this guide:</p>
<ul>
<li><a href="https://kivy.org/docs/installation/installation-osx.html" rel="nofollow">https://kivy.org/docs/installation/installation-osx.html</a></li>
</ul>
<p>then you should be able... | 0 | 2016-10-10T12:04:11Z | [
"python",
"osx",
"install",
"kivy"
] |
Implement ASN1 structure properly using pyasn1 | 39,689,890 | <p>I am new to ASN1 and want to implement this structure using pyasn1</p>
<pre><code> ECPrivateKey ::= SEQUENCE {
version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
privateKey OCTET STRING,
parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
publicKey [1] BIT STRING OPTIONAL
}
</cod... | 0 | 2016-09-25T17:46:31Z | 39,945,199 | <p>I guess in the ASN.1 module you are working with, EXPLICIT tagging mode is the default. So in your pyasn1 code you should use explicit tagging as well. </p>
<p>Here's slightly fixed code that should work as you want:</p>
<pre><code>from pyasn1.type import univ, namedtype, tag
from pyasn1.codec.der.encoder import e... | 0 | 2016-10-09T15:22:06Z | [
"python",
"python-3.x",
"pyasn1"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.