np5 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. np5/__init__.py +430 -0
  2. np5/data/figs/u1_f01.jpg +0 -0
  3. np5/data/figs/u1_f02.jpg +0 -0
  4. np5/data/figs/u1_f03.jpg +0 -0
  5. np5/data/figs/u1_f04.jpg +0 -0
  6. np5/data/figs/u1_f05.jpg +0 -0
  7. np5/data/figs/u1_f06.jpg +0 -0
  8. np5/data/figs/u1_f07.jpg +0 -0
  9. np5/data/figs/u1_f08.jpg +0 -0
  10. np5/data/figs/u1_f09.jpg +0 -0
  11. np5/data/figs/u1_f10.jpg +0 -0
  12. np5/data/figs/u1_f11.jpg +0 -0
  13. np5/data/figs/u1_f12.jpg +0 -0
  14. np5/data/figs/u1_f13.jpg +0 -0
  15. np5/data/figs/u1_f14.jpg +0 -0
  16. np5/data/figs/u1_f15.jpg +0 -0
  17. np5/data/figs/u1_f16.jpg +0 -0
  18. np5/data/figs/u1_f17.jpg +0 -0
  19. np5/data/figs/u1_f18.jpg +0 -0
  20. np5/data/figs/u1_f19.jpg +0 -0
  21. np5/data/figs/u1_f20.jpg +0 -0
  22. np5/data/figs/u1_f21.jpg +0 -0
  23. np5/data/figs/u1_f22.jpg +0 -0
  24. np5/data/figs/u1_f23.jpg +0 -0
  25. np5/data/figs/u1_f24.jpg +0 -0
  26. np5/data/figs/u1_f25.jpg +0 -0
  27. np5/data/figs/u1_f26.jpg +0 -0
  28. np5/data/figs/u1_f27.jpg +0 -0
  29. np5/data/figs/u1_f28.jpg +0 -0
  30. np5/data/figs/u1_f29.jpg +0 -0
  31. np5/data/figs/u1_f30.jpg +0 -0
  32. np5/data/figs/u1_f31.jpg +0 -0
  33. np5/data/figs/u1_f32.jpg +0 -0
  34. np5/data/figs/u1_f33.jpg +0 -0
  35. np5/data/figs/u1_f34.jpg +0 -0
  36. np5/data/figs/u1_f35.jpg +0 -0
  37. np5/data/figs/u1_f36.jpg +0 -0
  38. np5/data/figs/u1_f37.jpg +0 -0
  39. np5/data/figs/u1_f38.jpg +0 -0
  40. np5/data/figs/u1_f39.jpg +0 -0
  41. np5/data/figs/u1_f40.jpg +0 -0
  42. np5/data/figs/u1_f41.jpg +0 -0
  43. np5/data/figs/u1_f42.jpg +0 -0
  44. np5/data/figs/u1_f43.jpg +0 -0
  45. np5/data/figs/u2_f01.jpg +0 -0
  46. np5/data/figs/u2_f02.jpg +0 -0
  47. np5/data/figs/u2_f03.jpg +0 -0
  48. np5/data/figs/u2_f04.jpg +0 -0
  49. np5/data/figs/u2_f05.jpg +0 -0
  50. np5/data/figs/u2_f06.jpg +0 -0
  51. np5/data/figs/u2_f07.jpg +0 -0
  52. np5/data/figs/u2_f08.jpg +0 -0
  53. np5/data/figs/u2_f09.jpg +0 -0
  54. np5/data/figs/u2_f10.jpg +0 -0
  55. np5/data/figs/u2_f11.jpg +0 -0
  56. np5/data/figs/u2_f12.jpg +0 -0
  57. np5/data/figs/u2_f13.jpg +0 -0
  58. np5/data/figs/u2_f14.jpg +0 -0
  59. np5/data/figs/u2_f15.jpg +0 -0
  60. np5/data/figs/u2_f16.jpg +0 -0
  61. np5/data/figs/u2_f17.jpg +0 -0
  62. np5/data/figs/u2_f18.jpg +0 -0
  63. np5/data/figs/u2_f19.jpg +0 -0
  64. np5/data/figs/u2_f20.jpg +0 -0
  65. np5/data/figs/u2_f21.jpg +0 -0
  66. np5/data/figs/u2_f22.jpg +0 -0
  67. np5/data/figs/u2_f23.jpg +0 -0
  68. np5/data/figs/u2_f24.jpg +0 -0
  69. np5/data/figs/u2_f25.jpg +0 -0
  70. np5/data/figs/u3_f01.jpg +0 -0
  71. np5/data/figs/u3_f02.jpg +0 -0
  72. np5/data/figs/u3_f03.jpg +0 -0
  73. np5/data/figs/u3_f04.jpg +0 -0
  74. np5/data/figs/u3_f05.jpg +0 -0
  75. np5/data/figs/u3_f06.jpg +0 -0
  76. np5/data/figs/u3_f07.jpg +0 -0
  77. np5/data/figs/u3_f08.jpg +0 -0
  78. np5/data/figs/u4_f01.jpg +0 -0
  79. np5/data/figs/u4_f02.jpg +0 -0
  80. np5/data/figs/u4_f03.jpg +0 -0
  81. np5/data/figs/u4_f04.jpg +0 -0
  82. np5/data/figs/u4_f05.jpg +0 -0
  83. np5/data/figs/u4_f06.jpg +0 -0
  84. np5/data/figs/u4_f07.jpg +0 -0
  85. np5/data/figs/u4_f08.jpg +0 -0
  86. np5/data/figs/u4_f09.jpg +0 -0
  87. np5/data/figs/u4_f10.jpg +0 -0
  88. np5/data/figs/u4_f11.jpg +0 -0
  89. np5/data/figs/u4_f12.jpg +0 -0
  90. np5/data/figs/u4_f13.jpg +0 -0
  91. np5/data/figs/u4_f14.jpg +0 -0
  92. np5/data/figs/u4_f15.jpg +0 -0
  93. np5/data/figs/u4_f16.jpg +0 -0
  94. np5/data/figs/u5_f01.jpg +0 -0
  95. np5/data/figs/u5_f02.jpg +0 -0
  96. np5/data/figs/u5_f03.jpg +0 -0
  97. np5/data/figs/u5_f04.jpg +0 -0
  98. np5/data/figs/u5_f05.jpg +0 -0
  99. np5/data/figs/u5_f06.jpg +0 -0
  100. np5/data/figs/u5_f07.jpg +0 -0
  101. np5/data/figs/u5_f08.jpg +0 -0
  102. np5/data/figs/u6_f01.jpg +0 -0
  103. np5/data/figs/u6_f02.jpg +0 -0
  104. np5/data/figs/u6_f03.jpg +0 -0
  105. np5/data/figs/u6_f04.jpg +0 -0
  106. np5/data/figs/u7_f01.jpg +0 -0
  107. np5/data/figs/u7_f02.jpg +0 -0
  108. np5/data/figs/u8_f01.jpg +0 -0
  109. np5/data/figs/u8_f02.jpg +0 -0
  110. np5/data/figs/u8_f03.jpg +0 -0
  111. np5/data/figs/u8_f04.jpg +0 -0
  112. np5/data/figs/u8_f05.jpg +0 -0
  113. np5/data/unit1.md +574 -0
  114. np5/data/unit2.md +361 -0
  115. np5/data/unit3.md +301 -0
  116. np5/data/unit4.md +323 -0
  117. np5/data/unit5.md +233 -0
  118. np5/data/unit6.md +270 -0
  119. np5/data/unit7.md +346 -0
  120. np5/data/unit8.md +315 -0
  121. np5-1.0.0.dist-info/METADATA +27 -0
  122. np5-1.0.0.dist-info/RECORD +125 -0
  123. np5-1.0.0.dist-info/WHEEL +5 -0
  124. np5-1.0.0.dist-info/entry_points.txt +2 -0
  125. np5-1.0.0.dist-info/top_level.txt +1 -0
