You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

944 lines
75 KiB

3 years ago
5 years ago
2 years ago
1 year ago
1 year ago
5 years ago
3 months ago
2 years ago
2 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
5 years ago
1 year ago
1 year ago
8 months ago
1 year ago
8 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
6 months ago
6 months ago
6 months ago
4 years ago
4 years ago
4 years ago
2 years ago
2 years ago
1 year ago
2 years ago
1 year ago
1 year ago
2 years ago
1 year ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
7 months ago
3 years ago
7 months ago
3 years ago
7 months ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
4 years ago
1 year ago
1 year ago
3 years ago
1 year ago
3 years ago
3 years ago
3 years ago
3 years ago
1 year ago
1 year ago
2 years ago
1 year ago
2 years ago
2 years ago
1 year ago
2 years ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
2 years ago
5 years ago
2 years ago
2 years ago
2 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 months ago
5 years ago
1 year ago
1 year ago
5 years ago
8 months ago
1 year ago
6 months ago
6 months ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
1 year ago
  1. #!/usr/bin/env node
  2. // Usage: node parse.js
  3. //
  4. // Script that creates index.html out of web/template.html and README.md.
  5. //
  6. // It is written in JS because this code used to be executed on the client side.
  7. // To install the Node.js and npm run:
  8. // $ sudo apt install nodejs npm # On macOS use `brew install ...` instead.
  9. //
  10. // To install dependencies globally, run:
  11. // $ npm install -g jsdom jquery showdown highlightjs@9.12.0
  12. //
  13. // If running on macOS and modules can't be found after installation add:
  14. // export NODE_PATH=/usr/local/lib/node_modules
  15. // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'.
  16. //
  17. // To avoid problems with permissions and path variables, install modules
  18. // into project's directory using:
  19. // $ npm install jsdom jquery showdown highlightjs@9.12.0
  20. //
  21. // It is also advisable to add a Bash script into .git/hooks directory, that will
  22. // run this script before every commit. It should be named 'pre-commit' and it
  23. // should contain the following line: `./parse.js`.
  24. const fs = require('fs');
  25. const jsdom = require('jsdom');
  26. const showdown = require('showdown');
  27. const hljs = require('highlightjs');
  28. const TOC =
  29. '<br>' +
  30. '<h2 id="toc">Contents</h2>\n' +
  31. '<pre><code class="hljs bash" style="line-height: 1.327em;"><strong>ToC</strong> = {\n' +
  32. ' <strong><span class="hljs-string">\'1. Collections\'</span></strong>: [<a href="#list">List</a>, <a href="#dictionary">Dictionary</a>, <a href="#set">Set</a>, <a href="#tuple">Tuple</a>, <a href="#range">Range</a>, <a href="#enumerate">Enumerate</a>, <a href="#iterator">Iterator</a>, <a href="#generator">Generator</a>],\n' +
  33. ' <strong><span class="hljs-string">\'2. Types\'</span></strong>: [<a href="#type">Type</a>, <a href="#string">String</a>, <a href="#regex">Regular_Exp</a>, <a href="#format">Format</a>, <a href="#numbers">Numbers</a>, <a href="#combinatorics">Combinatorics</a>, <a href="#datetime">Datetime</a>],\n' +
  34. ' <strong><span class="hljs-string">\'3. Syntax\'</span></strong>: [<a href="#arguments">Args</a>, <a href="#inline">Inline</a>, <a href="#imports">Import</a>, <a href="#decorator">Decorator</a>, <a href="#class">Class</a>, <a href="#ducktypes">Duck_Types</a>, <a href="#enum">Enum</a>, <a href="#exceptions">Exception</a>],\n' +
  35. ' <strong><span class="hljs-string">\'4. System\'</span></strong>: [<a href="#exit">Exit</a>, <a href="#print">Print</a>, <a href="#input">Input</a>, <a href="#commandlinearguments">Command_Line_Arguments</a>, <a href="#open">Open</a>, <a href="#paths">Path</a>, <a href="#oscommands">OS_Commands</a>],\n' +
  36. ' <strong><span class="hljs-string">\'5. Data\'</span></strong>: [<a href="#json">JSON</a>, <a href="#pickle">Pickle</a>, <a href="#csv">CSV</a>, <a href="#sqlite">SQLite</a>, <a href="#bytes">Bytes</a>, <a href="#struct">Struct</a>, <a href="#array">Array</a>, <a href="#memoryview">Memory_View</a>, <a href="#deque">Deque</a>],\n' +
  37. ' <strong><span class="hljs-string">\'6. Advanced\'</span></strong>: [<a href="#threading">Threading</a>, <a href="#operator">Operator</a>, <a href="#matchstatement">Match_Stmt</a>, <a href="#logging">Logging</a>, <a href="#introspection">Introspection</a>, <a href="#coroutines">Coroutines</a>],\n' +
  38. ' <strong><span class="hljs-string">\'7. Libraries\'</span></strong>: [<a href="#progressbar">Progress_Bar</a>, <a href="#plot">Plot</a>, <a href="#table">Table</a>, <a href="#consoleapp">Console_App</a>, <a href="#guiapp">GUI</a>, <a href="#scraping">Scraping</a>, <a href="#web">Web</a>, <a href="#profiling">Profile</a>],\n' +
  39. ' <strong><span class="hljs-string">\'8. Multimedia\'</span></strong>: [<a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#animation">Animation</a>, <a href="#audio">Audio</a>, <a href="#synthesizer">Synthesizer</a>, <a href="#pygame">Pygame</a>, <a href="#pandas">Pandas</a>, <a href="#plotly">Plotly</a>]\n' +
  40. '}\n' +
  41. '</code></pre>\n';
  42. const BIN_HEX =
  43. '&lt;int&gt; = ±<span class="hljs-number">0b</span>&lt;bin&gt; <span class="hljs-comment"># Or: ±0x&lt;hex&gt;</span>\n' +
  44. '&lt;int&gt; = int(<span class="hljs-string">\'±&lt;bin&gt;\'</span>, <span class="hljs-number">2</span>) <span class="hljs-comment"># Or: int(\'±&lt;hex&gt;\', 16)</span>\n' +
  45. '&lt;int&gt; = int(<span class="hljs-string">\'±0b&lt;bin&gt;\'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int(\'±0x&lt;hex&gt;\', 0)</span>\n' +
  46. '&lt;str&gt; = bin(&lt;int&gt;) <span class="hljs-comment"># Returns \'[-]0b&lt;bin&gt;\'. Also hex().</span>\n';
  47. const LRU_CACHE =
  48. '<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> lru_cache\n' +
  49. '\n' +
  50. '<span class="hljs-meta">@lru_cache(maxsize=None)</span>\n' +
  51. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>\n' +
  52. ' <span class="hljs-keyword">return</span> n <span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">2</span> <span class="hljs-keyword">else</span> fib(n-<span class="hljs-number">2</span>) + fib(n-<span class="hljs-number">1</span>)\n';
  53. const PARAMETRIZED_DECORATOR =
  54. '<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps\n' +
  55. '\n' +
  56. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(print_result=<span class="hljs-keyword">False</span>)</span>:</span>\n' +
  57. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>\n' +
  58. '<span class="hljs-meta"> @wraps(func)</span>\n' +
  59. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>\n' +
  60. ' result = func(*args, **kwargs)\n' +
  61. ' print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">\'\'</span>)\n' +
  62. ' <span class="hljs-keyword">return</span> result\n' +
  63. ' <span class="hljs-keyword">return</span> out\n' +
  64. ' <span class="hljs-keyword">return</span> decorator\n' +
  65. '\n' +
  66. '<span class="hljs-meta">@debug(print_result=True)</span>\n' +
  67. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>\n' +
  68. ' <span class="hljs-keyword">return</span> x + y\n';
  69. const REPR_USE_CASES =
  70. 'print/str/repr([&lt;obj&gt;])\n' +
  71. 'print/str/repr({&lt;obj&gt;: &lt;obj&gt;})\n' +
  72. '<span class="hljs-string">f\'<span class="hljs-subst">{&lt;obj&gt;!r}</span>\'</span>\n' +
  73. 'Z = dataclasses.make_dataclass(<span class="hljs-string">\'Z\'</span>, [<span class="hljs-string">\'a\'</span>]); print/str/repr(Z(&lt;obj&gt;))\n' +
  74. '<span class="hljs-meta">&gt;&gt;&gt; </span>&lt;obj&gt;\n';
  75. const CONSTRUCTOR_OVERLOADING =
  76. '<span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">name</span>&gt;:</span>\n' +
  77. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a=<span class="hljs-keyword">None</span>)</span>:</span>\n' +
  78. ' self.a = a\n';
  79. const DATACLASS =
  80. '&lt;class&gt; = make_dataclass(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;coll_of_attribute_names&gt;)\n' +
  81. '&lt;class&gt; = make_dataclass(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;coll_of_tuples&gt;)\n' +
  82. '&lt;tuple&gt; = (<span class="hljs-string">\'&lt;attr_name&gt;\'</span>, &lt;type&gt; [, &lt;default_value&gt;])';
  83. const SHUTIL_COPY =
  84. 'shutil.copy(from, to) <span class="hljs-comment"># Copies the file. \'to\' can exist or be a dir.</span>\n' +
  85. 'shutil.copy2(from, to) <span class="hljs-comment"># Also copies creation and modification time.</span>\n' +
  86. 'shutil.copytree(from, to) <span class="hljs-comment"># Copies the directory. \'to\' must not exist.</span>\n';
  87. const OS_RENAME =
  88. 'os.rename(from, to) <span class="hljs-comment"># Renames/moves the file or directory.</span>\n' +
  89. 'os.replace(from, to) <span class="hljs-comment"># Same, but overwrites file \'to\' even on Windows.</span>\n' +
  90. 'shutil.move(from, to) <span class="hljs-comment"># Rename() that moves into \'to\' if it\'s a dir.</span>\n';
  91. const STRUCT_FORMAT =
  92. '<span class="hljs-section">\'&lt;n&gt;s\'</span><span class="hljs-attribute"></span>';
  93. const MATCH =
  94. '<span class="hljs-keyword">match</span> &lt;object/expression&gt;:\n' +
  95. ' <span class="hljs-keyword">case</span> &lt;pattern&gt; [<span class="hljs-keyword">if</span> &lt;condition&gt;]:\n' +
  96. ' &lt;code&gt;\n' +
  97. ' ...\n';
  98. const MATCH_EXAMPLE =
  99. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path\n' +
  100. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">match</span> Path(<span class="hljs-string">\'/home/gto/python-cheatsheet/README.md\'</span>):\n' +
  101. '<span class="hljs-meta">... </span> <span class="hljs-keyword">case</span> Path(\n' +
  102. '<span class="hljs-meta">... </span> parts=[<span class="hljs-string">\'/\'</span>, <span class="hljs-string">\'home\'</span>, user, *_],\n' +
  103. '<span class="hljs-meta">... </span> stem=stem,\n' +
  104. '<span class="hljs-meta">... </span> suffix=(<span class="hljs-string">\'.md\'</span> | <span class="hljs-string">\'.txt\'</span>) <span class="hljs-keyword">as</span> suffix\n' +
  105. '<span class="hljs-meta">... </span> ) <span class="hljs-keyword">if</span> stem.lower() == <span class="hljs-string">\'readme\'</span>:\n' +
  106. '<span class="hljs-meta">... </span> print(<span class="hljs-string">f\'<span class="hljs-subst">{stem}</span><span class="hljs-subst">{suffix}</span> is a readme file that belongs to user <span class="hljs-subst">{user}</span>.\'</span>)\n' +
  107. '<span class="hljs-string">\'README.md is a readme file that belongs to user gto.\'</span>\n';
  108. const COROUTINES =
  109. '<span class="hljs-keyword">import</span> asyncio, collections, curses, curses.textpad, enum, random\n' +
  110. '\n' +
  111. 'P = collections.namedtuple(<span class="hljs-string">\'P\'</span>, <span class="hljs-string">\'x y\'</span>) <span class="hljs-comment"># Position</span>\n' +
  112. 'D = enum.Enum(<span class="hljs-string">\'D\'</span>, <span class="hljs-string">\'n e s w\'</span>) <span class="hljs-comment"># Direction</span>\n' +
  113. 'W, H = <span class="hljs-number">15</span>, <span class="hljs-number">7</span> <span class="hljs-comment"># Width, Height</span>\n' +
  114. '\n' +
  115. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>\n' +
  116. ' curses.curs_set(<span class="hljs-number">0</span>) <span class="hljs-comment"># Makes cursor invisible.</span>\n' +
  117. ' screen.nodelay(<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Makes getch() non-blocking.</span>\n' +
  118. ' asyncio.run(main_coroutine(screen)) <span class="hljs-comment"># Starts running asyncio code.</span>\n' +
  119. '\n' +
  120. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main_coroutine</span><span class="hljs-params">(screen)</span>:</span>\n' +
  121. ' moves = asyncio.Queue()\n' +
  122. ' state = {<span class="hljs-string">\'*\'</span>: P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), **{id_: P(W//<span class="hljs-number">2</span>, H//<span class="hljs-number">2</span>) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)}}\n' +
  123. ' ai = [random_controller(id_, moves) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)]\n' +
  124. ' mvc = [human_controller(screen, moves), model(moves, state), view(state, screen)]\n' +
  125. ' tasks = [asyncio.create_task(coro) <span class="hljs-keyword">for</span> coro <span class="hljs-keyword">in</span> ai + mvc]\n' +
  126. ' <span class="hljs-keyword">await</span> asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)\n' +
  127. '\n' +
  128. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">random_controller</span><span class="hljs-params">(id_, moves)</span>:</span>\n' +
  129. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:\n' +
  130. ' d = random.choice(list(D))\n' +
  131. ' moves.put_nowait((id_, d))\n' +
  132. ' <span class="hljs-keyword">await</span> asyncio.sleep(random.triangular(<span class="hljs-number">0.01</span>, <span class="hljs-number">0.65</span>))\n' +
  133. '\n' +
  134. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">human_controller</span><span class="hljs-params">(screen, moves)</span>:</span>\n' +
  135. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:\n' +
  136. ' key_mappings = {<span class="hljs-number">258</span>: D.s, <span class="hljs-number">259</span>: D.n, <span class="hljs-number">260</span>: D.w, <span class="hljs-number">261</span>: D.e}\n' +
  137. ' <span class="hljs-keyword">if</span> d := key_mappings.get(screen.getch()):\n' +
  138. ' moves.put_nowait((<span class="hljs-string">\'*\'</span>, d))\n' +
  139. ' <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.005</span>)\n' +
  140. '\n' +
  141. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">model</span><span class="hljs-params">(moves, state)</span>:</span>\n' +
  142. ' <span class="hljs-keyword">while</span> state[<span class="hljs-string">\'*\'</span>] <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> (state[id_] <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)):\n' +
  143. ' id_, d = <span class="hljs-keyword">await</span> moves.get()\n' +
  144. ' deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}\n' +
  145. ' state[id_] = P((state[id_].x + deltas[d].x) % W, (state[id_].y + deltas[d].y) % H)\n' +
  146. '\n' +
  147. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">view</span><span class="hljs-params">(state, screen)</span>:</span>\n' +
  148. ' offset = P(curses.COLS//<span class="hljs-number">2</span> - W//<span class="hljs-number">2</span>, curses.LINES//<span class="hljs-number">2</span> - H//<span class="hljs-number">2</span>)\n' +
  149. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:\n' +
  150. ' screen.erase()\n' +
  151. ' curses.textpad.rectangle(screen, offset.y-<span class="hljs-number">1</span>, offset.x-<span class="hljs-number">1</span>, offset.y+H, offset.x+W)\n' +
  152. ' <span class="hljs-keyword">for</span> id_, p <span class="hljs-keyword">in</span> state.items():\n' +
  153. ' screen.addstr(offset.y + (p.y - state[<span class="hljs-string">\'*\'</span>].y + H//<span class="hljs-number">2</span>) % H,\n' +
  154. ' offset.x + (p.x - state[<span class="hljs-string">\'*\'</span>].x + W//<span class="hljs-number">2</span>) % W, str(id_))\n' +
  155. ' screen.refresh()\n' +
  156. ' <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.005</span>)\n' +
  157. '\n' +
  158. '<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">\'__main__\'</span>:\n' +
  159. ' curses.wrapper(main)\n';
  160. const CURSES =
  161. '<span class="hljs-comment"># $ pip3 install windows-curses</span>\n' +
  162. '<span class="hljs-keyword">import</span> curses, os\n' +
  163. '<span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> A_REVERSE, KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_ENTER\n' +
  164. '\n' +
  165. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>\n' +
  166. ' ch, first, selected, paths = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, os.listdir()\n' +
  167. ' <span class="hljs-keyword">while</span> ch != ord(<span class="hljs-string">\'q\'</span>):\n' +
  168. ' height, width = screen.getmaxyx()\n' +
  169. ' screen.erase()\n' +
  170. ' <span class="hljs-keyword">for</span> y, filename <span class="hljs-keyword">in</span> enumerate(paths[first : first+height]):\n' +
  171. ' color = A_REVERSE <span class="hljs-keyword">if</span> filename == paths[selected] <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>\n' +
  172. ' screen.addnstr(y, <span class="hljs-number">0</span>, filename, width-<span class="hljs-number">1</span>, color)\n' +
  173. ' ch = screen.getch()\n' +
  174. ' selected += (ch == KEY_DOWN) - (ch == KEY_UP)\n' +
  175. ' selected = max(<span class="hljs-number">0</span>, min(len(paths)-<span class="hljs-number">1</span>, selected))\n' +
  176. ' first += (selected &gt;= first + height) - (selected &lt; first)\n' +
  177. ' <span class="hljs-keyword">if</span> ch <span class="hljs-keyword">in</span> [KEY_LEFT, KEY_RIGHT, KEY_ENTER, ord(<span class="hljs-string">\'\\n\'</span>), ord(<span class="hljs-string">\'\\r\'</span>)]:\n' +
  178. ' new_dir = <span class="hljs-string">\'..\'</span> <span class="hljs-keyword">if</span> ch == KEY_LEFT <span class="hljs-keyword">else</span> paths[selected]\n' +
  179. ' <span class="hljs-keyword">if</span> os.path.isdir(new_dir):\n' +
  180. ' os.chdir(new_dir)\n' +
  181. ' first, selected, paths = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, os.listdir()\n' +
  182. '\n' +
  183. '<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">\'__main__\'</span>:\n' +
  184. ' curses.wrapper(main)\n';
  185. const PROGRESS_BAR =
  186. '<span class="hljs-comment"># $ pip3 install tqdm</span>\n' +
  187. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> tqdm, time\n' +
  188. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> tqdm.tqdm([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], desc=<span class="hljs-string">\'Processing\'</span>):\n' +
  189. '<span class="hljs-meta">... </span> time.sleep(<span class="hljs-number">1</span>)\n' +
  190. 'Processing: 100%|████████████████████| 3/3 [00:03&lt;00:00, 1.00s/it]\n';
  191. const LOGGING_EXAMPLE =
  192. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger = logging.getLogger(<span class="hljs-string">\'my_module\'</span>)\n' +
  193. '<span class="hljs-meta">&gt;&gt;&gt; </span>handler = logging.FileHandler(<span class="hljs-string">\'test.log\'</span>, encoding=<span class="hljs-string">\'utf-8\'</span>)\n' +
  194. '<span class="hljs-meta">&gt;&gt;&gt; </span>handler.setFormatter(logging.Formatter(<span class="hljs-string">\'%(asctime)s %(levelname)s:%(name)s:%(message)s\'</span>))\n' +
  195. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger.addHandler(handler)\n' +
  196. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger.setLevel(<span class="hljs-string">\'DEBUG\'</span>)\n' +
  197. '<span class="hljs-meta">&gt;&gt;&gt; </span>logging.basicConfig()\n' +
  198. '<span class="hljs-meta">&gt;&gt;&gt; </span>logging.root.handlers[<span class="hljs-number">0</span>].setLevel(<span class="hljs-string">\'WARNING\'</span>)\n' +
  199. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger.critical(<span class="hljs-string">\'Running out of disk space.\'</span>)\n' +
  200. 'CRITICAL:my_module:Running out of disk space.\n' +
  201. '<span class="hljs-meta">&gt;&gt;&gt; </span>print(open(<span class="hljs-string">\'test.log\'</span>).read())\n' +
  202. '2023-02-07 23:21:01,430 CRITICAL:my_module:Running out of disk space.\n';
  203. const AUDIO =
  204. '<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> pi, sin\n' +
  205. 'samples_f = (sin(i * <span class="hljs-number">2</span> * pi * <span class="hljs-number">440</span> / <span class="hljs-number">44100</span>) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100_000</span>))\n' +
  206. 'write_to_wav_file(<span class="hljs-string">\'test.wav\'</span>, samples_f)\n';
  207. const MARIO =
  208. '<span class="hljs-keyword">import</span> collections, dataclasses, enum, io, itertools <span class="hljs-keyword">as</span> it, pygame <span class="hljs-keyword">as</span> pg, urllib.request\n' +
  209. '<span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint\n' +
  210. '\n' +
  211. 'P = collections.namedtuple(<span class="hljs-string">\'P\'</span>, <span class="hljs-string">\'x y\'</span>) <span class="hljs-comment"># Position</span>\n' +
  212. 'D = enum.Enum(<span class="hljs-string">\'D\'</span>, <span class="hljs-string">\'n e s w\'</span>) <span class="hljs-comment"># Direction</span>\n' +
  213. 'W, H, MAX_S = <span class="hljs-number">50</span>, <span class="hljs-number">50</span>, P(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>) <span class="hljs-comment"># Width, Height, Max speed</span>\n' +
  214. '\n' +
  215. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>\n' +
  216. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_screen</span><span class="hljs-params">()</span>:</span>\n' +
  217. ' pg.init()\n' +
  218. ' <span class="hljs-keyword">return</span> pg.display.set_mode((W*<span class="hljs-number">16</span>, H*<span class="hljs-number">16</span>))\n' +
  219. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_images</span><span class="hljs-params">()</span>:</span>\n' +
  220. ' url = <span class="hljs-string">\'https://gto76.github.io/python-cheatsheet/web/mario_bros.png\'</span>\n' +
  221. ' img = pg.image.load(io.BytesIO(urllib.request.urlopen(url).read()))\n' +
  222. ' <span class="hljs-keyword">return</span> [img.subsurface(get_rect(x, <span class="hljs-number">0</span>)) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(img.get_width() // <span class="hljs-number">16</span>)]\n' +
  223. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_mario</span><span class="hljs-params">()</span>:</span>\n' +
  224. ' Mario = dataclasses.make_dataclass(<span class="hljs-string">\'Mario\'</span>, <span class="hljs-string">\'rect spd facing_left frame_cycle\'</span>.split())\n' +
  225. ' <span class="hljs-keyword">return</span> Mario(get_rect(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-keyword">False</span>, it.cycle(range(<span class="hljs-number">3</span>)))\n' +
  226. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_tiles</span><span class="hljs-params">()</span>:</span>\n' +
  227. ' border = [(x, y) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(W) <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(H) <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, W-<span class="hljs-number">1</span>] <span class="hljs-keyword">or</span> y <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, H-<span class="hljs-number">1</span>]]\n' +
  228. ' platforms = [(randint(<span class="hljs-number">1</span>, W-<span class="hljs-number">2</span>), randint(<span class="hljs-number">2</span>, H-<span class="hljs-number">2</span>)) <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(W*H // <span class="hljs-number">10</span>)]\n' +
  229. ' <span class="hljs-keyword">return</span> [get_rect(x, y) <span class="hljs-keyword">for</span> x, y <span class="hljs-keyword">in</span> border + platforms]\n' +
  230. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_rect</span><span class="hljs-params">(x, y)</span>:</span>\n' +
  231. ' <span class="hljs-keyword">return</span> pg.Rect(x*<span class="hljs-number">16</span>, y*<span class="hljs-number">16</span>, <span class="hljs-number">16</span>, <span class="hljs-number">16</span>)\n' +
  232. ' run(get_screen(), get_images(), get_mario(), get_tiles())\n' +
  233. '\n' +
  234. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run</span><span class="hljs-params">(screen, images, mario, tiles)</span>:</span>\n' +
  235. ' clock = pg.time.Clock()\n' +
  236. ' pressed = set()\n' +
  237. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">not</span> pg.event.get(pg.QUIT) <span class="hljs-keyword">and</span> clock.tick(<span class="hljs-number">28</span>):\n' +
  238. ' keys = {pg.K_UP: D.n, pg.K_RIGHT: D.e, pg.K_DOWN: D.s, pg.K_LEFT: D.w}\n' +
  239. ' pressed |= {keys.get(e.key) <span class="hljs-keyword">for</span> e <span class="hljs-keyword">in</span> pg.event.get(pg.KEYDOWN)}\n' +
  240. ' pressed -= {keys.get(e.key) <span class="hljs-keyword">for</span> e <span class="hljs-keyword">in</span> pg.event.get(pg.KEYUP)}\n' +
  241. ' update_speed(mario, tiles, pressed)\n' +
  242. ' update_position(mario, tiles)\n' +
  243. ' draw(screen, images, mario, tiles, pressed)\n' +
  244. '\n' +
  245. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_speed</span><span class="hljs-params">(mario, tiles, pressed)</span>:</span>\n' +
  246. ' x, y = mario.spd\n' +
  247. ' x += <span class="hljs-number">2</span> * ((D.e <span class="hljs-keyword">in</span> pressed) - (D.w <span class="hljs-keyword">in</span> pressed))\n' +
  248. ' x += (x &lt; <span class="hljs-number">0</span>) - (x &gt; <span class="hljs-number">0</span>)\n' +
  249. ' y += <span class="hljs-number">1</span> <span class="hljs-keyword">if</span> D.s <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> get_boundaries(mario.rect, tiles) <span class="hljs-keyword">else</span> (D.n <span class="hljs-keyword">in</span> pressed) * <span class="hljs-number">-10</span>\n' +
  250. ' mario.spd = P(x=max(-MAX_S.x, min(MAX_S.x, x)), y=max(-MAX_S.y, min(MAX_S.y, y)))\n' +
  251. '\n' +
  252. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_position</span><span class="hljs-params">(mario, tiles)</span>:</span>\n' +
  253. ' x, y = mario.rect.topleft\n' +
  254. ' n_steps = max(abs(s) <span class="hljs-keyword">for</span> s <span class="hljs-keyword">in</span> mario.spd)\n' +
  255. ' <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n_steps):\n' +
  256. ' mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))\n' +
  257. ' mario.rect.topleft = x, y = x + (mario.spd.x / n_steps), y + (mario.spd.y / n_steps)\n' +
  258. '\n' +
  259. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_boundaries</span><span class="hljs-params">(rect, tiles)</span>:</span>\n' +
  260. ' deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}\n' +
  261. ' <span class="hljs-keyword">return</span> {d <span class="hljs-keyword">for</span> d, delta <span class="hljs-keyword">in</span> deltas.items() <span class="hljs-keyword">if</span> rect.move(delta).collidelist(tiles) != <span class="hljs-number">-1</span>}\n' +
  262. '\n' +
  263. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">stop_on_collision</span><span class="hljs-params">(spd, bounds)</span>:</span>\n' +
  264. ' <span class="hljs-keyword">return</span> P(x=<span class="hljs-number">0</span> <span class="hljs-keyword">if</span> (D.w <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.x &lt; <span class="hljs-number">0</span>) <span class="hljs-keyword">or</span> (D.e <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.x &gt; <span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> spd.x,\n' +
  265. ' y=<span class="hljs-number">0</span> <span class="hljs-keyword">if</span> (D.n <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.y &lt; <span class="hljs-number">0</span>) <span class="hljs-keyword">or</span> (D.s <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.y &gt; <span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> spd.y)\n' +
  266. '\n' +
  267. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen, images, mario, tiles, pressed)</span>:</span>\n' +
  268. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_marios_image_index</span><span class="hljs-params">()</span>:</span>\n' +
  269. ' <span class="hljs-keyword">if</span> D.s <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> get_boundaries(mario.rect, tiles):\n' +
  270. ' <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>\n' +
  271. ' <span class="hljs-keyword">return</span> next(mario.frame_cycle) <span class="hljs-keyword">if</span> {D.w, D.e} &amp; pressed <span class="hljs-keyword">else</span> <span class="hljs-number">6</span>\n' +
  272. ' screen.fill((<span class="hljs-number">85</span>, <span class="hljs-number">168</span>, <span class="hljs-number">255</span>))\n' +
  273. ' mario.facing_left = (D.w <span class="hljs-keyword">in</span> pressed) <span class="hljs-keyword">if</span> {D.w, D.e} &amp; pressed <span class="hljs-keyword">else</span> mario.facing_left\n' +
  274. ' screen.blit(images[get_marios_image_index() + mario.facing_left * <span class="hljs-number">9</span>], mario.rect)\n' +
  275. ' <span class="hljs-keyword">for</span> t <span class="hljs-keyword">in</span> tiles:\n' +
  276. ' screen.blit(images[<span class="hljs-number">18</span> <span class="hljs-keyword">if</span> t.x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, (W-<span class="hljs-number">1</span>)*<span class="hljs-number">16</span>] <span class="hljs-keyword">or</span> t.y <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, (H-<span class="hljs-number">1</span>)*<span class="hljs-number">16</span>] <span class="hljs-keyword">else</span> <span class="hljs-number">19</span>], t)\n' +
  277. ' pg.display.flip()\n' +
  278. '\n' +
  279. '<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">\'__main__\'</span>:\n' +
  280. ' main()\n';
  281. const GROUPBY =
  282. '<span class="hljs-meta">&gt;&gt;&gt; </span>gb = df.groupby(<span class="hljs-string">\'z\'</span>); gb.apply(print)\n' +
  283. ' x y z\n' +
  284. 'a <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span>\n' +
  285. ' x y z\n' +
  286. 'b <span class="hljs-number">4</span> <span class="hljs-number">5</span> <span class="hljs-number">6</span>\n' +
  287. 'c <span class="hljs-number">7</span> <span class="hljs-number">8</span> <span class="hljs-number">6</span>';
  288. const CYTHON_1 =
  289. '<span class="hljs-keyword">cdef</span> &lt;ctype&gt; &lt;var_name&gt; = &lt;obj&gt;\n' +
  290. '<span class="hljs-keyword">cdef</span> &lt;ctype&gt;[n_elements] &lt;var_name&gt; = [&lt;el_1&gt;, &lt;el_2&gt;, ...]\n' +
  291. '<span class="hljs-keyword">cdef</span> &lt;ctype/void&gt; &lt;func_name&gt;(&lt;ctype&gt; &lt;arg_name&gt;): ...\n';
  292. const CYTHON_2 =
  293. '<span class="hljs-keyword">cdef</span> <span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">class_name</span>&gt;:</span>\n' +
  294. ' <span class="hljs-keyword">cdef</span> <span class="hljs-keyword">public</span> &lt;ctype&gt; &lt;attr_name&gt;\n' +
  295. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, &lt;ctype&gt; &lt;arg_name&gt;)</span>:</span>\n' +
  296. ' self.&lt;attr_name&gt; = &lt;arg_name&gt;\n';
  297. const CYTHON_3 =
  298. '<span class="hljs-keyword">cdef</span> <span class="hljs-keyword">enum</span> &lt;enum_name&gt;: &lt;member_name&gt;, &lt;member_name&gt;, ...\n';
  299. const INDEX =
  300. '<li><strong>Only available in the <a href="https://transactions.sendowl.com/products/78175486/4422834F/view">PDF</a>.</strong></li>\n' +
  301. '<li><strong>Ctrl+F / ⌘F is usually sufficient.</strong></li>\n' +
  302. '<li><strong>Searching <code class="python hljs"><span class="hljs-string">\'#&lt;title&gt;\'</span></code> will limit the search to the titles.</strong></li>\n';
  303. const DIAGRAM_1_A =
  304. '+------------------+------------+------------+------------+\n' +
  305. '| | Iterable | Collection | Sequence |\n' +
  306. '+------------------+------------+------------+------------+\n';
  307. const DIAGRAM_1_B =
  308. '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' +
  309. '┃ │ Iterable │ Collection │ Sequence ┃\n' +
  310. '┠──────────────────┼────────────┼────────────┼────────────┨\n' +
  311. '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' +
  312. '┃ dict, set │ ✓ │ ✓ │ ┃\n' +
  313. '┃ iter │ ✓ │ │ ┃\n' +
  314. '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n';
  315. const DIAGRAM_2_A =
  316. '+--------------------+----------+----------+----------+----------+----------+\n' +
  317. '| | Number | Complex | Real | Rational | Integral |\n' +
  318. '+--------------------+----------+----------+----------+----------+----------+\n';
  319. const DIAGRAM_2_B =
  320. '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' +
  321. '┃ │ Number │ Complex │ Real │ Rational │ Integral ┃\n' +
  322. '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' +
  323. '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  324. '┃ fractions.Fraction │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' +
  325. '┃ float │ ✓ │ ✓ │ ✓ │ │ ┃\n' +
  326. '┃ complex │ ✓ │ ✓ │ │ │ ┃\n' +
  327. '┃ decimal.Decimal │ ✓ │ │ │ │ ┃\n' +
  328. '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n';
  329. const DIAGRAM_3_A =
  330. '+---------------+----------+----------+----------+----------+----------+\n';
  331. const DIAGRAM_3_B =
  332. '┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' +
  333. '┃ │ [ !#$%…] │ [a-zA-Z] │ [¼½¾] │ [²³¹] │ [0-9] ┃\n' +
  334. '┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' +
  335. '┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  336. '┃ isalnum() │ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  337. '┃ isnumeric() │ │ │ ✓ │ ✓ │ ✓ ┃\n' +
  338. '┃ isdigit() │ │ │ │ ✓ │ ✓ ┃\n' +
  339. '┃ isdecimal() │ │ │ │ │ ✓ ┃\n' +
  340. '┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n';
  341. const DIAGRAM_4_A =
  342. "+--------------+----------------+----------------+----------------+----------------+\n" +
  343. "| | {<float>} | {<float>:f} | {<float>:e} | {<float>:%} |\n" +
  344. "+--------------+----------------+----------------+----------------+----------------+\n";
  345. const DIAGRAM_4_B =
  346. "┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓\n" +
  347. "┃ │ {&lt;float&gt;} │ {&lt;float&gt;:f} │ {&lt;float&gt;:e} │ {&lt;float&gt;:%} ┃\n" +
  348. "┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨\n" +
  349. "┃ 0.000056789 │ '5.6789e-05' │ '0.000057' │ '5.678900e-05' │ '0.005679%' ┃\n" +
  350. "┃ 0.00056789 │ '0.00056789' │ '0.000568' │ '5.678900e-04' │ '0.056789%' ┃\n" +
  351. "┃ 0.0056789 │ '0.0056789' │ '0.005679' │ '5.678900e-03' │ '0.567890%' ┃\n" +
  352. "┃ 0.056789 │ '0.056789' │ '0.056789' │ '5.678900e-02' │ '5.678900%' ┃\n" +
  353. "┃ 0.56789 │ '0.56789' │ '0.567890' │ '5.678900e-01' │ '56.789000%' ┃\n" +
  354. "┃ 5.6789 │ '5.6789' │ '5.678900' │ '5.678900e+00' │ '567.890000%' ┃\n" +
  355. "┃ 56.789 │ '56.789' │ '56.789000' │ '5.678900e+01' │ '5678.900000%' ┃\n" +
  356. "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n" +
  357. "\n" +
  358. "┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓\n" +
  359. "┃ │ {&lt;float&gt;:.2} │ {&lt;float&gt;:.2f} │ {&lt;float&gt;:.2e} │ {&lt;float&gt;:.2%} ┃\n" +
  360. "┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨\n" +
  361. "┃ 0.000056789 │ '5.7e-05' │ '0.00' │ '5.68e-05' │ '0.01%' ┃\n" +
  362. "┃ 0.00056789 │ '0.00057' │ '0.00' │ '5.68e-04' │ '0.06%' ┃\n" +
  363. "┃ 0.0056789 │ '0.0057' │ '0.01' │ '5.68e-03' │ '0.57%' ┃\n" +
  364. "┃ 0.056789 │ '0.057' │ '0.06' │ '5.68e-02' │ '5.68%' ┃\n" +
  365. "┃ 0.56789 │ '0.57' │ '0.57' │ '5.68e-01' │ '56.79%' ┃\n" +
  366. "┃ 5.6789 │ '5.7' │ '5.68' │ '5.68e+00' │ '567.89%' ┃\n" +
  367. "┃ 56.789 │ '5.7e+01' │ '56.79' │ '5.68e+01' │ '5678.90%' ┃\n" +
  368. "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n";
  369. const DIAGRAM_5_A =
  370. "+--------------+----------------+----------------+----------------+----------------+\n" +
  371. "| | {<float>:.2} | {<float>:.2f} | {<float>:.2e} | {<float>:.2%} |\n" +
  372. "+--------------+----------------+----------------+----------------+----------------+\n";
  373. const DIAGRAM_6_A =
  374. '+------------+------------+------------+------------+--------------+\n' +
  375. '| | Iterable | Collection | Sequence | abc.Sequence |\n' +
  376. '+------------+------------+------------+------------+--------------+\n';
  377. const DIAGRAM_6_B =
  378. '┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓\n' +
  379. '┃ │ Iterable │ Collection │ Sequence │ abc.Sequence ┃\n' +
  380. '┠────────────┼────────────┼────────────┼────────────┼──────────────┨\n' +
  381. '┃ iter() │ ! │ ! │ ✓ │ ✓ ┃\n' +
  382. '┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  383. '┃ len() │ │ ! │ ! │ ! ┃\n' +
  384. '┃ getitem() │ │ │ ! │ ! ┃\n' +
  385. '┃ reversed() │ │ │ ✓ │ ✓ ┃\n' +
  386. '┃ index() │ │ │ │ ✓ ┃\n' +
  387. '┃ count() │ │ │ │ ✓ ┃\n' +
  388. '┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n';
  389. const DIAGRAM_7_A =
  390. 'BaseException\n' +
  391. ' +-- SystemExit';
  392. const DIAGRAM_7_B =
  393. "BaseException\n" +
  394. " ├── SystemExit <span class='hljs-comment'># Raised by the sys.exit() function.</span>\n" +
  395. " ├── KeyboardInterrupt <span class='hljs-comment'># Raised when the user hits the interrupt key (ctrl-c).</span>\n" +
  396. " └── Exception <span class='hljs-comment'># User-defined exceptions should be derived from this class.</span>\n" +
  397. " ├── ArithmeticError <span class='hljs-comment'># Base class for arithmetic errors such as ZeroDivisionError.</span>\n" +
  398. " ├── AssertionError <span class='hljs-comment'># Raised by `assert &lt;exp&gt;` if expression returns false value.</span>\n" +
  399. " ├── AttributeError <span class='hljs-comment'># Raised when object doesn't have requested attribute/method.</span>\n" +
  400. " ├── EOFError <span class='hljs-comment'># Raised by input() when it hits an end-of-file condition.</span>\n" +
  401. " ├── LookupError <span class='hljs-comment'># Base class for errors when a collection can't find an item.</span>\n" +
  402. " │ ├── IndexError <span class='hljs-comment'># Raised when a sequence index is out of range.</span>\n" +
  403. " │ └── KeyError <span class='hljs-comment'># Raised when a dictionary key or set element is missing.</span>\n" +
  404. " ├── MemoryError <span class='hljs-comment'># Out of memory. May be too late to start deleting variables.</span>\n" +
  405. " ├── NameError <span class='hljs-comment'># Raised when nonexistent name (variable/func/class) is used.</span>\n" +
  406. " │ └── UnboundLocalError <span class='hljs-comment'># Raised when local name is used before it's being defined.</span>\n" +
  407. " ├── OSError <span class='hljs-comment'># Errors such as FileExistsError/TimeoutError (see #Open).</span>\n" +
  408. " │ └── ConnectionError <span class='hljs-comment'># Errors such as BrokenPipeError/ConnectionAbortedError.</span>\n" +
  409. " ├── RuntimeError <span class='hljs-comment'># Raised by errors that don't fall into other categories.</span>\n" +
  410. " │ ├── NotImplementedEr… <span class='hljs-comment'># Can be raised by abstract methods or by unfinished code.</span>\n" +
  411. " │ └── RecursionError <span class='hljs-comment'># Raised when the maximum recursion depth is exceeded.</span>\n" +
  412. " ├── StopIteration <span class='hljs-comment'># Raised when an empty iterator is passed to next().</span>\n" +
  413. " ├── TypeError <span class='hljs-comment'># When an argument of the wrong type is passed to function.</span>\n" +
  414. " └── ValueError <span class='hljs-comment'># When argument has the right type but inappropriate value.</span>\n";
  415. const DIAGRAM_8_A =
  416. '+-----------+------------+------------+------------+\n' +
  417. '| | List | Set | Dict |\n' +
  418. '+-----------+------------+------------+------------+\n';
  419. const DIAGRAM_8_B =
  420. '┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' +
  421. '┃ │ List │ Set │ Dict ┃\n' +
  422. '┠───────────┼────────────┼────────────┼────────────┨\n' +
  423. '┃ getitem() │ IndexError │ │ KeyError ┃\n' +
  424. '┃ pop() │ IndexError │ KeyError │ KeyError ┃\n' +
  425. '┃ remove() │ ValueError │ KeyError │ ┃\n' +
  426. '┃ index() │ ValueError │ │ ┃\n' +
  427. '┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n';
  428. const DIAGRAM_9_A =
  429. '+------------------+--------------+--------------+--------------+\n' +
  430. '| | excel | excel-tab | unix |\n' +
  431. '+------------------+--------------+--------------+--------------+\n';
  432. const DIAGRAM_9_B =
  433. "┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓\n" +
  434. "┃ │ excel │ excel-tab │ unix ┃\n" +
  435. "┠──────────────────┼──────────────┼──────────────┼──────────────┨\n" +
  436. "┃ delimiter │ ',' │ '\\t' │ ',' ┃\n" +
  437. "┃ lineterminator │ '\\r\\n' │ '\\r\\n' │ '\\n' ┃\n" +
  438. "┃ quotechar │ '\"' │ '\"' │ '\"' ┃\n" +
  439. "┃ escapechar │ None │ None │ None ┃\n" +
  440. "┃ doublequote │ True │ True │ True ┃\n" +
  441. "┃ quoting │ 0 │ 0 │ 1 ┃\n" +
  442. "┃ skipinitialspace │ False │ False │ False ┃\n" +
  443. "┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n";
  444. const DIAGRAM_95_A =
  445. '+------------+--------------+----------+----------------------------------+\n' +
  446. '| Dialect | pip3 install | import | Dependencies |\n' +
  447. '+------------+--------------+----------+----------------------------------+\n';
  448. const DIAGRAM_95_B =
  449. '┏━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n' +
  450. '┃ Dialect │ pip3 install │ import │ Dependencies ┃\n' +
  451. '┠────────────┼──────────────┼──────────┼──────────────────────────────────┨\n' +
  452. '┃ mysql │ mysqlclient │ MySQLdb │ www.pypi.org/project/mysqlclient ┃\n' +
  453. '┃ postgresql │ psycopg2 │ psycopg2 │ www.pypi.org/project/psycopg2 ┃\n' +
  454. '┃ mssql │ pyodbc │ pyodbc │ www.pypi.org/project/pyodbc ┃\n' +
  455. '┃ oracle │ oracledb │ oracledb │ www.pypi.org/project/oracledb ┃\n' +
  456. '┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n';
  457. const DIAGRAM_10_A =
  458. '+-------------+-------------+\n' +
  459. '| Classes | Metaclasses |\n' +
  460. '+-------------+-------------|\n' +
  461. '| MyClass <-- MyMetaClass |\n';
  462. const DIAGRAM_10_B =
  463. '┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
  464. '┃ Classes │ Metaclasses ┃\n' +
  465. '┠─────────────┼─────────────┨\n' +
  466. '┃ MyClass ←──╴MyMetaClass ┃\n' +
  467. '┃ │ ↑ ┃\n' +
  468. '┃ object ←─────╴type ←╮ ┃\n' +
  469. '┃ │ │ ╰──╯ ┃\n' +
  470. '┃ str ←─────────╯ ┃\n' +
  471. '┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛\n';
  472. const DIAGRAM_11_A =
  473. '+-------------+-------------+\n' +
  474. '| Classes | Metaclasses |\n' +
  475. '+-------------+-------------|\n' +
  476. '| MyClass | MyMetaClass |\n';
  477. const DIAGRAM_11_B =
  478. '┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
  479. '┃ Classes │ Metaclasses ┃\n' +
  480. '┠─────────────┼─────────────┨\n' +
  481. '┃ MyClass │ MyMetaClass ┃\n' +
  482. '┃ ↑ │ ↑ ┃\n' +
  483. '┃ object╶─────→ type ┃\n' +
  484. '┃ ↓ │ ┃\n' +
  485. '┃ str │ ┃\n' +
  486. '┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛\n';
  487. const DIAGRAM_115_A =
  488. '+--------------+------------+-------------------------------+-------+------+\n' +
  489. '| pip3 install | Target | How to run | Lines | Live |\n' +
  490. '+--------------+------------+-------------------------------+-------+------+\n';
  491. const DIAGRAM_115_B =
  492. '┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━┓\n' +
  493. '┃ pip3 install │ Target │ How to run │ Lines │ Live ┃\n' +
  494. '┠──────────────┼────────────┼───────────────────────────────┼───────┼──────┨\n' +
  495. '┃ pyinstrument │ CPU │ pyinstrument test.py │ × │ × ┃\n' +
  496. '┃ py-spy │ CPU │ py-spy top -- python3 test.py │ × │ ✓ ┃\n' +
  497. '┃ scalene │ CPU+Memory │ scalene test.py │ ✓ │ × ┃\n' +
  498. '┃ memray │ Memory │ memray run --live test.py │ ✓ │ ✓ ┃\n' +
  499. '┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━┛\n';
  500. const DIAGRAM_12_A =
  501. '+-----------+-----------+------+-----------+\n' +
  502. '| sampwidth | min | zero | max |\n' +
  503. '+-----------+-----------+------+-----------+\n';
  504. const DIAGRAM_12_B =
  505. '┏━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━┯━━━━━━━━━━━┓\n' +
  506. '┃ sampwidth │ min │ zero │ max ┃\n' +
  507. '┠───────────┼───────────┼──────┼───────────┨\n' +
  508. '┃ 1 │ 0 │ 128 │ 255 ┃\n' +
  509. '┃ 2 │ -32768 │ 0 │ 32767 ┃\n' +
  510. '┃ 3 │ -8388608 │ 0 │ 8388607 ┃\n' +
  511. '┗━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━┷━━━━━━━━━━━┛\n';
  512. const DIAGRAM_13_A =
  513. '| sr.apply(…) | 5 | sum 5 | s 5 |';
  514. const DIAGRAM_13_B =
  515. "┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  516. "┃ │ 'sum' │ ['sum'] │ {'s': 'sum'} ┃\n" +
  517. "┠───────────────┼─────────────┼─────────────┼───────────────┨\n" +
  518. "┃ sr.apply(…) │ 5 │ sum 5 │ s 5 ┃\n" +
  519. "┃ sr.agg(…) │ │ │ ┃\n" +
  520. "┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n" +
  521. "\n" +
  522. "┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  523. "┃ │ 'rank' │ ['rank'] │ {'r': 'rank'} ┃\n" +
  524. "┠───────────────┼─────────────┼─────────────┼───────────────┨\n" +
  525. "┃ sr.apply(…) │ │ rank │ ┃\n" +
  526. "┃ sr.agg(…) │ x 1 │ x 1 │ r x 1 ┃\n" +
  527. "┃ │ y 2 │ y 2 │ y 2 ┃\n" +
  528. "┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n";
  529. const DIAGRAM_14_A =
  530. "| | 'rank' | ['rank'] | {'r': 'rank'} |";
  531. const DIAGRAM_15_A =
  532. '+------------------------+---------------+------------+------------+--------------------------+';
  533. const DIAGRAM_15_B =
  534. "┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n" +
  535. "┃ │ 'outer' │ 'inner' │ 'left' │ Description ┃\n" +
  536. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  537. "┃ l.merge(r, on='y', │ x y z │ x y z │ x y z │ Merges on column if 'on' ┃\n" +
  538. "┃ how=…) │ 0 1 2 . │ 3 4 5 │ 1 2 . │ or 'left/right_on' are ┃\n" +
  539. "┃ │ 1 3 4 5 │ │ 3 4 5 │ set, else on shared cols.┃\n" +
  540. "┃ │ 2 . 6 7 │ │ │ Uses 'inner' by default. ┃\n" +
  541. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  542. "┃ l.join(r, lsuffix='l', │ x yl yr z │ │ x yl yr z │ Merges on row keys. ┃\n" +
  543. "┃ rsuffix='r', │ a 1 2 . . │ x yl yr z │ 1 2 . . │ Uses 'left' by default. ┃\n" +
  544. "┃ how=…) │ b 3 4 4 5 │ 3 4 4 5 │ 3 4 4 5 │ If r is a Series, it is ┃\n" +
  545. "┃ │ c . . 6 7 │ │ │ treated as a column. ┃\n" +
  546. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  547. "┃ pd.concat([l, r], │ x y z │ y │ │ Adds rows at the bottom. ┃\n" +
  548. "┃ axis=0, │ a 1 2 . │ 2 │ │ Uses 'outer' by default. ┃\n" +
  549. "┃ join=…) │ b 3 4 . │ 4 │ │ A Series is treated as a ┃\n" +
  550. "┃ │ b . 4 5 │ 4 │ │ column. To add a row use ┃\n" +
  551. "┃ │ c . 6 7 │ 6 │ │ pd.concat([l, DF([sr])]).┃\n" +
  552. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  553. "┃ pd.concat([l, r], │ x y y z │ │ │ Adds columns at the ┃\n" +
  554. "┃ axis=1, │ a 1 2 . . │ x y y z │ │ right end. Uses 'outer' ┃\n" +
  555. "┃ join=…) │ b 3 4 4 5 │ 3 4 4 5 │ │ by default. A Series is ┃\n" +
  556. "┃ │ c . . 6 7 │ │ │ treated as a column. ┃\n" +
  557. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  558. "┃ l.combine_first(r) │ x y z │ │ │ Adds missing rows and ┃\n" +
  559. "┃ │ a 1 2 . │ │ │ columns. Also updates ┃\n" +
  560. "┃ │ b 3 4 5 │ │ │ items that contain NaN. ┃\n" +
  561. "┃ │ c . 6 7 │ │ │ Argument r must be a DF. ┃\n" +
  562. "┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n";
  563. const DIAGRAM_16_A =
  564. '| df.apply(…) | x 4 | x y | x 4 |';
  565. const DIAGRAM_16_B =
  566. "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  567. "┃ │ 'sum' │ ['sum'] │ {'x': 'sum'} ┃\n" +
  568. "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" +
  569. "┃ df.apply(…) │ x 4 │ x y │ x 4 ┃\n" +
  570. "┃ df.agg(…) │ y 6 │ sum 4 6 │ ┃\n" +
  571. "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n" +
  572. "\n" +
  573. "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  574. "┃ │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" +
  575. "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" +
  576. "┃ df.apply(…) │ │ x y │ ┃\n" +
  577. "┃ df.agg(…) │ x y │ rank rank │ x ┃\n" +
  578. "┃ df.transform(…) │ a 1 1 │ a 1 1 │ a 1 ┃\n" +
  579. "┃ │ b 2 2 │ b 2 2 │ b 2 ┃\n" +
  580. "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n";
  581. const DIAGRAM_17_A =
  582. "| | 'rank' | ['rank'] | {'x': 'rank'} |";
  583. const DIAGRAM_18_A =
  584. '| gb.agg(…) | x y | | x y | |';
  585. const DIAGRAM_18_B =
  586. "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  587. "┃ │ 'sum' │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" +
  588. "┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" +
  589. "┃ gb.agg(…) │ x y │ │ x y │ ┃\n" +
  590. "┃ │ z │ x y │ rank rank │ x ┃\n" +
  591. "┃ │ 3 1 2 │ a 1 1 │ a 1 1 │ a 1 ┃\n" +
  592. "┃ │ 6 11 13 │ b 1 1 │ b 1 1 │ b 1 ┃\n" +
  593. "┃ │ │ c 2 2 │ c 2 2 │ c 2 ┃\n" +
  594. "┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" +
  595. "┃ gb.transform(…) │ x y │ x y │ │ ┃\n" +
  596. "┃ │ a 1 2 │ a 1 1 │ │ ┃\n" +
  597. "┃ │ b 11 13 │ b 1 1 │ │ ┃\n" +
  598. "┃ │ c 11 13 │ c 2 2 │ │ ┃\n" +
  599. "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n";
  600. const MENU = '<a href="https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md">Download text file</a>, <a href="https://transactions.sendowl.com/products/78175486/4422834F/view">Buy PDF</a>, <a href="https://github.com/gto76/python-cheatsheet">Fork me on GitHub</a>, <a href="https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions">Check out FAQ</a> or <a href="index.html?theme=dark3">Switch to dark theme</a>.\n';
  601. const DARK_THEME_SCRIPT =
  602. '<script>\n' +
  603. ' // Changes the image and link to theme if URL ends with "index.html?theme=dark". \n' +
  604. ' if (window.location.search.search(/[?&]theme=dark/) !== -1) {\n' +
  605. '\n' +
  606. ' var link_to_theme = document.createElement("a")\n' +
  607. ' link_to_theme.href = "index.html"\n' +
  608. ' link_to_theme.text = "Switch to light theme"\n' +
  609. ' document.getElementsByClassName("banner")[0].firstChild.children[4].replaceWith(link_to_theme)\n' +
  610. '\n' +
  611. ' var img_dark = document.createElement("img");\n' +
  612. ' img_dark.src = "web/image_orig_blue6.png";\n' +
  613. ' img_dark.alt = "Monthy Python";\n' +
  614. ' if ((window.location.search.search(/[?&]theme=dark2/) !== -1) ||\n' +
  615. ' (window.location.search.search(/[?&]theme=dark3/) !== -1)) {\n' +
  616. ' img_dark.style = "width: 910px;";\n' +
  617. ' } else {\n' +
  618. ' img_dark.style = "width: 960px;";\n' +
  619. ' }\n' +
  620. ' document.getElementsByClassName("banner")[1].firstChild.replaceWith(img_dark);\n' +
  621. ' }\n' +
  622. '</script>';
  623. function main() {
  624. const html = getMd();
  625. initDom(html);
  626. modifyPage();
  627. var template = readFile('web/template.html');
  628. template = updateDate(template);
  629. const tokens = template.split('<div id=main_container></div>');
  630. const text = `${tokens[0]} ${document.body.innerHTML} ${tokens[1]}`;
  631. writeToFile('index.html', text);
  632. }
  633. function getMd() {
  634. var readme = readFile('README.md');
  635. var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
  636. var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
  637. var readme = readme.replace("#dataframe-plot-encode-decode", "#dataframeplotencodedecode");
  638. const converter = new showdown.Converter();
  639. return converter.makeHtml(readme);
  640. }
  641. function initDom(html) {
  642. const { JSDOM } = jsdom;
  643. const dom = new JSDOM(html);
  644. const $ = (require('jquery'))(dom.window);
  645. global.$ = $;
  646. global.document = dom.window.document;
  647. }
  648. function modifyPage() {
  649. changeMenu();
  650. addDarkThemeScript();
  651. removeOrigToc();
  652. addToc();
  653. insertLinks();
  654. unindentBanner();
  655. updateDiagrams();
  656. highlightCode();
  657. fixPandasDiagram();
  658. removePlotImages();
  659. fixABCSequenceDiv();
  660. fixStructFormatDiv();
  661. }
  662. function changeMenu() {
  663. $('sup').first().html(MENU)
  664. }
  665. function addDarkThemeScript() {
  666. $('#main').before(DARK_THEME_SCRIPT);
  667. }
  668. function removeOrigToc() {
  669. const headerContents = $('#contents');
  670. const contentsList = headerContents.next();
  671. headerContents.remove();
  672. contentsList.remove();
  673. }
  674. function addToc() {
  675. const nodes = $.parseHTML(TOC);
  676. $('#main').before(nodes);
  677. }
  678. function insertLinks() {
  679. $('h2').each(function() {
  680. const aId = $(this).attr('id');
  681. const text = $(this).text();
  682. const line = `<a href="#${aId}" name="${aId}">#</a>${text}`;
  683. $(this).html(line);
  684. });
  685. }
  686. function unindentBanner() {
  687. const montyImg = $('img').first();
  688. montyImg.parent().addClass('banner');
  689. const downloadPraragrapth = $('p').first();
  690. downloadPraragrapth.addClass('banner');
  691. }
  692. function updateDiagrams() {
  693. $(`code:contains(${DIAGRAM_1_A})`).html(DIAGRAM_1_B);
  694. $(`code:contains(${DIAGRAM_2_A})`).html(DIAGRAM_2_B);
  695. $(`code:contains(${DIAGRAM_3_A})`).html(DIAGRAM_3_B);
  696. $(`code:contains(${DIAGRAM_4_A})`).html(DIAGRAM_4_B);
  697. $(`code:contains(${DIAGRAM_5_A})`).parent().remove();
  698. $(`code:contains(${DIAGRAM_6_A})`).html(DIAGRAM_6_B);
  699. $(`code:contains(${DIAGRAM_7_A})`).html(DIAGRAM_7_B);
  700. $(`code:contains(${DIAGRAM_8_A})`).html(DIAGRAM_8_B);
  701. $(`code:contains(${DIAGRAM_9_A})`).html(DIAGRAM_9_B);
  702. $(`code:contains(${DIAGRAM_95_A})`).html(DIAGRAM_95_B);
  703. $(`code:contains(${DIAGRAM_10_A})`).html(DIAGRAM_10_B);
  704. $(`code:contains(${DIAGRAM_11_A})`).html(DIAGRAM_11_B);
  705. $(`code:contains(${DIAGRAM_115_A})`).html(DIAGRAM_115_B);
  706. $(`code:contains(${DIAGRAM_12_A})`).html(DIAGRAM_12_B).removeClass("text").removeClass("language-text").addClass("python");
  707. $(`code:contains(${DIAGRAM_13_A})`).html(DIAGRAM_13_B).removeClass("text").removeClass("language-text").addClass("python");
  708. $(`code:contains(${DIAGRAM_14_A})`).parent().remove();
  709. $(`code:contains(${DIAGRAM_15_A})`).html(DIAGRAM_15_B).removeClass("text").removeClass("language-text").addClass("python");
  710. $(`code:contains(${DIAGRAM_16_A})`).html(DIAGRAM_16_B).removeClass("text").removeClass("language-text").addClass("python");
  711. $(`code:contains(${DIAGRAM_17_A})`).parent().remove();
  712. $(`code:contains(${DIAGRAM_18_A})`).html(DIAGRAM_18_B).removeClass("text").removeClass("language-text").addClass("python");
  713. }
  714. function highlightCode() {
  715. changeCodeLanguages();
  716. $('code').each(function(index) {
  717. hljs.highlightBlock(this);
  718. });
  719. fixClasses();
  720. fixHighlights();
  721. preventPageBreaks();
  722. fixPageBreaksFile();
  723. fixPageBreaksStruct();
  724. insertPageBreaks();
  725. }
  726. function changeCodeLanguages() {
  727. setApaches(['<D>', '<T>', '<DT>', '<TD>', '<a>', '<n>']);
  728. $('code').not('.python').not('.text').not('.bash').not('.apache').addClass('python');
  729. $('code:contains(<el> = <2d>[row_index, col_index])').removeClass().addClass('bash');
  730. $('code:contains(<1d_array> = <2d>[row_indices, col_indices])').removeClass().addClass('bash');
  731. $('code:contains(<2d_bools> = <2d> > <el/1d/2d>)').removeClass().addClass('bash');
  732. $('code.perl').removeClass().addClass('python');
  733. }
  734. function setApaches(elements) {
  735. for (el of elements) {
  736. $(`code:contains(${el})`).addClass('apache');
  737. }
  738. }
  739. function fixClasses() {
  740. // Changes class="hljs-keyword" to class="hljs-title" of 'class' keyword.
  741. $('.hljs-class').filter(':contains(class \')').find(':first-child').removeClass('hljs-keyword').addClass('hljs-title')
  742. }
  743. function fixHighlights() {
  744. $(`code:contains(<int> = ±0b<bin>)`).html(BIN_HEX);
  745. $(`code:contains(@lru_cache(maxsize=None))`).html(LRU_CACHE);
  746. $(`code:contains(@debug(print_result=True))`).html(PARAMETRIZED_DECORATOR);
  747. $(`code:contains(print/str/repr([<obj>]))`).html(REPR_USE_CASES);
  748. $(`code:contains((self, a=None):)`).html(CONSTRUCTOR_OVERLOADING);
  749. $(`code:contains(make_dataclass(\'<class_name>\')`).html(DATACLASS);
  750. $(`code:contains(shutil.copy)`).html(SHUTIL_COPY);
  751. $(`code:contains(os.rename)`).html(OS_RENAME);
  752. $(`code:contains(\'<n>s\')`).html(STRUCT_FORMAT);
  753. $(`code:contains(match <object/expression>:)`).html(MATCH);
  754. $(`code:contains(>>> match Path)`).html(MATCH_EXAMPLE);
  755. $(`code:contains(import asyncio, collections, curses, curses.textpad, enum, random)`).html(COROUTINES);
  756. $(`code:contains(import curses, os)`).html(CURSES);
  757. $(`code:contains(pip3 install tqdm)`).html(PROGRESS_BAR);
  758. $(`code:contains(>>> logging.basicConfig()`).html(LOGGING_EXAMPLE);
  759. $(`code:contains(samples_f = (sin(i *)`).html(AUDIO);
  760. $(`code:contains(collections, dataclasses, enum, io, itertools)`).html(MARIO);
  761. $(`code:contains(>>> gb = df.groupby)`).html(GROUPBY);
  762. $(`code:contains(cdef <ctype> <var_name> = <obj>)`).html(CYTHON_1);
  763. $(`code:contains(cdef class <class_name>:)`).html(CYTHON_2);
  764. $(`code:contains(cdef enum <enum_name>: <member_name>, <member_name>, ...)`).html(CYTHON_3);
  765. $(`ul:contains(Only available in)`).html(INDEX);
  766. }
  767. function preventPageBreaks() {
  768. $(':header').each(function(index) {
  769. var el = $(this)
  770. var untilPre = el.nextUntil('pre')
  771. var untilH2 = el.nextUntil('h2')
  772. if ((untilPre.length < untilH2.length) || el.prop('tagName') === 'H1') {
  773. untilPre.add(el).next().add(el).wrapAll("<div></div>");
  774. } else {
  775. untilH2.add(el).wrapAll("<div></div>");
  776. }
  777. });
  778. }
  779. function fixPageBreaksFile() {
  780. const modesDiv = $('#file').parent().parent().parent()
  781. move(modesDiv, 'file')
  782. move(modesDiv, 'exceptions-1')
  783. }
  784. function fixPageBreaksStruct() {
  785. const formatDiv = $('#floatingpointtypesstructalwaysusesstandardsizes').parent().parent().parent().parent()
  786. move(formatDiv, 'floatingpointtypesstructalwaysusesstandardsizes')
  787. move(formatDiv, 'integertypesuseacapitalletterforunsignedtypeminimumandstandardsizesareinbrackets')
  788. move(formatDiv, 'forstandardsizesstartformatstringwith')
  789. }
  790. function move(anchor_el, el_id) {
  791. const el = $('#'+el_id).parent()
  792. anchor_el.after(el)
  793. }
  794. function insertPageBreaks() {
  795. insertPageBreakBefore('#decorator')
  796. // insertPageBreakBefore('#print')
  797. }
  798. function insertPageBreakBefore(an_id) {
  799. $('<div class="pagebreak"></div>').insertBefore($(an_id).parent())
  800. }
  801. function fixPandasDiagram() {
  802. const diagram_15 = '┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━┓';
  803. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(and)").after("and");
  804. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(as)").after("as");
  805. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(is)").after("is");
  806. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(if)").after("if");
  807. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(or)").after("or");
  808. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(else)").after("else");
  809. $(`code:contains(${diagram_15})`).find(".hljs-keyword").remove();
  810. }
  811. function removePlotImages() {
  812. $('img[alt="Covid Deaths"]').remove();
  813. $('img[alt="Covid Cases"]').remove();
  814. }
  815. function fixABCSequenceDiv() {
  816. $('#abcsequence').parent().insertBefore($('#tableofrequiredandautomaticallyavailablespecialmethods').parent())
  817. }
  818. function fixStructFormatDiv() {
  819. const div = $('#format-2').parent()
  820. $('#format-2').insertBefore(div)
  821. $('#forstandardtypesizesandmanualalignmentpaddingstartformatstringwith').parent().insertBefore(div)
  822. }
  823. function updateDate(template) {
  824. const date = new Date();
  825. const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'});
  826. template = template.replace('May 20, 2021', date_str);
  827. template = template.replace('May 20, 2021', date_str);
  828. return template;
  829. }
  830. // UTIL
  831. function readFile(filename) {
  832. try {
  833. return fs.readFileSync(filename, 'utf8');
  834. } catch(e) {
  835. console.error('Error:', e.stack);
  836. }
  837. }
  838. function writeToFile(filename, text) {
  839. try {
  840. return fs.writeFileSync(filename, text, 'utf8');
  841. } catch(e) {
  842. console.error('Error:', e.stack);
  843. }
  844. }
  845. main();