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.

1025 lines
84 KiB

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