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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Using Requests Post to login to this site not working | 38,733,204 | <p>I know there are tons of threads and videos on how to do this, I've gone through them all and am in need of a little advanced guidance.</p>
<p>I am trying to log into this webpage where I have an account so I can send a request to download a report.<br>
First I send the <code>get</code> request to the login page, then send the <code>post</code> request but when I <code>print(resp.content)</code> I get the code back for the login page. I do get a code[200] but I can't get to the index page. No matter what page I try to <code>get</code> after the post it keeps redirecting me back to the login page</p>
<p>Here are a couple things I'm not sure if I did correctly:</p>
<ul>
<li>For the header I just put everything that was listed when I inspected the page</li>
<li>Not sure if I need to do something with the cookies?</li>
</ul>
<p>Below is my code:</p>
<pre><code>import requests
import urllib.parse
url = 'https://myurl.com/login.php'
next_url = 'https://myurl.com/index.php'
username = 'myuser'
password = 'mypw'
headers = {
'Host': 'url.myurl.com',
'Connection': 'keep-alive',
'Content-Length': '127',
'Cache-Control': 'max-age=0',
'Origin': 'https://url.myurl.com',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Referer': 'https://url.myurl.com/login.php?redirect=1',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.8',
'Cookie': 'PHPSESSID=3rgtou3h0tpjfts77kuho4nnm3'
}
login_payload = {
'XXX_login_name': username,
'XXX_login_password': password,
}
login_payload = urllib.parse.urlencode(login_payload)
r = requests.Session()
r.get(url, headers = headers)
r.post(url, headers = headers, data = login_payload)
resp = r.get(next_url, headers = headers)
print(resp.content)
</code></pre>
| 0 | 2016-08-03T02:05:42Z | 38,748,823 | <p>There are a few more fields in the form data to post:</p>
<pre><code>import requests
data = {"redirect": "1",
"XXX_login_name": "your_username",
"XXX_login_password": "your_password",
"XXX_actionSUBMITLOGIN": "Login",
"XXX_login_php": "1"}
with requests.Session() as s:
s.headers.update({"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"})
r1 = s.get("https://eym.sicomasp.com/login.php")
s.headers["cookie"] = r1.headers["Set-Cookie"]
pst = s.post("https://eym.sicomasp.com/login.php", data=data)
print(pst.history)
</code></pre>
<p>You may get redirected to index.php automatically after the post, you can check <code>r1.history</code> and <code>r1.content</code> to see exactly what is happening.</p>
| 1 | 2016-08-03T16:15:08Z | [
"python",
"post",
"login",
"python-requests"
] |
Using Requests Post to login to this site not working | 38,733,204 | <p>I know there are tons of threads and videos on how to do this, I've gone through them all and am in need of a little advanced guidance.</p>
<p>I am trying to log into this webpage where I have an account so I can send a request to download a report.<br>
First I send the <code>get</code> request to the login page, then send the <code>post</code> request but when I <code>print(resp.content)</code> I get the code back for the login page. I do get a code[200] but I can't get to the index page. No matter what page I try to <code>get</code> after the post it keeps redirecting me back to the login page</p>
<p>Here are a couple things I'm not sure if I did correctly:</p>
<ul>
<li>For the header I just put everything that was listed when I inspected the page</li>
<li>Not sure if I need to do something with the cookies?</li>
</ul>
<p>Below is my code:</p>
<pre><code>import requests
import urllib.parse
url = 'https://myurl.com/login.php'
next_url = 'https://myurl.com/index.php'
username = 'myuser'
password = 'mypw'
headers = {
'Host': 'url.myurl.com',
'Connection': 'keep-alive',
'Content-Length': '127',
'Cache-Control': 'max-age=0',
'Origin': 'https://url.myurl.com',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Referer': 'https://url.myurl.com/login.php?redirect=1',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.8',
'Cookie': 'PHPSESSID=3rgtou3h0tpjfts77kuho4nnm3'
}
login_payload = {
'XXX_login_name': username,
'XXX_login_password': password,
}
login_payload = urllib.parse.urlencode(login_payload)
r = requests.Session()
r.get(url, headers = headers)
r.post(url, headers = headers, data = login_payload)
resp = r.get(next_url, headers = headers)
print(resp.content)
</code></pre>
| 0 | 2016-08-03T02:05:42Z | 38,757,422 | <p>So I figured out what my problem was, just in case anyone in the future has the same issue. I am sure different websites have different requirements but in this case the <code>Cookie:</code> I was sending in the request header was blocking it. What I did was grab my cookie in the headers AFTER I logged in. I updated my headers and then I sent the request. This is what ended up working:</p>
<p>(also the form data needs to be encoded in HTML)</p>
<pre><code>import requests
import urllib.parse
headers = {
'Host' : 'eym.sicomasp.com',
'Content-Length' : '62',
'Origin' : 'https://eym.sicomasp.com',
'Upgrade-Insecure-Requests' : '1',
'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'Referer' : 'https://eym.sicomasp.com/login.php?redirect=1',
'Cookie' : 'PHPSESSID=vdn4er761ash4sb765ud7jakl0; SICOMUSER=31+147234553'
} #Additional cookie information after logging in ^^^^
data = {
'XXX_login_name': 'myuser',
'XXX_login_password': 'mypw',
}
data = urllib.parse.urlencode(data)
with requests.Session() as s:
s.headers.update(headers)
resp = s.post('https://eym.sicomasp.com/index.php', data=data2)
print(resp.content)
</code></pre>
| 0 | 2016-08-04T02:11:13Z | [
"python",
"post",
"login",
"python-requests"
] |
Simple table creation sql works for mysql and postgre, but reported errors in oracle | 38,733,212 | <p>I am using Python with cx_Oracle to work with Oracle 11g.</p>
<p>I have following SQL work well with MySQL/PostgreSQL, </p>
<pre><code>stock_info_create = 'CREATE TABLE STOCK_INFO(' + \
'CODE VARCHAR2(255) NOT NULL,' + \
'NAME VARCHAR2(255) NOT NULL,' + \
'TIMETOMARKET VARCHAR2(255),' + \
'PRIMARY KEY (CODE)' + \
');'
</code></pre>
<p>And the returned message was</p>
<pre><code>(cx_Oracle.DatabaseError) ORA-00911: invalid character
[SQL: 'CREATE TABLE STOCK_INFO(CODE VARCHAR2(255) NOT NULL,NAME VARCHAR2(255) NOT NULL,TIMETOMARKET VARCHAR2(255),PRIMARY KEY (CODE));']
</code></pre>
<p>Of course, to use this sql for Oracle I changed VARCHAR to VARCHAR2 since I thought the error was caused by wrong data type. But after changing to VARCHAR2 it still didn't work.</p>
<p>Another problem is with table creation as well.</p>
<pre><code>stock_h_create = 'CREATE TABLE STOCK_H_NONE(' + \
'CODE VARCHAR(16) NOT NULL,' + \
'DATE DATE,' + \
'OPEN FLOAT,' + \
'HIGH FLOAT,' + \
'CLOSE FLOAT,' + \
'LOW FLOAT,' + \
'VOLUME FLOAT,' + \
'AMOUNT FLOAT,' + \
'AUTYPE VARCHAR(16),' + \
'LAST_UPDATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,' + \
'PRIMARY KEY (CODE,AUTYPE,DATE)' + \
');'
</code></pre>
<p>The returned message was</p>
<pre><code>Creating table STOCK_H_NONE... (cx_Oracle.DatabaseError) ORA-00904: : invalid identifier
[SQL: 'CREATE TABLE STOCK_H_NONE(CODE VARCHAR(16) NOT NULL,DATE DATE,OPEN FLOAT,HIGH FLOAT,CLOSE FLOAT,LOW FLOAT,VOLUME FLOAT,AMOUNT FLOAT,AUTYPE VARCHAR(16),LAST_UPDATED TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (CODE,AUTYPE,DATE));']
</code></pre>
<p>I appreciate any kind of help and your visit.</p>
| 0 | 2016-08-03T02:06:25Z | 38,733,290 | <p>Certain reserved words in Oracle are not allowed to be used as column names - data types are among those reserved words, e.g. <code>Date</code>, <code>Number</code>. You got an "ORA-00904: invalid identifier" error because of your <code>Date</code> column. For good practice, try and avoid using reserved words as column names.</p>
| 1 | 2016-08-03T02:15:10Z | [
"python",
"mysql",
"oracle",
"postgresql"
] |
Difference between scikit-learn and sklearn | 38,733,220 | <p>On OS X 10.11.6 and python 2.7.10 I need to import from sklearn manifold.
I have numpy 1.8 Orc1, scipy .13 Ob1 and scikit-learn 0.17.1 installed.<br>
I used pip to install sklearn(0.0), but when I try to import from sklearn manifold I get the following: </p>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in
File
"/Library/Python/2.7/site-packages/sklearn/<strong>init</strong>.py", line 57, in
from .base import clone File
"/Library/Python/2.7/site-packages/sklearn/base.py", line 11, in
from .utils.fixes import signature File
"/Library/Python/2.7/site-packages/sklearn/utils/<strong>init</strong>.py", line
10, in from .murmurhash import murmurhash3_32 File
"numpy.pxd", line 155, in init sklearn.utils.murmurhash
(sklearn/utils/murmurhash.c:5029) ValueError: numpy.dtype has the
wrong size, try recompiling.</p>
</blockquote>
<p>What is the difference between scikit-learn and sklearn? Also,
I cant import scikit-learn because of a syntax error</p>
| 0 | 2016-08-03T02:07:21Z | 38,733,854 | <p>You might need to reinstall numpy. It doesn't seem to have installed correctly.</p>
<p><code>sklearn</code> is how you type the scikit-learn name in python.</p>
<p>Also, try running the standard tests in scikit-learn and check the output. You will have detailed error information there.</p>
<p>Do you have <code>nosetests</code> installed? Try: <code>nosetests -v sklearn</code>. You type this in bash, not in the python interpreter.</p>
| 0 | 2016-08-03T03:25:22Z | [
"python",
"python-2.7",
"scikit-learn"
] |
extract a string between 2 strings in python? | 38,733,221 | <p>I need to one give me the string between <code>~</code> and <code>^</code></p>
<p>i have string like this</p>
<p><code>:::ABC???,:::DEF???</code></p>
<p>I need to get the string between them with python</p>
<p>I want to do all this because i am trying to extract text from an html page. like this example</p>
<pre><code><td class="cell-1">
<div><span class="value-frame">&nbsp;~ABC^,~DEF^</span></div>
</td>
</code></pre>
| 1 | 2016-08-03T02:07:34Z | 38,733,282 | <p>You can use the <code>isalpha()</code> function in a generator expression. Then combine the characters as a single <code>string</code> using <code>join()</code>.</p>
<pre><code>def extract_string(s):
return ''.join(i for i in s if i.isalpha())
</code></pre>
<p><strong>Sample output:</strong></p>
<pre><code>print extract_string(':::ABC???,:::DEF???')
>>> ABCDEF
</code></pre>
<p>However that is only for extracting all characters, if you want to extract only characters between <code>~...^</code>:</p>
<pre><code>import re
def extract_string(s):
match = re.findall(r"~([a-zA-z]*)\^", s)
return match
</code></pre>
<p><strong>Sample output:</strong></p>
<pre><code>s = '&nbsp;~ABC^,~DEF^'
print extract_string(s)
>>> ['ABC', 'DEF']
</code></pre>
<p>Just a side note: if you're parsing <strong>HTML</strong> using <em>regex</em> and/or <em>string manipulation</em>, as the <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">famous S.O. reply</a> suggests, please use a HTML parser; such as the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">Beautiful Soup</a> library instead :D!</p>
| 2 | 2016-08-03T02:14:17Z | [
"python"
] |
extract a string between 2 strings in python? | 38,733,221 | <p>I need to one give me the string between <code>~</code> and <code>^</code></p>
<p>i have string like this</p>
<p><code>:::ABC???,:::DEF???</code></p>
<p>I need to get the string between them with python</p>
<p>I want to do all this because i am trying to extract text from an html page. like this example</p>
<pre><code><td class="cell-1">
<div><span class="value-frame">&nbsp;~ABC^,~DEF^</span></div>
</td>
</code></pre>
| 1 | 2016-08-03T02:07:34Z | 38,733,321 | <p>It seems like you want ABC and DEF , so you need write re like this (.*?) </p>
<pre><code>import re
target = ' <td class="cell-1"><div><span class="value-frame">&nbsp;~ABC^,~DEF^</span></div></td>'
matchObj = re.findall(r'~(.*?)\^', target)
print matchObj
# ['ABC', 'DEF']
</code></pre>
<p>you can learn more about re module</p>
| 1 | 2016-08-03T02:19:23Z | [
"python"
] |
IBM Bluemix set_hadoop_config error | 38,733,247 | <p>Whenever I try the setup procedure for Apache spark data analytics, I get this error.</p>
<p>In</p>
<pre><code>def set_hadoop_config(credentials):
prefix = "fs.swift.service." + credentials['name']
hconf = sc._jsc.hadoopConfiguration()
hconf.set(prefix + ".auth.url", credentials['auth_url']+'/v3/auth/tokens')
hconf.set(prefix + ".auth.endpoint.prefix", "endpoints")
hconf.set(prefix + ".tenant", credentials['project_id'])
hconf.set(prefix + ".username", credentials['user_id'])
hconf.set(prefix + ".password", credentials['password'])
hconf.setInt(prefix + ".http.port", 8080)
hconf.set(prefix + ".region", credentials['region'])
hconf.setBoolean(prefix + ".public", True)
</code></pre>
<p>In</p>
<pre><code>credentials['name'] = 'keystone'
set_hadoop_config(credentials)
</code></pre>
<p>Out</p>
<pre><code>---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-976c35e1d85e> in <module>()
----> 1 credentials['name'] = 'keystone'
2 set_hadoop_config(credentials)
NameError: name 'credentials' is not defined
</code></pre>
<p>Does anyone know how to solve this problem? I am stuck</p>
| 0 | 2016-08-03T02:10:12Z | 38,733,588 | <p>I think you are missing the credentials dictionary i.e you should pass the values for parameters of accessing Object Store service as follows: </p>
<pre><code>credentials =
{
'auth_uri':'',
'global_account_auth_uri':'',
'username':'admin_b055482b7febbd287d9020d65cdd55f5653d0ffb',
'password':"XXXXXX",
'auth_url':'https://identity.open.softlayer.com',
'project':'object_storage_e5e45537_ea14_4d15_b90a_5fdd271ea402',
'project_id':'7d7e5f2a83fe47e586b91f459d47169f',
'region':'dallas',
'user_id':'001c394e06d74b86a76a786615e358e2',
'domain_id':'2df6373c549e49f8973fb6d22ab18c1a',
'domain_name':'639347',
'filename':'2015_SQL.csv',
'container':'notebooks',
'tenantId':'s322-e1e9acad6196b9-a1259eb961e2'
}
</code></pre>
<p>If you are using the notebooks, you can get the above using the "Insert to Code" for the file listed under the data sources panel (right hand side). </p>
<p>To access the file , you will need Swift URI as follows:</p>
<pre><code>raw_data = sc.textFile("swift://" + credentials['container'] + "." + credentials['name'] + "/" + credentials['filename'])
</code></pre>
| 1 | 2016-08-03T02:49:25Z | [
"python",
"hadoop",
"apache-spark",
"ibm-bluemix",
"ibm"
] |
Returning multiple elements of a list | 38,733,287 | <p>Just have a simple question I need to write a function that takes a list as a parameter and returns a new list containing all the elements of the parameter data but with the last item appearing twice.</p>
<p>This is what I have:</p>
<pre><code>def duplicate_last(data):
return data[:], data[-1]
</code></pre>
<p>So duplicate_last([1,2,3]) comes out as ([1, 2, 3], 3) but I need it in the format of [1, 2, 3, 3].</p>
<p>Solution?</p>
<p>Also can't get </p>
<pre><code> return data[:] + data[-1]
</code></pre>
<p>to work as "can only concatenate list (not "int") to list"</p>
| 1 | 2016-08-03T02:14:55Z | 38,733,317 | <p>You want a list.</p>
<p>You have:</p>
<pre><code>def duplicate_last(data):
return data[:], data[-1]
</code></pre>
<p>That creates a tuple with two elements, a copy of the list (<code>data[:]</code>) and the last element of the list.</p>
<p>The error message is telling you exactly what the problem with <code>data[:] + data[-1]</code> is -- you're trying to use a <code>list + list</code> construction but you're doing <code>list + int</code>.</p>
<p>Solutions:</p>
<pre><code>new_list = data[:]
new_list.append(data[-1])
return new_list
</code></pre>
<p>Or fix the <code>TypeError</code> directly:</p>
<pre><code>return data[:] + [data[-1]]
</code></pre>
<p>With the extra brackets it's <code>list + list</code> again.</p>
<p>You can also do this with slicing, which always returns a list:</p>
<pre><code>return data[:] + data[-1:]
</code></pre>
<p>Of the 3, I would probably use the last solution because it seems to me the most readable. Any of the 3 is fine, though.</p>
| 1 | 2016-08-03T02:18:51Z | [
"python",
"python-3.x"
] |
Returning multiple elements of a list | 38,733,287 | <p>Just have a simple question I need to write a function that takes a list as a parameter and returns a new list containing all the elements of the parameter data but with the last item appearing twice.</p>
<p>This is what I have:</p>
<pre><code>def duplicate_last(data):
return data[:], data[-1]
</code></pre>
<p>So duplicate_last([1,2,3]) comes out as ([1, 2, 3], 3) but I need it in the format of [1, 2, 3, 3].</p>
<p>Solution?</p>
<p>Also can't get </p>
<pre><code> return data[:] + data[-1]
</code></pre>
<p>to work as "can only concatenate list (not "int") to list"</p>
| 1 | 2016-08-03T02:14:55Z | 38,733,318 | <p>You could make a slight amendment to your current code:</p>
<pre><code>def duplicate_last(data):
return data[:] + [data[-1]]
</code></pre>
| 3 | 2016-08-03T02:18:56Z | [
"python",
"python-3.x"
] |
Categorical axis with a bokeh area chart | 38,733,308 | <h2>Question</h2>
<p>Is it currently possible to use a categorical axis with a bokeh <code>Area</code> chart?</p>
<h2>Details</h2>
<p>I'm trying to plot an area chart with a categorical x-axis using the high-level <code>bokeh.charts</code> API.</p>
<h2>Example</h2>
<p>If set up bokeh and a dataframe like this:</p>
<pre><code>import numpy
import pandas
from bokeh import charts, plotting, models
plotting.output_notebook()
_, blue, _, green = bokeh.palettes.Paired4
datalist = [
{'month': 'Oct', 'rain': 107., 'snow': 0.0, 'wy_month': 0},
{'month': 'Nov', 'rain': 23.6, 'snow': 0.8, 'wy_month': 1},
{'month': 'Dec', 'rain': 31.9, 'snow': 30.5, 'wy_month': 2},
{'month': 'Jan', 'rain': 44.6, 'snow': 31.1, 'wy_month': 3},
{'month': 'Feb', 'rain': 49.6, 'snow': 31.7, 'wy_month': 4},
{'month': 'Mar', 'rain': 13.6, 'snow': 4.2, 'wy_month': 5},
{'month': 'Apr', 'rain': 107.2, 'snow': 1.6, 'wy_month': 6},
{'month': 'May', 'rain': 77.0, 'snow': 0.0, 'wy_month': 7},
{'month': 'Jun', 'rain': 108., 'snow': 0.0, 'wy_month': 8},
{'month': 'Jul', 'rain': 216., 'snow': 0.0, 'wy_month': 9},
{'month': 'Aug', 'rain': 76.8, 'snow': 0.0, 'wy_month': 10},
{'month': 'Sep', 'rain': 76.4, 'snow': 0.0, 'wy_month': 11},
]
data = pandas.DataFrame(datalist)
</code></pre>
<p>I can do:</p>
<pre><code>bar = charts.Bar(data=data, values='rain', label='month',
color=[blue], width=600, height=300)
plotting.show(bar)
scatter = charts.Scatter(data=data, x='month', y='rain',
color=[blue], width=600, height=300)
plotting.show(scatter)
</code></pre>
<p>and I get:</p>
<p><a href="http://i.stack.imgur.com/WWTan.png" rel="nofollow"><img src="http://i.stack.imgur.com/WWTan.png" alt="bars"></a></p>
<p>and </p>
<p><a href="http://i.stack.imgur.com/r6jvA.png" rel="nofollow"><img src="http://i.stack.imgur.com/r6jvA.png" alt="scatter"></a></p>
<h2>What I've tried</h2>
<p>But if I do that same with an area chart:</p>
<pre><code>area = charts.Area(data=data, y='rain', x='month', stack=True,
color=blue, width=600, height=300)
plotting.show(area)
</code></pre>
<p>I get:</p>
<p><a href="http://i.stack.imgur.com/ZDYXD.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZDYXD.png" alt="enter image description here"></a></p>
<h2>Other efforts</h2>
<p>Removing the explicit definition of <code>x</code> makes the areas show up, but with a numeric axis (0 - 12).</p>
<pre><code>area = charts.Area(data=data, y='rain', stack=True,
color=blue, width=600, height=300)
</code></pre>
<p>Specifying an <code>x_range</code> as either a list or <code>bokeh.models.ranges.FactorRange</code> seems to have no effect (with and without <code>x='month'</code>).</p>
| 2 | 2016-08-03T02:17:27Z | 38,733,857 | <p>One option would be to make custom tick labels for your axes. Modifying from the answer here - <a href="http://stackoverflow.com/questions/37173230/how-do-i-use-custom-labels-for-ticks-in-bokeh">How do I use custom labels for ticks in Bokeh?</a>:</p>
<p>First up we do our imports and create a dictionary to store our modified labels (using Jupyter notebook):</p>
<pre><code>import numpy
import pandas
from bokeh import charts, plotting, models
import bokeh
from bokeh.models.formatters import TickFormatter, String, List, Dict, Int
from bokeh.models import FixedTicker
plotting.output_notebook()
_, blue, _, green = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c']
datalist = [
{'month': 'Oct', 'rain': 107., 'snow': 0.0, 'wy_month': 0},
{'month': 'Nov', 'rain': 23.6, 'snow': 0.8, 'wy_month': 1},
{'month': 'Dec', 'rain': 31.9, 'snow': 30.5, 'wy_month': 2},
{'month': 'Jan', 'rain': 44.6, 'snow': 31.1, 'wy_month': 3},
{'month': 'Feb', 'rain': 49.6, 'snow': 31.7, 'wy_month': 4},
{'month': 'Mar', 'rain': 13.6, 'snow': 4.2, 'wy_month': 5},
{'month': 'Apr', 'rain': 107.2, 'snow': 1.6, 'wy_month': 6},
{'month': 'May', 'rain': 77.0, 'snow': 0.0, 'wy_month': 7},
{'month': 'Jun', 'rain': 108., 'snow': 0.0, 'wy_month': 8},
{'month': 'Jul', 'rain': 216., 'snow': 0.0, 'wy_month': 9},
{'month': 'Aug', 'rain': 76.8, 'snow': 0.0, 'wy_month': 10},
{'month': 'Sep', 'rain': 76.4, 'snow': 0.0, 'wy_month': 11},
]
data = pandas.DataFrame(datalist)
label_data = {x['wy_month']:x['month'] for x in datalist}
</code></pre>
<p>Now we define our custom label class (and associated JS code):</p>
<pre><code>JS_CODE = """
_ = require "underscore"
Model = require "model"
p = require "core/properties"
class FixedTickFormatter extends Model
type: 'FixedTickFormatter'
doFormat: (ticks) ->
labels = @get("labels")
return (labels[tick] ? "" for tick in ticks)
@define {
labels: [ p.Any ]
}
module.exports =
Model: FixedTickFormatter
"""
class FixedTickFormatter(TickFormatter):
labels = Dict(Int, String, help="""
A mapping of integer ticks values to their labels.
""")
__implementation__ = JS_CODE
</code></pre>
<p>And plot your chart with modified axes:</p>
<pre><code>area = charts.Area(data=data, y='rain', x='wy_month', stack=True,
color=blue, width=600, height=300)
area.xaxis[0].formatter = FixedTickFormatter(labels=label_data)
area.xaxis[0].ticker = FixedTicker(ticks=sorted(label_data.keys()))
plotting.show(area)
</code></pre>
<p>Here is the final plot I get:</p>
<p><a href="http://i.stack.imgur.com/WAlJn.png" rel="nofollow"><img src="http://i.stack.imgur.com/WAlJn.png" alt="Bokeh area plot"></a></p>
| 1 | 2016-08-03T03:25:36Z | [
"python",
"bokeh"
] |
Why am I unable to send HTTP Headers to Flask-RESTful reqparse module using add_argument()? | 38,733,337 | <p>I am trying to integrate the Flask-RESTful's request parsing interface, <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/reqparse.html" rel="nofollow">reqparse</a> in my backend to request HTTP headers from the client. Currently, I wish to use this for authentication of a user and wish to pass <code>'secret_key'</code> in HTTP headers.</p>
<p>The function I am using for this task is the <code>add_argument()</code> function. My code for requesting the header is as follows:</p>
<pre><code>reqparse = reqparse.RequestParser()
reqparse.add_argument('secret_key', type=str, location='headers', required=True)
</code></pre>
<p>However, on sending the following cURL request:</p>
<pre><code>curl -H "Content-Type: application/json" -H "{secret_key: SECRET}" -X POST -d '{}' http://localhost:5000/authUser
</code></pre>
<p>I recieve the following 400 error on my Pycharm Community edition editor :</p>
<pre><code>127.0.0.1 - - [02/Aug/2016 18:48:59] "POST /authUser HTTP/1.1" 400 -
</code></pre>
<p>and the following message on my cURL terminal:</p>
<pre><code>{
"message": {
"secret_key": "Missing required parameter in the HTTP headers"
}
}
</code></pre>
<p>To reproduce this error on Pycharm (and hopefully all other compilers as well), please use the files written below as follows:</p>
<pre><code>Folder - Sample_App
- __init__.py
- run.py
- views.py
</code></pre>
<p><strong>__init__.py</strong></p>
<pre><code>from flask import Flask
from flask_restful import Api
from views import AuthUser
app = Flask(__name__)
api = Api(app)
api.add_resource(AuthUser, '/authUser')
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from flask_restful import reqparse, Resource
class AuthUser(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('secret_key', type=str, location='headers', required=True)
def post(self):
data = self.reqparse.parse_args()
if data['secret_key'] == "SECRET":
print("Success")
return 200
return 400
</code></pre>
<p><strong>run.py</strong></p>
<pre><code>from __init__ import app
app.run(host='0.0.0.0', port=5000, debug=True)
</code></pre>
<p>Could you please tell me how to fix this issue? I want to know if the <code>location</code> parameter needs to be changed or if there is something wrong in my cURL request. </p>
<p>EDIT: </p>
<p>With the help of Methika's response, I have figured out the error. The <code>add_argument()</code> function does not take <code>_</code> in a headers parameter. However, when I use the <code>requests.headers['secret_key']</code> function, I am able to request headers with the <code>_</code> character just fine. Why is that the case?
<br><br>
New Code of <strong>views.py</strong>:</p>
<p><strong>views.py</strong></p>
<pre><code>from flask_restful import reqparse, Resource
class AuthUser(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
def post(self):
data = self.reqparse.parse_args()
data['secret_key'] = request.headers['secret_key']
if data['secret_key'] == "SECRET":
print("Success")
return 200
return 400
</code></pre>
| 2 | 2016-08-03T02:21:23Z | 38,792,538 | <p>I did some tests with the code you gave here and I found out that the problem doesn't come from you code but from the name of the variable:</p>
<p>If you replace <code>secret_key</code> by <code>secretkey</code> (or something else without underscore) it will work !</p>
<p>I found this <a href="http://stackoverflow.com/questions/22856136/why-underscores-are-forbidden-in-http-header-names">post</a>, flask seems to not accept underscores in header variable names.</p>
| 1 | 2016-08-05T15:10:24Z | [
"python",
"api",
"curl",
"http-headers",
"flask-restful"
] |
Python Unicode Handling | 38,733,356 | <p>I've looked through several questions and I can't seem to find the exact answer to what I need.</p>
<p>I am trying to figure out how to take an emoji and use unicodedata.name() to return it's name. </p>
<p>So for example, I have this emoji: í ½í²©.
I want to be able to get it's identifier and get the value of it's name (PILE OF POO). I want to know how to construct the string to pass in to the name function:</p>
<pre><code>unicodedata.name(u'\U0001f4a9')
</code></pre>
<p>The above code works. However passing as such:</p>
<pre><code>unicodedata.name(í ½í²©)
</code></pre>
<p>returns the following: </p>
<pre><code>mojidict['hi'] = unicodedata.name(\U0001f4a9) ^ ^
SyntaxError: invalid character in identifier
</code></pre>
| 0 | 2016-08-03T02:24:12Z | 38,733,401 | <p>The solution is very simple:</p>
<pre><code>import unicodedata
unicodedata.name('í ½í²©')
</code></pre>
<p>which returns:</p>
<pre><code>'PILE OF POO'
</code></pre>
| 2 | 2016-08-03T02:28:05Z | [
"python",
"unicode"
] |
Iterate and replace words in lines of a tuple python | 38,733,418 | <p>I want to iterate through this tuple and for each line, iterate through the words to find and replace some words (internet addresses, precisely) using regex while leaving them as lines.</p>
<pre><code>aList=
[
"being broken changes people, \nand rn im missing the old me",
"@SaifAlmazroui @troyboy621 @petr_hruby you're all missing the point",
"#News #Detroit Detroit water customer receives shutoff threat over missing 10 cents: - Theresa Braxton is a l... T.CO/CHPBRVH9WKk",
"@_EdenRodwell \ud83d\ude29\ud83d\ude29ahh I love you!! Missing u, McDonald's car park goss soon please \u2764\ufe0f\u2764\ufe0fxxxxx",
"This was my ring tone, before I decided change was good and missing a call was insignificant T.CO?BUXLVZFDWQ",
"want to go on holiday again, missing the sun\ud83d\ude29\u2600\ufe0f"
]
</code></pre>
<p>This code below almost does that, but it breaks the list into words separated by lines:</p>
<pre><code>i=0
while i<len(aList):
for line in aList[i].split():
line = re.sub(r"^[http](.*)\/(.*)$", "", line)
print (line)
i+=1
</code></pre>
<p>I'd love to have results as with the exception of the internet addresses in each line:</p>
<pre><code>[
"being broken changes people, \nand rn im missing the old me",
"@SaifAlmazroui @troyboy621 @petr_hruby you're all missing the point",
"#News #Detroit Detroit water customer receives shutoff threat over missing 10 cents: - Theresa Braxton is a ",
"@_EdenRodwell \ud83d\ude29\ud83d\ude29ahh I love you!! Missing u, McDonald's car park goss soon please \u2764\ufe0f\u2764\ufe0fxxxxx",
"This was my ring tone, before I decided change was good and missing a call was insignificant",
"want to go on holiday again, missing the sun\ud83d\ude29\u2600\ufe0f"
]
</code></pre>
<p>Thanks</p>
| 1 | 2016-08-03T02:30:33Z | 38,733,960 | <p>Your question is a little unclear, but I think I get what you're going for</p>
<pre><code>newlist = [re.sub(r"{regex}", "", line) for line in alist]
</code></pre>
<p>Should iterate through a list of strings and replace any strings that match your regex pattern with an empty string using a python list comprehension</p>
<p>side note:</p>
<p>Looking closer at your regex it looks like its not doing what you think its doing
I would look at this stack over flow post about matching urls in regex</p>
<p><a href="https://stackoverflow.com/questions/6883049/regex-to-find-urls-in-string-in-python">Regex to find urls in string in Python</a></p>
| 1 | 2016-08-03T03:38:11Z | [
"python",
"regex",
"loops",
"replace",
"tuples"
] |
Iterate and replace words in lines of a tuple python | 38,733,418 | <p>I want to iterate through this tuple and for each line, iterate through the words to find and replace some words (internet addresses, precisely) using regex while leaving them as lines.</p>
<pre><code>aList=
[
"being broken changes people, \nand rn im missing the old me",
"@SaifAlmazroui @troyboy621 @petr_hruby you're all missing the point",
"#News #Detroit Detroit water customer receives shutoff threat over missing 10 cents: - Theresa Braxton is a l... T.CO/CHPBRVH9WKk",
"@_EdenRodwell \ud83d\ude29\ud83d\ude29ahh I love you!! Missing u, McDonald's car park goss soon please \u2764\ufe0f\u2764\ufe0fxxxxx",
"This was my ring tone, before I decided change was good and missing a call was insignificant T.CO?BUXLVZFDWQ",
"want to go on holiday again, missing the sun\ud83d\ude29\u2600\ufe0f"
]
</code></pre>
<p>This code below almost does that, but it breaks the list into words separated by lines:</p>
<pre><code>i=0
while i<len(aList):
for line in aList[i].split():
line = re.sub(r"^[http](.*)\/(.*)$", "", line)
print (line)
i+=1
</code></pre>
<p>I'd love to have results as with the exception of the internet addresses in each line:</p>
<pre><code>[
"being broken changes people, \nand rn im missing the old me",
"@SaifAlmazroui @troyboy621 @petr_hruby you're all missing the point",
"#News #Detroit Detroit water customer receives shutoff threat over missing 10 cents: - Theresa Braxton is a ",
"@_EdenRodwell \ud83d\ude29\ud83d\ude29ahh I love you!! Missing u, McDonald's car park goss soon please \u2764\ufe0f\u2764\ufe0fxxxxx",
"This was my ring tone, before I decided change was good and missing a call was insignificant",
"want to go on holiday again, missing the sun\ud83d\ude29\u2600\ufe0f"
]
</code></pre>
<p>Thanks</p>
| 1 | 2016-08-03T02:30:33Z | 38,738,056 | <p>From this:</p>
<pre><code>re.sub(r"^[http](.*)\/(.*)$", "", line)
</code></pre>
<p>it looks to me as if you expect that all your URLs will be at the end of the line. In that case, try:</p>
<pre><code>[re.sub('http://.*', '', s) for s in aList]
</code></pre>
<p>Here, <code>http://</code> matches anything that starts with <code>http://</code>. <code>.*</code> matches everything that follows.</p>
<h3>Example</h3>
<p>Here is your list with some URLs added:</p>
<pre><code>aList = [
"being broken changes people, \nand rn im missing the old me",
"@SaifAlmazroui @troyboy621 @petr_hruby you're all missing the point",
"#News #Detroit Detroit water customer receives shutoff threat over missing 10 cents: - Theresa Braxton is a http://example.com/CHPBRVH9WKk",
"@_EdenRodwell ahh I love you!! Missing u, McDonald's car park goss soon please xxxxx",
"This was my ring tone, before I decided change was good and missing a call was insignificant http://example.com?BUXLVZFDWQ",
"want to go on holiday again, missing the sun"
]
</code></pre>
<p>Here is the result:</p>
<pre><code>>>> [re.sub('http://.*', '', s) for s in aList]
['being broken changes people, \nand rn im missing the old me',
"@SaifAlmazroui @troyboy621 @petr_hruby you're all missing the point",
'#News #Detroit Detroit water customer receives shutoff threat over missing 10 cents: - Theresa Braxton is a ',
"@_EdenRodwell ahh I love you!! Missing u, McDonald's car park goss soon please xxxxx",
'This was my ring tone, before I decided change was good and missing a call was insignificant ',
'want to go on holiday again, missing the sun']
</code></pre>
| 1 | 2016-08-03T08:14:21Z | [
"python",
"regex",
"loops",
"replace",
"tuples"
] |
Python dictionary throws invalid syntax | 38,733,475 | <p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p>
<pre><code>File "code.py", line 4
'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
SyntaxError: invalid syntax
</code></pre>
<p>If I comment out lines 4 and 5 the error points to line 7. The error always references the second single quote character. In line four it points to the <code>'</code> after the N in "<code>den</code>".</p>
<p>Here is the code:</p>
<pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\
'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\
\
'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},\
\
'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,\
'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},\
\
'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,\
'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},\
\
'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,\
'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},\
\
'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,\
'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},\
\
'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,\
'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},\
\
'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,\
'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},\
\
'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,\
'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},\
\
'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,\
'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},\
\
'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,\
'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},\
\
'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,\
'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},\
\
'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,\
'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1}
\
'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,\
'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9}
\
'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,\
'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}
</code></pre>
| 2 | 2016-08-03T02:38:03Z | 38,733,510 | <p>You lost <code>,</code> before string <code>'den'</code>.</p>
| 2 | 2016-08-03T02:42:06Z | [
"python",
"dictionary",
"syntax"
] |
Python dictionary throws invalid syntax | 38,733,475 | <p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p>
<pre><code>File "code.py", line 4
'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
SyntaxError: invalid syntax
</code></pre>
<p>If I comment out lines 4 and 5 the error points to line 7. The error always references the second single quote character. In line four it points to the <code>'</code> after the N in "<code>den</code>".</p>
<p>Here is the code:</p>
<pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\
'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\
\
'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},\
\
'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,\
'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},\
\
'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,\
'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},\
\
'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,\
'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},\
\
'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,\
'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},\
\
'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,\
'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},\
\
'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,\
'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},\
\
'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,\
'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},\
\
'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,\
'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},\
\
'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,\
'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},\
\
'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,\
'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},\
\
'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,\
'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1}
\
'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,\
'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9}
\
'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,\
'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}
</code></pre>
| 2 | 2016-08-03T02:38:03Z | 38,733,512 | <p>You seem to be missing a comma after the close brace after <code>'cen':.9</code>. Try this fix:</p>
<pre><code>... 'cen':.9} ,\
\
den:{...
</code></pre>
<p>I'm pretty sure that this file, in this condition, would not have run correctly three months ago.</p>
| 3 | 2016-08-03T02:42:12Z | [
"python",
"dictionary",
"syntax"
] |
Python dictionary throws invalid syntax | 38,733,475 | <p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p>
<pre><code>File "code.py", line 4
'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
SyntaxError: invalid syntax
</code></pre>
<p>If I comment out lines 4 and 5 the error points to line 7. The error always references the second single quote character. In line four it points to the <code>'</code> after the N in "<code>den</code>".</p>
<p>Here is the code:</p>
<pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\
'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\
\
'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},\
\
'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,\
'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},\
\
'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,\
'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},\
\
'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,\
'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},\
\
'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,\
'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},\
\
'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,\
'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},\
\
'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,\
'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},\
\
'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,\
'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},\
\
'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,\
'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},\
\
'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,\
'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},\
\
'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,\
'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},\
\
'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,\
'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1}
\
'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,\
'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9}
\
'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,\
'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}
</code></pre>
| 2 | 2016-08-03T02:38:03Z | 38,733,576 | <p>You missed a few commas, fixed:</p>
<pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9},'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1},'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9},'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}
</code></pre>
| 2 | 2016-08-03T02:48:42Z | [
"python",
"dictionary",
"syntax"
] |
Python dictionary throws invalid syntax | 38,733,475 | <p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p>
<pre><code>File "code.py", line 4
'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
SyntaxError: invalid syntax
</code></pre>
<p>If I comment out lines 4 and 5 the error points to line 7. The error always references the second single quote character. In line four it points to the <code>'</code> after the N in "<code>den</code>".</p>
<p>Here is the code:</p>
<pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\
'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\
\
'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},\
\
'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,\
'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},\
\
'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,\
'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},\
\
'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,\
'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},\
\
'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,\
'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},\
\
'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,\
'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},\
\
'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,\
'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},\
\
'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,\
'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},\
\
'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,\
'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},\
\
'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,\
'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},\
\
'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,\
'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},\
\
'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,\
'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1}
\
'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,\
'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9}
\
'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,\
'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}
</code></pre>
| 2 | 2016-08-03T02:38:03Z | 38,734,337 | <p>Such syntax errors are much easier to spot with judicious use of whitespace. At the very least, the error message will you give you a better idea of where to look.</p>
<pre><code>milevalue = {
'adm': {
'adm': 0,
'den': 2.4,
'ear': 3,
'edi': 3.2,
'hug': 2.6,
'fra': 2.1,
'the': 1.2,
'hor': 3.4,
'lon': 1.5,
'rid': 7.7,
'hig': 1.8,
'tho': 5.5,
'was': 1.8,
'act': 0.8,
'cen': .9
} # Oops, here's the missing comma
'den': {
'adm': 2.4,
'den': 0,
'ear': 3.5,
'edi': 3.6,
'hug': 1.6,
'fra': 3.0,
# etc
</code></pre>
| 2 | 2016-08-03T04:19:46Z | [
"python",
"dictionary",
"syntax"
] |
Python dictionary throws invalid syntax | 38,733,475 | <p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p>
<pre><code>File "code.py", line 4
'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
SyntaxError: invalid syntax
</code></pre>
<p>If I comment out lines 4 and 5 the error points to line 7. The error always references the second single quote character. In line four it points to the <code>'</code> after the N in "<code>den</code>".</p>
<p>Here is the code:</p>
<pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\
'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\
\
'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},\
\
'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,\
'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},\
\
'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,\
'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},\
\
'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,\
'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},\
\
'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,\
'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},\
\
'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,\
'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},\
\
'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,\
'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},\
\
'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,\
'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},\
\
'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,\
'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},\
\
'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,\
'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},\
\
'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,\
'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},\
\
'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,\
'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1}
\
'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,\
'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9}
\
'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,\
'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}
</code></pre>
| 2 | 2016-08-03T02:38:03Z | 38,736,383 | <p>Code Fixed.</p>
<p>Missing commas, "," please be careful with them or you should use dictionary notation to generate dictionaries.</p>
<pre>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\
'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\
\
'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\
'hor':1.6,'lon':1.4,'rid':7.4,'hig':2.3,'tho':5.8,'was':0.7,'aca':2.6,'cen':1.8},\
\
'ear':{'adm':3,'den':3.5,'ear':0,'edi':0.1,'eug':1.9,'fra':0.9,'thu':2.1,\
'hor':2.9,'lon':4.4,'rid':4.8,'hig':1.4,'tho':2.7,'was':3.2,'aca':2.4,'cen':2.5},\
\
'edi':{'adm':3.2,'den':2.4,'ear':0.1,'edi':0,'eug':2.0,'fra':1.1,'thu':2.3,\
'hor':2.7,'lon':4.5,'rid':4.7,'hig':1.5,'tho':2.5,'was':3.4,'aca':2.5,'cen':2.6},\
\
'eug':{'adm':2.6,'den':1.6,'ear':1.9,'edi':2.0,'eug':0,'fra':1.8,'thu':3.0,\
'hor':1,'lon':2.6,'rid':6.4,'hig':1.4,'tho':4.3,'was':1.4,'aca':2.5,'cen':1.7},\
\
'fra':{'adm':2.1,'den':3.0,'ear':0.9,'edi':1.1,'eug':1.8,'fra':0,'thu':1.2,\
'hor':2.8,'lon':3.4,'rid':5.7,'hig':0.4,'tho':3.6,'was':2.3,'aca':1.5,'cen':1.6},\
\
'thu':{'adm':1.2,'den':3.1,'ear':2.1,'edi':2.3,'eug':3.0,'fra':1.2,'thu':0,\
'hor':4,'lon':2.9,'rid':7.1,'hig':1.6,'tho':5.1,'was':2.4,'aca':0.6,'cen':1.6},\
\
'hor':{'adm':3.4,'den':1.6,'ear':2.9,'edi':2.7,'eug':1,'fra':2.8,'thu':4,\
'hor':0,'lon':2.7,'rid':6.1,'hig':2.4,'tho':4.4,'was':2,'aca':3.5,'cen':2.8},\
\
'lon':{'adm':1.5,'den':1.4,'ear':4.4,'edi':4.5,'eug':2.6,'fra':3.4,'thu':2.9,\
'hor':2.7,'lon':0,'rid':8.6,'hig':3.5,'tho':7.1,'was':1.6,'aca':2.5,'cen':2.5},\
\
'rid':{'adm':7.7,'den':7.4,'ear':4.8,'edi':4.7,'eug':6.4,'fra':5.7,'thu':7.1,\
'hor':6.1,'lon':8.6,'rid':0,'hig':5.9,'tho':2.4,'was':7.8,'aca':6.9,'cen':7},\
\
'hig':{'adm':1.8,'den':2.3,'ear':1.4,'edi':1.5,'eug':1.4,'fra':0.4,'thu':1.6,\
'hor':2.4,'lon':3.5,'rid':5.9,'hig':0,'tho':3.8,'was':1.9,'aca':1.3,'cen':1.1},\
\
'tho':{'adm':5.5,'den':5.8,'ear':2.7,'edi':2.5,'eug':4.3,'fra':3.6,'thu':5.1,\
'hor':4.4,'lon':7.1,'rid':2.4,'hig':3.8,'tho':0,'was':5.9,'aca':4.8,'cen':4.9},\
\
'was':{'adm':1.8,'den':0.7,'ear':3.2,'edi':3.4,'eug':1.4,'fra':2.3,'thu':2.4,\
'hor':2,'lon':1.6,'rid':7.8,'hig':1.9,'tho':5.9,'was':0,'aca':1.9,'cen':1.1},
\
'aca':{'adm':0.8,'den':2.6,'ear':2.4,'edi':2.5,'eug':2.5,'fra':1.5,'thu':0.6,\
'hor':3.5,'lon':2.5,'rid':6.9,'hig':1.3,'tho':4.8,'was':1.9,'aca':0,'cen':0.9},
\
'cen':{'adm':0.9,'den':1.8,'ear':2.5,'edi':2.6,'eug':1.7,'fra':1.6,'thu':1.6,\
'hor':2.8,'lon':2.5,'rid':7,'hig':1.1,'tho':4.9,'was':1.1,'aca':0.9,'cen':0}}</pre>
| 1 | 2016-08-03T06:51:57Z | [
"python",
"dictionary",
"syntax"
] |
What's the best way to sum all values in a Pandas dataframe? | 38,733,477 | <p>I figured out these two methods. Is there a better one?</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame({'A': [5, 6, 7], 'B': [7, 8, 9]})
>>> print df.sum().sum()
42
>>> print df.values.sum()
42
</code></pre>
<p>Just want to make sure I'm not missing something more obvious.</p>
| 2 | 2016-08-03T02:38:11Z | 38,733,583 | <pre><code>df.values
</code></pre>
<p>Is the underlying numpy array</p>
<pre><code>df.values.sum()
</code></pre>
<p>Is the numpy sum method and is faster</p>
| 3 | 2016-08-03T02:49:04Z | [
"python",
"pandas",
"dataframe",
"sum"
] |
Publishing MQTT messages from a Python script on a Raspberry Pi | 38,733,589 | <p>I am trying to configure a Raspberry Pi (Raspbian, Jessie) to send temperature data from a DS18B20 sensor to my MQTT broker.</p>
<p>I have installed mosquitto, mosquitto-clients, and python-mosquitto. I have also installed paho-mqtt.</p>
<p>Mosquitto seems to be working fine; I can publish from the command line but I can not get ANY python script I've written or found to publish or subscribe.</p>
<p>Why does this work from the command line,</p>
<pre><code>mosquitto_pub -h 192.168.0.21 -d -t test/test -m "Hello world!"
</code></pre>
<p>while this script does not?</p>
<pre><code> #!/usr/bin/env python
import paho.mqtt.client as mqtt
# set up the mqtt client
mqttc = mqtt.Client("python_pub")
# the server to publish to, and corresponding port
mqttc.connect("192.168.0.21", 1883)
# the topic to publish to, and the message to publish
mqttc.publish("test/test", "Hello world!")
# establish a two-second timeout
mqttc.loop(2)
</code></pre>
<p>Thanks in advance!</p>
<p>EDIT: Experimenting, I found that by changing the IP in the script to that of the Pi itself, I CAN publish MQTT that is received by the Pi. The Pi can also receive messages published to it. I still, however, can't publish from a script to an external broker. So now I'm thinking it's a broker issue...</p>
| 1 | 2016-08-03T02:49:25Z | 38,738,316 | <p>As mentioned in the comment, the code you posted does work, but for publishing a <a href="https://eclipse.org/paho/clients/python/docs/#single" rel="nofollow">single</a> message this form is better</p>
<pre><code>#!/usr/bin/env python
import paho.mqtt.publish as publish
publish.single("test/test", "Hello world!", hostname="192.168.0.21")
</code></pre>
| 2 | 2016-08-03T08:27:45Z | [
"python",
"raspberry-pi",
"mqtt"
] |
Best way to perform calculations on a list/tuple in Python 3x | 38,733,593 | <p>I wrote this program that will tell you the two <s>multiples</s> factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.</p>
<p>But I am wondering if there is a more concise or pythonic way to iterate through this tuple so I wouldn't have to code all those "elif" statements you see below.</p>
<p>Also it would be great if I didn't need to rely on any external libraries.</p>
<pre><code># multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )
# tuple 1 calculations
while True:
try:
semiprime = int(input('Enter Semiprime: '))
except ValueError:
print('INPUT MUST BE AN INTEGER')
continue
# index 0 - 3
if (tuple1[0]) * (tuple1[0]) == semiprime:
print((tuple1[0]), (tuple1[0]))
elif (tuple1[0]) * (tuple1[1]) == semiprime:
print((tuple1[0]), (tuple1[1]))
elif (tuple1[0]) * (tuple1[2]) == semiprime:
print((tuple1[0]), (tuple1[2]))
elif (tuple1[0]) * (tuple1[3]) == semiprime:
print((tuple1[0]), (tuple1[3]))
# index 1 - 3
elif (tuple1[1]) * (tuple1[0]) == semiprime:
print((tuple1[1]), (tuple1[0]))
elif (tuple1[1]) * (tuple1[1]) == semiprime:
print((tuple1[1]), (tuple1[1]))
elif (tuple1[1]) * (tuple1[2]) == semiprime:
print((tuple1[1]), (tuple1[2]))
elif (tuple1[1]) * (tuple1[3]) == semiprime:
print((tuple1[1]), (tuple1[3]))
# index 2 - 3
elif (tuple1[2]) * (tuple1[0]) == semiprime:
print((tuple1[2]), (tuple1[0]))
elif (tuple1[2]) * (tuple1[1]) == semiprime:
print((tuple1[2]), (tuple1[1]))
elif (tuple1[2]) * (tuple1[2]) == semiprime:
print((tuple1[2]), (tuple1[2]))
elif (tuple1[2]) * (tuple1[3]) == semiprime:
print((tuple1[2]), (tuple1[3]))
#index 3 - 3
elif (tuple1[3]) * (tuple1[0]) == semiprime:
print((tuple1[3]), (tuple1[0]))
elif (tuple1[3]) * (tuple1[1]) == semiprime:
print((tuple1[3]), (tuple1[1]))
elif (tuple1[3]) * (tuple1[2]) == semiprime:
print((tuple1[3]), (tuple1[2]))
</code></pre>
| 4 | 2016-08-03T02:49:58Z | 38,733,684 | <p>I hinted at this in my comment, but realized just the link to the function docs may not be enough.</p>
<p>Here's how you could write your code using <a href="https://docs.python.org/dev/library/itertools.html#itertools.combinations_with_replacement" rel="nofollow"><code>itertools.combinations_with_replacement</code></a>:</p>
<pre><code>from itertools import combinations_with_replacement
# multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )
# tuple 1 calculations
while True:
try:
semiprime = int(input('Enter Semiprime: '))
except ValueError:
print('INPUT MUST BE AN INTEGER')
continue
for (x,y) in combinations_with_replacement(tuple1, 2):
if x * y == semiprime:
print(x,y)
</code></pre>
<p>Much nicer, IMO :)</p>
<p><strong>Edit</strong>: A previous version used <a href="https://docs.python.org/dev/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a> which wouldn't yield (x,y) pairs with the same value (e.g. <code>(x,y) = (2,2)</code> would never happen). <code>combinations_with_replacement</code> allows for duplicates. Thanks to @Copperfield for pointing this out.</p>
| 3 | 2016-08-03T03:01:32Z | [
"python",
"python-3.x",
"tuples"
] |
Best way to perform calculations on a list/tuple in Python 3x | 38,733,593 | <p>I wrote this program that will tell you the two <s>multiples</s> factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.</p>
<p>But I am wondering if there is a more concise or pythonic way to iterate through this tuple so I wouldn't have to code all those "elif" statements you see below.</p>
<p>Also it would be great if I didn't need to rely on any external libraries.</p>
<pre><code># multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )
# tuple 1 calculations
while True:
try:
semiprime = int(input('Enter Semiprime: '))
except ValueError:
print('INPUT MUST BE AN INTEGER')
continue
# index 0 - 3
if (tuple1[0]) * (tuple1[0]) == semiprime:
print((tuple1[0]), (tuple1[0]))
elif (tuple1[0]) * (tuple1[1]) == semiprime:
print((tuple1[0]), (tuple1[1]))
elif (tuple1[0]) * (tuple1[2]) == semiprime:
print((tuple1[0]), (tuple1[2]))
elif (tuple1[0]) * (tuple1[3]) == semiprime:
print((tuple1[0]), (tuple1[3]))
# index 1 - 3
elif (tuple1[1]) * (tuple1[0]) == semiprime:
print((tuple1[1]), (tuple1[0]))
elif (tuple1[1]) * (tuple1[1]) == semiprime:
print((tuple1[1]), (tuple1[1]))
elif (tuple1[1]) * (tuple1[2]) == semiprime:
print((tuple1[1]), (tuple1[2]))
elif (tuple1[1]) * (tuple1[3]) == semiprime:
print((tuple1[1]), (tuple1[3]))
# index 2 - 3
elif (tuple1[2]) * (tuple1[0]) == semiprime:
print((tuple1[2]), (tuple1[0]))
elif (tuple1[2]) * (tuple1[1]) == semiprime:
print((tuple1[2]), (tuple1[1]))
elif (tuple1[2]) * (tuple1[2]) == semiprime:
print((tuple1[2]), (tuple1[2]))
elif (tuple1[2]) * (tuple1[3]) == semiprime:
print((tuple1[2]), (tuple1[3]))
#index 3 - 3
elif (tuple1[3]) * (tuple1[0]) == semiprime:
print((tuple1[3]), (tuple1[0]))
elif (tuple1[3]) * (tuple1[1]) == semiprime:
print((tuple1[3]), (tuple1[1]))
elif (tuple1[3]) * (tuple1[2]) == semiprime:
print((tuple1[3]), (tuple1[2]))
</code></pre>
| 4 | 2016-08-03T02:49:58Z | 38,733,835 | <p>While jedwards demonstrates the most Pythonic approach - using the <code>itertools</code> library which you will come to know and love- here is the more "classic" approach using for-loops for the pattern you want. I bring it up because as a programming beginner, it is important to know this basic, imperative idiom:</p>
<pre><code>>>> tuple1 = (2,3,5,7)
>>> for i in range(len(tuple1)):
... for j in range(i+1, len(tuple1)):
... print(tuple1[i], tuple1[j])
...
2 3
2 5
2 7
3 5
3 7
5 7
>>>
</code></pre>
<p>Thus, your code would be shortened to:</p>
<pre><code>for i in range(len(tuple1)):
for j in range(i+1, len(tuple1)):
if tuple1[i] * tuple1[j] == semiprime
print(tuple1[i], tuple1[j])
</code></pre>
| 1 | 2016-08-03T03:23:17Z | [
"python",
"python-3.x",
"tuples"
] |
Best way to perform calculations on a list/tuple in Python 3x | 38,733,593 | <p>I wrote this program that will tell you the two <s>multiples</s> factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.</p>
<p>But I am wondering if there is a more concise or pythonic way to iterate through this tuple so I wouldn't have to code all those "elif" statements you see below.</p>
<p>Also it would be great if I didn't need to rely on any external libraries.</p>
<pre><code># multiples of semiprimes 4 - 49
tuple1 = ( 2, 3, 5, 7 )
# tuple 1 calculations
while True:
try:
semiprime = int(input('Enter Semiprime: '))
except ValueError:
print('INPUT MUST BE AN INTEGER')
continue
# index 0 - 3
if (tuple1[0]) * (tuple1[0]) == semiprime:
print((tuple1[0]), (tuple1[0]))
elif (tuple1[0]) * (tuple1[1]) == semiprime:
print((tuple1[0]), (tuple1[1]))
elif (tuple1[0]) * (tuple1[2]) == semiprime:
print((tuple1[0]), (tuple1[2]))
elif (tuple1[0]) * (tuple1[3]) == semiprime:
print((tuple1[0]), (tuple1[3]))
# index 1 - 3
elif (tuple1[1]) * (tuple1[0]) == semiprime:
print((tuple1[1]), (tuple1[0]))
elif (tuple1[1]) * (tuple1[1]) == semiprime:
print((tuple1[1]), (tuple1[1]))
elif (tuple1[1]) * (tuple1[2]) == semiprime:
print((tuple1[1]), (tuple1[2]))
elif (tuple1[1]) * (tuple1[3]) == semiprime:
print((tuple1[1]), (tuple1[3]))
# index 2 - 3
elif (tuple1[2]) * (tuple1[0]) == semiprime:
print((tuple1[2]), (tuple1[0]))
elif (tuple1[2]) * (tuple1[1]) == semiprime:
print((tuple1[2]), (tuple1[1]))
elif (tuple1[2]) * (tuple1[2]) == semiprime:
print((tuple1[2]), (tuple1[2]))
elif (tuple1[2]) * (tuple1[3]) == semiprime:
print((tuple1[2]), (tuple1[3]))
#index 3 - 3
elif (tuple1[3]) * (tuple1[0]) == semiprime:
print((tuple1[3]), (tuple1[0]))
elif (tuple1[3]) * (tuple1[1]) == semiprime:
print((tuple1[3]), (tuple1[1]))
elif (tuple1[3]) * (tuple1[2]) == semiprime:
print((tuple1[3]), (tuple1[2]))
</code></pre>
| 4 | 2016-08-03T02:49:58Z | 38,733,966 | <p>Even though @<strong>jedwards</strong> solution is great, (<em>as well as concise/pythonic</em>); one other possible solution:</p>
<pre><code>def prime_multiples(l,t ):
for i in l: # Iterate over our list.
for j in t: # Iterate over the tuple of prime factors.
# We check to see that we can divide without a remainder with our factor,
# then check to see if that factor exists in our tuple.
if i%j == 0 and i/j in t:
print "Prime factors: {} * {} = {}".format(j, i/j, i)
break # We could go not break to print out more options.
</code></pre>
<p><strong>Sample output:</strong></p>
<pre><code>l = [4, 6, 9, 10, 14, 15, 21, 22, 25, 26, 33, 34, 35, 38, 39, 46, 49]
t = ( 2, 3, 5, 7 )
prime_multiples(l, t)
>>> Prime factors: 2 * 2 = 4
... Prime factors: 2 * 3 = 6
... Prime factors: 3 * 3 = 9
... Prime factors: 2 * 5 = 10
... Prime factors: 2 * 7 = 14
... Prime factors: 3 * 5 = 15
... Prime factors: 3 * 7 = 21
... Prime factors: 5 * 5 = 25
... Prime factors: 5 * 7 = 35
... Prime factors: 7 * 7 = 49
</code></pre>
| 1 | 2016-08-03T03:38:48Z | [
"python",
"python-3.x",
"tuples"
] |
Can't install Pillow for Python 3.x in Windows - Zlib is required | 38,733,647 | <p>I am using PyCharm with Python 3.0 and I want to import Pillow Module.</p>
<p>While installing the Pillow module from Project Interpreter, I got a message which says:</p>
<pre><code>ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting.
</code></pre>
<p><a href="http://i.stack.imgur.com/XAFN7.png" rel="nofollow"><img src="http://i.stack.imgur.com/XAFN7.png" alt="enter image description here"></a></p>
<p>I have also tried installing the same from command line by using both pip install and easy install but the command line is also throwing the same error.</p>
<p>I tried to find several solution in internet, but most of them are for Linux. for example, this solution: <a href="http://stackoverflow.com/questions/6169522/no-module-named-zlib">no module named zlib</a></p>
<p>How can I solve this issue in Windows and with PyCharm ?</p>
| 1 | 2016-08-03T02:56:35Z | 39,305,161 | <p>Go to the Virtualenv path
cd path to virtualenv
cd Script
then run
easy_install Pillow</p>
<p>It works fine</p>
| 1 | 2016-09-03T09:04:15Z | [
"python",
"windows",
"python-3.x",
"pycharm"
] |
Can't install Pillow for Python 3.x in Windows - Zlib is required | 38,733,647 | <p>I am using PyCharm with Python 3.0 and I want to import Pillow Module.</p>
<p>While installing the Pillow module from Project Interpreter, I got a message which says:</p>
<pre><code>ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting.
</code></pre>
<p><a href="http://i.stack.imgur.com/XAFN7.png" rel="nofollow"><img src="http://i.stack.imgur.com/XAFN7.png" alt="enter image description here"></a></p>
<p>I have also tried installing the same from command line by using both pip install and easy install but the command line is also throwing the same error.</p>
<p>I tried to find several solution in internet, but most of them are for Linux. for example, this solution: <a href="http://stackoverflow.com/questions/6169522/no-module-named-zlib">no module named zlib</a></p>
<p>How can I solve this issue in Windows and with PyCharm ?</p>
| 1 | 2016-08-03T02:56:35Z | 39,894,227 | <p>files > Settings > Project Test > Project Interpreter > ADD > Pillow-PIL</p>
| -1 | 2016-10-06T11:00:49Z | [
"python",
"windows",
"python-3.x",
"pycharm"
] |
Efficient way to get the unique values from 2 or more columns in a Dataframe | 38,733,719 | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| 12 | 2016-08-03T03:07:31Z | 38,734,603 | <p>I dont have SFrame but tested on pd.DataFrame: </p>
<pre><code> sf[["x", "y"]].stack().value_counts().index.tolist()
[2, 1, 8, 7, 6, 5, 4]
</code></pre>
| 2 | 2016-08-03T04:46:54Z | [
"python",
"csv",
"pandas",
"dataframe",
"sframe"
] |
Efficient way to get the unique values from 2 or more columns in a Dataframe | 38,733,719 | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| 12 | 2016-08-03T03:07:31Z | 38,735,070 | <p>Although I don't know how to do it in SFrame, here's a longer explanation of @Merlin's answer:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> df[['x', 'y']]
x y
0 1 2
1 1 4
2 2 6
3 5 8
4 7 2
</code></pre>
<p>To extract only columns X and Y</p>
<pre><code>>>> df[['x', 'y']] # Extract only columns x and y
x y
0 1 2
1 1 4
2 2 6
3 5 8
4 7 2
</code></pre>
<p>To stack the 2 columns per row into 1 column row, while still being able to access them as a dictionary:</p>
<pre><code>>>> df[['x', 'y']].stack()
0 x 1
y 2
1 x 1
y 4
2 x 2
y 6
3 x 5
y 8
4 x 7
y 2
dtype: int64
>>> df[['x', 'y']].stack()[0]
x 1
y 2
dtype: int64
>>> df[['x', 'y']].stack()[0]['x']
1
>>> df[['x', 'y']].stack()[0]['y']
2
</code></pre>
<p>Count the individual values of all elements within the combined columns:</p>
<pre><code>>>> df[['x', 'y']].stack().value_counts() # index(i.e. keys)=elements, Value=counts
2 3
1 2
8 1
7 1
6 1
5 1
4 1
</code></pre>
<p>To access the index and counts:</p>
<pre><code>>>> df[['x', 'y']].stack().value_counts().index
Int64Index([2, 1, 8, 7, 6, 5, 4], dtype='int64')
>>> df[['x', 'y']].stack().value_counts().values
array([3, 2, 1, 1, 1, 1, 1])
</code></pre>
<p>Convert to a list:</p>
<pre><code>>>> sf[["x", "y"]].stack().value_counts().index.tolist()
[2, 1, 8, 7, 6, 5, 4]
</code></pre>
<p>Still an SFrame answer would be great too. The same syntax doesn't work for SFrame.</p>
| 1 | 2016-08-03T05:27:10Z | [
"python",
"csv",
"pandas",
"dataframe",
"sframe"
] |
Efficient way to get the unique values from 2 or more columns in a Dataframe | 38,733,719 | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| 12 | 2016-08-03T03:07:31Z | 39,044,499 | <p>The easiest way I can think of is to convert to a numpy array then find unique values</p>
<pre><code>np.unique(sf[['x', 'y']].to_numpy())
array([1, 2, 4, 5, 6, 7, 8])
</code></pre>
<p>If you needed it in an sframe</p>
<pre><code>SFrame({'xy_unique': np.unique(sf[['x', 'y']].to_numpy())})
</code></pre>
<p><a href="http://i.stack.imgur.com/8Mo3Z.png" rel="nofollow"><img src="http://i.stack.imgur.com/8Mo3Z.png" alt="enter image description here"></a></p>
| 2 | 2016-08-19T17:12:04Z | [
"python",
"csv",
"pandas",
"dataframe",
"sframe"
] |
Efficient way to get the unique values from 2 or more columns in a Dataframe | 38,733,719 | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| 12 | 2016-08-03T03:07:31Z | 39,044,505 | <p><strong>SFrame</strong></p>
<p>I haven't used SFrame and don't know on which conditions it copies data. (Does selection <code>sf['x']</code> or <code>append</code> copy data to memory?). There are <code>pack_columns</code> and <code>stack</code> methods in SFrame and if they don't copy data, then this should work:</p>
<pre><code>sf[['x', 'y']].pack_columns(new_column_name='N').stack('N').unique()
</code></pre>
<p><strong>pandas</strong></p>
<p>If your data fit into memory then you can probably do it in pandas efficiently without extra copy.</p>
<pre><code># copies the data to memory
df = sf[['x', 'y']].to_dataframe()
# a reference to the underlying numpy array (no copy)
vals = df.values
# 1d array:
# (numpy.ravel doesn't copy if it doesn't have to - it depends on the data layout)
if np.isfortran(vals):
vals_1d = vals.ravel(order='F')
else:
vals_1d = vals.ravel(order='C')
uniques = pd.unique(vals_1d)
</code></pre>
<p>pandas's <code>unique</code> is more efficient than numpy's <code>np.unique</code> because it doesn't sort.</p>
| 2 | 2016-08-19T17:12:47Z | [
"python",
"csv",
"pandas",
"dataframe",
"sframe"
] |
Efficient way to get the unique values from 2 or more columns in a Dataframe | 38,733,719 | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| 12 | 2016-08-03T03:07:31Z | 39,071,903 | <p>Take a look at <a href="http://stackoverflow.com/questions/26977076/pandas-unique-values-multiple-columns">this answer</a> to a similar question. Note that Pandas' <code>pd.unique</code> function is considerably faster than Numpy's.</p>
<pre><code>>>> pd.unique(sf[['x','y']].values.ravel())
array([2, 8, 5, 4, 1, 7, 6], dtype=object)
</code></pre>
| 2 | 2016-08-22T05:27:51Z | [
"python",
"csv",
"pandas",
"dataframe",
"sframe"
] |
Efficient way to get the unique values from 2 or more columns in a Dataframe | 38,733,719 | <p>Given a matrix from an <code>SFrame</code>:</p>
<pre><code>>>> from sframe import SFrame
>>> sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]})
>>> sf
Columns:
x int
y int
z int
Rows: 5
Data:
+---+---+---+
| x | y | z |
+---+---+---+
| 1 | 2 | 2 |
| 1 | 4 | 5 |
| 2 | 6 | 8 |
| 5 | 8 | 6 |
| 7 | 2 | 2 |
+---+---+---+
[5 rows x 3 columns]
</code></pre>
<p>I want to get the unique values for the <code>x</code> and <code>y</code> columns and I can do it as such:</p>
<pre><code>>>> sf['x'].unique().append(sf['y'].unique()).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>This way I get the unique values of x and unique values of y then append them and get the unique values of the appended list.</p>
<p>I could also do it as such:</p>
<pre><code>>>> sf['x'].append(sf['y']).unique()
dtype: int
Rows: 7
[2, 8, 5, 4, 1, 7, 6]
</code></pre>
<p>But that way, if my x and y columns are huge with lots of duplicates, I would be appending it into a very huge container before getting the unique.</p>
<p><strong>Is there a more efficient way to get the unique values of a combined columns created from 2 or more columns in an SFrame?</strong></p>
<p><strong>What is the equivalence in pandas of the efficent way to get unique values from 2 or more columns in <code>pandas</code>?</strong></p>
| 12 | 2016-08-03T03:07:31Z | 39,154,077 | <p>Here's a little benchmark between three possible methods:</p>
<pre><code>from sframe import SFrame
import numpy as np
import pandas as pd
import timeit
sf = SFrame({'x': [1, 1, 2, 5, 7], 'y': [2, 4, 6, 8, 2], 'z': [2, 5, 8, 6, 2]})
def f1(sf):
return sf['x'].unique().append(sf['y'].unique()).unique()
def f2(sf):
return sf['x'].append(sf['y']).unique()
def f3(sf):
return np.unique(sf[['x', 'y']].to_numpy())
N = 1000
print timeit.timeit('f1(sf)', setup='from __main__ import f1, sf', number=N)
print timeit.timeit('f2(sf)', setup='from __main__ import f2, sf', number=N)
print timeit.timeit('f3(sf)', setup='from __main__ import f3, sf', number=N)
# 13.3195129933
# 4.66225642657
# 3.65669089489
# [Finished in 23.6s]
</code></pre>
<p>Benchmark using python2.7.11 x64 on windows7+i7_2.6ghz</p>
<p>Conclusion: I'd suggest you use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow">np.unique</a>, that's basically <strong>f3</strong>.</p>
| 1 | 2016-08-25T20:18:00Z | [
"python",
"csv",
"pandas",
"dataframe",
"sframe"
] |
How to Create New Columns to Store the Data of the Duplicate ID Column? | 38,733,732 | <p>I have this dataframe:</p>
<pre><code> ID key
0 1 A
1 1 B
2 2 C
3 3 D
4 3 E
5 3 E
</code></pre>
<p>I want to create additional <code>key</code> columns -as necessary- to store the data in the <code>key</code> column when there are duplicate <code>IDs</code></p>
<p>This is a snippet of the output:</p>
<pre><code> ID key key2
0 1 A B # Note: ID#1 appeared twice in the dataframe, so the key value "B"
# associated with the duplicate ID will be stored in the new column "key2"
</code></pre>
<p>The complete output should like the following: </p>
<pre><code> ID key key2 key3
0 1 A B NaN
1 2 C NaN NaN
2 3 D E E # The ID#3 has repeated three times. The key of
# of the second repeat "E" will be stored under the "key2" column
# and the third repeat "E" will be stored in the new column "key3"
</code></pre>
<p>Any suggestion or idea how should I approach this problem?</p>
<p>Thanks,</p>
| 0 | 2016-08-03T03:09:20Z | 38,734,358 | <p>Check out <code>groupby</code> and <code>apply</code>. Their respective docs are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">here</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow">here</a>. You can <code>unstack</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow">docs</a>) the extra level of the MultiIndex that is created.</p>
<pre><code>df.groupby('ID')['key'].apply(
lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])
).unstack(-1)
</code></pre>
<p>outputs</p>
<pre><code> key_0 key_1 key_2
ID
1 A B None
2 C None None
3 D E E
</code></pre>
<p>If you want <code>ID</code> as a column, you can call <code>reset_index</code> on this DataFrame.</p>
| 1 | 2016-08-03T04:22:33Z | [
"python",
"regex",
"pandas",
"dataframe",
"format"
] |
How to Create New Columns to Store the Data of the Duplicate ID Column? | 38,733,732 | <p>I have this dataframe:</p>
<pre><code> ID key
0 1 A
1 1 B
2 2 C
3 3 D
4 3 E
5 3 E
</code></pre>
<p>I want to create additional <code>key</code> columns -as necessary- to store the data in the <code>key</code> column when there are duplicate <code>IDs</code></p>
<p>This is a snippet of the output:</p>
<pre><code> ID key key2
0 1 A B # Note: ID#1 appeared twice in the dataframe, so the key value "B"
# associated with the duplicate ID will be stored in the new column "key2"
</code></pre>
<p>The complete output should like the following: </p>
<pre><code> ID key key2 key3
0 1 A B NaN
1 2 C NaN NaN
2 3 D E E # The ID#3 has repeated three times. The key of
# of the second repeat "E" will be stored under the "key2" column
# and the third repeat "E" will be stored in the new column "key3"
</code></pre>
<p>Any suggestion or idea how should I approach this problem?</p>
<p>Thanks,</p>
| 0 | 2016-08-03T03:09:20Z | 38,735,498 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>df['cols'] = 'key' + df.groupby('ID').cumcount().astype(str)
print (df.pivot_table(index='ID', columns='cols', values='key', aggfunc=''.join))
cols key0 key1 key2
ID
1 A B None
2 C None None
3 D E E
</code></pre>
| 1 | 2016-08-03T05:57:03Z | [
"python",
"regex",
"pandas",
"dataframe",
"format"
] |
Loading django.apps module inside the url patterns file | 38,733,763 | <p>I have added a router property (an instance of DRF's SimpleRouter) to my AppConfig. I want to get a list of all installed apps in my urls.py file and add any app with the router property to my url patterns.</p>
<p>This is my urls.py file:</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
from django.apps import apps
urlpatterns = [
url(r'^admin/', include(admin.site.urls))
]
# Loading the routers of the installed apps and core apps
for app in apps.get_app_configs():
if hasattr(app, 'router'):
urlpatterns += app.router.urls
</code></pre>
<p>and this is an example of my modified AppConfig:</p>
<pre><code>from django.apps import AppConfig
from .router import auth_router
class AuthConfig(AppConfig):
name = "core.auth"
# to avoid classing with the django auth
label = "custom_auth"
# router object
router = auth_router
def ready(self):
from .signals import user_initialize, password_reset_set_token
default_app_config = 'core.auth.AuthConfig'
</code></pre>
<p>When I try the above solution, I end up getting a "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." error message!</p>
<p>I've tried using the solutions proposed <a href="http://stackoverflow.com/questions/25537905/django-1-7-throws-django-core-exceptions-appregistrynotready-models-arent-load">here</a> but none of them worked!</p>
| 0 | 2016-08-03T03:13:27Z | 38,747,709 | <p>The error wasn't being caused by the urls.py folder, it was being by the AppConfig. I had to import the auth_router inside the ready method</p>
<pre><code>from django.apps import AppConfig
class AuthConfig(AppConfig):
name = "core.auth"
# to avoid classing with the django auth
label = "custom_auth"
# router object
router = None
def ready(self):
from .signals import user_initialize, password_reset_set_token
from .router import auth_router
self.router = auth_router
default_app_config = 'core.auth.AuthConfig'
</code></pre>
| 1 | 2016-08-03T15:23:02Z | [
"python",
"django",
"django-rest-framework",
"django-urls"
] |
Can not enter characters in dictionary with python script | 38,733,798 | <p>I made a dictionary in python by retrieving data in json format.</p>
<pre><code>[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},<br>
{"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_Streptophyta ","order":"Pinales ","family":"Pinaceae ","genus":"Abies"}]
</code></pre>
<p>When I access the data, I am trying to take only the ones in which the value of <code>genus</code> is <code>Abies</code>, but instead I get the error</p>
<blockquote>
<p>ValueError : invalid literal for int ( ) with base 10 : 'Abies'</p>
</blockquote>
<p>But if I input a numeric value, I get data corresponding to the "id" of the json.</p>
<p>This is my script:</p>
<pre><code>import urllib2
import simplejson
title = raw_input("find taxonom: ")
print "key: ",title
response = urllib2.urlopen("http://localhost/csv/taxo.json")
data = simplejson.load(response)
get = int(str(title))
print data[get]
</code></pre>
<p>How do I get it display data "id", "kingdom", "phlyum", "class", etc of each data that matches the input for genus?</p>
| 1 | 2016-08-03T03:17:54Z | 38,733,827 | <p>The error you are getting is because you are trying to convert a string containing non numeric values into an integer. To fix that, remove <code>get = int(str(title))</code></p>
<hr>
<p>The data you have is a list. Lists use numeric indexing to access elements at different locations in the list. To print <code>genus</code> value, you have to do:</p>
<pre><code>print data[1]['genus']
</code></pre>
<p>Note that this targets the second dictionary in the list. To print the value of <code>genus</code> for the first dictionary, you have to change that <code>1</code> to <code>0</code></p>
<hr>
<p>To print the value of each dictionary which contains a value for <code>genus</code> matching title, do this:</p>
<pre><code>for attr_map in data:
if attr_map['genus'] == title:
print attr_map
</code></pre>
<p>Example run of the program:</p>
<pre><code>>>> import json
>>> buffer = '[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},{"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_Streptophyta ","order":"Pinales ","family":"Pinaceae ","genus":"Abies"}]'
>>> data = json.loads(buffer)
>>> data
[{u'kingdom': u'Metazoa ', u'family': u'Belostomatidae ', u'class': u'Insecta ', u'id': u'1', u'phylum': u'Arthropoda ', u'genus': u'Abedus', u'order': u'Hemiptera '}, {u'kingdom': u'Viridiplantae ', u'family': u'Pinaceae ', u'class': u'unclassified_Streptophyta ', u'id': u'2', u'phylum': u'Streptophyta ', u'genus': u'Abies', u'order': u'Pinales '}]
>>>
>>> title = raw_input("find taxonom: ")
find taxonom: Abies
>>> for attr_map in data:
... if attr_map['genus'] == title:
... print attr_map
...
{u'kingdom': u'Viridiplantae ', u'family': u'Pinaceae ', u'class': u'unclassified_Streptophyta ', u'id': u'2', u'phylum': u'Streptophyta ', u'genus': u'Abies', u'order': u'Pinales '}
</code></pre>
| 3 | 2016-08-03T03:21:37Z | [
"python",
"json",
"python-2.7"
] |
Can not enter characters in dictionary with python script | 38,733,798 | <p>I made a dictionary in python by retrieving data in json format.</p>
<pre><code>[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},<br>
{"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_Streptophyta ","order":"Pinales ","family":"Pinaceae ","genus":"Abies"}]
</code></pre>
<p>When I access the data, I am trying to take only the ones in which the value of <code>genus</code> is <code>Abies</code>, but instead I get the error</p>
<blockquote>
<p>ValueError : invalid literal for int ( ) with base 10 : 'Abies'</p>
</blockquote>
<p>But if I input a numeric value, I get data corresponding to the "id" of the json.</p>
<p>This is my script:</p>
<pre><code>import urllib2
import simplejson
title = raw_input("find taxonom: ")
print "key: ",title
response = urllib2.urlopen("http://localhost/csv/taxo.json")
data = simplejson.load(response)
get = int(str(title))
print data[get]
</code></pre>
<p>How do I get it display data "id", "kingdom", "phlyum", "class", etc of each data that matches the input for genus?</p>
| 1 | 2016-08-03T03:17:54Z | 38,733,836 | <p>This will find the first entry that matches:</p>
<pre><code>print next(x for x in data if x["genus"] == title)
</code></pre>
| 2 | 2016-08-03T03:23:28Z | [
"python",
"json",
"python-2.7"
] |
how to avoid inserting duplicated rows working on pandas dataframe? | 38,733,807 | <p>I am working on pandas dataframe and mysql, my table is timeseries related like,</p>
<pre><code>symbol_id date close
1 2016-6-1 123
1 2016-6-2 133
1 2016-6-3 143
2 2016-6-1 23
2 2016-6-2 33
2 2016-6-3 43
</code></pre>
<p>When asserting a new dataframe into the table, I use </p>
<pre><code>df.to_sql(name='symbol_test1', con=engine, if_exists = 'replace', index=True)
</code></pre>
| 0 | 2016-08-03T03:18:53Z | 38,735,282 | <p>Assuming you want to remove duplicates, you can do something like this</p>
<pre><code>df.drop_duplicates(subset='symbol_id')
</code></pre>
<p>If you do not specify any subset parameter, then it by default checks for row level duplicates. </p>
<p>There are options to keep the first occurrence or last occurrence etc.
Please refer:
<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html</a></p>
| 0 | 2016-08-03T05:41:55Z | [
"python",
"mysql",
"pandas"
] |
python pandas reattach column after aggregation | 38,733,848 | <p>My DataFrame looks like this</p>
<pre><code>exams = pd.DataFrame({'id1':['1x', '1x','2x','3x','3x'], 'id2':['a','a','b','a','a'],'data':[1,2,3,4,5]})
id1 id2 data
0 1x a 1
1 1x a 2
2 2x b 3
3 3x a 4
4 3x a 5
</code></pre>
<p>Then I aggregate it to</p>
<pre><code>exams_agg = exams.groupby('id1').agg('mean')
</code></pre>
<p>Then <code>exams_agg</code> looks like </p>
<pre><code> data
id1
1x 1.5
2x 3
3x 4.5
</code></pre>
<p>I want to reattach <code>id2</code> column to <code>exams_agg</code>. So I was thinking about create a lookup table </p>
<pre><code>lookup = exams[['id1', 'id2']]
exams_agg = pd.merge(exams_agg, lookup, left_index=True, right_on='id1')
</code></pre>
<p>But since <code>lookup</code> contains duplicate pairs of ids, <code>exams_agg</code> contains duplicates as well. What is a good way to create</p>
<pre><code> data id2
id1
1x 1.5 a
2x 3 b
3x 4.5 a
</code></pre>
| 1 | 2016-08-03T03:24:56Z | 38,733,921 | <p>If a unique <code>id1</code> always corresponds to the same <code>id2</code>, you can simply add <code>id2</code> in your <code>groupby</code> :</p>
<pre><code>In [5]: df.groupby(['id1', 'id2']).agg('mean')
Out[5]:
data
id1 id2
1x a 1.5
2x b 3.0
3x a 4.5
</code></pre>
| 2 | 2016-08-03T03:33:53Z | [
"python",
"pandas",
"merge",
"aggregate"
] |
List of objects affecting other object's list | 38,733,882 | <p>I'm trying to build a graph where a vertex has a string identifier and is connected to another vertex if the string identifiers of the 2 vertices differ by only a single character. For example, 'dog' and 'dot' can be connected by an edge. I'm maintaining the graph with an adjacency list. However, after I have validated that 2 vertices can be connected, I'm appending the to_vertex object to the list of the from_vertex object and vice versa. But this is causing the lists to contain duplicate objects. Following is the code(it is quite dense):</p>
<pre><code>class vertex():
def __init__(self, distance = -1, edges = [], name = ''):
self.name = name
self.distance = distance
self.edges = edges
def create_graph(word_dict):
graph = []
num_words = len(word_dict)
v = [vertex(name = word_dict[x]) for x in range(num_words)]
for i in range(num_words):
for j in range(i + 1, num_words):
count = 0
if len(word_dict[i]) == len(word_dict[j]):
print word_dict[i], word_dict[j]
k = 0
is_valid = True
while k < len(word_dict[i]):
print word_dict[i][k], word_dict[j][k]
if word_dict[i][k] != word_dict[j][k]:
if count == 1:
is_valid = False
break
else:
count += 1
k += 1
else:
k += 1
if is_valid == True:
v[i].edges.append(v[j])
v[j].edges.append(v[i])
graph = [v[i] for i in range(num_words)]
return graph
if __name__ == '__main__':
graph = create_graph(['bat', 'cot', 'dog', 'dag', 'dot', 'cat'])
for v in graph:
print 'Vertex name ' + v.name
for edge in v.edges:
print edge.name
print '-----------------------------'
</code></pre>
<p>Following is the output of the for loop in the main:</p>
<pre><code>Vertex name bat
cat
bat
dot
cot
cat
cot
dag
dog
dot
dog
-----------------------------
Vertex name cot
cat
bat
dot
cot
cat
cot
dag
dog
dot
dog
-----------------------------
Vertex name dog
cat
bat
dot
cot
cat
cot
dag
dog
dot
dog
-----------------------------
Vertex name dag
cat
bat
dot
cot
cat
cot
dag
dog
dot
dog
-----------------------------
Vertex name dot
cat
bat
dot
cot
cat
cot
dag
dog
dot
dog
-----------------------------
Vertex name cat
cat
bat
dot
cot
cat
cot
dag
dog
dot
dog
-----------------------------
</code></pre>
<p>Through some debugging, I found that </p>
<pre><code>if is_valid == True:
v[i].edges.append(v[j])
v[j].edges.append(v[i])
</code></pre>
<p>is causing the issue but I'm just not able to wrap my head around it. It's not like I am modifying the to_vertex's edges field in the first append statement but the first append statement is affecting it too.</p>
| 1 | 2016-08-03T03:29:13Z | 38,733,931 | <p>I'm not completely sure but I think the problem is using the default value <code>[]</code> for <code>edges</code> which (I think) creates a unique object <code>[]</code> and then initialise by default to that unique object. So all your edges will essentially be the same object and when you append to one of them, you append to all the other as well. Does that make sense?</p>
<p>To avoid the problem, don't use the default init, but force <code>self.edges = []</code>.</p>
<p>Or if you really want to be able to initialise arbitrary edges, try something like:</p>
<pre><code>def __init__(self, distance = -1, edges = None, name = ''):
self.name = name
self.distance = distance
if edges is None:
edges = []
self.edges = edges
</code></pre>
<p>(Let me know if that works since I'm not sure about this...)</p>
| 1 | 2016-08-03T03:35:12Z | [
"python",
"list"
] |
What is the order of operations for 'and' and 'or'? | 38,733,885 | <p>In Python is this:</p>
<pre><code>def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if hand[0] in winning_cards and hand[1] == 'Ace':
return True
elif hand[0] == 'Ace' and hand[1] in winning_cards:
return True
else:
return False
</code></pre>
<p>the same as this...?</p>
<pre><code>def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if (hand[0] in winning_cards and hand[1]=='Ace' or
hand[0] == 'Ace' and hand[1] in winning_cards):
return True
else:
return False
</code></pre>
<p>Can I use the second code block instead of the first? It would eliminate an extra elif statement and it just seems cleaner.
My concern is how the 'and' and 'or' operators work. Are the two 'and' comparisons separate and the 'or' compares them? Is there an order of operations for 'and' and 'or'?
I ran the code and it works both ways but I want to make sure I understand exactly how the operators work.</p>
| 1 | 2016-08-03T03:29:27Z | 38,733,911 | <p>The usual advice is if you don't know, then your readers might not know either, and it would be better for everybody if you use parentheses.</p>
<pre><code>if ((hand[0] in winning_cards and hand[1]=='Ace') or
(hand[0] == 'Ace' and hand[1] in winning_cards)):
</code></pre>
<p>although you might try other formulations, such as</p>
<pre><code>if (any(card == 'Ace' for card in hand) and
any(card in winning_cards for card in hand)):
</code></pre>
<p>or writing a helper function and using</p>
<pre><code>if hascard(hand, ('Ace',)) and hascard(hand, winning_cards):
</code></pre>
| 0 | 2016-08-03T03:32:47Z | [
"python",
"if-statement",
"logical-operators"
] |
What is the order of operations for 'and' and 'or'? | 38,733,885 | <p>In Python is this:</p>
<pre><code>def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if hand[0] in winning_cards and hand[1] == 'Ace':
return True
elif hand[0] == 'Ace' and hand[1] in winning_cards:
return True
else:
return False
</code></pre>
<p>the same as this...?</p>
<pre><code>def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if (hand[0] in winning_cards and hand[1]=='Ace' or
hand[0] == 'Ace' and hand[1] in winning_cards):
return True
else:
return False
</code></pre>
<p>Can I use the second code block instead of the first? It would eliminate an extra elif statement and it just seems cleaner.
My concern is how the 'and' and 'or' operators work. Are the two 'and' comparisons separate and the 'or' compares them? Is there an order of operations for 'and' and 'or'?
I ran the code and it works both ways but I want to make sure I understand exactly how the operators work.</p>
| 1 | 2016-08-03T03:29:27Z | 38,733,915 | <p>Yes, the second code block is equivalent to the first one. According to <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">the documentation</a>, <code>or</code> has lower precedence than <code>and</code>. It means that the if statement is evaluated as</p>
<pre><code>if ((hand[0] in winning_cards and hand[1] == 'Ace') or
(hand[0] == 'Ace' and hand[1] in winning_cards)):
</code></pre>
<p>which is what you want.</p>
<p>You could return the result of that boolean expression to shorten the code:</p>
<pre><code>def blackjack_check(hand):
winning_cards = [10, 'Jack', 'Queen', 'King']
return (hand[0] in winning_cards and hand[1] == 'Ace' or
hand[0] == 'Ace' and hand[1] in winning_cards)
</code></pre>
| 4 | 2016-08-03T03:33:10Z | [
"python",
"if-statement",
"logical-operators"
] |
What is the order of operations for 'and' and 'or'? | 38,733,885 | <p>In Python is this:</p>
<pre><code>def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if hand[0] in winning_cards and hand[1] == 'Ace':
return True
elif hand[0] == 'Ace' and hand[1] in winning_cards:
return True
else:
return False
</code></pre>
<p>the same as this...?</p>
<pre><code>def blackjack_check(hand): # hand is a tuple
winning_cards = [10,'Jack','Queen','King']
if (hand[0] in winning_cards and hand[1]=='Ace' or
hand[0] == 'Ace' and hand[1] in winning_cards):
return True
else:
return False
</code></pre>
<p>Can I use the second code block instead of the first? It would eliminate an extra elif statement and it just seems cleaner.
My concern is how the 'and' and 'or' operators work. Are the two 'and' comparisons separate and the 'or' compares them? Is there an order of operations for 'and' and 'or'?
I ran the code and it works both ways but I want to make sure I understand exactly how the operators work.</p>
| 1 | 2016-08-03T03:29:27Z | 38,734,359 | <p><a href="http://stackoverflow.com/a/38733915/736937">vaultah's answer</a> addresses your actual question perfectly -- they deserve the upvote and checkmark.</p>
<p>But I think programming blackjack in every language you're learning is an excellent way to better understand it, so I threw together code to show a different way to implement the blackjack test. More for educational purposes than to actually answer your question:</p>
<pre><code># Note: sometimes an Ace should be 1, but when checking for blackjack you can always
# consider it 11
def card_value(c):
if isinstance(c, int):
return c
elif c in ['Jack', 'Queen', 'King']:
return 10
elif c == 'Ace':
return 11
def blackjack_check(hand):
hand_value = sum(card_value(c) for c in hand)
return hand_value == 21
print(blackjack_check((2, 10))) # False
print(blackjack_check((10, 10))) # False
print(blackjack_check((2, 'Ace'))) # False
print(blackjack_check(('King', 'Jack'))) # False
print(blackjack_check(('King', 'Ace'))) # True
print(blackjack_check(('Ace', 'Queen'))) # True
</code></pre>
<p>If I were to implement it today, Cards and Hands would be classes, and there'd be a <code>Hand.is_blackjack()</code> method, like:</p>
<pre><code>import random
class Card:
NAMES = {1: 'Ace', 11:'Jack', 12:'Queen', 13:'King'}
def __init__(self, pips, suit):
self.pips = pips
self.suit = suit
def __repr__(self):
name = Card.NAMES.get(self.pips, "%d" % self.pips)
return "%s of %s" % (name, self.suit)
def value(self, ace_hi=True):
# Handle Ace
if self.pips == 1:
return 11 if ace_hi else 1
return min(self.pips, 10)
class Hand(list):
def is_blackjack(self):
hand_value = sum(c.value() for c in self)
return hand_value == 21
CARDS = [Card(p,s) for p in range(1,14) for s in ['Spades', 'Hearts', 'Clubs', 'Diamonds']]
h = Hand(random.sample(CARDS, 2))
print("Hand:")
for c in h:
print(" %s" % c)
print("Blackjack? %s" % h.is_blackjack())
</code></pre>
<p>Examples:</p>
<pre>
Hand:
Jack of Spades
Ace of Spades
Blackjack? True
Hand:
Queen of Spades
9 of Diamonds
Blackjack? False
</pre>
<p>Sorry for the silly non-answer, but these are just different ideas to think about. Don't worry if they're over your head, you'll get there.</p>
| 2 | 2016-08-03T04:22:39Z | [
"python",
"if-statement",
"logical-operators"
] |
NumPy boolean array warning? | 38,733,897 | <p>I have a few numpy arrays, lets say <code>a</code>, <code>b</code>, and <code>c</code>, and have created a <code>mask</code> to apply to all of them. </p>
<p>I am trying to mask them as such:</p>
<p><code>a = a[mask]</code></p>
<p>where <code>mask</code> is a <code>bool</code> array. It is worth noting that I have verified that</p>
<p><code>len(a) = len(b) = len(c) = len(mask)</code></p>
<p>And I am getting a rather cryptic sounding warning:</p>
<p><code>FutureWarning: in the future, boolean array-likes will be handled as a boolean array index</code></p>
| 2 | 2016-08-03T03:31:10Z | 38,734,025 | <p>False == 0, and True == 1. If your mask is a list, and not an ndarray, you can get some unexpected behaviour:</p>
<pre><code>>>> a = np.array([1,2,3])
>>> mask_list = [True, False, True]
>>> a[mask_list]
__main__:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index
array([2, 1, 2])
</code></pre>
<p>where this array is made up of a[1], a[0], and a[1], just like</p>
<pre><code>>>> a[np.array([1,0,1])]
array([2, 1, 2])
</code></pre>
<p>On the other hand:</p>
<pre><code>>>> mask_array = np.array(mask_list)
>>> mask_array
array([ True, False, True], dtype=bool)
>>> a[mask_array]
array([1, 3])
</code></pre>
<p>The warning is telling you that eventually <code>a[mask_list]</code> will give you the same as <code>a[mask_array]</code> (which is probably what you wanted it to give you in the first place.)</p>
| 3 | 2016-08-03T03:45:32Z | [
"python",
"arrays",
"numpy",
"boolean",
"bitmask"
] |
Convert RDD of LabeledPoint to DataFrame toDF() Error | 38,733,928 | <p>I have a dataframe df which contains 13 values separated with comma. I want to get in df2 a dataFrame wich contains labeledPoint. firt value is label, twelve others are features. I use a split and select method to divide string with 13 value into an array of 13 values. map method allow me to create labeledPoint. Error come when i use toDF() method to convert RDD to DataFrame</p>
<pre><code>df2 = df.select(split(df[0], ',')).map(lambda x: LabeledPoint(float(x[0]),x[-12:])).toDF()
</code></pre>
<p>org.apache.spark.SparkException: Job aborted due to stage failure: </p>
<p>when I look in the stackerror I find:
IndexError: tuple index out of range.</p>
<p>in order to do test, I executed :</p>
<pre><code>display(df.select(split(df[0], ',')))
</code></pre>
<p>i obtain my 13 values in an array for each row:</p>
<pre><code>["2001.0","0.884123733793","0.610454259079","0.600498416968","0.474669212493","0.247232680947","0.357306088914","0.344136412234","0.339641227335","0.600858840135","0.425704689024","0.60491501652","0.419193351817"]
</code></pre>
<p>any Idea?</p>
| 0 | 2016-08-03T03:35:03Z | 38,864,086 | <p>The Error come from the index x[0] should be replace by x[0][0].
So :</p>
<pre><code>df2 = df.select(split(df[0], ',')).map(lambda x: LabeledPoint(float(x[0][0]), x[0][-12:])).toDF()
</code></pre>
| 1 | 2016-08-10T04:12:24Z | [
"python",
"apache-spark",
"pyspark",
"rdd",
"spark-dataframe"
] |
Losing merged cells border while editing Excel file with openpyxl | 38,734,044 | <p>I have two sheets in an Excel file and the first one is a cover sheet which I don't need to edit. There are few merged cells in the cover sheet. But when I edit the file using openpyxl not even touch the cover sheet, I lose borders from the merged cells. Is there any fix to this problem? I am using Load_workbook('excel file') to load the excel file and saving it with a different filename. </p>
| 0 | 2016-08-03T03:48:07Z | 38,736,739 | <p>This is covered in the <a href="http://openpyxl.readthedocs.io/en/latest/styles.html#styling-merged-cells" rel="nofollow">documentation of openpyxl</a>.</p>
| 1 | 2016-08-03T07:10:54Z | [
"python",
"excel",
"openpyxl"
] |
How to partially update a spark dataframe (update some rows) | 38,734,126 | <p>I am using Spark 1.5.2 with Python3. I have two dataframes in pyspark. They look like:</p>
<pre><code>old_df =
src | rank
------ | ------
a| 1
b| 1
c| 1
d| 1
e| 1
f| 1
g| 1
</code></pre>
<p>and</p>
<pre><code>new_df =
src| rank
---|-----------------
a| 0.5
b|0.3333333333333333
c|1.6666666666666665
d| 1.5
</code></pre>
<p>Now I want to update some rows in <code>old_df</code> with new values in <code>new_df</code>. My goal is to generate a new dataframe, which looks like:</p>
<pre><code> src | rank
------ | ------
a| 0.5
b|0.3333333333333333
c|1.6666666666666665
d| 1.5
e| 1
f| 1
g| 1
</code></pre>
<p>The solution I came up with is to first concatenate two dataframes and then perform <code>dropduplicates</code>.</p>
<pre><code>new_df = new_df.unionAll(old_df).dropDuplicates(['src'])
</code></pre>
<p>However, to my disappointment, Spark didn't keep the first record when performing the "drop" action, which resulted in a wrong dataframe.</p>
<p>Is there any approache to fix it? Or any alternative way to get the job done?</p>
| 0 | 2016-08-03T03:54:12Z | 38,736,989 | <p>You can resolve this with sql functions and join..</p>
<pre><code>import org.apache.spark.sql.funtions._
odl_df.join(new_df, "src")
.withColumn("finalRank",
when(new_df("rank").isNull, odl_df("rank"))
.otherwise(new_df("rank"))
.drop(new_df("rank"))
.drop(odl_df("rank"))
.withColumnRenamed("finalRank", "rank")
</code></pre>
<p>This assert that new rank is always in final df.</p>
| 0 | 2016-08-03T07:23:21Z | [
"python",
"apache-spark"
] |
Python File I/O issue: Bypassing For Loop? | 38,734,209 | <pre><code>def findWord(word):
f = open("words.txt", "r")
given_line = f.readlines()
for line in f:
if str(word) in line:
part = line[0]
## print(line+"\n"+str(word)+" is a "+part)
return True
else:
return False
print("fail")
f.close()
def partSpeech(inX):
f = open("words.txt", "a")
inX = inX.split()
for i in inX:
i = i.lower()
if(findWord(i) == False):
if "ify" in i[-3:] or "ate" in i[-3:] or "ize" in i[-3:] or "ing" in i[-3:] or "en" in i[-2:] or "ed" in i[-2:]:
f.write("\nV"+i)
elif "ment" in i[-4:] or "ion" in i[-3:] or "acy" in i[-3:] or "ism" in i[-3:] or "ist" in i[-3:] or "ness" in i[-3:] or "ity" in i[-3:] or "or" in i[-2:] or "y" in i[-1:]:
f.write("\nN"+i)
elif "ly" in i[-2:]:
f.write("\nD"+i)
else:
print(i+" was already in the database.")
</code></pre>
<p>Essentially, my issue with the above happens at "for line in f:". The problem is that, after putting numerous markers (prints to determine where it's getting) throughout the code, the for loop isn't even ran! I don't understand, really, whether or not it's just that line or f aren't being counted or what, but.</p>
<p>The goal is to, in this snippet, take a bunch of words, loop them through a system that checks whether or not they're already in the given text file (the part I'm having issues with) and then, if they're not, append them with a part of speech tag.</p>
<p>EDIT: I'm not getting an error at all, it's just that it's not running the For Loop like it should. Every function is called at some point or another, partSpeech is called toward the end with a small list of words.</p>
<p>EDIT 2: PROGRESS! Sort of. The text file was empty, so it wasn't reading any line whatsoever. Now, however, it's not taking into account whether or not the words are already there. It just skips over them.</p>
| 0 | 2016-08-03T04:05:16Z | 38,734,257 | <p>First off, delete this line:</p>
<pre><code>given_line = f.readlines()
</code></pre>
<p>This is reading the contents of the file into an unused <code>given_line</code> variable and leaving <code>f</code> positioned at the end of the file. Your <code>for</code> loop therefore has nothing to loop over.</p>
<hr>
<p>Your <code>findWord()</code> function is doing a number of odd/problematic things, any of which might be causing the behavior you're assuming means the for loop isn't even running. Here's a possible re-implementation:</p>
<pre><code>def findWord(word):
# it seems odd to pass a "word" parameter that isn't a str, but if you must handle that
# case you only need to do the cast once
word = str(word)
# always use the with statement to handle resources like files
# see https://www.python.org/dev/peps/pep-0343/
with open("words.txt", "r") as f:
for line in f:
if word in line:
return True
return False # only return False after the loop; once we've looked at every line
# no need to call f.close(), the with statement does it for us
</code></pre>
| 0 | 2016-08-03T04:10:13Z | [
"python",
"io"
] |
Python File I/O issue: Bypassing For Loop? | 38,734,209 | <pre><code>def findWord(word):
f = open("words.txt", "r")
given_line = f.readlines()
for line in f:
if str(word) in line:
part = line[0]
## print(line+"\n"+str(word)+" is a "+part)
return True
else:
return False
print("fail")
f.close()
def partSpeech(inX):
f = open("words.txt", "a")
inX = inX.split()
for i in inX:
i = i.lower()
if(findWord(i) == False):
if "ify" in i[-3:] or "ate" in i[-3:] or "ize" in i[-3:] or "ing" in i[-3:] or "en" in i[-2:] or "ed" in i[-2:]:
f.write("\nV"+i)
elif "ment" in i[-4:] or "ion" in i[-3:] or "acy" in i[-3:] or "ism" in i[-3:] or "ist" in i[-3:] or "ness" in i[-3:] or "ity" in i[-3:] or "or" in i[-2:] or "y" in i[-1:]:
f.write("\nN"+i)
elif "ly" in i[-2:]:
f.write("\nD"+i)
else:
print(i+" was already in the database.")
</code></pre>
<p>Essentially, my issue with the above happens at "for line in f:". The problem is that, after putting numerous markers (prints to determine where it's getting) throughout the code, the for loop isn't even ran! I don't understand, really, whether or not it's just that line or f aren't being counted or what, but.</p>
<p>The goal is to, in this snippet, take a bunch of words, loop them through a system that checks whether or not they're already in the given text file (the part I'm having issues with) and then, if they're not, append them with a part of speech tag.</p>
<p>EDIT: I'm not getting an error at all, it's just that it's not running the For Loop like it should. Every function is called at some point or another, partSpeech is called toward the end with a small list of words.</p>
<p>EDIT 2: PROGRESS! Sort of. The text file was empty, so it wasn't reading any line whatsoever. Now, however, it's not taking into account whether or not the words are already there. It just skips over them.</p>
| 0 | 2016-08-03T04:05:16Z | 38,734,286 | <p><code>for line in f:</code> never runs because you have already read the file contents and the cursor is at the end of the file.</p>
<p>You should do:</p>
<p><code>for line in given_line:</code></p>
<p>Or you could put this statement just before your for loop:</p>
<p><code>f.seek(0)</code></p>
<p>It places the cursor back at the beginning of the file.</p>
| 0 | 2016-08-03T04:13:23Z | [
"python",
"io"
] |
Creating an list of dictionaries that hold a variable sized array | 38,734,234 | <p>I'm trying to create the following data structure (that's not optimal, I know, but is necessary given my input data):</p>
<p>A list of 100 dictionaries with the same two keys, "x" and "y", where each key holds a variable length numpy array. "y" holds a vector and "x" holds an array of images, so an example shape for x could be 10 x 3 x 10 x 50, or, 10 RGB images of size 10 by 50. An example shape for the corresponding y would be 10, because the initial lengths of the x and y need to be the same. If I have only 8 images, then the length of y is also 8, etc.</p>
<p>I want to preinitialize this structure so I can fill it in with changed data values, and do it so that I can set the size of the variable length "x" and "y" arrays for each dictionary based on a separate piece of input data. I know that I can set the dictionary with something like this:</p>
<pre><code>imageArray = np.zeros(10,3,10,50)
vectorNumbers = np.zeros(10)
output = [{'x':imageArray,'y':vectorNumbers}]
</code></pre>
<p>So that should create a single dictionary, but if I have something like an array with the lengths of the dictionary values "x" and "y", how can I use something like this:</p>
<pre><code> output = [{'x':imageArray,'y':vectorNumbers} for k in range(listLength)]
</code></pre>
<p>But ensure that the imageArray length would be [variable,3,10,50] and the vectorNumbers length would be [variable], where variable is the number stored in another list that I can access thanks to the k counter above.</p>
| 1 | 2016-08-03T04:08:22Z | 38,734,342 | <p>I assume the input list of lengths is a list of pairs, or something similar.</p>
<pre><code>input_lengths = [(12,17), (8,50), (2,7)]
pre_filled_list = [{'x' : [None]*x, 'y' : [None]*y} for x,y in input_lengths]
print(pre_filled_list)
</code></pre>
<p>Pre_filled list is a list of dictionaries, each with two keys; each value is a list of None of the desired length.</p>
| 0 | 2016-08-03T04:20:11Z | [
"python",
"arrays",
"list",
"numpy",
"dictionary"
] |
Creating an list of dictionaries that hold a variable sized array | 38,734,234 | <p>I'm trying to create the following data structure (that's not optimal, I know, but is necessary given my input data):</p>
<p>A list of 100 dictionaries with the same two keys, "x" and "y", where each key holds a variable length numpy array. "y" holds a vector and "x" holds an array of images, so an example shape for x could be 10 x 3 x 10 x 50, or, 10 RGB images of size 10 by 50. An example shape for the corresponding y would be 10, because the initial lengths of the x and y need to be the same. If I have only 8 images, then the length of y is also 8, etc.</p>
<p>I want to preinitialize this structure so I can fill it in with changed data values, and do it so that I can set the size of the variable length "x" and "y" arrays for each dictionary based on a separate piece of input data. I know that I can set the dictionary with something like this:</p>
<pre><code>imageArray = np.zeros(10,3,10,50)
vectorNumbers = np.zeros(10)
output = [{'x':imageArray,'y':vectorNumbers}]
</code></pre>
<p>So that should create a single dictionary, but if I have something like an array with the lengths of the dictionary values "x" and "y", how can I use something like this:</p>
<pre><code> output = [{'x':imageArray,'y':vectorNumbers} for k in range(listLength)]
</code></pre>
<p>But ensure that the imageArray length would be [variable,3,10,50] and the vectorNumbers length would be [variable], where variable is the number stored in another list that I can access thanks to the k counter above.</p>
| 1 | 2016-08-03T04:08:22Z | 38,734,562 | <p>What about:</p>
<pre><code>import numpy as np
dims = [(42,43), (46,9), (47,49), (60,14)]
output = [{'x':np.zeros((x,3,10,50)), 'y':np.zeros((y,))} for (x,y) in dims]
print(len(output)) # 4, matches len(dims)
print(type(output[0]['x'])) # <type 'numpy.ndarray'>
print(type(output[0]['y'])) # <type 'numpy.ndarray'>
print(output[0]['x'].shape) # (42, 3, 10, 50)
# 42 is from the first element of the first tuple in dims
print(output[0]['y'].shape) # (43,)
# 43 is from the second element of the first tuple in dims
print(output[1]['x'].shape) # (46, 3, 10, 50)
print(output[1]['y'].shape) # (9,)
</code></pre>
<p>The arrays are in the dictionaries, which are in the list. All zeros of the dimensions (I think) you want.</p>
<p>If you want something closer to what you had, with <code>range(listLength)</code>, these four lines produce the same output as above:</p>
<pre><code>xd = [42, 46, 47, 60]
yd = [43, 9, 49, 14]
listLength = 4
output=[{'x':np.zeros((xd[k],3,10,50)),'y':np.zeros((yd[k],))} for k in range(listLength)]
</code></pre>
| 0 | 2016-08-03T04:42:27Z | [
"python",
"arrays",
"list",
"numpy",
"dictionary"
] |
Static classes being initialised on import. How does python 2 initialise static classes on import | 38,734,294 | <p>I am trying to introduce python 3 support for the package <a href="https://pypi.python.org/pypi/mime" rel="nofollow">mime</a> and the code is doing something I have never seen before. </p>
<p>There is a class <code>Types()</code> that is used in the package as a static class. </p>
<pre><code>class Types(with_metaclass(ItemMeta, object)): # I changed this for 2-3 compatibility
type_variants = defaultdict(list)
extension_index = defaultdict(list)
# __metaclass__ = ItemMeta # unnessecary now
def __init__(self, data_version=None):
self.data_version = data_version
</code></pre>
<p>The <code>type_variants</code> defaultdict is what is getting filled in python 2 but not in 3. </p>
<p>It very much seems to be getting filled by this class when is in a different file called <code>mime_types.py</code>.</p>
<pre><code>class MIMETypes(object):
_types = Types(VERSION)
def __repr__(self):
return '<MIMETypes version:%s>' % VERSION
@classmethod
def load_from_file(cls, type_file):
data = open(type_file).read()
data = data.split('\n')
mime_types = Types()
for index, line in enumerate(data):
item = line.strip()
if not item:
continue
try:
ret = TEXT_FORMAT_RE.match(item).groups()
except Exception as e:
__parsing_error(type_file, index, line, e)
(unregistered, obsolete, platform, mediatype, subtype, extensions,
encoding, urls, docs, comment) = ret
if mediatype is None:
if comment is None:
__parsing_error(type_file, index, line, RuntimeError)
continue
extensions = extensions and extensions.split(',') or []
urls = urls and urls.split(',') or []
mime_type = Type('%s/%s' % (mediatype, subtype))
mime_type.extensions = extensions
...
mime_type.url = urls
mime_types.add(mime_type) # instance of Type() is being filled?
return mime_types
</code></pre>
<p>The function <code>startup()</code> is being run whenever <code>mime_types.py</code> is imported and it does this. </p>
<pre><code>def startup():
global STARTUP
if STARTUP:
type_files = glob(join(DIR, 'types', '*'))
type_files.sort()
for type_file in type_files:
MIMETypes.load_from_file(type_file) # class method is filling Types?
STARTUP = False
</code></pre>
<p>This all seems pretty weird to me. The <code>MIMETypes</code> class first creates an instance of <code>Types()</code> on the first line. <code>_types = Types(VERSION)</code>. It then seems to do nothing with this instance and only use the <code>mime_types</code> instance created in the <code>load_from_file()</code> class method. <code>mime_types = Types()</code>. </p>
<p>This sort of thing vaguely reminds me of javascript class construction. How is the instance <code>mime_types</code> filling <code>Types.type_variants</code> so that when it is imported like this.</p>
<p><code>from mime import Type, Types</code></p>
<p>The class's <code>type_variants</code> defaultdict can be used. And why isn't this working in python 3?</p>
<p>EDIT: </p>
<p>Adding extra code to show how <code>type_variants</code> is filled </p>
<pre><code>(In "Types" Class)
@classmethod
def add_type_variant(cls, mime_type):
cls.type_veriants[mime_type.simplified].append(mime_type)
@classmethod
def add(cls, *types):
for mime_type in types:
if isinstance(mime_type, Types):
cls.add(*mime_type.defined_types())
else:
mts = cls.type_veriants.get(mime_type.simplified)
if mts and mime_type in mts:
Warning('Type %s already registered as a variant of %s.',
mime_type, mime_type.simplified)
cls.add_type_variant(mime_type)
cls.index_extensions(mime_type)
</code></pre>
<p>You can see that <code>MIMETypes</code> uses the <code>add()</code> classmethod.</p>
| 2 | 2016-08-03T04:13:54Z | 38,734,950 | <p>Without posting more of your code, it's hard to say. I will say that I was able to get that package ported to Python 3 with only a few changes (print statement -> function, <code>basestring</code> -> <code>str</code>, adding a dot before same-package imports, and a really ugly hack to compensate for their love of <code>cmp</code>:</p>
<pre><code>def cmp(x,y):
if isinstance(x, Type): return x.__cmp__(y)
if isinstance(y, Type): return y.__cmp__(x) * -1
return 0 if x == y else (1 if x > y else -1)
</code></pre>
<p>Note, I'm not even sure this is correct.</p>
<p>Then</p>
<pre><code>import mime
print(mime.Types.type_veriants) # sic
</code></pre>
<p>printed out a 1590 entry <code>defaultdict</code>.</p>
<hr>
<p>Regarding your question about <code>MIMETypes._types</code> not being used, I agree, it's not.</p>
<p>Regarding your question about <em>how</em> the dictionary is being populated, it's quite simple, and you've identified most of it.</p>
<pre><code>import mime
</code></pre>
<p>Imports the package's <code>__init__.py</code> which contains the line:</p>
<pre><code>from .mime_types import MIMETypes, VERSION
</code></pre>
<p>And <code>mime_types.py</code> includes the lines:</p>
<pre><code>def startup():
global STARTUP
if STARTUP:
type_files = glob(join(DIR, 'types', '*'))
type_files.sort()
for type_file in type_files:
MIMETypes.load_from_file(type_file)
STARTUP = False
startup()
</code></pre>
<p>And <code>MIMETypes.load_from_file()</code> has the lines:</p>
<pre><code>mime_types = Types()
#...
for ... in ...:
mime_types.add(mime_type)
</code></pre>
<p>And <code>Types.add():</code> has the line:</p>
<pre><code>cls.add_type_variant(mime_type)
</code></pre>
<p>And that classmethod contains:</p>
<pre><code>cls.type_veriants[mime_type.simplified].append(mime_type)
</code></pre>
| 2 | 2016-08-03T05:18:09Z | [
"python",
"class",
"import",
"static"
] |
Python regex - Replace bracketed text with contents of brackets | 38,734,335 | <p>I'm trying to write a Python function that replaces instances of text surrounded with curly braces with the contents of the braces, while leaving empty brace-pairs alone. For example: </p>
<p><code>foo {} bar {baz}</code> would become <code>foo {} bar baz</code>. </p>
<p>The pattern that I've created to match this is <code>{[^{}]+}</code>, i.e. some text that doesn't contain curly braces (to prevent overlapping matches) surrounded by a set of curly braces.</p>
<p>The obvious solution is to use <code>re.sub</code> with my pattern, and I've found that I can reference the matched text with <code>\g<0></code>:</p>
<pre><code>>>> re.sub("{[^{}]+}", "A \g<0> B", "foo {} bar {baz}")
'foo {} bar A {baz} B'
</code></pre>
<p>So that's no problem. However, I'm stuck on how to trim the brackets from the referenced text. If I try applying a range to the replacement string:</p>
<pre><code>>>> re.sub("{[^{}]+}", "\g<0>"[1:-1], "foo{}bar{baz}")
'foo{}barg<0'
</code></pre>
<p>The range is applied before the <code>\g<0></code> is resolved to the matched text, and it trims the leading <code>\</code> and trailing <code>></code>, leaving just <code>g<0</code>, which has no special meaning. </p>
<p>I also tried defining a function to perform the trimming:</p>
<pre><code>def trimBraces(string):
return string[1:-1]
</code></pre>
<p>But, unsurprisingly, that didn't change anything.</p>
<pre><code>>>> re.sub("{[^{}]+}", trimBraces("\g<0>"), "foo{}bar{baz}")
'foo{}barg<0'
</code></pre>
<p>What am I missing here? Many thanks in advance.</p>
| 3 | 2016-08-03T04:19:33Z | 38,734,403 | <p>You can use a <em>capturing group</em> to replace a part of the match:</p>
<pre><code>>>> re.sub(r"{([^{}]+)}", r"\1", "foo{}bar{baz}")
'foo{}barbaz'
>>> re.sub(r"{([^{}]+)}", r"\1", "foo {} bar {baz}")
'foo {} bar baz'
</code></pre>
| 2 | 2016-08-03T04:26:18Z | [
"python",
"regex",
"string",
"substitution",
"backreference"
] |
Python regex - Replace bracketed text with contents of brackets | 38,734,335 | <p>I'm trying to write a Python function that replaces instances of text surrounded with curly braces with the contents of the braces, while leaving empty brace-pairs alone. For example: </p>
<p><code>foo {} bar {baz}</code> would become <code>foo {} bar baz</code>. </p>
<p>The pattern that I've created to match this is <code>{[^{}]+}</code>, i.e. some text that doesn't contain curly braces (to prevent overlapping matches) surrounded by a set of curly braces.</p>
<p>The obvious solution is to use <code>re.sub</code> with my pattern, and I've found that I can reference the matched text with <code>\g<0></code>:</p>
<pre><code>>>> re.sub("{[^{}]+}", "A \g<0> B", "foo {} bar {baz}")
'foo {} bar A {baz} B'
</code></pre>
<p>So that's no problem. However, I'm stuck on how to trim the brackets from the referenced text. If I try applying a range to the replacement string:</p>
<pre><code>>>> re.sub("{[^{}]+}", "\g<0>"[1:-1], "foo{}bar{baz}")
'foo{}barg<0'
</code></pre>
<p>The range is applied before the <code>\g<0></code> is resolved to the matched text, and it trims the leading <code>\</code> and trailing <code>></code>, leaving just <code>g<0</code>, which has no special meaning. </p>
<p>I also tried defining a function to perform the trimming:</p>
<pre><code>def trimBraces(string):
return string[1:-1]
</code></pre>
<p>But, unsurprisingly, that didn't change anything.</p>
<pre><code>>>> re.sub("{[^{}]+}", trimBraces("\g<0>"), "foo{}bar{baz}")
'foo{}barg<0'
</code></pre>
<p>What am I missing here? Many thanks in advance.</p>
| 3 | 2016-08-03T04:19:33Z | 38,737,329 | <p>When you use <code>"\g<0>"[1:-1]</code> as a replacement pattern, you only slice the <code>"\g<0>"</code> <em>string</em>, not the actual value this backreference refers to.</p>
<p>If you need to use your "trimming" approach, you need to pass the match data object to the <code>re.sub</code>:</p>
<pre><code>re.sub("{[^{}]+}", lambda m: m.group()[1:-1], "foo{}bar{baz}")
# => foo{}barbaz
</code></pre>
<p>See <a href="https://ideone.com/0mGwiL" rel="nofollow">this Python demo</a>. Note that <code>m.group()</code> stands for the <code>\g<0></code> in your pattern, i.e. the whole match value.</p>
<p><em>However</em>, using <a href="http://www.regular-expressions.info/brackets.html" rel="nofollow"><strong>capturing groups</strong></a> is a more "organic" solution, see <a href="http://stackoverflow.com/a/38734403/3832970">alexce's solution</a>.</p>
| 2 | 2016-08-03T07:39:42Z | [
"python",
"regex",
"string",
"substitution",
"backreference"
] |
Pandas: Faster way to iterate through a dataframe and add new data based on operations | 38,734,369 | <p>I want to pandas to look into values in 2 columns in each row of df1, look for the match in another df2, and paste this in a new column in df1 in the same row and continue</p>
<pre><code>alp=list("ABCDEFGHIJKLMNOPQRTSUVQXYZ")
df1['NewCol'] = (np.random.choice(alp)) #create new col and input random values
for i in range(len(df1['code1'])):
a = df1['code2'].iloc[i].upper()
b = df1['code1'].str[-3:].iloc[i]
df1['NewCol'].iloc[i] = df2.loc[b,a]
df1['code3'] = df1[['code3','NewCol']].max(axis=1)
df1 =df1.drop('NewCol',axis=1)
</code></pre>
<p>My inputs as below:
df1:</p>
<pre><code> code1 code2 code3
0 XXXHYG a 12
1 XXXTBG a 23
2 XXXECT b 34
3 XXXKOL b 45
4 XXXBTW c 56
</code></pre>
<p>df2:</p>
<pre><code> A B C D E
HYG 33 38 40 41 30
TBG 20 46 41 43 45
ECT 53 42 39 34 45
KOL 45 51 54 47 30
BTW 37 36 49 48 58
</code></pre>
<p>output needed:</p>
<pre><code> code1 code2 code3
0 XXXHYG a 33
1 XXXTBG a 23
2 XXXECT b 42
3 XXXKOL b 51
4 XXXBTW c 56
</code></pre>
<p>When I do this over just 4200 rows in df1, it takes 222 seconds for just the loop.. there has got to be a way to utilize the power of pandas to do this faster?</p>
<p>thanks a lot for your time!</p>
| 1 | 2016-08-03T04:23:20Z | 38,734,663 | <p>You could use <code>apply</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">docs</a>), but a faster way to do this if you have a lot of data would be to create a version of <code>df2</code> with a <code>MultiIndex</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html" rel="nofollow">docs</a>) using <code>stack</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow">docs</a>) and look up values on this new DataFrame.</p>
<pre><code>df3 = df1.copy()
tups = list(zip(df1['code1'].str[-3:], df1['code2'].str.upper()))
df3['code3'] = df2.stack()[tups].values
print(df3)
</code></pre>
<p>outputs</p>
<pre><code> code1 code2 code3
0 XXXHYG a 33
1 XXXTBG a 20
2 XXXECT b 42
3 XXXKOL b 51
4 XXXBTW c 49
</code></pre>
| 0 | 2016-08-03T04:53:50Z | [
"python",
"pandas"
] |
How to plot a two column pandas dataframe's elements as an histogram? | 38,734,460 | <p>I have the following pandas dataframe:</p>
<pre><code> A B
1 3
0 2
1 4
0 1
0 3
</code></pre>
<p>I would like to plot the frequency of B instnaces given A, something like this:</p>
<pre><code> |
|
| __
B | | |
| ___ | |
| | | | |
| | | | |
|__|_|__|__|______________
A
</code></pre>
<p>Thus, I tried the following:</p>
<pre><code>df2.groupby([df.A, df.B]).count().plot(kind="bar")
</code></pre>
<p>However, I am getting the following exception:</p>
<pre><code>TypeError: Empty 'DataFrame': no numeric data to plot
</code></pre>
<p>Therefore, my question is how to plot the frequency of the elements in B given the frequency of A?.</p>
| 3 | 2016-08-03T04:31:54Z | 38,734,570 | <p>I'm not entirely sure what you mean by "plot the frequency of the elements in B given the frequency of A", but this gives the expected output :</p>
<pre><code>In [4]: df
Out[4]:
A B
3995 1 3
3996 0 2
3997 1 4
3998 0 1
3999 0 3
In [8]: df['data'] = df['A']*df['B']
In [9]: df
Out[9]:
A B data
3995 1 3 3
3996 0 2 0
3997 1 4 4
3998 0 1 0
3999 0 3 0
In [10]: df[['A','data']].plot(kind='bar', x='A', y='data')
Out[10]: <matplotlib.axes._subplots.AxesSubplot at 0x7fde7eebb9e8>
In [11]: plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/FJXAb.png" rel="nofollow"><img src="http://i.stack.imgur.com/FJXAb.png" alt="enter image description here"></a></p>
| 2 | 2016-08-03T04:43:37Z | [
"python",
"python-3.x",
"pandas",
"matplotlib"
] |
How to plot a two column pandas dataframe's elements as an histogram? | 38,734,460 | <p>I have the following pandas dataframe:</p>
<pre><code> A B
1 3
0 2
1 4
0 1
0 3
</code></pre>
<p>I would like to plot the frequency of B instnaces given A, something like this:</p>
<pre><code> |
|
| __
B | | |
| ___ | |
| | | | |
| | | | |
|__|_|__|__|______________
A
</code></pre>
<p>Thus, I tried the following:</p>
<pre><code>df2.groupby([df.A, df.B]).count().plot(kind="bar")
</code></pre>
<p>However, I am getting the following exception:</p>
<pre><code>TypeError: Empty 'DataFrame': no numeric data to plot
</code></pre>
<p>Therefore, my question is how to plot the frequency of the elements in B given the frequency of A?.</p>
| 3 | 2016-08-03T04:31:54Z | 38,734,736 | <p>I believe if you are trying to plot the frequency of occurrence of values in column b, this might help.</p>
<pre><code>from collections import Counter
vals = list(df['b'])
cntr = Counter(vals)
# Out[30]: Counter({1: 1, 2: 1, 3: 2, 4: 1})
vals = [(key,cntr[key]) for key in cntr]
x = [tup[0] for tup in vals]
y = [tup[1] for tup in vals]
plt.bar(x,y,label='Bar1',color='red')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/mnXcE.png" rel="nofollow"><img src="http://i.stack.imgur.com/mnXcE.png" alt="Plot"></a></p>
<p>Another way using <code>histogram</code> from <code>matplotlib</code>.
First declare a bins array, which are basically buckets into which your values will go into.</p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
l = [(1,3),(0,2),(1,4),(0,1),(0,3)]
df = pd.DataFrame(l)
df.columns = ['a','b']
bins = [1,2,3,4,5] #ranges of data
plt.hist(list(df['b']),bins,histtype='bar',rwidth=0.8)
</code></pre>
| 1 | 2016-08-03T05:01:22Z | [
"python",
"python-3.x",
"pandas",
"matplotlib"
] |
How to plot a two column pandas dataframe's elements as an histogram? | 38,734,460 | <p>I have the following pandas dataframe:</p>
<pre><code> A B
1 3
0 2
1 4
0 1
0 3
</code></pre>
<p>I would like to plot the frequency of B instnaces given A, something like this:</p>
<pre><code> |
|
| __
B | | |
| ___ | |
| | | | |
| | | | |
|__|_|__|__|______________
A
</code></pre>
<p>Thus, I tried the following:</p>
<pre><code>df2.groupby([df.A, df.B]).count().plot(kind="bar")
</code></pre>
<p>However, I am getting the following exception:</p>
<pre><code>TypeError: Empty 'DataFrame': no numeric data to plot
</code></pre>
<p>Therefore, my question is how to plot the frequency of the elements in B given the frequency of A?.</p>
| 3 | 2016-08-03T04:31:54Z | 38,734,831 | <p>Here is my way:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([[1,3],[0,2],[1,4],[0,1],[0,3]])
df.columns = ['A', 'B']
x = df.loc[:,'A'].values
y = df.loc[:,'B'].values
plt.bar(x, y, label = 'Bar', align='center',)
plt.xticks(x)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/dllft.png" rel="nofollow"><img src="http://i.stack.imgur.com/dllft.png" alt="enter image description here"></a></p>
| 1 | 2016-08-03T05:09:37Z | [
"python",
"python-3.x",
"pandas",
"matplotlib"
] |
How to plot a two column pandas dataframe's elements as an histogram? | 38,734,460 | <p>I have the following pandas dataframe:</p>
<pre><code> A B
1 3
0 2
1 4
0 1
0 3
</code></pre>
<p>I would like to plot the frequency of B instnaces given A, something like this:</p>
<pre><code> |
|
| __
B | | |
| ___ | |
| | | | |
| | | | |
|__|_|__|__|______________
A
</code></pre>
<p>Thus, I tried the following:</p>
<pre><code>df2.groupby([df.A, df.B]).count().plot(kind="bar")
</code></pre>
<p>However, I am getting the following exception:</p>
<pre><code>TypeError: Empty 'DataFrame': no numeric data to plot
</code></pre>
<p>Therefore, my question is how to plot the frequency of the elements in B given the frequency of A?.</p>
| 3 | 2016-08-03T04:31:54Z | 38,734,967 | <p>Sounds like this is what you want:
You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow">Series.value_counts()</a></p>
<pre><code>print(df['B'].value_counts().plot(kind='bar'))
</code></pre>
<p><a href="http://i.stack.imgur.com/5Qdwj.png" rel="nofollow"><img src="http://i.stack.imgur.com/5Qdwj.png" alt="enter image description here"></a></p>
<p>If you don't want the <code>value_count</code> sorted, you can do this:</p>
<pre><code>print(df['B'].value_counts(sort=False).plot(kind='bar'))
</code></pre>
<p><a href="http://i.stack.imgur.com/lpwz9.png" rel="nofollow"><img src="http://i.stack.imgur.com/lpwz9.png" alt="enter image description here"></a></p>
| 3 | 2016-08-03T05:19:52Z | [
"python",
"python-3.x",
"pandas",
"matplotlib"
] |
Python 2 and Python 3 - Running in Command Prompt | 38,734,521 | <p>Having various projects in both Python 2 and Python 3 (with both python versions installed), I was looking for a more intuitive way to run scripts via Command Prompt than
<code>py -3 script.py</code>.</p>
<p>Python 2 already took <code>python script.py</code>, so ideally <code>python3 script.py</code> should invoke Python 3.</p>
<p>My question: How can I add <code>python3</code> as a Command Prompt command?</p>
| 0 | 2016-08-03T04:37:34Z | 38,734,522 | <p>Searching did not yield good results, so I thought I should share the process I took with anyone looking for this in the future.</p>
<ol>
<li>Make sure the Python 3 folder is present in the PATH environment variable. </li>
<li>Locate the "python.exe" file in the Python 3 folder.</li>
<li>Copy and Paste the "python.exe" file within the Python 3 folder.</li>
<li>Rename the copied file to "python3" (or whatever you want the command to be).</li>
</ol>
<p>Now, when you input <code>python3 script.py</code> to Command Prompt, the script will run through the copied Python 3 file.</p>
<p>Also, by copying python.exe (instead of renaming it) you allow other interpreters - such as PyCharm - to continue using their default "python.exe" path settings.</p>
<p>I hope this helps!</p>
| 3 | 2016-08-03T04:37:34Z | [
"python",
"windows",
"command-prompt"
] |
Simplifying the extraction of particular string patterns with a multiple if-else and split() | 38,734,649 | <p>Given a string like this:</p>
<pre><code>>>> s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
</code></pre>
<p>First I want to split the string by underscores, i.e.:</p>
<pre><code>>>> s.split('_')
['X/NOUN/dobj>',
'hold/VERB/ROOT',
'<membership/NOUN/dobj',
'<with/ADP/prep',
'<Y/PROPN/pobj',
'>,/PUNCT/punct']
</code></pre>
<p>We assume that the underscore is solely used as the delimiter and never exist as part of the substring we want to extract. </p>
<p>Then I need to first checks whether each of these "nodes" in my splitted list above starts of ends with a '>', '<', then remove it and put the appropriate bracket as the end of the sublist, something like:</p>
<pre><code>result = []
nodes = s.split('_')
for node in nodes:
if node.endswith('>'):
result.append( node[:-1].split('/') + ['>'] )
elif node.startswith('>'):
result.append( node[1:].split('/') + ['>'] )
elif node.startswith('<'):
result.append( node[1:].split('/') + ['<'] )
elif node.endswith('<'):
result.append( node[:-1].split('/') + ['<'] )
else:
result.append( node.split('/') + ['-'] )
</code></pre>
<p>And if it doesn't start of ends with an angular bracket then we append <code>-</code> to the end of the sublist.</p>
<p>[out]:</p>
<pre><code>[['X', 'NOUN', 'dobj', '>'],
['hold', 'VERB', 'ROOT', '-'],
['membership', 'NOUN', 'dobj', '<'],
['with', 'ADP', 'prep', '<'],
['Y', 'PROPN', 'pobj', '<'],
[',', 'PUNCT', 'punct', '>']]
</code></pre>
<p><strong>Given the original input string, is there a less verbose way to get to the result? Maybe with regex and groups?</strong></p>
| 2 | 2016-08-03T04:51:42Z | 38,734,996 | <pre><code>s = 'X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct'
def get_sentinal(node):
if not node:
return '-'
# Assuming the node won't contain both '<' and '>' at a same time
for index in [0, -1]:
if node[index] in '<>':
return node[index]
return '-'
results = [
node.strip('<>').split('/') + [get_sentinal(node)]
for node in s.split('_')
]
print(results)
</code></pre>
<p>This does not make it significantly <em>shorter</em>, but personally I'd think it's somehow <em>a little bit cleaner</em>.</p>
| 3 | 2016-08-03T05:21:32Z | [
"python",
"regex",
"string",
"split"
] |
Simplifying the extraction of particular string patterns with a multiple if-else and split() | 38,734,649 | <p>Given a string like this:</p>
<pre><code>>>> s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
</code></pre>
<p>First I want to split the string by underscores, i.e.:</p>
<pre><code>>>> s.split('_')
['X/NOUN/dobj>',
'hold/VERB/ROOT',
'<membership/NOUN/dobj',
'<with/ADP/prep',
'<Y/PROPN/pobj',
'>,/PUNCT/punct']
</code></pre>
<p>We assume that the underscore is solely used as the delimiter and never exist as part of the substring we want to extract. </p>
<p>Then I need to first checks whether each of these "nodes" in my splitted list above starts of ends with a '>', '<', then remove it and put the appropriate bracket as the end of the sublist, something like:</p>
<pre><code>result = []
nodes = s.split('_')
for node in nodes:
if node.endswith('>'):
result.append( node[:-1].split('/') + ['>'] )
elif node.startswith('>'):
result.append( node[1:].split('/') + ['>'] )
elif node.startswith('<'):
result.append( node[1:].split('/') + ['<'] )
elif node.endswith('<'):
result.append( node[:-1].split('/') + ['<'] )
else:
result.append( node.split('/') + ['-'] )
</code></pre>
<p>And if it doesn't start of ends with an angular bracket then we append <code>-</code> to the end of the sublist.</p>
<p>[out]:</p>
<pre><code>[['X', 'NOUN', 'dobj', '>'],
['hold', 'VERB', 'ROOT', '-'],
['membership', 'NOUN', 'dobj', '<'],
['with', 'ADP', 'prep', '<'],
['Y', 'PROPN', 'pobj', '<'],
[',', 'PUNCT', 'punct', '>']]
</code></pre>
<p><strong>Given the original input string, is there a less verbose way to get to the result? Maybe with regex and groups?</strong></p>
| 2 | 2016-08-03T04:51:42Z | 38,735,351 | <p>Yes, although it's not pretty:</p>
<pre><code>s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
import re
out = []
for part in s.split('_'):
Left, Mid, Right = re.search('^([<>]|)(.*?)([<>]|)$', part).groups()
tail = ['-'] if not Left+Right else [Left+Right]
out.append(Mid.split('/') + tail)
print(out)
</code></pre>
<p>Try online: <a href="https://repl.it/Civg" rel="nofollow">https://repl.it/Civg</a></p>
<p>It relies on two main things:</p>
<ol>
<li>a regex pattern which always makes three groups <code>()()()</code> where the edge groups only look for characters <code><</code>, <code>></code> or nothing <code>([<>]|)</code>, and the middle matches everything (non-greedy) <code>(.*?)</code>. The whole thing is anchored at the start (<code>^</code>) and end (<code>$</code>) of the string so it consumes the whole input string.</li>
<li>Assuming that you will never have angles on both ends of the string, then the combined string <code>Left+Right</code> will either be an empty string plus the character to put at the end, one way or the other, or a completely empty string indicating a dash is required.</li>
</ol>
| 1 | 2016-08-03T05:46:42Z | [
"python",
"regex",
"string",
"split"
] |
Simplifying the extraction of particular string patterns with a multiple if-else and split() | 38,734,649 | <p>Given a string like this:</p>
<pre><code>>>> s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
</code></pre>
<p>First I want to split the string by underscores, i.e.:</p>
<pre><code>>>> s.split('_')
['X/NOUN/dobj>',
'hold/VERB/ROOT',
'<membership/NOUN/dobj',
'<with/ADP/prep',
'<Y/PROPN/pobj',
'>,/PUNCT/punct']
</code></pre>
<p>We assume that the underscore is solely used as the delimiter and never exist as part of the substring we want to extract. </p>
<p>Then I need to first checks whether each of these "nodes" in my splitted list above starts of ends with a '>', '<', then remove it and put the appropriate bracket as the end of the sublist, something like:</p>
<pre><code>result = []
nodes = s.split('_')
for node in nodes:
if node.endswith('>'):
result.append( node[:-1].split('/') + ['>'] )
elif node.startswith('>'):
result.append( node[1:].split('/') + ['>'] )
elif node.startswith('<'):
result.append( node[1:].split('/') + ['<'] )
elif node.endswith('<'):
result.append( node[:-1].split('/') + ['<'] )
else:
result.append( node.split('/') + ['-'] )
</code></pre>
<p>And if it doesn't start of ends with an angular bracket then we append <code>-</code> to the end of the sublist.</p>
<p>[out]:</p>
<pre><code>[['X', 'NOUN', 'dobj', '>'],
['hold', 'VERB', 'ROOT', '-'],
['membership', 'NOUN', 'dobj', '<'],
['with', 'ADP', 'prep', '<'],
['Y', 'PROPN', 'pobj', '<'],
[',', 'PUNCT', 'punct', '>']]
</code></pre>
<p><strong>Given the original input string, is there a less verbose way to get to the result? Maybe with regex and groups?</strong></p>
| 2 | 2016-08-03T04:51:42Z | 38,735,440 | <p>Instead of my other answer with regexes, you can drop a lot of lines and a lot of slicing, if you know that <code>string.strip('<>')</code> will strip <em>either</em> character from <em>both ends</em> of the string, in one move.</p>
<p>This code is about halfway between your original and my regex answer in linecount, but is more readable for it.</p>
<pre><code>s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
result = []
for node in s.split('_'):
if node.startswith('>') or node.startswith('<'):
tail = node[0]
elif node.endswith('>') or node.endswith('>'):
tail = node[-1]
else:
tail = '-'
result.append( node.strip('<>').split('/') + [tail])
print(result)
</code></pre>
<p>Try online: <a href="https://repl.it/Civr" rel="nofollow">https://repl.it/Civr</a></p>
<hr>
<p>Edit: how much less verbose do you want to get?</p>
<pre><code>result = [node.strip('<>').split('/') + [(''.join(char for char in node if char in '<>') + '-')[0]] for node in s.split('_')]
print(result)
</code></pre>
<p>This is quite neat, you don't have to check which side the <code><></code> is on, or whether it's there at all. One step <code>strip()</code>s either angle bracket whichever side it's on, the next step filters only the angle brackets out of the string (whichever side they're on) and adds the dash character. This is either a string starting with any angle bracket from either side or a single dash. Take char 0 to get the right one.</p>
| 1 | 2016-08-03T05:53:23Z | [
"python",
"regex",
"string",
"split"
] |
Simplifying the extraction of particular string patterns with a multiple if-else and split() | 38,734,649 | <p>Given a string like this:</p>
<pre><code>>>> s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
</code></pre>
<p>First I want to split the string by underscores, i.e.:</p>
<pre><code>>>> s.split('_')
['X/NOUN/dobj>',
'hold/VERB/ROOT',
'<membership/NOUN/dobj',
'<with/ADP/prep',
'<Y/PROPN/pobj',
'>,/PUNCT/punct']
</code></pre>
<p>We assume that the underscore is solely used as the delimiter and never exist as part of the substring we want to extract. </p>
<p>Then I need to first checks whether each of these "nodes" in my splitted list above starts of ends with a '>', '<', then remove it and put the appropriate bracket as the end of the sublist, something like:</p>
<pre><code>result = []
nodes = s.split('_')
for node in nodes:
if node.endswith('>'):
result.append( node[:-1].split('/') + ['>'] )
elif node.startswith('>'):
result.append( node[1:].split('/') + ['>'] )
elif node.startswith('<'):
result.append( node[1:].split('/') + ['<'] )
elif node.endswith('<'):
result.append( node[:-1].split('/') + ['<'] )
else:
result.append( node.split('/') + ['-'] )
</code></pre>
<p>And if it doesn't start of ends with an angular bracket then we append <code>-</code> to the end of the sublist.</p>
<p>[out]:</p>
<pre><code>[['X', 'NOUN', 'dobj', '>'],
['hold', 'VERB', 'ROOT', '-'],
['membership', 'NOUN', 'dobj', '<'],
['with', 'ADP', 'prep', '<'],
['Y', 'PROPN', 'pobj', '<'],
[',', 'PUNCT', 'punct', '>']]
</code></pre>
<p><strong>Given the original input string, is there a less verbose way to get to the result? Maybe with regex and groups?</strong></p>
| 2 | 2016-08-03T04:51:42Z | 38,735,501 | <p>Use this:</p>
<pre><code>import re
s_split = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct".split('_')
for i, text in enumerate(s_split):
Left, Mid, Right = re.search('^([<>]?)(.*?)([<>]?)$', text).groups()
s_split[i] = Mid.split('/') + [Left+Right or '-']
print s_split
</code></pre>
<p>I can't find a possible answer for a shorter one.</p>
<p>Use ternary to shorten code. Example: <code>print None or "a"</code> will print <code>a</code>. And also use regex to parse the occurence of <code><></code> easily.</p>
| 2 | 2016-08-03T05:57:20Z | [
"python",
"regex",
"string",
"split"
] |
Simplifying the extraction of particular string patterns with a multiple if-else and split() | 38,734,649 | <p>Given a string like this:</p>
<pre><code>>>> s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
</code></pre>
<p>First I want to split the string by underscores, i.e.:</p>
<pre><code>>>> s.split('_')
['X/NOUN/dobj>',
'hold/VERB/ROOT',
'<membership/NOUN/dobj',
'<with/ADP/prep',
'<Y/PROPN/pobj',
'>,/PUNCT/punct']
</code></pre>
<p>We assume that the underscore is solely used as the delimiter and never exist as part of the substring we want to extract. </p>
<p>Then I need to first checks whether each of these "nodes" in my splitted list above starts of ends with a '>', '<', then remove it and put the appropriate bracket as the end of the sublist, something like:</p>
<pre><code>result = []
nodes = s.split('_')
for node in nodes:
if node.endswith('>'):
result.append( node[:-1].split('/') + ['>'] )
elif node.startswith('>'):
result.append( node[1:].split('/') + ['>'] )
elif node.startswith('<'):
result.append( node[1:].split('/') + ['<'] )
elif node.endswith('<'):
result.append( node[:-1].split('/') + ['<'] )
else:
result.append( node.split('/') + ['-'] )
</code></pre>
<p>And if it doesn't start of ends with an angular bracket then we append <code>-</code> to the end of the sublist.</p>
<p>[out]:</p>
<pre><code>[['X', 'NOUN', 'dobj', '>'],
['hold', 'VERB', 'ROOT', '-'],
['membership', 'NOUN', 'dobj', '<'],
['with', 'ADP', 'prep', '<'],
['Y', 'PROPN', 'pobj', '<'],
[',', 'PUNCT', 'punct', '>']]
</code></pre>
<p><strong>Given the original input string, is there a less verbose way to get to the result? Maybe with regex and groups?</strong></p>
| 2 | 2016-08-03T04:51:42Z | 38,736,245 | <p>I did not use regex and groups but it can be solution as shorter way.</p>
<pre><code>>>> result=[]
>>> nodes=['X/NOUN/dobj>','hold/VERB/ROOT','<membership/NOUN/dobj',
'<with/ADP/prep','<Y/PROPN/pobj','>,/PUNCT/punct']
>>> for node in nodes:
... nd=node.replace(">",("/>" if node.endswith(">") else ">/"))
... nc=nd.replace("<",("/<" if nd.endswith("<") else "</"))
... result.append(nc.split("/"))
>>> nres=[inner for outer in result for inner in outer] #nres used to join all result at single array. If you dont need single array you can use result.
</code></pre>
| 0 | 2016-08-03T06:44:58Z | [
"python",
"regex",
"string",
"split"
] |
Simplifying the extraction of particular string patterns with a multiple if-else and split() | 38,734,649 | <p>Given a string like this:</p>
<pre><code>>>> s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
</code></pre>
<p>First I want to split the string by underscores, i.e.:</p>
<pre><code>>>> s.split('_')
['X/NOUN/dobj>',
'hold/VERB/ROOT',
'<membership/NOUN/dobj',
'<with/ADP/prep',
'<Y/PROPN/pobj',
'>,/PUNCT/punct']
</code></pre>
<p>We assume that the underscore is solely used as the delimiter and never exist as part of the substring we want to extract. </p>
<p>Then I need to first checks whether each of these "nodes" in my splitted list above starts of ends with a '>', '<', then remove it and put the appropriate bracket as the end of the sublist, something like:</p>
<pre><code>result = []
nodes = s.split('_')
for node in nodes:
if node.endswith('>'):
result.append( node[:-1].split('/') + ['>'] )
elif node.startswith('>'):
result.append( node[1:].split('/') + ['>'] )
elif node.startswith('<'):
result.append( node[1:].split('/') + ['<'] )
elif node.endswith('<'):
result.append( node[:-1].split('/') + ['<'] )
else:
result.append( node.split('/') + ['-'] )
</code></pre>
<p>And if it doesn't start of ends with an angular bracket then we append <code>-</code> to the end of the sublist.</p>
<p>[out]:</p>
<pre><code>[['X', 'NOUN', 'dobj', '>'],
['hold', 'VERB', 'ROOT', '-'],
['membership', 'NOUN', 'dobj', '<'],
['with', 'ADP', 'prep', '<'],
['Y', 'PROPN', 'pobj', '<'],
[',', 'PUNCT', 'punct', '>']]
</code></pre>
<p><strong>Given the original input string, is there a less verbose way to get to the result? Maybe with regex and groups?</strong></p>
| 2 | 2016-08-03T04:51:42Z | 38,739,840 | <p>Even shorter with a list comprehension and some regex magic:</p>
<pre><code>import re
s = "X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct"
rx = re.compile(r'([<>])|/')
items = [list(filter(None, match)) \
for item in s.split('_') \
for match in [rx.split(item)]]
print(items)
# [['X', 'NOUN', 'dobj', '>'], ['hold', 'VERB', 'ROOT'], ['<', 'membership', 'NOUN', 'dobj'], ['<', 'with', 'ADP', 'prep'], ['<', 'Y', 'PROPN', 'pobj'], ['>', ',', 'PUNCT', 'punct']]
</code></pre>
<p><hr>
<strong>Explanation:</strong>
The code splits the <code>items</code> by <code>_</code>, splits it again with the help of the regular expression <code>rx</code> and filters out empty elements in the end.
<hr>
See a demo on <a href="http://ideone.com/G2mIAE" rel="nofollow"><strong>ideone.com</strong></a>. </p>
| 1 | 2016-08-03T09:37:09Z | [
"python",
"regex",
"string",
"split"
] |
Is there a better way to swap string without a placeholder | 38,735,328 | <p>I have a string:</p>
<pre><code>>>> s = 'Y/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<X/PROPN/pobj_>,/PUNCT/punct'
</code></pre>
<p>And the aim is to change the position of <code>Y/</code> to <code>X/</code>, i.e. something like:</p>
<pre><code>>>> s.replace('X/', '@@').replace('Y/', 'X/').replace('@@', 'Y/')
'X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct'
</code></pre>
<p>Assuming that there'll be no conflict when doing the replacement, i.e. <code>X/</code> and <code>Y/</code> is unique and will only happen once each in the original string.</p>
<p><strong>Is there a way to do the replacement without the placeholder?</strong> Currently, i'm swapping there position by using the <code>@@</code> placeholder. </p>
| 1 | 2016-08-03T05:45:06Z | 38,736,034 | <p>In Python, an easy way using a regex is via a lambda in the <code>re.sub</code> replacement part where you can evaluate/check texts captured with capturing groups and select appropriate replacement:</p>
<p>So, <code>(X|Y)/</code> (<em>I assume <code>X</code> and <code>Y</code> are potentially multicharacter string placeholders, otherwise use <code>([XY])</code></em>) should work:</p>
<pre><code>import re
s = 'Y/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<X/PROPN/pobj_>,/PUNCT/punct'
print(s)
print(re.sub(r"(X|Y)/", lambda m: "Y/" if m.group(1) == 'X' else 'X/' , s))
</code></pre>
<p>Output:</p>
<pre><code>Y/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<X/PROPN/pobj_>,/PUNCT/punct
X/NOUN/dobj>_hold/VERB/ROOT_<membership/NOUN/dobj_<with/ADP/prep_<Y/PROPN/pobj_>,/PUNCT/punct
</code></pre>
| 2 | 2016-08-03T06:33:15Z | [
"python",
"regex",
"string",
"replace",
"swap"
] |
filter() and get() don't give correct GQLQuery results | 38,735,372 | <p>So I'm building a small wiki using Google App Engine, where if you type in a URL like <code>/newpage</code>, it redirects you to it if it already exists, else it redirects you to <code>/edit/newpage/</code> where you can edit (or in this case, add) the contents of the page. After the editing, it redirects you to the page itself, i.e. <code>/newpage</code>.</p>
<p>Here's the code:</p>
<p>The table that holds the entries:</p>
<pre><code>class Entries(db.Model):
title = db.TextProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
</code></pre>
<p>The app handlers:</p>
<pre><code>app = webapp2.WSGIApplication([('/', MainPage),
('/signup', SignUp),
('/welcome', Welcome),
('/login', Login),
('/logout', Logout),
('/([a-zA-Z0-9_]+)', WikiEntry),
('/edit/([a-zA-Z0-9_]+)', EditWikiEntry)
], debug = True)
</code></pre>
<p>The handler functions:</p>
<pre><code>class WikiEntry(webapp2.RequestHandler):
def get(self, wiki_entry):
1 entry = Entries.all().filter('title =', wiki_entry).get()
2 # entry = db.GqlQuery("select * from Entries where title = 'hello'")
3 # logging.error(entry.title)
4 logging.error(entry)
5 if entry:
6 logging.error("inside if")
7 self.response.write(render_str('entrypage.html', entry=entry))
8 else:
9 logging.error("inside else")
10 self.redirect('/edit/' + wiki_entry)
class EditWikiEntry(webapp2.RequestHandler):
1 def get(self, wiki_entry):
2 self.response.write(render_str('edit.html', wiki_entry = wiki_entry))
3 def post(self, wiki_entry):
4 content = self.request.get('textarea')
5 if content:
6 e = Entries(title = wiki_entry, content = content)
7 e.put()
8 self.redirect('/' + wiki_entry)
</code></pre>
<p><code>textarea</code> is the name of the textarea on the <code>edit</code> page.</p>
<p>And here is <code>entrypage.html</code>:</p>
<pre><code><html>
<head>
<title>{{ entry.title }}</title>
</head>
<body>
{{ entry.content }}
</body>
</html>
</code></pre>
<p>So here's the problem: I typed in <code>/hello</code> and since it didn't exist, it redirected me to the <code>edit</code> page. I typed into the contents <code><h1> Hello World </h1></code>, hit Save but it redirected me to the <code>edit</code> page yet again (with the textarea blank). I went to the admin page and confirmed that there IS indeed an object with title and content as I had saved. </p>
<p>I tried debugging and found out the query function in line 1 of <code>WikiEntry</code> doesn't work. When I print out <code>entry</code> in line 4, it's <code>None</code>. When I manually put in the string <code>hello</code> into the query as in line 2 of <code>WikiEntry</code>, I do get an object out of line 4 and it redirected me to <code>entrypage.html</code>, but with nothing in it. When I tried printing out the title on the console itself as in line 3, it threw an <code>AttributeError</code>:</p>
<pre><code>AttributeError: 'GqlQuery' object has no attribute 'title'
</code></pre>
<p>If the object has no <code>title</code> attribute, then how did it print the object in the first place?</p>
<pre><code><google.appengine.ext.db.GqlQuery object at 0x04766270>
</code></pre>
<p>I'm really confused and don't how to resolve this.</p>
| 0 | 2016-08-03T05:48:23Z | 38,742,367 | <p>You are performing a query to retrieve the WikiPage, at times (due to eventual consistency) the query will not find the page just created.</p>
<p>You need to spend some time reading up on Eventual Consistency, it is important to understand concept this when using the data store.</p>
<p>I suggest you consider using the wiki page name as the key of the Entries entity and then fetching by Key rather than by a query. This will guarantee you will always be able to retrieve the Entry just created.</p>
| 1 | 2016-08-03T11:32:12Z | [
"python",
"google-app-engine",
"redirect",
"google-cloud-datastore",
"gql"
] |
Pivot a groupby object in Pandas? | 38,735,384 | <p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame([
[123, 'abc', '121'],
[124, 'abc', '121'],
[456, 'def', '121'],
[123, 'abc', '122'],
[123, 'abc', '122'],
[456, 'def', '145'],
[456, 'def', '145'],
[456, 'def', '146'],
], columns=['userid', 'name', 'dt'])
</code></pre>
<p>I have grouped it according to the date:
<code>df2 = df.groupby('dt').apply(lambda df: df.reset_index(drop=True))</code></p>
<p>Now, the dataframe looks like this:
<a href="http://i.stack.imgur.com/o92eN.png" rel="nofollow"><img src="http://i.stack.imgur.com/o92eN.png" alt="enter image description here"></a></p>
<p>Now, I want to pivot the above such that they are in this format:
<code>userid name_1, name_2, ..., name_k</code> for each group such that the end df looks something like this:</p>
<pre><code>userid name
123 abc
124 abc
456 def
123 abc, abc
</code></pre>
| 3 | 2016-08-03T05:49:12Z | 38,735,489 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, where parameter index use columns <code>userid</code> and <code>dt</code>, so it looks like create <code>df2</code> is not necessary:</p>
<pre><code>df['cols'] = 'name_' + (df.groupby(['userid','dt']).cumcount() + 1).astype(str)
print (df.pivot_table(index=['userid', 'dt'],columns='cols', values='name', aggfunc=''.join))
cols name_1 name_2
userid dt
123 121 abc None
122 abc abc
124 121 abc None
456 121 def None
145 def def
146 def None
</code></pre>
| 2 | 2016-08-03T05:56:24Z | [
"python",
"pandas"
] |
Pivot a groupby object in Pandas? | 38,735,384 | <p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame([
[123, 'abc', '121'],
[124, 'abc', '121'],
[456, 'def', '121'],
[123, 'abc', '122'],
[123, 'abc', '122'],
[456, 'def', '145'],
[456, 'def', '145'],
[456, 'def', '146'],
], columns=['userid', 'name', 'dt'])
</code></pre>
<p>I have grouped it according to the date:
<code>df2 = df.groupby('dt').apply(lambda df: df.reset_index(drop=True))</code></p>
<p>Now, the dataframe looks like this:
<a href="http://i.stack.imgur.com/o92eN.png" rel="nofollow"><img src="http://i.stack.imgur.com/o92eN.png" alt="enter image description here"></a></p>
<p>Now, I want to pivot the above such that they are in this format:
<code>userid name_1, name_2, ..., name_k</code> for each group such that the end df looks something like this:</p>
<pre><code>userid name
123 abc
124 abc
456 def
123 abc, abc
</code></pre>
| 3 | 2016-08-03T05:49:12Z | 38,735,764 | <p>Check out <code>groupby</code> and <code>apply</code>. Their respective docs are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">here</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow">here</a>. You can <code>unstack</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow">docs</a>) the extra level of the MultiIndex that is created.</p>
<pre><code>df = df.set_index(['userid', 'dt'])['name']
df = df.groupby(level=[0,1]).apply(
lambda st: pd.Series(st.values, index=['name_%i'%i for i in range(st.shape[0])])
).unstack(level=-1)
print(df)
</code></pre>
<p>outputs</p>
<pre><code> name_0 name_1
userid dt
123 121 abc None
122 abc abc
124 121 abc None
456 121 def None
145 def def
146 def None
</code></pre>
| 2 | 2016-08-03T06:15:12Z | [
"python",
"pandas"
] |
Packing an integer number to 3 bytes in Python | 38,735,421 | <p>With background knowledge of C I want to serialize an integer number to 3 bytes. I searched a lot and found out I should use struct packing. I want something like this:</p>
<pre><code>number = 1195855
buffer = struct.pack("format_string", number)
</code></pre>
<p>Now I expect buffer to be something like <code>['\x12' '\x3F' '\x4F']</code>. Is it also possible to set endianness?</p>
| 2 | 2016-08-03T05:52:31Z | 38,735,535 | <p>It is possible, using either <code>></code> or <code><</code> in your format string:</p>
<pre><code>import struct
number = 1195855
def print_buffer(buffer):
print(''.join(["%02x" % ord(b) for b in buffer])) # Python 2
#print(buffer.hex()) # Python 3
# Little Endian
buffer = struct.pack("<L", number)
print_buffer(buffer) # 4f3f1200
# Big Endian
buffer = struct.pack(">L", number)
print_buffer(buffer) # 00123f4f
</code></pre>
<ul>
<li><a href="https://docs.python.org/2/library/struct.html#byte-order-size-and-alignment" rel="nofollow">2.x docs</a></li>
<li><a href="https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment" rel="nofollow">3.x docs</a></li>
</ul>
<p>Note, however, that you're going to have to figure out how you want to get rid of the empty byte in the buffer, since <code>L</code> will give you 4 bytes and you only want 3.</p>
<p>Something like:</p>
<pre><code>buffer = struct.pack("<L", number)
print_buffer(buffer[:3]) # 4f3f12
# Big Endian
buffer = struct.pack(">L", number)
print_buffer(buffer[-3:]) # 123f4f
</code></pre>
<p>would be one way.</p>
| 3 | 2016-08-03T05:59:13Z | [
"python"
] |
Python Tkinter button stuck down after press | 38,735,643 | <p>I press this tkinter button, and the function bound to it finishes, but the button is stuck down. The rest of the gui is fine, its responsive, everything normal except for the button that is stuck down. I can even press the "stuck down" button again, and the bound function executes and finishes, but the button is still stuck down.
Sometimes the first few times I click the button it works fine and the button comes back up, but then after a few more clicks it will be stuck down. What could be causing this?</p>
<p>Here is the code for the button:</p>
<pre><code>bf1=Button(self.canvas,text='F1',fg='tan1')
bf1.grid(row=4,column=1,sticky='nwse',columnspan=4)
bf1.bind('<Button-1>',self.f1)
</code></pre>
| -2 | 2016-08-03T06:06:13Z | 38,748,117 | <p>I have found what is causing this, it is the fact that I am using the 'bind' function instead of the 'command'.</p>
<p>When I use this, the button sticks if you move the mouse off the button before the callback finishes (you can only realistically do this if you have a lot of work to do in the callback):</p>
<pre><code>bf1=Button(self.canvas,text='F1',fg='tan1')
bf1.grid(row=4,column=1,sticky='nwse',columnspan=4)
bf1.bind('<Button-1>',self.f1)
</code></pre>
<p>But if you use the 'command', then there is no problem:</p>
<pre><code>bf1=Button(self.canvas,text='F1',fg='tan1',command=self.f1)
bf1.grid(row=4,column=1,sticky='nwse',columnspan=4)
</code></pre>
<p>Is this a bug with tkinter's 'bind'?</p>
| 0 | 2016-08-03T15:40:49Z | [
"python",
"button",
"tkinter"
] |
Brookstone rover 2.0 Python program to control from computer isn't working | 38,735,708 | <p>I have a python program that controls a Brookstone Rover 2.0 from a computer through openCV and pygame and I've been working on this for 7 hours now and it has been nothing but errors after errors and this is what it's showing me now</p>
<pre><code> PS C:\users\sessi\desktop> C:\Users\sessi\Desktop\rover\ps3rover20.py
Traceback (most recent call last):
File "C:\Users\sessi\Desktop\rover\ps3rover20.py", line 168, in <module>
rover = PS3Rover()
File "C:\Users\sessi\Desktop\rover\ps3rover20.py", line 58, in __init__
Rover20.__init__(self)
File "C:\Program Files\Python 3.5\lib\site-packages\roverpylot-0.1-py3.5.egg\rover\__init__.py", line 182, in __init__
Rover.__init__(self)
File "C:\Program Files\Python 3.5\lib\site-packages\roverpylot-0.1-py3.5.egg\rover\__init__.py", line 47, in __init__
self._sendCommandIntRequest(0, [0, 0, 0, 0])
File "C:\Program Files\Python 3.5\lib\site-packages\roverpylot-0.1-py3.5.egg\rover\__init__.py", line 149, in _sendCommandIntRequest
bytevals.append(ord(c))
TypeError: ord() expected string of length 1, but int found
</code></pre>
<p>These are the two files that it's getting errors from</p>
<p>ps3rover20.py</p>
<pre><code>#!/usr/bin/env python
'''
ps3rover20.py Drive the Brookstone Rover 2.0 via the P3 Controller, displaying
the streaming video using OpenCV.
Copyright (C) 2014 Simon D. Levy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
# You may want to adjust these buttons for your own controller
BUTTON_LIGHTS = 3 # Square button toggles lights
BUTTON_STEALTH = 1 # Circle button toggles stealth mode
BUTTON_CAMERA_UP = 0 # Triangle button raises camera
BUTTON_CAMERA_DOWN = 2 # X button lowers camera
# Avoid button bounce by enforcing lag between button events
MIN_BUTTON_LAG_SEC = 0.5
# Avoid close-to-zero values on axis
MIN_AXIS_ABSVAL = 0.01
from rover import Rover20
import time
import pygame
import sys
import signal
# Supports CTRL-C to override threads
def _signal_handler(signal, frame):
frame.f_locals['rover'].close()
sys.exit(0)
# Try to start OpenCV for video
try:
import cv
except:
cv = None
# Rover subclass for PS3 + OpenCV
class PS3Rover(Rover20):
def __init__(self):
# Set up basics
Rover20.__init__(self)
self.wname = 'Rover 2.0: Hit ESC to quit'
self.quit = False
# Set up controller using PyGame
pygame.display.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
# Defaults on startup: lights off, ordinary camera
self.lightsAreOn = False
self.stealthIsOn = False
# Tracks button-press times for debouncing
self.lastButtonTime = 0
# Try to create OpenCV named window
try:
if cv:
cv.NamedWindow(self.wname, cv.CV_WINDOW_AUTOSIZE )
else:
pass
except:
pass
self.pcmfile = open('rover20.pcm', 'w')
# Automagically called by Rover class
def processAudio(self, pcmsamples, timestamp_10msec):
for samp in pcmsamples:
self.pcmfile.write('%d\n' % samp)
# Automagically called by Rover class
def processVideo(self, jpegbytes, timestamp_10msec):
# Update controller events
pygame.event.pump()
# Toggle lights
self.lightsAreOn = self.checkButton(self.lightsAreOn, BUTTON_LIGHTS, self.turnLightsOn, self.turnLightsOff)
# Toggle night vision (infrared camera)
self.stealthIsOn = self.checkButton(self.stealthIsOn, BUTTON_STEALTH, self.turnStealthOn, self.turnStealthOff)
# Move camera up/down
if self.controller.get_button(BUTTON_CAMERA_UP):
self.moveCameraVertical(1)
elif self.controller.get_button(BUTTON_CAMERA_DOWN):
self.moveCameraVertical(-1)
else:
self.moveCameraVertical(0)
# Set treads based on axes
self.setTreads(self.axis(1), self.axis(3))
# Display video image if possible
try:
if cv:
# Save image to file on disk and load as OpenCV image
fname = 'tmp.jpg'
fd = open(fname, 'w')
fd.write(jpegbytes)
fd.close()
image = cv.LoadImage(fname)
# Show image
cv.ShowImage(self.wname, image )
if cv.WaitKey(1) & 0xFF == 27: # ESC
self.quit = True
else:
pass
except:
pass
# Converts Y coordinate of specified axis to +/-1 or 0
def axis(self, index):
value = -self.controller.get_axis(index)
if value > MIN_AXIS_ABSVAL:
return 1
elif value < -MIN_AXIS_ABSVAL:
return -1
else:
return 0
# Handles button bounce by waiting a specified time between button presses
def checkButton(self, flag, buttonID, onRoutine=None, offRoutine=None):
if self.controller.get_button(buttonID):
if (time.time() - self.lastButtonTime) > MIN_BUTTON_LAG_SEC:
self.lastButtonTime = time.time()
if flag:
if offRoutine:
offRoutine()
flag = False
else:
if onRoutine:
onRoutine()
flag = True
return flag
# main -----------------------------------------------------------------------------------
if __name__ == '__main__':
# Create a PS3 Rover object
rover = PS3Rover()
# Set up signal handler for CTRL-C
signal.signal(signal.SIGINT, _signal_handler)
# Loop until user hits quit button on controller
while not rover.quit:
pass
# Shut down Rover
rover.close()
</code></pre>
<p>__ init__.py</p>
<pre><code>'''
Python classes for interacting with the Brookstone Rover 2.0
and Rover Revolution
Copyright (C) 2015 Simon D. Levy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
'''
import struct
import threading
import socket
import time
from blowfish import Blowfish
from adpcm import decodeADPCMToPCM
from byteutils import *
class Rover:
def __init__(self):
''' Creates a Rover object that you can communicate with.
'''
self.HOST = '192.168.1.100'
self.PORT = 80
TARGET_ID = 'AC13'
TARGET_PASSWORD = 'AC13'
self.TREAD_DELAY_SEC = 1.0
self.KEEPALIVE_PERIOD_SEC = 60
# Create command socket connection to Rover
self.commandsock = self._newSocket()
# Send login request with four arbitrary numbers
self._sendCommandIntRequest(0, [0, 0, 0, 0])
# Get login reply
reply = self._receiveCommandReply(82)
# Extract Blowfish key from camera ID in reply
cameraID = reply[25:37].decode('utf-8')
key = TARGET_ID + ':' + cameraID + '-save-private:' + TARGET_PASSWORD
# Extract Blowfish inputs from rest of reply
L1 = bytes_to_int(reply, 66)
R1 = bytes_to_int(reply, 70)
L2 = bytes_to_int(reply, 74)
R2 = bytes_to_int(reply, 78)
# Make Blowfish cipher from key
bf = _RoverBlowfish(key)
# Encrypt inputs from reply
L1,R1 = bf.encrypt(L1, R1)
L2,R2 = bf.encrypt(L2, R2)
# Send encrypted reply to Rover
self._sendCommandIntRequest(2, [L1, R1, L2, R2])
# Ignore reply from Rover
self._receiveCommandReply(26)
# Start timer task for keep-alive message every 60 seconds
self._startKeepaliveTask()
# Set up vertical camera controller
self.cameraVertical = _RoverCamera(self, 1)
# Send video-start request
self._sendCommandIntRequest(4, [1])
# Get reply from Rover
reply = self._receiveCommandReply(29)
# Create media socket connection to Rover
self.mediasock = self._newSocket()
# Send video-start request based on last four bytes of reply
self._sendRequest(self.mediasock, 'V', 0, 4, map(ord, reply[25:]))
# Send audio-start request
self._sendCommandByteRequest(8, [1])
# Ignore audio-start reply
self._receiveCommandReply(25)
# Receive images on another thread until closed
self.is_active = True
self.reader_thread = _MediaThread(self)
self.reader_thread.start()
def close(self):
''' Closes off commuincation with Rover.
'''
self.keepalive_timer.cancel()
self.is_active = False
self.commandsock.close()
if self.mediasock:
self.mediasock.close()
def turnStealthOn(self):
''' Turns on stealth mode (infrared).
'''
self._sendCameraRequest(94)
def turnStealthOff(self):
''' Turns off stealth mode (infrared).
'''
self._sendCameraRequest(95)
def moveCameraVertical(self, where):
''' Moves the camera up or down, or stops moving it. A nonzero value for the
where parameter causes the camera to move up (+) or down (-). A
zero value stops the camera from moving.
'''
self.cameraVertical.move(where)
def _startKeepaliveTask(self,):
self._sendCommandByteRequest(255)
self.keepalive_timer = \
threading.Timer(self.KEEPALIVE_PERIOD_SEC, self._startKeepaliveTask, [])
self.keepalive_timer.start()
def _sendCommandByteRequest(self, id, bytes=[]):
self._sendCommandRequest(id, len(bytes), bytes)
def _sendCommandIntRequest(self, id, intvals):
bytevals = []
for val in intvals:
for c in struct.pack('I', val):
bytevals.append(ord(c))
self._sendCommandRequest(id, 4*len(intvals), bytevals)
def _sendCommandRequest(self, id, n, contents):
self._sendRequest(self.commandsock, 'O', id, n, contents)
def _sendRequest(self, sock, c, id, n, contents):
bytes = [ord('M'), ord('O'), ord('_'), ord(c), id, \
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n, 0, 0, 0, 0, 0, 0, 0]
bytes.extend(contents)
request = ''.join(map(chr, bytes))
sock.send(request)
def _receiveCommandReply(self, count):
reply = self.commandsock.recv(count)
return reply
def _newSocket(self):
sock = socket.socket()
sock.connect((self.HOST, self.PORT))
return sock
def _sendDeviceControlRequest(self, a, b) :
self._sendCommandByteRequest(250, [a,b])
def _sendCameraRequest(self, request):
self._sendCommandByteRequest(14, [request])
class Rover20(Rover):
def __init__(self):
Rover.__init__(self)
# Set up treads
self.leftTread = _RoverTread(self, 4)
self.rightTread = _RoverTread(self, 1)
def close(self):
''' Closes off commuincation with Rover.
'''
Rover.close(self)
# Stop moving treads
self.setTreads(0, 0)
def getBatteryPercentage(self):
''' Returns percentage of battery remaining.
'''
self._sendCommandByteRequest(251)
reply = self._receiveCommandReply(32)
return 15 * ord(reply[23])
def setTreads(self, left, right):
''' Sets the speed of the left and right treads (wheels). + = forward;
- = backward; 0 = stop. Values should be in [-1..+1].
'''
currTime = time.time()
self.leftTread.update(left)
self.rightTread.update(right)
def turnLightsOn(self):
''' Turns the headlights and taillights on.
'''
self._setLights(8)
def turnLightsOff(self):
''' Turns the headlights and taillights off.
'''
self._setLights(9)
def _setLights(self, onoff):
self._sendDeviceControlRequest(onoff, 0)
def processVideo(self, jpegbytes, timestamp_10msec):
''' Proccesses bytes from a JPEG image streamed from Rover.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def processAudio(self, pcmsamples, timestamp_10msec):
''' Proccesses a block of 320 PCM audio samples streamed from Rover.
Audio is sampled at 8192 Hz and quantized to +/- 2^15.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def _spinWheels(self, wheeldir, speed):
# 1: Right, forward
# 2: Right, backward
# 4: Left, forward
# 5: Left, backward
self._sendDeviceControlRequest(wheeldir, speed)
class Revolution(Rover):
def __init__(self):
Rover.__init__(self)
self.steerdir_prev = 0
self.command_prev = 0
self.goslow_prev = 0
self.using_turret = False
# Set up vertical camera controller
self.cameraHorizontal = _RoverCamera(self, 5)
def drive(self, wheeldir, steerdir, goslow):
goslow = 1 if goslow else 0
command = 0
if wheeldir == +1 and steerdir == 0:
command = 1
if wheeldir == -1 and steerdir == 0:
command = 2
if wheeldir == 0 and steerdir == +1:
command = 4
if wheeldir == 0 and steerdir == -1:
command = 5
if wheeldir == +1 and steerdir == -1:
command = 6
if wheeldir == +1 and steerdir == +1:
command = 7
if wheeldir == -1 and steerdir == -1:
command = 8
if wheeldir == -1 and steerdir == +1:
command = 9
if steerdir == 0 and self.steerdir_prev != 0:
command = 3
if command != self.command_prev or goslow != self.goslow_prev:
self._sendDeviceControlRequest(command, goslow)
self.steerdir_prev = steerdir
self.command_prev = command
self.goslow_prev = goslow
def processVideo(self, imgbytes, timestamp_msec):
''' Proccesses bytes from an image streamed from Rover.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def processAudio(self, audiobytes, timestamp_msec):
''' Proccesses a block of 1024 PCM audio samples streamed from Rover.
Audio is sampled at 8192 Hz and quantized to +/- 2^15.
Default method is a no-op; subclass and override to do something
interesting.
'''
pass
def useTurretCamera(self):
''' Switches to turret camera.
'''
self._sendUseCameraRequest(1)
def useDrivingCamera(self):
''' Switches to driving camera.
'''
self._sendUseCameraRequest(2)
def moveCameraHorizontal(self, where):
''' Moves the camera up or down, or stops moving it. A nonzero value for the
where parameter causes the camera to move up (+) or down (-). A
zero value stops the camera from moving.
'''
self.cameraHorizontal.move(where)
def _sendUseCameraRequest(self, camera):
self._sendCommandByteRequest(19, [6, camera])
# "Private" classes ===========================================================
# A special Blowfish variant with P-arrays set to zero instead of digits of Pi
class _RoverBlowfish(Blowfish):
def __init__(self, key):
ORIG_P = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
self._keygen(key, ORIG_P)
# A thread for reading streaming media from the Rover
class _MediaThread(threading.Thread):
def __init__(self, rover):
threading.Thread.__init__(self)
self.rover = rover
self.BUFSIZE = 1024
def run(self):
# Accumulates media bytes
mediabytes = ''
# Starts True; set to False by Rover.close()
while self.rover.is_active:
# Grab bytes from rover, halting on failure
try:
buf = self.rover.mediasock.recv(self.BUFSIZE)
except:
break
# Do we have a media frame start?
k = buf.find('MO_V')
# Yes
if k >= 0:
# Already have media bytes?
if len(mediabytes) > 0:
# Yes: add to media bytes up through start of new
mediabytes += buf[0:k]
# Both video and audio messages are time-stamped in 10msec units
timestamp = bytes_to_uint(mediabytes, 23)
# Video bytes: call processing routine
if ord(mediabytes[4]) == 1:
self.rover.processVideo(mediabytes[36:], timestamp)
# Audio bytes: call processing routine
else:
audsize = bytes_to_uint(mediabytes, 36)
sampend = 40 + audsize
offset = bytes_to_short(mediabytes, sampend)
index = ord(mediabytes[sampend+2])
pcmsamples = decodeADPCMToPCM(mediabytes[40:sampend], offset, index)
self.rover.processAudio(pcmsamples, timestamp)
# Start over with new bytes
mediabytes = buf[k:]
# No media bytes yet: start with new bytes
else:
mediabytes = buf[k:]
# No: accumulate media bytes
else:
mediabytes += buf
class _RoverTread(object):
def __init__(self, rover, index):
self.rover = rover
self.index = index
self.isMoving = False
self.startTime = 0
def update(self, value):
if value == 0:
if self.isMoving:
self.rover._spinWheels(self.index, 0)
self.isMoving = False
else:
if value > 0:
wheel = self.index
else:
wheel = self.index + 1
currTime = time.time()
if (currTime - self.startTime) > self.rover.TREAD_DELAY_SEC:
self.startTime = currTime
self.rover._spinWheels(wheel, int(round(abs(value)*10)))
self.isMoving = True
class _RoverCamera(object):
def __init__(self, rover, stopcmd):
self.rover = rover
self.stopcmd = stopcmd
self.isMoving = False
def move(self, where):
if where == 0:
if self.isMoving:
self.rover._sendCameraRequest(self.stopcmd)
self.isMoving = False
elif not self.isMoving:
if where == 1:
self.rover._sendCameraRequest(self.stopcmd-1)
else:
self.rover._sendCameraRequest(self.stopcmd+1)
self.isMoving = True
</code></pre>
<p>I know almost nothing about python by the way.</p>
<p>I'm using windows 10 64 bit</p>
| -1 | 2016-08-03T06:11:21Z | 38,737,318 | <p>At </p>
<p><a href="https://github.com/simondlevy/RoverPylot" rel="nofollow">https://github.com/simondlevy/RoverPylot</a></p>
<p>it says:</p>
<blockquote>
<p>Tips for Windows</p>
<p>Rob Crawley has put a lot of work into getting RoverPylot to work
smoothly on Windows 10. Here are his changes:</p>
<p>Original: # Create a named temporary file for video stream tmpfile =
tempfile.NamedTemporaryFile()</p>
<p>Changed to: tmpfile = tempfile.NamedTemporaryFile(mode='w+b',
bufsize=0 , suffix='.avi', prefix='RoverRev',
dir='\Python27\RoverRev_WinPylot', delete=False) Original: # Wait a
few seconds, then being playing the tmp video file cmd = 'ffplay
-window_title Rover_Revolution -framerate %d %s' % (FRAMERATE, tmpfile.name)</p>
<p>Changed to: cmd = '/Python27/ffmpeg/bin/ffplay.exe -x 640 -y 480
-window_title Rover_Revolution -framerate %d %s' % (FRAMERATE, tmpfile.name) Your files paths may be different than those listed
below, so make your changes accordingly</p>
</blockquote>
<p>Which means that the author uses Python 2.7. From your error reports I gather you use Python 3.5, which treats bytes differently. Install and use 2.7 instead.</p>
| 0 | 2016-08-03T07:39:20Z | [
"python",
"python-2.7",
"python-3.x",
"opencv",
"pygame"
] |
How to use Hyperlinked in Django Rest Framework? | 38,735,842 | <p>I just want to add url in some serializer fields.</p>
<pre><code>class PageListSerializer(ModelSerializer):
slider = SerializerMethodField()
lookup_field = 'title'
class Meta:
model = Page
fields = [
'is_active',
'category',
'title',
'slug',
'bundle_section',
'login_register_section',
'user_review_section',
'slider',
'top_content',
'mini_content',
'panel_content',
]
</code></pre>
<p>For example, following print is give to 1 in top, mini, panel content. Instead of 1 , I want to add url.</p>
<p>"top_content": [
1
],
"mini_content": [
1
],
"panel_content": [
1
]</p>
<p>How can I fix it with using Hyperlinked? Thank you.</p>
| -1 | 2016-08-03T06:21:25Z | 38,736,770 | <p>Refer the <a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/" rel="nofollow">hyperlink</a> API and make sure that url is defined in your url.py</p>
| 0 | 2016-08-03T07:12:25Z | [
"python",
"django",
"django-rest-framework"
] |
A function that works on a function and returns a function | 38,736,095 | <p>Suppose I want to define a meta-function that accept a function as an argument and returns a new modified function. Something like</p>
<pre><code>metaf(f) -> f**2
</code></pre>
<p>So whatever <code>f</code> would result, <code>metaf</code> would result with the answer to the power of two (and if the result cannot be raised to the power of 2, so be it. Raise an error).</p>
<p>Currently the way I've found to do that requires explicit reference to the argument of <code>f</code> in the definition of <code>metaf</code>, i.e. define</p>
<pre><code>metaf = lambda f, x : f(x)**2
</code></pre>
<p>and then</p>
<pre><code>mynewf = lambda x : metaf(f, x)
</code></pre>
<p>This works, but I wonder if it will hold for complex argument functions where there could be many variation to the input argument. </p>
<p>So I'm wondering if you can suggest a different way, especially one that does not require specifying the argument in <code>metaf</code> definition. </p>
<p><strong>Edit:</strong> Both answers below were helpful. Just for reference, following the answers I've also realized the way to define <code>metaf</code> using lambda expression. Slightly cumbersome, but might still be worth noting:</p>
<pre><code>metaf = lambda func: lambda *args, **kwargs : func(*args, **kwargs)**2
</code></pre>
| 1 | 2016-08-03T06:37:31Z | 38,736,261 | <p>You should be able to use <code>*args</code> and <code>**kwargs</code> to gobble up all other arguments and pass them on like so:</p>
<pre><code>def squarer(f):
return lambda *args, **kwargs: f(*args, **kwargs)**2
>>> squarer(lambda x: x+1)(3)
16
>>> squarer(lambda x: x+1)(4)
25
>>> squarer(lambda x,y: x+1)(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in <lambda>
TypeError: <lambda>() takes exactly 2 arguments (1 given)
>>> squarer(lambda x,y=1: x+y)(4)
25
>>> squarer(lambda x,y=1: x+y)(4,2)
36
</code></pre>
| 3 | 2016-08-03T06:45:38Z | [
"python"
] |
A function that works on a function and returns a function | 38,736,095 | <p>Suppose I want to define a meta-function that accept a function as an argument and returns a new modified function. Something like</p>
<pre><code>metaf(f) -> f**2
</code></pre>
<p>So whatever <code>f</code> would result, <code>metaf</code> would result with the answer to the power of two (and if the result cannot be raised to the power of 2, so be it. Raise an error).</p>
<p>Currently the way I've found to do that requires explicit reference to the argument of <code>f</code> in the definition of <code>metaf</code>, i.e. define</p>
<pre><code>metaf = lambda f, x : f(x)**2
</code></pre>
<p>and then</p>
<pre><code>mynewf = lambda x : metaf(f, x)
</code></pre>
<p>This works, but I wonder if it will hold for complex argument functions where there could be many variation to the input argument. </p>
<p>So I'm wondering if you can suggest a different way, especially one that does not require specifying the argument in <code>metaf</code> definition. </p>
<p><strong>Edit:</strong> Both answers below were helpful. Just for reference, following the answers I've also realized the way to define <code>metaf</code> using lambda expression. Slightly cumbersome, but might still be worth noting:</p>
<pre><code>metaf = lambda func: lambda *args, **kwargs : func(*args, **kwargs)**2
</code></pre>
| 1 | 2016-08-03T06:37:31Z | 38,736,292 | <p>I believe this is what you are after:</p>
<pre><code>def metaf(f):
def func(*r, **kw):
return f(*r, **kw) ** 2
return func
</code></pre>
<p>And now let's define some <code>f</code>...</p>
<pre><code>def f(a, b):
return a + b
</code></pre>
<p>And here is converting it:</p>
<pre><code>mynewf = metaf(f)
</code></pre>
<p>Try it:</p>
<pre><code>In [148]: f(10, 20)
Out[148]: 30
In [149]: mynewf(10, b=20)
Out[149]: 900
</code></pre>
<p>Please note the use of both normal argument and keyword argument in the useage of mynewf. I works as you would expect.</p>
| 4 | 2016-08-03T06:47:16Z | [
"python"
] |
How to proceed multipart/form-data or application/x-www-form-urlencoded request using requests module in python? | 38,736,179 | <p>Our API clients support only multipart/form-data and application/x-www-form-urlencoded format. So, when I try to access their API:</p>
<pre><code>import requests
import json
url = "http://api.client.com/admin/offer"
headers = {"Content-Type": "multipart/form-data", "API-Key": "ffffffffffffffffffffffffffffffffffffffff"}
data = {"Content-Type": "multipart/form-data", "title": "Demo offer", "advertiser": "f4a89a7h1aq", "url": "http://demo.com/", "url_preview": "http://demo.com/", "description": "Bla bla bla", "freshness": "fresh", "total": "2.0", "revenue": "1.8"}
r = requests.post(url, headers=headers, data=json.dumps(data))
print r.text
</code></pre>
<p>I get this:</p>
<pre><code>{"status":2,"error":"Submitted wrong data. Check Content-Type header"}
</code></pre>
<p>How to overcome this issue?</p>
<p>Thanks!</p>
| -1 | 2016-08-03T06:41:41Z | 38,736,498 | <blockquote>
<p>Our API clients support only multipart/form-data and
application/x-www-form-urlencoded format</p>
</blockquote>
<p>Yet you are setting the <code>Content-type</code> <em>header</em> to <code>application/json</code>, which is not <code>multipart/form-data</code> nor <code>application/x-www-form-urlencoded</code>.</p>
<p>Setting the content type in the body of the HTTP request will not help.</p>
<p>It appears that the server does not support JSON. You should try posting the data as a standard form like this:</p>
<pre><code>import requests
import json
url = "http://api.client.com/admin/offer"
headers = {"API-Key": "ffffffffffffffffffffffffffffffffffffffff"}
data = {"title": "Demo offer", "advertiser": "f4a89a7h1aq", "url": "http://demo.com/", "url_preview": "http://demo.com/", "description": "Bla bla bla", "freshness": "fresh", "total": "2.0", "revenue": "1.8"}
r = requests.post(url, headers=headers, data=data)
print r.text
</code></pre>
<p>By default <code>requests.post</code> will set the Content-type header to <code>application/x-www-form-urlencoded</code> and will "urlencode" the data in the body of the request. This should work because you state that the server supports <code>application/x-www-form-urlencoded</code>.</p>
| 2 | 2016-08-03T06:57:54Z | [
"python",
"python-requests",
"urllib"
] |
Python: Issue with Writing over Lines? | 38,736,230 | <p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p>
<blockquote>
<p>NN by</p>
<p>PP at</p>
<p>PP at</p>
</blockquote>
<p>... This is the issue. For whatever reason (one I can't figure out and have been trying to for a few hours), the program I'm using to go through the word inputs isn't clearing duplicates, so the next best thing I can do is the former! Y'know, cycle through the file and delete the duplicates on run. However, whenever I do, this code instead takes the last line of the list and duplicates <em>that</em> hundreds of thousands of times.</p>
<p>Thoughts, please? :(</p>
<p>EDIT: The idea is that cleanseArchive() goes through a file called words.txt, takes any duplicate lines and deletes them. Since Python isn't able to delete lines, though, and I haven't had luck with any other methods, I've turned to essentially saving the non-duplicate data in a list (saveList) and then writing each object from that list into a new file (deleting the old). However, as of the moment as I said, it just repeats the final object of the original list thousands upon thousands of times.</p>
<p>EDIT2: This is what I have so far, taking suggestions from the replies:</p>
<pre><code>def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
</code></pre>
<p>but ATM it's giving me this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 154, in <module>
initialize()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 100, in initialize
cleanseArchive()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 29, in cleanseArchive
f.write(saveList)
TypeError: must be str, not set
</code></pre>
| 0 | 2016-08-03T06:44:19Z | 38,736,326 | <pre><code>for i in saveList:
f.write(n+"\n")
</code></pre>
<p>You basically print the value of <code>n</code> over and over.</p>
<p>Try this:</p>
<pre><code>for i in saveList:
f.write(i+"\n")
</code></pre>
| 1 | 2016-08-03T06:49:06Z | [
"python",
"file",
"io"
] |
Python: Issue with Writing over Lines? | 38,736,230 | <p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p>
<blockquote>
<p>NN by</p>
<p>PP at</p>
<p>PP at</p>
</blockquote>
<p>... This is the issue. For whatever reason (one I can't figure out and have been trying to for a few hours), the program I'm using to go through the word inputs isn't clearing duplicates, so the next best thing I can do is the former! Y'know, cycle through the file and delete the duplicates on run. However, whenever I do, this code instead takes the last line of the list and duplicates <em>that</em> hundreds of thousands of times.</p>
<p>Thoughts, please? :(</p>
<p>EDIT: The idea is that cleanseArchive() goes through a file called words.txt, takes any duplicate lines and deletes them. Since Python isn't able to delete lines, though, and I haven't had luck with any other methods, I've turned to essentially saving the non-duplicate data in a list (saveList) and then writing each object from that list into a new file (deleting the old). However, as of the moment as I said, it just repeats the final object of the original list thousands upon thousands of times.</p>
<p>EDIT2: This is what I have so far, taking suggestions from the replies:</p>
<pre><code>def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
</code></pre>
<p>but ATM it's giving me this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 154, in <module>
initialize()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 100, in initialize
cleanseArchive()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 29, in cleanseArchive
f.write(saveList)
TypeError: must be str, not set
</code></pre>
| 0 | 2016-08-03T06:44:19Z | 38,736,421 | <p>If you just want to delete "duplicated lines", I've modified your reading code:</p>
<pre><code>saveList = []
duplicates = []
with open("words.txt", "r") as ins:
for line in ins:
if line not in duplicates:
duplicates.append(line)
saveList.append(line)
</code></pre>
<p>Additionally take the correction above!</p>
| 0 | 2016-08-03T06:53:39Z | [
"python",
"file",
"io"
] |
Python: Issue with Writing over Lines? | 38,736,230 | <p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p>
<blockquote>
<p>NN by</p>
<p>PP at</p>
<p>PP at</p>
</blockquote>
<p>... This is the issue. For whatever reason (one I can't figure out and have been trying to for a few hours), the program I'm using to go through the word inputs isn't clearing duplicates, so the next best thing I can do is the former! Y'know, cycle through the file and delete the duplicates on run. However, whenever I do, this code instead takes the last line of the list and duplicates <em>that</em> hundreds of thousands of times.</p>
<p>Thoughts, please? :(</p>
<p>EDIT: The idea is that cleanseArchive() goes through a file called words.txt, takes any duplicate lines and deletes them. Since Python isn't able to delete lines, though, and I haven't had luck with any other methods, I've turned to essentially saving the non-duplicate data in a list (saveList) and then writing each object from that list into a new file (deleting the old). However, as of the moment as I said, it just repeats the final object of the original list thousands upon thousands of times.</p>
<p>EDIT2: This is what I have so far, taking suggestions from the replies:</p>
<pre><code>def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
</code></pre>
<p>but ATM it's giving me this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 154, in <module>
initialize()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 100, in initialize
cleanseArchive()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 29, in cleanseArchive
f.write(saveList)
TypeError: must be str, not set
</code></pre>
| 0 | 2016-08-03T06:44:19Z | 38,738,095 | <pre><code>def cleanseArchive():
f = open("words.txt", "r+")
f.seek(0)
given_line = f.readlines()
saveList = set()
for x,y in enumerate(given_line):
t=(y)
saveList.add(t)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
for i in saveList: f.write(i)
</code></pre>
<p>Finished product! I ended up digging into enumerate and essentially just using that to get the strings. Man, Python has some bumpy roads when you get into sets/lists, holy shit. So much stuff not working for very ambiguous reasons! Whatever the case, fixed it up.</p>
| 0 | 2016-08-03T08:15:57Z | [
"python",
"file",
"io"
] |
Python: Issue with Writing over Lines? | 38,736,230 | <p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p>
<blockquote>
<p>NN by</p>
<p>PP at</p>
<p>PP at</p>
</blockquote>
<p>... This is the issue. For whatever reason (one I can't figure out and have been trying to for a few hours), the program I'm using to go through the word inputs isn't clearing duplicates, so the next best thing I can do is the former! Y'know, cycle through the file and delete the duplicates on run. However, whenever I do, this code instead takes the last line of the list and duplicates <em>that</em> hundreds of thousands of times.</p>
<p>Thoughts, please? :(</p>
<p>EDIT: The idea is that cleanseArchive() goes through a file called words.txt, takes any duplicate lines and deletes them. Since Python isn't able to delete lines, though, and I haven't had luck with any other methods, I've turned to essentially saving the non-duplicate data in a list (saveList) and then writing each object from that list into a new file (deleting the old). However, as of the moment as I said, it just repeats the final object of the original list thousands upon thousands of times.</p>
<p>EDIT2: This is what I have so far, taking suggestions from the replies:</p>
<pre><code>def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
</code></pre>
<p>but ATM it's giving me this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 154, in <module>
initialize()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 100, in initialize
cleanseArchive()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 29, in cleanseArchive
f.write(saveList)
TypeError: must be str, not set
</code></pre>
| 0 | 2016-08-03T06:44:19Z | 38,738,823 | <p>Let's clean up this code you gave us in your update:</p>
<pre><code>def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
</code></pre>
<p>We have bad names that don't respect the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">Style Guide for Python Code</a>, we have superfluous code parts, we don't use the full power of Python and part of it is not working.</p>
<p>Let us start with dropping unneeded code while at the same time using meaningful names.</p>
<pre><code>def cleanse_archive():
infile = open("words.txt", "r")
given_lines = infile.readlines()
words = set(given_lines)
infile.close()
outfile = open("words.txt", "w")
outfile.write(words)
</code></pre>
<p>The <code>seek</code> was not needed, the mode for opening a file to read is now just <code>r</code>, the mode for writing is now <code>w</code> and we dropped the removing of the file because it will be overwritten anyway. Having a look at this now clearer code we see, that we missed to close the file after writing. If we open the file with the <code>with</code> statement Python will take care of that for us.</p>
<pre><code>def cleanse_archive():
with open("words.txt", "r") as infile:
words = set(infile.readlines())
with open("words.txt", "w") as outfile:
outfile.write(words)
</code></pre>
<p>Now that we have clear code we'll deal with the error message that occurs when <code>outfile.write</code> is called: <code>TypeError: must be str, not set</code>. This message is clear: You can't write a set directly to the file. Obviously you'll have to loop over the content of the set.</p>
<pre><code>def cleanse_archive():
with open("words.txt", "r") as infile:
words = set(infile.readlines())
with open("words.txt", "w") as outfile:
for word in words:
outfile.write(word)
</code></pre>
<p>That's it.</p>
| 0 | 2016-08-03T08:51:43Z | [
"python",
"file",
"io"
] |
How do I make button press first stopping a playing audio file and then playing its own audio? | 38,736,340 | <p>My problem is, that the audio files under each button are quite lengthy and if I pressed the wrong button, I would have to wait it to play to end. How can I make every button press to 1) stop the possible playing audio file and then 2) play it's own file?
I'm using mpg123 to play the audio files and file names are placeholders.</p>
<p>Code:</p>
<pre><code>#!/usr/bin/env python
import os
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN)
GPIO.setup(19, GPIO.IN)
GPIO.setup(20, GPIO.IN)
GPIO.setup(21, GPIO.IN)
GPIO.setup(22, GPIO.IN)
GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(25, GPIO.IN)
GPIO.setup(26, GPIO.IN)
GPIO.setup(27, GPIO.IN)
while True:
if (GPIO.input(18)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(19)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(20)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(21)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(22)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(23)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(24)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(25)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(26)==False):
os.system('mpg123 audio.mp3 &')
if (GPIO.input(27)==False):
os.system('mpg123 audio.mp3 &')
sleep(0.1):
</code></pre>
| 0 | 2016-08-03T06:49:59Z | 38,740,803 | <p>You can use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> asynchronously so the function call returns immediately. I think it is possible to get a "handle" object to communicate with the external process that also allows you to "<a href="http://stackoverflow.com/questions/16866602/kill-a-running-subprocess-call">kill</a>" it.</p>
<p>Similarly, you could check your keys in the main program and start a thread for playing: <a href="http://docs.python.org/3/library/threading.html" rel="nofollow">http://docs.python.org/3/library/threading.html</a> (does not make much sense as the other program is a new process anyway).</p>
| 0 | 2016-08-03T10:19:42Z | [
"python",
"button",
"audio",
"raspberry-pi",
"gpio"
] |
Can't figure out well why my function is returning True with anagrams | 38,736,714 | <p>This is my function (says if 2 compared words are anagrams or not):</p>
<pre><code>def are_anagrams(word1, word2):
word1list = list(word1)
word2list = list(word2)
anagramfalse = False
anagramtrue = True
if (word1 == word2):
return anagramfalse
if (word1list.sort()) == (word2list.sort()):
return anagramtrue
else:
return anagramfalse
</code></pre>
<p>So this function is returning </p>
<pre><code>are_anagrams("lopped", "poodle")
</code></pre>
<p>as <code>True</code>, for some reason. Can't figure out why. It should be compared the sorted list of letters for each word and returning a <code>False</code>. </p>
<p>Solution? Mainly just want to know what's wrong.</p>
| 0 | 2016-08-03T07:09:32Z | 38,736,848 | <p><code>sort</code> does not do what you think. Observe:</p>
<pre><code>>>> x = list('lopped')
>>> print(x.sort())
None
</code></pre>
<p>Since <code>None == None</code> is always True, the function always returns True.</p>
<p>Further, the code can be simplified:</p>
<pre><code>def are_anagrams(word1, word2):
return sorted(word1) == sorted(word2)
</code></pre>
<p>Sample runs:</p>
<pre><code>>>> are_anagrams("lopped", "poodle")
False
>>> are_anagrams("lopped", "doppel")
True
</code></pre>
<p>Notes:</p>
<ol>
<li><p>Both <code>sort</code> and <code>sorted</code> operate on strings as well as lists. There is no need to convert to lists first.</p></li>
<li><p><code>sorted(word1) == sorted(word2)</code> evaluates to True or False. Consequentl, the <code>if-then-else</code> statement can be eliminated.</p></li>
</ol>
<h3>Extensions to phrases and mixed-case</h3>
<p>Phrases can also be considered anagrams of each other. Also, for anagrams, case should generally be ignored. Thus:</p>
<pre><code>def are_anagrams(word1, word2):
return sorted(word1.lower().replace(' ', '')) == sorted(word2.lower().replace(' ', ''))
</code></pre>
<p>Thus:</p>
<pre><code>>>> are_anagrams('Lopped', 'Ed Plop')
True
</code></pre>
<h3>Rejecting the case of words being equal</h3>
<p>If the words are the same, should they be considered anagrams? If not, then use:</p>
<pre><code> def are_anagrams(word1, word2):
return (word1.lower() != word2.lower()) and sorted(word1.lower().replace(' ', '')) == sorted(word2.lower().replace(' ', ''))
</code></pre>
<p>Example: </p>
<pre><code>>>> are_anagrams('Lopped', 'Lopped')
False
>>> are_anagrams('Lopped', 'Old Pep')
True
</code></pre>
| 1 | 2016-08-03T07:15:51Z | [
"python",
"python-3.x"
] |
Can't figure out well why my function is returning True with anagrams | 38,736,714 | <p>This is my function (says if 2 compared words are anagrams or not):</p>
<pre><code>def are_anagrams(word1, word2):
word1list = list(word1)
word2list = list(word2)
anagramfalse = False
anagramtrue = True
if (word1 == word2):
return anagramfalse
if (word1list.sort()) == (word2list.sort()):
return anagramtrue
else:
return anagramfalse
</code></pre>
<p>So this function is returning </p>
<pre><code>are_anagrams("lopped", "poodle")
</code></pre>
<p>as <code>True</code>, for some reason. Can't figure out why. It should be compared the sorted list of letters for each word and returning a <code>False</code>. </p>
<p>Solution? Mainly just want to know what's wrong.</p>
| 0 | 2016-08-03T07:09:32Z | 38,736,901 | <p>Here's the issue: <code>wordlist.sort()</code> will return <code>None</code> because it does the sorting <strong>in place</strong> comparing <code>None</code> to <code>None</code> will always evaluate to <code>True</code> and yield falsified results. You should be using <code>sorted()</code> which instead returns the newly sorted list and then perform the comparison:</p>
<pre><code>def are_anagrams(word1, word2):
word1list = list(word1)
word2list = list(word2)
anagramfalse = False
anagramtrue = True
if (word1 == word2):
return anagramfalse
if (sorted(word1list)) == (sorted(word2list)):
return anagramtrue
else:
return anagramfalse
</code></pre>
<p>Apart from that, there are further things to note, first, no need to set explicit names for <code>True</code> and <code>False</code>; just return them:</p>
<pre><code>def are_anagrams(word1, word2):
word1list = list(word1)
word2list = list(word2)
if (word1 == word2):
return False
if (sorted(word1list)) == (sorted(word2list)):
return True
else:
return False
</code></pre>
<p>Second off, no need to cast the strings to lists with <code>list</code>, <code>sorted</code> will take care of that for you automatically by creating a <code>list</code> from the string, sorting it and then returning it:</p>
<pre><code>def are_anagrams(word1, word2):
if (word1 == word2):
return False
if (sorted(word1)) == (sorted(word2)):
return True
else:
return False
</code></pre>
<p>Third off <code>word1 == word2</code> won't really do much as a "quick check" to exit early; sorting is <strong>fast</strong> in general, you could drop that all together:</p>
<pre><code>def are_anagrams(word1, word2):
if (sorted(word1)) == (sorted(word2)):
return True
else:
return False
</code></pre>
<p>For the final step to make this code as sortest as possible, look at Johns answer; he simply returns the result of comparing the sorted objects. No need to be explicit if your comparison will yield the right value for you. :-)</p>
| 1 | 2016-08-03T07:18:27Z | [
"python",
"python-3.x"
] |
How to check input against a huge list? | 38,736,722 | <p>This is my code:</p>
<pre><code>while True:
print(vehiclelist)
reg = input('Enter registration number of vehicle: ')
if reg in vehiclelist:
break
else:
print("Invalid")
</code></pre>
<p>But it keeps showing its invalid, this is the output:</p>
<blockquote>
<p>[Car('SJV1883R', 'Honda', 'Civic', 60.00), Car('SJZ2987A', 'Toyota', 'Altis', 60.00), Car('SKA4370H', 'Honda', 'Accord', 80.00),
Car('SKD8024M', 'Toyota', 'Camry', 80.00), Car('SKH5922D', 'BMW',
'320i', 90.00), Car('SKM5139C', 'BMW', '520i', 100.00),
Car('SKP8899H', 'Mercedes', 'S500', 300.00), Truck('GB3221K', 'Tata',
'Magic', 200.00), Truck('YB8283M', 'Isuzu', 'NPR', 250.00),
Truck('YK5133H', 'Isuzu', 'NQR', 300.00)]<br>
Enter registration number of vehicle: SJZ2987A<br>
Invalid</p>
</blockquote>
<p>Any idea how I can check the input?</p>
<p>This is my vehicle class:</p>
<pre><code>class Vehicle():
def __init__(self, regNo, make, model, dailyRate, available):
self.regNo = regNo
self.make = make
self.model = model
self.dailyRate = dailyRate
self.available = available
@property
def dailyRate(self):
return self.__dailyRate
@dailyRate.setter
def dailyRate(self, dailyRate):
if dailyRate < 0:
self.__dailyRate = 0
else:
self.__dailyRate = dailyRate
def __repr__(self):
return "Vehicle('{:s}', '{:s}', '{:s}', {:.2f}, '{:s}')".format(self.regNo, self.make, self.model, self.dailyRate, self.available)
</code></pre>
| 0 | 2016-08-03T07:09:51Z | 38,736,851 | <p>Here the problem is <code>vehicle_list</code> is a list of Vehicle objects and you can not directly search for a registration number inside a list of vehicle object.</p>
<p>A better design pattern is to use a dictionary in which <code>regNo</code> will appear as key and vehicle object will appear as value.</p>
<p>You may change your code as follows:</p>
<pre><code>vehicle_details = {vehicle.regNo : vehicle for vehicle in vehiclelist}
while True:
reg = input('Enter registration number of vehicle: ')
if reg in vehicle_details:
break
else:
print("Invalid")
</code></pre>
| 1 | 2016-08-03T07:16:07Z | [
"python"
] |
How to check input against a huge list? | 38,736,722 | <p>This is my code:</p>
<pre><code>while True:
print(vehiclelist)
reg = input('Enter registration number of vehicle: ')
if reg in vehiclelist:
break
else:
print("Invalid")
</code></pre>
<p>But it keeps showing its invalid, this is the output:</p>
<blockquote>
<p>[Car('SJV1883R', 'Honda', 'Civic', 60.00), Car('SJZ2987A', 'Toyota', 'Altis', 60.00), Car('SKA4370H', 'Honda', 'Accord', 80.00),
Car('SKD8024M', 'Toyota', 'Camry', 80.00), Car('SKH5922D', 'BMW',
'320i', 90.00), Car('SKM5139C', 'BMW', '520i', 100.00),
Car('SKP8899H', 'Mercedes', 'S500', 300.00), Truck('GB3221K', 'Tata',
'Magic', 200.00), Truck('YB8283M', 'Isuzu', 'NPR', 250.00),
Truck('YK5133H', 'Isuzu', 'NQR', 300.00)]<br>
Enter registration number of vehicle: SJZ2987A<br>
Invalid</p>
</blockquote>
<p>Any idea how I can check the input?</p>
<p>This is my vehicle class:</p>
<pre><code>class Vehicle():
def __init__(self, regNo, make, model, dailyRate, available):
self.regNo = regNo
self.make = make
self.model = model
self.dailyRate = dailyRate
self.available = available
@property
def dailyRate(self):
return self.__dailyRate
@dailyRate.setter
def dailyRate(self, dailyRate):
if dailyRate < 0:
self.__dailyRate = 0
else:
self.__dailyRate = dailyRate
def __repr__(self):
return "Vehicle('{:s}', '{:s}', '{:s}', {:.2f}, '{:s}')".format(self.regNo, self.make, self.model, self.dailyRate, self.available)
</code></pre>
| 0 | 2016-08-03T07:09:51Z | 38,766,816 | <p>You need to iterate the individual car objects and compare the <code>regNo</code></p>
<pre><code>def getInput():
while True:
print(vehiclelist)
reg = input('Enter registration number of vehicle: ')
for car in vehiclelist:
if reg == car.regNo:
return
print("Invalid")
</code></pre>
| 0 | 2016-08-04T12:03:26Z | [
"python"
] |
create a table using file contents python | 38,736,806 | <p>if the file for example contains:</p>
<ul>
<li>A: GHJIG</li>
<li>B: AHYFASF</li>
<li>C: IYDDFG</li>
</ul>
<p><code>f = open(example.txt)</code></p>
<p>I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.</p>
<ul>
<li>input: A</li>
<li>output: GHJIG</li>
</ul>
<p>how to do it?</p>
| 0 | 2016-08-03T07:14:04Z | 38,737,131 | <p>Try this:</p>
<pre><code>with open('test.txt','r') as file:
content = file.readlines()
my_dict = {}
for line in content:
split = line.split(':')
my_dict[split[0]] = split[1]
input = raw_input("Choose a letter")
if input in my_dict:
print my_dict[input]
</code></pre>
<p>It would be better to use a OrderedDict from collections, because default dictionary has a not a precise order.</p>
| 0 | 2016-08-03T07:30:42Z | [
"python"
] |
create a table using file contents python | 38,736,806 | <p>if the file for example contains:</p>
<ul>
<li>A: GHJIG</li>
<li>B: AHYFASF</li>
<li>C: IYDDFG</li>
</ul>
<p><code>f = open(example.txt)</code></p>
<p>I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.</p>
<ul>
<li>input: A</li>
<li>output: GHJIG</li>
</ul>
<p>how to do it?</p>
| 0 | 2016-08-03T07:14:04Z | 38,784,384 | <p>Try the solution below, you can provide a useful message if the user enters any alphabet which is not present in your txt file.</p>
<pre><code>with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj:
content = file_obj.readlines()
sample_dict = {}
for value in content:
sample_dict[value.split(':')[0]] = value.split(':')[1]
input_key = raw_input("Please enter an alphabet: \n")
print sample_dict.get(input_key, "No value exists")
</code></pre>
| 0 | 2016-08-05T08:13:53Z | [
"python"
] |
Python to get specific last 2 or 3 characters | 38,736,812 | <p>I'm looking for a Python script that will get the last 2 or 3 specific characters. To be more specific, I'm looking to cut the IP name to the last 2 or 3 digits.</p>
<pre><code>import socket
ip = socket.gethostbyname(socket.gethostname())[-3:0]
</code></pre>
<p>I was thinking of just slicing the ip address and get the last 3 digits but figured that will give me issues when the IP address ends with 2 digits (i.e. 192.168.1.XX)</p>
<p>Any help would be really appreciated!</p>
| 1 | 2016-08-03T07:14:09Z | 38,736,865 | <p>Another option is to <code>lstrip</code> a possibly leading <code>'.'</code>:</p>
<pre><code>import socket
ip = socket.gethostbyname(socket.gethostname())[-3:].lstrip('.')
</code></pre>
<p>An example:</p>
<pre><code>ip1 = '192.168.1.10'
ip2 = '192.168.1.100'
print(ip1[-3:].lstrip('.'))
>> 10
print(ip2[-3:].lstrip('.'))
>> 100
</code></pre>
| 1 | 2016-08-03T07:16:42Z | [
"python"
] |
Python to get specific last 2 or 3 characters | 38,736,812 | <p>I'm looking for a Python script that will get the last 2 or 3 specific characters. To be more specific, I'm looking to cut the IP name to the last 2 or 3 digits.</p>
<pre><code>import socket
ip = socket.gethostbyname(socket.gethostname())[-3:0]
</code></pre>
<p>I was thinking of just slicing the ip address and get the last 3 digits but figured that will give me issues when the IP address ends with 2 digits (i.e. 192.168.1.XX)</p>
<p>Any help would be really appreciated!</p>
| 1 | 2016-08-03T07:14:09Z | 38,736,869 | <pre><code>import socket
ip = socket.gethostbyname(socket.gethostname()).split('.')[-1]
</code></pre>
| 6 | 2016-08-03T07:16:49Z | [
"python"
] |
ElasticSearch and special characters | 38,736,828 | <p>I can not figure out how to look up words with special characters.</p>
<p>For example, I have two documents:</p>
<p>1) We are looking for C++ and C# developers <br/>
2) We are looking for C developers</p>
<p>I want only to find a document which contains <code>C++</code>.</p>
<p>Code for creating an index, documents and searching:</p>
<pre><code>from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
ELASTIC_SEARCH_NODES = ['http://localhost:9200']
INDEX = 'my_index'
DOC_TYPE = 'material'
def create_index():
data = {
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"type": "custom",
"filter": [
"lowercase"
],
"tokenizer": "whitespace",
}
}
}
}
}
print es_client.indices.create(index=INDEX, body=data)
def create_doc(body):
if es_client.exists(INDEX, DOC_TYPE, body['docid']):
es_client.delete(INDEX, DOC_TYPE, body['docid'])
print es_client.create(index=INDEX, doc_type=DOC_TYPE, body=body, id=body['docid'])
def find_doc(value):
results_generator = scan(es_client,
query={"query": {
"match_phrase" : {
"text" : value
}
}},
index=INDEX
)
return results_generator
if __name__ == '__main__':
es_client = Elasticsearch(ELASTIC_SEARCH_NODES, verify_certs=True)
# create_index()
doc1 = {"docid": 1, 'text': u"We are looking for C developers"}
doc2 = {"docid": 2, 'text': u"We are looking for C++ and C# developers"}
# create_doc(doc1)
# create_doc(doc2)
for r in find_doc("C++"):
print r
</code></pre>
<p>Search result(if I <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters" rel="nofollow">escape</a> <code>+</code> (<code>"C\+\+"</code>), the result will be the same):</p>
<pre><code>{u'_score': 0.0, u'_type': u'material', u'_id': u'2', u'_source': {u'text': u'We are looking for C++ and C# developers', u'docid': 2}, u'_index': u'my_index'}
{u'_score': 0.0, u'_type': u'material', u'_id': u'1', u'_source': {u'text': u'We are looking for C developers', u'docid': 1}, u'_index': u'my_index'}
</code></pre>
<p>It seems that such a result is obtained because in the division into tokens symbols like <code>+</code> and <code>#</code> <a href="http://stackoverflow.com/questions/13178550/elasticsearch-return-the-tokens-of-a-field">not indexed</a>, and in fact, it looks for documents in which there is the symbol <code>C</code>:</p>
<pre><code>curl 'http://localhost:9200/my_index/material/_search?pretty=true' -d '{
"query" : {
"match_all" : { }
},
"script_fields": {
"terms" : {
"script": "doc[field].values",
"params": {
"field": "text"
}
}
}
}'
</code></pre>
<p>Result:</p>
<pre><code>{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : 1.0,
"hits" : [ {
"_index" : "my_index",
"_type" : "material",
"_id" : "2",
"_score" : 1.0,
"fields" : {
"terms" : [ "and", "are", "c", "developers", "for", "looking", "we" ]
}
}, {
"_index" : "my_index",
"_type" : "material",
"_id" : "1",
"_score" : 1.0,
"fields" : {
"terms" : [ "are", "c", "developers", "for", "looking", "we" ]
}
}]
}
}
</code></pre>
<p>How can this problem be solved? The second question related to the previous: is it possible to search only non-alphanumeric characters such as <code>%</code> or <code>+</code> ?</p>
<p>P.S. I am using Elastic 2.3.2 and elasticsearch=2.3.0.</p>
| 0 | 2016-08-03T07:14:45Z | 39,289,658 | <p>Thanks <a href="http://ru.stackoverflow.com/a/551949/181420">Andrew</a>, I solved the problem. The problem was that the standard analyzer was used for indexing, and not <em>my_analyzer</em>. Thus, I forgot to use the mapping. The correct version:</p>
<pre><code>data = {
"settings": {
"analysis": {
"analyzer": {
"my_analyzer": {
"type": "custom",
"filter": [
"lowercase"
],
"tokenizer": "whitespace",
}
}
}
},
"mappings": {
"material": {
"properties": {
"docid": {
"type": "integer"
},
"text": {
"type": "string",
"analyzer": "my_analyzer"
}
}
}
}
}
</code></pre>
<p>In addition, it was necessary to recreate the index and add documents.
To search for special characters, you I am using the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html" rel="nofollow">query_string</a>. Code of <code>find_doc</code> function:</p>
<pre><code>def find_doc(value):
results_generator = scan(es_client,
query=
{
"query": {
"filtered" : {
"query" : {
"query_string" : {
"query": value,
"fields" : ["text"],
"analyzer": ANALYZER,
"default_operator": "AND"
},
}
}
}
},
index=INDEX
)
return results_generator
</code></pre>
<p>Examples of queries (now the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html" rel="nofollow">wildcard-characters</a> can be used):</p>
<pre><code>for r in find_doc("*#"):
print r
for r in find_doc(u"%"):
print r
for r in find_doc("looking fo*"):
print r
</code></pre>
<p>Request for verification of the analyzer (on which token string is broken):</p>
<pre><code>curl -XPOST "http://localhost:9200/my_index/_analyze?analyzer=my_analyzer&pretty=true" -d 'We are looking for C++ and C# developers'
</code></pre>
| 0 | 2016-09-02T10:01:13Z | [
"python",
"elasticsearch"
] |
How to check the python socket recvfrom() data | 38,736,833 | <p>I am working on socket programming in python. Using ESP python i have created a socket to server and sending a request (in API packet format, according to server code it will respond). In receiving socket, i need to check the data(if data is received, it need continue to next operation. If not, i need to send request once again).
sending is okay. In receiving socket, if it is not receiving data, it is not going to next instruction.. please help me out.</p>
<p>code:</p>
<pre><code>try:
s = socket(AF_INET, SOCK_DGRAM)
print "socket created"
except socket.error:
print "failed to create socket"
sys.exit()
</code></pre>
<p>sending data: </p>
<pre><code>s.sendto("packet of data", 0, (HOST,PORT))
</code></pre>
<p>In receiving:</p>
<pre><code>recvpack, payload=s.recvfrom(1024)
if not recvpack:
s.sendto("packet of data", 0, (HOST,PORT))
elif(recvpack[]="packet of data"):
pass # continue to next operations..
</code></pre>
<p>In the above receiving statement, if <code>recvfrom()</code> in not getting anydata, how to check <code>recvpack</code> and get back to next operations.. If <code>socket.settimeout()</code> or <code>socket.setblocking()</code> is the solution, how to use these..</p>
| 0 | 2016-08-03T07:15:03Z | 38,738,533 | <p>If you don't mind a blocking call, I usually use settimeout to wait for a message. settimeout will raise an exception if it doesn't receive a message in time. </p>
<p>So basically you could do something like this:</p>
<pre><code>s.settimeout(1)
try:
recvpack, payload = s.recvfrom(1024)
except error:
recvpack = None
if recvpack is not None:
...
</code></pre>
<p>Source : <a href="https://docs.python.org/2/library/socket.html#socket.socket.settimeout" rel="nofollow">https://docs.python.org/2/library/socket.html#socket.socket.settimeout</a></p>
| 0 | 2016-08-03T08:38:05Z | [
"python",
"sockets",
"recv",
"recvfrom"
] |
python classes inheriting from each other | 38,736,838 | <p>I am having 2 Python files in same directory. one.py and two.py containing classes First and Second respectively. <strong>I want import classes and inherit each other and use methods defined in each other</strong>. </p>
<p>one.py</p>
<pre><code>from two import Second
class First(Second):
def first(self):
print "first"
</code></pre>
<p>two.py </p>
<pre><code>from one import First
class Second(First):
def second(self):
print "second"
</code></pre>
<p>while compiling I am getting following error. Is there any way I can overcome this. Please suggest alternative methods also.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\uvijayac\Desktop\New folder\two.py", line 1, in <module>
from one import First
File "C:\Users\uvijayac\Desktop\New folder\one.py", line 1, in <module>
from two import Second
File "C:\Users\uvijayac\Desktop\New folder\two.py", line 1, in <module>
from one import First
ImportError: cannot import name First
</code></pre>
| 0 | 2016-08-03T07:15:10Z | 38,736,932 | <p>The actual problem you're encountering is that you're trying to do a circular import, which has nothing to do with your circular inheritance. (There's plenty of material on SO on how to avoid that.)</p>
<p>However, note that circular inheritance is also not possible, as a class is only available for subclassing once it's defined, and its definition includes being subclassed from the other class, which therefore also needs to already be defined, which requires... you get the point - you can't have circular inheritance.</p>
| 1 | 2016-08-03T07:20:10Z | [
"python",
"class",
"inheritance"
] |
Equivalent code of __getitem__ in __iter__ | 38,736,872 | <p>I am trying to understand more about <code>__iter__</code> in Python 3. For some reason <code>__getitem__</code> is better understood by me than <code>__iter__</code>. I think I get somehow don't get the corresponding <strong>next</strong> implemention followed with <code>__iter__</code>.</p>
<p>I have this following code:</p>
<pre><code>class Item:
def __getitem__(self,pos):
return range(0,30,10)[pos]
item1= Item()
print (f[1]) # 10
for i in item1:
print (i) # 0 10 20
</code></pre>
<p>I understand the code above, but then again how do i write the equivalent code using <code>__iter__</code> and <code>__next__()</code> ?</p>
<pre><code>class Item:
def __iter__(self):
return self
#Lost here
def __next__(self,pos):
#Lost here
</code></pre>
<p>I understand when python sees a <code>__getitem__</code> method, it tries iterating over that object by calling the method with the integer index starting with <code>0</code>.</p>
| 0 | 2016-08-03T07:17:02Z | 38,737,160 | <p>In general, a really good approach is to make <code>__iter__</code> a generator by <code>yield</code>ing values. This might be <em>less</em> intuitive but it is straight-forward; you just yield back the results you want and <code>__next__</code> is then provided automatically for you:</p>
<pre><code>class Item:
def __iter__(self):
for item in range(0, 30, 10):
yield item
</code></pre>
<p>This just uses the power of <code>yield</code> to get the desired effect, when <code>Python</code> calls <code>__iter__</code> on your object, it expects back an <code>iterator</code> (i.e an object that supports <code>__next__</code> calls), a generator does just that, producing each item as defined in your generator function (i.e <code>__iter__</code> in this case) when <code>__next__</code> is called:</p>
<pre><code>>>> i = iter(Item())
>>> print(i) # generator, supports __next__
<generator object __iter__ at 0x7f6aeaf9e6d0>
>>> next(i)
0
>>> next(i)
10
>>> next(i)
20
</code></pre>
<p>Now you get the same effect as <code>__getitem__</code>. The difference is that no <code>index</code> is passed in, you have to manually loop through it in order to yield the result:</p>
<pre><code>>>> for i in Item():
... print(i)
0
10
20
</code></pre>
<p>Apart from this, there's two other alternatives for creating an object that supports Iteration.</p>
<p><strong>One time looping: Make item an iterator</strong></p>
<p>Make <code>Item</code> an iterator by defining <code>__next__</code> and returning <code>self</code> from <code>__iter__</code> in this case, since you're not using <code>yield</code> the <code>__iter__</code> method returns <code>self</code> and <code>__next__</code> handles the logic of returning values:</p>
<pre><code>class Item:
def __init__(self):
self.val = 0
def __iter__(self):
return self
def __next__(self):
if self.val > 2: raise StopIteration
res = range(0, 30, 10)[self.val]
self.val += 1
return res
</code></pre>
<p>This also uses an auxiliary <code>val</code> to get the result from the range and check if we should still be iterating (if not, we raise <code>StopIteration</code>):</p>
<pre><code>>>> for i in Item():
... print(i)
0
10
20
</code></pre>
<p>The problem with this approach is that it is a one time ride, after iterating once, the <code>self.val</code> points to <code>3</code> and iteration can't be performed again. (using <code>yield</code> resolves this issue). (Yes, you could go and set <code>val</code> to 0 but that's just being sneaky.)</p>
<p><strong>Many times looping: create custom iterator object.</strong></p>
<p>The second approach is to use a custom iterator object specifically for your <code>Item</code> class and return it from <code>Item.__iter__</code> instead of <code>self</code>:</p>
<pre><code>class Item:
def __iter__(self):
return IterItem()
class IterItem:
def __init__(self):
self.val = 0
def __iter__(self):
return self
def __next__(self):
if self.val > 2: raise StopIteration
res = range(0, 30, 10)[self.val]
self.val += 1
return res
</code></pre>
<p>Now every time you iterate a new custom iterator is supplied and you can support multiple iterations over <code>Item</code> objects.</p>
| 4 | 2016-08-03T07:32:16Z | [
"python",
"python-3.x",
"iterator"
] |
Equivalent code of __getitem__ in __iter__ | 38,736,872 | <p>I am trying to understand more about <code>__iter__</code> in Python 3. For some reason <code>__getitem__</code> is better understood by me than <code>__iter__</code>. I think I get somehow don't get the corresponding <strong>next</strong> implemention followed with <code>__iter__</code>.</p>
<p>I have this following code:</p>
<pre><code>class Item:
def __getitem__(self,pos):
return range(0,30,10)[pos]
item1= Item()
print (f[1]) # 10
for i in item1:
print (i) # 0 10 20
</code></pre>
<p>I understand the code above, but then again how do i write the equivalent code using <code>__iter__</code> and <code>__next__()</code> ?</p>
<pre><code>class Item:
def __iter__(self):
return self
#Lost here
def __next__(self,pos):
#Lost here
</code></pre>
<p>I understand when python sees a <code>__getitem__</code> method, it tries iterating over that object by calling the method with the integer index starting with <code>0</code>.</p>
| 0 | 2016-08-03T07:17:02Z | 38,737,183 | <p>Iter returns a iterator, mainly a generator as @machineyearning told at the comments, with next you can iterate over the object, see the example:</p>
<pre><code>class Item:
def __init__(self):
self.elems = range(10)
self.current = 0
def __iter__(self):
return (x for x in self.elems)
def __next__(self):
if self.current >= len(self.elems):
self.current = 0
raise StopIteration
return self.elems[self.current]
>>> i = Item()
>>> a = iter(i)
>>> for x in a:
... print x
...
0
1
2
3
4
5
6
7
8
9
>>> for x in i:
... print x
...
0
1
2
3
4
5
6
7
8
9
</code></pre>
| 0 | 2016-08-03T07:32:56Z | [
"python",
"python-3.x",
"iterator"
] |
Python whois.whois returns a property object | 38,736,894 | <p>I'm running whois.whois on Python 3.5 as follows:</p>
<pre><code>def simpleWhois(url):
try:
result = whois.whois(url)
return result
except Exception as error:
print(type(error), error, url)
return pd.Series.empty
</code></pre>
<p>On most URLs e.g. 'google.com' I get a Pandas Series, but on some example like 'www.usaa-a.com' an error is raised, and I get a
<code><property object at 0x00000000XXXX>, Name: whois, dtype: object</code>.
Whose properties are they? How can I get to them? How can I test test that I'm getting this kind of result rather than a series, and perhaps overwrite it with an empty series if I can't get anything useful out of it?
Thanks!</p>
| 0 | 2016-08-03T07:18:11Z | 38,760,068 | <p>I still don't understand why I got a property object, but for this particular problem I came up with the following solution:</p>
<pre><code> def simpleWhois(url):
try:
result = whois.whois(url)
return result
except:
error = sys.exc_info()[0]
print("Error: %s, %s, for %s " % (type(error), error, url))
return whois.parser.WhoisEntry.load(url, '')
</code></pre>
<p>i.e. return an empty whois entry.</p>
| 0 | 2016-08-04T06:35:43Z | [
"python",
"pandas",
"whois"
] |
raise *error doesn't work in Python 2.7; how can I raise a previously captured exception? | 38,736,940 | <p>My code works, but I am thinking there is something wrong with my understanding, or possibly (gasp) an error in Python's <code>raise</code> behavior.</p>
<p>I am looping over a set of arguments. I capture the <em>first</em> error and want to raise it after I have finished looping, with the original traceback etc as described in <a href="http://stackoverflow.com/questions/1350671/inner-exception-with-traceback-in-python">âInner exceptionâ (with traceback) in Python?</a></p>
<p>I obviously want the loop to process all the arguments, and only then tell me what went wrong.</p>
<pre><code>error = None
for arg in arguments:
try:
process(arg)
except ValueError, err:
if not error:
error = sys.exc_info()
if error:
raise error[0], error[1], error[2]
</code></pre>
<p>The last line is the problematic line. It works (demo: <a href="http://ideone.com/HFZETm" rel="nofollow">http://ideone.com/HFZETm</a> -- note how it prints the traceback from the first error, not the last one), but it seems extremely clunky. How could I express that more succinctly?</p>
<p><code>raise error</code> would seem more elegant, but it behaves as if I had simply <code>raise error[0]</code> (or perhaps raise <code>error[1]</code>). <code>raise *error</code> is a syntax error. </p>
| 3 | 2016-08-03T07:20:38Z | 38,737,103 | <p>Maybe, you could just do this:</p>
<pre><code>for arg in arguments:
try:
process(arg)
except ValueError:
raise
</code></pre>
<p>Also, if you're going to do this multiple times, you could just wrap it in a function:</p>
<pre><code>def raise_error(err):
raise err[0], err[1]. err[2]
error = None
for arg in arguments:
try:
process(arg)
except ValueError, err:
if not error:
error = sys.exc_info()
if error:
raise_error(error)
</code></pre>
| 0 | 2016-08-03T07:29:29Z | [
"python",
"python-2.7",
"syntax",
"exception-handling"
] |
TypeError: Can't convert 'coroutine' object to str implicitly | 38,736,986 | <p>trying to pull a JSON object from a <code>.json</code> with python 3.5.2 using async and I'm returned with this error <code>TypeError: Can't convert 'coroutine' object to str implicitly</code> and <code>sys:1: RuntimeWarning: coroutine 'Configuration.parseField' was never awaited</code></p>
<p><strong>I'm using discord.py and asyncio</strong></p>
<p>What do I do?</p>
<p>Here is my code:</p>
<p><strong>Config</strong></p>
<pre><code>class Configuration:
# This is the hard
FILE_PATH="config.json"
async def parseField(fieldname):
json = open(Configuration.FILE_PATH, 'r')
data = json.dumps(json)
await data[fieldname]
</code></pre>
<p><strong>Main</strong></p>
<pre><code>bot_token = Configuration.parseField(fieldname="BOT_TOKEN")
client.run(bot_token)
</code></pre>
| 0 | 2016-08-03T07:23:13Z | 38,738,371 | <p>try</p>
<pre><code>class Configuration:
def __init__(self, filename):
with open(filename, 'r') as f:
self.data = json.load(f)
def __getattr__(self, name):
return self.data[name]
</code></pre>
<p>This way you can use</p>
<pre><code>c = Configuration('config.json')
bot_token = c.token
</code></pre>
| 0 | 2016-08-03T08:30:21Z | [
"python",
"asynchronous"
] |
PySide application crashes when setting a new widget to QScrollArea | 38,737,106 | <p>This is a simplification of an application I wrote.</p>
<p>The application's main window has a button and a checkbox.
The checkbox resides inside a QScrollArea (via a widget).
The checkbox has a number stating how many times that checkbox was created.
Clicking on the button will open a dialog with a refresh button.</p>
<p>Clicking on the refresh button will set a new widget to the scroll area with a new checkbox.</p>
<p>The checkbox has a context menu that opens the same dialog.
However, when the widget is created using the dialog triggered by the context menu of the checkbox the application crashes with the following error:</p>
<blockquote>
<p>2016-08-03 09:22:00.036 Python[17690:408202] modalSession has been
exited prematurely - check for a reentrant call to endModalSession:</p>
<p>Python(17690,0x7fff76dcb300) malloc: <strong>* error for object
0x7fff5fbfe2c0: pointer being freed was not allocated
*</strong> set a breakpoint in malloc_error_break to debug</p>
</blockquote>
<p><strong>The crash doesn't happen when clicking on the button to open the dialog and clicking refresh from the dialog.</strong></p>
<p>The crash happens on both Mac and Windows.
I am using Python 2.7.10 with PySide 1.2.4</p>
<p><a href="http://i.stack.imgur.com/eF2qc.png" rel="nofollow"><img src="http://i.stack.imgur.com/eF2qc.png" alt="Context menu of the checkbox"></a><a href="http://i.stack.imgur.com/tI7IK.png" rel="nofollow"><img src="http://i.stack.imgur.com/tI7IK.png" alt="Main Window"></a></p>
<pre><code>#!/usr/bin/env python
import sys
from itertools import count
from PySide import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.centralwidget = QtGui.QWidget(parent=self)
self.open_diag_btn = QtGui.QPushButton('Open dialog', parent=self)
self.open_diag_btn.clicked.connect(self.open_dialog)
self.scroll_widget = QtGui.QScrollArea(parent=self)
layout = QtGui.QGridLayout(self.centralwidget)
layout.addWidget(self.scroll_widget)
layout.addWidget(self.open_diag_btn)
self.setCentralWidget(self.centralwidget)
self.set_scroll_widget()
def open_dialog(self):
dialog = Dialog(parent=self)
dialog.refresh.connect(self.set_scroll_widget) # Connecting the signal from the dialog to set a new widget to the scroll area
dialog.exec_()
# Even if I call the function here, after the dialog was closed instead of using the signal above the application crashes, but only via the checkbox
# self.set_scroll_widget()
def set_scroll_widget(self):
"""Replacing the widget of the scroll area with a new one.
The checkbox in the layout of the widget has an class instance counter so you can see how many times the checkbox was created."""
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout(widget)
widget.setLayout(layout)
open_diag_check = RefreshCheckbox(parent=self)
open_diag_check.do_open_dialog.connect(self.open_dialog) # Connecting the signal to open the dialog window
layout.addWidget(open_diag_check)
self.scroll_widget.setWidget(widget)
class RefreshCheckbox(QtGui.QCheckBox):
"""A checkbox class that has a context menu item which emits a signal that eventually opens a dialog window"""
do_open_dialog = QtCore.Signal()
_instance_counter = count(1)
def __init__(self, *args, **kwargs):
super(RefreshCheckbox, self).__init__(unicode(self._instance_counter.next()), *args, **kwargs)
self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
action = QtGui.QAction(self)
action.setText("Open dialog")
action.triggered.connect(self.emit_open_dialog)
self.addAction(action)
def emit_open_dialog(self):
self.do_open_dialog.emit()
class Dialog(QtGui.QDialog):
"""A dialog window with a button that emits a refresh signal when clicked.
This signal is used to call MainWindow.set_scroll_widget()"""
refresh = QtCore.Signal()
def __init__(self, *args, **kwargs):
super(Dialog, self).__init__(*args, **kwargs)
self.refresh_btn = QtGui.QPushButton('Refresh')
self.refresh_btn.clicked.connect(self.do_refresh)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.refresh_btn)
def do_refresh(self):
self.refresh.emit()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mySW = MainWindow()
mySW.show()
mySW.raise_()
app.exec_()
</code></pre>
| 1 | 2016-08-03T07:29:41Z | 38,750,447 | <p>It looks like Python is trying to delete an object (or one of its child objects) which is no longer there - but quite what causes that to happen is not completely clear to me. The problematic object is the widget set on the scroll-area. If you excplicitly keep a reference to it:</p>
<pre><code> def set_scroll_widget(self):
self._old_widget = self.scroll_widget.takeWidget()
...
</code></pre>
<p>your example will no longer dump core.</p>
<p>I think running the dialog with <code>exec</code> may somehow be the proximal cause of the problem, since this means it will run with its own event-loop (which might have an affect on the order of deletion-related events). I was able to find a better fix for your example by running the dialog with <code>show</code>:</p>
<pre><code>def open_dialog(self):
dialog = Dialog(parent=self)
dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
dialog.refresh.connect(self.set_scroll_widget)
dialog.setModal(True)
dialog.show()
</code></pre>
<p>Doing things this way means it's no longer necessary to keep an explicit reference to the previous scroll-area widget.</p>
| 1 | 2016-08-03T17:46:55Z | [
"python",
"qt",
"pyside"
] |
Loss of precision while converting floats to strings in pandas | 38,737,134 | <p>I am converting in Python some floats (some shorter some longer) to strings and getting unexpected (?) results:</p>
<p><strong>Case 1</strong></p>
<pre><code>pd.options.display.float_format = '{:.2f}'.format
pd.DataFrame({'x': [12345.67]})
x
0 12345.67
</code></pre>
<p><strong>Case 2</strong></p>
<pre><code>pd.DataFrame({'x': [1234589890808980.67]})
x
0 1234589890808980.75
</code></pre>
<p><strong>Case 3</strong></p>
<pre><code>pd.DataFrame({'x': [1234589890878708980.67]})
x
0 1234589890878708992.00
</code></pre>
<p>I even tried dtypes <code>np.float128</code> and <code>np.longdouble</code>, but without avail.</p>
<p>Can somebody please explain what is happenning here and is "proper" conversion posiible in Cases 2 and 3?</p>
<p>Thanks!</p>
| 2 | 2016-08-03T07:30:47Z | 38,737,328 | <p>I'm afraid this "issue" happens in the Python (instead of pandas) side. When you have some instant values like <code>1234589890878708980.67</code> it's recognized as <code>float</code> and loses precision instantly, e.g.:</p>
<pre><code>>>> 1234589890878708980.67
1.234589890878709e+18
>>> 1234589890878708980.67 == 1234589890878708980.6712345
True
</code></pre>
<p>You might try something like <code>decimal.Decimal</code>:</p>
<pre><code>>>> import decimal
>>> pd.DataFrame({'x': [decimal.Decimal('1234589890808980.67')]})
x
0 1234589890808980.67
</code></pre>
<p><strong>EDITED:</strong></p>
<p>OP's added a few questions in the comment.</p>
<blockquote>
<p>However, do I understand it right that for this method work correctly the value should be string in the first place?</p>
</blockquote>
<p>Yes :)</p>
<blockquote>
<p>What if it's float read from csv file?</p>
</blockquote>
<p>AFAIK Python's <code>csv</code> reader shall not have performed any type conversion, and you'll get strings that could be later converted freely. Otherwise if you're using <code>pandas.read_csv</code>, you could try setting the <code>dtype</code> and <code>float_precision</code> arguments (you could also ask pandas to load plain strings, and have the values converted later yourself).</p>
| 3 | 2016-08-03T07:39:40Z | [
"python",
"string",
"pandas",
"floating-point"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.