title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Use of hdf5 library in Python with ctypes | 39,154,663 | <p>I would like to use <code>hdf5</code> library directly from <code>Python</code> with <code>ctypes</code>. I know that <code>h5py</code> and <code>PyTables</code> do the job perfectly. The reason I want to do this: I need to work with <code>hdf5</code> files with a <code>Python</code> interpreter where I can not install any package.</p>
<p>I am looking for an example that creates a file and write a list of doubles. </p>
<p>So far, I have written</p>
<pre><code>from ctypes import *
hdf5Lib=r'/usr/local/lib/libhdf5.dylib'
lib=cdll.LoadLibrary(hdf5Lib)
major = c_uint()
minor = c_uint()
release = c_uint()
lib.H5get_libversion(byref(major), byref(minor), byref(release))
H5Fopen=lib.H5Fopen
...
</code></pre>
<p>I don't know how to call H5Fopen. Should I use <code>H5Fopen.argtypes</code>? Any advice is welcome is to open the hdf5 file, create a dataset that of doubles, write the data and close the file.</p>
| 0 | 2016-08-25T21:01:28Z | 39,174,875 | <p>I have followed the advices given, and I have written a small C program to discover the value of different macros. </p>
<pre><code>#include "hdf5.h"
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
printf("H5F_ACC_TRUNC = %u\n",H5F_ACC_TRUNC);
printf("H5P_DEFAULT = %u\n",H5P_DEFAULT);
printf("H5T_STD_I32LE = %u\n",H5T_STD_I32LE);
printf("H5T_STD_I32BE = %i\n",H5T_STD_I32BE);
printf("H5T_NATIVE_INT = %u\n",H5T_NATIVE_INT);
printf("H5S_ALL = %u\n",H5S_ALL);
return 0;
}
</code></pre>
<p>which produce</p>
<pre><code>H5F_ACC_TRUNC = 2
H5P_DEFAULT = 0
H5T_STD_I32LE = 50331712
H5T_STD_I32BE = 50331713
H5T_NATIVE_INT = 50331660
H5S_ALL = 0
</code></pre>
| 0 | 2016-08-26T21:30:06Z | [
"python",
"ctypes",
"hdf5"
] |
Installing basemap | 39,154,666 | <p>There are some pretty helpful links in <a href="http://gnperdue.github.io/yak-shaving/osx/python/matplotlib/2014/05/01/basemap-toolkit.html" rel="nofollow">installing basemap</a> for python, however I seem to be encountering an issue towards the end of installation when trying to test if the installation has worked or not. I'm installing on a Mac.</p>
<p>The error message I'm seeing is: </p>
<pre><code> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 475, in _parse_localename
raise ValueError, 'unknown locale: %s' % locale name
</code></pre>
<p>Admittedly I'm still not savvy with knowing my way around Macs and installing the anaconda suite took me a while to figure out. In my .profile file I added the following lines:</p>
<pre><code>export LC_ALL=en_US.UTF-8
epxort LANG=en_US.UTF-8
</code></pre>
<p>Still didn't change anything. Where am I going wrong?</p>
| 2 | 2016-08-25T21:01:46Z | 39,156,099 | <p>You should try to set the locale of python before importing basemap </p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, 'en_US')
</code></pre>
| 1 | 2016-08-25T23:13:03Z | [
"python",
"installation",
"matplotlib-basemap"
] |
How do I make a Python Docker image an OpenWhisk action? | 39,154,762 | <p>I have a Docker image which runs a Python program. I want now to run this container as an OpenWhisk action. How do I do this? </p>
<p>I have seen several examples in other programming languages, and an excellent <a href="http://blog.altoros.com/how-to-use-openwhisk-docker-actions-in-ibm-bluemix.html" rel="nofollow">black box</a> skeleton approach in C and Node.js. but I want to understand more about how OpenWhisk interacts with the container and, if possible, employ just Python.</p>
| 2 | 2016-08-25T21:09:08Z | 39,154,763 | <p>It's a lot simpler now (Sept 2016) than in my previous answer.</p>
<p>After having created the <code>dockerSkeleton</code> directory with the command <code>$ wsk sdk install docker</code> all you have to do is to edit the <code>Dockerfile</code> and make sure your Python (2.7 right now) is accepting parameters and supplying outputs in the appropriate format.</p>
<p>Here's a summary. I've written it up in greater detail <a href="https://github.com/iainhouston/dockerPython" rel="nofollow">here on GitHub</a></p>
<h3>The program</h3>
<p>File <code>test.py</code> (or <code>whatever_name.py</code> you will use in your edited <code>Dockerfile</code> below.) </p>
<ul>
<li>Make sure it's executable (<code>chmod a+x test.py</code>).</li>
<li>Make sure it's got the shebang on line one.</li>
<li>Make sure it runs locally.
<ul>
<li>e.g. <code>./test.py '{"tart":"tarty"}'</code><br>
produces the JSON dictionary:<br>
<code>{"allparams": {"tart": "tarty", "myparam": "myparam default"}}</code></li>
</ul></li>
</ul>
<pre> <code>
#!/usr/bin/env python
import sys
import json
def main():
# accept multiple '--param's
params = json.loads(sys.argv[1])
# find 'myparam' if supplied on invocation
myparam = params.get('myparam', 'myparam default')
# add or update 'myparam' with default or
# what we were invoked with as a quoted string
params['myparam'] = '{}'.format(myparam)
# output result of this action
print(json.dumps({ 'allparams' : params}))
if __name__ == "__main__":
main()
</code> </pre>
<h3>The Dockerfile</h3>
<p>Compare the following with the supplied <code>Dockerfile</code> to take the Python script <code>test.py</code> and ready it to build the docker image. </p>
<p>Hopefully the comments explain the differences. Any assets (data files or modules) in the current directory will become part of the image as will any Python dependencies listed in <code>requirements.txt</code></p>
<pre><code># Dockerfile for Python whisk docker action
FROM openwhisk/dockerskeleton
ENV FLASK_PROXY_PORT 8080
# Install our action's Python dependencies
ADD requirements.txt /action/requirements.txt
RUN cd /action; pip install -r requirements.txt
# Ensure source assets are not drawn from the cache
# after this date
ENV REFRESHED_AT 2016-09-05T13:59:39Z
# Add all source assets
ADD . /action
# Rename our executable Python action
ADD test.py /action/exec
# Leave CMD as is for Openwhisk
CMD ["/bin/bash", "-c", "cd actionProxy && python -u actionproxy.py"]
</code></pre>
<p>Note the <code>ENV REFRESHED_AT ...</code> which I used to make sure that an updated <code>test.py</code> layer is picked up afresh rather than being drawn from the cache when the image is built.</p>
| 3 | 2016-08-25T21:09:08Z | [
"python",
"docker",
"openwhisk"
] |
Postgres syntax error on a DELETE query | 39,154,774 | <p>I've successfully run this query as a <code>SELECT</code> using DataGrip directly against the specified table, but when I try to run it as a <code>DELETE</code>, it's resulting in a syntax error.</p>
<p>Code:</p>
<pre><code>conn = psycopg2.connect(connection_str.format(*connection_args))
with conn, conn.cursor() as curs:
delete_duplicates_command = """
DELETE FROM (SELECT *, row_number() OVER (PARTITION BY {pk}
ORDER BY _ts DESC) as row_num
FROM {table}) as t
WHERE t.row_num != 1;
""".format(table=target_table, pk=primary_key)
curs.execute(delete_duplicates_command)
</code></pre>
<p>Error:</p>
<pre><code>Migration failed: syntax error at or near "("
LINE 2: DELETE FROM (SELECT *, row_number() OVER (PARTIT...
^
</code></pre>
<p>Both the table and primary key are valid string values. I've tried reformatting this command multiple ways ways to no avail.</p>
<p>FYI I'm using <code>psycopg2==2.6</code> and <code>Python 2.7.3</code></p>
<hr>
<p>Trying to rewrite the query to avoid doing a select inside the delete:</p>
<pre><code>WITH ordered_table AS
(SELECT *, row_number() OVER (PARTITION BY pk ORDER BY _ts DESC) as row_num
FROM orig_table)
DELETE FROM orig_table
USING ordered_table
WHERE ordered_table.row_num > 1;
</code></pre>
<p>Which results in the follow error:
<code>ERROR: syntax error at or near "DELETE"</code></p>
| 1 | 2016-08-25T21:09:50Z | 39,154,917 | <p>from the docs:</p>
<pre><code>cur.execute(
"""INSERT INTO some_table (an_int, a_date, another_date, a_string)
VALUES (%(int)s, %(date)s, %(date)s, %(str)s);""",
{'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})
</code></pre>
<p>so, for you:</p>
<pre><code>cur = conn.cursor()
query = """DELETE FROM (SELECT *, row_number() OVER (PARTITION BY (%(pk)s)
ORDER BY _ts DESC) as row_num
FROM (%(table)s) as t
WHERE t.row_num != 1;"""
cur.execute(query, {'pk': whateverpkis, 'table': whatevertableis})
</code></pre>
<p><a href="http://initd.org/psycopg/docs/usage.html" rel="nofollow">http://initd.org/psycopg/docs/usage.html</a></p>
| 0 | 2016-08-25T21:22:14Z | [
"python",
"postgresql",
"amazon-redshift",
"psycopg2"
] |
PyQt, Any way to use one changeValue method for multiple sliders? | 39,154,886 | <p>I need to have 3 sliders (or more). So at the moment, I have three different changeValues methods for each slider. </p>
<p>In initUI(self), I have three sliders:</p>
<pre><code> sigmaTitle = QtGui.QLabel('Sigma')
sigmaSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
sigmaSlider.setRange(0, 100)
sigmaSlider.valueChanged[int].connect(self.sigmaChangeValue)
dtTitle = QtGui.QLabel('Sigma')
dtSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
dtSlider.setRange(200, 400)
dtSlider.valueChanged[int].connect(self.dtChangeValue)
rTitle = QtGui.QLabel('Sigma')
rSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
rSlider.setRange(300, 400)
rSlider.valueChanged[int].connect(self.rChangeValue)
</code></pre>
<p>Then I have three changeValue methods:</p>
<pre><code>def sigmaChangeValue(self, value):
self.sigma = value / 1000.0
print self.sigma
def dtChangeValue(self, value):
self.dt = value / 1000.0
print self.dt
def rChangeValue(self, value):
self.r = value / 1000.0
print self.r
</code></pre>
<p>so is there a way to use one share changeValue method and still allow to individually assign variable with different range?</p>
<p>Thanks </p>
| 0 | 2016-08-25T21:19:28Z | 39,160,103 | <p>Yes, you can connect all slider <code>valueChanged</code> signals to the same slot.
If you need to know which slider has sent the signal, you can use the <code>QObject.sender()</code> method inside the slot.
See <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qobject.html#sender" rel="nofollow">QObject.sender()</a> </p>
<p>Example:</p>
<pre><code>#create the sliders using self:
self.sigmaSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self)
self.sigmaSlider.setRange(0, 100)
#etc...
</code></pre>
<p>The slot:</p>
<pre><code>def mySlot(self, value):
if self.sender() == self.sigmaSlider:
self.sigma = value / 1000.0
print self.sigma
elif self.sender() == self.dtSlider:
#etc....
</code></pre>
| 0 | 2016-08-26T06:55:20Z | [
"python",
"qt",
"pyqt",
"slider"
] |
How can I dynamically read streamed/pushed data from a webpage with java or Python? | 39,154,937 | <p>I am looking for the best approach that can help me to fetch/receive a Push Stream (e.g. lightstreamer) from a Web-Page. </p>
<p>It is not possible to program a crawler for this as the website updates a Table via JavaScript every 5 seconds, it is dynamically loaded. </p>
<p>I want this Table of data from this web page, but I do not know how I can do this with Java or Python. I have searched a lot and most answers are for questions like âHow to stream data from the serverâ but what I want is the exact opposite, how can I read dynamically streamed/pushed data from a web page?</p>
| 0 | 2016-08-25T21:24:07Z | 39,155,256 | <p>You can use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> to retrieve the web page.</p>
<p>Then parse the response every 5sec.</p>
| 0 | 2016-08-25T21:49:31Z | [
"javascript",
"java",
"python",
"http",
"stream"
] |
How can I dynamically read streamed/pushed data from a webpage with java or Python? | 39,154,937 | <p>I am looking for the best approach that can help me to fetch/receive a Push Stream (e.g. lightstreamer) from a Web-Page. </p>
<p>It is not possible to program a crawler for this as the website updates a Table via JavaScript every 5 seconds, it is dynamically loaded. </p>
<p>I want this Table of data from this web page, but I do not know how I can do this with Java or Python. I have searched a lot and most answers are for questions like âHow to stream data from the serverâ but what I want is the exact opposite, how can I read dynamically streamed/pushed data from a web page?</p>
| 0 | 2016-08-25T21:24:07Z | 39,355,646 | <p>It looks like their <a href="http://www.lightstreamer.com/repo/distros/Lightstreamer_Allegro-Presto-Vivace_6_0_3_20160905.zip%23/Lightstreamer/DOCS-SDKs/sdk_client_web_unified/doc/API-reference/index.html" rel="nofollow">JavaScript Client Library</a> is what you want. If you program it in Python or Java you'll just be moving the problem to the server side and still need an answer on the web side.</p>
| 0 | 2016-09-06T18:32:19Z | [
"javascript",
"java",
"python",
"http",
"stream"
] |
pyodbc/sqlalchemy - read each column in the table using pd.read_sql_query. Pass variable through the query | 39,154,972 | <p>I want to pass a variable 'single_column' through pd.read_sql_query in loop:</p>
<pre><code>for single_column in columns_list:
df_trial_queries = pd.read_sql_query("SELECT single_column FROM dw.db.table;",db_cnxn)
</code></pre>
<p>I tried to use something like this:</p>
<pre><code>for single_column in columns_list:
df_trial_queries = pd.read_sql_query("SELECT %(column_name)s FROM dw.db.table;",db_cnxn,params = {'column_name':single_column})
</code></pre>
<p>No luck at all!</p>
| 0 | 2016-08-25T21:27:05Z | 39,155,116 | <p>You can't "paremeterize" table or column names in SQL (SQL allows to "parameterize" <a href="https://en.wikipedia.org/wiki/Literal_(computer_programming)" rel="nofollow">literals</a> only), but you can easily do it on Python level:</p>
<pre><code>In [25]: single_column = 'col1'
In [52]: table = 'dw.db.table'
In [53]: "SELECT {} FROM {}".format(single_column, table)
Out[53]: 'SELECT col1 FROM dw.db.table'
</code></pre>
<p>or in your case:</p>
<pre><code>df_trial_queries = pd.read_sql_query("SELECT {} FROM dw.db.table".format(single_column), db_cnxn)
</code></pre>
<p>NOTE: it's very inefficient way! I'm sure there is a better way to achieve your goals, but you would have to shed some light on what are you going to achieve using this loop...</p>
| 1 | 2016-08-25T21:38:36Z | [
"python",
"sql",
"pandas",
"sqlalchemy",
"pyodbc"
] |
How to get elements in a string after and until a specific point in Python? | 39,155,022 | <p>I'm sure the title sounded a bit cryptic but I couldn't think of a better way to ask the question.</p>
<p>I have this code: </p>
<pre><code>from bs4 import BeautifulSoup
from requests import get
import re
eune = 'http://www.lolking.net/leaderboards#/eune/1'
patt = re.compile("\$\.get\('/leaderboards/(\w+)/")
js = 'http://www.lolking.net/leaderboards/{}/eune/1.json'
url = get(eune)
soup = BeautifulSoup(url.text, 'lxml')
script = soup.find('script', text=re.compile("\$\.get\('/leaderboards/"))
val = patt.search(script.text).group(1)
json = get(js.format(val)).json()
print(str(json))
</code></pre>
<p>Basically I'm trying to make a username scraper and I'm getting the data in a json format which outputs like this:</p>
<pre><code>{'data': [{'summoner_id': '42893043', 'tier': '6', 'global_ranking': '17', 'name': 'Sadastyczny', 'lks': '2961', 'wins': '128', 'region': 'eune', 'profile_icon_id': 944, 'division': '1', 'previous_ranking': '1', 'ranking': '1', 'tier_name': 'CHALLENGER', 'losses': '31', 'most_played_champions': [{'wins': '34', 'kills': '288', 'deaths': '131', 'creep_score': '7227', 'played': '39', 'champion_id': '236', 'assists': '238', 'losses': '5'}, {'wins': '24', 'kills': '204', 'deaths': '111', 'creep_score': '5454', 'played': '27', 'champion_id': '429', 'assists': '209', 'losses': '3'}, {'wins': '18', 'kills': '168', 'deaths': '103', 'creep_score': '4800', 'played': '26', 'champion_id': '81', 'assists': '155', 'losses': '8'}], 'league_points': '1217'}, {'summoner_id': '40385818', 'tier': '6', 'global_ranking': '40', 'name': 'Richor', 'lks': '2955', 'wins': '260', 'region': 'eune', 'profile_icon_id': 577, 'division': '1', 'previous_ranking': '2', 'ranking': '2', 'tier_name': 'CHALLENGER', 'losses': '187', 'most_played_champions': [{'wins': '150', 'kills': '1923', 'deaths': '1466', 'creep_score': '38820', 'played': '217', 'champion_id': '24', 'assists': '952', 'losses': '67'}, {'wins': '53', 'kills': '662', 'deaths': '584', 'creep_score': '16836', 'played': '90', 'champion_id': '67', 'assists': '501', 'losses': '37'}, {'wins': '15', 'kills': '150', 'deaths': '211', 'creep_score': '5372', 'played': '29', 'champion_id': '157', 'assists': '135', 'losses': '14'}], 'league_points': '1100'}, {'summoner_id': '21348510', 'tier': '6', 'global_ranking': '44', 'name': 'Azzapp', 'lks': '2954', 'wins': '415', 'region': 'eune', 'profile_icon_id': 588, 'division': '1', 'previous_ranking': '6', 'ranking': '3', 'tier_name': 'CHALLENGER', 'losses': '348', 'most_played_champions': [{'wins': '70', 'kills': '645', 'deaths': '576', 'creep_score': '9538', 'played': '122', 'champion_id': '161', 'assists': '1293', 'losses': '52'}, {'wins': '44', 'kills': '644', 'deaths': '385', 'creep_score': '14366', 'played': '80', 'champion_id': '202', 'assists': '762', 'losses': '36'}, {'wins': '41', 'kills': '473', 'deaths': '252', 'creep_score': '12970', 'played': '68', 'champion_id': '103', 'assists': '473', 'losses': '27'}], 'league_points': '1071'}, {'summoner_id': '24275559', 'tier': '6', 'global_ranking': '58', 'name': 'YanetGarcia1337', 'lks': '2953', 'wins': '152', 'region': 'eune', 'profile_icon_id': 1227, 'division': '1', 'previous_ranking': '3', 'ranking': '4', 'tier_name': 'CHALLENGER', 'losses': '47', 'most_played_champions': [{'wins': '59', 'kills': '199', 'deaths': '99', 'creep_score': '11927', 'played': '66', 'champion_id': '117', 'assists': '638', 'losses': '7'}, {'wins': '32', 'kills': '192', 'deaths': '99', 'creep_score': '8061', 'played': '43', 'champion_id': '48', 'assists': '345', 'losses': '11'}, {'wins': '20', 'kills': '165', 'deaths': '64', 'creep_score': '5584', 'played': '31', 'champion_id': '114', 'assists': '161', 'losses': '11'}], 'league_points': '1051'}, {'summoner_id': '31881620', 'tier': '6', 'global_ranking': '66', 'name': 'Rapisher', 'lks': '2952', 'wins': '158', 'region': 'eune', 'profile_icon_id': 518, 'division': '1', 'previous_ranking': '4', 'ranking': '5', 'tier_name': 'CHALLENGER', 'losses': '92', 'most_played_champions': [{'wins': '100', 'kills': '887', 'deaths': '597', 'creep_score': '26352', 'played': '137', 'champion_id': '429', 'assists': '905', 'losses': '37'}, {'wins': '22', 'kills': '10', 'deaths': '120', 'creep_score': '425', 'played': '36', 'champion_id': '40', 'assists': '533', 'losses': '14'}, {'wins': '15', 'kills': '162', 'deaths': '126', 'creep_score': '6134', 'played': '29', 'champion_id': '236', 'assists': '194', 'losses': '14'}], 'league_points': '1030'}, {'summoner_id': '36880627', 'tier': '6', 'global_ranking': '82', 'name': 'Kizuro', 'lks': '2951', 'wins': '158', 'region': 'eune', 'profile_icon_id': 909, 'division': '1', 'previous_ranking': '5', 'ranking': '6', 'tier_name': 'CHALLENGER', 'losses': '79', 'most_played_champions': [{'wins': '32', 'kills': '359', 'deaths': '190', 'creep_score': '1952', 'played': '49', 'champion_id': '76', 'assists': '377', 'losses': '17'}, {'wins': '29', 'kills': '297', 'deaths': '153', 'creep_score': '1266', 'played': '38', 'champion_id': '60', 'assists': '387', 'losses': '9'}, {'wins': '24', 'kills': '254', 'deaths': '163', 'creep_score': '1202', 'played': '37', 'champion_id': '64', 'assists': '308', 'losses': '13'}], 'league_points': '1010'}, {'summoner_id': '44064579', 'tier': '6', 'global_ranking': '124', 'name': 'Nataa', 'lks': '2946', 'wins': '278', 'region': 'eune', 'profile_icon_id': 2076, 'division': '1', 'previous_ranking': '7', 'ranking': '7', 'tier_name': 'CHALLENGER', 'losses': '213', 'most_played_champions': [{'wins': '52', 'kills': '651', 'deaths': '405', 'creep_score': '17094', 'played': '82', 'champion_id': '67', 'assists': '445', 'losses': '30'}, {'wins': '44', 'kills': '584', 'deaths': '354', 'creep_score': '16397', 'played': '74', 'champion_id': '236', 'assists': '463', 'losses': '30'}, {'wins': '25', 'kills': '349', 'deaths': '208', 'creep_score': '9768', 'played': '45', 'champion_id': '81', 'assists': '331', 'losses': '20'}], 'league_points': '920'}, {'summoner_id': '24504284', 'tier': '6', 'global_ranking': '165', 'name': 'Huunntér', 'lks': '2943', 'wins': '148', 'region': 'eune', 'profile_icon_id': 1234, 'division': '1', 'previous_ranking': '8', 'ranking': '8', 'tier_name': 'CHALLENGER', 'losses': '67', 'most_played_champions': [{'wins': '36', 'kills': '267', 'deaths': '263', 'creep_score': '2331', 'played': '54', 'champion_id': '60', 'assists': '449', 'losses': '18'}, {'wins': '33', 'kills': '270', 'deaths': '149', 'creep_score': '2880', 'played': '39', 'champion_id': '104', 'assists': '296', 'losses': '6'}, {'wins': '22', 'kills': '102', 'deaths': '76', 'creep_score': '865', 'played': '25', 'champion_id': '421', 'assists': '279', 'losses': '3'}], 'league_points': '858'}, {'summoner_id': '27565071', 'tier': '6', 'global_ranking': '209', 'name': 'Hades147', 'lks': '2941', 'wins': '243', 'region': 'eune', 'profile_icon_id': 588, 'division': '1', 'previous_ranking': '9', 'ranking': '9', 'tier_name': 'CHALLENGER', 'losses': '146', 'most_played_champions': [{'wins': '73', 'kills': '741', 'deaths': '261', 'creep_score': '5693', 'played': '94', 'champion_id': '102', 'assists': '675', 'losses': '21'}, {'wins': '27', 'kills': '199', 'deaths': '203', 'creep_score': '9370', 'played': '51', 'champion_id': '117', 'assists': '514', 'losses': '24'}, {'wins': '25', 'kills': '187', 'deaths': '179', 'creep_score': '2047', 'played': '42', 'champion_id': '79', 'assists': '420', 'losses': '17'}], 'league_points': '811'}, {'summoner_id': '35655567', 'tier': '6', 'global_ranking': '210', 'name': 'Yolo Que Warrior', 'lks': '2941', 'wins': '210', 'region': 'eune', 'profile_icon_id': 682, 'division': '1', 'previous_ranking': '11', 'ranking': '10', 'tier_name': 'CHALLENGER', 'losses': '148', 'most_played_champions': [{'wins': '46', 'kills': '445', 'deaths': '252', 'creep_score': '15061', 'played': '74', 'champion_id': '236', 'assists': '437', 'losses': '28'}, {'wins': '39', 'kills': '394', 'deaths': '179', 'creep_score': '3349', 'played': '68', 'champion_id': '76', 'assists': '593', 'losses': '29'}, {'wins': '22', 'kills': '267', 'deaths': '117', 'creep_score': '2683', 'played': '37', 'champion_id': '203', 'assists': '271', 'losses': '15'}], 'league_points': '811'}], 'status': True}
</code></pre>
<p>Now I need to find whatever is after <code>'name': '</code> and stop at <code>'</code> and store that in a list.
How would I do this?</p>
| 0 | 2016-08-25T21:31:45Z | 39,155,064 | <p>If <code>json</code> is your dictionary, you can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>
<pre><code>username_list = [summoner['name'] for summoner in json['data']]
</code></pre>
<p>Output:</p>
<pre><code>['Sadastyczny', 'Richor', 'Azzapp', 'YanetGarcia1337', 'Rapisher', 'Kizuro', 'Nataa', 'Huunntér', 'Hades147', 'Yolo Que Warrior']
</code></pre>
| 2 | 2016-08-25T21:34:40Z | [
"python"
] |
How to get elements in a string after and until a specific point in Python? | 39,155,022 | <p>I'm sure the title sounded a bit cryptic but I couldn't think of a better way to ask the question.</p>
<p>I have this code: </p>
<pre><code>from bs4 import BeautifulSoup
from requests import get
import re
eune = 'http://www.lolking.net/leaderboards#/eune/1'
patt = re.compile("\$\.get\('/leaderboards/(\w+)/")
js = 'http://www.lolking.net/leaderboards/{}/eune/1.json'
url = get(eune)
soup = BeautifulSoup(url.text, 'lxml')
script = soup.find('script', text=re.compile("\$\.get\('/leaderboards/"))
val = patt.search(script.text).group(1)
json = get(js.format(val)).json()
print(str(json))
</code></pre>
<p>Basically I'm trying to make a username scraper and I'm getting the data in a json format which outputs like this:</p>
<pre><code>{'data': [{'summoner_id': '42893043', 'tier': '6', 'global_ranking': '17', 'name': 'Sadastyczny', 'lks': '2961', 'wins': '128', 'region': 'eune', 'profile_icon_id': 944, 'division': '1', 'previous_ranking': '1', 'ranking': '1', 'tier_name': 'CHALLENGER', 'losses': '31', 'most_played_champions': [{'wins': '34', 'kills': '288', 'deaths': '131', 'creep_score': '7227', 'played': '39', 'champion_id': '236', 'assists': '238', 'losses': '5'}, {'wins': '24', 'kills': '204', 'deaths': '111', 'creep_score': '5454', 'played': '27', 'champion_id': '429', 'assists': '209', 'losses': '3'}, {'wins': '18', 'kills': '168', 'deaths': '103', 'creep_score': '4800', 'played': '26', 'champion_id': '81', 'assists': '155', 'losses': '8'}], 'league_points': '1217'}, {'summoner_id': '40385818', 'tier': '6', 'global_ranking': '40', 'name': 'Richor', 'lks': '2955', 'wins': '260', 'region': 'eune', 'profile_icon_id': 577, 'division': '1', 'previous_ranking': '2', 'ranking': '2', 'tier_name': 'CHALLENGER', 'losses': '187', 'most_played_champions': [{'wins': '150', 'kills': '1923', 'deaths': '1466', 'creep_score': '38820', 'played': '217', 'champion_id': '24', 'assists': '952', 'losses': '67'}, {'wins': '53', 'kills': '662', 'deaths': '584', 'creep_score': '16836', 'played': '90', 'champion_id': '67', 'assists': '501', 'losses': '37'}, {'wins': '15', 'kills': '150', 'deaths': '211', 'creep_score': '5372', 'played': '29', 'champion_id': '157', 'assists': '135', 'losses': '14'}], 'league_points': '1100'}, {'summoner_id': '21348510', 'tier': '6', 'global_ranking': '44', 'name': 'Azzapp', 'lks': '2954', 'wins': '415', 'region': 'eune', 'profile_icon_id': 588, 'division': '1', 'previous_ranking': '6', 'ranking': '3', 'tier_name': 'CHALLENGER', 'losses': '348', 'most_played_champions': [{'wins': '70', 'kills': '645', 'deaths': '576', 'creep_score': '9538', 'played': '122', 'champion_id': '161', 'assists': '1293', 'losses': '52'}, {'wins': '44', 'kills': '644', 'deaths': '385', 'creep_score': '14366', 'played': '80', 'champion_id': '202', 'assists': '762', 'losses': '36'}, {'wins': '41', 'kills': '473', 'deaths': '252', 'creep_score': '12970', 'played': '68', 'champion_id': '103', 'assists': '473', 'losses': '27'}], 'league_points': '1071'}, {'summoner_id': '24275559', 'tier': '6', 'global_ranking': '58', 'name': 'YanetGarcia1337', 'lks': '2953', 'wins': '152', 'region': 'eune', 'profile_icon_id': 1227, 'division': '1', 'previous_ranking': '3', 'ranking': '4', 'tier_name': 'CHALLENGER', 'losses': '47', 'most_played_champions': [{'wins': '59', 'kills': '199', 'deaths': '99', 'creep_score': '11927', 'played': '66', 'champion_id': '117', 'assists': '638', 'losses': '7'}, {'wins': '32', 'kills': '192', 'deaths': '99', 'creep_score': '8061', 'played': '43', 'champion_id': '48', 'assists': '345', 'losses': '11'}, {'wins': '20', 'kills': '165', 'deaths': '64', 'creep_score': '5584', 'played': '31', 'champion_id': '114', 'assists': '161', 'losses': '11'}], 'league_points': '1051'}, {'summoner_id': '31881620', 'tier': '6', 'global_ranking': '66', 'name': 'Rapisher', 'lks': '2952', 'wins': '158', 'region': 'eune', 'profile_icon_id': 518, 'division': '1', 'previous_ranking': '4', 'ranking': '5', 'tier_name': 'CHALLENGER', 'losses': '92', 'most_played_champions': [{'wins': '100', 'kills': '887', 'deaths': '597', 'creep_score': '26352', 'played': '137', 'champion_id': '429', 'assists': '905', 'losses': '37'}, {'wins': '22', 'kills': '10', 'deaths': '120', 'creep_score': '425', 'played': '36', 'champion_id': '40', 'assists': '533', 'losses': '14'}, {'wins': '15', 'kills': '162', 'deaths': '126', 'creep_score': '6134', 'played': '29', 'champion_id': '236', 'assists': '194', 'losses': '14'}], 'league_points': '1030'}, {'summoner_id': '36880627', 'tier': '6', 'global_ranking': '82', 'name': 'Kizuro', 'lks': '2951', 'wins': '158', 'region': 'eune', 'profile_icon_id': 909, 'division': '1', 'previous_ranking': '5', 'ranking': '6', 'tier_name': 'CHALLENGER', 'losses': '79', 'most_played_champions': [{'wins': '32', 'kills': '359', 'deaths': '190', 'creep_score': '1952', 'played': '49', 'champion_id': '76', 'assists': '377', 'losses': '17'}, {'wins': '29', 'kills': '297', 'deaths': '153', 'creep_score': '1266', 'played': '38', 'champion_id': '60', 'assists': '387', 'losses': '9'}, {'wins': '24', 'kills': '254', 'deaths': '163', 'creep_score': '1202', 'played': '37', 'champion_id': '64', 'assists': '308', 'losses': '13'}], 'league_points': '1010'}, {'summoner_id': '44064579', 'tier': '6', 'global_ranking': '124', 'name': 'Nataa', 'lks': '2946', 'wins': '278', 'region': 'eune', 'profile_icon_id': 2076, 'division': '1', 'previous_ranking': '7', 'ranking': '7', 'tier_name': 'CHALLENGER', 'losses': '213', 'most_played_champions': [{'wins': '52', 'kills': '651', 'deaths': '405', 'creep_score': '17094', 'played': '82', 'champion_id': '67', 'assists': '445', 'losses': '30'}, {'wins': '44', 'kills': '584', 'deaths': '354', 'creep_score': '16397', 'played': '74', 'champion_id': '236', 'assists': '463', 'losses': '30'}, {'wins': '25', 'kills': '349', 'deaths': '208', 'creep_score': '9768', 'played': '45', 'champion_id': '81', 'assists': '331', 'losses': '20'}], 'league_points': '920'}, {'summoner_id': '24504284', 'tier': '6', 'global_ranking': '165', 'name': 'Huunntér', 'lks': '2943', 'wins': '148', 'region': 'eune', 'profile_icon_id': 1234, 'division': '1', 'previous_ranking': '8', 'ranking': '8', 'tier_name': 'CHALLENGER', 'losses': '67', 'most_played_champions': [{'wins': '36', 'kills': '267', 'deaths': '263', 'creep_score': '2331', 'played': '54', 'champion_id': '60', 'assists': '449', 'losses': '18'}, {'wins': '33', 'kills': '270', 'deaths': '149', 'creep_score': '2880', 'played': '39', 'champion_id': '104', 'assists': '296', 'losses': '6'}, {'wins': '22', 'kills': '102', 'deaths': '76', 'creep_score': '865', 'played': '25', 'champion_id': '421', 'assists': '279', 'losses': '3'}], 'league_points': '858'}, {'summoner_id': '27565071', 'tier': '6', 'global_ranking': '209', 'name': 'Hades147', 'lks': '2941', 'wins': '243', 'region': 'eune', 'profile_icon_id': 588, 'division': '1', 'previous_ranking': '9', 'ranking': '9', 'tier_name': 'CHALLENGER', 'losses': '146', 'most_played_champions': [{'wins': '73', 'kills': '741', 'deaths': '261', 'creep_score': '5693', 'played': '94', 'champion_id': '102', 'assists': '675', 'losses': '21'}, {'wins': '27', 'kills': '199', 'deaths': '203', 'creep_score': '9370', 'played': '51', 'champion_id': '117', 'assists': '514', 'losses': '24'}, {'wins': '25', 'kills': '187', 'deaths': '179', 'creep_score': '2047', 'played': '42', 'champion_id': '79', 'assists': '420', 'losses': '17'}], 'league_points': '811'}, {'summoner_id': '35655567', 'tier': '6', 'global_ranking': '210', 'name': 'Yolo Que Warrior', 'lks': '2941', 'wins': '210', 'region': 'eune', 'profile_icon_id': 682, 'division': '1', 'previous_ranking': '11', 'ranking': '10', 'tier_name': 'CHALLENGER', 'losses': '148', 'most_played_champions': [{'wins': '46', 'kills': '445', 'deaths': '252', 'creep_score': '15061', 'played': '74', 'champion_id': '236', 'assists': '437', 'losses': '28'}, {'wins': '39', 'kills': '394', 'deaths': '179', 'creep_score': '3349', 'played': '68', 'champion_id': '76', 'assists': '593', 'losses': '29'}, {'wins': '22', 'kills': '267', 'deaths': '117', 'creep_score': '2683', 'played': '37', 'champion_id': '203', 'assists': '271', 'losses': '15'}], 'league_points': '811'}], 'status': True}
</code></pre>
<p>Now I need to find whatever is after <code>'name': '</code> and stop at <code>'</code> and store that in a list.
How would I do this?</p>
| 0 | 2016-08-25T21:31:45Z | 39,155,092 | <p>I don't understand why you're talking about strings. Json is a serialisation format that you decode into Python objects: in this case, a dict. You can get the name with <code>json['data'][0]['name']</code>.</p>
| 1 | 2016-08-25T21:36:46Z | [
"python"
] |
How to get elements in a string after and until a specific point in Python? | 39,155,022 | <p>I'm sure the title sounded a bit cryptic but I couldn't think of a better way to ask the question.</p>
<p>I have this code: </p>
<pre><code>from bs4 import BeautifulSoup
from requests import get
import re
eune = 'http://www.lolking.net/leaderboards#/eune/1'
patt = re.compile("\$\.get\('/leaderboards/(\w+)/")
js = 'http://www.lolking.net/leaderboards/{}/eune/1.json'
url = get(eune)
soup = BeautifulSoup(url.text, 'lxml')
script = soup.find('script', text=re.compile("\$\.get\('/leaderboards/"))
val = patt.search(script.text).group(1)
json = get(js.format(val)).json()
print(str(json))
</code></pre>
<p>Basically I'm trying to make a username scraper and I'm getting the data in a json format which outputs like this:</p>
<pre><code>{'data': [{'summoner_id': '42893043', 'tier': '6', 'global_ranking': '17', 'name': 'Sadastyczny', 'lks': '2961', 'wins': '128', 'region': 'eune', 'profile_icon_id': 944, 'division': '1', 'previous_ranking': '1', 'ranking': '1', 'tier_name': 'CHALLENGER', 'losses': '31', 'most_played_champions': [{'wins': '34', 'kills': '288', 'deaths': '131', 'creep_score': '7227', 'played': '39', 'champion_id': '236', 'assists': '238', 'losses': '5'}, {'wins': '24', 'kills': '204', 'deaths': '111', 'creep_score': '5454', 'played': '27', 'champion_id': '429', 'assists': '209', 'losses': '3'}, {'wins': '18', 'kills': '168', 'deaths': '103', 'creep_score': '4800', 'played': '26', 'champion_id': '81', 'assists': '155', 'losses': '8'}], 'league_points': '1217'}, {'summoner_id': '40385818', 'tier': '6', 'global_ranking': '40', 'name': 'Richor', 'lks': '2955', 'wins': '260', 'region': 'eune', 'profile_icon_id': 577, 'division': '1', 'previous_ranking': '2', 'ranking': '2', 'tier_name': 'CHALLENGER', 'losses': '187', 'most_played_champions': [{'wins': '150', 'kills': '1923', 'deaths': '1466', 'creep_score': '38820', 'played': '217', 'champion_id': '24', 'assists': '952', 'losses': '67'}, {'wins': '53', 'kills': '662', 'deaths': '584', 'creep_score': '16836', 'played': '90', 'champion_id': '67', 'assists': '501', 'losses': '37'}, {'wins': '15', 'kills': '150', 'deaths': '211', 'creep_score': '5372', 'played': '29', 'champion_id': '157', 'assists': '135', 'losses': '14'}], 'league_points': '1100'}, {'summoner_id': '21348510', 'tier': '6', 'global_ranking': '44', 'name': 'Azzapp', 'lks': '2954', 'wins': '415', 'region': 'eune', 'profile_icon_id': 588, 'division': '1', 'previous_ranking': '6', 'ranking': '3', 'tier_name': 'CHALLENGER', 'losses': '348', 'most_played_champions': [{'wins': '70', 'kills': '645', 'deaths': '576', 'creep_score': '9538', 'played': '122', 'champion_id': '161', 'assists': '1293', 'losses': '52'}, {'wins': '44', 'kills': '644', 'deaths': '385', 'creep_score': '14366', 'played': '80', 'champion_id': '202', 'assists': '762', 'losses': '36'}, {'wins': '41', 'kills': '473', 'deaths': '252', 'creep_score': '12970', 'played': '68', 'champion_id': '103', 'assists': '473', 'losses': '27'}], 'league_points': '1071'}, {'summoner_id': '24275559', 'tier': '6', 'global_ranking': '58', 'name': 'YanetGarcia1337', 'lks': '2953', 'wins': '152', 'region': 'eune', 'profile_icon_id': 1227, 'division': '1', 'previous_ranking': '3', 'ranking': '4', 'tier_name': 'CHALLENGER', 'losses': '47', 'most_played_champions': [{'wins': '59', 'kills': '199', 'deaths': '99', 'creep_score': '11927', 'played': '66', 'champion_id': '117', 'assists': '638', 'losses': '7'}, {'wins': '32', 'kills': '192', 'deaths': '99', 'creep_score': '8061', 'played': '43', 'champion_id': '48', 'assists': '345', 'losses': '11'}, {'wins': '20', 'kills': '165', 'deaths': '64', 'creep_score': '5584', 'played': '31', 'champion_id': '114', 'assists': '161', 'losses': '11'}], 'league_points': '1051'}, {'summoner_id': '31881620', 'tier': '6', 'global_ranking': '66', 'name': 'Rapisher', 'lks': '2952', 'wins': '158', 'region': 'eune', 'profile_icon_id': 518, 'division': '1', 'previous_ranking': '4', 'ranking': '5', 'tier_name': 'CHALLENGER', 'losses': '92', 'most_played_champions': [{'wins': '100', 'kills': '887', 'deaths': '597', 'creep_score': '26352', 'played': '137', 'champion_id': '429', 'assists': '905', 'losses': '37'}, {'wins': '22', 'kills': '10', 'deaths': '120', 'creep_score': '425', 'played': '36', 'champion_id': '40', 'assists': '533', 'losses': '14'}, {'wins': '15', 'kills': '162', 'deaths': '126', 'creep_score': '6134', 'played': '29', 'champion_id': '236', 'assists': '194', 'losses': '14'}], 'league_points': '1030'}, {'summoner_id': '36880627', 'tier': '6', 'global_ranking': '82', 'name': 'Kizuro', 'lks': '2951', 'wins': '158', 'region': 'eune', 'profile_icon_id': 909, 'division': '1', 'previous_ranking': '5', 'ranking': '6', 'tier_name': 'CHALLENGER', 'losses': '79', 'most_played_champions': [{'wins': '32', 'kills': '359', 'deaths': '190', 'creep_score': '1952', 'played': '49', 'champion_id': '76', 'assists': '377', 'losses': '17'}, {'wins': '29', 'kills': '297', 'deaths': '153', 'creep_score': '1266', 'played': '38', 'champion_id': '60', 'assists': '387', 'losses': '9'}, {'wins': '24', 'kills': '254', 'deaths': '163', 'creep_score': '1202', 'played': '37', 'champion_id': '64', 'assists': '308', 'losses': '13'}], 'league_points': '1010'}, {'summoner_id': '44064579', 'tier': '6', 'global_ranking': '124', 'name': 'Nataa', 'lks': '2946', 'wins': '278', 'region': 'eune', 'profile_icon_id': 2076, 'division': '1', 'previous_ranking': '7', 'ranking': '7', 'tier_name': 'CHALLENGER', 'losses': '213', 'most_played_champions': [{'wins': '52', 'kills': '651', 'deaths': '405', 'creep_score': '17094', 'played': '82', 'champion_id': '67', 'assists': '445', 'losses': '30'}, {'wins': '44', 'kills': '584', 'deaths': '354', 'creep_score': '16397', 'played': '74', 'champion_id': '236', 'assists': '463', 'losses': '30'}, {'wins': '25', 'kills': '349', 'deaths': '208', 'creep_score': '9768', 'played': '45', 'champion_id': '81', 'assists': '331', 'losses': '20'}], 'league_points': '920'}, {'summoner_id': '24504284', 'tier': '6', 'global_ranking': '165', 'name': 'Huunntér', 'lks': '2943', 'wins': '148', 'region': 'eune', 'profile_icon_id': 1234, 'division': '1', 'previous_ranking': '8', 'ranking': '8', 'tier_name': 'CHALLENGER', 'losses': '67', 'most_played_champions': [{'wins': '36', 'kills': '267', 'deaths': '263', 'creep_score': '2331', 'played': '54', 'champion_id': '60', 'assists': '449', 'losses': '18'}, {'wins': '33', 'kills': '270', 'deaths': '149', 'creep_score': '2880', 'played': '39', 'champion_id': '104', 'assists': '296', 'losses': '6'}, {'wins': '22', 'kills': '102', 'deaths': '76', 'creep_score': '865', 'played': '25', 'champion_id': '421', 'assists': '279', 'losses': '3'}], 'league_points': '858'}, {'summoner_id': '27565071', 'tier': '6', 'global_ranking': '209', 'name': 'Hades147', 'lks': '2941', 'wins': '243', 'region': 'eune', 'profile_icon_id': 588, 'division': '1', 'previous_ranking': '9', 'ranking': '9', 'tier_name': 'CHALLENGER', 'losses': '146', 'most_played_champions': [{'wins': '73', 'kills': '741', 'deaths': '261', 'creep_score': '5693', 'played': '94', 'champion_id': '102', 'assists': '675', 'losses': '21'}, {'wins': '27', 'kills': '199', 'deaths': '203', 'creep_score': '9370', 'played': '51', 'champion_id': '117', 'assists': '514', 'losses': '24'}, {'wins': '25', 'kills': '187', 'deaths': '179', 'creep_score': '2047', 'played': '42', 'champion_id': '79', 'assists': '420', 'losses': '17'}], 'league_points': '811'}, {'summoner_id': '35655567', 'tier': '6', 'global_ranking': '210', 'name': 'Yolo Que Warrior', 'lks': '2941', 'wins': '210', 'region': 'eune', 'profile_icon_id': 682, 'division': '1', 'previous_ranking': '11', 'ranking': '10', 'tier_name': 'CHALLENGER', 'losses': '148', 'most_played_champions': [{'wins': '46', 'kills': '445', 'deaths': '252', 'creep_score': '15061', 'played': '74', 'champion_id': '236', 'assists': '437', 'losses': '28'}, {'wins': '39', 'kills': '394', 'deaths': '179', 'creep_score': '3349', 'played': '68', 'champion_id': '76', 'assists': '593', 'losses': '29'}, {'wins': '22', 'kills': '267', 'deaths': '117', 'creep_score': '2683', 'played': '37', 'champion_id': '203', 'assists': '271', 'losses': '15'}], 'league_points': '811'}], 'status': True}
</code></pre>
<p>Now I need to find whatever is after <code>'name': '</code> and stop at <code>'</code> and store that in a list.
How would I do this?</p>
| 0 | 2016-08-25T21:31:45Z | 39,155,098 | <p>You may achieve this by using <code>map</code> and <code>lambda</code> function as:</p>
<pre><code># my_json = your json object
>>> map(lambda x: x['name'], my_json['data'])
['Sadastyczny', 'Richor', 'Azzapp', 'YanetGarcia1337', 'Rapisher',
'Kizuro', 'Nataa', 'Huunnt\xc3\xa9r', 'Hades147', 'Yolo Que Warrior']
</code></pre>
| 0 | 2016-08-25T21:37:33Z | [
"python"
] |
Unable to mock open, even when using the example from the documentation | 39,155,048 | <p>I've copied and pasted the following code directly from the Python <a href="https://docs.python.org/3/library/unittest.mock.html#mock-open" rel="nofollow">mock docs</a>:</p>
<pre><code>from unittest.mock import patch, mock_open
with patch('__main__.open', mock_open(read_data='bibble')) as m:
with open('foo') as h:
result = h.read()
m.assert_called_once_with('foo')
assert result == 'bibble'
</code></pre>
<p>When I run this I get the following error:</p>
<pre><code>AttributeError: <module '__main__' from 'path/to/file'> does not have the attribute 'open'
</code></pre>
<p>Given that this is the example given in the documentation, I'm not sure where else to turn. I'm running Python 3.4.5.</p>
| 2 | 2016-08-25T21:33:24Z | 39,155,212 | <p>Well, <code>__main__</code> is the module name given by default when you run a script.</p>
<p>Paste the code in a python file and call it.</p>
| 0 | 2016-08-25T21:46:05Z | [
"python",
"python-3.x",
"io",
"mocking"
] |
Unable to mock open, even when using the example from the documentation | 39,155,048 | <p>I've copied and pasted the following code directly from the Python <a href="https://docs.python.org/3/library/unittest.mock.html#mock-open" rel="nofollow">mock docs</a>:</p>
<pre><code>from unittest.mock import patch, mock_open
with patch('__main__.open', mock_open(read_data='bibble')) as m:
with open('foo') as h:
result = h.read()
m.assert_called_once_with('foo')
assert result == 'bibble'
</code></pre>
<p>When I run this I get the following error:</p>
<pre><code>AttributeError: <module '__main__' from 'path/to/file'> does not have the attribute 'open'
</code></pre>
<p>Given that this is the example given in the documentation, I'm not sure where else to turn. I'm running Python 3.4.5.</p>
| 2 | 2016-08-25T21:33:24Z | 39,155,250 | <p>I figured it out.</p>
<p><code>open</code> is a builtin, so I needed to patch <code>builtins.open</code>, not <code>__main__.open</code>.</p>
<p>Skipped over this info in the docs.</p>
| 0 | 2016-08-25T21:48:53Z | [
"python",
"python-3.x",
"io",
"mocking"
] |
In python 2.7 using CGI, how to check whether forked process completed | 39,155,088 | <p>So I have a set of python scripts. In an attempt to make a simple GUI, I have been combining html and CGI. So far so good. However, one of my scripts takes a long time to complete (>2 hours). So obviously, when I run this on my server (localhost on mac) I get a "gateway timeout error". I was reading about forking the sub process, and checking whether the process completed.<br>
This is what I came up with, but it isn't working :(.</p>
<pre><code>import os, time
#upstream stuff happening as part of main script
pid=os.fork()
if pid==0:
os.system("external_program") #this program will make "text.txt" as output
exit()
while os.stat(""text.txt").st_size == 0: # check whether text.txt has been written, if not print "processing" and continue to wait
print "processing"
sys.stdout.flush()
time.sleep(300)
#downstream stuff happening
</code></pre>
<p>As alwas, any help is appreciated</p>
| 0 | 2016-08-25T21:36:28Z | 39,155,191 | <p>Did you try this one:</p>
<pre><code>import os
processing = len(os.popen('ps aux | grep yourscript.py').readlines()) > 2
</code></pre>
<p>It tells you if your script is still running (returns boolean value).</p>
| -1 | 2016-08-25T21:44:33Z | [
"python",
"subprocess",
"cgi"
] |
Loop a function using the previous output value as input | 39,155,113 | <p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the following function. Here's what I want my loop to essentially do:</p>
<pre><code>def query(my_offset=None):
page = at.get('Accounts',offset=my_offset)
a = page['records']
return str(page['offset'])
query()
query(query())
query(query(query(query())))
query(query(query(query(query()))))
query(query(query(query(query(query())))))
...
...
...
...
</code></pre>
| 0 | 2016-08-25T21:38:24Z | 39,155,192 | <p>I'm guessing <code>res</code> can have a special value indicating no more rows were returned, if so, a while loop can be deployed:</p>
<pre><code>res = query()
while True:
res = query(res)
if not res: break
</code></pre>
<p>you just rebind the result of the query to <code>res</code> and re-use it during every iteration. </p>
| 3 | 2016-08-25T21:44:36Z | [
"python",
"function",
"loops"
] |
Loop a function using the previous output value as input | 39,155,113 | <p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the following function. Here's what I want my loop to essentially do:</p>
<pre><code>def query(my_offset=None):
page = at.get('Accounts',offset=my_offset)
a = page['records']
return str(page['offset'])
query()
query(query())
query(query(query(query())))
query(query(query(query(query()))))
query(query(query(query(query(query())))))
...
...
...
...
</code></pre>
| 0 | 2016-08-25T21:38:24Z | 39,155,229 | <p>Try collecting the results externally, and then call the function again:</p>
<pre><code>results = []
MAX_ITERATIONS = 20
offset = None
def query(offset=None):
page = at.get('Accounts', offset=offset)
return page['records'], page['offset']
while len(results) <= MAX_ITERATIONS:
result, offset = query(offset)
results.append(result)
</code></pre>
| 0 | 2016-08-25T21:47:25Z | [
"python",
"function",
"loops"
] |
Loop a function using the previous output value as input | 39,155,113 | <p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the following function. Here's what I want my loop to essentially do:</p>
<pre><code>def query(my_offset=None):
page = at.get('Accounts',offset=my_offset)
a = page['records']
return str(page['offset'])
query()
query(query())
query(query(query(query())))
query(query(query(query(query()))))
query(query(query(query(query(query())))))
...
...
...
...
</code></pre>
| 0 | 2016-08-25T21:38:24Z | 39,155,295 | <p>how are you returning the final results? consider:</p>
<pre><code>def query():
offset = None
a = []
while True:
page = at.get('Accounts',offset=offset)
a.extend(page['records'])
offset = page['offset']
if not offset: break
return a
</code></pre>
<p>which is really just Jim's answer while collecting and returning the page results</p>
| 0 | 2016-08-25T21:52:01Z | [
"python",
"function",
"loops"
] |
Loop a function using the previous output value as input | 39,155,113 | <p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the following function. Here's what I want my loop to essentially do:</p>
<pre><code>def query(my_offset=None):
page = at.get('Accounts',offset=my_offset)
a = page['records']
return str(page['offset'])
query()
query(query())
query(query(query(query())))
query(query(query(query(query()))))
query(query(query(query(query(query())))))
...
...
...
...
</code></pre>
| 0 | 2016-08-25T21:38:24Z | 39,155,303 | <pre><code>def query(result):
# perform query
return result
def end_query_condition(result):
# if want to continue query:
return True
# if you want to stop:
return False
continue_query = True
result = None
while continue_query:
result = query(result)
continue_query = end_query_condition(result)
</code></pre>
| 0 | 2016-08-25T21:52:27Z | [
"python",
"function",
"loops"
] |
Loop a function using the previous output value as input | 39,155,113 | <p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the following function. Here's what I want my loop to essentially do:</p>
<pre><code>def query(my_offset=None):
page = at.get('Accounts',offset=my_offset)
a = page['records']
return str(page['offset'])
query()
query(query())
query(query(query(query())))
query(query(query(query(query()))))
query(query(query(query(query(query())))))
...
...
...
...
</code></pre>
| 0 | 2016-08-25T21:38:24Z | 39,155,323 | <p>You may simply make your function recursive without the need of any loop as:</p>
<pre><code>def query(my_offset=None):
if not offset:
return None
page = at.get('Accounts',offset=my_offset)
a = page['records']
return query(str(page['offset']))
</code></pre>
| 0 | 2016-08-25T21:54:23Z | [
"python",
"function",
"loops"
] |
Using python3, what is the fastest way to extract all <div> blocks from a html str? | 39,155,127 | <p>there are <code><div></code> inner blocks inside a <code><div></code> block,
What is the fastest way to extract all <code><div></code> blocks from a html str ?
(bs4, lxml or regex ?)</p>
| -1 | 2016-08-25T21:39:15Z | 39,155,253 | <p><a href="http://lxml.de/" rel="nofollow"><code>lxml</code></a> is generally considered to be the fastest among existing Python parsers, though the parsing speed depends on multiple factors starting with the specific HTML to parse and ending with the computational power you have available. For HTML parsing use the <code>lxml.html</code> subpackage:</p>
<pre><code>from lxml.html import fromstring, tostring
data = """my HTML string"""
root = fromstring(data)
print([tostring(div) for div in root.xpath(".//div")])
print([div.text_content() for div in root.xpath(".//div")])
</code></pre>
<p>There is also the awesome <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code></a> parser which, <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#differences-between-parsers" rel="nofollow">if allowed to use <code>lxml</code> under-the-hood</a>, would be a great combination of convenience, flexibility and speed. It would not be generally faster than pure <code>lxml</code>, but it comes with one of the best APIs I've ever seen allowing you to "view" your XML/HTML from different angles and use a huge variety of techniques:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup(data, "lxml")
print([str(div) for div in soup.find_all("div")])
print([div.get_text() for div in soup.find_all("div")])
</code></pre>
<p>And, I personally think, <em>there is rarely a case</em> when regex is suitable for HTML parsing:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">RegEx match open tags except XHTML self-contained tags</a></li>
</ul>
| 1 | 2016-08-25T21:49:02Z | [
"python",
"html",
"regex",
"parsing"
] |
Using python3, what is the fastest way to extract all <div> blocks from a html str? | 39,155,127 | <p>there are <code><div></code> inner blocks inside a <code><div></code> block,
What is the fastest way to extract all <code><div></code> blocks from a html str ?
(bs4, lxml or regex ?)</p>
| -1 | 2016-08-25T21:39:15Z | 39,155,600 | <p>When I'm teaching XML/HTML parsing with Python, I use to show this levels of complexity:</p>
<ol>
<li>RegEx: efficient for (very) simple parsing but can be/become hard to maintain.</li>
<li>SAX: efficient and safe to parse XML as a stream. Easy to extract pieces of data but awful when you want to transform the tree. Can become really difficult to maintain. Who still use that anyway?</li>
<li>DOM parsing or ElementTree parsing with <strong>lxml</strong>: less efficient: all the XML tree is loaded in memory (can be an issue for big XML). But this library is compiled (in Cython). Very popular and reliable. Easy to understand: the code can be maintained.</li>
<li>XSLT1 is also a possibility. Very good to transform the tree in depth. But not efficient because of the templates machinery. Need learn a new language which appears to be difficult to learn. Maintenance often become heavy. Note that <strong>lxml</strong> can do XSLT with Pyton functions as an extension. </li>
<li>XSLT2 is very powerful but the only implementation I know is in Java language with Saxon. Launching the JRE is time consuming. The language is difficult to learn. One need to be an expert to understand every subtleties. Worse as XSLT1.</li>
</ol>
<p>For your problem, <strong>lxml</strong> (or <strong>BeautifulSoup</strong>) sound good.</p>
| 0 | 2016-08-25T22:18:15Z | [
"python",
"html",
"regex",
"parsing"
] |
NameError: global name 'Path' is not defined | 39,155,206 | <p>I'm a beginner of learning GUI. My python version is 2.7,and I'm using windows</p>
<p>what should I do to be able to change the value of "path" by clicking button?</p>
<p>here is the part of my code. :)</p>
<pre><code>class Sign_page(tk.Frame):
def __init__(self, parent, controller):
self.controller = controller
tk.Frame.__init__(self, parent)
img_path = "C:/"
Path = tk.Text(self, width = 45, height=1)
Path.insert("end",img_path)
Path.grid(row=2,column=0)
ask_path = tk.Button(self, text = "...", command = lambda: asking_path(self))
ask_path.grid(row=2,column=1)
</code></pre>
<p>and this part is out of class "Sign_page"</p>
<pre><code>def asking_path(self):
fileName = askopenfilename(initialdir = "C:/")
img_path = fileName
Path.delete("1.0","end")
Path.insert("end",img_path)
</code></pre>
| 0 | 2016-08-25T21:45:48Z | 39,155,276 | <p><code>Path</code> is not accessible from <code>asking_path</code> because it's not defined in the scope. One solution is to set an attribute on the instance when you create <code>Path</code> in <code>__init__</code>. In general, you should use lowercased variable names for Python variables ("<code>path</code>"), and title case for class names ("<code>SignPage</code>").</p>
<pre><code>class SignPage(tk.Frame):
def __init__(self, parent, controller):
...
path = tk.Text(self, width = 45, height=1)
path.insert("end",img_path)
path.grid(row=2,column=0)
self.path = path
...
def asking_path(self):
...
self.path.delete("1.0","end")
self.path.insert("end",img_path)
</code></pre>
| 0 | 2016-08-25T21:51:07Z | [
"python",
"user-interface",
"tkinter"
] |
Can someone explain debugging / Pycharm's debugger in an easy to understand way? | 39,155,391 | <p>I have reached the stage in developing my Django project where I need to start debugging my code, as my site is breaking and I don't know why. I'm using Pycharm's IDE to code, and the debugger that comes with it is super intimidating! </p>
<p>Maybe because I am a total newbie to programming (been coding only since May) but I don't really understand how debugging, as a basic concept, works. I've read the Pycharm docs about debugging, but I'm still confused. What is the debugger supposed to do/how is it supposed to interact with your program? What helpful info about the code is debugging supposed to offer? </p>
<p>When I previously thought about debugging I imagined that it would be a way of running through the code line by line, say, and finding out "my program is breaking at this line of code," but "stepping through my code" seems to take me into files that aren't even part of my project (e.g. stepping into my code in admin.py will take me into the middle of a function in widgets.py?) etc. and seems to present lots of extra/confusing info. How do I use debugging productively? How can I use it to debug my Django webapp?</p>
<p>Please help! TIA :) </p>
| 0 | 2016-08-25T22:00:34Z | 39,162,697 | <p>A can leave you some links i found useful when i got to that same point - i cant get you a more comprehensive explanation on the topic than this materials do.
Debugging is fundamental as you said and very broad. But this videos and links should get you start with more confidence.</p>
<pre><code>https://www.youtube.com/watch?v=U5Zi2HDb2Dk
https://www.youtube.com/watch?v=BBPoInSOiOY
https://www.youtube.com/watch?v=QJtWxm12Eo0
http://pedrokroger.net/python-debugger/
</code></pre>
<p><a href="https://waterprogramming.wordpress.com/2016/04/08/debugging-in-python-using-pycharm-part-1/" rel="nofollow">https://waterprogramming.wordpress.com/2016/04/08/debugging-in-python-using-pycharm-part-1/</a>
<a href="https://waterprogramming.wordpress.com/2016/04/08/debugging-in-python-using-pycharm-part-2/" rel="nofollow">https://waterprogramming.wordpress.com/2016/04/08/debugging-in-python-using-pycharm-part-2/</a>
<a href="https://waterprogramming.wordpress.com/2016/04/08/debugging-in-python-using-pycharm-part-3/" rel="nofollow">https://waterprogramming.wordpress.com/2016/04/08/debugging-in-python-using-pycharm-part-3/</a></p>
<p>Hope that helps </p>
| 1 | 2016-08-26T09:15:35Z | [
"python",
"django",
"debugging",
"pycharm"
] |
Can someone explain debugging / Pycharm's debugger in an easy to understand way? | 39,155,391 | <p>I have reached the stage in developing my Django project where I need to start debugging my code, as my site is breaking and I don't know why. I'm using Pycharm's IDE to code, and the debugger that comes with it is super intimidating! </p>
<p>Maybe because I am a total newbie to programming (been coding only since May) but I don't really understand how debugging, as a basic concept, works. I've read the Pycharm docs about debugging, but I'm still confused. What is the debugger supposed to do/how is it supposed to interact with your program? What helpful info about the code is debugging supposed to offer? </p>
<p>When I previously thought about debugging I imagined that it would be a way of running through the code line by line, say, and finding out "my program is breaking at this line of code," but "stepping through my code" seems to take me into files that aren't even part of my project (e.g. stepping into my code in admin.py will take me into the middle of a function in widgets.py?) etc. and seems to present lots of extra/confusing info. How do I use debugging productively? How can I use it to debug my Django webapp?</p>
<p>Please help! TIA :) </p>
| 0 | 2016-08-25T22:00:34Z | 39,164,574 | <p>It's really easy. You can debug your script by pressing Alt+F5 or the bug button in Pycharm IDE. After that the Debugger handle the execution of the script. now you can debugging line by line by F10, get into a function or other object by pressing F11. Also there is Watch Window where you can trace your variable values while debugging. I really encourage you to search blogs on internet. There are lots of tutorial in this area</p>
| 1 | 2016-08-26T10:52:47Z | [
"python",
"django",
"debugging",
"pycharm"
] |
Django rest framework assign POST data to specific user | 39,155,423 | <p>Started Django and DRF a month ago and I'm stuck on this part... I get a JSON from Android device that already contains a primary key of user so the data gets saved to correct user. Recently I have implemented JWT token authentication (from Blimp) and it's working like a charm. Now I want to remove that primary key field in JSON (sent from Android) and assign data to that logged in user (on Android). Here's some code:</p>
<p>models.py</p>
<pre><code>class Izdavatelji(models.Model):
user = models.ForeignKey(User, default=1)
name = models.CharField(max_length=100)
class Obrazac(models.Model):
izdavatelj = models.ForeignKey(Izdavatelji, default='Izdavatelj')
local = models.CharField(max_length=100)
</code></pre>
<p>serializers.py</p>
<pre><code>class ObrazacSerializer(serializers.ModelSerializer):
class Meta:
model = Obrazac
fields = ('local', 'izdavatelj')
</code></pre>
<p>DRF views.py</p>
<pre><code>class ObrazacList(generics.ListCreateAPIView):
queryset = Obrazac.objects.all()
serializer_class = ObrazacSerialize
permission_classes = (IsAuthenticated,)
authentication_classes = (JSONWebTokenAuthentication,)
</code></pre>
| 0 | 2016-08-25T22:03:03Z | 39,164,763 | <pre><code>class ObrazacSerializer(serializers.ModelSerializer):
izdavatelj = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Obrazac
fields = ('local', 'izdavatelj')
class ObrazacList(generics.ListCreateAPIView):
queryset = Obrazac.objects.all()
serializer_class = ObrazacSerializer
permission_classes = (IsAuthenticated,)
authentication_classes = (JSONWebTokenAuthentication,)
def perform_create(self, serializer):
izdavatelj = Izdavatelji.objects.get(user=self.request.user)
return serializer.save(izdavatelj=izdavatelj)
</code></pre>
<p>Adding a field to <code>serializes.py</code> that pointed to the model relationships and overwriting the <code>perform_create(self, serializer)</code>method in ListCreateAPIView seems to do the job.</p>
| 0 | 2016-08-26T11:01:38Z | [
"python",
"django",
"authentication",
"django-rest-framework",
"jwt"
] |
Using a named (fifo) pipe to transport arrays (images) between python and c++ | 39,155,655 | <p>I need to send an array (representing an image) through a named FIFO pipe from a python process to a c++ process, and then back the other way (on a Linux system). </p>
<p>The below code works great when using named pipes between two Python processes. It uses numpy's tostring() and fromstring() functions:</p>
<p><strong>Send frames over named pipe (Python)</strong>
</p>
<pre><code>import cv2
import numpy as np
from time import sleep
##########################################################
FIFO_Images = "./../pipes/images.fifo"
videoName = "./../../videos/videoName.avi"
delim = "break"
##########################################################
def sendImage(h, w, d, pixelarray):
imageString = pixelarray.tostring()
with open(FIFO_Images, "w") as f:
f.write(str(h)+ delim + str(w)+ delim + str(d) + delim + imageString)
sleep(.01)
return
##########################################################
cap = cv2.VideoCapture(videoName)
while(cap.isOpened()):
ret, frame_rgb = cap.read()
h, w, d = frame_rgb.shape
sendImage(h, w, d, frame_rgb)
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p><strong>Read frames over named pipe (Python)</strong>
</p>
<pre><code>import cv2
import numpy as np
##########################################################
FIFO_Images = "./../pipes/images.fifo"
delim = "break"
##########################################################
def getFrame():
with open(FIFO_Images, "r") as f:
data = f.read().split(delim)
#parse incoming string, which has format (height, width, depth, imageData)
h=int(data[0])
w=int(data[1])
d=int(data[2])
imageString = data[3]
#convert array string into numpy array
array = np.fromstring(imageString, dtype=np.uint8)
#reshape numpy array into the required dimensions
frame = array.reshape((h,w,d))
return frame
##########################################################
while(True):
frame = getFrame()
cv2.imshow('frame', frame)
cv2.waitKey(1) & 0xFF
</code></pre>
<p>However, I couldn't figure out how to read the entire image from the pipe on the cpp side, since it takes "\n" as a delimiter for the read automatically. </p>
<p>My workaround was to do a base64 encoding on the "tostring()" image, then send <em>that</em> over the pipe. This works, but the base64 decoding on the other slide is much too slow for real-time applications (~0.2 seconds per frame). Code: </p>
<p><strong>Send base64-encoded images over named pipe (Python)</strong>
</p>
<pre><code>import cv2
import numpy as np
from time import time
from time import sleep
import base64
##########################################################
FIFO_Images = "./../pipes/images.fifo"
videoName = "./../../videos/videoName.avi"
delim = ";;"
##########################################################
def sendImage(h, w, d, pixelarray):
flat = pixelarray.flatten()
imageString = base64.b64encode(pixelarray.tostring())
fullString = str(h)+ delim + str(w)+ delim + str(d)+ delim + imageString + delim + "\n"
with open(FIFO_Images, "w") as f:
f.write(fullString)
return
##########################################################
cap = cv2.VideoCapture(videoName)
count = 0
while(cap.isOpened()):
ret, frame_rgb = cap.read()
h, w, d = frame_rgb.shape
frame_gbr = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2BGR)
sendImage(h, w, d, frame_rgb)
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p><strong>Read base64-encoded images over named pipe (C++)</strong>
</p>
<pre><code>#include "opencv2/opencv.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <linux/stat.h>
#include <ctime>
using namespace std;
using namespace cv;
#define FIFO_FILE "./../../../pipes/images.fifo"
#define MAX_BUF 10000000
FILE *fp;
char readbuf[MAX_BUF + 1]; //add 1 to the expected size to accomodate the mysterious "extra byte", which I think signals the end of the line.
/************************BASE64 Decoding*********************************************/
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
/*********************************************************************/
int stringToInt(string str)
{
int num;
if (!(istringstream(str) >> num)) num = 0;
return num;
}
/*********************************************************************/
bool timerOn = 0;
clock_t timerStart;
void Timer(string process)
{
if (!timerOn)
{
timerStart = clock();
timerOn = true;
}
else if (timerOn)
{
double duration = (clock() - timerStart) / (double) CLOCKS_PER_SEC;
cout << "Time to complete: ";
printf("%.2f", duration);
cout << ": " << process << endl;
timerOn = false;
}
}
/*********************************************************************/
void getFrame()
{
string fullString;
string delimiter = ";;";
size_t pos = 0;
string token;
int h;
int w;
int d;
string imgString;
int fifo;
bool cont(true);
/***************************
Read from the pipe
www.tldp.org/LDP/lpg/node18.html
***************************/
Timer("Read from pipe");
fp = fopen(FIFO_FILE, "r");
fgets(readbuf, MAX_BUF + 1, fp); // Stops when MAX_BUF characters are read, the newline character ("\n") is read, or the EOF (end of file) is reached
string line(readbuf);
fclose(fp);
Timer("Read from pipe");
//////parse the string into components
Timer("Parse string");
int counter = 0;
while ((pos = line.find(delimiter)) != string::npos)
{
token = line.substr(0,pos);
if (counter == 0)
{
h = stringToInt(token);
}
else if (counter == 1)
{
w = stringToInt(token);
}
else if (counter == 2)
{
d = stringToInt(token);
}
else if (counter == 3)
{
imgString = token;
//cout << imgString[0] << endl;
}
else
{
cout << "ERROR: Too many paramaters passed" << endl;
return;
}
line.erase(0, pos + delimiter.length());
counter ++;
}
if (counter == 3)
{
imgString = token;
}
if (counter < 3)
{
cout << "ERROR: Not enough paramaters passed: " << counter << endl;
//return;
}
Timer("Parse string");
/***************************
Convert from Base64
***************************/
Timer("Decode Base64");
std::string decoded = base64_decode(imgString);
Timer("Decode Base64");
/***************************
Convert to vector of ints
***************************/
Timer("Convert to vector of ints");
std::vector<uchar> imgVector;
for (int i = 0; i < decoded.length(); i = i+1) // + 4)
{
int temp = (char(decoded[i]));
imgVector.push_back(temp);
}
Timer("Convert to vector of ints");
//////convert the vector into a matrix
Mat frame = Mat(imgVector).reshape(d, h);
namedWindow("Frame", WINDOW_AUTOSIZE);
imshow("Frame", frame);
waitKey(1);
}
int main()
{
/* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1)
{
getFrame();
}
return 0;
}
</code></pre>
<p>There must be a more efficient way to accomplish this. Can anyone make a recommendation? While I'm happy to hear suggestions for other methods to accomplish this, <strong>I am constrained to using named pipes</strong> for now. </p>
| 2 | 2016-08-25T22:23:05Z | 39,155,722 | <p>This is overcomplicated. If you need to send binary data, send their length first, then newline (<code>\n</code>), and then the data (raw, no base64). Receive it on the other side by readling a line, parsing the number and then just reading a block of data of given length.</p>
<p><strong>Example</strong> - writing binary data to a FIFO (or file) in Python:</p>
<pre><code>#!/usr/bin/env python3
import os
fifo_name = 'fifo'
def main():
data = b'blob\n\x00 123'
try:
os.mkfifo(fifo_name)
except FileExistsError:
pass
with open(fifo_name, 'wb') as f:
# b for binary mode
f.write('{}\n'.format(len(data)).encode())
f.write(data)
if __name__ == '__main__':
main()
</code></pre>
<p>Reading binary data from FIFO in C++:</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
const char *fifo_name = "fifo";
mknod(fifo_name, S_IFIFO | 0666, 0);
std::ifstream f(fifo_name);
std::string line;
getline(f, line);
auto data_size = std::stoi(line);
std::cout << "Size: " << data_size << std::endl;
std::string data;
{
std::vector<char> buf(data_size);
f.read(buf.data(), data_size);
// write to vector data is valid since C++11
data.assign(buf.data(), buf.size());
}
if (!f.good()) {
std::cerr << "Read failed" << std::endl;
}
std::cout << "Data size: " << data.size() << " content: " << data << std::endl;
}
</code></pre>
| 1 | 2016-08-25T22:29:37Z | [
"python",
"c++",
"linux",
"pipe",
"ipc"
] |
I Need Bigger Font in Python IDLE | 39,155,656 | <p>Context for why I'm asking:</p>
<p>I am currently teaching a course on Python. I am using IDLE to show basic syntax in the shell. My screen is projected onto a large screen. The maximum font size in IDLE's preferences is 22. This is decently sized, but when projected, the students in the back have trouble seeing it. I don't want to use a different IDE or text editor, because I want the class to easily follow along, and write and execute along with my examples.</p>
<p>What I am asking:</p>
<p>I need larger font in IDLE. The max font size is 22. Is there a way to manipulate this in my local installation? Or does anyone know of an extension for IDLE that fixes this issue?</p>
| 0 | 2016-08-25T22:23:10Z | 39,156,068 | <p>The font size selection had ended with 22 for at least 15 years. It is set by this statement in <code>idlelib.ConfigDialog.py</code> (or <code>configdialog</code> in 3.6). It is about line 1000.</p>
<pre><code> self.optMenuFontSize.SetMenu(('7', '8', '9', '10', '11', '12', '13',
'14', '16', '18', '20', '22'), fontSize )
</code></pre>
<p>Extend the sequence as you wish, such as to</p>
<pre><code> self.optMenuFontSize.SetMenu(('7', '8', '9', '10', '11', '12', '13',
'14', '16', '18', '20', '22',
'25', '30', '35', '40'), fontSize )
</code></pre>
<p>At present, you will have to re-patch every time you update.</p>
<p>This <a href="https://bugs.python.org/issue17642" rel="nofollow">tracker issue</a> is about changing font size within a window with key or mousewheel. The use case of projecting is mentioned. Now that I know this is a real, not hypothetical issue, I will make this issue a higher priority. If you tell me what size you need, I might extend the fixed list something like the above.</p>
| 4 | 2016-08-25T23:08:57Z | [
"python",
"fonts",
"python-idle"
] |
Python: Append a list with a newline | 39,155,665 | <p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p>
<p>I thought it would have been:</p>
<pre><code>lines = []
for i in range(10):
line = ser.readline()
if line:
lines.append(line + '\n') #'\n' newline
lines.append(datetime.now())
</code></pre>
<p>But this only adds the '\n' as a string. I have also tried the same without without the quotes, but no luck.</p>
<p>I am getting this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), '\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 519000), '\r\x00leftRaw; 928091; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00)]
</code></pre>
<p>But I want this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000),
'\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)]
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-25T22:24:25Z | 39,155,786 | <p>You can add all items to the list, then use .join() function to add new line between each item in the list:</p>
<pre><code>for i in range(10):
line = ser.readline()
if line:
lines.append(line)
lines.append(datetime.now())
final_string = '\n'.join(lines)
</code></pre>
| 3 | 2016-08-25T22:35:45Z | [
"python"
] |
Python: Append a list with a newline | 39,155,665 | <p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p>
<p>I thought it would have been:</p>
<pre><code>lines = []
for i in range(10):
line = ser.readline()
if line:
lines.append(line + '\n') #'\n' newline
lines.append(datetime.now())
</code></pre>
<p>But this only adds the '\n' as a string. I have also tried the same without without the quotes, but no luck.</p>
<p>I am getting this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), '\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 519000), '\r\x00leftRaw; 928091; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00)]
</code></pre>
<p>But I want this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000),
'\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)]
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-25T22:24:25Z | 39,155,797 | <p>It looks like the <code>lines</code> list is simple being printed in its entirety. The <code>\n</code> you see is only printing as an indicator that there are in fact new-lines. See this smaller example:</p>
<pre><code>In [18]: print ['asdf' + '\n\n'] + [datetime.now()],
['asdf\n\n', datetime.datetime(2016, 8, 25, 15, 32, 5, 955895)]
In [19]: a = ['asdf' + '\n\n', datetime.now()]
In [20]: print a[0]
asdf
In [21]: print a
['asdf\n\n', datetime.datetime(2016, 8, 25, 15, 37, 14, 330440)]
In [22]:
</code></pre>
| 0 | 2016-08-25T22:36:43Z | [
"python"
] |
Python: Append a list with a newline | 39,155,665 | <p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p>
<p>I thought it would have been:</p>
<pre><code>lines = []
for i in range(10):
line = ser.readline()
if line:
lines.append(line + '\n') #'\n' newline
lines.append(datetime.now())
</code></pre>
<p>But this only adds the '\n' as a string. I have also tried the same without without the quotes, but no luck.</p>
<p>I am getting this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 517000), '\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n', datetime.datetime(2016, 8, 25, 23, 48, 4, 519000), '\r\x00leftRaw; 928091; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00)]
</code></pre>
<p>But I want this:</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000),
'\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)]
</code></pre>
<p>Any ideas?</p>
| 0 | 2016-08-25T22:24:25Z | 39,188,175 | <p>I fixed the issue by appending 'datetime.now' to the list as a string on every frame using the 'strftime' method. I was then able to add newlines with 'lines = '\n'.join(lines)'. See code below for the working code.</p>
<pre><code>lines = []
for frame in range(frames):
line = ser.readline()
if line:
lines.append(line)
lines.append(datetime.now().strftime('%H:%M:%S'))
lines = '\n'.join(lines)
dataFile.write('%s'%(lines))
</code></pre>
<p>This gives me the desired output of each list item on a new line e.g.</p>
<pre><code>['leftRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 517000),
'\r\x00rightRaw; 928090; 0; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00; 0.00;\n',
datetime.datetime(2016, 8, 25, 23, 48, 4, 519000)']
</code></pre>
| 0 | 2016-08-28T05:03:25Z | [
"python"
] |
Python 2.7.11 pip not installed | 39,155,669 | <p>I have Python 2.7.11 installed on my machine which to my understanding should come with pip, however when I check the <code>C:\Python27\Tools\Scripts\</code> directory there is no <code>pip.exe</code> present.</p>
<p>I have tried completely removing and reinstalling Python 2.7.11 without success. Running the installer pip is set to be installed, but after the install pip is nowhere to be found.</p>
<p>I also have Python 3.4 installed which has pip as expected. Any thoughts?</p>
| 0 | 2016-08-25T22:24:38Z | 39,155,891 | <p><a href="https://www.python.org/ftp/python/2.7.11/python-2.7.11.amd64.msi" rel="nofollow">python2.7.11</a> should install pip into c:\python27\scripts, you can take a look <a href="http://screencast.com/t/xX6WwxdnNN" rel="nofollow">here</a></p>
| 0 | 2016-08-25T22:46:22Z | [
"python",
"windows",
"python-2.7",
"pip"
] |
Passing variables with continuous functions? | 39,155,697 | <p>I am using a function to read an analog value from a joystick and update the label on the tkinter screen. This works well but I also want to use that value outside the function to perform if statements with other returned values. Here is what I have so far:</p>
<pre><code>def joystick():
global joystick_adc
joystickRead = readadc(joystick_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
joystickValue = joystickRead
joy_val.config(text=joystickRead)
joy_val.after(1000, joystick)
return joystickValue
</code></pre>
<p>After it is returned I am assigning it to a variable using:</p>
<pre><code>joystickVal = joystick()
</code></pre>
<p>But it only returns the value once and not continuously like I had hoped. Is there something I am doing wrong here??</p>
| -1 | 2016-08-25T22:27:52Z | 39,155,755 | <p>If you <em>really</em> need such architecture, you could do it like this:</p>
<pre><code>def joystick(adc):
global joystickVal
joystickVal = readadc(adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
joy_val.config(text=joystickVal)
joy_val.after(1000, joystick, adc)
joystick(joystick_adc) # to start
# Also this wouldn't stop, so you'd better coding it in class with shared
# attribute, used to indicate condition
</code></pre>
<p>But you'd better avoiding such patterns, cause it brings strong coupling. Generally, function should be as independent, as possible</p>
<p>See how it's properly done in ThreadDispatcher <a href="https://gist.github.com/thodnev/d2c70d1034d1b8547fa8edf1c297b859" rel="nofollow">here</a></p>
<p><strong>UPD:</strong> (part of reply to your comment)
for simulating readadc:</p>
<pre><code>def sim(string):
parts = string.splitlines()
def callback(*args, **kwargs):
if parts:
cur = parts.pop(0)
return cur
return 'Empty'
return callback
sim_adc = sim('Firs\nsecond\nthird\netc...') # run func with this
</code></pre>
| -1 | 2016-08-25T22:32:32Z | [
"python",
"python-3.x",
"tkinter"
] |
Passing variables with continuous functions? | 39,155,697 | <p>I am using a function to read an analog value from a joystick and update the label on the tkinter screen. This works well but I also want to use that value outside the function to perform if statements with other returned values. Here is what I have so far:</p>
<pre><code>def joystick():
global joystick_adc
joystickRead = readadc(joystick_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
joystickValue = joystickRead
joy_val.config(text=joystickRead)
joy_val.after(1000, joystick)
return joystickValue
</code></pre>
<p>After it is returned I am assigning it to a variable using:</p>
<pre><code>joystickVal = joystick()
</code></pre>
<p>But it only returns the value once and not continuously like I had hoped. Is there something I am doing wrong here??</p>
| -1 | 2016-08-25T22:27:52Z | 39,166,206 | <p>By far, the simplest solution is to simply make <code>joystickValue</code> a global variable.</p>
<pre><code>def joystick():
global joystickValue
...
joystickValue = joystickRead
...
</code></pre>
<p>Generally speaking, global variables should be avoided. In an event driven program, however, they are a necessity. It would be better to use classes for your application, but it appears that you're not so globals in this case are unavoidable.</p>
<hr>
<p>In your code, it actually <em>is</em> returning the value every time it's called. It's just that it's returning the value to <code>mainloop</code> rather than whatever function called it the first time. That is because you use <code>after</code> which defers the call to a future date. The code that makes that call in the future is not your code, but rather <code>mainloop</code>. </p>
| 1 | 2016-08-26T12:20:04Z | [
"python",
"python-3.x",
"tkinter"
] |
Error redirecting after login | 39,155,772 | <p>I am trying to redirect users to a create-profile form after signup.Since I don't know how to use dynamic url for LOGIN_REDIRECT_URL.I tried this little trick of linking it to a static view then finally to a dynamic view using <code>redirect</code>.It gives the error <code>Reverse for 'add_profile' with arguments '()' and keyword arguments '{'username': u'badguy'}' not found. 0 pattern(s) tried: []</code> (with 'badguy' truly the username of the just signed-up user').From the error,it is clearly passing the username to the view.My codes are:</p>
<pre><code>settings.py
LOGIN_REDIRECT_URL = '/prof-change/gdyu734648dgey83y37gyyeyu8g/'
urls.py
url(r'^prof-change/gdyu734648dgey83y37gyyeyu8g/',views.login_redir,name='login_redir'),
url(r'^create-profile/(?P<username>\w+)/$',views.add_profile,name='create-profile'),
views.py
def login_redir(request):
user=get_object_or_404(User,username=request.user.username)
username=user.username
return redirect('add_profile',username=username)
def add_profile(request,username):
userman=User.objects.get(username=username)
........
........
</code></pre>
| 0 | 2016-08-25T22:34:12Z | 39,155,848 | <p>When you reverse urls (including when you use a url name with the <code>redirect</code> shortcut), you should use the name of the <em>url pattern</em>, not the view. The url pattern has <code>name='create-profile'</code>, so use that. </p>
<pre><code>redirect('create-profile', username=username)
</code></pre>
| 0 | 2016-08-25T22:42:18Z | [
"python",
"django",
"django-views"
] |
thresholds in roc_curve in scikit learn | 39,155,900 | <p>I am referring to the below link and sample, and post the plot diagram from this page where I am confused. My confusion is, there are only 4 threshold, but it seems the roc curve has many data points (> 4 data points), wondering how roc_curve working underlying to find more data points?</p>
<p><a href="http://scikit-learn.org/stable/modules/model_evaluation.html#roc-metrics" rel="nofollow">http://scikit-learn.org/stable/modules/model_evaluation.html#roc-metrics</a></p>
<pre><code>>>> import numpy as np
>>> from sklearn.metrics import roc_curve
>>> y = np.array([1, 1, 2, 2])
>>> scores = np.array([0.1, 0.4, 0.35, 0.8])
>>> fpr, tpr, thresholds = roc_curve(y, scores, pos_label=2)
>>> fpr
array([ 0. , 0.5, 0.5, 1. ])
>>> tpr
array([ 0.5, 0.5, 1. , 1. ])
>>> thresholds
array([ 0.8 , 0.4 , 0.35, 0.1 ])
</code></pre>
<p><a href="http://i.stack.imgur.com/s3AVy.png" rel="nofollow"><img src="http://i.stack.imgur.com/s3AVy.png" alt="enter image description here"></a></p>
| 0 | 2016-08-25T22:47:13Z | 39,157,785 | <p>That plot is actually from this example: <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html</a></p>
| 1 | 2016-08-26T03:15:50Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"roc"
] |
How to get a python script to invoke "python -i" when called normally? | 39,155,928 | <p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p>
<p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the script will enter interactive mode after running?</p>
<p>Of course, I can simply add the <code>-i</code>, or if that is too much effort, I can write a shell script to invoke this.</p>
| 18 | 2016-08-25T22:51:54Z | 39,155,956 | <p>I think you're looking for <a href="https://docs.python.org/3/library/code.html#code.interact" rel="nofollow" title="code.interact">this</a>?</p>
<pre class="lang-py prettyprint-override"><code>import code
foo = 'bar'
print foo
code.interact(local=locals())
</code></pre>
| 3 | 2016-08-25T22:54:42Z | [
"python",
"python-interactive"
] |
How to get a python script to invoke "python -i" when called normally? | 39,155,928 | <p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p>
<p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the script will enter interactive mode after running?</p>
<p>Of course, I can simply add the <code>-i</code>, or if that is too much effort, I can write a shell script to invoke this.</p>
| 18 | 2016-08-25T22:51:54Z | 39,155,981 | <p>From within <code>script.py</code>, set the <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONINSPECT"><code>PYTHONINSPECT</code></a> environment variable to any nonempty string. Python will recheck this environment variable at the end of the program and enter interactive mode.</p>
<pre><code>import os
# This can be placed at top or bottom of the script, unlike code.interact
os.environ['PYTHONINSPECT'] = 'TRUE'
</code></pre>
| 19 | 2016-08-25T22:57:40Z | [
"python",
"python-interactive"
] |
How to get a python script to invoke "python -i" when called normally? | 39,155,928 | <p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p>
<p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the script will enter interactive mode after running?</p>
<p>Of course, I can simply add the <code>-i</code>, or if that is too much effort, I can write a shell script to invoke this.</p>
| 18 | 2016-08-25T22:51:54Z | 39,155,984 | <p>You could use an instance of <a href="https://docs.python.org/3/library/code.html#code.InteractiveInterpreter" rel="nofollow"><code>code.InteractiveConsole</code></a> to get this to work:</p>
<pre><code>from code import InteractiveConsole
i = 20
d = 30
InteractiveConsole(locals=locals()).interact()
</code></pre>
<p>running this with <code>python script.py</code> will launch an interactive interpreter as the final statement and make the local names defined visible via <code>locals=locals()</code>.</p>
<pre><code>>>> i
20
</code></pre>
<p>Similarly, a convenience function named <a href="https://docs.python.org/3/library/code.html#code.interact" rel="nofollow"><code>code.interact</code></a> can be used:</p>
<pre><code>from code import interact
i = 20
d = 30
interact(local=locals())
</code></pre>
<p>This creates the instance for you, with the only caveat that <code>locals</code> is named <code>local</code> instead.</p>
<hr>
<p>In addition to this, as <a href="http://stackoverflow.com/users/464744/blender">@Blender</a> stated in the comments, you could also embed the <code>IPython</code> REPL by using:</p>
<pre><code>import IPython
IPython.embed()
</code></pre>
<p>which has the added benefit of not requiring the namespace that has been populated in your script to be passed with <code>locals</code>.</p>
| 6 | 2016-08-25T22:58:07Z | [
"python",
"python-interactive"
] |
How to get a python script to invoke "python -i" when called normally? | 39,155,928 | <p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p>
<p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the script will enter interactive mode after running?</p>
<p>Of course, I can simply add the <code>-i</code>, or if that is too much effort, I can write a shell script to invoke this.</p>
| 18 | 2016-08-25T22:51:54Z | 39,156,962 | <p>In addition to all the above answers, you can run the script as simply <code>./script.py</code> by making the file executable and setting the shebang line, e.g.</p>
<pre><code>#!/usr/bin/python -i
this = "A really boring program"
</code></pre>
<hr>
<p>If you want to use this with the <code>env</code> command in order to get the system default <code>python</code>, then you can try using a shebang like <a href="http://stackoverflow.com/users/5249307/donkopotamus">@donkopotamus</a> suggested in the comments</p>
<pre><code>#!/usr/bin/env PYTHONINSPECT=1 python
</code></pre>
<p>The success of this may depend on the version of <code>env</code> installed on your platform however.</p>
| 7 | 2016-08-26T01:10:06Z | [
"python",
"python-interactive"
] |
How to get a python script to invoke "python -i" when called normally? | 39,155,928 | <p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p>
<p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the script will enter interactive mode after running?</p>
<p>Of course, I can simply add the <code>-i</code>, or if that is too much effort, I can write a shell script to invoke this.</p>
| 18 | 2016-08-25T22:51:54Z | 39,157,837 | <p>I would simply accompany the script with a shell script that invokes it.</p>
<pre class="lang-sh prettyprint-override"><code>exec python -i "$(dirname "$0")/script.py"
</code></pre>
| 1 | 2016-08-26T03:23:18Z | [
"python",
"python-interactive"
] |
"QStackedWidget.setCurrentIndex": It does not work or error mark | 39,155,952 | <p>I'm doing a program with graphical interface using PyQt5 . I want to do is that when the user presses certain button, this change widget and show other options.</p>
<p>For this I decided to use QStackedWidget, and all my interface build it from the QT5 designer.</p>
<p>However, in my code, wanting to determine that my name button "btfr" show me "page_2" of my stackedWidget when pressed, using the QStackedWidget.setCurrentIndex method, this does nothing or make any error.</p>
<p>the code is as follows:</p>
<pre><code>import sys
from PyQt5 import uic
from PyQt5.QtCore import QTimeLine
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
infz = uic.loadUiType("main.ui")[0]
class FaderWidget(QWidget):
def __init__(self, old_widget, new_widget):
QWidget.__init__(self, new_widget)
self.old_pixmap = QPixmap(new_widget.size())
old_widget.render(self.old_pixmap)
self.pixmap_opacity = 1.0
self.timeline = QTimeLine()
self.timeline.valueChanged.connect(self.animate)
self.timeline.finished.connect(self.close)
self.timeline.setDuration(333)
self.timeline.start()
self.resize(new_widget.size())
self.show()
def paintEvent(self, event):
painter = QPainter()
painter.begin(self)
painter.setOpacity(self.pixmap_opacity)
painter.drawPixmap(0, 0, self.old_pixmap)
painter.end()
def animate(self, value):
self.pixmap_opacity = 1.0 - value
self.repaint()
class StackedWidget(QStackedWidget):
def __init__(self, parent=None):
QStackedWidget.__init__(self, parent)
def setCurrentIndex(self, index):
self.stack = MyWindowClass()
self.a = self.stack.stackedWidget.currentWidget()
self.b = self.stack.stackedWidget.widget(index)
self.fader_widget = FaderWidget(self.a, self.b)
QStackedWidget.setCurrentIndex(self, index)
print(self, index)
def setPage1(self):
self.setCurrentIndex(0)
def setPage2(self):
self.setCurrentIndex(1)
class MyWindowClass(QStackedWidget, infz):
def __init__(self, parent=None):
global pos, c, f
self.pos = 0
self.c = []
self.f = False
QStackedWidget.__init__(self, parent)
self.setupUi(self)
self.setWindowTitle('SkR')
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWindowClass()
window.resize(788, 518)
stack = StackedWidget()
window.btfr.clicked.connect(stack.setPage2)
window.btnpx.clicked.connect(stack.setPage1)
window.show()
sys.exit(app.exec_())
</code></pre>
<p>What I intend with this code is that the change of widget does so with an effect: "fade out".</p>
<p>If I print the "self " and the "index " receiving QStackedWidget.setCurrentIndex shows the following:</p>
<pre><code><__main__.StackedWidget object at 0x7fc2eb6b5c18> 0
</code></pre>
<p>The number zero is index, and the other element is self</p>
<p>Thank you for your attention, I hope someone can help.</p>
| 2 | 2016-08-25T22:54:23Z | 39,158,076 | <p>Your question isn't completely clear, but don't you just want:</p>
<pre><code>def setIndex(self, index):
self.setCurrentIndex(index)
</code></pre>
<p>However, this is a little redundant as you should able to link the button directly to the <code>setCurrentIndex</code> method and use <code>lambda</code> to pass the index value:</p>
<pre><code>btfr.clicked.connect(lambda: self.setCurrentIndex(2))
</code></pre>
| 0 | 2016-08-26T03:59:59Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5",
"qstackedwidget"
] |
Exposing python jupyter on LAN | 39,155,953 | <p>I've installed jupyter on local network LAN but im unable to access <code>http://<IP>:8888</code> from another macine on LAN. I've opened ports 8888 and port range 49152 to 65535 with iptables (this range is specified at <a href="http://jupyter-notebook.readthedocs.io/en/latest/public_server.html" rel="nofollow">http://jupyter-notebook.readthedocs.io/en/latest/public_server.html</a>) </p>
<p>This guide <a href="http://jupyter-notebook.readthedocs.io/en/latest/public_server.html" rel="nofollow">http://jupyter-notebook.readthedocs.io/en/latest/public_server.html</a> describes exposing a notebook publicly but I'm just attempting to share over LAN.</p>
<p>Have I missed a step ? </p>
| 3 | 2016-08-25T22:54:27Z | 39,156,006 | <p>Try <code>jupyter notebook --ip <your_LAN_ip> --port 8888</code>
Then visit <code>http://your_LAN_ip:8888</code> from another computer</p>
| 2 | 2016-08-25T23:00:27Z | [
"python",
"linux",
"python-3.x",
"ubuntu-14.04",
"jupyter"
] |
how to do a nested for-each loop with PySpark | 39,155,954 | <p>Imagine a large dataset (>40GB parquet file) containing value observations of thousands of variables as triples <strong>(variable, timestamp, value)</strong>.</p>
<p>Now think of a query in which you are just interested in a subset of 500 variables. And you want to retrieve the observations (values --> time series) for those variables for specific points in time (observation window or timeframe). Such having a start and end time. </p>
<p>Without distributed computing (Spark), you could code it like this:</p>
<pre><code>for var_ in variables_of_interest:
for incident in incidents:
var_df = df_all.filter(
(df.Variable == var_)
& (df.Time > incident.startTime)
& (df.Time < incident.endTime))
</code></pre>
<p><strong>My question is:</strong> how to do that with Spark/PySpark? I was thinking of either:</p>
<ol>
<li>joining the incidents somehow with the variables and filter the dataframe afterward.</li>
<li>broadcasting the incident dataframe and use it within a map-function when filtering the variable observations (df_all).</li>
<li>use RDD.cartasian or RDD.mapParitions somehow (remark: the parquet file was saved partioned by variable).</li>
</ol>
<p>The expected output should be:</p>
<pre><code>incident1 --> dataframe 1
incident2 --> dataframe 2
...
</code></pre>
<p>Where dataframe 1 contains all variables and their observed values within the timeframe of incident 1 and dataframe 2 those values within the timeframe of incident 2.</p>
<p>I hope you got the idea.</p>
<p><strong>UPDATE</strong></p>
<p>I tried to code a solution based on idea #1 and the code from the answer given by zero323. Work's quite well, but I wonder how to aggregate/group it to the incident in the final step? I tried adding a sequential number to each incident, but then I got errors in the last step. Would be cool if you can review and/or complete the code. Therefore I uploaded sample data and the scripts. The environment is Spark 1.4 (PySpark):</p>
<ul>
<li>Incidents: <a href="http://matthias-heise.de/stackoverflow/incidents.csv" rel="nofollow">incidents.csv</a></li>
<li>Variable value observation data (77MB): <a href="http://matthias-heise.de/stackoverflow/parameters_sample.csv" rel="nofollow">parameters_sample.csv</a> (put it to HDFS)</li>
<li>Jupyter Notebook: <a href="http://matthias-heise.de/stackoverflow/nested_for_loop_optimized.ipynb" rel="nofollow">nested_for_loop_optimized.ipynb</a></li>
<li>Python Script: <a href="http://matthias-heise.eu/stackoverflow/nested_for_loop_optimized.py" rel="nofollow">nested_for_loop_optimized.py</a></li>
<li>PDF export of Script: <a href="http://matthias-heise.eu/stackoverflow/nested_for_loop_optimized.pdf" rel="nofollow">nested_for_loop_optimized.pdf</a></li>
</ul>
| 2 | 2016-08-25T22:54:29Z | 39,166,573 | <p>Generally speaking only the first approach looks sensible to me. Exact joining strategy on the number of records and distribution but you can either create a top level data frame:</p>
<pre><code>ref = sc.parallelize([(var_, incident)
for var_ in variables_of_interest:
for incident in incidents
]).toDF(["var_", "incident"])
</code></pre>
<p>and simply <code>join</code></p>
<pre><code>same_var = col("Variable") == col("var_")
same_time = col("Time").between(
col("incident.startTime"),
col("incident.endTime")
)
ref.join(df.alias("df"), same_var & same_time)
</code></pre>
<p>or perform joins against particular partitions:</p>
<pre><code>incidents_ = sc.parallelize([
(incident, ) for incident in incidents
]).toDF(["incident"])
for var_ in variables_of_interest:
df = spark.read.parquet("/some/path/Variable={0}".format(var_))
df.join(incidents_, same_time)
</code></pre>
<p>optionally <a href="http://stackoverflow.com/a/37487575/1560062">marking one side as small enough to be broadcasted</a>.</p>
| 1 | 2016-08-26T12:38:48Z | [
"python",
"apache-spark",
"pyspark"
] |
Sending multiple pings with Python | 39,155,999 | <p>How can I ping <code>192.168.0.1</code> - <code>192.168.0.254</code> all at once? Trying to make the script run faster as it takes several minutes to finish. </p>
<pre><code>import os
import subprocess
ip = raw_input("IP Address? ")
print "Scanning IP Address: " + ip
subnet = ip.split(".")
FNULL = open(os.devnull, 'w')
for x in range(1, 255):
ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x)
response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait()
if response == 0:
print ip2, 'is up!'
else:
print ip2, 'is down!'
</code></pre>
| 2 | 2016-08-25T22:59:33Z | 39,156,105 | <p>Instead of waiting for each process to finish in your loop you can start all the processes at once and save them in a list:</p>
<pre><code>processes = []
for x in range(1, 255):
ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x)
process = subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT)
processes.append((ip2, process))
</code></pre>
<p>Then you can then wait for each process to finish and print the results:</p>
<pre><code>for ip2, process in processes:
response = process.wait()
if response == 0:
print ip2, 'is up!'
else:
print ip2, 'is down!'
</code></pre>
| 2 | 2016-08-25T23:13:32Z | [
"python"
] |
Sending multiple pings with Python | 39,155,999 | <p>How can I ping <code>192.168.0.1</code> - <code>192.168.0.254</code> all at once? Trying to make the script run faster as it takes several minutes to finish. </p>
<pre><code>import os
import subprocess
ip = raw_input("IP Address? ")
print "Scanning IP Address: " + ip
subnet = ip.split(".")
FNULL = open(os.devnull, 'w')
for x in range(1, 255):
ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x)
response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait()
if response == 0:
print ip2, 'is up!'
else:
print ip2, 'is down!'
</code></pre>
| 2 | 2016-08-25T22:59:33Z | 39,156,126 | <p>Look at the method you use to get a response:</p>
<pre><code>response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait()
</code></pre>
<p>most importantly, the <code>.wait()</code> at the end means your program will wait until the process finishes.</p>
<p>You can start 255 processes at once (though you might want to start smaller chunks for the case of sanity) by putting the result of Popen (and not wait) into a list:</p>
<pre><code>processes = []
for ip8 in range(1, 255):
ip32 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(ip8)
process = subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip32], stdout=FNULL, stderr=subprocess.STDOUT)
processes.append(process)
</code></pre>
<p>You can then go through each and every process and wait until they finish:</p>
<pre><code>for process, ip8 in zip(processes, range(1, 255)):
ip32 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(ip8)
response = process.wait()
if response == 0:
print("%s is up!" % (ip32))
else:
print("%s is down!" % (ip32))
</code></pre>
| 0 | 2016-08-25T23:16:03Z | [
"python"
] |
Sending multiple pings with Python | 39,155,999 | <p>How can I ping <code>192.168.0.1</code> - <code>192.168.0.254</code> all at once? Trying to make the script run faster as it takes several minutes to finish. </p>
<pre><code>import os
import subprocess
ip = raw_input("IP Address? ")
print "Scanning IP Address: " + ip
subnet = ip.split(".")
FNULL = open(os.devnull, 'w')
for x in range(1, 255):
ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x)
response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait()
if response == 0:
print ip2, 'is up!'
else:
print ip2, 'is down!'
</code></pre>
| 2 | 2016-08-25T22:59:33Z | 39,156,641 | <p>Or you could ping them all with one ping to the subnet broadcast address. So if your subnet is <code>255.255.255.0</code> (also known as <code>/24</code>) then just ping <code>192.168.0.255</code> and <em>normally</em> everyone will ping back. </p>
| 0 | 2016-08-26T00:23:02Z | [
"python"
] |
UnboundLocalError local variables referenced before assignment / Consideration | 39,156,076 | <p>I have the following function based view</p>
<pre><code>def post_search(request):
form = SearchForm()
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all()
# count total results
total_results = results.count()
return render(request, 'blog/post/search.html', {'form': form,
'cd': cd,
'results': results,
'total_results': total_results})
</code></pre>
<p>When I execute my url that call this function I get the following error</p>
<pre><code>UnboundLocalError: local variable 'cd' referenced before assignment
[25/Aug/2016 22:48:13] "GET /blog/search/ HTTP/1.1" 500 69440
</code></pre>
<p><code>cd</code>, <code>results</code> and <code>total_results</code> variables are declared and used in a scope different to the <code>return render(request ...)</code> sentence at the end.</p>
<p>It's for this reason the error.</p>
<p>I've initialized this variables as a globals of this way:</p>
<pre><code>cd = results=total_results=None
</code></pre>
<p>before of the conditional sentences</p>
<pre><code>def post_search(request):
form = SearchForm()
# Initialize variables
cd = results=total_results=None
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all()
# count total results
total_results = results.count()
return render(request, 'blog/post/search.html', {'form': form,
'cd': cd,
'results': results,
'total_results': total_results})
</code></pre>
<p>And my GET request it's works </p>
<pre><code>[25/Aug/2016 23:05:33] "GET /blog/search/ HTTP/1.1" 200 2260
</code></pre>
<p>I could solve this of some another way?
This functionality is for search in a web,
Is this good when I have many users using this functionality? </p>
<p>I think that the solution is not good practice ... I don't know.</p>
| 0 | 2016-08-25T23:10:17Z | 39,156,094 | <p>It means, either your <code>form.is_valid()</code> is <code>False</code> or, you are not making the <code>GET</code> request. </p>
<p>Add <code>cd = results = total_results = None</code> before the first if condition. Because, in your current code, if any of the <code>if</code> condition fails, <code>cd</code>, <code>results</code> and <code>total_results</code> will not be initialized and hence will throw this error. Your updated code should be:</p>
<pre><code>def post_search(request):
form = SearchForm()
cd = results = total_results = None # <--- Add this to your code
if 'query' in request.GET:
. . . Something Something
return render(request, 'blog/post/search.html', {'form': form,
'cd': cd,
'results': results,
'total_results': total_results})
</code></pre>
| 1 | 2016-08-25T23:12:35Z | [
"python",
"django",
"variables",
"scope"
] |
Is it possible to insert knobs on nodes in Nuke? | 39,156,092 | <p>The main interface for adding knobs to nodes in nuke appears to be the <code>node.addKnob()</code> function. The knobs are added in the order that the <code>addKnob</code> method is called. Is there a way to insert knobs before other knobs that have already been created?</p>
| 0 | 2016-08-25T23:12:14Z | 39,215,596 | <p>According to Foundry support, it is <em>not</em> possible to insert knobs into existing nodes or groups. The only option is to delete and recreate the set of knobs.</p>
| 0 | 2016-08-29T21:37:07Z | [
"python",
"nuke"
] |
Can't find string after a tag with BeautifulSoup in Python? | 39,156,107 | <p>In this HTML I want to get the string of it but no matter what I try it doesn't work (string = none)</p>
<pre><code> <a href="/analyze/default/index/49398962/1/34925733" target="_blank">
<img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/profileIconId/default.jpg" src="/images/common/transbg.png"/>
Jue VioIe Grace
</a>
</code></pre>
<p>There's a few of these on the page and I tried this:</p>
<pre><code>print([a.string for a in soup.findAll('td', class_='tou')])
</code></pre>
<p>The output is just none.</p>
<p>EDIT: here is the entire page HTML, hope this helps, just to clarify, I need to find all instances like the one above and extract their string</p>
<p><a href="http://pastebin.com/4mvcMsJu" rel="nofollow">http://pastebin.com/4mvcMsJu</a></p>
| 3 | 2016-08-25T23:13:51Z | 39,156,201 | <p>Well, if your <code>soup</code> variable is made off that html piece of code then the output you get is <code>None</code> because there is no <code>td</code> element inside it, and of course there is not <code>td</code> element with <code>class=tou</code>.</p>
<p>Now, if you want to get that text maybe you could call <code>soup.findAll(text=True)</code> which outputs something like <code>['\n', '\n Jue VioIe Grace\n ']</code></p>
| 0 | 2016-08-25T23:25:51Z | [
"python",
"beautifulsoup"
] |
Can't find string after a tag with BeautifulSoup in Python? | 39,156,107 | <p>In this HTML I want to get the string of it but no matter what I try it doesn't work (string = none)</p>
<pre><code> <a href="/analyze/default/index/49398962/1/34925733" target="_blank">
<img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/profileIconId/default.jpg" src="/images/common/transbg.png"/>
Jue VioIe Grace
</a>
</code></pre>
<p>There's a few of these on the page and I tried this:</p>
<pre><code>print([a.string for a in soup.findAll('td', class_='tou')])
</code></pre>
<p>The output is just none.</p>
<p>EDIT: here is the entire page HTML, hope this helps, just to clarify, I need to find all instances like the one above and extract their string</p>
<p><a href="http://pastebin.com/4mvcMsJu" rel="nofollow">http://pastebin.com/4mvcMsJu</a></p>
| 3 | 2016-08-25T23:13:51Z | 39,156,223 | <p>You need to select the <em>a</em> from the parent <em>td</em> and call <em>.text</em>, the text is inside the anchor which is a child of the td:</p>
<pre><code>print([td.a.text for td in soup.find_all('td', class_='tou')])
</code></pre>
<p>There obviously is a td with the class tou or you would not be getting a list with None:</p>
<pre><code>In [10]: html = """<td class='tou'>
<a href="/analyze/default/index/49398962/1/34925733" target="_blank">
<img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/profileIconId/default.jpg" src="/images/common/transbg.png"/>
Jue VioIe Grace
</a>
</td>"""
In [11]: soup = BeautifulSoup(html,"html.parser")
In [12]: [a.string for a in soup.find_all('td', class_='tou')]
Out[12]: [None]
In [13]: [td.a.text for td in soup.find_all('td', class_='tou')]
Out[13]: [u'\n\n Jue VioIe Grace\n ']
</code></pre>
<p>You could also call .text on the td:</p>
<pre><code>In [14]: [td.text for td in soup.find_all('td', class_='tou')]
Out[14]: [u'\n\n\n Jue VioIe Grace\n \n']
</code></pre>
<p>But that would maybe get more than you want.</p>
<p>using your full html from pastebin:</p>
<pre><code>In [18]: import requests
In [19]: soup = BeautifulSoup(requests.get("http://pastebin.com/raw/4mvcMsJu").content,"html.parser")
In [20]: [td.a.text.strip() for td in soup.find_all('td', class_='tou')]
Out[20]:
[u'KElTHMCBRlEF',
u'game 5 loser',
u'Cris',
u'interestingstare',
u'ApoIlo Price',
u'Zary',
u'Adrian Ma',
u'Liquid Inori',
u'focus plz',
u'Shiphtur',
u'Cody Sun',
u'ApoIIo Price',
u'Pobelter',
u'Jue VioIe Grace',
u'Valkrin',
u'Piggy Kitten',
u'1 and 17',
u'BLOCK IT',
u'JiaQQ1035716423',
u'Twitchtv Flaresz']
</code></pre>
<p>In this case <code>td.text.strip()</code> gives you the same output:</p>
<pre><code>In [23]: [td.text.strip() for td in soup.find_all('td', class_='tou')]
Out[23]:
[u'KElTHMCBRlEF',
u'game 5 loser',
u'Cris',
u'interestingstare',
u'ApoIlo Price',
u'Zary',
u'Adrian Ma',
u'Liquid Inori',
u'focus plz',
u'Shiphtur',
u'Cody Sun',
u'ApoIIo Price',
u'Pobelter',
u'Jue VioIe Grace',
u'Valkrin',
u'Piggy Kitten',
u'1 and 17',
u'BLOCK IT',
u'JiaQQ1035716423',
u'Twitchtv Flaresz']
</code></pre>
<p>But you should understand that there is a difference. Also the difference between <a href="http://stackoverflow.com/questions/25327693/difference-between-string-and-text-beautifulsoup">.string vs .text</a></p>
| 3 | 2016-08-25T23:28:35Z | [
"python",
"beautifulsoup"
] |
Can't find string after a tag with BeautifulSoup in Python? | 39,156,107 | <p>In this HTML I want to get the string of it but no matter what I try it doesn't work (string = none)</p>
<pre><code> <a href="/analyze/default/index/49398962/1/34925733" target="_blank">
<img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/profileIconId/default.jpg" src="/images/common/transbg.png"/>
Jue VioIe Grace
</a>
</code></pre>
<p>There's a few of these on the page and I tried this:</p>
<pre><code>print([a.string for a in soup.findAll('td', class_='tou')])
</code></pre>
<p>The output is just none.</p>
<p>EDIT: here is the entire page HTML, hope this helps, just to clarify, I need to find all instances like the one above and extract their string</p>
<p><a href="http://pastebin.com/4mvcMsJu" rel="nofollow">http://pastebin.com/4mvcMsJu</a></p>
| 3 | 2016-08-25T23:13:51Z | 39,156,228 | <pre><code>>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(open('input.html'), 'lxml')
>>> [tag.text.strip() for tag in soup]
[u'Jue VioIe Grace']
</code></pre>
<p>If we want to restrict the search to text in <em>anchor</em> tags:</p>
<pre><code>>>> [tag.text.strip() for tag in soup.findAll('a')]
[u'Jue VioIe Grace']
</code></pre>
<p>Note that there are no <code>td</code> tags in your sample input and no tag has the attribute <code>class_='tou'</code>.</p>
| 2 | 2016-08-25T23:29:16Z | [
"python",
"beautifulsoup"
] |
Django client test (get, post) response load data from main db instead fixtures loaded in test db | 39,156,132 | <p>I'm new in Django, and I have this problem:
I use self.client to test routes in my app.
e.g.</p>
<pre><code>class BookSell(TestCase):
fixtures = [
'sellers.yaml',
'books.yaml'
...
]
def test_get_book_sell(self):
book = Books.objects.get(pk=1)
print(book.name)#it prints "El Quijote" in the test output
response = self.client.get('/sell/book-sell')
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Book Sell")
self.assertContains(response, "El Quijote")#book name
</code></pre>
<p>The view method linked to that path should load some data from the database and then render it.
But when I run </p>
<pre><code>python manage.py test app_name
</code></pre>
<p>it doesn't load data from fixtures, because the response doesn't contain "El Quijote". Only when I run:</p>
<pre><code>python manage.py loaddata fixture_name.yaml ...
</code></pre>
<p>and then run again the tests the view method loads data from the database.</p>
<p>So I conclude that when I run the tests, my views methods load data from main database instead of test database</p>
<p>What is that I'm doing wrong?
Is there a way to load just data from test database?</p>
<p>django version: 1.9.4</p>
<p>python version: 2.7.6</p>
<p>I'm sure that the fixtures load with sucess in test database</p>
| 0 | 2016-08-25T23:16:39Z | 39,339,532 | <p>Finally I discovered what I was doing wrong, thanks to this answer: <a href="http://stackoverflow.com/questions/29773665/django-reload-form-data-after-db-values-change">Django: reload form data after db values change</a></p>
<p>I had a form like this:</p>
<pre><code>class BookSellForm(forms.Form):
books = [('', 'Choose a book')]
books.extend(Books.objects.values_list('id', 'name'))
libro = forms.ChoiceField(books)
</code></pre>
<p>And that was the problem, I had to change to this</p>
<pre><code>class BookSellForm(forms.Form):
def __init__(self, *args, **kwargs):
super(BookSellForm, self).__init__(*args, **kwargs)
books = [('', 'Choose a book')]
books.extend(Books.objects.values_list('id', 'name'))
self.fields['book'] = forms.ChoiceField(books)
</code></pre>
<p>and then everything worked fine, I hope this will be helpful to someone in the future.</p>
| 0 | 2016-09-06T01:49:19Z | [
"python",
"django",
"testing",
"fixtures"
] |
Django how to filter based on ManyToManyField? | 39,156,154 | <p>Suppose I have the following Django classes:</p>
<p>in myclassa.py:</p>
<pre><code>class MyClassA(models.Model):
name = models.CharField(max_length=254)
def my_method(self):
# WHAT GOES HERE?
</code></pre>
<p>in myclassb.py:</p>
<pre><code>from myclassa import MyClassA
class MyClassB(models.Model):
name = models.CharField(max_length=254)
a = models.ManyToManyField(MyClassA, related_name="MyClassB_MyClassA")
</code></pre>
<p>Now suppose I have an instance <code>x</code> of <code>MyClassA</code>.
What do I put in <code>my_method()</code> such that it returns all the instances of <code>MyClassB</code> that contain <code>x</code> in their field <code>a</code>?</p>
| 2 | 2016-08-25T23:19:14Z | 39,156,215 | <p>You may define it as:</p>
<pre><code>def my_method(self):
return self.MyClassB_MyClassA.all()
</code></pre>
<p>Alternatively, you may also define it as:</p>
<pre><code>def my_method(self):
return MyClassB.objects.filter(a=self)
</code></pre>
| 2 | 2016-08-25T23:27:34Z | [
"python",
"django",
"django-models",
"django-queryset"
] |
Installing module in python with anaconda and jupyter notebook | 39,156,207 | <p>I've been having a problem with installing modules, and I can't find an exact solution to it anywhere. What I'm trying to do is use anaconda to install a module. When I type into the anaconda command prompt:</p>
<pre><code>pip install imbox
</code></pre>
<p>it says it installs. So then i open jupyter notebook by simply using</p>
<pre><code>jupyter notebook
</code></pre>
<p>Everything seems ok until I try to</p>
<pre><code>from imbox import Imbox
</code></pre>
<p>and I get</p>
<pre><code>No module named imbox
</code></pre>
<p>How would I make jupyter notebook include that module?</p>
| 0 | 2016-08-25T23:26:35Z | 39,156,348 | <p>Try using the pip that comes with conda, instead of your default pip.</p>
<p><code>PATH_TO_CONDA_DIR/bin/pip install imbox</code></p>
<p>In your case:</p>
<p><code>C:\Users\USERNAME\Anaconda2\bin\pip install imbox</code></p>
<p>Alternative, install the package again, in the specified location:</p>
<p><code>pip install --target=C:\Users\USERNAME\Anaconda2\lib\site-packages imbox</code></p>
| 1 | 2016-08-25T23:42:53Z | [
"python",
"module",
"anaconda",
"jupyter"
] |
Python - Fastest way to clear the screen? | 39,156,221 | <p>What would the fastest way to clear the screen, be?</p>
<p>I've tried many solutions, they seem to work, however, I need the fastest way. Could anyone point me in the right direction?</p>
<p>The screen, in my case, is a command prompt.</p>
<p>I've edited my question for better understandings.</p>
<p>Any help welcomed :)</p>
| -5 | 2016-08-25T23:28:16Z | 39,156,262 | <p>One portable solution could be:</p>
<pre><code>def clear_sceen():
os.system('cls' if os.name == 'nt' else 'clear')
</code></pre>
<p>Another possible way would be using:</p>
<pre><code>print(chr(27) + "[2J")
</code></pre>
<p>Although this one wouldn't be really a portable solution</p>
| 3 | 2016-08-25T23:33:08Z | [
"python",
"cmd",
"screen",
"line",
"clear"
] |
Why am I getting an sqlalchemy.exc.ProgrammingError rather than a sqlalchemy.exc.IntegrityError? | 39,156,330 | <p>I'm writing some account creation code and trying to catch a particular sqlalchemy exception so that I can feed back an appropriate error message when a user registers an account with an email that is already associated to an existing account.</p>
<p>I was expecting to get an IntegrityError when this happened but I am instead getting a ProgrammingError. I could happily catch ProgrammingError instead but I'm trying to understand why I'm not getting what I'd expect.</p>
<p>I've cut down the model and code for clarity but the model looks like:</p>
<pre><code>from service import db
from sqlalchemy import Index
class UserProfile(db.Model):
user_id = db.Column(db.String(255), nullable=False, primary_key=True)
email = db.Column(db.String(255), nullable=False)
def __init__(self, account_data):
self.user_id = account_data['userId']
self.email = account_data['email'].lower()
def __repr__(self):
return 'UserID-{}, Email-{}'.format(self.user_id,self.email)
Index('idx_email', UserProfile.email, unique=True)
</code></pre>
<p>And the main bit of the code looks like:</p>
<pre><code>@app.route('/create_account', methods=['POST'])
def create_account():
account_data = request.get_json()
account_details = UserProfile(account_data)
try:
db.session.add(account_details)
db.session.flush()
# do stuff
db.session.commit()
except ProgrammingError as err:
db.session.rollback()
if "duplicate key value violates unique constraint \"idx_email\"" in str(err):
LOGGER.error('Email address already in use!'
</code></pre>
<p>So if I post in some json for example:</p>
<pre><code>{
"userId": "Fred",
"email": "a@b.com"
}
</code></pre>
<p>and then post again with a different userId but the same email:</p>
<pre><code>{
"userId": "Bob",
"email": "a@b.com"
}
</code></pre>
<p>I would expect the second post to raise an IntegrityError but I'm seeing it raise a ProgrammingError:</p>
<pre><code>sqlalchemy.exc.ProgrammingError: (pg8000.core.ProgrammingError)
('ERROR',
'23505',
'duplicate key value violates unique constraint "idx_email"',
'Key (email)=(a@b.com) already exists.',
'public',
'user_profile',
'idx_email',
'nbtinsert.c',
'406',
'_bt_check_unique', '', '')
[SQL: 'INSERT INTO user_profile (user_id, email) VALUES (%s, %s)']
[parameters: ('Bob', 'a@b.com')]
</code></pre>
<p>What am I missing?</p>
| 3 | 2016-08-25T23:40:46Z | 39,156,742 | <p>Unfortunately, when it comes to <a href="https://www.python.org/dev/peps/pep-0249" rel="nofollow">DBAPI</a> errors SQLAlchemy merely wraps the exception raised by the underlying dbapi compatible library.</p>
<p>That is, SQLAlchemy raises a <code>ProgrammingError</code> in particular only <em>because <code>pg8000</code> chose to raise a <code>ProgrammingError</code></em>. </p>
<p>If you had been using <code>psycopg2</code> to manage your underlying connection, your error would have manifested itself as an <code>IntegrityError</code> (as expected).</p>
<p>According to the <a href="http://pythonhosted.org/pg8000/dbapi.html#pg8000.IntegrityError" rel="nofollow"><code>pg8000</code> documentation</a>, it will never raise an <code>IntegrityError</code>. In fact it will not raise any of the following:</p>
<ul>
<li>IntegrityError;</li>
<li>DataError;</li>
<li>DatabaseError;</li>
<li>OperationalError; </li>
</ul>
<p>The lesson here is that when it comes to database level errors, you cannot guarantee the type that SQLAlchemy will throw across different dbapi connectors.</p>
| 3 | 2016-08-26T00:38:42Z | [
"python",
"sqlalchemy"
] |
Do ec2 tag numbers change? | 39,156,377 | <p>Below is some simple code. What SHOULD pull the key:name tag. However when I add a second tag, it seems to change the order, so 0 isn't always the name??? </p>
<pre><code>instances = ec2.instances.filter(Filters=[{'Name':'instance-state-name','Values':['running']}])
for instance in instances:
for tag in instance.tags:
if 'Name'in tag['Key']:
name = tag['Value']
print "Pulling all instance info..."
for instance in instances:
print(instance.id, instance.instance_type,instance.private_ip_address, instance.tags[0].get("Value"))
</code></pre>
| -1 | 2016-08-25T23:46:54Z | 39,156,416 | <p>Yes. <code>instance.tags</code> is a list and your tag can appear anywhere in the list. If you are trying to get the 'Name', you have to loop through the list. Each element in the list is a dictionary. Check if the key is 'Name' before getting the value.</p>
<p>It sounds complex, but very simple to code. You cannot blindly do <code>instance.tags[0].get("Value")</code></p>
| 1 | 2016-08-25T23:51:27Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto3"
] |
Sorting dictionary of lists based on first value in list | 39,156,425 | <p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p>
<pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]}
should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]}
</code></pre>
<p>What I had originally was:</p>
<pre><code>orderedDict = collections.OrderedDict(sorted(dict.iteritems(), key=lambda (k,v):(v,k), reverse=True))
</code></pre>
<p>when the values of the dictionary were simply numbers, but now that I have changed the value of the dictionary to be a list to contain 2 numbers, I'm not sure how to access and sort by the first number..</p>
<p>I'm using Python 2.7. Any help would be greatly appreciated! Thanks!</p>
| 0 | 2016-08-25T23:53:33Z | 39,156,452 | <p>You are almost there!</p>
<pre><code>collections.OrderedDict(sorted(a.iteritems(), key=lambda (k,v):v[0], reverse=True))
^^^^
</code></pre>
<p>When <code>sorted(..)</code> is called with a <code>key=</code> argument, every element of the first parameter is passed to the lambda. In your case, <code>k</code> would be one key (eg: <code>"key1"</code>), and <code>v</code> would be one value (eg: <code>[7,7]</code>). All you need to say from here is: <code>v[0]</code></p>
<pre><code>>>> collections.OrderedDict(sorted(a.iteritems(), key=lambda (k,v):v[0], reverse=True))
OrderedDict([('key2', [7, 7]), ('key3', [5, 10]), ('key1', [2, 3])])
</code></pre>
<hr>
<p><strong>NOTE</strong>: There is a difference between saying: <code>v[0]</code> and <code>(v[0],k)</code>. In the latter case, you are passing a tuple for comparison. It might not do what you'd want. Read up on how tuple comparison works.</p>
| 1 | 2016-08-25T23:57:37Z | [
"python",
"list",
"sorting",
"dictionary",
"ordereddictionary"
] |
Sorting dictionary of lists based on first value in list | 39,156,425 | <p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p>
<pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]}
should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]}
</code></pre>
<p>What I had originally was:</p>
<pre><code>orderedDict = collections.OrderedDict(sorted(dict.iteritems(), key=lambda (k,v):(v,k), reverse=True))
</code></pre>
<p>when the values of the dictionary were simply numbers, but now that I have changed the value of the dictionary to be a list to contain 2 numbers, I'm not sure how to access and sort by the first number..</p>
<p>I'm using Python 2.7. Any help would be greatly appreciated! Thanks!</p>
| 0 | 2016-08-25T23:53:33Z | 39,156,462 | <p>Instead of <code>v</code>, you have to just mention <code>v[0]</code> that is the is the index in value on which you want to sort.</p>
<pre><code>>>> orderedDict = collections.OrderedDict(sorted(my_dict.iteritems(), key=lambda (k,v):v[0], reverse=True))
>>> orderedDict
OrderedDict([('key2', [7, 7]), ('key3', [5, 10]), ('key1', [2, 3])])
</code></pre>
<p>Additonal piece of info, you may remove <code>reversed=True</code> param in the call and replace <code>v[0]</code> with <code>-v[0]</code>. Result will be same:</p>
<pre><code>>>> orderedDict = collections.OrderedDict(sorted(my_dict.iteritems(), key=lambda (k,v):-v[0]))
>>> orderedDict
OrderedDict([('key2', [7, 7]), ('key3', [5, 10]), ('key1', [2, 3])])
</code></pre>
| 0 | 2016-08-25T23:58:42Z | [
"python",
"list",
"sorting",
"dictionary",
"ordereddictionary"
] |
Sorting dictionary of lists based on first value in list | 39,156,425 | <p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p>
<pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]}
should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]}
</code></pre>
<p>What I had originally was:</p>
<pre><code>orderedDict = collections.OrderedDict(sorted(dict.iteritems(), key=lambda (k,v):(v,k), reverse=True))
</code></pre>
<p>when the values of the dictionary were simply numbers, but now that I have changed the value of the dictionary to be a list to contain 2 numbers, I'm not sure how to access and sort by the first number..</p>
<p>I'm using Python 2.7. Any help would be greatly appreciated! Thanks!</p>
| 0 | 2016-08-25T23:53:33Z | 39,156,603 | <p>Did you test what you already had to see whether it still worked? Because it does. When you sort a group of sequences, they are compared "alphabetically" - if the first items of two sequences are equal, their second items are compared, and so on. This means that, in your example, <code>sorted</code> would compare the first element of the value's <code>list</code>. If they are different, the sort order is exactly what it would be if you were comparing the first element only with <code>v[0]</code>. If they are the same, sorting by <code>v[0]</code> would simply ensure an arbitrary order for those elements. Leaving it as <code>(v,k)</code> ensures that if the first elements of the value <code>list</code> are equal, it sorts based on the rest of the elements. If there are two values with identical <code>list</code>s, it sorts based on the key.</p>
<pre><code>>>> import collections
>>> d = {'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]}
>>> orderedDict = collections.OrderedDict(sorted(d.iteritems(), key=lambda (k,v):(v,k), reverse=True))
>>> orderedDict
OrderedDict([('key2', [7, 7]), ('key3', [5, 10]), ('key1', [2, 3])])
</code></pre>
| 0 | 2016-08-26T00:16:30Z | [
"python",
"list",
"sorting",
"dictionary",
"ordereddictionary"
] |
How do you permanently change the JYTHONPATH in Jython 2.5 on Ubuntu 14? | 39,156,446 | <p>I'm using Ubuntu 14.04 LTS and Jython 2.5.3. I want to add a directory to the path Jython takes to search for Python packages. When I import sys and enter sys.path, here's what I get:</p>
<pre><code>>>> sys.path
['', '/usr/lib/site-python', '/usr/share/jython/Lib', '/usr/Lib', '__classpath__', '__pyclasspath__/']
</code></pre>
<p>I want to add the directory '/foo/bar' at the beginning of the list.</p>
| 0 | 2016-08-25T23:56:33Z | 39,156,478 | <p>I was able to accomplish this by adding the following line to my user bashrc file (~/.bashrc):</p>
<pre><code>export JYTHONPATH=/foo/bar:/usr/lib/site-python:/usr/share/jython/Lib
</code></pre>
| 0 | 2016-08-26T00:00:11Z | [
"python",
"ubuntu",
"ubuntu-14.04",
"pythonpath",
"jython-2.5"
] |
numpy delete not deleting element | 39,156,458 | <p>Under what circumstances would bumpy.delete simply return a copy of the original array, unaltered?</p>
<p>If I do a simple example as follows, then things work as advertised:</p>
<pre><code>>>> a = numpy.arange(0, 10)
>>> numpy.delete(a, [1])
>>> array([0, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>but when I work with an array created from a list by numpy.array() then things don't work anymore.</p>
<pre><code> scale = [Params.BADVALUE, Params.BADVALUE+1]
for h in xrange(500, 3001, 500):
scale.append(h)
scale += [4000, 5000]
for h in xrange(7000, 17001, 2000):
scale.append(h)
scale.append(upper_bound)
self.SCALE = numpy.array(scale)
self.SCALE_WRITE = numpy.delete(self.SCALE, [1000.0])
</code></pre>
<p>self.SCALE_WRITE ends up being identical to self.SCALE</p>
<p>I've checked that self.SCALE is indeed 1-dimensional and that no extra dimensions have been added by mistake. </p>
<p>It's easy enough to code my way around this but I would still like to know what I'm doing wrong.</p>
<p>Catherine</p>
| -2 | 2016-08-25T23:58:27Z | 39,156,679 | <p>To me, it appears that you are simply trying to delete an index that is out of the array; hence the lack of change ...
From your code <code>len(scale)</code> gives only 17 .</p>
<p>For the record as the <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.delete.html" rel="nofollow">doc</a> indicates, <code>numpy.delete(arr,obj)</code> will try to delete the element <strong>returned by arr[obj]</strong> for a 1-D array so :</p>
<ul>
<li>numpy.delete(arr,0)</li>
<li>numpy.delete(arr,[0])</li>
<li>numpy.delete(arr,0.0)</li>
<li>numpy.delete(arr,[0.0])</li>
</ul>
<p>will all <strong>delete <code>arr[0]</code> which is the zero-th element</strong> of that 1-D array.</p>
| 1 | 2016-08-26T00:30:29Z | [
"python",
"arrays",
"numpy"
] |
numpy delete not deleting element | 39,156,458 | <p>Under what circumstances would bumpy.delete simply return a copy of the original array, unaltered?</p>
<p>If I do a simple example as follows, then things work as advertised:</p>
<pre><code>>>> a = numpy.arange(0, 10)
>>> numpy.delete(a, [1])
>>> array([0, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>but when I work with an array created from a list by numpy.array() then things don't work anymore.</p>
<pre><code> scale = [Params.BADVALUE, Params.BADVALUE+1]
for h in xrange(500, 3001, 500):
scale.append(h)
scale += [4000, 5000]
for h in xrange(7000, 17001, 2000):
scale.append(h)
scale.append(upper_bound)
self.SCALE = numpy.array(scale)
self.SCALE_WRITE = numpy.delete(self.SCALE, [1000.0])
</code></pre>
<p>self.SCALE_WRITE ends up being identical to self.SCALE</p>
<p>I've checked that self.SCALE is indeed 1-dimensional and that no extra dimensions have been added by mistake. </p>
<p>It's easy enough to code my way around this but I would still like to know what I'm doing wrong.</p>
<p>Catherine</p>
| -2 | 2016-08-25T23:58:27Z | 39,156,967 | <p>first, <code>delete</code> does not operate in place:</p>
<pre><code>In [849]: a=np.arange(10)
In [850]: np.delete(a,[1])
Out[850]: array([0, 2, 3, 4, 5, 6, 7, 8, 9]) # returned array
In [851]: a
Out[851]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # not change in a
</code></pre>
<p>If I do an out of bounds delete with a scalar, I get an error:</p>
<pre><code>In [853]: a1=np.delete(a,11)
...
IndexError: index 11 is out of bounds for axis 0 with size 10
</code></pre>
<p>But if the delete is a list, it appears the bounds check does not operate (is there a parameter for that?)</p>
<pre><code>In [854]: a1=np.delete(a,[11])
In [855]: a1
Out[855]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p><code>a1</code> is a copy though; changing one of its values does not affect <code>a</code>.</p>
<pre><code>In [858]: a1[-1]=100
In [859]: a1
Out[859]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 100])
In [860]: a
Out[860]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p><code>np.delete</code> is a complicated Python function, written to be quite general. It can be studied. It is not a fundamental function. It is not doing anything you can't do just as well with basic array operations like masking, indexing and/or selective copying. And it isn't going to be faster.</p>
<p>================</p>
<p>You can study <code>np.delete</code>. My memory is that it often does the following:</p>
<p><code>delete</code> via mask for scalar:</p>
<pre><code>In [863]: mask=np.ones(a.shape,dtype=bool)
In [864]: mask[1]=False
In [865]: a[mask]
Out[865]: array([0, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>for list:</p>
<pre><code>In [866]: mask=np.ones(a.shape,dtype=bool)
In [867]: mask[[1,3,5]]=False
In [868]: a[mask]
Out[868]: array([0, 2, 4, 6, 7, 8, 9])
</code></pre>
<p>==================</p>
<p>Recreation of your script with added displays:</p>
<pre><code>In [874]: scale=[1,2]
In [875]: for h in range(500,3001,500):scale.append(h)
In [876]: len(scale)
Out[876]: 8
In [877]: scale+=[4000,5000]
In [878]: for h in range(7000,17001,2000):scale.append(h)
In [879]: len(scale)
Out[879]: 16
In [880]: scale.append(1000)
In [881]: Scale=np.array(scale)
In [882]: Scale.shape
Out[882]: (17,)
In [883]: np.delete(Scale,[1000])
Out[883]:
array([ 1, 2, 500, 1000, 1500, 2000, 2500, 3000, 4000,
5000, 7000, 9000, 11000, 13000, 15000, 17000, 1000])
</code></pre>
<p>So there are only 17 items in the array, not a 1000. And as I illustrated with a delete list, it does not raise an error if it is out of bounds. Hence the <code>delete</code> result is a copy of the input.</p>
<p>By the way I create that same array with an array concatenate</p>
<pre><code>In [886]: np.r_[1, 2, 500:3001:500, [4000,5000], 7000:17001:2000, 1000]
Out[886]:
array([ 1, 2, 500, 1000, 1500, 2000, 2500, 3000, 4000,
5000, 7000, 9000, 11000, 13000, 15000, 17000, 1000])
</code></pre>
<p>Even sticking with the list I can avoid the loops with <code>extend</code>:</p>
<pre><code>In [887]: scale=[1,2]
In [888]: scale.extend(range(500,3001,500))
In [889]: scale.extend([4000,5000])
In [890]: scale.extend(range(7000,17001,2000))
In [891]: scale.append(1000)
</code></pre>
| 0 | 2016-08-26T01:11:12Z | [
"python",
"arrays",
"numpy"
] |
alpha & beta (for linear regression) calculations output nan? | 39,156,506 | <p>I am new to Python and have been attempting to calculate the linear regression/Beta/Alpha for two securities, however my code is outputting Nan for both Beta & Alpha, and therefore I am unable to draw the regression line. </p>
<p>here is the code in question:</p>
<pre><code>#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
</code></pre>
<p>and here is the full script:</p>
<pre><code>from pandas.io.data import DataReader
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
#inputs
symbols = ['EUR=X', 'JPY=X']
startDate = datetime(2011,1,1)
endDate = datetime(2016,12,31)
#get data from yahoo
instrument = DataReader(symbols, 'yahoo', startDate, endDate)
#isolate column
close = instrument['Adj Close']
#calculate daily returns
def compute_daily_returns(df):
daily_returns = (df / df.shift(1)) - 1
return daily_returns
dlyRtns = compute_daily_returns(close)
xPlt = dlyRtns[symbols[0]]
yPlt = dlyRtns[symbols[1]]
#draw "scatter plot" - using "o" workaround
dlyRtns.plot(x=symbols[0], y=symbols[1], marker='o', linewidth=0)
#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
# Calculate correlation coefficient
print "Correlation", dlyRtns.corr(method='pearson')
plt.show()
</code></pre>
<p>and here is the output:</p>
<pre><code>C:\Python27\python.exe C:/Users/Us/Desktop/untitled3/scatterPlot.py
Y Beta nan
Y Alpha nan
Correlation EUR=X JPY=X
EUR=X 1.000000 0.228223
JPY=X 0.228223 1.000000
Process finished with exit code 0
</code></pre>
<p>Any ideas why I getting Nan here? I am at a loss, any help is much appreciated.</p>
| 0 | 2016-08-26T00:03:14Z | 39,160,836 | <p>Trying to look into this, but it's a little confusing to me. In addition, I can not reproduce the data-pulling from yahoo on my current machine, so I can not run your code as it is.</p>
<p>Here a few questions and ideas:</p>
<ul>
<li>You should not name a variable <code>close</code>, since this word is used by Python. Sometimes (as in your example) it works anyway, but it's not good practice.</li>
<li>Can you plot your data <code>xPlt</code> and <code>yPlt</code> separately, without anything else? I suspect that the error is in there.</li>
<li>You call <code>DataReader</code> with an array of two values and save the output in <code>instrument</code>. Then you assign one column (chosen by name) to <code>close</code>, but in fact, there will be two columns named <code>Adj close</code>, right?</li>
</ul>
<p>To cut a long story short: You should try to build up your code step by step, adding some <code>print</code> and <code>plot</code> commands after every step to see how the data that is saved in your variables looks like.</p>
| 0 | 2016-08-26T07:35:22Z | [
"python",
"pandas",
"numpy",
"linear-regression"
] |
alpha & beta (for linear regression) calculations output nan? | 39,156,506 | <p>I am new to Python and have been attempting to calculate the linear regression/Beta/Alpha for two securities, however my code is outputting Nan for both Beta & Alpha, and therefore I am unable to draw the regression line. </p>
<p>here is the code in question:</p>
<pre><code>#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
</code></pre>
<p>and here is the full script:</p>
<pre><code>from pandas.io.data import DataReader
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
#inputs
symbols = ['EUR=X', 'JPY=X']
startDate = datetime(2011,1,1)
endDate = datetime(2016,12,31)
#get data from yahoo
instrument = DataReader(symbols, 'yahoo', startDate, endDate)
#isolate column
close = instrument['Adj Close']
#calculate daily returns
def compute_daily_returns(df):
daily_returns = (df / df.shift(1)) - 1
return daily_returns
dlyRtns = compute_daily_returns(close)
xPlt = dlyRtns[symbols[0]]
yPlt = dlyRtns[symbols[1]]
#draw "scatter plot" - using "o" workaround
dlyRtns.plot(x=symbols[0], y=symbols[1], marker='o', linewidth=0)
#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
# Calculate correlation coefficient
print "Correlation", dlyRtns.corr(method='pearson')
plt.show()
</code></pre>
<p>and here is the output:</p>
<pre><code>C:\Python27\python.exe C:/Users/Us/Desktop/untitled3/scatterPlot.py
Y Beta nan
Y Alpha nan
Correlation EUR=X JPY=X
EUR=X 1.000000 0.228223
JPY=X 0.228223 1.000000
Process finished with exit code 0
</code></pre>
<p>Any ideas why I getting Nan here? I am at a loss, any help is much appreciated.</p>
| 0 | 2016-08-26T00:03:14Z | 39,165,218 | <p>I cannot retrieve the data either.</p>
<p>My best guess: there are <code>nan</code>s or duplicate points in the retrieved data.</p>
| 0 | 2016-08-26T11:25:21Z | [
"python",
"pandas",
"numpy",
"linear-regression"
] |
alpha & beta (for linear regression) calculations output nan? | 39,156,506 | <p>I am new to Python and have been attempting to calculate the linear regression/Beta/Alpha for two securities, however my code is outputting Nan for both Beta & Alpha, and therefore I am unable to draw the regression line. </p>
<p>here is the code in question:</p>
<pre><code>#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
</code></pre>
<p>and here is the full script:</p>
<pre><code>from pandas.io.data import DataReader
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
#inputs
symbols = ['EUR=X', 'JPY=X']
startDate = datetime(2011,1,1)
endDate = datetime(2016,12,31)
#get data from yahoo
instrument = DataReader(symbols, 'yahoo', startDate, endDate)
#isolate column
close = instrument['Adj Close']
#calculate daily returns
def compute_daily_returns(df):
daily_returns = (df / df.shift(1)) - 1
return daily_returns
dlyRtns = compute_daily_returns(close)
xPlt = dlyRtns[symbols[0]]
yPlt = dlyRtns[symbols[1]]
#draw "scatter plot" - using "o" workaround
dlyRtns.plot(x=symbols[0], y=symbols[1], marker='o', linewidth=0)
#calculate linear regression
beta_yPlt, alpha_yPlt = np.polyfit(xPlt, yPlt, 1) # fit poly degree 1
print "Y Beta", beta_yPlt
print "Y Alpha", alpha_yPlt
plt.plot(xPlt, beta_yPlt * xPlt + alpha_yPlt, '-', color='red')
# Calculate correlation coefficient
print "Correlation", dlyRtns.corr(method='pearson')
plt.show()
</code></pre>
<p>and here is the output:</p>
<pre><code>C:\Python27\python.exe C:/Users/Us/Desktop/untitled3/scatterPlot.py
Y Beta nan
Y Alpha nan
Correlation EUR=X JPY=X
EUR=X 1.000000 0.228223
JPY=X 0.228223 1.000000
Process finished with exit code 0
</code></pre>
<p>Any ideas why I getting Nan here? I am at a loss, any help is much appreciated.</p>
| 0 | 2016-08-26T00:03:14Z | 39,166,741 | <pre><code>def compute_daily_returns(df):
daily_returns = (df / df.shift(1)) - 1
daily_returns.ix[0, :] = 0
return daily_returns
</code></pre>
<p>adding <code>daily_returns.ix[0, :] = 0</code> fixed the issue, thanks to Nickil Maveli</p>
| 0 | 2016-08-26T12:48:10Z | [
"python",
"pandas",
"numpy",
"linear-regression"
] |
interactive conditional histogram bucket slicing data visualization | 39,156,545 | <p>I have a df that looks like: </p>
<pre><code>df.head()
Out[1]:
A B C
city0 40 12 73
city1 65 56 10
city2 77 58 71
city3 89 53 49
city4 33 98 90
</code></pre>
<p>An example df can be created by the following code:</p>
<pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,3)), columns=list('ABC'))
indx = ['city'+str(x) for x in range(0,1000000)]
df.index = indx
</code></pre>
<p>What I want to do is:</p>
<p>a) determine appropriate histogram bucket lengths for column A and assign each city to a bucket for column A</p>
<p>b) determine appropriate histogram bucket lengths for column B and assign each city to a bucket for column B</p>
<p>Maybe the resulting df looks like (or is there a better built in way in pandas?)</p>
<pre><code> df.head()
Out[1]:
A B C Abkt Bbkt
city0 40 12 73 2 1
city1 65 56 10 4 3
city2 77 58 71 4 3
city3 89 53 49 5 3
city4 33 98 90 2 5
</code></pre>
<p>Where Abkt and Bbkt are histogram bucket identifiers:</p>
<pre><code>1-20 = 1
21-40 = 2
41-60 = 3
61-80 = 4
81-100 = 5
</code></pre>
<p>Ultimately, I want to better understand the behavior of each city with respect to columns A, B and C and be able to answer questions like:</p>
<p>a) What does the distribution of Column A (or B) look like - i.e. what buckets are most/least populated.</p>
<p>b) Conditional on a particular slice/bucket of Column A, what does the distribution of Column B look like - i.e. what buckets are most/least populated.</p>
<p>c) Conditional on a particular slice/bucket of Column A and B, what does the behavior of C look like.</p>
<p>Ideally, I want to be able to visualize the data (heat maps, region identifiers etc). I'm a relative pandas/python newbie and don't know what is possible to develop. </p>
<p>If the SO community can kindly provide code examples of how I can do what I want (or a better approach if there are better pandas/numpy/scipy built in methods) I would be grateful. </p>
<p>As well, any pointers to resources that can help me better summarize/slice/dice my data and be able to visualize at intermediate steps as I proceed with my analysis. </p>
<p><strong>UPDATE:</strong></p>
<p>I am following some of the suggestions in the comments. </p>
<p>I tried:</p>
<p>1) <code>df.hist()</code></p>
<pre><code>ValueError: The first argument of bincount must be non-negative
</code></pre>
<p>2) <code>df[['A']].hist(bins=10,range=(0,10))</code></p>
<pre><code>array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000A2350615C0>]], dtype=object)
</code></pre>
<p>Isn't <code>#2</code> suppose to show a plot? instead of producing an object that is not rendered? I am using <code>jupyter notebook</code>. </p>
<p>Is there something I need to turn-on / enable in <code>Jupyter Notebook</code> to render the histogram objects? </p>
<p><strong>UPDATE2:</strong></p>
<p>I solved the rendering problem by: <a href="http://stackoverflow.com/questions/10511024/in-ipython-notebook-pandas-is-not-displying-the-graph-i-try-to-plot">in Ipython notebook, Pandas is not displying the graph I try to plot.</a></p>
<p><strong>UPDATE3:</strong></p>
<p>As per suggestions from the comments, I started looking through <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="nofollow">pandas visualization</a>, <a href="http://bokeh.pydata.org/en/latest/" rel="nofollow">bokeh</a> and <a href="http://stanford.edu/~mwaskom/software/seaborn/" rel="nofollow">seaborn</a>. However, I'm not sure how I can create linkages between plots. </p>
<p>Lets say I have 10 variables. I want to explore them but since 10 is a large number to explore at once, lets say I want to explore 5 at any given time (r,s,t,u,v). </p>
<p>If I want an interactive hexbin with marginal distributions plot to examine the relationship between r & s, how do I also see the distribution of t, u and v given interactive region selections/slices of r&s (polygons).</p>
<p>I found hexbin with marginal distribution plot here <a href="http://stanford.edu/~mwaskom/software/seaborn/examples/hexbin_marginals.html" rel="nofollow">hexbin plot</a>: </p>
<p><strong>But:</strong></p>
<p>1) How to make this interactive (allow selections of polygons)</p>
<p>2) How to link region selections of r & s to other plots, for example 3 histogram plots of t,u, and v (or any other type of plot).</p>
<p>This way, I can navigate through the data more rigorously and explore the relationships in depth.</p>
| 12 | 2016-08-26T00:08:52Z | 39,218,998 | <p>As a newbie with insufficient rep, I can't comment, so I'm putting this here as an "answer," though it shouldn't be treated as one; these are just some incomplete suggestions in the same vein as the comments. </p>
<p>Along with the others, I like <code>seaborn</code> though I'm not sure those plots are interactive in the way you are seeking. While I haven't used <code>bokeh</code>, my understanding is that it provides more in the way of interactivity, but regardless of the package, as you move beyond 3 and 4 variables, you can only cram so much into one (family of) charts. </p>
<p>As for in your table directly, the aforementioned <code>df.hist()</code> (by <a href="http://stackoverflow.com/users/5285918/lanery">lanery</a>) is a good start. Once you have those bins, you can then play with the <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">immensely powerful</a> <code>df.groupby()</code> function. I've been using pandas for two years now, and that function STILL blows my mind. While not interactive, it will definitely help you slice and dice your data as you see fit.</p>
| 3 | 2016-08-30T04:55:13Z | [
"python",
"pandas",
"data-visualization",
"seaborn",
"bokeh"
] |
interactive conditional histogram bucket slicing data visualization | 39,156,545 | <p>I have a df that looks like: </p>
<pre><code>df.head()
Out[1]:
A B C
city0 40 12 73
city1 65 56 10
city2 77 58 71
city3 89 53 49
city4 33 98 90
</code></pre>
<p>An example df can be created by the following code:</p>
<pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,3)), columns=list('ABC'))
indx = ['city'+str(x) for x in range(0,1000000)]
df.index = indx
</code></pre>
<p>What I want to do is:</p>
<p>a) determine appropriate histogram bucket lengths for column A and assign each city to a bucket for column A</p>
<p>b) determine appropriate histogram bucket lengths for column B and assign each city to a bucket for column B</p>
<p>Maybe the resulting df looks like (or is there a better built in way in pandas?)</p>
<pre><code> df.head()
Out[1]:
A B C Abkt Bbkt
city0 40 12 73 2 1
city1 65 56 10 4 3
city2 77 58 71 4 3
city3 89 53 49 5 3
city4 33 98 90 2 5
</code></pre>
<p>Where Abkt and Bbkt are histogram bucket identifiers:</p>
<pre><code>1-20 = 1
21-40 = 2
41-60 = 3
61-80 = 4
81-100 = 5
</code></pre>
<p>Ultimately, I want to better understand the behavior of each city with respect to columns A, B and C and be able to answer questions like:</p>
<p>a) What does the distribution of Column A (or B) look like - i.e. what buckets are most/least populated.</p>
<p>b) Conditional on a particular slice/bucket of Column A, what does the distribution of Column B look like - i.e. what buckets are most/least populated.</p>
<p>c) Conditional on a particular slice/bucket of Column A and B, what does the behavior of C look like.</p>
<p>Ideally, I want to be able to visualize the data (heat maps, region identifiers etc). I'm a relative pandas/python newbie and don't know what is possible to develop. </p>
<p>If the SO community can kindly provide code examples of how I can do what I want (or a better approach if there are better pandas/numpy/scipy built in methods) I would be grateful. </p>
<p>As well, any pointers to resources that can help me better summarize/slice/dice my data and be able to visualize at intermediate steps as I proceed with my analysis. </p>
<p><strong>UPDATE:</strong></p>
<p>I am following some of the suggestions in the comments. </p>
<p>I tried:</p>
<p>1) <code>df.hist()</code></p>
<pre><code>ValueError: The first argument of bincount must be non-negative
</code></pre>
<p>2) <code>df[['A']].hist(bins=10,range=(0,10))</code></p>
<pre><code>array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000A2350615C0>]], dtype=object)
</code></pre>
<p>Isn't <code>#2</code> suppose to show a plot? instead of producing an object that is not rendered? I am using <code>jupyter notebook</code>. </p>
<p>Is there something I need to turn-on / enable in <code>Jupyter Notebook</code> to render the histogram objects? </p>
<p><strong>UPDATE2:</strong></p>
<p>I solved the rendering problem by: <a href="http://stackoverflow.com/questions/10511024/in-ipython-notebook-pandas-is-not-displying-the-graph-i-try-to-plot">in Ipython notebook, Pandas is not displying the graph I try to plot.</a></p>
<p><strong>UPDATE3:</strong></p>
<p>As per suggestions from the comments, I started looking through <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="nofollow">pandas visualization</a>, <a href="http://bokeh.pydata.org/en/latest/" rel="nofollow">bokeh</a> and <a href="http://stanford.edu/~mwaskom/software/seaborn/" rel="nofollow">seaborn</a>. However, I'm not sure how I can create linkages between plots. </p>
<p>Lets say I have 10 variables. I want to explore them but since 10 is a large number to explore at once, lets say I want to explore 5 at any given time (r,s,t,u,v). </p>
<p>If I want an interactive hexbin with marginal distributions plot to examine the relationship between r & s, how do I also see the distribution of t, u and v given interactive region selections/slices of r&s (polygons).</p>
<p>I found hexbin with marginal distribution plot here <a href="http://stanford.edu/~mwaskom/software/seaborn/examples/hexbin_marginals.html" rel="nofollow">hexbin plot</a>: </p>
<p><strong>But:</strong></p>
<p>1) How to make this interactive (allow selections of polygons)</p>
<p>2) How to link region selections of r & s to other plots, for example 3 histogram plots of t,u, and v (or any other type of plot).</p>
<p>This way, I can navigate through the data more rigorously and explore the relationships in depth.</p>
| 12 | 2016-08-26T00:08:52Z | 39,363,715 | <p>In order to get the interaction effect you're looking for, you must bin all the columns you care about, together.</p>
<p>The cleanest way I can think of doing this is to <code>stack</code> into a single <code>series</code> then use <code>pd.cut</code></p>
<p>Considering your sample <code>df</code></p>
<p><a href="http://i.stack.imgur.com/8IjPO.png" rel="nofollow"><img src="http://i.stack.imgur.com/8IjPO.png" alt="enter image description here"></a></p>
<pre><code>df_ = pd.cut(df[['A', 'B']].stack(), 5, labels=list(range(5))).unstack()
df_.columns = df_.columns.to_series() + 'bkt'
pd.concat([df, df_], axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/dlCEm.png" rel="nofollow"><img src="http://i.stack.imgur.com/dlCEm.png" alt="enter image description here"></a></p>
<hr>
<p>Let's build a better example and look at a visualization using <code>seaborn</code></p>
<pre><code>df = pd.DataFrame(dict(A=(np.random.randn(10000) * 100 + 20).astype(int),
B=(np.random.randn(10000) * 100 - 20).astype(int)))
import seaborn as sns
df.index = df.index.to_series().astype(str).radd('city')
df_ = pd.cut(df[['A', 'B']].stack(), 30, labels=list(range(30))).unstack()
df_.columns = df_.columns.to_series() + 'bkt'
sns.jointplot(x=df_.Abkt, y=df_.Bbkt, kind="scatter", color="k")
</code></pre>
<p><a href="http://i.stack.imgur.com/Q2XnW.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q2XnW.png" alt="enter image description here"></a></p>
<hr>
<p>Or how about some data with some correlation</p>
<pre><code>mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 100000)
df = pd.DataFrame(data, columns=["A", "B"])
df.index = df.index.to_series().astype(str).radd('city')
df_ = pd.cut(df[['A', 'B']].stack(), 30, labels=list(range(30))).unstack()
df_.columns = df_.columns.to_series() + 'bkt'
sns.jointplot(x=df_.Abkt, y=df_.Bbkt, kind="scatter", color="k")
</code></pre>
<p><a href="http://i.stack.imgur.com/YMo9M.png" rel="nofollow"><img src="http://i.stack.imgur.com/YMo9M.png" alt="enter image description here"></a></p>
<hr>
<h3>Interactive <code>bokeh</code></h3>
<p>Without getting too complicated</p>
<pre><code>from bokeh.io import show, output_notebook, output_file
from bokeh.plotting import figure
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, Select, CustomJS
output_notebook()
# generate random data
flips = np.random.choice((1, -1), (5, 5))
flips = np.tril(flips, -1) + np.triu(flips, 1) + np.eye(flips.shape[0])
half = np.ones((5, 5)) / 2
cov = (half + np.diag(np.diag(half))) * flips
mean = np.zeros(5)
data = np.random.multivariate_normal(mean, cov, 10000)
df = pd.DataFrame(data, columns=list('ABCDE'))
df.index = df.index.to_series().astype(str).radd('city')
# Stack and cut to get dependent relationships
b = 20
df_ = pd.cut(df.stack(), b, labels=list(range(b))).unstack()
# assign default columns x and y. These will be the columns I set bokeh to read
df_[['x', 'y']] = df_.loc[:, ['A', 'B']]
source = ColumnDataSource(data=df_)
tools = 'box_select,pan,box_zoom,wheel_zoom,reset,resize,save'
p = figure(plot_width=600, plot_height=300)
p.circle('x', 'y', source=source, fill_color='olive', line_color='black', alpha=.5)
def gcb(like, n):
code = """
var data = source.get('data');
var f = cb_obj.get('value');
data['{0}{1}'] = data[f];
source.trigger('change');
"""
return CustomJS(args=dict(source=source), code=code.format(like, n))
xcb = CustomJS(
args=dict(source=source),
code="""
var data = source.get('data');
var colm = cb_obj.get('value');
data['x'] = data[colm];
source.trigger('change');
"""
)
ycb = CustomJS(
args=dict(source=source),
code="""
var data = source.get('data');
var colm = cb_obj.get('value');
data['y'] = data[colm];
source.trigger('change');
"""
)
options = list('ABCDE')
x_select = Select(options=options, callback=xcb, value='A')
y_select = Select(options=options, callback=ycb, value='B')
show(column(p, row(x_select, y_select)))
</code></pre>
<p><a href="http://i.stack.imgur.com/RTu1E.png" rel="nofollow"><img src="http://i.stack.imgur.com/RTu1E.png" alt="enter image description here"></a></p>
| 7 | 2016-09-07T07:26:47Z | [
"python",
"pandas",
"data-visualization",
"seaborn",
"bokeh"
] |
interactive conditional histogram bucket slicing data visualization | 39,156,545 | <p>I have a df that looks like: </p>
<pre><code>df.head()
Out[1]:
A B C
city0 40 12 73
city1 65 56 10
city2 77 58 71
city3 89 53 49
city4 33 98 90
</code></pre>
<p>An example df can be created by the following code:</p>
<pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,3)), columns=list('ABC'))
indx = ['city'+str(x) for x in range(0,1000000)]
df.index = indx
</code></pre>
<p>What I want to do is:</p>
<p>a) determine appropriate histogram bucket lengths for column A and assign each city to a bucket for column A</p>
<p>b) determine appropriate histogram bucket lengths for column B and assign each city to a bucket for column B</p>
<p>Maybe the resulting df looks like (or is there a better built in way in pandas?)</p>
<pre><code> df.head()
Out[1]:
A B C Abkt Bbkt
city0 40 12 73 2 1
city1 65 56 10 4 3
city2 77 58 71 4 3
city3 89 53 49 5 3
city4 33 98 90 2 5
</code></pre>
<p>Where Abkt and Bbkt are histogram bucket identifiers:</p>
<pre><code>1-20 = 1
21-40 = 2
41-60 = 3
61-80 = 4
81-100 = 5
</code></pre>
<p>Ultimately, I want to better understand the behavior of each city with respect to columns A, B and C and be able to answer questions like:</p>
<p>a) What does the distribution of Column A (or B) look like - i.e. what buckets are most/least populated.</p>
<p>b) Conditional on a particular slice/bucket of Column A, what does the distribution of Column B look like - i.e. what buckets are most/least populated.</p>
<p>c) Conditional on a particular slice/bucket of Column A and B, what does the behavior of C look like.</p>
<p>Ideally, I want to be able to visualize the data (heat maps, region identifiers etc). I'm a relative pandas/python newbie and don't know what is possible to develop. </p>
<p>If the SO community can kindly provide code examples of how I can do what I want (or a better approach if there are better pandas/numpy/scipy built in methods) I would be grateful. </p>
<p>As well, any pointers to resources that can help me better summarize/slice/dice my data and be able to visualize at intermediate steps as I proceed with my analysis. </p>
<p><strong>UPDATE:</strong></p>
<p>I am following some of the suggestions in the comments. </p>
<p>I tried:</p>
<p>1) <code>df.hist()</code></p>
<pre><code>ValueError: The first argument of bincount must be non-negative
</code></pre>
<p>2) <code>df[['A']].hist(bins=10,range=(0,10))</code></p>
<pre><code>array([[<matplotlib.axes._subplots.AxesSubplot object at 0x000000A2350615C0>]], dtype=object)
</code></pre>
<p>Isn't <code>#2</code> suppose to show a plot? instead of producing an object that is not rendered? I am using <code>jupyter notebook</code>. </p>
<p>Is there something I need to turn-on / enable in <code>Jupyter Notebook</code> to render the histogram objects? </p>
<p><strong>UPDATE2:</strong></p>
<p>I solved the rendering problem by: <a href="http://stackoverflow.com/questions/10511024/in-ipython-notebook-pandas-is-not-displying-the-graph-i-try-to-plot">in Ipython notebook, Pandas is not displying the graph I try to plot.</a></p>
<p><strong>UPDATE3:</strong></p>
<p>As per suggestions from the comments, I started looking through <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="nofollow">pandas visualization</a>, <a href="http://bokeh.pydata.org/en/latest/" rel="nofollow">bokeh</a> and <a href="http://stanford.edu/~mwaskom/software/seaborn/" rel="nofollow">seaborn</a>. However, I'm not sure how I can create linkages between plots. </p>
<p>Lets say I have 10 variables. I want to explore them but since 10 is a large number to explore at once, lets say I want to explore 5 at any given time (r,s,t,u,v). </p>
<p>If I want an interactive hexbin with marginal distributions plot to examine the relationship between r & s, how do I also see the distribution of t, u and v given interactive region selections/slices of r&s (polygons).</p>
<p>I found hexbin with marginal distribution plot here <a href="http://stanford.edu/~mwaskom/software/seaborn/examples/hexbin_marginals.html" rel="nofollow">hexbin plot</a>: </p>
<p><strong>But:</strong></p>
<p>1) How to make this interactive (allow selections of polygons)</p>
<p>2) How to link region selections of r & s to other plots, for example 3 histogram plots of t,u, and v (or any other type of plot).</p>
<p>This way, I can navigate through the data more rigorously and explore the relationships in depth.</p>
| 12 | 2016-08-26T00:08:52Z | 39,432,898 | <p>Here is a new solution using <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/charts.html" rel="nofollow"><code>bokeh</code></a> and <a href="http://holoviews.org/#installation" rel="nofollow"><code>HoloViews</code></a>. It should respond a little more to the interactive part.</p>
<p>I try to remember that <em>simple is beautiful</em> when it comes to dataviz. </p>
<p>I used <a href="https://pypi.python.org/pypi/fake-factory" rel="nofollow"><code>faker</code></a> library in order to generate random city names to make the following graphs more realistic.</p>
<p>I will let all my codes here even if the most important part is the choice of the libraries.</p>
<pre><code>import pandas as pd
import numpy as np
from faker import Faker
def generate_random_dataset(city_number,
list_identifier,
labels,
bins,
city_location='en_US'):
fake = Faker(locale=city_location)
df = pd.DataFrame(data=np.random.uniform(0, 100, len(list_identifier)]),
index=[fake.city() for _ in range(city_number)],
columns=list_identifier)
for name in list_identifier:
df[name + 'bkt'] = pd.Series(pd.cut(df[name], bins, labels=labels))
return df
list_identifier=list('ABC')
labels = ['Low', 'Medium', 'Average', 'Good', 'Great']
bins = np.array([-1, 20, 40, 60, 80, 101])
df = generate_random_dataset(30, list_identifier, labels, bins)
df.head()
</code></pre>
<p>will output:
<a href="http://i.stack.imgur.com/cnnxh.png" rel="nofollow"><img src="http://i.stack.imgur.com/cnnxh.png" alt="df"></a></p>
<p>Sometimes, when your dataset is small, exposing a simple chart with colors could be enough. </p>
<pre><code>from bokeh.charts import Bar, output_file, show
from bokeh.layouts import column
bar = []
for name in list_identifier:
bar.append(Bar(df, label='index', values=name, stack=name+'bkt',
title="percentage of " + name, legend='top_left', plot_width=1024))
output_file('cities.html')
show(column(bar))
</code></pre>
<p>Will create a new html page (cities) containing the graphs. Note that all the graphs generated with <code>bokeh</code> are interactive.</p>
<p><a href="http://i.stack.imgur.com/ZrIBp.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZrIBp.png" alt="graphA"></a></p>
<p><a href="http://i.stack.imgur.com/TEK9x.png" rel="nofollow"><img src="http://i.stack.imgur.com/TEK9x.png" alt="graphB"></a></p>
<p><code>bokeh</code> can't initially plot hexbin. However, <code>HoloViews</code> can. Thus, it allows to draw interactive plots whitin <code>ipython notebook</code>.</p>
<p>The syntax is quite straightforward, you just need a Matrix with two columns and call the hist method:</p>
<pre><code>import holoviews as hv
hv.notebook_extension('bokeh')
df = generate_random_dataset(1000, list_identifier, list(range(5)), 5)
points = hv.Points(np.column_stack((df.A, df.B)))
points.hist(num_bins=5, dimension=['x', 'y'])
</code></pre>
<p><a href="http://i.stack.imgur.com/2khIc.png" rel="nofollow"><img src="http://i.stack.imgur.com/2khIc.png" alt="repartition of A and B"></a></p>
<p>To compare with @piRSquared solution, I stole a bit of code (thank you btw :) to show the data with some correlation:</p>
<pre><code>mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 100000)
df = pd.DataFrame(data, columns=["A", "B"])
df.index = df.index.to_series().astype(str).radd('city')
df_ = pd.cut(df[['A', 'B']].stack(), 30, labels=list(range(30))).unstack()
df_.columns = df_.columns.to_series() + 'bkt'
points = hv.Points(np.column_stack((df_.Abkt, df_.Bbkt)))
points.hist(num_bins=5, dimension=['x', 'y'])
</code></pre>
<p><a href="http://i.stack.imgur.com/ZZxM5.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZZxM5.png" alt="mean covariance"></a></p>
<p>Please consider visit <code>HoloViews</code> <a href="http://holoviews.org/Tutorials/Bokeh_Backend.html" rel="nofollow">tutorial</a>.</p>
| 4 | 2016-09-11T04:37:31Z | [
"python",
"pandas",
"data-visualization",
"seaborn",
"bokeh"
] |
why use transpose than directly set array? | 39,156,724 | <p>In a python code I see two lines below (initially, labels was of type (15093, that is, 1-d array)(from py-faster-rcnn)</p>
<pre><code>labels = labels.reshape((1, height, width, A)).transpose(0, 3, 1, 2)
labels = labels.reshape((1, 1, A * height, width))
</code></pre>
<p>Is there any reason the author use transpose than directly set</p>
<pre><code>labels = labels.reshape((1, A, height, width))
labels = labels.reshape((1, 1, A * height, width))
</code></pre>
<p>Or even,</p>
<pre><code>labels = labels.reshape((1, 1, A * height, width))
</code></pre>
<p>? (I guess it's related to the data order in the initial labels array)</p>
| 0 | 2016-08-26T00:36:20Z | 39,156,968 | <p>The answer is quite easy : yes there is a reason, given the same <code>labels</code> array, the results of your 3 methods simply aren't the same. </p>
<p>Lets check that with an example:</p>
<pre><code>import numpy as np
height, width, A = [2,3,4]
arr=np.random.rand(1*height*width*A)
print("Method 1")
labels1=np.copy(arr)
labels1 = labels1.reshape((1, height, width, A)).transpose(0, 3, 1, 2)
labels1 = labels1.reshape((1, 1, A * height, width))
print(labels1)
print("Method 2")
labels2=np.copy(arr)
labels2 = labels2.reshape((1, A, height, width))
labels2 = labels2.reshape((1, 1, A * height, width))
print(labels2)
print("Method 3")
labels3=np.copy(arr)
labels3 = labels3.reshape((1, 1, A * height, width))
print(labels3)
</code></pre>
<p>Which gives:</p>
<pre><code>>>> Method 1
>>> [[[[ 0.97360395 0.40639034 0.92936386]
>>> [ 0.01687321 0.94744919 0.39188023]
>>> [ 0.34210967 0.36342341 0.6938464 ]
>>> [ 0.60065943 0.00356836 0.91785409]
>>> [ 0.57095964 0.61036102 0.17318427]
>>> [ 0.38002045 0.08596757 0.29407445]
>>> [ 0.95899964 0.13046103 0.36286533]
>>> [ 0.86970793 0.11659624 0.82073826]]]]
>>> Method 2
>>> [[[[ 0.97360395 0.34210967 0.57095964]
>>> [ 0.95899964 0.40639034 0.36342341]
>>> [ 0.61036102 0.13046103 0.92936386]
>>> [ 0.6938464 0.17318427 0.36286533]
>>> [ 0.01687321 0.60065943 0.38002045]
>>> [ 0.86970793 0.94744919 0.00356836]
>>> [ 0.08596757 0.11659624 0.39188023]
>>> [ 0.91785409 0.29407445 0.82073826]]]]
>>> Method 3
>>> [[[[ 0.97360395 0.34210967 0.57095964]
>>> [ 0.95899964 0.40639034 0.36342341]
>>> [ 0.61036102 0.13046103 0.92936386]
>>> [ 0.6938464 0.17318427 0.36286533]
>>> [ 0.01687321 0.60065943 0.38002045]
>>> [ 0.86970793 0.94744919 0.00356836]
>>> [ 0.08596757 0.11659624 0.39188023]
>>> [ 0.91785409 0.29407445 0.82073826]]]]
</code></pre>
<p>So method 1 is different from 2 and 3, while 2 and 3 are the same.</p>
| 1 | 2016-08-26T01:11:24Z | [
"python",
"numpy"
] |
While loop not repeating once information in entered | 39,156,728 | <p>Making a program which has a list of the different star signs, then asks the user to enter what star sign they are and then for the program to check that is contained in the list before moving on. </p>
<p>The problem is that it does check that it is in the list, but it does not repeat.</p>
<pre><code>play = True
while play:
print("Welcome to my Pseudo_Sammy program, please enter your name, star sign and then your question by typing it in and pressing the enter key, and I will give you the answer to your question")
name = input("What do they call you? ")
starsigns = ("leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces", "aries", "taurus", "gemini", "cancer")
starsign = str(input("What star do you come from? ")).lower()
while True:
try:
if starsign in starsigns:
break
else:
raise
except:
print("Please enter a valid star sign")
question = input("What bothers you dear? ")
</code></pre>
| 1 | 2016-08-26T00:36:42Z | 39,189,676 | <p>if you want to repeat an <code>input</code> until you get a valid answer and THEN ask the next question, you need to place the 1st input inside <code>while</code> loop and the 2nd input outside the loop, like this:</p>
<pre><code>starsigns = ("leo", "virgo", ...)
starsign = None
while starsign not in starsigns:
if starsign:
print("Please enter a valid star sign: {}.".format(", ".join(starsigns)))
starsign = input("What start do you come from? ").lower().strip()
question = input("What bothers you dear? ")
</code></pre>
| 0 | 2016-08-28T09:12:59Z | [
"python"
] |
Python: Replace Slashes | 39,156,795 | <p>I got some unicode with percent signs I want to change to backslashes. I know you need an additional backslash as an escape sequence, but when I did this <code>replace()</code> gave me two backslashes:</p>
<pre><code>>>> s ="%20%u200F%u05D1%u05E8%u05DB%u05EA%u200F%20%u200F%u05D4%u05E8%u05D9%u05D7%u200F%20%u200F%u05D5%u05D1%u05E8%u05DB%u05EA%u200F%20%u200F%u05D4%u05D5%u05D3%u05D0%u05D4"
>>> s.replace("%","\")
File "<stdin>", line 1
s.replace("%","\")
SyntaxError: EOL while scanning string literal
>>> s.replace("%","\\")
'\\20\\u200F\\u05D1\\u05E8\\u05DB\\u05EA\\u200F\\20\\u200F\\u05D4\\u05E8\\u05D9\\u05D7\\u200F\\20\\u200F\\u05D5\\u05D1\\u05E8\\u05DB\\u05EA\\u200F\\20\\u200F\\u05D4\\u05D5\\u05D3\\u05D0\\u05D4'
</code></pre>
<p>The <code>'r'</code> qualifyer isn't working either. Any ideas?</p>
| 0 | 2016-08-26T00:46:05Z | 39,156,826 | <p>That is just python invoking the string <code>__repr__</code> because you're in the REPL and the <code>__repr__</code> escapes the <code>\</code> character giving you the output you see.</p>
<p>Using <code>print</code>, which will use the strings <code>__str__</code>, will get you the right output:</p>
<pre><code>print(s.replace("%","\\"))
\20\u200F\u05D1\u05E8\u05DB\u05EA\u200F\20\u200F\u05D4\u05E8\u05D9\u05D7\u200F\20\u200F\u05D5\u05D1\u05E8\u05DB\u05EA\u200F\20\u200F\u05D4\u05D5\u05D3\u05D0\u05D4
</code></pre>
<p>That is, the replacement happens just fine.</p>
| 3 | 2016-08-26T00:49:27Z | [
"python",
"string"
] |
Python: Replace Slashes | 39,156,795 | <p>I got some unicode with percent signs I want to change to backslashes. I know you need an additional backslash as an escape sequence, but when I did this <code>replace()</code> gave me two backslashes:</p>
<pre><code>>>> s ="%20%u200F%u05D1%u05E8%u05DB%u05EA%u200F%20%u200F%u05D4%u05E8%u05D9%u05D7%u200F%20%u200F%u05D5%u05D1%u05E8%u05DB%u05EA%u200F%20%u200F%u05D4%u05D5%u05D3%u05D0%u05D4"
>>> s.replace("%","\")
File "<stdin>", line 1
s.replace("%","\")
SyntaxError: EOL while scanning string literal
>>> s.replace("%","\\")
'\\20\\u200F\\u05D1\\u05E8\\u05DB\\u05EA\\u200F\\20\\u200F\\u05D4\\u05E8\\u05D9\\u05D7\\u200F\\20\\u200F\\u05D5\\u05D1\\u05E8\\u05DB\\u05EA\\u200F\\20\\u200F\\u05D4\\u05D5\\u05D3\\u05D0\\u05D4'
</code></pre>
<p>The <code>'r'</code> qualifyer isn't working either. Any ideas?</p>
| 0 | 2016-08-26T00:46:05Z | 39,156,863 | <p>Just like you have to type two backslashes to enter one, Python, when displaying a quoted string, displays two to indicate it is a literal backslash. <code>'\\x41'</code> is four characters, <code>'\x41'</code> is one (equivalent to <code>'A'</code>). It's a debugging feature so you can see unprintable characters, for example, and tell the difference.</p>
<pre><code>>>> a = '\xa0\\xa0'
>>> a
'\xa0\\xa0'
>>> print(a)
 \xa0
</code></pre>
| 0 | 2016-08-26T00:55:20Z | [
"python",
"string"
] |
PyGame draw a square inside a square | 39,156,809 | <p>I'm writing a grid-based game where instances of the Character class can move around using their move(direction) method.</p>
<pre><code>class Character(object): #can move around and do cool stuff
def __init__(self, name, HP, internal_column, internal_row):
self.name = name
self.HP = HP
self.internal_column = internal_column
self.internal_row = internal_row
moves_left = 15
direction = "N"
def move(self, direction): #how characters move around
if self.moves_left == 0:
print("No more moves left")
return
elif direction == "N":
self.internal_row -= 1
self.direction = "N"
elif direction == "W":
self.internal_column -= 1
self.direction = "W"
elif direction == "E":
self.internal_column += 1
self.direction = "E"
elif direction == "S":
self.internal_row += 1
self.direction = "S"
self.moves_left = self.moves_left - 1
</code></pre>
<p>The direction variable keeps track of where the character is pointing. I draw the graphics using PyGame: </p>
<pre><code>for row in range(MAPSIZE): # Drawing grid
for column in range(MAPSIZE):
for i in range(0, len(Map.Grid[column][row])):
Color = WHITE
if len(Map.can_move) > 0: # Creating colored area around character showing his move range
if (math.sqrt((Map.can_move[0].internal_column - column)**2 + (Map.can_move[0].internal_row - row)**2)) <= Map.can_move[0].moves_left:
Color = MOVECOLOR
if len(Map.Grid[column][row]) > 1:
Color = RED
if Map.Grid[column][row][i].name == "Tree":
Color = GREEN
if str(Map.Grid[column][row][i].__class__.__name__) == "Character":
Color = BROWN
pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN,
(TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN,
TILEWIDTH,
TILEHEIGHT])
</code></pre>
<p>Here is the full code, where the constants and the Map class are defined: </p>
<pre><code>import random
import pygame
import math
pygame.init()
Clock = pygame.time.Clock()
Screen = pygame.display.set_mode([650, 650])
DONE = False
MAPSIZE = 25 #how many tiles
TILEWIDTH = 20 #pixel size of tile
TILEHEIGHT = 20
TILEMARGIN = 4
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BROWN = (123, 123, 0)
MOVECOLOR = (150, 250, 150)
KeyLookup = {
pygame.K_LEFT: "W",
pygame.K_RIGHT: "E",
pygame.K_DOWN: "S",
pygame.K_UP: "N"
}
class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff.
def __init__(self, name, internal_column, internal_row):
self.name = name
self.internal_column = internal_column
self.internal_row = internal_row
class Character(object): #can move around and do cool stuff
def __init__(self, name, HP, internal_column, internal_row):
self.name = name
self.HP = HP
self.internal_column = internal_column
self.internal_row = internal_row
moves_left = 15
direction = "N"
def move(self, direction): #how characters move around
if self.collision_check(direction) == True:
print("Collision")
return
if self.moves_left == 0:
print("No more moves left")
return
elif direction == "N":
self.internal_row -= 1
self.direction = "N"
elif direction == "W":
self.internal_column -= 1
self.direction = "W"
elif direction == "E":
self.internal_column += 1
self.direction = "E"
elif direction == "S":
self.internal_row += 1
self.direction = "S"
self.moves_left = self.moves_left - 1
def collision_check(self, direction):
if direction == "N":
if self.internal_row == 0:
return True
if len(Map.Grid[self.internal_column][(self.internal_row)-1]) > 1:
return True
elif direction == "W":
if self.internal_column == 0:
return True
if len(Map.Grid[self.internal_column-1][(self.internal_row)]) > 1:
return True
elif direction == "E":
if self.internal_column == MAPSIZE-1:
return True
if len(Map.Grid[self.internal_column+1][(self.internal_row)]) > 1:
return True
elif direction == "S":
if self.internal_row == MAPSIZE-1:
return True
if len(Map.Grid[self.internal_column][(self.internal_row)+1]) > 1:
return True
return False
def attack(self, direction):
if self.collision_check(direction) == True:
print("attacked")
class Goblin(Character):
def __init__(self):
Character.__init__(self, "Goblin", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))
def random_move(self):
i = random.randint(0,3)
if i == 0:
self.move("N")
elif i == 1:
self.move("S")
elif i == 2:
self.move("W")
elif i == 3:
self.move("E")
self.moves_left = 10
class Archer(Character):
def __init__(self):
Character.__init__(self, "Archer", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))
class Warrior(Character):
def __init__(self):
Character.__init__(self, "Warrior", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))
class Scout(Character):
def __init__(self):
Character.__init__(self, "Scout", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))
class Rogue(Character):
def __init__(self):
Character.__init__(self, "Rogue", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))
class Wizard(Character):
def __init__(self):
Character.__init__(self, "Wizard", random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))
class Map(object): #The main class; where the action happens
global MAPSIZE
wild_characters = []
can_move = []
no_moves = []
Grid = []
for row in range(MAPSIZE): # Creating grid
Grid.append([])
for column in range(MAPSIZE):
Grid[row].append([])
for row in range(MAPSIZE): #Filling grid with grass
for column in range(MAPSIZE):
TempTile = MapTile("Grass", column, row)
Grid[column][row].append(TempTile)
for row in range(MAPSIZE): #Putting some rocks near the top
for column in range(MAPSIZE):
TempTile = MapTile("Rock", column, row)
if row == 1:
Grid[column][row].append(TempTile)
for i in range(10): #Trees in random places
random_row = random.randint(0, MAPSIZE - 1)
random_column = random.randint(0, MAPSIZE - 1)
TempTile = MapTile("Tree", random_column, random_row)
Grid[random_column][random_row].append(TempTile)
def generate_hero(self): #Generate a character and place it randomly
random_row = random.randint(0, MAPSIZE - 1)
random_column = random.randint(0, MAPSIZE - 1)
id_number = len(Map.can_move) + random.randint(0,100)
temp_hero = Character(str("Hero " + str(id_number)), 10, random_column, random_row)
self.Grid[random_column][random_row].append(temp_hero)
self.can_move.append(temp_hero)
def generate_goblin(self): #Generate a character and place it randomly
random_row = random.randint(0, MAPSIZE - 1)
random_column = random.randint(0, MAPSIZE - 1)
temp_goblin = Goblin()
self.Grid[random_column][random_row].append(temp_goblin)
Map.wild_characters.append(temp_goblin)
def update(self): #Important function
for column in range(MAPSIZE): #These nested loops go through entire grid
for row in range(MAPSIZE): #They check if any objects internal coordinates
for i in range(len(Map.Grid[column][row])): #disagree with its place on the grid and update it accordingly
if Map.Grid[column][row][i].internal_column != column:
TempChar = Map.Grid[column][row][i]
Map.Grid[column][row].remove(Map.Grid[column][row][i])
Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar)
elif Map.Grid[column][row][i].internal_row != row:
TempChar = Map.Grid[column][row][i]
Map.Grid[column][row].remove(Map.Grid[column][row][i])
Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar)
temparr = Map.no_moves[:]
for characterobject in temparr: #This moves any characters with moves to the can move list
if len(temparr) > 0:
if characterobject.moves_left > 0:
print("character moved from no moves to moves")
Map.can_move.append(characterobject)
Map.no_moves.remove(characterobject)
arr = Map.can_move[:] # copy
for item in arr:
if item.moves_left == 0:
print("character moved from moves to no moves")
Map.can_move.remove(item)
Map.no_moves.append(item)
Map = Map()
Map.generate_hero()
while not DONE: #Main pygame loop
for event in pygame.event.get(): #catching events
if event.type == pygame.QUIT:
DONE = True
elif event.type == pygame.MOUSEBUTTONDOWN:
Pos = pygame.mouse.get_pos()
column = Pos[0] // (TILEWIDTH + TILEMARGIN) #Translating the position of the mouse into rows and columns
row = Pos[1] // (TILEHEIGHT + TILEMARGIN)
print(str(row) + ", " + str(column))
for i in range(len(Map.Grid[column][row])):
print(str(Map.Grid[column][row][i].name)) #print stuff that inhabits that square
elif event.type == pygame.KEYDOWN:
wild_char_arr = Map.wild_characters[:]
for wildcharacter in wild_char_arr:
if wildcharacter.name == "Goblin":
print("Goblin moved")
wildcharacter.random_move()
if event.key == 97: # Keypress: a
print("New turn.")
temparr = Map.no_moves[:]
for item in temparr:
if item.moves_left == 0:
item.moves_left = 15
elif event.key == 115: # Keypress: s
print("Generated hero.")
Map.generate_hero()
elif event.key == 100: # Keypress: d
Map.generate_goblin()
print("Generated goblin.")
elif event.key == 102: # Keypress: f
Map.can_move[0].attack("N")
elif len(Map.can_move) > 0:
Map.can_move[0].move(KeyLookup[event.key])
else:
print("invalid")
Map.update()
Screen.fill(BLACK)
for row in range(MAPSIZE): # Drawing grid
for column in range(MAPSIZE):
for i in range(0, len(Map.Grid[column][row])):
Color = WHITE
if len(Map.can_move) > 0: # Creating colored area around character showing his move range
if (math.sqrt((Map.can_move[0].internal_column - column)**2 + (Map.can_move[0].internal_row - row)**2)) <= Map.can_move[0].moves_left:
Color = MOVECOLOR
if len(Map.Grid[column][row]) > 1:
Color = RED
if Map.Grid[column][row][i].name == "Tree":
Color = GREEN
if str(Map.Grid[column][row][i].__class__.__name__) == "Character":
Color = BROWN
pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN,
(TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN,
TILEWIDTH,
TILEHEIGHT])
Clock.tick(60)
pygame.display.flip()
pygame.quit()
</code></pre>
<p>The problem I'm having is displaying the character's direction graphically. All I want to do is draw a small, red square inside the character's grid tile on the side they are facing. For example, if they are facing north, the small red square would be on the top side of the character's grid square.</p>
<p>How can I do this?</p>
| 0 | 2016-08-26T00:47:46Z | 39,416,708 | <p>Ended up doing it like this:</p>
<pre><code> if str(Map.Grid[column][row][i].__class__.__name__) == "Character": #Drawing the little red square showing character direction
if Map.Grid[column][row][i].direction == "N":
Color = RED
pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8,
(TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN,
TILEWIDTH/4,
TILEHEIGHT/4])
if str(Map.Grid[column][row][i].__class__.__name__) == "Character": #Drawing the little red square showing character directio
if Map.Grid[column][row][i].direction == "S":
Color = RED
pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8,
(TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 1 ,
TILEWIDTH/4,
TILEHEIGHT/4])
if str(Map.Grid[column][row][i].__class__.__name__) == "Character": #Drawing the little red square showing character directio
if Map.Grid[column][row][i].direction == "E":
Color = RED
pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 15,
(TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8,
TILEWIDTH/4,
TILEHEIGHT/4])
if str(Map.Grid[column][row][i].__class__.__name__) == "Character": #Drawing the little red square showing character directio
if Map.Grid[column][row][i].direction == "W":
Color = RED
pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN
,
(TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8 ,
TILEWIDTH/4,
TILEHEIGHT/4])
</code></pre>
| 0 | 2016-09-09T17:17:51Z | [
"python",
"python-3.x",
"oop",
"pygame",
"game-engine"
] |
Sage doesn't find cycle_type() attribute on a permutation element | 39,156,851 | <p>Im trying to work on some group theory with Sage.</p>
<p>In particular I was trying to learn the basic commands related to symmetric groups.</p>
<p>My input is</p>
<pre><code>G=SymmetricGroup(6)
sigma=G('(1,3,5)(4,6)')
</code></pre>
<p>then I use <code>sigma.cycle_type()</code> and according to the documentation, I should get as output a list with the lengths of the cycles that form sigma in decreasing order, in this case I should get something like [3,2]. Instead I get an "AttributeError" :</p>
<pre><code>---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-94f73ca80516> in <module>()
----> 1 sigma.cycle_type()
/home/sage/sage-7.2/src/sage/structure/element.pyx in sage.structure.element.Element.__getattr__ (/home/sage/sage-7.2/src/build/cythonized/sage/structure/element.c:4649)()
411 dummy_error_message.name = name
412 raise dummy_attribute_error
--> 413 return getattr_from_other_class(self, P._abstract_element_class, name)
414
415 def __dir__(self):
/home/sage/sage-7.2/src/sage/structure/misc.pyx in sage.structure.misc.getattr_from_other_class (/home/sage/sage-7.2/src/build/cythonized/sage/structure/misc.c:1870)()
257 dummy_error_message.cls = type(self)
258 dummy_error_message.name = name
--> 259 raise dummy_attribute_error
260 if isinstance(attribute, methodwrapper):
261 dummy_error_message.cls = type(self)
AttributeError: 'sage.groups.perm_gps.permgroup_element.SymmetricGroupElement' object has no attribute 'cycle_type'
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 2016-08-26T00:53:48Z | 39,156,979 | <p>Possibly you just need a newer version of Sage? In a late beta of 7.3, I get:</p>
<pre><code>sage: sigma.cycle_type()
[3, 2, 1]
</code></pre>
<p>I should point out that the version in SageMathCloud appears to be too old for this currently, if that's your platform...</p>
| 0 | 2016-08-26T01:13:46Z | [
"python",
"sage"
] |
Having no performance problems with threading and Python's Global Interpreter Lock. Scalability? | 39,156,864 | <p>I have been having no problems with performance with Python's Global Interpreter Lock. I've had to make a few things thread-safe - despite common advice, the GIL does NOT automatically guarantee thread-safety - but I've got a program commonly running upwards of 10 threads, where all of them can be active at any time, including together. It is a somewhat complex asynchronous messaging system.</p>
<p>I understand multiprocessing and am even using Celery in this program, but the solution would have to be very convoluted to work through multiprocessing for this problem set.</p>
<p>I'm running 2.7 and using recursive locks despite their performance penalties.</p>
<p>My question is this: will I run into scaling problems with the GIL? I have seen no performance problems with it so far. Measuring this is...problematic. Is there a number of threads or something similar that you hit and it just starts choking? Does GIL performance differ significantly from executing multi-threaded code on a single-core CPU?</p>
<p>Thanks!</p>
| 0 | 2016-08-26T00:55:41Z | 39,157,969 | <p>The GIL is a complex topic and the exact behavior in your case is hard to explain without your code. So I can not tell you if you will run into troubles in future. I can just advise to bring you project to a recent version of Python 3 if posdible. There have been many improvents made to the GIL in Python 3.</p>
<p>The is nothing like a magic number of threads at which Python will break. The general rule is just: The more threads, the more problem. Most complicated is going from one to two.</p>
<p>The GIL is released in some situations, especially when C code is executed or I/O is done. This allows code to run in parallel. With the advanced featured of modern CPUs is wouldn't be wise to limit your code to just one CPU.</p>
| 0 | 2016-08-26T03:44:20Z | [
"python",
"multithreading",
"globalinterpreterlock"
] |
Integrating twisted into existing pyqt GUI application | 39,156,867 | <p>I am trying to add twisted to my already existing app. According to <a href="https://pypi.python.org/pypi/qt4reactor/1.6" rel="nofollow">this</a> and other sources, I should import qt4reactor. When I try:</p>
<pre><code>app = QApplication(sys.argv)
from twisted.application import reactors
reactors.installReactor('pyqt4')
</code></pre>
<p>(I also tried:)</p>
<pre><code>from twisted.internet import qt4reactor
</code></pre>
<p>I get twisted.application.reactors.NoSuchReactor: 'pyqt4'. I can download and install qt4reactor directly, but then I can't install it after instantiating QApplication?</p>
<p>Also, since I am adding on twisted, the documentation states that I should use reactor.runReturn() instead of reactor.run(). </p>
<pre><code>from twisted.internet import reactor, protocol
reactor.listenTCP(8001, tcpFactory())
reactor.runReturn()
</code></pre>
<p>When I try this, I get AttributeError: 'SelectReactor' object has no attribute 'runReturn'. Is this because I am unable to install qt4reactor after instantiating QApplication? </p>
| 0 | 2016-08-26T00:56:05Z | 39,157,264 | <p>Now qt4reactor is separate from Twisted and located <a href="https://github.com/ghtdak/qtreactor" rel="nofollow">here</a></p>
<p>So you need to install it first, then try:</p>
<pre><code>from twisted.application import reactors
reactors.installReactor('pyqt4')
</code></pre>
<p>or</p>
<pre><code>from qtreactor import pyqt4reactor
pyqt4reactor.install()
</code></pre>
| 0 | 2016-08-26T01:56:20Z | [
"python",
"pyqt4",
"twisted"
] |
My function doesn't return a value, can't figure out why | 39,156,882 | <p>The function is supposed to open a csv file that has data in this format</p>
<p>"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"</p>
<p>When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe there is an issue with the rest of the code as if I replaced 'return poll data' with 'print(poll_data)' there is the desired output. </p>
<p>I am a noob at this and don't have a full grasp of return. </p>
<pre><code>def read_data_file(filename):
file = open(filename, 'r')
poll_data = []
for data in file:
data = data.strip('\n')
data = data.split(',')
poll_data.append(data)
return poll_data
read_data_file('florida-gop.csv')
</code></pre>
| 3 | 2016-08-26T00:58:18Z | 39,156,909 | <p>you changed that last line in the function from <code>print</code> to <code>return</code>. So, when you call your function as such:</p>
<p><code>read_data_file('florida-gop.csv')</code></p>
<p>it <em>does</em> return that data. It's sitting right there! But then your script ends, doing nothing with that data. so, instead, do something like this:</p>
<pre><code>data = read_data_file('florida-gop.csv')
print(data)
</code></pre>
<p>a short addendum - political data is an excellent way to learn data manipulation with Python and, if so inclined, Python itself. I'd recommend the O'Reilly books on data & Python - but that's outside the scope of this question.</p>
| 2 | 2016-08-26T01:02:10Z | [
"python",
"function",
"return"
] |
My function doesn't return a value, can't figure out why | 39,156,882 | <p>The function is supposed to open a csv file that has data in this format</p>
<p>"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"</p>
<p>When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe there is an issue with the rest of the code as if I replaced 'return poll data' with 'print(poll_data)' there is the desired output. </p>
<p>I am a noob at this and don't have a full grasp of return. </p>
<pre><code>def read_data_file(filename):
file = open(filename, 'r')
poll_data = []
for data in file:
data = data.strip('\n')
data = data.split(',')
poll_data.append(data)
return poll_data
read_data_file('florida-gop.csv')
</code></pre>
| 3 | 2016-08-26T00:58:18Z | 39,156,915 | <p>You have two options here:</p>
<ol>
<li>Replacing <code>return poll_data</code> with <code>print poll_data</code>.</li>
<li>Instead of <code>read_data_file('florida-gop.csv')</code>, you can do <code>print read_data_file('florida-gop.csv')</code>.</li>
</ol>
<p>Why do you need to do this? </p>
<p><strong><code>Print</code> vs <code>Return</code></strong></p>
<p><code>print</code> actually shows you the result, while <code>return</code> only gives the result to the computer, if that makes sense. The computer knows it, but it doesn't print it, which is why the second solution works - the computer has the data you want, and it is able to print it if you command it too. However, in your case, the first solution is probably easier. </p>
<p>Hope this helps!</p>
| 1 | 2016-08-26T01:02:59Z | [
"python",
"function",
"return"
] |
My function doesn't return a value, can't figure out why | 39,156,882 | <p>The function is supposed to open a csv file that has data in this format</p>
<p>"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"</p>
<p>When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe there is an issue with the rest of the code as if I replaced 'return poll data' with 'print(poll_data)' there is the desired output. </p>
<p>I am a noob at this and don't have a full grasp of return. </p>
<pre><code>def read_data_file(filename):
file = open(filename, 'r')
poll_data = []
for data in file:
data = data.strip('\n')
data = data.split(',')
poll_data.append(data)
return poll_data
read_data_file('florida-gop.csv')
</code></pre>
| 3 | 2016-08-26T00:58:18Z | 39,156,924 | <p>Continuing from the above(or not so above anymore xD) answer...</p>
<p>the full code would now be,</p>
<pre><code>def read_data_file(filename):
file = open(filename, 'r')
poll_data = []
for data in file:
data = data.strip('\n')
data = data.split(',')
poll_data.append(data)
return poll_data
print(read_data_file('florida-gop.csv')) # Before you forgot to print it.
</code></pre>
<p>or exactly like the above answer,</p>
<pre><code>def read_data_file(filename):
file = open(filename, 'r')
poll_data = []
for data in file:
data = data.strip('\n')
data = data.split(',')
poll_data.append(data)
return poll_data
data = read_data_file('florida-gop.csv')
print(data)
</code></pre>
| 0 | 2016-08-26T01:04:30Z | [
"python",
"function",
"return"
] |
How do you query MongoDB by pairs of keys using pymongo | 39,156,920 | <p>I have a list of pairs of things, of the form e.g. <code>[['A', 'B'], ['C', 'D']]</code>. I want to query <code>MongoDB</code> for records in a specific collection which have properties matching both of these things.</p>
<p>For example, here is what I would want to get back:</p>
<pre><code>[{'_id': ObjectId('...'),
'first_property': 'A',
'second_property': 'B'
},
{'_id': ObjectId('...'),
'first_property': 'C',
'second_property': 'D'
}]
</code></pre>
<p>How do I query <em>simultaneous</em> properties using <code>pymongo</code>?</p>
| 0 | 2016-08-26T01:03:34Z | 39,157,867 | <p>I got pretty good performance out of the following pattern:</p>
<pre><code>client.find({'$or': [{'property_a': value_a, 'property_b': value_b} for value_a, value_b in some_list_of_two_element_tuples]}
</code></pre>
<p>This creates a very long <a href="https://docs.mongodb.com/manual/reference/operator/query/or/" rel="nofollow"><code>$or</code></a> statement out of our requested tuples.</p>
| 1 | 2016-08-26T03:28:09Z | [
"python",
"mongodb",
"pymongo"
] |
My url template not work | 39,156,940 | <p>I have a problem with my template tag url. The redirect not work when i click on button.</p>
<p>Django version => 1.9
Python version => 2.7</p>
<p>In my urls.py(main) i have:</p>
<pre><code>from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from memoryposts.views import home, profile, preregistration
urlpatterns = [
url(r'^$', home, name="home"),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', admin.site.urls),
url(r'^memory/', include("memoryposts.urls", namespace="memory")),
url(r'^avatar/', include('avatar.urls')),
url(r'^accounts/', include('registration.backends.hmac.urls')),
url(r'^preregistration/', preregistration, name="preregistration"),
url(r'^profile/', profile, name="profile"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<p>In my urls.py(apps) i have:</p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from .views import (
memory_list,
memory_create,
memory_detail,
memory_update,
memory_delete,
)
urlpatterns = [
url(r'^$', memory_list, name='list'),
url(r'^create/$', memory_create, name='create'),
url(r'^(?P<slug>[-\w]+)/$', memory_detail, name='detail'),
url(r'^(?P<slug>[-\w]+)/edit/$', memory_update, name='update'),
url(r'^(?P<slug>[-\w]+)/delete/$', memory_delete, name='delete'),
]
</code></pre>
<p>In my views.py(apps) i have:</p>
<pre><code>from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import PostForm
def home(request):
return render(request, "base.html")
def profile(request):
return render(request, "profile.html")
def preregistration(request):
return render(request, "preregistration.html")
def memory_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Succès !")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "memory_create.html", context)
def memory_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
context = {
"title":instance.title,
"instance":instance,
}
return render(request, "memory_detail.html", context)
def memory_list(request):
queryset = Post.objects.all()
context = {
"object_list": queryset,
}
return render(request, "memory_list.html", context)
def memory_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Mis à jour !")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title":instance.title,
"instance":instance,
"form": form,
}
return render(request, "memory_create.html", context)
def memory_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Supprimer !")
return redirect("posts:list")
</code></pre>
<p>In my template html i have:</p>
<pre><code><button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' %}"> Update</a></button>
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:delete' %}"> Delete</a></button>
</code></pre>
<p>The redirect not work with this template tag.
can you help me please :) ?</p>
| 0 | 2016-08-26T01:06:19Z | 39,157,643 | <p>From doc here <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-dispatcher" rel="nofollow">URL dispatcher</a></p>
<pre><code><button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' %}"> Update</a></button>
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:delete' %}"> Delete</a></button>
</code></pre>
<p>You should put what you 'slug' in your button, like this (if slug is 200)</p>
<pre><code><button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' 200 %}"> Update</a></button>
</code></pre>
<p>Usually will look like this:</p>
<pre><code>{% for slug in slug_list %}
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' slug %}"> Update</a></button>
{% endfor %}
</code></pre>
| 0 | 2016-08-26T02:55:08Z | [
"python",
"django",
"templates",
"django-templates"
] |
Extract specific section from LaTeX file with python | 39,157,084 | <p>I have a set of LaTeX files. I would like to extract the "abstract" section for each one: </p>
<pre class="lang-tex prettyprint-override"><code>\begin{abstract}
.....
\end{abstract}
</code></pre>
<p>I have tried the suggestion here: <a href="http://stackoverflow.com/questions/30752351/how-to-parse-latex-file">How to Parse LaTex file</a></p>
<p>And tried :</p>
<pre><code>A = re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data)
</code></pre>
<p>Where data contains the text from the LaTeX file. But <code>A</code> is just an empty list. Any help would be greatly appreciated!</p>
| 3 | 2016-08-26T01:30:22Z | 39,157,185 | <p><code>.*</code> does not match newlines unless the re.S flag is given:</p>
<pre><code>re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data, re.S)
</code></pre>
<h3>Example</h3>
<p>Consider this test file:</p>
<pre class="lang-tex prettyprint-override"><code>\documentclass{report}
\usepackage[margin=1in]{geometry}
\usepackage{longtable}
\begin{document}
Title maybe
\begin{abstract}
Good stuff
\end{abstract}
Other stuff
\end{document}
</code></pre>
<p>This gets the abstract:</p>
<pre><code>>>> import re
>>> data = open('a.tex').read()
>>> re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data, re.S)
['\nGood stuff\n']
</code></pre>
<h3>Documentation</h3>
<p>From the <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="nofollow"><code>re</code> module's webpage</a>:</p>
<blockquote>
<p>re.S<br> re.DOTALL<br></p>
<p>Make the '.' special character match any character at
all, including a newline; without this flag, '.' will match anything
except a newline.</p>
</blockquote>
| 3 | 2016-08-26T01:45:00Z | [
"python",
"regex",
"latex"
] |
Extract specific section from LaTeX file with python | 39,157,084 | <p>I have a set of LaTeX files. I would like to extract the "abstract" section for each one: </p>
<pre class="lang-tex prettyprint-override"><code>\begin{abstract}
.....
\end{abstract}
</code></pre>
<p>I have tried the suggestion here: <a href="http://stackoverflow.com/questions/30752351/how-to-parse-latex-file">How to Parse LaTex file</a></p>
<p>And tried :</p>
<pre><code>A = re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data)
</code></pre>
<p>Where data contains the text from the LaTeX file. But <code>A</code> is just an empty list. Any help would be greatly appreciated!</p>
| 3 | 2016-08-26T01:30:22Z | 39,157,209 | <p>The <code>.</code> does not match newline character. However, you can pass a flag to ask it to include newlines.</p>
<p>Example:</p>
<pre><code>import re
s = r"""\begin{abstract}
this is a test of the
linebreak capture.
\end{abstract}"""
pattern = r'\\begin\{abstract\}(.*?)\\end\{abstract\}'
re.findall(pattern, s, re.DOTALL)
#output:
['\nthis is a test of the\nlinebreak capture.\n']
</code></pre>
| 1 | 2016-08-26T01:48:49Z | [
"python",
"regex",
"latex"
] |
Pandas Multiindex selecting list of columns from given level | 39,157,142 | <p>If I make a multi-indexed column dataframe like this:</p>
<pre><code>iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
first bar baz foo qux \
second one two one two one two one
A -0.119687 -0.518318 0.113920 -1.028505 1.106375 -1.020139 -0.039300
B 0.123480 -2.091120 0.464597 -0.147211 -0.489895 -1.090659 -0.592679
C -1.174376 0.282011 -0.197658 -0.030751 0.117374 1.591109 0.796908
first
second two
A -0.938209
B -0.851483
C 0.442621
</code></pre>
<p>and I want to select columns from only the first set of columns using a list, </p>
<p><code>select_cols=['bar', 'qux']</code></p>
<p>such that the result would be:</p>
<pre><code>first bar qux
second one two one two
A -0.119687 -0.518318 -0.039300 -0.938209
B 0.123480 -2.091120 -0.592679 -0.851483
C -1.174376 0.282011 0.796908 0.442621
</code></pre>
<p>How would I go about doing that? (Thanks ahead of time)</p>
| 1 | 2016-08-26T01:38:36Z | 39,157,232 | <p>You can use <code>loc</code> to select columns:</p>
<pre><code>df.loc[:, ["bar", "qux"]]
# first bar qux
# second one two one two
# A 1.245525 -1.469999 -0.399174 0.017094
# B -0.242284 0.835131 -0.400847 -0.344612
# C -1.067006 -1.880113 -0.516234 -0.410847
</code></pre>
| 3 | 2016-08-26T01:52:16Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
Pandas Multiindex selecting list of columns from given level | 39,157,142 | <p>If I make a multi-indexed column dataframe like this:</p>
<pre><code>iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]
index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
first bar baz foo qux \
second one two one two one two one
A -0.119687 -0.518318 0.113920 -1.028505 1.106375 -1.020139 -0.039300
B 0.123480 -2.091120 0.464597 -0.147211 -0.489895 -1.090659 -0.592679
C -1.174376 0.282011 -0.197658 -0.030751 0.117374 1.591109 0.796908
first
second two
A -0.938209
B -0.851483
C 0.442621
</code></pre>
<p>and I want to select columns from only the first set of columns using a list, </p>
<p><code>select_cols=['bar', 'qux']</code></p>
<p>such that the result would be:</p>
<pre><code>first bar qux
second one two one two
A -0.119687 -0.518318 -0.039300 -0.938209
B 0.123480 -2.091120 -0.592679 -0.851483
C -1.174376 0.282011 0.796908 0.442621
</code></pre>
<p>How would I go about doing that? (Thanks ahead of time)</p>
| 1 | 2016-08-26T01:38:36Z | 39,157,293 | <p>Simple column selection works as well:</p>
<pre><code>df[['bar', 'qux']]
# first bar qux
# second one two one two
# A 0.651522 0.480115 -2.924574 0.616674
# B -0.395988 0.001643 0.358048 0.022727
# C -0.317829 1.400970 -0.773148 1.549135
</code></pre>
| 4 | 2016-08-26T02:01:35Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
python how to implement a list into a tree? | 39,157,193 | <p>I have a list of data indicates what direction is going next like:</p>
<pre><code>[[0,1,0,0,1],[0,0,1],[0,0],[0,1,1,1,0]]
</code></pre>
<p>I want to implement this data into a tree structure like:
<a href="http://i.stack.imgur.com/NA80y.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NA80y.jpg" alt="enter image description here"></a></p>
<p>The number inside the node is how many people walked on this direction.</p>
<p>I have a Tree class that I write myself like this:</p>
<pre><code>class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = 0
def insert(self,num):
self.data = self.data + 1
if num == 0:
if self.left == None:
self.left = Tree()
return self.left
elif num == 1:
if self.right == None:
self.right = Tree()
return self.right
</code></pre>
<p>How can I do this? I tried to make it in a recursive way but turns out it's not saving under <code>root</code> but <code>build_tree</code> which is a variable that I tried to make as the recursive pointer.</p>
<pre><code>root = Tree()
for route in data:
build_tree = root
for i in range (0,len(route)):
num = route[i]
build_tree = build_tree.insert(num)
</code></pre>
<p>Thanks!</p>
<p>Edit: This code actually works just like Blender said in comment. I think I had something wrong when I implemented it to a more complex code.</p>
<p>Also thanks John La Rooy for the suggestion and Kevin K. for the example!</p>
| 2 | 2016-08-26T01:46:31Z | 39,157,266 | <p>Try making a separate class for the node like so</p>
<pre><code>class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
</code></pre>
<p>Then in your <code>Tree</code> class initialize <code>self.root</code> and declare your functions with recursion within <code>Tree</code></p>
<p>Edit: <a href="https://github.com/kkirchhoff01/MiscScripts/blob/master/binary_tree.py" rel="nofollow">Here</a> is an example.</p>
| 2 | 2016-08-26T01:56:56Z | [
"python",
"data-structures"
] |
Python Sockets Select is hanging - Doing other tasks while waiting for socket data? | 39,157,229 | <p>I am rather a noob here, but trying to setup a script where I can poll a socket, and when no socket data has been sent, a loop continues to run and do other things. I have been playing with several examples I found using select(), but no matter how I organize the code, it seems to stop on or near the server.recv() line and wait for a response. I want to skip out of this if no data has been sent by a client, or if no client connection exists.</p>
<p>Note that this application does not require the server script to send any reply data, if it makes any difference.</p>
<p>The actual application is to run a loop and animate some LEDs (which needs root access to the I/O on a Raspberry Pi). I am going to send this script data from another separate script via sockets that will pass in control parameters for the animations. This way the external script does not require root access.</p>
<p>So far the sending and receiving of data works great, I just can't get loop to keep spinning in the absence of incoming data. It is my understanding that this is what select() was intended to allow, but the examples I've found don't seem to be working that way.</p>
<p>I have attempted adding server.setblocking(0) a few different places to no avail. (If I understand correctly a non-blocking instance should allow the code to skip over the recv() if no data has been sent, but I may be off on this).</p>
<p>I have based my code on an example here:
<a href="http://ilab.cs.byu.edu/python/select/echoserver.html" rel="nofollow">http://ilab.cs.byu.edu/python/select/echoserver.html</a></p>
<p>Here is the server side script followed by the client side script.</p>
<p><strong>Server Code: sockselectserver.py</strong></p>
<pre><code>#!/usr/bin/env python
import select
import socket
import sys
server = socket.socket()
host = socket.gethostname()
port = 20568
size = 1024
server.bind((host,port))
server.listen(5)
input = [server,sys.stdin]
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == server:
# handle the server socket
client, address = server.accept()
input.append(client)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = 0
else:
# handle all other sockets
data = s.recv(size)
if data:
s.send(data)
else:
s.close()
input.remove(s)
print "looping"
server.close()
</code></pre>
<p><strong>Client Code: skclient.py</strong></p>
<pre><code>#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 20568 # Reserve a port for your service.
s.connect((host, port))
data = "123:120:230:51:210:120:55:12:35:24"
s.send(data)
print s.recv(1024)
s.close # Close the socket when done
</code></pre>
<p>What I would like to achieve by this example is to see "looping" repeated forever, then when the client script sends data, see that data print, then see the "looping" resume printing over and over. That would tell me it's doing what is intended I can take it from there.</p>
<p>Interesting enough, when I test this as is, whenever I run the client, I see "looping" printed 3 times on the screen, then no more. I don't fully understand what is happening inside the select, but I'd assume it would only print 1 time.</p>
<p>I tried moving the inputready.. select.select() around to different places but found it appears to need to be called each time, otherwise the server stops responding (for example if it is called once prior to the endless while: loop).</p>
<p>I'm hoping this can be made simple enough that it can be taught to other hacker types in a maker class, so I'm hopeful I don't need to get too crazy with multi-threading and more elaborate solutions. As a last resort I'm considering logging all my parameters to mySQL from the external script then using this script to query them back out of tables. I've got experience there and would probably work, but it seems this socket angle would be a more direct solution.</p>
<p>Any help very much appreciated.</p>
| 0 | 2016-08-26T01:52:05Z | 39,166,461 | <p>Great news. This was an easy fix, wanted to post in case anyone else needed it. The suggestion from acw1668 above got me going.</p>
<p>Simply added a timeout of "0" to the select.select() like this:</p>
<pre><code>inputready,outputready,exceptready = select.select(input,[],[],0)
</code></pre>
<p>This is in the python docs but somehow I missed it. Link here: <a href="https://docs.python.org/2/library/select.html" rel="nofollow">https://docs.python.org/2/library/select.html</a></p>
<p>Per the docs:
"The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks."</p>
<p>I tested the same code as above, adding a delay of 5 seconds using time.sleep(5) right after the print "looping" line. With the delay, if no data or client is present the code just loops every 5 seconds and prints "looping" to the screen. If I kick off the client script during the 5 second delay, it pauses and the message is processed the next time the 5 second delay ends. Occasionally it doesn't respond the very next loop, but rather the loop following. I assume this is because the first time through the server.accept is running and the next time through the s.recv() is running which actually exchanges the data.</p>
| 0 | 2016-08-26T12:32:32Z | [
"python",
"multithreading",
"sockets",
"select"
] |
Python - scapy sniff() filter with port range | 39,157,299 | <p>I want to sniff all packets in a range of ports with the scapy module.</p>
<p>This is how it works for one port..</p>
<pre><code>from scapy.all import *
packets = sniff(filter='udp and port 14000')
</code></pre>
<p>But rather than only port 14000, i want to sniff the range from 14000 up to 64000.</p>
<p>The following code does not work..</p>
<pre><code>from scapy.all import *
packets = sniff(filter='udp and port 14000 to 64000')
</code></pre>
<p>What should the filter string look like if I want to do this?</p>
| 1 | 2016-08-26T02:02:07Z | 39,171,891 | <p><em>Scapy</em> uses the <a href="http://biot.com/capstats/bpf.html" rel="nofollow"><em>BPF</em> syntax</a> for specifying the filter:</p>
<pre><code>packets = sniff(filter='udp and portrange 14000-64000')
</code></pre>
<p>Note that the range is inclusive and that no spaces are allowed around the <code>'-'</code> sign.</p>
| 2 | 2016-08-26T17:38:38Z | [
"python",
"range",
"port",
"scapy",
"packet-sniffers"
] |
tweepy IndexError: list index out of range | 39,157,338 | <p>This could be a super stupid mistake, but I just cant see what's wrong.</p>
<pre><code>class listener(tweepy.streaming.StreamListener):
def on_data(self, data):
tweet = data.split(',"text":"')[1].split('","source')[0]
screen_name = data.split(',"screen_name":"')[1].split('","location":')[0]
print tweet
print data
return True
def on_error(self, status):
print status
def main():
twitterStream = tweepy.Stream(auth, listener())
twitterStream.userstream()
if __name__ == "__main__":
main()
</code></pre>
<p>and the error is:</p>
<pre><code>Traceback (most recent call last):
File "C:\Rex\702_EH\new 1.py", line 35, in <module>
main()
File "C:\Rex\702_EH\new 1.py", line 32, in main
twitterStream.userstream()
File "build\bdist.win32\egg\tweepy\streaming.py", line 394, in userstream
File "build\bdist.win32\egg\tweepy\streaming.py", line 361, in _start
File "build\bdist.win32\egg\tweepy\streaming.py", line 294, in _run
IndexError: list index out of range
</code></pre>
<p>can anyone help me with this please?</p>
| 0 | 2016-08-26T02:07:45Z | 39,160,294 | <p>The tweets you get are in a JSON format, you should take advantage of that rather than trying to parse them as plain text. The attributes will be a lot easier to extract, and your code will also be much more readable.</p>
<pre><code>class listener(tweepy.streaming.StreamListener):
def on_data(self, data):
decoded = json.loads(data)
tweet = decoded['text']
screen_name = decoded['user']['screen_name']
print tweet
print data
return True
def on_error(self, status):
print status
def main():
twitterStream = tweepy.Stream(auth, listener())
twitterStream.userstream()
if __name__ == "__main__":
main()
</code></pre>
<p>As a sidenote, I suggest you switch to Python3, dealing with Unicode in Python2 can be quite nightmarish.</p>
| 0 | 2016-08-26T07:06:47Z | [
"python",
"split",
"tweepy"
] |
tweepy IndexError: list index out of range | 39,157,338 | <p>This could be a super stupid mistake, but I just cant see what's wrong.</p>
<pre><code>class listener(tweepy.streaming.StreamListener):
def on_data(self, data):
tweet = data.split(',"text":"')[1].split('","source')[0]
screen_name = data.split(',"screen_name":"')[1].split('","location":')[0]
print tweet
print data
return True
def on_error(self, status):
print status
def main():
twitterStream = tweepy.Stream(auth, listener())
twitterStream.userstream()
if __name__ == "__main__":
main()
</code></pre>
<p>and the error is:</p>
<pre><code>Traceback (most recent call last):
File "C:\Rex\702_EH\new 1.py", line 35, in <module>
main()
File "C:\Rex\702_EH\new 1.py", line 32, in main
twitterStream.userstream()
File "build\bdist.win32\egg\tweepy\streaming.py", line 394, in userstream
File "build\bdist.win32\egg\tweepy\streaming.py", line 361, in _start
File "build\bdist.win32\egg\tweepy\streaming.py", line 294, in _run
IndexError: list index out of range
</code></pre>
<p>can anyone help me with this please?</p>
| 0 | 2016-08-26T02:07:45Z | 39,164,448 | <p>The output of Tweepy response is JSON. Because JSON is an standard in intra-communicating between applications you should follow this standard by using json lib in python. So you need to load Tweepy response like this:</p>
<pre><code>tweet = json.loads(data)
username = tweet[user][screeen_name]
language = tweet[user][lang]
......
.....
</code></pre>
| 0 | 2016-08-26T10:46:09Z | [
"python",
"split",
"tweepy"
] |
python return empty list from function | 39,157,353 | <p>I am sorry to ask such a basic question but I am trying to learn python and don't understand why this does not work. When I run this program on a directory it prints and empty list []. I don't understand why. Can someone help? Python 3.</p>
<pre><code>import sys, os,
def getfiles(currdir):
myfiles = []
for file in os.listdir(currdir):
for file in os.listdir(currdir):
path = os.path.join(currdir,file)
if not os.path.isdir(path):
myfiles.append(path)
else:
getfiles(path)
return(myfiles)
if __name__ == '__main__':
filedirectory = []
filedirectory = getfiles(sys.argv[1])
print(filedirectory)
</code></pre>
<p>This returns []</p>
<p>Thank you for the help</p>
| -1 | 2016-08-26T02:10:26Z | 39,163,420 | <p>If i understand you want to get all of the file names in a specific directory. here is my code to do that :</p>
<pre><code>Import os
AllFiles = []
AllFiles = os.listdir("your Directory")
</code></pre>
<p>listdir() return all files name in the specific directory.</p>
| 0 | 2016-08-26T09:50:36Z | [
"python"
] |
python return empty list from function | 39,157,353 | <p>I am sorry to ask such a basic question but I am trying to learn python and don't understand why this does not work. When I run this program on a directory it prints and empty list []. I don't understand why. Can someone help? Python 3.</p>
<pre><code>import sys, os,
def getfiles(currdir):
myfiles = []
for file in os.listdir(currdir):
for file in os.listdir(currdir):
path = os.path.join(currdir,file)
if not os.path.isdir(path):
myfiles.append(path)
else:
getfiles(path)
return(myfiles)
if __name__ == '__main__':
filedirectory = []
filedirectory = getfiles(sys.argv[1])
print(filedirectory)
</code></pre>
<p>This returns []</p>
<p>Thank you for the help</p>
| -1 | 2016-08-26T02:10:26Z | 39,163,700 | <p>Well, at least one case where your function will return an empty list, is if the topmost directory contains only directories. Here's your code (after removing the redundant loop):</p>
<pre><code>for file in os.listdir(currdir):
path = os.path.join(currdir,file)
if not os.path.isdir(path):
myfiles.append(path)
else:
getfiles(path)
</code></pre>
<p>If the <code>else</code> part is reached, then you recursively call <code>getfiles(path)</code>. Unfortunately, you don't do anything with the result, and actually just throw it away. You probably meant the last line to be something like </p>
<pre><code> myfiles.extend(getfiles(path))
</code></pre>
<hr>
<p>Additionally, you might want to check out <a href="https://docs.python.org/2/library/os.html" rel="nofollow"><code>os.walk</code></a>, as it does what it seems you're trying to do here.</p>
| 0 | 2016-08-26T10:06:09Z | [
"python"
] |
how can I move a list index value forward 'x' amount of times using python? | 39,157,398 | <p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p>
<p>For example if the code was</p>
<pre><code>abc
</code></pre>
<p>Then the solution would be</p>
<pre><code>cde
</code></pre>
<p>So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following)</p>
<pre><code>alphabet = ["a","b","c"...."z"]
</code></pre>
<p>I am trying to write code similar to this</p>
<pre><code>def scramble(sentence):
alphabet = ["a","b","c"...]
solution = []
for i in sentence:
newIndex = get index value of i, += 2
newLetter = translate newIndex into the corresponding letter
solution.append(newLetter)
for i in solution:
print(i, end="")
</code></pre>
<p>But I am not yet skilled enough in python to figure it out</p>
| 2 | 2016-08-26T02:19:26Z | 39,157,428 | <p>Try:</p>
<pre><code>>>> s = 'abc'
>>> ''.join(chr(ord(c)+2) for c in s)
'cde'
</code></pre>
<p>The above is not limited to standard ASCII: it works up through the unicode character set.</p>
<h3>Limiting ourselves to 26 characters</h3>
<pre><code>>>> s = 'abcyz'
>>> ''.join(chr(ord('a')+(ord(c)-ord('a')+2) % 26) for c in s)
'cdeab'
</code></pre>
<h3>Modifying the original code</h3>
<p>If we want to modify the original only enough to get it working:</p>
<pre><code>from string import ascii_lowercase as alphabet
def scramble(sentence):
solution = []
for i in sentence:
newIndex = (alphabet.index(i) + 2) % 26
newLetter = alphabet[newIndex]
solution.append(newLetter)
for i in solution:
print(i, end="")
</code></pre>
<p>Example:</p>
<pre><code>>>> scramble('abcz')
cdeb
</code></pre>
| 1 | 2016-08-26T02:23:21Z | [
"python"
] |
how can I move a list index value forward 'x' amount of times using python? | 39,157,398 | <p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p>
<p>For example if the code was</p>
<pre><code>abc
</code></pre>
<p>Then the solution would be</p>
<pre><code>cde
</code></pre>
<p>So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following)</p>
<pre><code>alphabet = ["a","b","c"...."z"]
</code></pre>
<p>I am trying to write code similar to this</p>
<pre><code>def scramble(sentence):
alphabet = ["a","b","c"...]
solution = []
for i in sentence:
newIndex = get index value of i, += 2
newLetter = translate newIndex into the corresponding letter
solution.append(newLetter)
for i in solution:
print(i, end="")
</code></pre>
<p>But I am not yet skilled enough in python to figure it out</p>
| 2 | 2016-08-26T02:19:26Z | 39,157,441 | <p>One solution would be to use enumerate:</p>
<pre><code>for idx, char in enumerate(sentence):
# Do what you need to do here, idx is the index of the char,
# char is the char itself
letter = sentence[idx + 2] # would get you the char 2 places ahead in the list
</code></pre>
<p>This way you could index in by adding to idx. Make sure you check for the end of the list though.</p>
<p>You could also wrap around the list by using modulus on the length of the list, so if you added 2 to the index 25 in a 26 element list, you would get 27 % 26 = 1, so the second element of the list again. </p>
| 0 | 2016-08-26T02:25:34Z | [
"python"
] |
how can I move a list index value forward 'x' amount of times using python? | 39,157,398 | <p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p>
<p>For example if the code was</p>
<pre><code>abc
</code></pre>
<p>Then the solution would be</p>
<pre><code>cde
</code></pre>
<p>So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following)</p>
<pre><code>alphabet = ["a","b","c"...."z"]
</code></pre>
<p>I am trying to write code similar to this</p>
<pre><code>def scramble(sentence):
alphabet = ["a","b","c"...]
solution = []
for i in sentence:
newIndex = get index value of i, += 2
newLetter = translate newIndex into the corresponding letter
solution.append(newLetter)
for i in solution:
print(i, end="")
</code></pre>
<p>But I am not yet skilled enough in python to figure it out</p>
| 2 | 2016-08-26T02:19:26Z | 39,157,443 | <p>There are a couple of ways to do this. </p>
<p>First one, use a dictionary.</p>
<pre><code>a={'a':'c','b':'e'....}
sol=[]
for i in sentence:
sol.append(a[i])
</code></pre>
| 0 | 2016-08-26T02:26:02Z | [
"python"
] |
how can I move a list index value forward 'x' amount of times using python? | 39,157,398 | <p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p>
<p>For example if the code was</p>
<pre><code>abc
</code></pre>
<p>Then the solution would be</p>
<pre><code>cde
</code></pre>
<p>So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following)</p>
<pre><code>alphabet = ["a","b","c"...."z"]
</code></pre>
<p>I am trying to write code similar to this</p>
<pre><code>def scramble(sentence):
alphabet = ["a","b","c"...]
solution = []
for i in sentence:
newIndex = get index value of i, += 2
newLetter = translate newIndex into the corresponding letter
solution.append(newLetter)
for i in solution:
print(i, end="")
</code></pre>
<p>But I am not yet skilled enough in python to figure it out</p>
| 2 | 2016-08-26T02:19:26Z | 39,157,452 | <pre><code>alphabet = "abc"
ord_a = ord('a')
solution = ''.join(chr((ord(c)-ord_a+2)%26+ord_a) for c in alphabet)
</code></pre>
| 0 | 2016-08-26T02:27:13Z | [
"python"
] |
how can I move a list index value forward 'x' amount of times using python? | 39,157,398 | <p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p>
<p>For example if the code was</p>
<pre><code>abc
</code></pre>
<p>Then the solution would be</p>
<pre><code>cde
</code></pre>
<p>So I am trying to figure out how I add 2 to the index value of a letter (given it is in a list like the following)</p>
<pre><code>alphabet = ["a","b","c"...."z"]
</code></pre>
<p>I am trying to write code similar to this</p>
<pre><code>def scramble(sentence):
alphabet = ["a","b","c"...]
solution = []
for i in sentence:
newIndex = get index value of i, += 2
newLetter = translate newIndex into the corresponding letter
solution.append(newLetter)
for i in solution:
print(i, end="")
</code></pre>
<p>But I am not yet skilled enough in python to figure it out</p>
| 2 | 2016-08-26T02:19:26Z | 39,157,703 | <p>Something like this would be useful because it would allow you to change your offset value easily. It'll also handle things other than characters</p>
<pre><code>def caesar_cipher(sentence, offset):
pt_alphabet = ['a','b'...'z']
ct_alphabet = []
index = len(pt_alphabet) + offset
while len(ct_alphabet) < len(pt_alphabet):
if index < (len(pt_alphabet) - 1):
ct_alphabet.append(pt_alphabet[index])
index += 1
else:
index -= len(pt_alphabet)
out_word = ''
for character in sentence:
if character.lower() not in pt_alphabet:
out_word += character
if character.lower() in pt_alphabet:
out_word += ct_alphabet[pt_alphabet.index(character.lower())]
return out_word
if __name__ == '__main__':
offset = 2
sentence = "This is a test with caps and special characters!!"
cipher_text = caesar_cipher(sentence, offset)
print sentence
print cipher_text
</code></pre>
<p>Usage like this:</p>
<pre><code>$ python cipher.py
>> This is a test with caps and special characters!!
>> vjku ku c vguv ykvj ecru cnf urgekco ejctcevgtu!!
</code></pre>
| 0 | 2016-08-26T03:03:14Z | [
"python"
] |
String compression using repeated chars count | 39,157,420 | <p>I'm going through Cracking the Code and there is this question where they ask to write a method for string compression so:</p>
<pre><code>aabbccccaa
</code></pre>
<p>Would become: </p>
<pre><code>a2b1c4a2
</code></pre>
<p>I came up with this:</p>
<pre><code>''.join(y+str.count(y) for y in set(str))
</code></pre>
<p>But my output was: </p>
<pre><code>a5c4b1
</code></pre>
<p>Could someone point me in the clean direction?</p>
<p>Sorry for bad edits, I'm on a cellphone</p>
| 2 | 2016-08-26T02:22:17Z | 39,157,493 | <p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby"><code>groupby</code></a> to do the work for you:</p>
<pre><code>>>> from itertools import groupby
>>> s = 'aabbccccaa'
>>> ''.join(k + str(sum(1 for x in g)) for k, g in groupby(s))
'a2b2c4a2'
</code></pre>
| 7 | 2016-08-26T02:31:53Z | [
"python"
] |
using newaxis in Python | 39,157,426 | <pre><code>A = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10,11,12]])
B = A[:, np.newaxis]
print(B)
print(B.shape)
</code></pre>
<p>the output is</p>
<pre><code>[[[ 1 2 3]]
[[ 4 5 6]]
[[ 7 8 9]]
[[10 11 12]]]
(4L, 1L, 3L)
</code></pre>
<p>I have two questions:</p>
<ol>
<li>Why are there extra brackets outside brackets, for example, <code>[[ 1 2 3]]</code>, so why it is not <code>[ 1 2 3]</code>? </li>
<li>what does <code>1L</code> mean? It looks like to me that <code>B</code> is a 4X3 matrix, so why is it not <code>(4L, 3L)</code>?</li>
</ol>
| 0 | 2016-08-26T02:22:59Z | 39,157,505 | <p>Refer to numpy reference document (<a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a>),
Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.</p>
<ol>
<li>Here, each bracket represent one dimension, extra bracket is caused by newaxis.</li>
<li>1L means the dimension increased by newaxis.</li>
</ol>
| 0 | 2016-08-26T02:34:36Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.