Edits for reorg
I moved book_format.py to the root directory so that all of the notebooks do not need to modify the system path to import it. It modifies the path on import so that all of the code in ./code can then be accessed. Altered links to nbviewer to account for no longer using subdirectories.
This commit is contained in:
@@ -1,77 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from IPython.core.display import HTML
|
||||
import matplotlib.pylab as pylab
|
||||
import matplotlib.pyplot as plt
|
||||
import json
|
||||
import numpy as np
|
||||
import sys
|
||||
|
||||
def test_filterpy_version():
|
||||
import filterpy
|
||||
min_version = [0,0,10]
|
||||
v = filterpy.__version__
|
||||
tokens = v.split('.')
|
||||
for i,v in enumerate(tokens):
|
||||
if int(v) > min_version[i]:
|
||||
return
|
||||
|
||||
i = len(tokens) - 1
|
||||
if min_version[i] > int(tokens[i]):
|
||||
raise Exception("Minimum FilterPy version supported is {}.{}.{}.\n"
|
||||
"Please install a more recent version." .format(
|
||||
*min_version))
|
||||
v = int(tokens[0]*1000)
|
||||
|
||||
|
||||
# ensure that we have the correct filterpy loaded. This is
|
||||
# called when this module is imported at the top of each book
|
||||
# chapter so the reader can see that they need to update FilterPy.
|
||||
test_filterpy_version()
|
||||
|
||||
|
||||
def equal_axis():
|
||||
pylab.rcParams['figure.figsize'] = 10,10
|
||||
plt.axis('equal')
|
||||
|
||||
def reset_axis():
|
||||
pylab.rcParams['figure.figsize'] = 12, 6
|
||||
|
||||
|
||||
def _decode_list(data):
|
||||
rv = []
|
||||
for item in data:
|
||||
if isinstance(item, unicode):
|
||||
item = item.encode('utf-8')
|
||||
elif isinstance(item, list):
|
||||
item = _decode_list(item)
|
||||
elif isinstance(item, dict):
|
||||
item = _decode_dict(item)
|
||||
rv.append(item)
|
||||
return rv
|
||||
|
||||
def _decode_dict(data):
|
||||
rv = {}
|
||||
for key, value in data.iteritems():
|
||||
if isinstance(key, unicode):
|
||||
key = key.encode('utf-8')
|
||||
if isinstance(value, unicode):
|
||||
value = value.encode('utf-8')
|
||||
elif isinstance(value, list):
|
||||
value = _decode_list(value)
|
||||
elif isinstance(value, dict):
|
||||
value = _decode_dict(value)
|
||||
rv[key] = value
|
||||
return rv
|
||||
|
||||
|
||||
def load_style(directory = '.', name='/styles/custom2.css'):
|
||||
if sys.version_info[0] >= 3:
|
||||
s = json.load(open(directory + "/code/538.json"))
|
||||
else:
|
||||
s = json.load(open(directory + "/code/538.json"), object_hook=_decode_dict)
|
||||
plt.rcParams.update(s)
|
||||
reset_axis ()
|
||||
np.set_printoptions(suppress=True)
|
||||
|
||||
styles = open(directory + name, 'r').read()
|
||||
return HTML(styles)
|
||||
74
code/secnum.js
Normal file
74
code/secnum.js
Normal file
@@ -0,0 +1,74 @@
|
||||
console.log("Section numbering...");
|
||||
|
||||
function number_sections(threshold) {
|
||||
|
||||
var h1_number = 0;
|
||||
var h2_number = 0;
|
||||
|
||||
if (threshold === undefined) {
|
||||
threshold = 2; // does nothing so far
|
||||
}
|
||||
|
||||
var cells = IPython.notebook.get_cells();
|
||||
|
||||
for (var i=0; i < cells.length; i++) {
|
||||
|
||||
var cell = cells[i];
|
||||
if (cell.cell_type !== 'heading') continue;
|
||||
|
||||
var level = cell.level;
|
||||
if (level > threshold) continue;
|
||||
|
||||
if (level === 1) {
|
||||
|
||||
h1_number ++;
|
||||
var h1_element = cell.element.find('h1');
|
||||
var h1_html = h1_element.html();
|
||||
|
||||
console.log("h1_html: " + h1_html);
|
||||
|
||||
var patt = /^[0-9]+\.\s(.*)/; // section number at start of string
|
||||
var title = h1_html.match(patt); // just the title
|
||||
|
||||
if (title != null) {
|
||||
h1_element.html(h1_number + ". " + title[1]);
|
||||
}
|
||||
else {
|
||||
h1_element.html(h1_number + ". " + h1_html);
|
||||
}
|
||||
|
||||
h2_number = 0;
|
||||
|
||||
}
|
||||
|
||||
if (level === 2) {
|
||||
|
||||
h2_number ++;
|
||||
|
||||
var h2_element = cell.element.find('h2');
|
||||
var h2_html = h2_element.html();
|
||||
|
||||
console.log("h2_html: " + h2_html);
|
||||
|
||||
|
||||
var patt = /^[0-9]+\.[0-9]+\.\s/;
|
||||
var result = h2_html.match(patt);
|
||||
|
||||
if (result != null) {
|
||||
h2_html = h2_html.replace(result, "");
|
||||
}
|
||||
|
||||
h2_element.html(h1_number + "." + h2_number + ". " + h2_html);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
number_sections();
|
||||
|
||||
// $([IPython.evnts]).on('create.Cell', number_sections);
|
||||
|
||||
$([IPython.events]).on('selected_cell_type_changed.Notebook', number_sections);
|
||||
|
||||
79
code/secnum.py
Normal file
79
code/secnum.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
IPython Notebook magic command for automatically numbering sections of a notebook "interactively"
|
||||
|
||||
Use:
|
||||
%install_ext https://raw.github.com/dpsanders/ipython_extensions/master/section_numbering/secnum.py
|
||||
|
||||
once to install, and then
|
||||
|
||||
%load_ext secnum
|
||||
%secnum
|
||||
|
||||
to get automatic section numbering, which is updated when any cell changes type.
|
||||
(This could, of course, be more efficient.)
|
||||
|
||||
This is based, completely and shamelessly, on MinRK's `nbtoc` magic
|
||||
<https://github.com/minrk/ipython_extensions>
|
||||
|
||||
Thanks also to:
|
||||
- Clayton Davis, for a great explanation of HTML, CSS and JavaScript
|
||||
- Brian Granger, for a crucial hint about extracting a JQuery object from a notebook cell object
|
||||
- Fernando Perez, for an inspiring talk at SciPy 2013 (and, of course, for creating IPython)
|
||||
|
||||
"""
|
||||
|
||||
import io
|
||||
import os
|
||||
import urllib2
|
||||
|
||||
from IPython.display import display_html, display_javascript
|
||||
|
||||
here = os.path.abspath(os.path.dirname(__file__))
|
||||
secnum_js = ""
|
||||
|
||||
def download(fname, redownload=False):
|
||||
"""download a file
|
||||
|
||||
if redownload=False, the file will not be downloaded if it already exists.
|
||||
"""
|
||||
dest = os.path.join(here, fname)
|
||||
if os.path.exists(dest) and not redownload:
|
||||
return
|
||||
url = 'https://raw.github.com/dpsanders/ipython_extensions/master/section_numbering/' + fname
|
||||
print("Downloading %s to %s" % (url, dest))
|
||||
|
||||
filein = urllib2.urlopen(url)
|
||||
fileout = open(dest, "wb")
|
||||
chunk = filein.read(1024)
|
||||
while chunk:
|
||||
fileout.write(chunk)
|
||||
chunk = filein.read(1024)
|
||||
filein.close()
|
||||
fileout.close()
|
||||
|
||||
def load_file(fname, redownload=False):
|
||||
"""load global variable from a file"""
|
||||
download(fname, redownload)
|
||||
with io.open(os.path.join(here, fname)) as f:
|
||||
globals()[fname.replace('.', '_')] = f.read()
|
||||
|
||||
|
||||
load_file('secnum.js')
|
||||
|
||||
|
||||
|
||||
def secnum(line):
|
||||
"""add a table of contents to an IPython Notebook"""
|
||||
display_javascript(secnum_js, raw=True)
|
||||
|
||||
|
||||
def update_secnum(line):
|
||||
"""download the latest version of the nbtoc extension from GitHub"""
|
||||
download('secnum.py', True)
|
||||
download('secnum.js', True)
|
||||
get_ipython().extension_manager.reload_extension("secnum")
|
||||
|
||||
def load_ipython_extension(ip):
|
||||
ip.magics_manager.register_function(secnum)
|
||||
ip.magics_manager.register_function(update_secnum)
|
||||
|
||||
Reference in New Issue
Block a user