From ca15335ef238e061eb195db5a9ae7498d39b78f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Mar 2021 23:34:10 +0100 Subject: [PATCH 001/721] Math, CSV, SQLite, Threading, NumPy, Synthesizer --- README.md | 54 ++++++++++++++++++++++++++--------------------------- index.html | 55 ++++++++++++++++++++++++++---------------------------- parse.js | 35 +++++++++------------------------- 3 files changed, 61 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index 1ea48ce7f..6909f1fa0 100644 --- a/README.md +++ b/README.md @@ -500,7 +500,7 @@ Numbers ### Math ```python from math import e, pi, inf, nan, isinf, isnan -from math import cos, acos, sin, asin, tan, atan, degrees, radians +from math import cos, sin, tan, acos, asin, atan, degrees, radians from math import log, log10, log2 ``` @@ -599,7 +599,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary ``` * **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means the second pass in case of time jumping back for one hour.** -* **`' = resolve_imaginary()'` fixes DTs that fall into the missing hour.** +* **`' = resolve_imaginary()'` fixes DTs that fall into missing hour.** ### Now ```python @@ -1782,7 +1782,7 @@ import csv = next() # Returns next row as a list of strings. = list() # Returns list of remaining rows. ``` -* **File must be opened with `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** +* **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** ### Write ```python @@ -1790,7 +1790,7 @@ import csv .writerow() # Encodes objects using `str()`. .writerows() # Appends multiple rows. ``` -* **File must be opened with `'newline=""'` argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!** +* **File must be opened with a `'newline=""'` argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!** ### Parameters * **`'dialect'` - Master parameter that sets the default values.** @@ -1805,15 +1805,15 @@ import csv ### Dialects ```text +------------------+--------------+--------------+--------------+ -| | excel | excel-tab | unix | +| | excel | excel-tab | unix | +------------------+--------------+--------------+--------------+ -| delimiter | ',' | '\t' | ',' | -| quotechar | '"' | '"' | '"' | -| doublequote | True | True | True | -| skipinitialspace | False | False | False | -| lineterminator | '\r\n' | '\r\n' | '\n' | -| quoting | 0 | 0 | 1 | -| escapechar | None | None | None | +| delimiter | ',' | '\t' | ',' | +| quotechar | '"' | '"' | '"' | +| doublequote | True | True | True | +| skipinitialspace | False | False | False | +| lineterminator | '\r\n' | '\r\n' | '\n' | +| quoting | 0 | 0 | 1 | +| escapechar | None | None | None | +------------------+--------------+--------------+--------------+ ``` @@ -1879,10 +1879,10 @@ with : ```python >>> conn = sqlite3.connect('test.db') ->>> conn.execute('create table person (person_id integer primary key, name, height)') ->>> conn.execute('insert into person values (null, ?, ?)', ('Jean-Luc', 187)).lastrowid +>>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)') +>>> conn.execute('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid 1 ->>> conn.execute('select * from person').fetchall() +>>> conn.execute('SELECT * FROM person').fetchall() [(1, 'Jean-Luc', 187)] ``` @@ -2087,7 +2087,7 @@ from concurrent.futures import ThreadPoolExecutor ```python = ThreadPoolExecutor(max_workers=None) # Or: `with ThreadPoolExecutor() as : …` -.shutdown(wait=True) # Gets called at the end of 'with' block. +.shutdown(wait=True) # Blocks until all threads finish executing. ``` ```python @@ -2542,7 +2542,7 @@ duration = perf_counter() - start_time ### Timing a Snippet ```python >>> from timeit import timeit ->>> timeit('"".join(str(i) for i in range(100))', +>>> timeit("''.join(str(i) for i in range(100))", ... number=10000, globals=globals(), setup='pass') 0.34986 ``` @@ -2623,24 +2623,22 @@ indexes = .argmin(axis) ### Indexing ```bash - = <2d_array>[0, 0] # First element. -<1d_view> = <2d_array>[0] # First row. -<1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. -<3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1. + = <2d_array>[row_index, column_index] +<1d_view> = <2d_array>[row_index] +<1d_view> = <2d_array>[:, column_index] ``` ```bash -<1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] -<2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] +<1d_array> = <2d_array>[row_indexes, column_indexes] +<2d_array> = <2d_array>[row_indexes] +<2d_array> = <2d_array>[:, column_indexes] ``` ```bash -<2d_bools> = <2d_array> > 0 +<2d_bools> = <2d_array> ><== <1d_array> = <2d_array>[<2d_bools>] ``` -* **If row and column indexes differ in shape, they are combined with broadcasting.** - ### Broadcasting **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** @@ -2899,8 +2897,8 @@ Synthesizer #### Plays Popcorn by Gershon Kingsley: ```python # $ pip3 install simpleaudio -import simpleaudio, math, struct -from itertools import chain, repeat +import math, struct, simpleaudio +from itertools import repeat, chain F = 44100 P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,' P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,' diff --git a/index.html b/index.html index 0acc54475..68b79e81d 100644 --- a/index.html +++ b/index.html @@ -606,7 +606,7 @@

Math

from math import e, pi, inf, nan, isinf, isnan
-from math import cos, acos, sin, asin, tan, atan, degrees, radians
+from math import cos, sin, tan, acos, asin, atan, degrees, radians
 from math import log, log10, log2
 
@@ -681,7 +681,7 @@
  • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
  • 'fold=1' means the second pass in case of time jumping back for one hour.
  • -
  • '<DTa> = resolve_imaginary(<DTa>)' fixes DTs that fall into the missing hour.
  • +
  • '<DTa> = resolve_imaginary(<DTa>)' fixes DTs that fall into missing hour.

Now

<D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
 <DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
@@ -1626,7 +1626,7 @@
 
    -
  • File must be opened with 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
  • +
  • File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!

Write

<writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
 <writer>.writerow(<collection>)     # Encodes objects using `str(<el>)`.
@@ -1634,7 +1634,7 @@
 
    -
  • File must be opened with 'newline=""' argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!
  • +
  • File must be opened with a 'newline=""' argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!

Parameters

  • 'dialect' - Master parameter that sets the default values.
  • @@ -1646,15 +1646,15 @@
  • 'quoting' - Controls the amount of quoting: 0 - as necessary, 1 - all.
  • 'escapechar' - Character for escaping 'quotechar' if 'doublequote' is False.

Dialects

┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
-┃                  │     excel    │   excel-tab  │     unix     ┃
+┃                  │    excel     │   excel-tab  │     unix     ┃
 ┠──────────────────┼──────────────┼──────────────┼──────────────┨
-┃ delimiter        │       ','    │      '\t'    │       ','    ┃
-┃ quotechar        │       '"'    │       '"'    │       '"'    ┃
-┃ doublequote      │      True    │      True    │      True    ┃
-┃ skipinitialspace │     False    │     False    │     False    ┃
-┃ lineterminator   │    '\r\n'    │    '\r\n'    │      '\n'    ┃
-┃ quoting          │         0    │         0    │         1    ┃
-┃ escapechar       │      None    │      None    │      None    ┃
+┃ delimiter        │    ','       │    '\t'      │    ','       ┃
+┃ quotechar        │    '"'       │    '"'       │    '"'       ┃
+┃ doublequote      │    True      │    True      │     True     ┃
+┃ skipinitialspace │    False     │    False     │     False    ┃
+┃ lineterminator   │    '\r\n'    │    '\r\n'    │    '\n'      ┃
+┃ quoting          │    0         │    0         │     1        ┃
+┃ escapechar       │    None      │    None      │     None     ┃
 ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
 
@@ -1703,10 +1703,10 @@

Example

In this example values are not actually saved because 'conn.commit()' is omitted!