np5/__init__.py ADDED
@@ -0,0 +1,430 @@
1
+ """np5: Time Series Forecasting notes, Units 1-8.
2
+
3
+ import np5
4
+ np5.units() # list all units
5
+ np5.show(2) # whole Unit 2 (scrollable)
6
+ np5.topics(2) # numbered topic list of Unit 2
7
+ np5.show(2, 4) # topic 4 of Unit 2
8
+ np5.show(2, "smoothing") # first topic whose title contains "smoothing"
9
+ np5.figure(2, 3) # open figure 3 of Unit 2
10
+ np5.open(2) # open Unit 2 as a page in your browser (with figures)
11
+ np5.search("ARIMA") # search every unit
12
+ np5.text(2) # Unit 2 as a plain string
13
+ """
14
+ import base64
15
+ import html as _html
16
+ import os
17
+ import re
18
+ import shutil
19
+ import sys
20
+ import tempfile
21
+ import textwrap
22
+ import webbrowser
23
+ from pathlib import Path
24
+
25
+ __version__ = "1.0.0"
26
+ __all__ = ["units", "show", "topics", "search", "text", "figure", "open", "help"]
27
+
28
+ _DATA = Path(__file__).resolve().parent / "data"
29
+ _FIG_RE = re.compile(r"^FIG:\s*(\S+)\s*\|\s*(.*)$")
30
+
31
+
32
+ # ----------------------------------------------------------------- data access
33
+ def _available():
34
+ out = []
35
+ for p in _DATA.glob("unit*.md"):
36
+ m = re.match(r"unit(\d+)\.md$", p.name)
37
+ if m:
38
+ out.append(int(m.group(1)))
39
+ return sorted(out)
40
+
41
+
42
+ def _read(n):
43
+ try:
44
+ n = int(n)
45
+ except (TypeError, ValueError):
46
+ raise ValueError(f"Unit must be a number, e.g. np5.show(1). Available: {_available()}") from None
47
+ p = _DATA / f"unit{n}.md"
48
+ if not p.exists():
49
+ raise ValueError(f"There is no Unit {n}. Available units: {_available()}")
50
+ return p.read_text(encoding="utf-8")
51
+
52
+
53
+ def _unit(n):
54
+ """-> (unit title, [(topic title, body), ...])"""
55
+ raw = _read(n)
56
+ parts = re.split(r"(?m)^## ", raw)
57
+ head = parts[0].strip().lstrip("#").strip() or f"UNIT {n}"
58
+ secs = []
59
+ for p in parts[1:]:
60
+ t, _, b = p.partition("\n")
61
+ secs.append((t.strip(), b.strip()))
62
+ return head, secs
63
+
64
+
65
+ def _figures(n):
66
+ """-> list of (file name, caption) in order, numbered from 1."""
67
+ figs = []
68
+ for line in _read(n).splitlines():
69
+ m = _FIG_RE.match(line.strip())
70
+ if m:
71
+ figs.append((m.group(1), m.group(2).strip()))
72
+ return figs
73
+
74
+
75
+ def _pick(n, which):
76
+ """Find a topic by number (1-based) or by part of its title."""
77
+ _, secs = _unit(n)
78
+ if isinstance(which, int) or (isinstance(which, str) and which.strip().isdigit()):
79
+ k = int(which)
80
+ if 1 <= k <= len(secs):
81
+ return k, secs[k - 1]
82
+ raise ValueError(f"Unit {n} has topics 1 to {len(secs)}. See np5.topics({n})")
83
+ w = str(which).lower()
84
+ for i, (t, b) in enumerate(secs, 1):
85
+ if w in t.lower():
86
+ return i, (t, b)
87
+ for i, (t, b) in enumerate(secs, 1):
88
+ if w in b.lower():
89
+ return i, (t, b)
90
+ raise ValueError(f"No topic matching {which!r} in Unit {n}. See np5.topics({n})")
91
+
92
+
93
+ # ------------------------------------------------------------- text rendering
94
+ def _width():
95
+ try:
96
+ return max(60, min(110, shutil.get_terminal_size((100, 24)).columns - 2))
97
+ except Exception:
98
+ return 100
99
+
100
+
101
+ def _fig_numbers(n):
102
+ return {f: i for i, (f, _) in enumerate(_figures(n), 1)}
103
+
104
+
105
+ def _render_text(n, secs, numbered_from=1):
106
+ title, _ = _unit(n)
107
+ W = _width()
108
+ fnum = _fig_numbers(n)
109
+ bar = "=" * W
110
+ out = [bar, title.upper().center(W), bar, ""]
111
+ for i, (t, body) in enumerate(secs, numbered_from):
112
+ out += [f"{i}. {t}", "-" * min(W, len(t) + 4)]
113
+ for line in body.splitlines():
114
+ m = _FIG_RE.match(line.strip())
115
+ if m:
116
+ k = fnum.get(m.group(1), "?")
117
+ out.append(f" [FIGURE {k}] {m.group(2)}")
118
+ out.append(f" -> to see it: np5.figure({n}, {k}) or open the unit: np5.open({n})")
119
+ continue
120
+ s = line.rstrip()
121
+ if not s or s.lstrip().startswith("|") or len(s) <= W:
122
+ out.append(s)
123
+ continue
124
+ indent = len(s) - len(s.lstrip())
125
+ bullet = re.match(r"(\s*(?:[-•*]|\d+[.)]|Step \d+:)\s+)", s)
126
+ sub = " " * (len(bullet.group(1)) if bullet else indent)
127
+ out.extend(textwrap.wrap(s, W, initial_indent="", subsequent_indent=sub,
128
+ break_long_words=False, break_on_hyphens=False) or [s])
129
+ out.append("")
130
+ return "\n".join(out)
131
+
132
+
133
+ # ------------------------------------------------------------- html rendering
134
+ _CSS = """
135
+ body{font-family:-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;max-width:900px;margin:0 auto;padding:24px 16px;line-height:1.6;color:#1d1d1f;background:#fff}
136
+ h1{font-size:26px;border-bottom:3px solid #305496;padding-bottom:8px}
137
+ h2{font-size:20px;color:#305496;margin-top:36px;border-bottom:1px solid #ddd;padding-bottom:4px}
138
+ nav ol{columns:2;font-size:14px} nav a{color:#305496;text-decoration:none}
139
+ table{border-collapse:collapse;margin:10px 0;font-size:14px;display:block;overflow-x:auto}
140
+ td,th{border:1px solid #bbb;padding:4px 8px} th{background:#eef2f9}
141
+ figure{margin:16px 0;text-align:center} figure img{max-width:100%;border:1px solid #ddd;border-radius:6px}
142
+ figcaption{font-size:14px;color:#444;margin-top:6px}
143
+ .f{font-family:Menlo,Consolas,monospace;background:#f5f7fb;padding:6px 10px;border-radius:4px;display:block;margin:6px 0;white-space:pre-wrap}
144
+ ul{padding-left:22px} p{margin:8px 0}
145
+ """
146
+
147
+
148
+ def _img_src(fname, inline):
149
+ p = _DATA / "figs" / fname
150
+ if not p.exists():
151
+ return None
152
+ if inline:
153
+ return "data:image/jpeg;base64," + base64.b64encode(p.read_bytes()).decode()
154
+ return p.as_uri()
155
+
156
+
157
+ def _looks_formula(s):
158
+ return bool(re.search(r"[=≈≤≥Σ√]", s)) and len(s) < 160 and not s.endswith(".") \
159
+ and not s.lower().startswith(("where", "- ", "• "))
160
+
161
+
162
+ def _body_html(n, body, inline):
163
+ fnum = _fig_numbers(n)
164
+ out, lst, tbl = [], False, []
165
+
166
+ def flush_table():
167
+ nonlocal tbl
168
+ if not tbl:
169
+ return
170
+ rows = [r for r in tbl if not re.fullmatch(r"[\s|:\-]+", r)]
171
+ h = ["<table>"]
172
+ for j, r in enumerate(rows):
173
+ cells = [c.strip() for c in r.strip().strip("|").split("|")]
174
+ tag = "th" if j == 0 else "td"
175
+ h.append("<tr>" + "".join(f"<{tag}>{_html.escape(c)}</{tag}>" for c in cells) + "</tr>")
176
+ h.append("</table>")
177
+ out.append("".join(h))
178
+ tbl = []
179
+
180
+ for line in body.splitlines():
181
+ s = line.strip()
182
+ if s.startswith("|"):
183
+ if lst:
184
+ out.append("</ul>"); lst = False
185
+ tbl.append(s)
186
+ continue
187
+ flush_table()
188
+ m = _FIG_RE.match(s)
189
+ if m:
190
+ if lst:
191
+ out.append("</ul>"); lst = False
192
+ k = fnum.get(m.group(1), "?")
193
+ src = _img_src(m.group(1), inline)
194
+ img = f'<img src="{src}" alt="Figure {k}">' if src else ""
195
+ out.append(f"<figure>{img}<figcaption><b>Figure {k}.</b> {_html.escape(m.group(2))}</figcaption></figure>")
196
+ continue
197
+ b = re.match(r"^\s*(?:[-•*])\s+(.*)", line)
198
+ if b:
199
+ if not lst:
200
+ out.append("<ul>"); lst = True
201
+ out.append(f"<li>{_html.escape(b.group(1))}</li>")
202
+ continue
203
+ if lst:
204
+ out.append("</ul>"); lst = False
205
+ if not s:
206
+ continue
207
+ if _looks_formula(s):
208
+ out.append(f'<span class="f">{_html.escape(s)}</span>')
209
+ elif s.startswith("What it shows:") or re.match(r"^(Step \d+|Example|Where|where)\b", s):
210
+ out.append(f"<p><i>{_html.escape(s)}</i></p>" if s.startswith("What") else f"<p><b>{_html.escape(s)}</b></p>")
211
+ else:
212
+ out.append(f"<p>{_html.escape(s)}</p>")
213
+ flush_table()
214
+ if lst:
215
+ out.append("</ul>")
216
+ return "\n".join(out)
217
+
218
+
219
+ def _render_html(n, secs, inline, numbered_from=1, full_page=True):
220
+ title, _ = _unit(n)
221
+ parts = []
222
+ if full_page:
223
+ parts.append(f"<h1>{_html.escape(title)}</h1>")
224
+ if len(secs) > 1:
225
+ parts.append("<nav><ol>" + "".join(
226
+ f'<li><a href="#t{i}">{_html.escape(t)}</a></li>' for i, (t, _) in enumerate(secs, numbered_from)
227
+ ) + "</ol></nav>")
228
+ for i, (t, b) in enumerate(secs, numbered_from):
229
+ parts.append(f'<h2 id="t{i}">{i}. {_html.escape(t)}</h2>')
230
+ parts.append(_body_html(n, b, inline))
231
+ return "\n".join(parts)
232
+
233
+
234
+ # ------------------------------------------------------------------ display
235
+ def _in_notebook():
236
+ try:
237
+ from IPython import get_ipython
238
+ ip = get_ipython()
239
+ return ip is not None and ip.__class__.__name__ in ("ZMQInteractiveShell", "Shell")
240
+ except Exception:
241
+ return False
242
+
243
+
244
+ def _safe_print(s):
245
+ try:
246
+ print(s)
247
+ except UnicodeEncodeError:
248
+ enc = getattr(sys.stdout, "encoding", None) or "utf-8"
249
+ print(s.encode(enc, "replace").decode(enc, "replace"))
250
+
251
+
252
+ def _page(s, pager):
253
+ if pager is None:
254
+ pager = sys.stdout.isatty() and sys.stdin.isatty()
255
+ if pager:
256
+ try:
257
+ if os.environ.get("PAGER") is None and shutil.which("less"):
258
+ os.environ.setdefault("LESS", "-R")
259
+ import pydoc
260
+ pydoc.pager(s)
261
+ return
262
+ except Exception:
263
+ pass
264
+ _safe_print(s)
265
+
266
+
267
+ def _scoped_css():
268
+ rules = []
269
+ for sel, decl in re.findall(r"([^{}]+)\{([^}]*)\}", _CSS):
270
+ sels = [s.strip() for s in sel.split(",")]
271
+ sels = [".np5" if s == "body" else f".np5 {s}" for s in sels]
272
+ rules.append(",".join(sels) + "{" + decl + "}")
273
+ return "".join(rules)
274
+
275
+
276
+ def _show_notebook(n, secs, start):
277
+ from IPython.display import HTML, display
278
+ body = _render_html(n, secs, inline=True, numbered_from=start, full_page=len(secs) > 1)
279
+ display(HTML(f'<div style="max-height:650px;overflow-y:auto;border:1px solid #ccc;'
280
+ f'border-radius:8px;padding:4px 18px;background:#fff;color:#1d1d1f">'
281
+ f'<style>{_scoped_css()}</style>'
282
+ f'<div class="np5">{body}</div></div>'))
283
+
284
+
285
+ # ------------------------------------------------------------------ public API
286
+ def show(n=None, topic=None, pager=None):
287
+ """Show a unit, or one topic of it.
288
+
289
+ np5.show(2) whole Unit 2
290
+ np5.show(2, 4) topic number 4 (see np5.topics(2))
291
+ np5.show(2, "holt") first topic whose title contains "holt"
292
+
293
+ Terminal: opens in a scroller (arrows/space to scroll, q to quit). pager=False just prints.
294
+ Jupyter / Colab: shows a scrollable box with the real figures inside.
295
+ """
296
+ if n is None:
297
+ return units()
298
+ if topic is None:
299
+ secs, start = _unit(n)[1], 1
300
+ else:
301
+ k, sec = _pick(n, topic)
302
+ secs, start = [sec], k
303
+ if _in_notebook():
304
+ try:
305
+ return _show_notebook(n, secs, start)
306
+ except Exception:
307
+ pass
308
+ _page(_render_text(n, secs, start), pager)
309
+
310
+
311
+ def text(n):
312
+ """Return a unit's notes as one plain string."""
313
+ _, secs = _unit(n)
314
+ return _render_text(n, secs)
315
+
316
+
317
+ def units():
318
+ """List all units."""
319
+ lines = ["", "np5 — Time Series Forecasting notes", ""]
320
+ for n in _available():
321
+ title, secs = _unit(n)
322
+ lines.append(f" np5.show({n}) {title} ({len(secs)} topics, {len(_figures(n))} figures)")
323
+ lines += ["", "More: np5.topics(n) np5.show(n, topic) np5.figure(n, k) np5.open(n) np5.search('word')", ""]
324
+ _safe_print("\n".join(lines))
325
+
326
+
327
+ def topics(n):
328
+ """Numbered list of the topics in a unit."""
329
+ title, secs = _unit(n)
330
+ lines = [title, ""]
331
+ for i, (t, b) in enumerate(secs, 1):
332
+ nf = sum(1 for l in b.splitlines() if _FIG_RE.match(l.strip()))
333
+ lines.append(f" {i:>2}. {t}" + (f" [{nf} fig]" if nf else ""))
334
+ lines += ["", f"Open one with np5.show({n}, <number>)"]
335
+ _safe_print("\n".join(lines))
336
+
337
+
338
+ def search(word, limit=60):
339
+ """Search every unit for a word or phrase."""
340
+ w = str(word).lower().strip()
341
+ hits = []
342
+ for n in _available():
343
+ for i, (t, b) in enumerate(_unit(n)[1], 1):
344
+ if w in t.lower() or w in b.lower():
345
+ snip = ""
346
+ for l in b.splitlines():
347
+ if w in l.lower() and not l.startswith("FIG:"):
348
+ snip = l.strip()
349
+ break
350
+ hits.append(f" Unit {n}, topic {i}: {t}" + (f"\n ...{snip[:140]}..." if snip else ""))
351
+ if not hits:
352
+ _safe_print(f"No match for {word!r}")
353
+ return
354
+ _safe_print("\n".join(hits[:limit]) + f"\n\n{len(hits)} topic(s) found. Open with np5.show(unit, topic)")
355
+
356
+
357
+ def figure(n, k=None):
358
+ """Open figure k of unit n (np5.figure(2) lists the unit's figures)."""
359
+ figs = _figures(n)
360
+ if k is None:
361
+ _safe_print("\n".join(f" {i:>2}. {c}" for i, (_, c) in enumerate(figs, 1))
362
+ + f"\n\nOpen one with np5.figure({n}, <number>)")
363
+ return
364
+ k = int(k)
365
+ if not 1 <= k <= len(figs):
366
+ raise ValueError(f"Unit {n} has figures 1 to {len(figs)}. See np5.figure({n})")
367
+ fname, cap = figs[k - 1]
368
+ p = _DATA / "figs" / fname
369
+ if _in_notebook():
370
+ from IPython.display import Image, display, Markdown
371
+ display(Markdown(f"**Figure {k}.** {cap}"))
372
+ return display(Image(filename=str(p)))
373
+ _safe_print(f"Figure {k}: {cap}\n{p}")
374
+ _open_path(p)
375
+
376
+
377
+ def _open_path(p):
378
+ try:
379
+ if sys.platform == "darwin":
380
+ os.system(f'open "{p}"')
381
+ elif os.name == "nt":
382
+ os.startfile(str(p)) # type: ignore[attr-defined]
383
+ else:
384
+ webbrowser.open(Path(p).as_uri())
385
+ except Exception:
386
+ webbrowser.open(Path(p).as_uri())
387
+
388
+
389
+ def open(n=None): # noqa: A001 - friendly name
390
+ """Open a unit (or all units when n is None) as a nicely formatted page in your browser."""
391
+ nums = _available() if n is None else [int(n)]
392
+ body = []
393
+ for u in nums:
394
+ _, secs = _unit(u)
395
+ body.append(_render_html(u, secs, inline=False))
396
+ title = "np5 notes" if n is None else _unit(nums[0])[0]
397
+ doc = (f"<!doctype html><html><head><meta charset='utf-8'><meta name='viewport' "
398
+ f"content='width=device-width,initial-scale=1'><title>{_html.escape(title)}</title>"
399
+ f"<style>{_CSS}</style></head><body>{''.join(body)}</body></html>")
400
+ out = Path(tempfile.gettempdir()) / f"np5_unit{'_all' if n is None else nums[0]}.html"
401
+ out.write_text(doc, encoding="utf-8")
402
+ webbrowser.open(out.as_uri())
403
+ _safe_print(f"Opened {out}")
404
+ return str(out)
405
+
406
+
407
+ def help(): # noqa: A001
408
+ _safe_print(__doc__)
409
+
410
+
411
+ def _cli():
412
+ a = sys.argv[1:]
413
+ try:
414
+ if not a or a[0] in ("-h", "--help", "help"):
415
+ units()
416
+ _safe_print("Terminal: np5 <unit> [topic] | np5 topics <unit> | np5 search <word> | "
417
+ "np5 open <unit> | np5 fig <unit> <k>")
418
+ elif a[0] in ("search", "s") and len(a) > 1:
419
+ search(" ".join(a[1:]))
420
+ elif a[0] in ("topics", "t") and len(a) > 1:
421
+ topics(a[1])
422
+ elif a[0] in ("open", "o"):
423
+ open(a[1] if len(a) > 1 else None)
424
+ elif a[0] in ("fig", "figure", "f") and len(a) > 1:
425
+ figure(a[1], a[2] if len(a) > 2 else None)
426
+ else:
427
+ show(a[0], " ".join(a[1:]) if len(a) > 1 else None)
428
+ except ValueError as e:
429
+ _safe_print(f"np5: {e}")
430
+ sys.exit(1)
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file