CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

| Download

Python Data Science Handbook

Views: 92281
1
import os
2
import itertools
3
4
from ipykernel import kernelspec as ks
5
import nbformat
6
from nbformat.v4.nbbase import new_markdown_cell
7
8
from generate_contents import NOTEBOOK_DIR, REG, iter_notebooks, get_notebook_title
9
10
11
def prev_this_next(it):
12
a, b, c = itertools.tee(it,3)
13
next(c)
14
return zip(itertools.chain([None], a), b, itertools.chain(c, [None]))
15
16
17
PREV_TEMPLATE = "< [{title}]({url}) "
18
CONTENTS = "| [Contents](Index.ipynb) |"
19
NEXT_TEMPLATE = " [{title}]({url}) >"
20
NAV_COMMENT = "<!--NAVIGATION-->\n"
21
22
23
def iter_navbars():
24
for prev_nb, nb, next_nb in prev_this_next(iter_notebooks()):
25
navbar = NAV_COMMENT
26
if prev_nb:
27
navbar += PREV_TEMPLATE.format(title=get_notebook_title(prev_nb),
28
url=prev_nb)
29
navbar += CONTENTS
30
if next_nb:
31
navbar += NEXT_TEMPLATE.format(title=get_notebook_title(next_nb),
32
url=next_nb)
33
yield os.path.join(NOTEBOOK_DIR, nb), navbar
34
35
36
def write_navbars():
37
for nb_name, navbar in iter_navbars():
38
nb = nbformat.read(nb_name, as_version=4)
39
nb_file = os.path.basename(nb_name)
40
is_comment = lambda cell: cell.source.startswith(NAV_COMMENT)
41
42
if is_comment(nb.cells[1]):
43
print("- amending navbar for {0}".format(nb_file))
44
nb.cells[1].source = navbar
45
else:
46
print("- inserting navbar for {0}".format(nb_file))
47
nb.cells.insert(1, new_markdown_cell(source=navbar))
48
49
if is_comment(nb.cells[-1]):
50
nb.cells[-1].source = navbar
51
else:
52
nb.cells.append(new_markdown_cell(source=navbar))
53
nbformat.write(nb, nb_name)
54
55
56
if __name__ == '__main__':
57
write_navbars()
58
59