>>> conn = sqlite3.connect('test.db')
->>> conn.execute('create table person (person_id integer primary key, name, height)')
->>> conn.execute('insert into person values (null, ?, ?)', ('Jean-Luc', 187)).lastrowid
+>>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
+>>> conn.execute('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid
 1
->>> conn.execute('select * from person').fetchall()
+>>> conn.execute('SELECT * FROM person').fetchall()
 [(1, 'Jean-Luc', 187)]
 
@@ -1865,7 +1865,7 @@
<Exec> = ThreadPoolExecutor(max_workers=None)  # Or: `with ThreadPoolExecutor() as <name>: …`
-<Exec>.shutdown(wait=True)                     # Gets called at the end of 'with' block.
+<Exec>.shutdown(wait=True)                     # Blocks until all threads finish executing.
 
<iter> = <Exec>.map(<func>, <args_1>, ...)     # A multithreaded and non-lazy map().
 <Futr> = <Exec>.submit(<func>, <arg_1>, ...)   # Starts a thread and returns its Future object.
@@ -2214,7 +2214,7 @@
 

Timing a Snippet

>>> from timeit import timeit
->>> timeit('"".join(str(i) for i in range(100))',
+>>> timeit("''.join(str(i) for i in range(100))",
 ...        number=10000, globals=globals(), setup='pass')
 0.34986
 
@@ -2275,21 +2275,18 @@
  • Shape is a tuple of dimension sizes.
  • Axis is an index of the dimension that gets collapsed. Leftmost dimension has index 0.
  • -

    Indexing

    <el>       = <2d_array>[0, 0]        # First element.
    -<1d_view>  = <2d_array>[0]           # First row.
    -<1d_view>  = <2d_array>[:, 0]        # First column. Also [..., 0].
    -<3d_view>  = <2d_array>[None, :, :]  # Expanded by dimension of size 1.
    +

    Indexing

    <el>       = <2d_array>[row_index, column_index]
    +<1d_view>  = <2d_array>[row_index]
    +<1d_view>  = <2d_array>[:, column_index]
     
    -
    <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
    -<2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
    +
    <1d_array> = <2d_array>[row_indexes, column_indexes]
    +<2d_array> = <2d_array>[row_indexes]
    +<2d_array> = <2d_array>[:, column_indexes]
     
    -
    <2d_bools> = <2d_array> > 0
    +
    <2d_bools> = <2d_array> ><== <el>
     <1d_array> = <2d_array>[<2d_bools>]
     
    -
      -
    • If row and column indexes differ in shape, they are combined with broadcasting.
    • -

    Broadcasting

    Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.

    left  = [[0.1], [0.6], [0.8]]        # Shape: (3, 1)
     right = [ 0.1 ,  0.6 ,  0.8 ]        # Shape: (3)
     
    @@ -2492,8 +2489,8 @@

    #Synthesizer

    Plays Popcorn by Gershon Kingsley:

    # $ pip3 install simpleaudio
    -import simpleaudio, math, struct
    -from itertools import chain, repeat
    +import math, struct, simpleaudio
    +from itertools import repeat, chain
     F  = 44100
     P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,'
     P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,'
    diff --git a/parse.js b/parse.js
    index 606524ff1..9d6d8d780 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -74,20 +74,6 @@ const PROGRESS_BAR =
       '...     sleep(1)\n' +
       'Processing: 100%|████████████████████| 3/3 [00:03<00:00,  1.00s/it]\n';
     
    -const NUMPY_1 =
    -  '<el>       = <2d_array>[0, 0]        # First element.\n' +
    -  '<1d_view>  = <2d_array>[0]           # First row.\n' +
    -  '<1d_view>  = <2d_array>[:, 0]        # First column. Also [..., 0].\n' +
    -  '<3d_view>  = <2d_array>[None, :, :]  # Expanded by dimension of size 1.\n';
    -
    -const NUMPY_2 =
    -  '<1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]\n' +
    -  '<2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]\n';
    -
    -const NUMPY_3 =
    -  '<2d_bools> = <2d_array> > 0\n' +
    -  '<1d_array> = <2d_array>[<2d_bools>]\n';
    -
     const PYINSTALLER =
       '$ pip3 install pyinstaller\n' +
       '$ pyinstaller script.py                        # Compiles into \'./dist/script\' directory.\n' +
    @@ -244,20 +230,20 @@ const DIAGRAM_8_B =
     
     const DIAGRAM_9_A =
       '+------------------+--------------+--------------+--------------+\n' +
    -  '|                  |     excel    |   excel-tab  |     unix     |\n' +
    +  '|                  |    excel     |   excel-tab  |     unix     |\n' +
       '+------------------+--------------+--------------+--------------+\n';
     
     const DIAGRAM_9_B =
       "┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓\n" +
    -  "┃                  │     excel    │   excel-tab  │     unix     ┃\n" +
    +  "┃                  │    excel     │   excel-tab  │     unix     ┃\n" +
       "┠──────────────────┼──────────────┼──────────────┼──────────────┨\n" +
    -  "┃ delimiter        │       ','    │      '\\t'    │       ','    ┃\n" +
    -  "┃ quotechar        │       '\"'    │       '\"'    │       '\"'    ┃\n" +
    -  "┃ doublequote      │      True    │      True    │      True    ┃\n" +
    -  "┃ skipinitialspace │     False    │     False    │     False    ┃\n" +
    -  "┃ lineterminator   │    '\\r\\n'    │    '\\r\\n'    │      '\\n'    ┃\n" +
    -  "┃ quoting          │         0    │         0    │         1    ┃\n" +
    -  "┃ escapechar       │      None    │      None    │      None    ┃\n" +
    +  "┃ delimiter        │    ','       │    '\\t'      │    ','       ┃\n" +
    +  "┃ quotechar        │    '\"'       │    '\"'       │    '\"'       ┃\n" +
    +  "┃ doublequote      │    True      │    True      │     True     ┃\n" +
    +  "┃ skipinitialspace │    False     │    False     │     False    ┃\n" +
    +  "┃ lineterminator   │    '\\r\\n'    │    '\\r\\n'    │    '\\n'      ┃\n" +
    +  "┃ quoting          │    0         │    0         │     1        ┃\n" +
    +  "┃ escapechar       │    None      │    None      │     None     ┃\n" +
       "┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n";
     
     const DIAGRAM_10_A =
    @@ -530,9 +516,6 @@ function fixHighlights() {
       $(`code:contains(\'\', , )`).html(TYPE);
       $(`code:contains(ValueError: malformed node)`).html(EVAL);
       $(`code:contains(pip3 install tqdm)`).html(PROGRESS_BAR);
    -  $(`code:contains(       = <2d_array>[0, 0])`).html(NUMPY_1).removeClass().addClass("python language-python hljs");
    -  $(`code:contains(<1d_array> = <2d_array>[<1d_row_indexes>)`).html(NUMPY_2).removeClass().addClass("python language-python hljs");
    -  $(`code:contains(<2d_bools> = <2d_array> > 0)`).html(NUMPY_3).removeClass().addClass("python language-python hljs");
       $(`code:contains(pip3 install pyinstaller)`).html(PYINSTALLER);
       $(`ul:contains(Only available in)`).html(INDEX);
     }
    
    From a56efa9662b834747bacd137fe645368c6083c2b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 18 Mar 2021 15:14:28 +0100
    Subject: [PATCH 002/721] Map, copy, struct
    
    ---
     README.md  | 3 +++
     index.html | 3 +++
     2 files changed, 6 insertions(+)
    
    diff --git a/README.md b/README.md
    index 6909f1fa0..caacd078f 100644
    --- a/README.md
    +++ b/README.md
    @@ -773,6 +773,7 @@ for i in range(10):
     ### Map, Filter, Reduce
     ```python
     from functools import reduce
    +
      = map(lambda x: x + 1, range(10))            # (1, 2, ..., 10)
      = filter(lambda x: x > 5, range(10))         # (6, 7, 8, 9)
       = reduce(lambda out, x: out + x, range(10))  # 45
    @@ -1061,6 +1062,7 @@ class MyClassWithSlots:
     ### Copy
     ```python
     from copy import copy, deepcopy
    +
      = copy()
      = deepcopy()
     ```
    @@ -1948,6 +1950,7 @@ Struct
     
     ```python
     from struct import pack, unpack, iter_unpack
    +
       = pack('',  [, , ...])
       = unpack('', )
      = iter_unpack('', )
    diff --git a/index.html b/index.html
    index 68b79e81d..ba80b5fbb 100644
    --- a/index.html
    +++ b/index.html
    @@ -809,6 +809,7 @@
     
     
     

    Map, Filter, Reduce

    from functools import reduce
    +
     <iter> = map(lambda x: x + 1, range(10))            # (1, 2, ..., 10)
     <iter> = filter(lambda x: x > 5, range(10))         # (6, 7, 8, 9)
     <obj>  = reduce(lambda out, x: out + x, range(10))  # 45
    @@ -1039,6 +1040,7 @@
     
     
     

    Copy

    from copy import copy, deepcopy
    +
     <object> = copy(<object>)
     <object> = deepcopy(<object>)
     
    @@ -1754,6 +1756,7 @@
  • Module that performs conversions between a sequence of numbers and a bytes object.
  • Machine’s native type sizes and byte order are used by default.
  • from struct import pack, unpack, iter_unpack
    +
     <bytes>  = pack('<format>', <num_1> [, <num_2>, ...])
     <tuple>  = unpack('<format>', <bytes>)
     <tuples> = iter_unpack('<format>', <bytes>)
    
    From d420693d481e765b1c4cd93ca359bcfec8945113 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 18 Mar 2021 15:40:41 +0100
    Subject: [PATCH 003/721] Image
    
    ---
     README.md  | 4 ++--
     index.html | 6 +++---
     2 files changed, 5 insertions(+), 5 deletions(-)
    
    diff --git a/README.md b/README.md
    index caacd078f..55692d00f 100644
    --- a/README.md
    +++ b/README.md
    @@ -2750,13 +2750,13 @@ img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()])
     img.convert('RGB').save('test.png')
     ```
     
    -### Drawing
    +### Image Draw
     ```python
     from PIL import ImageDraw
    + = ImageDraw.Draw()
     ```
     
     ```python
    - = ImageDraw.Draw()
     .point((x, y), fill=None)
     .line((x1, y1, x2, y2 [, ...]), fill=None, width=0, joint=None) 
     .arc((x1, y1, x2, y2), from_deg, to_deg, fill=None, width=0)
    diff --git a/index.html b/index.html
    index ba80b5fbb..7d1efc01e 100644
    --- a/index.html
    +++ b/index.html
    @@ -2373,11 +2373,11 @@
     img.convert('RGB').save('test.png')
     
    -

    Drawing

    from PIL import ImageDraw
    +

    Image Draw

    from PIL import ImageDraw
    +<ImageDraw> = ImageDraw.Draw(<Image>)
     
    -
    <ImageDraw> = ImageDraw.Draw(<Image>)
    -<ImageDraw>.point((x, y), fill=None)
    +
    <ImageDraw>.point((x, y), fill=None)
     <ImageDraw>.line((x1, y1, x2, y2 [, ...]), fill=None, width=0, joint=None) 
     <ImageDraw>.arc((x1, y1, x2, y2), from_deg, to_deg, fill=None, width=0)
     <ImageDraw>.rectangle((x1, y1, x2, y2), fill=None, outline=None, width=0)
    
    From 02563bb7e0d07fac62104308672b726fd880c5d5 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 18 Mar 2021 20:41:06 +0100
    Subject: [PATCH 004/721] Fixed CSV table
    
    ---
     index.html | 8 ++++----
     parse.js   | 8 ++++----
     2 files changed, 8 insertions(+), 8 deletions(-)
    
    diff --git a/index.html b/index.html
    index 7d1efc01e..5ec5d95f8 100644
    --- a/index.html
    +++ b/index.html
    @@ -1652,11 +1652,11 @@
     ┠──────────────────┼──────────────┼──────────────┼──────────────┨
     ┃ delimiter        │    ','       │    '\t'      │    ','       ┃
     ┃ quotechar        │    '"'       │    '"'       │    '"'       ┃
    -┃ doublequote      │    True      │    True      │     True     ┃
    -┃ skipinitialspace │    False     │    False     │     False    ┃
    +┃ doublequote      │    True      │    True      │    True      ┃
    +┃ skipinitialspace │    False     │    False     │    False     ┃
     ┃ lineterminator   │    '\r\n'    │    '\r\n'    │    '\n'      ┃
    -┃ quoting          │    0         │    0         │     1        ┃
    -┃ escapechar       │    None      │    None      │     None     ┃
    +┃ quoting          │    0         │    0         │    1         ┃
    +┃ escapechar       │    None      │    None      │    None      ┃
     ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
     
    diff --git a/parse.js b/parse.js index 9d6d8d780..2779c07ae 100755 --- a/parse.js +++ b/parse.js @@ -239,11 +239,11 @@ const DIAGRAM_9_B = "┠──────────────────┼──────────────┼──────────────┼──────────────┨\n" + "┃ delimiter │ ',' │ '\\t' │ ',' ┃\n" + "┃ quotechar │ '\"' │ '\"' │ '\"' ┃\n" + - "┃ doublequote │ True │ True │ True ┃\n" + - "┃ skipinitialspace │ False │ False │ False ┃\n" + + "┃ doublequote │ True │ True │ True ┃\n" + + "┃ skipinitialspace │ False │ False │ False ┃\n" + "┃ lineterminator │ '\\r\\n' │ '\\r\\n' │ '\\n' ┃\n" + - "┃ quoting │ 0 │ 0 │ 1 ┃\n" + - "┃ escapechar │ None │ None │ None ┃\n" + + "┃ quoting │ 0 │ 0 │ 1 ┃\n" + + "┃ escapechar │ None │ None │ None ┃\n" + "┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n"; const DIAGRAM_10_A = From 031875e7c14ee0e4b42f0d906ccb57e925980167 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 2 Apr 2021 06:31:10 +0200 Subject: [PATCH 005/721] Inline, Struct, Threading --- README.md | 60 ++++++++++++++++++------------------------ index.html | 76 +++++++++++++++++++++++++----------------------------- parse.js | 3 ++- 3 files changed, 62 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 55692d00f..f2c320a8c 100644 --- a/README.md +++ b/README.md @@ -599,7 +599,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary ``` * **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means the second pass in case of time jumping back for one hour.** -* **`' = resolve_imaginary()'` fixes DTs that fall into missing hour.** +* **`' = resolve_imaginary()'` fixes DTs that fall into the missing hour.** ### Now ```python @@ -731,10 +731,10 @@ def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3 ### Other Uses ```python - = [* [, ...]] - = {* [, ...]} - = (*, [...]) - = {** [, ...]} + = [* [, ...]] + = {* [, ...]} + = (*, [...]) + = {** [, ...]} ``` ```python @@ -746,48 +746,40 @@ Inline ------ ### Lambda ```python - = lambda: - = lambda , : + = lambda: + = lambda , : ``` ### Comprehensions ```python - = [i+1 for i in range(10)] # [1, 2, ..., 10] - = {i for i in range(10) if i > 5} # {6, 7, 8, 9} - = (i+5 for i in range(10)) # (5, 6, ..., 14) - = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} + = [i+1 for i in range(10)] # [1, 2, ..., 10] + = {i for i in range(10) if i > 5} # {6, 7, 8, 9} + = (i+5 for i in range(10)) # (5, 6, ..., 14) + = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} ``` ```python -out = [i+j for i in range(10) for j in range(10)] -``` - -#### Is the same as: -```python -out = [] -for i in range(10): - for j in range(10): - out.append(i+j) +>>> [l+r for l in 'abc' for r in 'abc'] +['aa', 'ab', 'ac', ..., 'cc'] ``` ### Map, Filter, Reduce ```python -from functools import reduce - - = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) - = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) - = reduce(lambda out, x: out + x, range(10)) # 45 + = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) + = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) + = reduce(lambda out, x: out + x, range(10)) # 45 ``` +* **Reduce must be imported from functools module.** ### Any, All ```python - = any() # False if empty. - = all(el[1] for el in ) # True if empty. + = any() # False if empty. + = all(el[1] for el in ) # True if empty. ``` -### If - Else +### Conditional Expression ```python - = if else + = if else ``` ```python @@ -810,7 +802,7 @@ direction = Direction.n ```python from dataclasses import make_dataclass -Creature = make_dataclass('Creature', ['location', 'direction']) +Creature = make_dataclass('Creature', ['loc', 'dir']) creature = Creature(Point(0, 0), Direction.n) ``` @@ -1950,13 +1942,14 @@ Struct ```python from struct import pack, unpack, iter_unpack +``` +```python = pack('', [, , ...]) = unpack('', ) = iter_unpack('', ) ``` -### Example ```python >>> pack('>hhl', 1, 2, 3) b'\x00\x01\x00\x02\x00\x00\x00\x03' @@ -2049,6 +2042,7 @@ Threading * **That is why using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation.** ```python from threading import Thread, RLock, Semaphore, Event, Barrier +from concurrent.futures import ThreadPoolExecutor ``` ### Thread @@ -2084,10 +2078,6 @@ with lock: ### Thread Pool Executor **Object that manages thread execution.** -```python -from concurrent.futures import ThreadPoolExecutor -``` - ```python = ThreadPoolExecutor(max_workers=None) # Or: `with ThreadPoolExecutor() as : …` .shutdown(wait=True) # Blocks until all threads finish executing. diff --git a/index.html b/index.html index 5ec5d95f8..782ecd941 100644 --- a/index.html +++ b/index.html @@ -681,7 +681,7 @@
    • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
    • 'fold=1' means the second pass in case of time jumping back for one hour.
    • -
    • '<DTa> = resolve_imaginary(<DTa>)' fixes DTs that fall into missing hour.
    • +
    • '<DTa> = resolve_imaginary(<DTa>)' fixes DTs that fall into the missing hour.

    Now

    <D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
     <DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
    @@ -781,45 +781,41 @@
     def f(*args, y, **kwargs):     # f(x=1, y=2, z=3) | f(1, y=2, z=3)
     def f(x, *args, z, **kwargs):  # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
     
    -

    Other Uses

    <list>  = [*<collection> [, ...]]
    -<set>   = {*<collection> [, ...]}
    -<tuple> = (*<collection>, [...])
    -<dict>  = {**<dict> [, ...]}
    +

    Other Uses

    <list> = [*<collection> [, ...]]
    +<set>  = {*<collection> [, ...]}
    +<tup.> = (*<collection>, [...])
    +<dict> = {**<dict> [, ...]}
     
    head, *body, tail = <collection>
     
    -

    #Inline

    Lambda

    <function> = lambda: <return_value>
    -<function> = lambda <argument_1>, <argument_2>: <return_value>
    +

    #Inline

    Lambda

    <func> = lambda: <return_value>
    +<func> = lambda <arg_1>, <arg_2>: <return_value>
     
    -

    Comprehensions

    <list> = [i+1 for i in range(10)]                   # [1, 2, ..., 10]
    -<set>  = {i for i in range(10) if i > 5}            # {6, 7, 8, 9}
    -<iter> = (i+5 for i in range(10))                   # (5, 6, ..., 14)
    -<dict> = {i: i*2 for i in range(10)}                # {0: 0, 1: 2, ..., 9: 18}
    +

    Comprehensions

    <list> = [i+1 for i in range(10)]                         # [1, 2, ..., 10]
    +<set>  = {i for i in range(10) if i > 5}                  # {6, 7, 8, 9}
    +<iter> = (i+5 for i in range(10))                         # (5, 6, ..., 14)
    +<dict> = {i: i*2 for i in range(10)}                      # {0: 0, 1: 2, ..., 9: 18}
     
    -
    out = [i+j for i in range(10) for j in range(10)]
    +
    >>> [l+r for l in 'abc' for r in 'abc']
    +['aa', 'ab', 'ac', ..., 'cc']
     
    -

    Is the same as:

    out = []
    -for i in range(10):
    -    for j in range(10):
    -        out.append(i+j)
    +

    Map, Filter, Reduce

    <iter> = map(lambda x: x + 1, range(10))                  # (1, 2, ..., 10)
    +<iter> = filter(lambda x: x > 5, range(10))               # (6, 7, 8, 9)
    +<obj>  = reduce(lambda out, x: out + x, range(10))        # 45
     
    -

    Map, Filter, Reduce

    from functools import reduce
    -
    -<iter> = map(lambda x: x + 1, range(10))            # (1, 2, ..., 10)
    -<iter> = filter(lambda x: x > 5, range(10))         # (6, 7, 8, 9)
    -<obj>  = reduce(lambda out, x: out + x, range(10))  # 45
    -
    - -

    Any, All

    <bool> = any(<collection>)                          # False if empty.
    -<bool> = all(el[1] for el in <collection>)          # True if empty.
    +
      +
    • Reduce must be imported from functools module.
    • +
    +

    Any, All

    <bool> = any(<collection>)                                # False if empty.
    +<bool> = all(el[1] for el in <collection>)                # True if empty.
     
    -

    If - Else

    <obj> = <expression_if_true> if <condition> else <expression_if_false>
    +

    Conditional Expression

    <obj> = <exp_if_true> if <condition> else <exp_if_false>
     
    >>> [a if a else 'zero' for a in (0, 1, 2, 3)]
    @@ -835,7 +831,7 @@
     direction = Direction.n
     
    from dataclasses import make_dataclass
    -Creature  = make_dataclass('Creature', ['location', 'direction'])
    +Creature  = make_dataclass('Creature', ['loc', 'dir'])
     creature  = Creature(Point(0, 0), Direction.n)
     

    #Closure

    We have a closure in Python when:

      @@ -884,7 +880,7 @@ >>> counter(), counter(), counter() (1, 2, 3)
    -

    #Decorator

    A decorator takes a function, adds some functionality and returns it.

    @decorator_name
    +

    #Decorator

    A decorator takes a function, adds some functionality and returns it.

    @decorator_name
     def function_that_gets_passed_to_decorator():
         ...
     
    @@ -1397,7 +1393,7 @@
    -

    #Print

    print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    +

    #Print

    print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
     
      @@ -1756,19 +1752,18 @@
    • Module that performs conversions between a sequence of numbers and a bytes object.
    • Machine’s native type sizes and byte order are used by default.
    from struct import pack, unpack, iter_unpack
    -
    -<bytes>  = pack('<format>', <num_1> [, <num_2>, ...])
    -<tuple>  = unpack('<format>', <bytes>)
    -<tuples> = iter_unpack('<format>', <bytes>)
     
    -

    Example

    >>> pack('>hhl', 1, 2, 3)
    +
    <bytes>  = pack('<format>', <num_1> [, <num_2>, ...])
    +<tuple>  = unpack('<format>', <bytes>)
    +<tuples> = iter_unpack('<format>', <bytes>)
    +
    +
    >>> pack('>hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
     >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
     (1, 2, 3)
    -
    - +

    Format

    For standard type sizes start format string with:

    • '=' - native byte order (usually little-endian)
    • '<' - little-endian
    • @@ -1835,6 +1830,7 @@
    • CPython interpreter can only run a single thread at a time.
    • That is why using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation.
    from threading import Thread, RLock, Semaphore, Event, Barrier
    +from concurrent.futures import ThreadPoolExecutor
     
    @@ -1863,13 +1859,11 @@ <Barrier> = Barrier(n_times) # Wait() blocks until it's called n_times.
    -

    Thread Pool Executor

    Object that manages thread execution.

    from concurrent.futures import ThreadPoolExecutor
    +

    Thread Pool Executor

    Object that manages thread execution.

    <Exec> = ThreadPoolExecutor(max_workers=None)  # Or: `with ThreadPoolExecutor() as <name>: …`
    +<Exec>.shutdown(wait=True)                     # Blocks until all threads finish executing.
     
    -
    <Exec> = ThreadPoolExecutor(max_workers=None)  # Or: `with ThreadPoolExecutor() as <name>: …`
    -<Exec>.shutdown(wait=True)                     # Blocks until all threads finish executing.
    -
    <iter> = <Exec>.map(<func>, <args_1>, ...)     # A multithreaded and non-lazy map().
     <Futr> = <Exec>.submit(<func>, <arg_1>, ...)   # Starts a thread and returns its Future object.
     <bool> = <Futr>.done()                         # Checks if the thread has finished executing.
    @@ -2303,7 +2297,7 @@
     right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]]  # Shape: (3, 3) <- !
     
    -

    3. If neither non-matching dimension has size 1, raise an error.

    Example

    For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

    >>> points = np.array([0.1, 0.6, 0.8])
    +

    3. If neither non-matching dimension has size 1, raise an error.

    Example

    For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

    >>> points = np.array([0.1, 0.6, 0.8])
      [ 0.1,  0.6,  0.8]
     >>> wrapped_points = points.reshape(3, 1)
     [[ 0.1],
    diff --git a/parse.js b/parse.js
    index 2779c07ae..0081b674e 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -552,7 +552,8 @@ function move(anchor_el, el_id) {
     }
     
     function insertPageBreaks() {
    -  insertPageBreakBefore('#print')
    +  insertPageBreakBefore('#decorator')
    +  // insertPageBreakBefore('#print')
     }
     
     function insertPageBreakBefore(an_id) {
    
    From dea8327eca4a472a921658437fb3746415a23f97 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 15 Apr 2021 16:39:24 +0200
    Subject: [PATCH 006/721] String, Regex, Format, Duck types, Pygame
    
    ---
     README.md  | 80 +++++++++++++++++++++++++--------------------------
     index.html | 84 ++++++++++++++++++++++++++++--------------------------
     parse.js   | 58 ++++++++++++++++++-------------------
     3 files changed, 111 insertions(+), 111 deletions(-)
    
    diff --git a/README.md b/README.md
    index f2c320a8c..9fe1164df 100644
    --- a/README.md
    +++ b/README.md
    @@ -308,7 +308,7 @@ String
     ```python
      = .split()                       # Splits on one or more whitespace characters.
      = .split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
    - = .splitlines(keepends=False)    # Splits on \n,\r,\r\n. Keeps them if 'keepends'.
    + = .splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'.
       = .join()       # Joins elements using string as a separator.
     ```
     
    @@ -376,12 +376,13 @@ import re
     ```
     
     ### Special Sequences
    -* **By default digits, alphanumerics and whitespaces from all alphabets are matched, unless `'flags=re.ASCII'` argument is used.**
    +* **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.**
    +* **As shown below, it restricts special sequence matches to `'[\x00-\x7f]'` and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.**
     * **Use a capital letter for negation.**
     ```python
    -'\d' == '[0-9]'                                # Matches any digit.
    -'\w' == '[a-zA-Z0-9_]'                         # Matches any alphanumeric.
    -'\s' == '[ \t\n\r\f\v]'                        # Matches any whitespace.
    +'\d' == '[0-9]'                                # Matches decimal characters.
    +'\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
    +'\s' == '[ \t\n\r\f\v]'                        # Matches whitespaces.
     ```
     
     
    @@ -440,33 +441,32 @@ Format
     
     #### Comparison of presentation types:
     ```text
    -+---------------+-----------------+-----------------+-----------------+-----------------+
    -|               |    {}    |   {:f}   |   {:e}   |   {:%}   |
    -+---------------+-----------------+-----------------+-----------------+-----------------+
    -|   0.000056789 |    '5.6789e-05' |     '0.000057'  |  '5.678900e-05' |     '0.005679%' |
    -|   0.00056789  |    '0.00056789' |     '0.000568'  |  '5.678900e-04' |     '0.056789%' |
    -|   0.0056789   |    '0.0056789'  |     '0.005679'  |  '5.678900e-03' |     '0.567890%' |
    -|   0.056789    |    '0.056789'   |     '0.056789'  |  '5.678900e-02' |     '5.678900%' |
    -|   0.56789     |    '0.56789'    |     '0.567890'  |  '5.678900e-01' |    '56.789000%' |
    -|   5.6789      |    '5.6789'     |     '5.678900'  |  '5.678900e+00' |   '567.890000%' |
    -|  56.789       |   '56.789'      |    '56.789000'  |  '5.678900e+01' |  '5678.900000%' |
    -| 567.89        |  '567.89'       |   '567.890000'  |  '5.678900e+02' | '56789.000000%' |
    -+---------------+-----------------+-----------------+-----------------+-----------------+
    ++--------------+----------------+----------------+----------------+----------------+
    +|              |    {}   |   {:f}  |   {:e}  |   {:%}  |
    ++--------------+----------------+----------------+----------------+----------------+
    +|  0.000056789 |   '5.6789e-05' |    '0.000057'  | '5.678900e-05' |    '0.005679%' |
    +|  0.00056789  |   '0.00056789' |    '0.000568'  | '5.678900e-04' |    '0.056789%' |
    +|  0.0056789   |   '0.0056789'  |    '0.005679'  | '5.678900e-03' |    '0.567890%' |
    +|  0.056789    |   '0.056789'   |    '0.056789'  | '5.678900e-02' |    '5.678900%' |
    +|  0.56789     |   '0.56789'    |    '0.567890'  | '5.678900e-01' |   '56.789000%' |
    +|  5.6789      |   '5.6789'     |    '5.678900'  | '5.678900e+00' |  '567.890000%' |
    +| 56.789       |  '56.789'      |   '56.789000'  | '5.678900e+01' | '5678.900000%' |
    ++--------------+----------------+----------------+----------------+----------------+
     ```
     ```text
    -+---------------+-----------------+-----------------+-----------------+-----------------+
    -|               |   {:.2}  |  {:.2f}  |  {:.2e}  |  {:.2%}  |
    -+---------------+-----------------+-----------------+-----------------+-----------------+
    -|   0.000056789 |    '5.7e-05'    |       '0.00'    |    '5.68e-05'   |       '0.01%'   |
    -|   0.00056789  |    '0.00057'    |       '0.00'    |    '5.68e-04'   |       '0.06%'   |
    -|   0.0056789   |    '0.0057'     |       '0.01'    |    '5.68e-03'   |       '0.57%'   |
    -|   0.056789    |    '0.057'      |       '0.06'    |    '5.68e-02'   |       '5.68%'   |
    -|   0.56789     |    '0.57'       |       '0.57'    |    '5.68e-01'   |      '56.79%'   |
    -|   5.6789      |    '5.7'        |       '5.68'    |    '5.68e+00'   |     '567.89%'   |
    -|  56.789       |    '5.7e+01'    |      '56.79'    |    '5.68e+01'   |    '5678.90%'   |
    -| 567.89        |    '5.7e+02'    |     '567.89'    |    '5.68e+02'   |   '56789.00%'   |
    -+---------------+-----------------+-----------------+-----------------+-----------------+
    -```
    ++--------------+----------------+----------------+----------------+----------------+
    +|              |  {:.2}  |  {:.2f} |  {:.2e} |  {:.2%} |
    ++--------------+----------------+----------------+----------------+----------------+
    +|  0.000056789 |    '5.7e-05'   |      '0.00'    |   '5.68e-05'   |      '0.01%'   |
    +|  0.00056789  |    '0.00057'   |      '0.00'    |   '5.68e-04'   |      '0.06%'   |
    +|  0.0056789   |    '0.0057'    |      '0.01'    |   '5.68e-03'   |      '0.57%'   |
    +|  0.056789    |    '0.057'     |      '0.06'    |   '5.68e-02'   |      '5.68%'   |
    +|  0.56789     |    '0.57'      |      '0.57'    |   '5.68e-01'   |     '56.79%'   |
    +|  5.6789      |    '5.7'       |      '5.68'    |   '5.68e+00'   |    '567.89%'   |
    +| 56.789       |    '5.7e+01'   |     '56.79'    |   '5.68e+01'   |   '5678.90%'   |
    ++--------------+----------------+----------------+----------------+----------------+
    +```
    +* **When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes `'{6.5:.0f}'` a `'6'` and `'{7.5:.0f}'` an `'8'`.**
     
     ### Ints
     ```python
    @@ -1140,7 +1140,7 @@ class Counter:
     ```
     
     #### Python has many different iterator objects:
    -* **Iterators returned by the [iter()](#iterator) function, such as list\_iterator and set\_iterator.**
    +* **Sequence iterators returned by the [iter()](#iterator) function, such as list\_iterator and set\_iterator.**
     * **Objects returned by the [itertools](#itertools) module, such as count, repeat and cycle.**
     * **Generators returned by the [generator functions](#generator) and [generator expressions](#comprehensions).**
     * **File objects returned by the [open()](#open) function, etc.**
    @@ -2506,7 +2506,7 @@ def odds_handler(sport):
     # $ pip3 install requests
     >>> import threading, requests
     >>> threading.Thread(target=run, daemon=True).start()
    ->>> url  = 'http://localhost:8080/odds/football'
    +>>> url = 'http://localhost:8080/odds/football'
     >>> data = {'team': 'arsenal f.c.'}
     >>> response = requests.post(url, data=data)
     >>> response.json()
    @@ -2899,7 +2899,7 @@ get_pause   = lambda seconds: repeat(0, int(seconds * F))
     sin_f       = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
     get_wave    = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
     get_hz      = lambda key: 8.176 * 2 ** (int(key) / 12)
    -parse_note  = lambda note: (get_hz(note[:-1]), 1/4 if '♩' in note else 1/8)
    +parse_note  = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8)
     get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8)
     samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(','))
     samples_b   = b''.join(struct.pack(' = scale(, (width, height))         # Returns scaled surface.
      = rotate(, degrees)                # Returns rotated and scaled surface.
      = flip(, x_bool, y_bool)           # Returns flipped surface.
     ```
     
     ```python
    -from pygame.draw import *
    +from pygame.draw import line, arc, rect
     line(, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
     arc(, color, , from_rad, to_rad)    # Also: ellipse(, color, )
     rect(, color, )                     # Also: polygon(, color, points)
    @@ -3029,12 +3029,12 @@ def update_speed(mario, tiles, pressed):
         mario.spd = P(*[max(-limit, min(limit, s)) for limit, s in zip(MAX_SPEED, P(x, y))])
     
     def update_position(mario, tiles):
    -    p = mario.rect.topleft
    -    larger_speed = max(abs(s) for s in mario.spd)
    -    for _ in range(larger_speed):
    +    x, y = mario.rect.topleft
    +    n_steps = max(abs(s) for s in mario.spd)
    +    for _ in range(n_steps):
             mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))
    -        p = P(*[a + s/larger_speed for a, s in zip(p, mario.spd)])
    -        mario.rect.topleft = p
    +        x, y = x + mario.spd.x/n_steps, y + mario.spd.y/n_steps
    +        mario.rect.topleft = x, y
     
     def get_boundaries(rect, tiles):
         deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
    diff --git a/index.html b/index.html
    index 782ecd941..aae2432f8 100644
    --- a/index.html
    +++ b/index.html
    @@ -449,7 +449,7 @@
     
     
    <list> = <str>.split()                       # Splits on one or more whitespace characters.
     <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
    -<list> = <str>.splitlines(keepends=False)    # Splits on \n,\r,\r\n. Keeps them if 'keepends'.
    +<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'.
     <str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as a separator.
     
    <bool> = <sub_str> in <str>                  # Checks if string contains a substring.
    @@ -507,11 +507,12 @@
     

    Special Sequences

      -
    • By default digits, alphanumerics and whitespaces from all alphabets are matched, unless 'flags=re.ASCII' argument is used.
    • +
    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • +
    • As shown below, it restricts special sequence matches to '[\x00-\x7f]' and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
    • Use a capital letter for negation.
    • -
    '\d' == '[0-9]'                                # Matches any digit.
    -'\w' == '[a-zA-Z0-9_]'                         # Matches any alphanumeric.
    -'\s' == '[ \t\n\r\f\v]'                        # Matches any whitespace.
    +
    '\d' == '[0-9]'                                # Matches decimal characters.
    +'\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
    +'\s' == '[ \t\n\r\f\v]'                        # Matches whitespaces.
     
    @@ -555,33 +556,34 @@ {1.23456:10.3%} # ' 123.456%'
    -

    Comparison of presentation types:

    ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓
    -┃               │    {<float>}    │   {<float>:f}   │   {<float>:e}   │   {<float>:%}   ┃
    -┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨
    -┃   0.000056789 │    '5.6789e-05' │     '0.000057'  │  '5.678900e-05' │     '0.005679%' ┃
    -┃   0.00056789  │    '0.00056789' │     '0.000568'  │  '5.678900e-04' │     '0.056789%' ┃
    -┃   0.0056789   │    '0.0056789'  │     '0.005679'  │  '5.678900e-03' │     '0.567890%' ┃
    -┃   0.056789    │    '0.056789'   │     '0.056789'  │  '5.678900e-02' │     '5.678900%' ┃
    -┃   0.56789     │    '0.56789'    │     '0.567890'  │  '5.678900e-01' │    '56.789000%' ┃
    -┃   5.6789      │    '5.6789'     │     '5.678900'  │  '5.678900e+00' │   '567.890000%' ┃
    -┃  56.789       │   '56.789'      │    '56.789000'  │  '5.678900e+01' │  '5678.900000%' ┃
    -┃ 567.89        │  '567.89'       │   '567.890000'  │  '5.678900e+02' │ '56789.000000%' ┃
    -┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛
    -
    - -
    ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓
    -┃               │   {<float>:.2}  │  {<float>:.2f}  │  {<float>:.2e}  │  {<float>:.2%}  ┃
    -┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨
    -┃   0.000056789 │    '5.7e-05'    │       '0.00'    │    '5.68e-05'   │       '0.01%'   ┃
    -┃   0.00056789  │    '0.00057'    │       '0.00'    │    '5.68e-04'   │       '0.06%'   ┃
    -┃   0.0056789   │    '0.0057'     │       '0.01'    │    '5.68e-03'   │       '0.57%'   ┃
    -┃   0.056789    │    '0.057'      │       '0.06'    │    '5.68e-02'   │       '5.68%'   ┃
    -┃   0.56789     │    '0.57'       │       '0.57'    │    '5.68e-01'   │      '56.79%'   ┃
    -┃   5.6789      │    '5.7'        │       '5.68'    │    '5.68e+00'   │     '567.89%'   ┃
    -┃  56.789       │    '5.7e+01'    │      '56.79'    │    '5.68e+01'   │    '5678.90%'   ┃
    -┃ 567.89        │    '5.7e+02'    │     '567.89'    │    '5.68e+02'   │   '56789.00%'   ┃
    -┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛
    +

    Comparison of presentation types:

    ┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
    +┃              │    {<float>}   │   {<float>:f}  │   {<float>:e}  │   {<float>:%}  ┃
    +┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
    +┃  0.000056789 │   '5.6789e-05' │    '0.000057'  │ '5.678900e-05' │    '0.005679%' ┃
    +┃  0.00056789  │   '0.00056789' │    '0.000568'  │ '5.678900e-04' │    '0.056789%' ┃
    +┃  0.0056789   │   '0.0056789'  │    '0.005679'  │ '5.678900e-03' │    '0.567890%' ┃
    +┃  0.056789    │   '0.056789'   │    '0.056789'  │ '5.678900e-02' │    '5.678900%' ┃
    +┃  0.56789     │   '0.56789'    │    '0.567890'  │ '5.678900e-01' │   '56.789000%' ┃
    +┃  5.6789      │   '5.6789'     │    '5.678900'  │ '5.678900e+00' │  '567.890000%' ┃
    +┃ 56.789       │  '56.789'      │   '56.789000'  │ '5.678900e+01' │ '5678.900000%' ┃
    +┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
    +
    + +
    ┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
    +┃              │  {<float>:.2}  │  {<float>:.2f} │  {<float>:.2e} │  {<float>:.2%} ┃
    +┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
    +┃  0.000056789 │    '5.7e-05'   │      '0.00'    │   '5.68e-05'   │      '0.01%'   ┃
    +┃  0.00056789  │    '0.00057'   │      '0.00'    │   '5.68e-04'   │      '0.06%'   ┃
    +┃  0.0056789   │    '0.0057'    │      '0.01'    │   '5.68e-03'   │      '0.57%'   ┃
    +┃  0.056789    │    '0.057'     │      '0.06'    │   '5.68e-02'   │      '5.68%'   ┃
    +┃  0.56789     │    '0.57'      │      '0.57'    │   '5.68e-01'   │     '56.79%'   ┃
    +┃  5.6789      │    '5.7'       │      '5.68'    │   '5.68e+00'   │    '567.89%'   ┃
    +┃ 56.789       │    '5.7e+01'   │     '56.79'    │   '5.68e+01'   │   '5678.90%'   ┃
    +┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
     
    +
      +
    • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
    • +

    Ints

    {90:c}                                   # 'Z'
     {90:b}                                   # '1011010'
     {90:X}                                   # '5A'
    @@ -1115,7 +1117,7 @@
     (1, 2, 3)
     

    Python has many different iterator objects:

    Dialects

    ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
    -┃                  │    excel     │   excel-tab  │     unix     ┃
    +┃                  │     excel    │   excel-tab  │     unix     ┃
     ┠──────────────────┼──────────────┼──────────────┼──────────────┨
    -┃ delimiter        │    ','       │    '\t'      │    ','       ┃
    -┃ quotechar        │    '"'       │    '"'       │    '"'       ┃
    -┃ doublequote      │    True      │    True      │    True      ┃
    -┃ skipinitialspace │    False     │    False     │    False     ┃
    -┃ lineterminator   │    '\r\n'    │    '\r\n'    │    '\n'      ┃
    -┃ quoting          │    0         │    0         │    1         ┃
    -┃ escapechar       │    None      │    None      │    None      ┃
    +┃ delimiter        │       ','    │      '\t'    │       ','    ┃
    +┃ quotechar        │       '"'    │       '"'    │       '"'    ┃
    +┃ doublequote      │      True    │      True    │      True    ┃
    +┃ skipinitialspace │     False    │     False    │     False    ┃
    +┃ lineterminator   │    '\r\n'    │    '\r\n'    │      '\n'    ┃
    +┃ quoting          │         0    │         0    │         1    ┃
    +┃ escapechar       │      None    │      None    │      None    ┃
     ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
     
    diff --git a/parse.js b/parse.js index 13b7c669f..2d56bc6d7 100755 --- a/parse.js +++ b/parse.js @@ -228,20 +228,20 @@ const DIAGRAM_8_B = const DIAGRAM_9_A = '+------------------+--------------+--------------+--------------+\n' + - '| | excel | excel-tab | unix |\n' + + '| | excel | excel-tab | unix |\n' + '+------------------+--------------+--------------+--------------+\n'; const DIAGRAM_9_B = "┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓\n" + - "┃ │ excel │ excel-tab │ unix ┃\n" + + "┃ │ excel │ excel-tab │ unix ┃\n" + "┠──────────────────┼──────────────┼──────────────┼──────────────┨\n" + - "┃ delimiter │ ',' │ '\\t' │ ',' ┃\n" + - "┃ quotechar │ '\"' │ '\"' │ '\"' ┃\n" + - "┃ doublequote │ True │ True │ True ┃\n" + - "┃ skipinitialspace │ False │ False │ False ┃\n" + - "┃ lineterminator │ '\\r\\n' │ '\\r\\n' │ '\\n' ┃\n" + - "┃ quoting │ 0 │ 0 │ 1 ┃\n" + - "┃ escapechar │ None │ None │ None ┃\n" + + "┃ delimiter │ ',' │ '\\t' │ ',' ┃\n" + + "┃ quotechar │ '\"' │ '\"' │ '\"' ┃\n" + + "┃ doublequote │ True │ True │ True ┃\n" + + "┃ skipinitialspace │ False │ False │ False ┃\n" + + "┃ lineterminator │ '\\r\\n' │ '\\r\\n' │ '\\n' ┃\n" + + "┃ quoting │ 0 │ 0 │ 1 ┃\n" + + "┃ escapechar │ None │ None │ None ┃\n" + "┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n"; const DIAGRAM_10_A = From f57188c6650edfbf6f9158a3ed3d06f090eeccd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 29 Apr 2021 03:23:00 +0200 Subject: [PATCH 016/721] Bytes --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fa8c7cbdd..439cce20e 100644 --- a/README.md +++ b/README.md @@ -1898,7 +1898,7 @@ Bytes **Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** ```python - = b'' # Only accepts ASCII characters and \x00 - \xff. + = b'' # Only accepts ASCII characters and \x00-\xff. = [] # Returns int in range from 0 to 255. = [] # Returns bytes even if it has only one element. = .join() # Joins elements using bytes object as separator. diff --git a/index.html b/index.html index 1cfe517cc..099d36c8f 100644 --- a/index.html +++ b/index.html @@ -1721,7 +1721,7 @@
    -

    #Bytes

    Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

    <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00 - \xff.
    +

    #Bytes

    Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

    <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
     <int>   = <bytes>[<index>]               # Returns int in range from 0 to 255.
     <bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
     <bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes object as separator.
    
    From 41ce7f02e1395d4b91ecb2481d74e286f102cc13 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 29 Apr 2021 03:27:19 +0200
    Subject: [PATCH 017/721] Pygame
    
    ---
     README.md  | 4 ++--
     index.html | 4 ++--
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index 439cce20e..2ff7e353f 100644
    --- a/README.md
    +++ b/README.md
    @@ -2917,7 +2917,7 @@ pg.init()
     screen = pg.display.set_mode((500, 500))
     rect = pg.Rect(240, 240, 20, 20)
     while all(event.type != pg.QUIT for event in pg.event.get()):
    -    deltas = {pg.K_UP: (0, -3), pg.K_RIGHT: (3, 0), pg.K_DOWN: (0, 3), pg.K_LEFT: (-3, 0)}
    +    deltas = {pg.K_UP: (0, -1), pg.K_RIGHT: (1, 0), pg.K_DOWN: (0, 1), pg.K_LEFT: (-1, 0)}
         for key_code, is_pressed in enumerate(pg.key.get_pressed()):
             rect = rect.move(deltas[key_code]) if key_code in deltas and is_pressed else rect
         screen.fill((0, 0, 0))
    @@ -2964,7 +2964,7 @@ from pygame.transform import scale, …
     ```
     
     ```python
    -from pygame.draw import line, arc, rect
    +from pygame.draw import line, …
     line(, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
     arc(, color, , from_rad, to_rad)    # Also: ellipse(, color, )
     rect(, color, )                     # Also: polygon(, color, points)
    diff --git a/index.html b/index.html
    index 099d36c8f..223ce2536 100644
    --- a/index.html
    +++ b/index.html
    @@ -2511,7 +2511,7 @@
     screen = pg.display.set_mode((500, 500))
     rect = pg.Rect(240, 240, 20, 20)
     while all(event.type != pg.QUIT for event in pg.event.get()):
    -    deltas = {pg.K_UP: (0, -3), pg.K_RIGHT: (3, 0), pg.K_DOWN: (0, 3), pg.K_LEFT: (-3, 0)}
    +    deltas = {pg.K_UP: (0, -1), pg.K_RIGHT: (1, 0), pg.K_DOWN: (0, 1), pg.K_LEFT: (-1, 0)}
         for key_code, is_pressed in enumerate(pg.key.get_pressed()):
             rect = rect.move(deltas[key_code]) if key_code in deltas and is_pressed else rect
         screen.fill((0, 0, 0))
    @@ -2548,7 +2548,7 @@
     <Surf> = rotate(<Surf>, degrees)                # Returns rotated and scaled surface.
     <Surf> = flip(<Surf>, x_bool, y_bool)           # Returns flipped surface.
     
    -
    from pygame.draw import line, arc, rect
    +
    from pygame.draw import line, …
     line(<Surf>, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
     arc(<Surf>, color, <Rect>, from_rad, to_rad)    # Also: ellipse(<Surf>, color, <Rect>)
     rect(<Surf>, color, <Rect>)                     # Also: polygon(<Surf>, color, points)
    
    From ce3261bed8d99615c197f38496a5eea98417f494 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 29 Apr 2021 03:30:43 +0200
    Subject: [PATCH 018/721] Numbers
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 2ff7e353f..c2f5a3890 100644
    --- a/README.md
    +++ b/README.md
    @@ -500,7 +500,7 @@ Numbers
     ### Math
     ```python
     from math import e, pi, inf, nan, isinf, isnan
    -from math import cos, sin, tan, acos, asin, atan, degrees, radians
    +from math import sin, cos, tan, asin, acos, atan, degrees, radians
     from math import log, log10, log2
     ```
     
    diff --git a/index.html b/index.html
    index 223ce2536..dc8594425 100644
    --- a/index.html
    +++ b/index.html
    @@ -608,7 +608,7 @@
     

    Math

    from math import e, pi, inf, nan, isinf, isnan
    -from math import cos, sin, tan, acos, asin, atan, degrees, radians
    +from math import sin, cos, tan, asin, acos, atan, degrees, radians
     from math import log, log10, log2
     
    From d1bdde452d152debfef8ab9b7cd915bce6c6746e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 29 Apr 2021 03:32:36 +0200 Subject: [PATCH 019/721] Numbers --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c2f5a3890..ecd876a23 100644 --- a/README.md +++ b/README.md @@ -531,7 +531,7 @@ from random import random, randint, choice, shuffle, gauss, seed = & # And = | # Or = ^ # Xor (0 if both bits equal) - = << n_bits # Shift left (>> for right) + = << n_bits # Left shift (>> for right) = ~ # Not (also: - - 1) ``` diff --git a/index.html b/index.html index dc8594425..d7e629b3c 100644 --- a/index.html +++ b/index.html @@ -631,7 +631,7 @@

    Bitwise Operators

    <int> = <int> & <int>                    # And
     <int> = <int> | <int>                    # Or
     <int> = <int> ^ <int>                    # Xor (0 if both bits equal)
    -<int> = <int> << n_bits                  # Shift left (>> for right)
    +<int> = <int> << n_bits                  # Left shift (>> for right)
     <int> = ~<int>                           # Not (also: -<int> - 1)
     
    From 05ea5c02dcfe502919b3ef1bc5539c5acfcaeb2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 29 Apr 2021 03:51:37 +0200 Subject: [PATCH 020/721] Introspection --- README.md | 4 ++-- index.html | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ecd876a23..983d8d28e 100644 --- a/README.md +++ b/README.md @@ -2141,8 +2141,8 @@ Introspection ### Attributes ```python = dir() # Names of object's attributes (incl. methods). - = vars() # Dict of object's fields. Also .__dict__. - = hasattr(, '') # Checks if getattr() raises an error. + = vars() # Dict of writable attrs. Also .__dict__. + = hasattr(, '') # Checks if getattr() raises an AttributeError. value = getattr(, '') # Raises AttributeError if attribute is missing. setattr(, '', value) # Only works on objects with __dict__ attribute. delattr(, '') # Equivalent to `del .`. diff --git a/index.html b/index.html index d7e629b3c..55df02804 100644 --- a/index.html +++ b/index.html @@ -1905,8 +1905,8 @@

    Attributes

    <list> = dir(<object>)                     # Names of object's attributes (incl. methods).
    -<dict> = vars(<object>)                    # Dict of object's fields. Also <obj>.__dict__.
    -<bool> = hasattr(<object>, '<attr_name>')  # Checks if getattr() raises an error.
    +<dict> = vars(<object>)                    # Dict of writable attrs. Also <obj>.__dict__.
    +<bool> = hasattr(<object>, '<attr_name>')  # Checks if getattr() raises an AttributeError.
     value  = getattr(<object>, '<attr_name>')  # Raises AttributeError if attribute is missing.
     setattr(<object>, '<attr_name>', value)    # Only works on objects with __dict__ attribute.
     delattr(<object>, '<attr_name>')           # Equivalent to `del <object>.<attr_name>`.
    
    From ead33624a39410947dc137f5696a9cd2043353f8 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 30 Apr 2021 03:12:12 +0200
    Subject: [PATCH 021/721] Introspection
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 983d8d28e..18ca85b09 100644
    --- a/README.md
    +++ b/README.md
    @@ -2141,7 +2141,7 @@ Introspection
     ### Attributes
     ```python
      = dir()                     # Names of object's attributes (incl. methods).
    - = vars()                    # Dict of writable attrs. Also .__dict__.
    + = vars()                    # Dict of writable attributes. Also .__dict__.
      = hasattr(, '')  # Checks if getattr() raises an AttributeError.
     value  = getattr(, '')  # Raises AttributeError if attribute is missing.
     setattr(, '', value)    # Only works on objects with __dict__ attribute.
    diff --git a/index.html b/index.html
    index 55df02804..c4d37f2bf 100644
    --- a/index.html
    +++ b/index.html
    @@ -1905,7 +1905,7 @@
     
     
     

    Attributes

    <list> = dir(<object>)                     # Names of object's attributes (incl. methods).
    -<dict> = vars(<object>)                    # Dict of writable attrs. Also <obj>.__dict__.
    +<dict> = vars(<object>)                    # Dict of writable attributes. Also <obj>.__dict__.
     <bool> = hasattr(<object>, '<attr_name>')  # Checks if getattr() raises an AttributeError.
     value  = getattr(<object>, '<attr_name>')  # Raises AttributeError if attribute is missing.
     setattr(<object>, '<attr_name>', value)    # Only works on objects with __dict__ attribute.
    
    From e2cdb93ff6faedba7297dfd737eec125ad112b79 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 7 May 2021 23:54:06 +0200
    Subject: [PATCH 022/721] Struct, Array, Memoryview, Plot
    
    ---
     README.md  | 11 ++++++-----
     index.html | 13 +++++++------
     2 files changed, 13 insertions(+), 11 deletions(-)
    
    diff --git a/README.md b/README.md
    index 18ca85b09..c80d3b3e8 100644
    --- a/README.md
    +++ b/README.md
    @@ -1938,7 +1938,7 @@ def write_bytes(filename, bytes_obj):
     Struct
     ------
     * **Module that performs conversions between a sequence of numbers and a bytes object.**
    -* **Machine’s native type sizes and byte order are used by default.**
    +* **System’s native type sizes and byte order are used by default.**
     
     ```python
     from struct import pack, unpack, iter_unpack
    @@ -1986,6 +1986,7 @@ from array import array
      = array('', )         # Array from bytes object.
      = array('', )         # Treats array as a sequence of numbers.
      = bytes()                       # Or: .tobytes()
    +.write()                          # Writes array to the binary file.
     ```
     
     
    @@ -1994,6 +1995,7 @@ Memory View
     * **A sequence object that points to the memory of another object.**
     * **Each element can reference a single or multiple consecutive bytes, depending on format.**
     * **Order and number of elements can be changed with slicing.**
    +* **Casting only works between char and other types and always uses native size and b. order.**
     
     ```python
      = memoryview()  # Immutable if bytes, else mutable.
    @@ -2005,10 +2007,10 @@ Memory View
     
     ### Decode
     ```python
    -.write()                      # Writes mview to the binary file.
      = bytes()                       # Creates a new bytes object.
      = .join()       # Joins mviews using bytes object as sep.
      = array('', )         # Treats mview as a sequence of numbers.
    +.write()                          # Writes mview to the binary file.
     ```
     
     ```python
    @@ -2342,8 +2344,7 @@ Plot
     ```python
     # $ pip3 install matplotlib
     import matplotlib.pyplot as plt
    -plt.plot( [, label=])
    -plt.plot(, )
    +plt.plot(,  [, label=])   # Or: plt.plot()
     plt.legend()                                   # Adds a legend.
     plt.savefig()                            # Saves the figure.
     plt.show()                                     # Displays the figure.
    @@ -2370,7 +2371,7 @@ Curses
     #### Runs a basic file explorer in the terminal:
     ```python
     from curses import wrapper, ascii, A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER
    -from os import listdir, chdir, path
    +from os import listdir, path, chdir
     
     def main(screen):
         ch, first, selected, paths = 0, 0, 0, listdir()
    diff --git a/index.html b/index.html
    index c4d37f2bf..ea5bfee0d 100644
    --- a/index.html
    +++ b/index.html
    @@ -1752,7 +1752,7 @@
     
     

    #Struct

    • Module that performs conversions between a sequence of numbers and a bytes object.
    • -
    • Machine’s native type sizes and byte order are used by default.
    • +
    • System’s native type sizes and byte order are used by default.
    from struct import pack, unpack, iter_unpack
     
    @@ -1792,6 +1792,7 @@ <array> = array('<typecode>', <bytes>) # Array from bytes object. <array> = array('<typecode>', <array>) # Treats array as a sequence of numbers. <bytes> = bytes(<array>) # Or: <array>.tobytes() +<file>.write(<array>) # Writes array to the binary file.
    @@ -1799,6 +1800,7 @@
  • A sequence object that points to the memory of another object.
  • Each element can reference a single or multiple consecutive bytes, depending on format.
  • Order and number of elements can be changed with slicing.
  • +
  • Casting only works between char and other types and always uses native size and b. order.
  • <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
     <real>  = <mview>[<index>]                     # Returns an int or a float.
     <mview> = <mview>[<slice>]                     # Mview with rearranged elements.
    @@ -1807,10 +1809,10 @@
     
    -

    Decode

    <bin_file>.write(<mview>)                      # Writes mview to the binary file.
    -<bytes> = bytes(<mview>)                       # Creates a new bytes object.
    +

    Decode

    <bytes> = bytes(<mview>)                       # Creates a new bytes object.
     <bytes> = <bytes>.join(<coll_of_mviews>)       # Joins mviews using bytes object as sep.
     <array> = array('<typecode>', <mview>)         # Treats mview as a sequence of numbers.
    +<file>.write(<mview>)                          # Writes mview to the binary file.
     
    <list>  = list(<mview>)                        # Returns list of ints or floats.
    @@ -2061,8 +2063,7 @@
     
     

    #Plot

    # $ pip3 install matplotlib
     import matplotlib.pyplot as plt
    -plt.plot(<y_data> [, label=<str>])
    -plt.plot(<x_data>, <y_data>)
    +plt.plot(<x_data>, <y_data> [, label=<str>])   # Or: plt.plot(<y_data>)
     plt.legend()                                   # Adds a legend.
     plt.savefig(<path>)                            # Saves the figure.
     plt.show()                                     # Displays the figure.
    @@ -2080,7 +2081,7 @@
     
     
     

    #Curses

    Runs a basic file explorer in the terminal:

    from curses import wrapper, ascii, A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER
    -from os import listdir, chdir, path
    +from os import listdir, path, chdir
     
     def main(screen):
         ch, first, selected, paths = 0, 0, 0, listdir()
    
    From 3ab66cd3aae5efa7420eeac26cb3cc517f275381 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 13 May 2021 14:56:41 +0200
    Subject: [PATCH 023/721] Updated a link to text file
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index c80d3b3e8..12c4031ca 100644
    --- a/README.md
    +++ b/README.md
    @@ -1,6 +1,6 @@
     Comprehensive Python Cheatsheet
     ===============================
    -[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions).
    +[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions).
     
     
     ![Monty Python](web/image_888.jpeg)
    diff --git a/index.html b/index.html
    index ea5bfee0d..4b6f8010b 100644
    --- a/index.html
    +++ b/index.html
    @@ -231,7 +231,7 @@
       
     
       
    -   

    Comprehensive Python Cheatsheet

    Comprehensive Python Cheatsheet


    #Contents

    ToC = {
         '1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
         '2. Types':       [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],
    
    From cab456867b4a00e488804d8771a45769b9b75951 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 15 May 2021 15:03:59 +0200
    Subject: [PATCH 024/721] OS commands, SQLite, Bytes
    
    ---
     README.md              | 17 ++++++++++-------
     index.html             | 21 ++++++++++++---------
     parse.js               |  2 +-
     pdf/index_for_pdf.html |  6 +++---
     web/script_2.js        |  4 ++--
     5 files changed, 28 insertions(+), 22 deletions(-)
    
    diff --git a/README.md b/README.md
    index 12c4031ca..1953f2927 100644
    --- a/README.md
    +++ b/README.md
    @@ -13,7 +13,7 @@ Contents
     **   ** **3. Syntax:** **         **  **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Closure`](#closure)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#exceptions)**__.__  
     **   ** **4. System:** **        **  **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__  
     **   ** **5. Data:** **             **  **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__  
    -**   ** **6. Advanced:** **   **  **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprograming)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutines`](#coroutines)**__.__  
    +**   ** **6. Advanced:** **   **  **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprogramming)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutines`](#coroutines)**__.__  
     **   ** **7. Libraries:** **      **  **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Curses`](#curses)**__,__ **[`Logging`](#logging)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web)**__,__ **[`Profile`](#profiling)**__,__  
     **                                 ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Audio`](#audio)**__,__ **[`Games`](#pygame)**__,__ **[`Data`](#pandas)**__.__
     
    @@ -1670,6 +1670,7 @@ import os, shutil
     ```python
     os.chdir()                    # Changes the current working directory.
     os.mkdir(, mode=0o777)        # Creates a directory. Mode is in octal.
    +os.makedirs(, mode=0o777)     # Creates all directories in the path.
     ```
     
     ```python
    @@ -1850,13 +1851,14 @@ import sqlite3
     ### Write
     ```python
     .execute('')                       # Can raise a subclass of sqlite3.Error.
    -.commit()                                 # Commits all transactions since last commit.
    +.commit()                                 # Saves all changes since the last commit.
    +.rollback()                               # Discards all changes since the last commit.
     ```
     
     #### Or:
     ```python
    -with :
    -    .execute('')
    +with :                                    # Exits block with commit() or rollback(),
    +    .execute('')                   # depending on whether an exception occurred.
     ```
     
     ### Placeholders
    @@ -1901,7 +1903,7 @@ Bytes
      = b''                       # Only accepts ASCII characters and \x00-\xff.
        = []               # Returns int in range from 0 to 255.
      = []               # Returns bytes even if it has only one element.
    - = .join()  # Joins elements using bytes object as separator.
    + = .join()  # Joins elements using bytes as a separator.
     ```
     
     ### Encode
    @@ -1950,6 +1952,7 @@ from struct import pack, unpack, iter_unpack
      = iter_unpack('', )
     ```
     
    +### Example
     ```python
     >>> pack('>hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
    @@ -2160,8 +2163,8 @@ from inspect import signature
     ```
     
     
    -Metaprograming
    ---------------
    +Metaprogramming
    +---------------
     **Code that generates code.**
     
     ### Type
    diff --git a/index.html b/index.html
    index 4b6f8010b..820e0841e 100644
    --- a/index.html
    +++ b/index.html
    @@ -238,7 +238,7 @@
         '3. Syntax':      [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],
         '4. System':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
         '5. Data':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
    -    '6. Advanced':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
    +    '6. Advanced':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
         '7. Libraries':   [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
                            NumPy, Image, Audio, Games, Data]
     }
    @@ -1556,6 +1556,7 @@
     
     
    os.chdir(<path>)                    # Changes the current working directory.
     os.mkdir(<path>, mode=0o777)        # Creates a directory. Mode is in octal.
    +os.makedirs(<path>, mode=0o777)     # Creates all directories in the path.
     
    shutil.copy(from, to)               # Copies the file. 'to' can exist or be a dir.
     shutil.copytree(from, to)           # Copies the directory. 'to' must not exist.
    @@ -1686,11 +1687,12 @@
     
     
     

    Write

    <conn>.execute('<query>')                       # Can raise a subclass of sqlite3.Error.
    -<conn>.commit()                                 # Commits all transactions since last commit.
    +<conn>.commit()                                 # Saves all changes since the last commit.
    +<conn>.rollback()                               # Discards all changes since the last commit.
     
    -

    Or:

    with <conn>:
    -    <conn>.execute('<query>')
    +

    Or:

    with <conn>:                                    # Exits block with commit() or rollback(),
    +    <conn>.execute('<query>')                   # depending on whether an exception occurred.
     

    Placeholders

      @@ -1724,7 +1726,7 @@

      #Bytes

      Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

      <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
       <int>   = <bytes>[<index>]               # Returns int in range from 0 to 255.
       <bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
      -<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes object as separator.
      +<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes as a separator.
       
      @@ -1761,11 +1763,12 @@ <tuple> = unpack('<format>', <bytes>) <tuples> = iter_unpack('<format>', <bytes>)
    -
    >>> pack('>hhl', 1, 2, 3)
    +

    Example

    >>> pack('>hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
     >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
     (1, 2, 3)
    -
    +
    +

    Format

    For standard type sizes start format string with:

    • '=' - native byte order (usually little-endian)
    • '<' - little-endian
    • @@ -1921,7 +1924,7 @@ <memb> = <Param>.kind # Member of ParameterKind enum.
    -

    #Metaprograming

    Code that generates code.

    Type

    Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.

    <class> = type('<class_name>', <parents_tuple>, <attributes_dict>)
    +

    #Metaprogramming

    Code that generates code.

    Type

    Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.

    <class> = type('<class_name>', <parents_tuple>, <attributes_dict>)
    @@ -2300,7 +2303,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
    -

    3. If neither non-matching dimension has size 1, raise an error.

    Example

    For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

    >>> points = np.array([0.1, 0.6, 0.8])
    +

    3. If neither non-matching dimension has size 1, raise an error.

    Example

    For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

    >>> points = np.array([0.1, 0.6, 0.8])
      [ 0.1,  0.6,  0.8]
     >>> wrapped_points = points.reshape(3, 1)
     [[ 0.1],
    diff --git a/parse.js b/parse.js
    index 2d56bc6d7..c760811a9 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -24,7 +24,7 @@ const TOC =
       '    \'3. Syntax\':      [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],\n' +
       '    \'4. System\':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],\n' +
       '    \'5. Data\':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],\n' +
    -  '    \'6. Advanced\':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' +
    +  '    \'6. Advanced\':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' +
       '    \'7. Libraries\':   [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,\n' +
       '                       NumPy, Image, Audio, Games, Data]\n' +
       '}\n' +
    diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html
    index 43ffa77b4..afd9e5c82 100644
    --- a/pdf/index_for_pdf.html
    +++ b/pdf/index_for_pdf.html
    @@ -20,7 +20,7 @@ 

    B

    C

    cache, 13
    callable, 17
    -class, 4, 14-20, 31-32
    +class, 4, 14-20, 31-32
    closure, 12-13
    collection, 4, 18, 19
    collections module, 2, 3, 4, 19, 29
    @@ -85,7 +85,7 @@

    M

    math module, 7
    memoryviews, 29
    metaclass attribute, 32
    -metaprograming, 31-32
    +metaprogramming, 31-32
    mysql library, 27

    N

    namedtuples, 3
    @@ -139,7 +139,7 @@

    T

    threading module, 30
    time module, 34, 36
    tuples, 3, 4, 11
    -type, 4, 31-32

    +type, 4, 31-32

    W

    wave module, 40-41
    web, 36

    diff --git a/web/script_2.js b/web/script_2.js index 97691b47b..efb56e947 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -5,7 +5,7 @@ const TOC = ' \'3. Syntax\': [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],\n' + ' \'4. System\': [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],\n' + ' \'5. Data\': [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],\n' + - ' \'6. Advanced\': [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' + + ' \'6. Advanced\': [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' + ' \'7. Libraries\': [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,\n' + ' NumPy, Image, Audio, Games, Data]\n' + '}\n'; @@ -30,7 +30,7 @@ const TOC_MOBILE = ' Memory_View, Deque],\n' + ' \'6. Advanced\': [Threading, Operator,\n' + ' Introspection,\n' + - ' Metaprograming, Eval,\n' + + ' Metaprograming, Eval,\n' + ' Coroutine],\n' + ' \'7. Libraries\': [Progress_Bar, Plot, Table,\n' + ' Curses, Logging, Scraping,\n' + From 606208ac68a2191d8281f3bfe1903e3233590908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 16 May 2021 14:36:20 +0200 Subject: [PATCH 025/721] Web, Profiling --- README.md | 15 +++++++-------- index.html | 15 +++++++-------- pdf/index_for_pdf.html | 2 +- pdf/index_for_pdf_print.html | 2 +- 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 1953f2927..b30c92352 100644 --- a/README.md +++ b/README.md @@ -2496,7 +2496,7 @@ def send_page(sport): ### REST Request ```python -@post('/odds/') +@post('//odds') def odds_handler(sport): team = request.forms.get('team') home_odds, away_odds = 2.44, 3.29 @@ -2510,7 +2510,7 @@ def odds_handler(sport): # $ pip3 install requests >>> import threading, requests >>> threading.Thread(target=run, daemon=True).start() ->>> url = 'http://localhost:8080/odds/football' +>>> url = 'http://localhost:8080/football/odds' >>> data = {'team': 'arsenal f.c.'} >>> response = requests.post(url, data=data) >>> response.json() @@ -2577,11 +2577,10 @@ Line # Mem usage Increment Line Contents ### Call Graph #### Generates a PNG image of a call graph with highlighted bottlenecks: ```python -# $ pip3 install pycallgraph -from pycallgraph import output, PyCallGraph +# $ pip3 install pycallgraph2 +from pycallgraph2 import output, PyCallGraph from datetime import datetime -time_str = datetime.now().strftime('%Y%m%d%H%M%S') -filename = f'profile-{time_str}.png' +filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png' drawer = output.GraphvizOutput(output_file=filename) with PyCallGraph(drawer): @@ -2961,14 +2960,14 @@ while all(event.type != pg.QUIT for event in pg.event.get()): ``` ```python -from pygame.transform import scale, … +from pygame.transform import scale, ... = scale(, (width, height)) # Returns scaled surface. = rotate(, degrees) # Returns rotated and scaled surface. = flip(, x_bool, y_bool) # Returns flipped surface. ``` ```python -from pygame.draw import line, … +from pygame.draw import line, ... line(, color, (x1, y1), (x2, y2), width) # Draws a line to the surface. arc(, color, , from_rad, to_rad) # Also: ellipse(, color, ) rect(, color, ) # Also: polygon(, color, points) diff --git a/index.html b/index.html index 820e0841e..d8f6b6da2 100644 --- a/index.html +++ b/index.html @@ -2184,7 +2184,7 @@ return template('<h1>{{title}}</h1>', title=sport)
    -

    REST Request

    @post('/odds/<sport>')
    +

    REST Request

    @post('/<sport>/odds')
     def odds_handler(sport):
         team = request.forms.get('team')
         home_odds, away_odds = 2.44, 3.29
    @@ -2196,7 +2196,7 @@
     

    Test:

    # $ pip3 install requests
     >>> import threading, requests
     >>> threading.Thread(target=run, daemon=True).start()
    ->>> url = 'http://localhost:8080/odds/football'
    +>>> url = 'http://localhost:8080/football/odds'
     >>> data = {'team': 'arsenal f.c.'}
     >>> response = requests.post(url, data=data)
     >>> response.json()
    @@ -2246,11 +2246,10 @@
          3        38.012 MiB      0.344 MiB       a = [*range(10000)]
          4        38.477 MiB      0.465 MiB       b = {*range(10000)}
     
    -

    Call Graph

    Generates a PNG image of a call graph with highlighted bottlenecks:

    # $ pip3 install pycallgraph
    -from pycallgraph import output, PyCallGraph
    +

    Call Graph

    Generates a PNG image of a call graph with highlighted bottlenecks:

    # $ pip3 install pycallgraph2
    +from pycallgraph2 import output, PyCallGraph
     from datetime import datetime
    -time_str = datetime.now().strftime('%Y%m%d%H%M%S')
    -filename = f'profile-{time_str}.png'
    +filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png'
     drawer = output.GraphvizOutput(output_file=filename)
     with PyCallGraph(drawer):
         <code_to_be_profiled>
    @@ -2547,12 +2546,12 @@
     <Surf>.set_at((x, y), color)                    # Updates pixel.
     <Surf>.blit(<Surf>, (x, y))                     # Draws passed surface to the surface.
     
    -
    from pygame.transform import scale, …
    +
    from pygame.transform import scale, ...
     <Surf> = scale(<Surf>, (width, height))         # Returns scaled surface.
     <Surf> = rotate(<Surf>, degrees)                # Returns rotated and scaled surface.
     <Surf> = flip(<Surf>, x_bool, y_bool)           # Returns flipped surface.
     
    -
    from pygame.draw import line, …
    +
    from pygame.draw import line, ...
     line(<Surf>, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
     arc(<Surf>, color, <Rect>, from_rad, to_rad)    # Also: ellipse(<Surf>, color, <Rect>)
     rect(<Surf>, color, <Rect>)                     # Also: polygon(<Surf>, color, points)
    diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html
    index afd9e5c82..192cb16f5 100644
    --- a/pdf/index_for_pdf.html
    +++ b/pdf/index_for_pdf.html
    @@ -51,7 +51,7 @@ 

    F

    files, 22-29, 34, 46
    filter function, 11
    floats, 4, 6, 7
    -format, 6-7
    +format, 6-7, 37
    functools module, 11, 12, 13, 16
    futures, 30

    G

    diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 84a1d47b8..5d9519c36 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -51,7 +51,7 @@

    F

    files, 22-29, 34, 46
    filter function, 11
    floats, 4, 6, 7
    -format, 6-7
    +format, 6-7, 37
    functools module, 11, 12, 13, 16
    futures, 30

    G

    From a658334dfe5f5d49c6e8964577676f04972c59a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 19 May 2021 23:39:52 +0200 Subject: [PATCH 026/721] Regex, Format, Struct, Threading --- README.md | 30 ++++++++++++++++-------------- index.html | 38 ++++++++++++++++++++------------------ 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index b30c92352..a88494f3d 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ import re ### Special Sequences * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.** -* **As shown below, it restricts special sequence matches to `'[\x00-\x7f]'` and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.** +* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.** * **Use a capital letter for negation.** ```python '\d' == '[0-9]' # Matches decimal characters. @@ -412,9 +412,10 @@ Format {:.<10} # '......' {:0} # '' ``` +* **Use `'{:{}[...]}'` to set options dynamically.** +* **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.** ### Strings -**`'!r'` calls object's [repr()](#class) method, instead of [str()](#class), to get a string.** ```python {'abcde'!r:10} # "'abcde' " {'abcde':10.3} # 'abc ' @@ -1286,7 +1287,9 @@ Enum ---- ```python from enum import Enum, auto +``` +```python class (Enum): = = , @@ -1857,7 +1860,7 @@ import sqlite3 #### Or: ```python -with : # Exits block with commit() or rollback(), +with : # Exits the block with commit() or rollback(), .execute('') # depending on whether an exception occurred. ``` @@ -1940,7 +1943,7 @@ def write_bytes(filename, bytes_obj): Struct ------ * **Module that performs conversions between a sequence of numbers and a bytes object.** -* **System’s native type sizes and byte order are used by default.** +* **System’s type sizes and byte order are used by default.** ```python from struct import pack, unpack, iter_unpack @@ -1962,7 +1965,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' ### Format #### For standard type sizes start format string with: -* **`'='` - native byte order (usually little-endian)** +* **`'='` - system's byte order (usually little-endian)** * **`'<'` - little-endian** * **`'>'` - big-endian (also `'!'`)** @@ -1998,7 +2001,7 @@ Memory View * **A sequence object that points to the memory of another object.** * **Each element can reference a single or multiple consecutive bytes, depending on format.** * **Order and number of elements can be changed with slicing.** -* **Casting only works between char and other types and always uses native size and b. order.** +* **Casting only works between char and other types and uses system's sizes and byte order.** ```python = memoryview() # Immutable if bytes, else mutable. @@ -2052,10 +2055,10 @@ from concurrent.futures import ThreadPoolExecutor ### Thread ```python - = Thread(target=) # Use `args=` to set arguments. + = Thread(target=) # Use `args=` to set the arguments. .start() # Starts the thread. - = .is_alive() # Checks if thread has finished executing. -.join() # Waits for thread to finish. + = .is_alive() # Checks if the thread has finished executing. +.join() # Waits for the thread to finish. ``` * **Use `'kwargs='` to pass keyword arguments to the function.** * **Use `'daemon=True'`, or the program will not be able to exit while the thread is alive.** @@ -2063,15 +2066,14 @@ from concurrent.futures import ThreadPoolExecutor ### Lock ```python = RLock() # Lock that can only be released by the owner. -.acquire() # Waits for lock to be available. -.release() # Makes lock available again. +.acquire() # Waits for the lock to be available. +.release() # Makes the lock available again. ``` #### Or: ```python -lock = RLock() -with lock: - ... +with : # Enters the block by calling acquire(), + ... # and exits it with release(). ``` ### Semaphore, Event, Barrier diff --git a/index.html b/index.html index d8f6b6da2..4833a5e14 100644 --- a/index.html +++ b/index.html @@ -508,7 +508,7 @@

    Special Sequences

    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • -
    • As shown below, it restricts special sequence matches to '[\x00-\x7f]' and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
    • +
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
    • Use a capital letter for negation.
    '\d' == '[0-9]'                                # Matches decimal characters.
     '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
    @@ -536,12 +536,15 @@
     {<el>:0}                                       # '<el>'
     
    -

    Strings

    '!r' calls object's repr() method, instead of str(), to get a string.

    {'abcde'!r:10}                                 # "'abcde'   "
    +
      +
    • Use '{<el>:{<str/int/float>}[...]}' to set options dynamically.
    • +
    • Adding '!r' before the colon converts object to string by calling its repr() method.
    • +
    +

    Strings

    {'abcde'!r:10}                                 # "'abcde'   "
     {'abcde':10.3}                                 # 'abc       '
     {'abcde':.3}                                   # 'abc'
     
    -

    Numbers

    { 123456:10,}                                  # '   123,456'
     { 123456:10_}                                  # '   123_456'
     { 123456:+10}                                  # '   +123456'
    @@ -1252,13 +1255,13 @@
     
  • Names of their required methods are stored in '<abc>.__abstractmethods__'.
  • #Enum

    from enum import Enum, auto
    +
    -class <enum_name>(Enum): +
    class <enum_name>(Enum):
         <member_name_1> = <value_1>
         <member_name_2> = <value_2_a>, <value_2_b>
         <member_name_3> = auto()
    -
    - +
    • If there are no numeric values before auto(), it returns 1.
    • Otherwise it returns an increment of the last numeric value.
    • @@ -1691,7 +1694,7 @@ <conn>.rollback() # Discards all changes since the last commit.
    -

    Or:

    with <conn>:                                    # Exits block with commit() or rollback(),
    +

    Or:

    with <conn>:                                    # Exits the block with commit() or rollback(),
         <conn>.execute('<query>')                   # depending on whether an exception occurred.
     
    @@ -1754,7 +1757,7 @@

    #Struct

    • Module that performs conversions between a sequence of numbers and a bytes object.
    • -
    • System’s native type sizes and byte order are used by default.
    • +
    • System’s type sizes and byte order are used by default.
    from struct import pack, unpack, iter_unpack
     
    @@ -1770,7 +1773,7 @@

    Format

    For standard type sizes start format string with:

      -
    • '=' - native byte order (usually little-endian)
    • +
    • '=' - system's byte order (usually little-endian)
    • '<' - little-endian
    • '>' - big-endian (also '!')

    Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:

      @@ -1803,7 +1806,7 @@
    • A sequence object that points to the memory of another object.
    • Each element can reference a single or multiple consecutive bytes, depending on format.
    • Order and number of elements can be changed with slicing.
    • -
    • Casting only works between char and other types and always uses native size and b. order.
    • +
    • Casting only works between char and other types and uses system's sizes and byte order.
    <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
     <real>  = <mview>[<index>]                     # Returns an int or a float.
     <mview> = <mview>[<slice>]                     # Mview with rearranged elements.
    @@ -1841,10 +1844,10 @@
     
    -

    Thread

    <Thread> = Thread(target=<function>)           # Use `args=<collection>` to set arguments.
    +

    Thread

    <Thread> = Thread(target=<function>)           # Use `args=<collection>` to set the arguments.
     <Thread>.start()                               # Starts the thread.
    -<bool> = <Thread>.is_alive()                   # Checks if thread has finished executing.
    -<Thread>.join()                                # Waits for thread to finish.
    +<bool> = <Thread>.is_alive()                   # Checks if the thread has finished executing.
    +<Thread>.join()                                # Waits for the thread to finish.
     
      @@ -1852,13 +1855,12 @@
    • Use 'daemon=True', or the program will not be able to exit while the thread is alive.

    Lock

    <lock> = RLock()                               # Lock that can only be released by the owner.
    -<lock>.acquire()                               # Waits for lock to be available.
    -<lock>.release()                               # Makes lock available again.
    +<lock>.acquire()                               # Waits for the lock to be available.
    +<lock>.release()                               # Makes the lock available again.
     
    -

    Or:

    lock = RLock()
    -with lock:
    -    ...
    +

    Or:

    with <lock>:                                   # Enters the block by calling acquire(),
    +    ...                                        # and exits it with release().
     

    Semaphore, Event, Barrier

    <Semaphore> = Semaphore(value=1)               # Lock that can be acquired by 'value' threads.
    
    From 52abd7b82b865922bcad1272be7fbd12f307b015 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 20 May 2021 11:58:00 +0200
    Subject: [PATCH 027/721] Changed date
    
    ---
     index.html        | 4 ++--
     web/template.html | 4 ++--
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/index.html b/index.html
    index 4833a5e14..bc15fc509 100644
    --- a/index.html
    +++ b/index.html
    @@ -226,7 +226,7 @@
     
     
       
    - +
    @@ -3005,7 +3005,7 @@ diff --git a/web/template.html b/web/template.html index ab2864476..d508fa55b 100644 --- a/web/template.html +++ b/web/template.html @@ -226,7 +226,7 @@
    - +
    @@ -234,7 +234,7 @@
    From f3ea09fe8be31556402ab26f549145e6d445934a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 20 May 2021 12:54:51 +0200 Subject: [PATCH 028/721] Regex --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a88494f3d..19637c4ad 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ import re ### Special Sequences * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.** -* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.** +* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'`.** * **Use a capital letter for negation.** ```python '\d' == '[0-9]' # Matches decimal characters. diff --git a/index.html b/index.html index bc15fc509..bc964be98 100644 --- a/index.html +++ b/index.html @@ -508,7 +508,7 @@

    Special Sequences

    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • -
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
    • +
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]'.
    • Use a capital letter for negation.
    '\d' == '[0-9]'                                # Matches decimal characters.
     '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
    
    From f4d5399d2d58b2afb176c53bfb500d8fdf873133 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 20 May 2021 14:50:43 +0200
    Subject: [PATCH 029/721] Updated remove_links.py script
    
    ---
     pdf/remove_links.py | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/pdf/remove_links.py b/pdf/remove_links.py
    index 2f97aef27..1dc54a4ed 100755
    --- a/pdf/remove_links.py
    +++ b/pdf/remove_links.py
    @@ -8,9 +8,9 @@
     
     MATCHES = {
         'Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.': 'Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.',
    -    '\'!r\' calls object\'s repr() method, instead of str(), to get a string.': '\'!r\' calls object\'s repr() method, instead of str(), to get a string (p. 14).',
    +    'Adding \'!r\' before the colon converts object to string by calling its repr() method.': 'Adding \'!r\' before the colon converts object to string by calling its repr() method (p. 14).',
         'Default_factory can be any callable.': 'Default_factory can be any callable (p. 17).',
    -    'Iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).',
    +    'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).',
         'Objects returned by the itertools module, such as count, repeat and cycle.': 'Objects returned by the itertools module, such as count, repeat and cycle (p. 3).',
         'Generators returned by the generator functions and generator expressions.': 'Generators returned by the generator functions (p. 4) and generator expressions (p. 11).',
         'File objects returned by the open() function, etc.': 'File objects returned by the open() function (p. 22), etc.',
    
    From de1f11380cdaa01f68bbe8f68261b3176c9024ee Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 28 Jul 2021 20:03:59 +0200
    Subject: [PATCH 030/721] Updated parse.js documentation
    
    ---
     .gitignore |  3 +++
     parse.js   | 12 +++++++++---
     2 files changed, 12 insertions(+), 3 deletions(-)
     create mode 100644 .gitignore
    
    diff --git a/.gitignore b/.gitignore
    new file mode 100644
    index 000000000..b8ffe08f2
    --- /dev/null
    +++ b/.gitignore
    @@ -0,0 +1,3 @@
    +node_modules/
    +package-lock.json
    +
    diff --git a/parse.js b/parse.js
    index c760811a9..69f53d0ea 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -1,12 +1,18 @@
     #!/usr/bin/env node
     // Usage: node parse.js
    +//
     // Script that creates index.html out of web/template.html and README.md.
     // It is written in JS because this code used to be executed on the client side.
    -// To install dependencies run:
    -// $ npm install -g jsdom jquery showdown highlightjs
    -// If running on Mac and modules can't be found after installation add:
    +// To install the Node.js and npm run:
    +// $ sudo apt install nodejs npm  # On macOS use `brew install ...` instead.
    +// To install dependencies globally, run:
    +// $ npm install -g jsdom jquery showdown highlightjs@9.12.0
    +// If running on macOS and modules can't be found after installation add:
     // export NODE_PATH=/usr/local/lib/node_modules
     // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'.
    +// To avoid problems with permissions and path variables, install modules
    +// into project's directory using:
    +// $ npm install jsdom jquery showdown highlightjs@9.12.0
     
     
     const fs = require('fs');
    
    From 6b23015f735d6080670dd358bb6f61cc9a828580 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 28 Jul 2021 20:15:25 +0200
    Subject: [PATCH 031/721] Updated parse.js documentation
    
    ---
     parse.js | 3 +++
     1 file changed, 3 insertions(+)
    
    diff --git a/parse.js b/parse.js
    index 69f53d0ea..aaba64012 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -13,6 +13,9 @@
     // To avoid problems with permissions and path variables, install modules
     // into project's directory using:
     // $ npm install jsdom jquery showdown highlightjs@9.12.0
    +// It is also advisable to add a script into .git/hooks directory, that will run 
    +// this script before every commit. It should be named 'pre-commit' and it should
    +// contain the following line: `./parse.js`.
     
     
     const fs = require('fs');
    
    From 332bf7e913a7849943c77824425e4b30afe1876a Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 29 Jul 2021 00:58:34 +0200
    Subject: [PATCH 032/721] Removed .gitignore
    
    ---
     .gitignore | 3 ---
     1 file changed, 3 deletions(-)
     delete mode 100644 .gitignore
    
    diff --git a/.gitignore b/.gitignore
    deleted file mode 100644
    index b8ffe08f2..000000000
    --- a/.gitignore
    +++ /dev/null
    @@ -1,3 +0,0 @@
    -node_modules/
    -package-lock.json
    -
    
    From 1fa9a9939b3ebb086a041d1a021d89f372f308d5 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 11 Aug 2021 21:18:55 +0200
    Subject: [PATCH 033/721] Parse.js now automatically updates the date of
     index.html
    
    ---
     index.html        |  6 +++---
     parse.js          | 26 ++++++++++++++++++++++----
     web/template.html |  2 +-
     3 files changed, 26 insertions(+), 8 deletions(-)
    
    diff --git a/index.html b/index.html
    index bc964be98..e62fe063f 100644
    --- a/index.html
    +++ b/index.html
    @@ -226,7 +226,7 @@
     
     
       
    - +
    @@ -3005,8 +3005,8 @@ diff --git a/parse.js b/parse.js index aaba64012..ab5bdbe32 100755 --- a/parse.js +++ b/parse.js @@ -2,20 +2,25 @@ // Usage: node parse.js // // Script that creates index.html out of web/template.html and README.md. +// // It is written in JS because this code used to be executed on the client side. // To install the Node.js and npm run: // $ sudo apt install nodejs npm # On macOS use `brew install ...` instead. +// // To install dependencies globally, run: // $ npm install -g jsdom jquery showdown highlightjs@9.12.0 +// // If running on macOS and modules can't be found after installation add: // export NODE_PATH=/usr/local/lib/node_modules // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'. +// // To avoid problems with permissions and path variables, install modules // into project's directory using: // $ npm install jsdom jquery showdown highlightjs@9.12.0 -// It is also advisable to add a script into .git/hooks directory, that will run -// this script before every commit. It should be named 'pre-commit' and it should -// contain the following line: `./parse.js`. +// +// It is also advisable to add a Bash script into .git/hooks directory, that will +// run this script before every commit. It should be named 'pre-commit' and it +// should contain the following line: `./parse.js`. const fs = require('fs'); @@ -408,7 +413,8 @@ function main() { const html = getMd(); initDom(html); modifyPage(); - const template = readFile('web/template.html'); + var template = readFile('web/template.html'); + template = updateDate(template); const tokens = template.split('
    '); const text = `${tokens[0]} ${document.body.innerHTML} ${tokens[1]}`; writeToFile('index.html', text); @@ -580,6 +586,18 @@ function removePlotImages() { $('img[alt="Covid Cases"]').remove(); } + +function updateDate(template) { + const date = new Date(); + const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'}); + template = template.replace('May 20, 2021', date_str); + template = template.replace('May 20, 2021', date_str); + return template; +} + + +// UTIL + function readFile(filename) { try { return fs.readFileSync(filename, 'utf8'); diff --git a/web/template.html b/web/template.html index d508fa55b..8db5fe75e 100644 --- a/web/template.html +++ b/web/template.html @@ -235,7 +235,7 @@ From dd37505f3fc1c80bef73d9c5ec798a7dc49c550d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Oct 2021 01:22:39 +0200 Subject: [PATCH 034/721] Inline --- README.md | 22 +++++++++++----------- index.html | 26 +++++++++++++------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 19637c4ad..26e451a55 100644 --- a/README.md +++ b/README.md @@ -732,10 +732,10 @@ def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3 ### Other Uses ```python - = [* [, ...]] - = {* [, ...]} - = (*, [...]) - = {** [, ...]} + = [* [, ...]] + = {* [, ...]} + = (*, [...]) + = {** [, ...]} ``` ```python @@ -774,8 +774,8 @@ Inline ### Any, All ```python - = any() # False if empty. - = all(el[1] for el in ) # True if empty. + = any() # Is `bool(el)` True for any element. + = all() # Is True for all elements or empty. ``` ### Conditional Expression @@ -788,11 +788,11 @@ Inline ['zero', 1, 2, 3] ``` -### Namedtuple, Enum, Dataclass +### Named Tuple, Enum, Dataclass ```python from collections import namedtuple -Point = namedtuple('Point', 'x y') -point = Point(0, 0) +Point = namedtuple('Point', 'x y') +point = Point(0, 0) ``` ```python @@ -803,8 +803,8 @@ direction = Direction.n ```python from dataclasses import make_dataclass -Creature = make_dataclass('Creature', ['loc', 'dir']) -creature = Creature(Point(0, 0), Direction.n) +Creature = make_dataclass('Creature', ['loc', 'dir']) +creature = Creature(point, direction) ``` diff --git a/index.html b/index.html index e62fe063f..6a3e2e703 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -786,10 +786,10 @@ def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
    -

    Other Uses

    <list> = [*<collection> [, ...]]
    -<set>  = {*<collection> [, ...]}
    -<tup.> = (*<collection>, [...])
    -<dict> = {**<dict> [, ...]}
    +

    Other Uses

    <list>  = [*<collection> [, ...]]
    +<set>   = {*<collection> [, ...]}
    +<tuple> = (*<collection>, [...])
    +<dict>  = {**<dict> [, ...]}
     
    head, *body, tail = <collection>
    @@ -816,8 +816,8 @@
     
    • Reduce must be imported from functools module.
    -

    Any, All

    <bool> = any(<collection>)                                # False if empty.
    -<bool> = all(el[1] for el in <collection>)                # True if empty.
    +

    Any, All

    <bool> = any(<collection>)                                # Is `bool(el)` True for any element.
    +<bool> = all(<collection>)                                # Is True for all elements or empty.
     

    Conditional Expression

    <obj> = <exp_if_true> if <condition> else <exp_if_false>
    @@ -826,9 +826,9 @@
     
    >>> [a if a else 'zero' for a in (0, 1, 2, 3)]
     ['zero', 1, 2, 3]
     
    -

    Namedtuple, Enum, Dataclass

    from collections import namedtuple
    -Point     = namedtuple('Point', 'x y')
    -point     = Point(0, 0)
    +

    Named Tuple, Enum, Dataclass

    from collections import namedtuple
    +Point = namedtuple('Point', 'x y')
    +point = Point(0, 0)
     
    from enum import Enum
    @@ -836,8 +836,8 @@
     direction = Direction.n
     
    from dataclasses import make_dataclass
    -Creature  = make_dataclass('Creature', ['loc', 'dir'])
    -creature  = Creature(Point(0, 0), Direction.n)
    +Creature = make_dataclass('Creature', ['loc', 'dir'])
    +creature = Creature(point, direction)
     

    #Closure

    We have a closure in Python when:

    • A nested function references a value of its enclosing function and then
    • @@ -3005,7 +3005,7 @@ From 19eb97ccf52601e83651a5e918d2d96df9e078c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Oct 2021 04:12:05 +0200 Subject: [PATCH 035/721] String --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 26e451a55..79a3f9d10 100644 --- a/README.md +++ b/README.md @@ -308,7 +308,7 @@ String ```python = .split() # Splits on one or more whitespace characters. = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'. + = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85…] and \r\n. = .join() # Joins elements using string as a separator. ``` diff --git a/index.html b/index.html index 6a3e2e703..7afc768d0 100644 --- a/index.html +++ b/index.html @@ -449,7 +449,7 @@
      <list> = <str>.split()                       # Splits on one or more whitespace characters.
       <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
      -<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'.
      +<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85…] and \r\n.
       <str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as a separator.
       
      <bool> = <sub_str> in <str>                  # Checks if string contains a substring.
      
      From 7af8bec7c34403de4d7c80a316de2f2ee815eb7e Mon Sep 17 00:00:00 2001
      From: =?UTF-8?q?Jure=20=C5=A0orn?= 
      Date: Sat, 2 Oct 2021 03:05:05 +0200
      Subject: [PATCH 036/721] Curses
      
      ---
       README.md  | 4 ++--
       index.html | 8 ++++----
       2 files changed, 6 insertions(+), 6 deletions(-)
      
      diff --git a/README.md b/README.md
      index 79a3f9d10..57bbf577a 100644
      --- a/README.md
      +++ b/README.md
      @@ -2383,8 +2383,8 @@ def main(screen):
           while ch != ascii.ESC:
               height, _ = screen.getmaxyx()
               screen.clear()
      -        for y, a_path in enumerate(paths[first : first+height]):
      -            screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y))
      +        for y, filename in enumerate(paths[first : first+height]):
      +            screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y))
               ch = screen.getch()
               selected += (ch == KEY_DOWN) - (ch == KEY_UP)
               selected = max(0, min(len(paths)-1, selected))
      diff --git a/index.html b/index.html
      index 7afc768d0..009e5f7b9 100644
      --- a/index.html
      +++ b/index.html
      @@ -226,7 +226,7 @@
       
       
         
      - +
      @@ -2093,8 +2093,8 @@ while ch != ascii.ESC: height, _ = screen.getmaxyx() screen.clear() - for y, a_path in enumerate(paths[first : first+height]): - screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y)) + for y, filename in enumerate(paths[first : first+height]): + screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y)) ch = screen.getch() selected += (ch == KEY_DOWN) - (ch == KEY_UP) selected = max(0, min(len(paths)-1, selected)) @@ -3005,7 +3005,7 @@ From 6344398401ca3b9c6466a53e95d966ed398e57ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Oct 2021 03:15:42 +0200 Subject: [PATCH 037/721] Fixed links at the top --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 57bbf577a..31722a497 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). +Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. ![Monty Python](web/image_888.jpeg) From fd773050e35876500b810ad4a84d23870320dcb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Oct 2021 03:20:15 +0200 Subject: [PATCH 038/721] Reverted link changes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 31722a497..57bbf577a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. +[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). ![Monty Python](web/image_888.jpeg) From bbde7a70b58ff97b8706e3734794fee4bf346737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 4 Oct 2021 04:31:29 +0200 Subject: [PATCH 039/721] Format, Pygame --- README.md | 8 +++++--- index.html | 14 ++++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 57bbf577a..7c213e3aa 100644 --- a/README.md +++ b/README.md @@ -412,18 +412,20 @@ Format {:.<10} # '......' {:0} # '' ``` -* **Use `'{:{}[...]}'` to set options dynamically.** +* **Options can be generated dynamically: `f'{:{}[…]}'`.** * **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.** ### Strings ```python -{'abcde'!r:10} # "'abcde' " +{'abcde':10} # 'abcde ' {'abcde':10.3} # 'abc ' {'abcde':.3} # 'abc' +{'abcde'!r:10} # "'abcde' " ``` ### Numbers ```python +{ 123456:10} # ' 123456' { 123456:10,} # ' 123,456' { 123456:10_} # ' 123_456' { 123456:+10} # ' +123456' @@ -2950,7 +2952,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): **Object for representing images.** ```python = pg.display.set_mode((width, height)) # Returns display surface. - = pg.Surface((width, height), …) # New RGB surface. Add `pg.SRCALPHA` for RGBA. + = pg.Surface((width, height) [, flags]) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. = pg.image.load('') # Loads the image. Format depends on source. = .subsurface() # Returns a subsurface. ``` diff --git a/index.html b/index.html index 009e5f7b9..1d802bbef 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -537,15 +537,17 @@
      -
    • Use '{<el>:{<str/int/float>}[...]}' to set options dynamically.
    • +
    • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
    • Adding '!r' before the colon converts object to string by calling its repr() method.
    -

    Strings

    {'abcde'!r:10}                                 # "'abcde'   "
    +

    Strings

    {'abcde':10}                                   # 'abcde     '
     {'abcde':10.3}                                 # 'abc       '
     {'abcde':.3}                                   # 'abc'
    +{'abcde'!r:10}                                 # "'abcde'   "
     
    -

    Numbers

    { 123456:10,}                                  # '   123,456'
    +

    Numbers

    { 123456:10}                                   # '    123456'
    +{ 123456:10,}                                  # '   123,456'
     { 123456:10_}                                  # '   123_456'
     { 123456:+10}                                  # '   +123456'
     {-123456:=10}                                  # '-   123456'
    @@ -2538,7 +2540,7 @@
     <list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
     

    Surface

    Object for representing images.

    <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
    -<Surf> = pg.Surface((width, height), …)         # New RGB surface. Add `pg.SRCALPHA` for RGBA.
    +<Surf> = pg.Surface((width, height) [, flags])  # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
     <Surf> = pg.image.load('<path>')                # Loads the image. Format depends on source.
     <Surf> = <Surf>.subsurface(<Rect>)              # Returns a subsurface.
     
    @@ -3005,7 +3007,7 @@ From a9454ebabd0fab409d71eec41eea1a6eade84593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com> Date: Wed, 6 Oct 2021 10:21:42 +0800 Subject: [PATCH 040/721] subprocess.run: encoding -> text=True --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c213e3aa..94f8ada68 100644 --- a/README.md +++ b/README.md @@ -1703,7 +1703,7 @@ import os #### Sends '1 + 1' to the basic calculator and captures its output: ```python >>> from subprocess import run ->>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8') +>>> run('bc', input='1 + 1\n', capture_output=True, text=True) CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ``` From 2be9c2df86dfd98a8ece1bfed24a2d255785f3ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Oct 2021 10:03:17 +0200 Subject: [PATCH 041/721] Format, Class, Enum, Exception --- README.md | 20 ++++++++++---------- index.html | 24 ++++++++++++------------ web/faq.html | 2 +- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 7c213e3aa..fde4a5d09 100644 --- a/README.md +++ b/README.md @@ -425,12 +425,12 @@ Format ### Numbers ```python -{ 123456:10} # ' 123456' -{ 123456:10,} # ' 123,456' -{ 123456:10_} # ' 123_456' -{ 123456:+10} # ' +123456' -{-123456:=10} # '- 123456' -{ 123456: } # ' 123456' +{123456:10} # ' 123456' +{123456:10,} # ' 123,456' +{123456:10_} # ' 123_456' +{123456:+10} # ' +123456' +{123456:=+10} # '+ 123456' +{123456: } # ' 123456' {-123456: } # '-123456' ``` @@ -1031,6 +1031,7 @@ class : : = : list/dict/set = field(default_factory=list/dict/set) ``` +* **For arbitrary type use `'typing.Any'`.** * **Objects can be made sortable with `'order=True'` and immutable with `'frozen=True'`.** * **For object to be hashable, all attributes must be hashable and frozen must be True.** * **Function field() is needed because `': list = []'` would make a list that is shared among all instances.** @@ -1333,9 +1334,9 @@ Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3}) ```python from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), - 'OR' : partial(lambda l, r: l or r)}) + 'OR': partial(lambda l, r: l or r)}) ``` -* **Another solution in this particular case is to use functions and\_() and or\_() from the module [operator](#operator).** +* **Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.** Exceptions @@ -1362,7 +1363,7 @@ finally: ``` * **Code inside the `'else'` block will only be executed if `'try'` block had no exceptions.** -* **Code inside the `'finally'` block will always be executed.** +* **Code inside the `'finally'` block will always be executed (unless a signal is received).** ### Catching Exceptions ```python @@ -2131,7 +2132,6 @@ sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) product_of_elems = functools.reduce(op.mul, ) union_of_sets = functools.reduce(op.or_, ) -LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_}) last_el = op.methodcaller('pop')() ``` diff --git a/index.html b/index.html index 1d802bbef..3326aeade 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -546,12 +546,12 @@ {'abcde'!r:10} # "'abcde' "
    -

    Numbers

    { 123456:10}                                   # '    123456'
    -{ 123456:10,}                                  # '   123,456'
    -{ 123456:10_}                                  # '   123_456'
    -{ 123456:+10}                                  # '   +123456'
    -{-123456:=10}                                  # '-   123456'
    -{ 123456: }                                    # ' 123456'
    +

    Numbers

    {123456:10}                                    # '    123456'
    +{123456:10,}                                   # '   123,456'
    +{123456:10_}                                   # '   123_456'
    +{123456:+10}                                   # '   +123456'
    +{123456:=+10}                                  # '+   123456'
    +{123456: }                                     # ' 123456'
     {-123456: }                                    # '-123456'
     
    @@ -1025,6 +1025,7 @@
      +
    • For arbitrary type use 'typing.Any'.
    • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
    • For object to be hashable, all attributes must be hashable and frozen must be True.
    • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances.
    • @@ -1291,11 +1292,11 @@

      User-defined functions cannot be values, so they must be wrapped:

      from functools import partial
       LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
      -                           'OR' : partial(lambda l, r: l or r)})
      +                           'OR':  partial(lambda l, r: l or r)})
       
        -
      • Another solution in this particular case is to use functions and_() and or_() from the module operator.
      • +
      • Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.

      #Exceptions

      Basic Example

      try:
           <code>
      @@ -1318,7 +1319,7 @@
       
       
      • Code inside the 'else' block will only be executed if 'try' block had no exceptions.
      • -
      • Code inside the 'finally' block will always be executed.
      • +
      • Code inside the 'finally' block will always be executed (unless a signal is received).

      Catching Exceptions

      except <exception>:
       except <exception> as <name>:
      @@ -1903,7 +1904,6 @@
       sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
       product_of_elems = functools.reduce(op.mul, <collection>)
       union_of_sets    = functools.reduce(op.or_, <coll_of_sets>)
      -LogicOp          = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_})
       last_el          = op.methodcaller('pop')(<list>)
       

      #Introspection

      Inspecting code at runtime.

      Variables

      <list> = dir()                             # Names of local variables (incl. functions).
      @@ -3007,7 +3007,7 @@
        
       
         
       
      diff --git a/web/faq.html b/web/faq.html
      index 088ed6110..1c659c3c1 100644
      --- a/web/faq.html
      +++ b/web/faq.html
      @@ -1,5 +1,5 @@
       
      Python 2 or Python 3?
      -    Python 3.6 (Except for dataclasses and asyncio that require version 3.7). +    Python 3.7

      What is the best way to use it?
      From 85bbdb43d937a821556eb0a9dd0b1c6bba26c8ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Oct 2021 17:24:07 +0200 Subject: [PATCH 042/721] Path, SQLite, Synthesizer --- README.md | 12 ++++++------ index.html | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index fde4a5d09..87e97d3e9 100644 --- a/README.md +++ b/README.md @@ -1645,7 +1645,7 @@ from pathlib import Path ``` ```python - = .parent # Returns Path without final component. + = .parent # Returns Path without the final component. = .name # Returns final component as a string. = .stem # Returns final component without extension. = .suffix # Returns final component's extension. @@ -1864,11 +1864,11 @@ import sqlite3 #### Or: ```python with : # Exits the block with commit() or rollback(), - .execute('') # depending on whether an exception occurred. + .execute('') # depending on whether any exception occurred. ``` ### Placeholders -* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.** +* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.** * **Bools will be stored and returned as ints and dates as [ISO formatted strings](#encode).** ```python .execute('', ) # Replaces '?'s in query with values. @@ -2900,15 +2900,15 @@ Synthesizer import math, struct, simpleaudio from itertools import repeat, chain F = 44100 -P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,' -P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,' +P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,' +P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,' get_pause = lambda seconds: repeat(0, int(seconds * F)) sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F) get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F))) get_hz = lambda key: 8.176 * 2 ** (int(key) / 12) parse_note = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8) get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8) -samples_f = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(',')) +samples_f = chain.from_iterable(get_samples(n) for n in f'{P1},{P1},{P2}'.split(',')) samples_b = b''.join(struct.pack('
      - +
      @@ -1540,7 +1540,7 @@ <Path> = Path.home() # Returns user's home directory. <Path> = Path(__file__).resolve() # Returns script's path if cwd wasn't changed.
      -
      <Path> = <Path>.parent              # Returns Path without final component.
      +
      <Path> = <Path>.parent              # Returns Path without the final component.
       <str>  = <Path>.name                # Returns final component as a string.
       <str>  = <Path>.stem                # Returns final component without extension.
       <str>  = <Path>.suffix              # Returns final component's extension.
      @@ -1698,11 +1698,11 @@
       

      Or:

      with <conn>:                                    # Exits the block with commit() or rollback(),
      -    <conn>.execute('<query>')                   # depending on whether an exception occurred.
      +    <conn>.execute('<query>')                   # depending on whether any exception occurred.
       

      Placeholders

        -
      • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
      • +
      • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.
      • Bools will be stored and returned as ints and dates as ISO formatted strings.
      <conn>.execute('<query>', <list/tuple>)         # Replaces '?'s in query with values.
       <conn>.execute('<query>', <dict/namedtuple>)    # Replaces ':<key>'s with values.
      @@ -2498,15 +2498,15 @@
       import math, struct, simpleaudio
       from itertools import repeat, chain
       F  = 44100
      -P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,'
      -P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,'
      +P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,'
      +P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,'
       get_pause   = lambda seconds: repeat(0, int(seconds * F))
       sin_f       = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
       get_wave    = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
       get_hz      = lambda key: 8.176 * 2 ** (int(key) / 12)
       parse_note  = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8)
       get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8)
      -samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(','))
      +samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1},{P1},{P2}'.split(','))
       samples_b   = b''.join(struct.pack('<h', int(f * 30000)) for f in samples_f)
       simpleaudio.play_buffer(samples_b, 1, 2, F)
       
      @@ -3007,7 +3007,7 @@ From 4c53f911818aa09712bb2784b2a8a9ac6de40d11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Oct 2021 17:29:36 +0200 Subject: [PATCH 043/721] Parsed changes to OS Commands --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 94671a3b8..c9fca8bde 100644 --- a/index.html +++ b/index.html @@ -1579,7 +1579,7 @@

      Sends '1 + 1' to the basic calculator and captures its output:

      >>> from subprocess import run
      ->>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8')
      +>>> run('bc', input='1 + 1\n', capture_output=True, text=True)
       CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
       
      From ac54ab1e1ff2ce8e02970f255ffb654ce7d31fb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 13 Oct 2021 10:42:30 +0200 Subject: [PATCH 044/721] Input, Pygame --- README.md | 4 ++-- index.html | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c08762812..bbed66a37 100644 --- a/README.md +++ b/README.md @@ -1489,7 +1489,7 @@ Input ``` * **Trailing newline gets stripped.** * **Prompt string is printed to the standard output before reading input.** -* **Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.** +* **Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.** Command Line Arguments @@ -2952,7 +2952,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): **Object for representing images.** ```python = pg.display.set_mode((width, height)) # Returns display surface. - = pg.Surface((width, height) [, flags]) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. + = pg.Surface((width, height), flags=0) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. = pg.image.load('') # Loads the image. Format depends on source. = .subsurface() # Returns a subsurface. ``` diff --git a/index.html b/index.html index c9fca8bde..14acf5f4b 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -1422,7 +1422,7 @@
      • Trailing newline gets stripped.
      • Prompt string is printed to the standard output before reading input.
      • -
      • Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.
      • +
      • Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.

      #Command Line Arguments

      import sys
       scripts_path = sys.argv[0]
      @@ -2540,7 +2540,7 @@
       <list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
       

      Surface

      Object for representing images.

      <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
      -<Surf> = pg.Surface((width, height) [, flags])  # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
      +<Surf> = pg.Surface((width, height), flags=0)   # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
       <Surf> = pg.image.load('<path>')                # Loads the image. Format depends on source.
       <Surf> = <Surf>.subsurface(<Rect>)              # Returns a subsurface.
       
      @@ -3007,7 +3007,7 @@ From dd2f928c29b7cc9c6c47831b317a93dbc4d63943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 14 Oct 2021 14:56:22 +0200 Subject: [PATCH 045/721] Added Imports --- README.md | 11 +++++++++++ index.html | 13 +++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bbed66a37..82b99f930 100644 --- a/README.md +++ b/README.md @@ -810,6 +810,17 @@ creature = Creature(point, direction) ``` +Imports +------- +```python +import # Imports a built-in or '.py'. +import # Imports a built-in or '/__init__.py'. +import . # Imports a built-in or '/.py'. +``` +* **Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called `'__init__.py'` as a package.** +* **Running `'import '` does not automatically provide access to package's modules unless they are imported in its init script.** + + Closure ------- **We have a closure in Python when:** diff --git a/index.html b/index.html index 14acf5f4b..a652a550e 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -841,6 +841,15 @@ Creature = make_dataclass('Creature', ['loc', 'dir']) creature = Creature(point, direction)
    +

    #Imports

    import <module>            # Imports a built-in or '<module>.py'.
    +import <package>           # Imports a built-in or '<package>/__init__.py'.
    +import <package>.<module>  # Imports a built-in or '<package>/<module>.py'.
    +
    + +
      +
    • Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called '__init__.py' as a package.
    • +
    • Running 'import <package>' does not automatically provide access to package's modules unless they are imported in its init script.
    • +

    #Closure

    We have a closure in Python when:

    • A nested function references a value of its enclosing function and then
    • the enclosing function returns the nested function.
    • @@ -3007,7 +3016,7 @@
      - +
      From f340968b233f60114eee58bed6f58e0993cf46aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Oct 2021 12:33:14 +0200 Subject: [PATCH 046/721] Updated index --- index.html | 4 ++-- pdf/index_for_pdf.html | 1 + pdf/index_for_pdf_print.html | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index a652a550e..1372d41dc 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -3016,7 +3016,7 @@
      - +
      diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index 192cb16f5..3593efe73 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -63,6 +63,7 @@

      H

      hexadecimal representation, 7, 8, 28

      I

      image, 35, 39-40, 42-43
      +imports, 12
      inline, 11-12, 15, 20
      input function, 22
      introspection, 31
      diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 5d9519c36..1720a9692 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -63,6 +63,7 @@

      H

      hexadecimal representation, 7, 8, 28

      I

      image, 35, 39-40, 42-43
      +imports, 12
      inline, 11-12, 15, 20
      input function, 22
      introspection, 31
      From cae27c1fb3d6058749110dac65b166d9aeba33a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Oct 2021 17:18:42 +0200 Subject: [PATCH 047/721] Imports --- README.md | 5 +++-- index.html | 9 +++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 82b99f930..da01ea7b4 100644 --- a/README.md +++ b/README.md @@ -817,8 +817,9 @@ import # Imports a built-in or '.py'. import # Imports a built-in or '/__init__.py'. import . # Imports a built-in or '/.py'. ``` -* **Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called `'__init__.py'` as a package.** -* **Running `'import '` does not automatically provide access to package's modules unless they are imported in its init script.** +* **Package is a collection of modules, but it can also define its own objects.** +* **On a filesystem this corresponds to a directory of Python files with an optional init script.** +* **Running `'import '` does not automatically provide access to the package's modules unless they are explicitly imported in its init script.** Closure diff --git a/index.html b/index.html index 1372d41dc..2e416ed7e 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@

      - +
      @@ -847,8 +847,9 @@
      -
    • Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called '__init__.py' as a package.
    • -
    • Running 'import <package>' does not automatically provide access to package's modules unless they are imported in its init script.
    • +
    • Package is a collection of modules, but it can also define its own objects.
    • +
    • On a filesystem this corresponds to a directory of Python files with an optional init script.
    • +
    • Running 'import <package>' does not automatically provide access to the package's modules unless they are explicitly imported in its init script.

    #Closure

    We have a closure in Python when: