From dae03ded70af230716d09bd202558ad060f1c9e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 21 Apr 2024 21:20:08 +0200 Subject: [PATCH 001/281] Exceptions, Print, Open --- README.md | 6 +++--- index.html | 6 +++--- parse.js | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index bdf5dbc37..c0f04a0cd 100644 --- a/README.md +++ b/README.md @@ -1452,7 +1452,7 @@ BaseException +-- LookupError # Base class for errors when a collection can't find an item. | +-- IndexError # Raised when a sequence index is out of range. | +-- KeyError # Raised when a dictionary key or set element is missing. - +-- MemoryError # Out of memory. Could be too late to start deleting vars. + +-- MemoryError # Out of memory. May be too late to start deleting objects. +-- NameError # Raised when nonexistent name (variable/func/class) is used. | +-- UnboundLocalError # Raised when local name is used before it's being defined. +-- OSError # Errors such as FileExistsError/TimeoutError (see #Open). @@ -1515,7 +1515,7 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) from pprint import pprint pprint(, width=80, depth=None, compact=False, sort_dicts=True) ``` -* **Each item is printed on its own line if collection takes up more than 'width' characters.** +* **Each item is printed on its own line if collection exceeds 'width' characters.** * **Nested collections that are 'depth' levels deep get printed as '...'.** @@ -1601,7 +1601,7 @@ Open .write() # Writes a string or bytes object. .writelines() # Writes a coll. of strings or bytes objects. .flush() # Flushes write buffer. Runs every 4096/8192 B. -.close() # Closes the file after flushing. +.close() # Closes the file after flushing write buffer. ``` * **Methods do not add or strip trailing newlines, not even writelines().** diff --git a/index.html b/index.html index d355a8799..51d364ad1 100644 --- a/index.html +++ b/index.html @@ -1237,7 +1237,7 @@ ├── LookupError # Base class for errors when a collection can't find an item. │ ├── IndexError # Raised when a sequence index is out of range. │ └── KeyError # Raised when a dictionary key or set element is missing. - ├── MemoryError # Out of memory. Could be too late to start deleting vars. + ├── MemoryError # Out of memory. May be too late to start deleting objects. ├── NameError # Raised when nonexistent name (variable/func/class) is used. │ └── UnboundLocalError # Raised when local name is used before it's being defined. ├── OSError # Errors such as FileExistsError/TimeoutError (see #Open). @@ -1288,7 +1288,7 @@
    -
  • Each item is printed on its own line if collection takes up more than 'width' characters.
  • +
  • Each item is printed on its own line if collection exceeds 'width' characters.
  • Nested collections that are 'depth' levels deep get printed as '…'.

#Input

<str> = input(prompt=None)
@@ -1361,7 +1361,7 @@
 
<file>.write(<str/bytes>)           # Writes a string or bytes object.
 <file>.writelines(<collection>)     # Writes a coll. of strings or bytes objects.
 <file>.flush()                      # Flushes write buffer. Runs every 4096/8192 B.
-<file>.close()                      # Closes the file after flushing.
+<file>.close()                      # Closes the file after flushing write buffer.
 
  • Methods do not add or strip trailing newlines, not even writelines().
  • diff --git a/parse.js b/parse.js index 7ccf6e8a5..8c47a4534 100755 --- a/parse.js +++ b/parse.js @@ -427,7 +427,7 @@ const DIAGRAM_7_B = " ├── LookupError # Base class for errors when a collection can't find an item.\n" + " │ ├── IndexError # Raised when a sequence index is out of range.\n" + " │ └── KeyError # Raised when a dictionary key or set element is missing.\n" + - " ├── MemoryError # Out of memory. Could be too late to start deleting vars.\n" + + " ├── MemoryError # Out of memory. May be too late to start deleting objects.\n" + " ├── NameError # Raised when nonexistent name (variable/func/class) is used.\n" + " │ └── UnboundLocalError # Raised when local name is used before it's being defined.\n" + " ├── OSError # Errors such as FileExistsError/TimeoutError (see #Open).\n" + From 8075b0f215527dd5329981bc2f58d4a8174e0f3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 22 Apr 2024 11:35:40 +0200 Subject: [PATCH 002/281] Input --- README.md | 2 +- index.html | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c0f04a0cd..6f242949d 100644 --- a/README.md +++ b/README.md @@ -1525,7 +1525,7 @@ Input = input(prompt=None) ``` * **Reads a line from the user input or pipe if present (trailing newline gets stripped).** -* **Prompt string is printed to the standard output before reading input.** +* **Prompt string is printed to the standard output before input is read.** * **Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.** diff --git a/index.html b/index.html index 51d364ad1..884979a21 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1296,7 +1296,7 @@
    • Reads a line from the user input or pipe if present (trailing newline gets stripped).
    • -
    • Prompt string is printed to the standard output before reading input.
    • +
    • Prompt string is printed to the standard output before input is read.
    • Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.

    #Command Line Arguments

    import sys
    @@ -2933,7 +2933,7 @@ 

    Format

#Closure

We have/get a closure in Python when a nested function references a value of its enclosing function and then the enclosing function returns the nested function.

def get_multiplier(a):
     def out(b):
@@ -707,8 +709,7 @@
 30
 
    -
  • If multiple nested functions within enclosing function reference the same value, that value gets shared.
  • -
  • To dynamically access function's first free variable use '<function>.__closure__[0].cell_contents'.
  • +
  • Any value that is referenced from within multiple nested functions gets shared.

Partial

from functools import partial
 <function> = partial(<function> [, <arg_1>, <arg_2>, ...])
@@ -2933,7 +2934,7 @@ 

Format

-

#Imports

import <module>            # Imports a built-in or '<module>.py'.
+

#Imports

Mechanism that makes code in one module available to another module.

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 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.
  • Location of the file that is passed to python command serves as a root of all local imports.
  • For relative imports use 'from .[…][<pkg/module>[.…]] import <obj>'.
  • -
  • To install your package go to its parent dir, add 'import setuptools; setuptools.setup()' to setup.py, '[options]' and 'packages = <dir>' to setup.cfg, and run 'pip3 install -e .'.

#Closure

We have/get a closure in Python when a nested function references a value of its enclosing function and then the enclosing function returns the nested function.

def get_multiplier(a):
     def out(b):
@@ -800,7 +800,7 @@
 
  • Using only '@debug' to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can however manually check if the argument they received is a function and act accordingly.
-

#Class

class <name>:
+

#Class

A template for creating user-defined objects.

class MyClass:
     def __init__(self, a):
         self.a = a
     def __str__(self):
@@ -814,11 +814,16 @@
         return cls.__name__
 
+
  • Return value of repr() should be unambiguous and of str() readable.
  • If only repr() is defined, it will also be used for str().
  • Methods decorated with '@staticmethod' do not receive 'self' nor 'cls' as their first arg.
+
>>> obj = MyClass(1)
+>>> obj.a, str(obj), repr(obj)
+(1, '1', 'MyClass(1)')
+

Expressions that call the str() method:

print(<el>)
 f'{<el>}'
 logging.warning(<el>)
@@ -833,11 +838,6 @@
 >>> <el>
 
-

Constructor Overloading

class <name>:
-    def __init__(self, a=None):
-        self.a = a
-
-

Inheritance

class Person:
     def __init__(self, name):
         self.name = name
@@ -848,7 +848,7 @@
         self.staff_num = staff_num
 
-

Multiple Inheritance

class A: pass
+

Multiple inheritance:

class A: pass
 class B: pass
 class C(A, B): pass
 
@@ -857,22 +857,6 @@
>>> C.mro()
 [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
 
-

Property

Pythonic way of implementing getters and setters.

class Person:
-    @property
-    def name(self):
-        return ' '.join(self._name)
-
-    @name.setter
-    def name(self, value):
-        self._name = value.split()
-
- - -
>>> person = Person()
->>> person.name = '\t Guido  van Rossum \n'
->>> person.name
-'Guido van Rossum'
-

Type Annotations

  • They add type hints to variables, arguments and functions ('def f() -> <type>:').
  • Hints are used by type checkers like mypy, data validation libraries such as Pydantic and lately also by Cython compiler. However, they are not enforced by CPython interpreter.
  • @@ -903,6 +887,22 @@
    <class> = make_dataclass('<class_name>', <coll_of_attribute_names>)
     <class> = make_dataclass('<class_name>', <coll_of_tuples>)
     <tuple> = ('<attr_name>', <type> [, <default_value>])
    +

    Property

    Pythonic way of implementing getters and setters.

    class Person:
    +    @property
    +    def name(self):
    +        return ' '.join(self._name)
    +
    +    @name.setter
    +    def name(self, value):
    +        self._name = value.split()
    +
    + + +
    >>> person = Person()
    +>>> person.name = '\t Guido  van Rossum \n'
    +>>> person.name
    +'Guido van Rossum'
    +

    Slots

    Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.

    class MyClassWithSlots:
         __slots__ = ['a']
         def __init__(self):
    
    From d113a073907b1128c7af32d89543ba28d7f46587 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 28 Apr 2024 12:18:21 +0200
    Subject: [PATCH 005/281] Imports
    
    ---
     README.md  | 2 +-
     index.html | 6 +++---
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index 66ac9b8bc..82232df0c 100644
    --- a/README.md
    +++ b/README.md
    @@ -816,7 +816,7 @@ player = Player(point, direction)                   # Returns its instance.
     
     Imports
     -------
    -**Mechanism that makes code in one module available to another module.**
    +**Mechanism that makes code in one file available to another file.**
     
     ```python
     import             # Imports a built-in or '.py'.
    diff --git a/index.html b/index.html
    index 05177db6e..0af2bfb06 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -684,7 +684,7 @@ Player = make_dataclass('Player', ['loc', 'dir']) # Creates a class. player = Player(point, direction) # Returns its instance.
    -

    #Imports

    Mechanism that makes code in one module available to another module.

    import <module>            # Imports a built-in or '<module>.py'.
    +

    #Imports

    Mechanism that makes code in one file available to another file.

    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'.
     
    @@ -2934,7 +2934,7 @@

    Format

cdef <ctype> <var_name> = <el>
+cdef <ctype>[n_elements] <var_name> = [<el>, <el>, ...]
+cdef <ctype/void> <func_name>(<ctype> <arg_name>): ...
 
-
cdef class <class_name>:
-    cdef public <ctype> <attr_name>
+
cdef class <class_name>:
+    cdef public <ctype> <attr_name>
     def __init__(self, <ctype> <arg_name>):
         self.<attr_name> = <arg_name>
 
-
cdef enum <enum_name>: <member_name>, <member_name>, ...
+
cdef enum <enum_name>: <member_name>, <member_name>, ...
 

Virtual Environments

System for installing libraries directly into project's directory.

$ python3 -m venv <name>      # Creates virtual environment in current directory.
 $ source <name>/bin/activate  # Activates venv. On Windows run `<name>\Scripts\activate`.
diff --git a/parse.js b/parse.js
index 8c47a4534..01765a215 100755
--- a/parse.js
+++ b/parse.js
@@ -300,7 +300,7 @@ const MARIO =
   'if __name__ == \'__main__\':\n' +
   '    main()\n';
 
-const PLOTLY =
+const GROUPBY =
   '>>> gb = df.groupby(\'z\'); gb.apply(print)\n' +
   '   x  y  z\n' +
   'a  1  2  3\n' +
@@ -308,6 +308,20 @@ const PLOTLY =
   'b  4  5  6\n' +
   'c  7  8  6';
 
+const CYTHON_1 =
+  'cdef <ctype> <var_name> = <el>\n' +
+  'cdef <ctype>[n_elements] <var_name> = [<el>, <el>, ...]\n' +
+  'cdef <ctype/void> <func_name>(<ctype> <arg_name>): ...\n';
+
+const CYTHON_2 =
+  'cdef class <class_name>:\n' +
+  '    cdef public <ctype> <attr_name>\n' +
+  '    def __init__(self, <ctype> <arg_name>):\n' +
+  '        self.<attr_name> = <arg_name>\n';
+
+const CYTHON_3 =
+  'cdef enum <enum_name>: <member_name>, <member_name>, ...\n';
+
 const INDEX =
   '
  • Only available in the PDF.
  • \n' + '
  • Ctrl+F / ⌘F is usually sufficient.
  • \n' + @@ -827,7 +841,10 @@ function fixHighlights() { $(`code:contains(>>> logging.basicConfig()`).html(LOGGING_EXAMPLE); $(`code:contains(samples_f = (sin(i *)`).html(AUDIO); $(`code:contains(collections, dataclasses, enum, io, itertools)`).html(MARIO); - $(`code:contains(>>> gb = df.groupby)`).html(PLOTLY); + $(`code:contains(>>> gb = df.groupby)`).html(GROUPBY); + $(`code:contains(cdef = )`).html(CYTHON_1); + $(`code:contains(cdef class :)`).html(CYTHON_2); + $(`code:contains(cdef enum : , , ...)`).html(CYTHON_3); $(`ul:contains(Only available in)`).html(INDEX); } From 937f5c1a85665f81ba03c3f5a917748288d5f2ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 4 May 2024 21:44:40 +0200 Subject: [PATCH 007/281] List, Format, Enum, Path, Bytes, Memoryview, Pandas --- README.md | 79 +++++++++++++++++++++++++------------------------ index.html | 86 ++++++++++++++++++++++++++++-------------------------- 2 files changed, 85 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 82232df0c..af086b4b3 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ if __name__ == '__main__': # Runs main() if file wasn't imported. List ---- ```python + = [index] # First index is 0. Last -1. Allows assignments. = [] # Or: [from_inclusive : to_exclusive : ±step] ``` @@ -57,10 +58,11 @@ list_of_chars = list() * **Module [operator](#operator) provides functions itemgetter() and mul() that offer the same functionality as [lambda](#lambda) expressions above.** ```python -.insert(, ) # Inserts item at index and moves the rest to the right. - = .pop([]) # Removes and returns item at index or from the end. - = .count() # Returns number of occurrences. Also works on strings. + = len() # Returns number of items. Also works on other collections. + = .count() # Returns number of occurrences. Also `if in : ...`. = .index() # Returns index of the first occurrence or raises ValueError. + = .pop() # Removes and returns item from the end or at index if passed. +.insert(, ) # Inserts item at index and moves the rest to the right. .remove() # Removes first occurrence of the item or raises ValueError. .clear() # Removes all items. Also works on dictionary and set. ``` @@ -477,9 +479,9 @@ Format ### Ints ```python -{90:c} # 'Z' -{90:b} # '1011010' -{90:X} # '5A' +{90:c} # 'Z'. Unicode character with value 90. +{90:b} # '1011010'. Number 90 in binary. +{90:X} # '5A'. Number 90 in uppercase hexadecimal. ``` @@ -499,7 +501,7 @@ Numbers ### Basic Functions ```python - = pow(, ) # Or: ** + = pow(, ) # Or: ** = abs() # = abs() = round( [, ±ndigits]) # `round(126, -1) == 130` ``` @@ -605,8 +607,8 @@ from dateutil.tz import tzlocal, gettz ### Now ```python - = D/DT.today() # Current local date or naive DT. Also DT.now(). - = DT.now() # Aware DT from current time in passed timezone. + = D/DT.today() # Current local date or naive DT. Also DT.now(). + = DT.now() # Aware DT from current time in passed timezone. ``` * **To extract time use `'.time()'`, `'.time()'` or `'.timetz()'`.** @@ -1320,23 +1322,24 @@ class MyAbcSequence(abc.Sequence): +------------+------------+------------+------------+--------------+ ``` * **Method iter() is required for `'isinstance(, abc.Iterable)'` to return True, however any object with getitem() will work with any code expecting an iterable.** -* **Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping.** +* **Other extendable ABCs: MutableSequence, Set, MutableSet, Mapping, MutableMapping.** * **Names of their required methods are stored in `'.__abstractmethods__'`.** Enum ---- +**Class of named constants called members.** + ```python from enum import Enum, auto ``` ```python class (Enum): - = auto() - = - = , + = auto() # Increment of the last numeric value or 1. + = # Values don't have to be hashable. + = , # Tuple can be used for multiple values. ``` -* **Function auto() returns an increment of the last numeric value or 1.** * **Accessing a member named after a reserved keyword causes SyntaxError.** * **Methods receive the member they were called on as the 'self' argument.** @@ -1356,7 +1359,7 @@ class (Enum): ```python = type() # Returns member's enum. - = itertools.cycle() # Retruns endless iterator of members. + = itertools.cycle() # Returns endless iterator of members. = random.choice(list()) # Returns a random member. ``` @@ -1630,7 +1633,7 @@ from pathlib import Path ``` ```python - = os.getcwd() # Returns the current working directory. + = os.getcwd() # Returns current directory. Same as `$ pwd`. = os.path.join(, ...) # Joins two or more pathname components. = os.path.realpath() # Resolves symlinks and calls path.abspath(). ``` @@ -1654,7 +1657,7 @@ from pathlib import Path ```python = os.stat() # Or: .stat() - = .st_mtime/st_size/… # Modification time, size in bytes, ... + = .st_mtime/st_size/… # Modification time, size in bytes, ... ``` ### DirEntry @@ -1949,11 +1952,11 @@ with .begin(): ... # Exits the block with commit or Bytes ----- -**Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** +**A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** ```python = b'' # Only accepts ASCII characters and \x00-\xff. - = [] # Returns an int in range from 0 to 255. + = [index] # Returns an int in range from 0 to 255. = [] # Returns bytes even if it has only one element. = .join() # Joins elements using bytes as a separator. ``` @@ -1961,17 +1964,17 @@ Bytes ### Encode ```python = bytes() # Ints must be in range from 0 to 255. - = bytes(, 'utf-8') # Or: .encode('utf-8') - = .to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`. + = bytes(, 'utf-8') # Encodes string. Also .encode('utf-8'). = bytes.fromhex('') # Hex pairs can be separated by whitespaces. + = .to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`. ``` ### Decode ```python = list() # Returns ints in range from 0 to 255. - = str(, 'utf-8') # Or: .decode('utf-8') + = str(, 'utf-8') # Decodes bytes. Also .decode('utf-8'). + = .hex() # Returns hex pairs. Accepts `sep=`. = int.from_bytes(, …) # `byteorder='big/little', signed=False`. -'' = .hex() # Returns hex pairs. Accepts `sep=`. ``` ### Read Bytes from File @@ -2013,7 +2016,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * **`'<'` - Little-endian (i.e. least significant byte first).** * **`'>'` - Big-endian (also `'!'`).** -#### Besides numbers, pack() and unpack() also support bytes objects as part of the sequence: +#### Besides numbers, pack() and unpack() also support bytes objects as a part of the sequence: * **`'c'` - A bytes object with a single element. For pad byte use `'x'`.** * **`'s'` - A bytes object with n elements (not effected by byte order).** @@ -2035,10 +2038,10 @@ Array ```python from array import array - = array('', ) # Array from collection of numbers. + = array('', ) # Array from collection of numbers. = array('', ) # Array from bytes object. = array('', ) # Treats array as a sequence of numbers. -.fromfile(, n_items) # Appends items. Raises EOFError on end. +.fromfile(, n_items) # Appends items. Also frombytes(). = bytes() # Or: .tobytes() .write() # Writes array to the binary file. ``` @@ -2054,7 +2057,7 @@ Memory View ```python = memoryview() # Immutable if bytes, else mutable. - = [] # Returns an int or a float. + = [index] # Returns an int or a float. = [] # Mview with rearranged elements. = .cast('') # Casts memoryview to the new format. .release() # Releases memory buffer of target object. @@ -2068,10 +2071,10 @@ Memory View ``` ```python - = list() # Returns a list of ints or floats. - = str(, 'utf-8') # Treats mview as a bytes object. - = int.from_bytes(, …) # `byteorder='big/little', signed=False`. -'' = .hex() # Treats mview as a bytes object. + = list() # Returns a list of ints or floats. + = str(, 'utf-8') # Treats mview as a bytes object. + = .hex() # Returns hex pairs. Accepts `sep=`. + = int.from_bytes(, …) # `byteorder='big/little', signed=False`. ``` @@ -2779,7 +2782,7 @@ from PIL import Image ``` ```python - = .filter() # ` = ImageFilter.([])` + = .filter() # ` = ImageFilter.()` = .enhance() # ` = ImageEnhance.()` ``` @@ -3159,13 +3162,13 @@ Name: a, dtype: int64 ```python = .loc[key] # Or: .iloc[i] - = .loc[keys] # Or: .iloc[coll_of_i] - = .loc[from_key:to_key_inc] # Or: .iloc[from_i:to_i_exc] + = .loc[coll_of_keys] # Or: .iloc[coll_of_i] + = .loc[from_key : to_key_inc] # Or: .iloc[from_i : to_i_exc] ``` ```python = [key/i] # Or: . - = [keys/coll_of_i] # Or: [key/i : key/i] + = [coll_of_keys/coll_of_i] # Or: [key/i : key/i] = [bools] # Or: .loc/iloc[bools] ``` @@ -3216,7 +3219,7 @@ y 3 | | y 2 | y 2 | y 2 | +---------------+-------------+-------------+---------------+ ``` -* **Keys/indices/bools can't be tuples because `'obj[x, y]'` is converted to `'obj[(x, y)]'`!** +* **Indexing objects can't be tuples because `'obj[x, y]'` is converted to `'obj[(x, y)]'`!** * **Methods ffill(), interpolate(), fillna() and dropna() accept `'inplace=True'`.** * **Last result has a hierarchical index. Use `'[key_1, key_2]'` to get its values.** @@ -3354,8 +3357,8 @@ plt.show() # Displays the plot. Also plt.sav ``` ```python - = .to_dict(['d/l/s/…']) # Returns columns as dicts, lists or series. - = .to_json/html/csv([]) # Also to_markdown/latex([]). + = .to_dict('d/l/s/…') # Returns columns as dicts, lists or series. + = .to_json/html/csv/latex() # Saves output to file if path is passed. .to_pickle/excel() # Run `$ pip3 install "pandas[excel]" odfpy`. .to_sql('', ) # Also `if_exists='fail/replace/append'`. ``` diff --git a/index.html b/index.html index 4c144d48c..c700dba86 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -100,7 +100,8 @@ main()
    -

    #List

    <list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
    +

    #List

    <el>   = <list>[index]          # First index is 0. Last -1. Allows assignments.
    +<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
     
    <list>.append(<el>)             # Or: <list> += [<el>]
    @@ -123,10 +124,11 @@
     
  • For details about sorted(), min() and max() see sortable.
  • Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
  • -
    <list>.insert(<int>, <el>)      # Inserts item at index and moves the rest to the right.
    -<el>  = <list>.pop([<int>])     # Removes and returns item at index or from the end.
    -<int> = <list>.count(<el>)      # Returns number of occurrences. Also works on strings.
    +
    <int> = len(<list>)             # Returns number of items. Also works on other collections.
    +<int> = <list>.count(<el>)      # Returns number of occurrences. Also `if <el> in <coll>: ...`.
     <int> = <list>.index(<el>)      # Returns index of the first occurrence or raises ValueError.
    +<el>  = <list>.pop()            # Removes and returns item from the end or at index if passed.
    +<list>.insert(<int>, <el>)      # Inserts item at index and moves the rest to the right.
     <list>.remove(<el>)             # Removes first occurrence of the item or raises ValueError.
     <list>.clear()                  # Removes all items. Also works on dictionary and set.
     
    @@ -435,9 +437,9 @@
  • 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'.
  • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
  • -

    Ints

    {90:c}                                   # 'Z'
    -{90:b}                                   # '1011010'
    -{90:X}                                   # '5A'
    +

    Ints

    {90:c}                                   # 'Z'. Unicode character with value 90.
    +{90:b}                                   # '1011010'. Number 90 in binary.
    +{90:X}                                   # '5A'. Number 90 in uppercase hexadecimal.
     

    #Numbers

    <int>      = int(<float/str/bool>)                # Or: math.floor(<float>)
    @@ -453,7 +455,7 @@
     
  • Floats can be compared with: 'math.isclose(<float>, <float>)'.
  • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.
  • -

    Basic Functions

    <num> = pow(<num>, <num>)                         # Or: <num> ** <num>
    +

    Basic Functions

    <num> = pow(<num>, <num>)                         # Or: <number> ** <number>
     <num> = abs(<num>)                                # <float> = abs(<complex>)
     <num> = round(<num> [, ±ndigits])                 # `round(126, -1) == 130`
     
    @@ -528,8 +530,8 @@
  • Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).
  • Use '<D/DT>.weekday()' to get the day of the week as an int, with Monday being 0.
  • -

    Now

    <D/DTn>  = D/DT.today()                     # Current local date or naive DT. Also DT.now().
    -<DTa>    = DT.now(<tzinfo>)                 # Aware DT from current time in passed timezone.
    +

    Now

    <D/DTn> = D/DT.today()                      # Current local date or naive DT. Also DT.now().
    +<DTa>   = DT.now(<tzinfo>)                  # Aware DT from current time in passed timezone.
     
      @@ -1130,19 +1132,19 @@
      • Method iter() is required for 'isinstance(<obj>, abc.Iterable)' to return True, however any object with getitem() will work with any code expecting an iterable.
      • -
      • Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping.
      • +
      • Other extendable ABCs: MutableSequence, Set, MutableSet, Mapping, MutableMapping.
      • Names of their required methods are stored in '<abc>.__abstractmethods__'.
      -

      #Enum

      from enum import Enum, auto
      +

      #Enum

      Class of named constants called members.

      from enum import Enum, auto
       
      +
      class <enum_name>(Enum):
      -    <member_name> = auto()
      -    <member_name> = <value>
      -    <member_name> = <value>, <value>
      +    <member_name> = auto()              # Increment of the last numeric value or 1.
      +    <member_name> = <value>             # Values don't have to be hashable.
      +    <member_name> = <value>, <value>    # Tuple can be used for multiple values.
       
        -
      • Function auto() returns an increment of the last numeric value or 1.
      • Accessing a member named after a reserved keyword causes SyntaxError.
      • Methods receive the member they were called on as the 'self' argument.
      @@ -1157,7 +1159,7 @@ <list> = [a.value for a in <enum>] # Returns enum's member values.
      <enum>   = type(<member>)               # Returns member's enum.
      -<iter>   = itertools.cycle(<enum>)      # Retruns endless iterator of members.
      +<iter>   = itertools.cycle(<enum>)      # Returns endless iterator of members.
       <member> = random.choice(list(<enum>))  # Returns a random member.
       

      Inline

      Cutlery = Enum('Cutlery', 'FORK KNIFE SPOON')
      @@ -1381,7 +1383,7 @@
       from pathlib import Path
       
      -
      <str>  = os.getcwd()                # Returns the current working directory.
      +
      <str>  = os.getcwd()                # Returns current directory. Same as `$ pwd`.
       <str>  = os.path.join(<path>, ...)  # Joins two or more pathname components.
       <str>  = os.path.realpath(<path>)   # Resolves symlinks and calls path.abspath().
       
      @@ -1397,7 +1399,7 @@ <bool> = os.path.isdir(<path>) # Or: <DirEntry/Path>.is_dir()
      <stat> = os.stat(<path>)            # Or: <DirEntry/Path>.stat()
      -<real> = <stat>.st_mtime/st_size/…  # Modification time, size in bytes, ...
      +<num>  = <stat>.st_mtime/st_size/…  # Modification time, size in bytes, ...
       

      DirEntry

      Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.

      <iter> = os.scandir(path='.')       # Returns DirEntry objects located at the path.
       <str>  = <DirEntry>.path            # Returns the whole path as a string.
      @@ -1614,23 +1616,23 @@
       ┃ oracle     │ oracledb     │ oracledb │ www.pypi.org/project/oracledb    ┃
       ┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
       
      -

      #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 an int in range from 0 to 255.
      +

      #Bytes

      A 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 an 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 as a separator.
       

      Encode

      <bytes> = bytes(<coll_of_ints>)          # Ints must be in range from 0 to 255.
      -<bytes> = bytes(<str>, 'utf-8')          # Or: <str>.encode('utf-8')
      -<bytes> = <int>.to_bytes(n_bytes, …)     # `byteorder='big/little', signed=False`.
      +<bytes> = bytes(<str>, 'utf-8')          # Encodes string. Also <str>.encode('utf-8').
       <bytes> = bytes.fromhex('<hex>')         # Hex pairs can be separated by whitespaces.
      +<bytes> = <int>.to_bytes(n_bytes, …)     # `byteorder='big/little', signed=False`.
       

      Decode

      <list>  = list(<bytes>)                  # Returns ints in range from 0 to 255.
      -<str>   = str(<bytes>, 'utf-8')          # Or: <bytes>.decode('utf-8')
      +<str>   = str(<bytes>, 'utf-8')          # Decodes bytes. Also <bytes>.decode('utf-8').
      +<str>   = <bytes>.hex()                  # Returns hex pairs. Accepts `sep=<str>`.
       <int>   = int.from_bytes(<bytes>, …)     # `byteorder='big/little', signed=False`.
      -'<hex>' = <bytes>.hex()                  # Returns hex pairs. Accepts `sep=<str>`.
       

      Read Bytes from File

      def read_bytes(filename):
      @@ -1661,7 +1663,7 @@ 

      Format

      '=' - System's byte order (usually little-endian).
    • '<' - Little-endian (i.e. least significant byte first).
    • '>' - Big-endian (also '!').
    • -

    Besides numbers, pack() and unpack() also support bytes objects as part of the sequence:

      +

    Besides numbers, pack() and unpack() also support bytes objects as a part of the sequence:

    • 'c' - A bytes object with a single element. For pad byte use 'x'.
    • '<n>s' - A bytes object with n elements (not effected by byte order).

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

      @@ -1683,10 +1685,10 @@

      Format

      #Array

      List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method.

      from array import array
      -<array> = array('<typecode>', <collection>)    # Array from collection of numbers.
      +<array> = array('<typecode>', <coll_of_nums>)  # Array from collection of numbers.
       <array> = array('<typecode>', <bytes>)         # Array from bytes object.
       <array> = array('<typecode>', <array>)         # Treats array as a sequence of numbers.
      -<array>.fromfile(<file>, n_items)              # Appends items. Raises EOFError on end.
      +<array>.fromfile(<file>, n_items)              # Appends items. Also frombytes().
       <bytes> = bytes(<array>)                       # Or: <array>.tobytes()
       <file>.write(<array>)                          # Writes array to the binary file.
       
      @@ -1699,7 +1701,7 @@

      Format

      <mview> = memoryview(<bytes/bytearray/array>) # Immutable if bytes, else mutable. -<real> = <mview>[<index>] # Returns an int or a float. +<real> = <mview>[index] # Returns an int or a float. <mview> = <mview>[<slice>] # Mview with rearranged elements. <mview> = <mview>.cast('<typecode>') # Casts memoryview to the new format. <mview>.release() # Releases memory buffer of target object. @@ -1711,10 +1713,10 @@

      Format

      '<typecode>', <mview>) # Treats mview as a sequence of numbers. <file>.write(<mview>) # Writes mview to the binary file.

    -
    <list>  = list(<mview>)                        # Returns a list of ints or floats.
    -<str>   = str(<mview>, 'utf-8')                # Treats mview as a bytes object.
    -<int>   = int.from_bytes(<mview>, …)           # `byteorder='big/little', signed=False`.
    -'<hex>' = <mview>.hex()                        # Treats mview as a bytes object.
    +
    <list> = list(<mview>)                         # Returns a list of ints or floats.
    +<str>  = str(<mview>, 'utf-8')                 # Treats mview as a bytes object.
    +<str>  = <mview>.hex()                         # Returns hex pairs. Accepts `sep=<str>`.
    +<int>  = int.from_bytes(<mview>, …)            # `byteorder='big/little', signed=False`.
     

    #Deque

    A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

    from collections import deque
     <deque> = deque(<collection>)                  # Also `maxlen=None`.
    @@ -2276,7 +2278,7 @@ 

    Format

    # Updates pixels with a copy of the sequence. <Image>.paste(<Image>, (x, y)) # Draws passed image at specified location.

    -
    <Image> = <Image>.filter(<Filter>)              # `<Filter> = ImageFilter.<name>([<args>])`
    +
    <Image> = <Image>.filter(<Filter>)              # `<Filter> = ImageFilter.<name>(<args>)`
     <Image> = <Enhance>.enhance(<float>)            # `<Enhance> = ImageEnhance.<name>(<Image>)`
     
    <array> = np.array(<Image>)                     # Creates a 2d/3d NumPy array from the image.
    @@ -2590,11 +2592,11 @@ 

    Format

    # Only keeps items with keys specified in index.

    <el> = <Sr>.loc[key]                           # Or: <Sr>.iloc[i]
    -<Sr> = <Sr>.loc[keys]                          # Or: <Sr>.iloc[coll_of_i]
    -<Sr> = <Sr>.loc[from_key:to_key_inc]           # Or: <Sr>.iloc[from_i:to_i_exc]
    +<Sr> = <Sr>.loc[coll_of_keys]                  # Or: <Sr>.iloc[coll_of_i]
    +<Sr> = <Sr>.loc[from_key : to_key_inc]         # Or: <Sr>.iloc[from_i : to_i_exc]
     
    <el> = <Sr>[key/i]                             # Or: <Sr>.<key>
    -<Sr> = <Sr>[keys/coll_of_i]                    # Or: <Sr>[key/i : key/i]
    +<Sr> = <Sr>[coll_of_keys/coll_of_i]            # Or: <Sr>[key/i : key/i]
     <Sr> = <Sr>[bools]                             # Or: <Sr>.loc/iloc[bools]
     
    <Sr> = <Sr> > <el/Sr>                          # Returns a Series of bools.
    @@ -2633,7 +2635,7 @@ 

    Format

    'obj[x, y]' is converted to 'obj[(x, y)]'! +
  • Indexing objects can't be tuples because 'obj[x, y]' is converted to 'obj[(x, y)]'!
  • Methods ffill(), interpolate(), fillna() and dropna() accept 'inplace=True'.
  • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
  • @@ -2746,8 +2748,8 @@

    Format

    '<path/url>') # Use `sheet_name=None` to get all Excel sheets. <DF> = pd.read_sql('<table/query>', <conn.>) # SQLite3/SQLAlchemy connection (see #SQLite).

    -
    <dict> = <DF>.to_dict(['d/l/s/…'])             # Returns columns as dicts, lists or series.
    -<str>  = <DF>.to_json/html/csv([<path>])       # Also to_markdown/latex([<path>]).
    +
    <dict> = <DF>.to_dict('d/l/s/…')               # Returns columns as dicts, lists or series.
    +<str>  = <DF>.to_json/html/csv/latex()         # Saves output to file if path is passed.
     <DF>.to_pickle/excel(<path>)                   # Run `$ pip3 install "pandas[excel]" odfpy`.
     <DF>.to_sql('<table_name>', <connection>)      # Also `if_exists='fail/replace/append'`.
     
    @@ -2934,7 +2936,7 @@

    Format

    -
    <list> = list(<mview>)                         # Returns a list of ints or floats.
    -<str>  = str(<mview>, 'utf-8')                 # Treats mview as a bytes object.
    -<str>  = <mview>.hex()                         # Returns hex pairs. Accepts `sep=<str>`.
    -<int>  = int.from_bytes(<mview>, …)            # `byteorder='big/little', signed=False`.
    +
    <list>  = list(<mview>)                        # Returns a list of ints or floats.
    +<str>   = str(<mview>, 'utf-8')                # Treats mview as a bytes object.
    +<str>   = <mview>.hex()                        # Returns hex pairs. Accepts `sep=<str>`.
     

    #Deque

    A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

    from collections import deque
     <deque> = deque(<collection>)                  # Also `maxlen=None`.
    @@ -2936,7 +2937,7 @@ 

    Format

      -
    • Accessing a member named after a reserved keyword causes SyntaxError.
    • Methods receive the member they were called on as the 'self' argument.
    • +
    • Accessing a member named after a reserved keyword causes SyntaxError.
    <member> = <enum>.<member_name>         # Returns a member.
     <member> = <enum>['<member_name>']      # Returns a member. Raises KeyError.
    @@ -1193,8 +1193,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 (unless a signal is received).
    • -
    • All variables that are initialized in executed blocks are also visible in all subsequent blocks -, as well as outside the try statement (only function block delimits scope).
    • +
    • All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try statement (only function block delimits scope).
    • To catch signals use 'signal.signal(signal_number, <func>)'.

    Catching Exceptions

    except <exception>: ...
    
    From fabdfe33f4cee7a4ad0cfb2e9d15147da599f9c5 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 5 May 2024 12:02:45 +0200
    Subject: [PATCH 010/281] Exceptions
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 281fe39b3..d8009c6ce 100644
    --- a/README.md
    +++ b/README.md
    @@ -1416,7 +1416,7 @@ except (, [...]) as : ...
     * **Use `'traceback.print_exc()'` to print the full error message to stderr.**
     * **Use `'print()'` to print just the cause of the exception (its arguments).**
     * **Use `'logging.exception()'` to log the passed message, followed by the full error message of the caught exception. For details see [logging](#logging).**
    -* **Use `'sys.exc_info()'` to get exception type, object and traceback of caught exception.**
    +* **Use `'sys.exc_info()'` to get exception type, object, and traceback of caught exception.**
     
     ### Raising Exceptions
     ```python
    diff --git a/index.html b/index.html
    index 01492a272..f4d17c01e 100644
    --- a/index.html
    +++ b/index.html
    @@ -1207,7 +1207,7 @@
     
  • Use 'traceback.print_exc()' to print the full error message to stderr.
  • Use 'print(<name>)' to print just the cause of the exception (its arguments).
  • Use 'logging.exception(<message>)' to log the passed message, followed by the full error message of the caught exception. For details see logging.
  • -
  • Use 'sys.exc_info()' to get exception type, object and traceback of caught exception.
  • +
  • Use 'sys.exc_info()' to get exception type, object, and traceback of caught exception.
  • Raising Exceptions

    raise <exception>
     raise <exception>()
    
    From 5e5233f8ffdf2ab19e25fa3860799031fd8dee43 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 5 May 2024 13:23:33 +0200
    Subject: [PATCH 011/281] Command line arguments
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index d8009c6ce..3b5d1a29c 100644
    --- a/README.md
    +++ b/README.md
    @@ -1555,7 +1555,7 @@ p.add_argument('', type=, nargs='?/*')                # Optional arg
     ```
     
     * **Use `'help='` to set argument description that will be displayed in help message.**
    -* **Use `'default='` to set option's default value.**
    +* **Use `'default='` to set option's or optional argument's default value.**
     * **Use `'type=FileType()'` for files. Accepts 'encoding', but 'newline' is None.**
     
     
    diff --git a/index.html b/index.html
    index f4d17c01e..2b5717e04 100644
    --- a/index.html
    +++ b/index.html
    @@ -1319,7 +1319,7 @@
     
     
    • Use 'help=<str>' to set argument description that will be displayed in help message.
    • -
    • Use 'default=<el>' to set option's default value.
    • +
    • Use 'default=<el>' to set option's or optional argument's default value.
    • Use 'type=FileType(<mode>)' for files. Accepts 'encoding', but 'newline' is None.

    #Open

    Opens the file and returns a corresponding file object.

    <file> = open(<path>, mode='r', encoding=None, newline=None)
    
    From 695961bad3c20c01a8a4b18738e2975bf4172c79 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 5 May 2024 19:16:53 +0200
    Subject: [PATCH 012/281] Struct
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 3b5d1a29c..ca751072c 100644
    --- a/README.md
    +++ b/README.md
    @@ -1998,7 +1998,7 @@ Struct
     
     ```python
     from struct import pack, unpack
    - = pack('',  [, ...])  # Packages arguments or raises struct.error.
    + = pack('',  [, ...])  # Packages arguments. Can raise struct.error.
      = unpack('', )       # Use iter_unpack() to get iterator of tuples.
     ```
     
    diff --git a/index.html b/index.html
    index 2b5717e04..5640f2502 100644
    --- a/index.html
    +++ b/index.html
    @@ -1648,7 +1648,7 @@
     
  • Module that performs conversions between a sequence of numbers and a bytes object.
  • System’s type sizes, byte order, and alignment rules are used by default.
  • from struct import pack, unpack
    -<bytes> = pack('<format>', <el_1> [, ...])  # Packages arguments or raises struct.error.
    +<bytes> = pack('<format>', <el_1> [, ...])  # Packages arguments. Can raise struct.error.
     <tuple> = unpack('<format>', <bytes>)       # Use iter_unpack() to get iterator of tuples.
     
    From a2001bfcd47210fa396c6c851075191101930e7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 7 May 2024 04:46:39 +0200 Subject: [PATCH 013/281] Struct, Memoryview, Deque --- README.md | 24 ++++++++++++------------ index.html | 34 +++++++++++++++------------------- 2 files changed, 27 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index ca751072c..7dad4c6e7 100644 --- a/README.md +++ b/README.md @@ -1998,7 +1998,8 @@ Struct ```python from struct import pack, unpack - = pack('', [, ...]) # Packages arguments. Can raise struct.error. + + = pack('', [, ...]) # Packs objects according to format string. = unpack('', ) # Use iter_unpack() to get iterator of tuples. ``` @@ -2054,23 +2055,19 @@ from array import array Memory View ----------- -* **A sequence object that points to the memory of another bytes-like 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 uses system's sizes.** -* **Byte order is always determined by the system.** +**A sequence object that points to the memory of another bytes-like object. Each element can reference a single or multiple consecutive bytes, depending on format. Order and number of elements can be changed with slicing.** ```python = memoryview() # Immutable if bytes, else mutable. = [index] # Returns an int or a float. - = [] # Mview with rearranged elements. - = .cast('') # Casts memoryview to the new format. -.release() # Releases memory buffer of target object. + = [] # Returns mview with rearranged elements. + = .cast('') # Only works between b/B/c and other types. +.release() # Releases memory buffer of the base object. ``` ```python = bytes() # Returns a new bytes object. - = .join() # Joins mviews using bytes object as sep. + = .join() # Joins mviews using bytes as a separator. = array('', ) # Treats mview as a sequence of numbers. .write() # Writes mview to the binary file. ``` @@ -2088,11 +2085,14 @@ Deque ```python from collections import deque +``` + +```python = deque() # Also `maxlen=None`. .appendleft() # Opposite element is dropped if full. -.extendleft() # Collection gets reversed. - = .popleft() # Raises IndexError if empty. +.extendleft() # Passed collection gets reversed. .rotate(n=1) # Rotates elements to the right. + = .popleft() # Raises IndexError if empty. ``` diff --git a/index.html b/index.html index 5640f2502..3dbf04f2e 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1648,7 +1648,8 @@
  • Module that performs conversions between a sequence of numbers and a bytes object.
  • System’s type sizes, byte order, and alignment rules are used by default.
  • from struct import pack, unpack
    -<bytes> = pack('<format>', <el_1> [, ...])  # Packages arguments. Can raise struct.error.
    +
    +<bytes> = pack('<format>', <el_1> [, ...])  # Packs objects according to format string.
     <tuple> = unpack('<format>', <bytes>)       # Use iter_unpack() to get iterator of tuples.
     
    @@ -1695,22 +1696,16 @@

    Format

    <bytes> = bytes(<array>) # Converts array to a bytes object. <file>.write(<array>) # Writes array to the binary file.

    -

    #Memory View

      -
    • A sequence object that points to the memory of another bytes-like 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 uses system's sizes.
    • -
    • Byte order is always determined by the system.
    • -
    <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
    +

    #Memory View

    A sequence object that points to the memory of another bytes-like object. Each element can reference a single or multiple consecutive bytes, depending on format. Order and number of elements can be changed with slicing.

    <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.
    -<mview> = <mview>.cast('<typecode>')           # Casts memoryview to the new format.
    -<mview>.release()                              # Releases memory buffer of target object.
    +<mview> = <mview>[<slice>]                     # Returns mview with rearranged elements.
    +<mview> = <mview>.cast('<typecode>')           # Only works between b/B/c and other types.
    +<mview>.release()                              # Releases memory buffer of the base object.
     
    <bytes> = bytes(<mview>)                       # Returns a new bytes object.
    -<bytes> = <bytes>.join(<coll_of_mviews>)       # Joins mviews using bytes object as sep.
    +<bytes> = <bytes>.join(<coll_of_mviews>)       # Joins mviews using bytes as a separator.
     <array> = array('<typecode>', <mview>)         # Treats mview as a sequence of numbers.
     <file>.write(<mview>)                          # Writes mview to the binary file.
     
    @@ -1719,14 +1714,15 @@

    Format

    # Returns hex pairs. Accepts `sep=<str>`.

    #Deque

    A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

    from collections import deque
    -<deque> = deque(<collection>)                  # Also `maxlen=None`.
    -<deque>.appendleft(<el>)                       # Opposite element is dropped if full.
    -<deque>.extendleft(<collection>)               # Collection gets reversed.
    -<el> = <deque>.popleft()                       # Raises IndexError if empty.
    -<deque>.rotate(n=1)                            # Rotates elements to the right.
     
    +
    <deque> = deque(<collection>)                  # Also `maxlen=None`.
    +<deque>.appendleft(<el>)                       # Opposite element is dropped if full.
    +<deque>.extendleft(<collection>)               # Passed collection gets reversed.
    +<deque>.rotate(n=1)                            # Rotates elements to the right.
    +<el> = <deque>.popleft()                       # Raises IndexError if empty.
    +

    #Threading

    CPython interpreter can only run a single thread at a time. 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, Timer, RLock, Semaphore, Event, Barrier
     from concurrent.futures import ThreadPoolExecutor, as_completed
     
    @@ -2936,7 +2932,7 @@

    Format

    -
    <bytes> = bytes(<array>)                       # Converts array to a bytes object.
    +
    <bytes> = bytes(<array>)                       # Returns a copy of array's memory.
     <file>.write(<array>)                          # Writes array to the binary file.
     

    #Memory View

    A sequence object that points to the memory of another bytes-like object. Each element can reference a single or multiple consecutive bytes, depending on format. Order and number of elements can be changed with slicing.

    <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
    
    From 8f46c967fbf65cd2589bd3fffc6d9cd484ffda22 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 8 May 2024 01:42:12 +0200
    Subject: [PATCH 015/281] Updated index
    
    ---
     index.html                   |  4 +-
     pdf/index_for_pdf.html       | 71 +++++++++++++++++-------------------
     pdf/index_for_pdf_print.html | 31 +++++++---------
     3 files changed, 50 insertions(+), 56 deletions(-)
    
    diff --git a/index.html b/index.html
    index 713555000..582354b59 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -2932,7 +2932,7 @@

    Format

    A

    asyncio module, 33
    audio, 40-41, 42

    B

    -

    beautifulsoup library, 35
    +

    beautifulsoup library, 35
    binary representation, 7, 8
    bitwise operators, 8, 31
    bytes, 22-23, 25, 28-29

    C

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

    C

    copy function, 15
    coroutine, 33
    counter, 2, 4, 12, 17
    -csv, 26, 34, 46, 47
    +csv, 26, 34, 46, 47
    curses module, 33, 34
    cython, 49

    D

    dataclasses module, 12, 15
    -datetime module, 8-9
    -decorator, 13, 14, 15, 16
    +datetime module, 8-9
    +decorator, 13, 14, 15, 16
    deques, 29
    dictionaries, 2, 4, 11, 19, 21
    duck types, 16-19

    E

    -

    enum module, 19-20
    +

    enum module, 19-20
    enumerate function, 3
    -eval function, 33
    -exceptions, 20-21, 23, 35

    +exceptions, 20-21, 23, 32

    F

    -

    files, 22-29, 34, 46
    +

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

    G

    generators, 4, 11, 17
    global keyword, 12
    -gui, 48

    +gui, 35

    H

    hashable, 15, 16
    hexadecimal representation, 7, 8, 28

    I

    -

    image, 35, 39-40, 42-43
    +

    image, 35, 39-40, 42-43
    imports, 12
    -inline, 11, 15, 20
    +inline, 11, 15, 20
    input function, 22
    -introspection, 21, 31
    -ints, 4, 7, 8, 28
    -is operator, 16
    +introspection, 21, 32
    +ints, 4, 7, 8, 28
    +is operator, 16, 31
    iterable, 4, 18, 19
    iterator, 3-4, 11, 17
    itertools module, 3, 8

    J

    -

    json, 25, 36, 46

    +

    json, 25, 36, 46

    L

    lambda, 11
    list comprehension, 11
    -lists, 1-2, 4, 11, 19, 21
    +lists, 1-2, 4, 11, 18-19, 21
    locale module, 16
    -locks, 30, 33
    -logging, 35

    +locks, 30
    +logging, 32

    M

    main function, 1, 49
    map function, 11, 31
    -math module, 7
    -memoryviews, 29
    -metaclass attribute, 32
    -metaprogramming, 31-32

    +math module, 7
    +memoryviews, 29

    N

    namedtuples, 3
    nonlocal keyword, 12
    @@ -95,38 +92,38 @@

    N

    O

    open function, 17, 22-23, 25, 26, 28
    operator module, 31
    -os commands, 23-25, 34

    +os commands, 23-25, 34

    P

    pandas library, 44-48
    partial function, 12, 20
    -paths, 23-24, 34
    +paths, 23-24, 34
    pickle module, 25
    pillow library, 39-40
    -plotting, 34, 46, 47-48
    +plotting, 34, 44, 46, 47-48
    print function, 22
    profiling, 36-37
    progress bar, 34
    property decorator, 15
    pygame library, 42-43

    Q

    -

    queues, 29, 30, 33

    +

    queues, 29, 30, 33

    R

    random module, 8
    ranges, 3, 4
    recursion, 13
    reduce function, 11, 31
    regular expressions, 5-6
    -requests library, 35, 36

    +requests library, 35, 36

    S

    scope, 10, 12, 20
    -scraping, 35, 43, 46, 47-48
    +scraping, 35, 43, 46, 47-48
    sequence, 4, 18-19
    -sets, 2, 4, 11, 19, 21, 31
    +sets, 2, 4, 11, 19, 21
    shell commands, 25
    sleep function, 34
    sortable, 1, 16
    splat operator, 10-11, 26
    -sql, 27, 46
    +sql, 27, 46
    statistics, 7, 37-38, 44-48
    strings, 4-7, 14
    struct module, 28-29
    @@ -136,11 +133,11 @@

    S

    T

    table, 26, 27, 34, 37-38, 45-46
    template, 6, 36
    -threading module, 30
    -time module, 34, 36
    -tuples, 3, 4, 11
    -type, 4, 31-32
    -type annotations, 15

    +threading module, 30, 36
    +time module, 34, 36
    +tuples, 3, 4, 11, 18-19
    +type, 4
    +type annotations, 15, 32

    W

    wave module, 40-41
    web, 36

    diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 6099f8d88..86a0e7e94 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -44,8 +44,7 @@

    D

    E

    enum module, 19-20
    enumerate function, 3
    -eval function, 33
    -exceptions, 20-21, 23, 35

    +exceptions, 20-21, 23, 32

    F

    files, 22-29, 34, 46
    filter function, 11
    @@ -57,7 +56,7 @@

    F

    G

    generators, 4, 11, 17
    global keyword, 12
    -gui, 48

    +gui, 35

    H

    hashable, 15, 16
    hexadecimal representation, 7, 8, 28

    @@ -66,9 +65,9 @@

    I

    imports, 12
    inline, 11, 15, 20
    input function, 22
    -introspection, 21, 31
    +introspection, 21, 32
    ints, 4, 7, 8, 28
    -is operator, 16
    +is operator, 16, 31
    iterable, 4, 18, 19
    iterator, 3-4, 11, 17
    itertools module, 3, 8

    @@ -77,17 +76,15 @@

    J

    L

    lambda, 11
    list comprehension, 11
    -lists, 1-2, 4, 11, 19, 21
    +lists, 1-2, 4, 11, 18-19, 21
    locale module, 16
    -locks, 30, 33
    -logging, 35

    +locks, 30
    +logging, 32

    M

    main function, 1, 49
    map function, 11, 31
    math module, 7
    -memoryviews, 29
    -metaclass attribute, 32
    -metaprograming, 31-32

    +memoryviews, 29

    N

    namedtuples, 3
    nonlocal keyword, 12
    @@ -102,7 +99,7 @@

    P

    paths, 23-24, 34
    pickle module, 25
    pillow library, 39-40
    -plotting, 34, 46, 47-48
    +plotting, 34, 44, 46, 47-48
    print function, 22
    profiling, 36-37
    progress bar, 34
    @@ -121,7 +118,7 @@

    S

    scope, 10, 12, 20
    scraping, 35, 43, 46, 47-48
    sequence, 4, 18-19
    -sets, 2, 4, 11, 19, 21, 31
    +sets, 2, 4, 11, 19, 21
    shell commands, 25
    sleep function, 34
    sortable, 1, 16
    @@ -136,11 +133,11 @@

    S

    T

    table, 26, 27, 34, 37-38, 45-46
    template, 6, 36
    -threading module, 30
    +threading module, 30, 36
    time module, 34, 36
    -tuples, 3, 4, 11
    -type, 4, 31-32
    -type annotations, 15

    +tuples, 3, 4, 11, 18-19
    +type, 4
    +type annotations, 15, 32

    W

    wave module, 40-41
    web, 36

    From af9f3c5bbc81942e581dcef4f8d183dfe37e82b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 8 May 2024 02:05:19 +0200 Subject: [PATCH 016/281] Updated index --- pdf/index_for_pdf.html | 3 ++- pdf/index_for_pdf_print.html | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index f516465c1..a375e91f0 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -82,6 +82,7 @@

    L

    logging, 32

    M

    main function, 1, 49
    +match statement, 31
    map function, 11, 31
    math module, 7
    memoryviews, 29

    @@ -110,7 +111,7 @@

    Q

    R

    random module, 8
    ranges, 3, 4
    -recursion, 13
    +recursion, 13, 21
    reduce function, 11, 31
    regular expressions, 5-6
    requests library, 35, 36

    diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 86a0e7e94..c649ab95e 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -82,6 +82,7 @@

    L

    logging, 32

    M

    main function, 1, 49
    +match statement, 31
    map function, 11, 31
    math module, 7
    memoryviews, 29

    @@ -110,7 +111,7 @@

    Q

    R

    random module, 8
    ranges, 3, 4
    -recursion, 13
    +recursion, 13, 21
    reduce function, 11, 31
    regular expressions, 5-6
    requests library, 35, 36

    From d7cc1422d1b29e6221613db7e9a8a20d42fad028 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 9 May 2024 01:47:20 +0200 Subject: [PATCH 017/281] Updated index --- index.html | 4 ++-- pdf/index_for_pdf.html | 18 ++++++++++-------- pdf/index_for_pdf_print.html | 20 +++++++++++--------- 3 files changed, 23 insertions(+), 19 deletions(-) diff --git a/index.html b/index.html index 582354b59..c6755ca75 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -2932,7 +2932,7 @@

    Format

    C

    collections module, 2, 3, 4, 19, 29
    combinatorics, 8
    command line arguments, 22
    -comparable, 16
    comprehensions, 11
    context manager, 17, 23, 27, 30
    copy function, 15
    @@ -44,17 +43,19 @@

    D

    E

    enum module, 19-20
    enumerate function, 3
    -exceptions, 20-21, 23, 32

    +excel, 46
    +exceptions, 20-21, 23, 32
    +exit function, 21

    F

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

    +functools module, 11, 12, 13, 16

    G

    -

    generators, 4, 11, 17
    +

    games, 33, 42-43
    +generators, 4, 11, 17
    global keyword, 12
    gui, 35

    H

    @@ -75,20 +76,21 @@

    J

    json, 25, 36, 46

    L

    lambda, 11
    -list comprehension, 11
    lists, 1-2, 4, 11, 18-19, 21
    locale module, 16
    -locks, 30
    logging, 32

    M

    main function, 1, 49
    match statement, 31
    +matplotlib library, 34, 44, 46
    map function, 11, 31
    math module, 7
    -memoryviews, 29

    +memoryviews, 29
    +module, 12

    N

    namedtuples, 3
    nonlocal keyword, 12
    +numbers, 4, 6-8
    numpy library, 37-38

    O

    open function, 17, 22-23, 25, 26, 28
    diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index c649ab95e..97d99e22c 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -19,13 +19,12 @@

    B

    C

    cache, 13
    callable, 17
    -class, 4, 14-20, 31-32
    +class, 4, 14-20
    closure, 12-13
    collection, 4, 18, 19
    collections module, 2, 3, 4, 19, 29
    combinatorics, 8
    command line arguments, 22
    -comparable, 16
    comprehensions, 11
    context manager, 17, 23, 27, 30
    copy function, 15
    @@ -44,17 +43,19 @@

    D

    E

    enum module, 19-20
    enumerate function, 3
    -exceptions, 20-21, 23, 32

    +excel, 46
    +exceptions, 20-21, 23, 32
    +exit function, 21

    F

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

    +functools module, 11, 12, 13, 16

    G

    -

    generators, 4, 11, 17
    +

    games, 33, 42-43
    +generators, 4, 11, 17
    global keyword, 12
    gui, 35

    H

    @@ -75,20 +76,21 @@

    J

    json, 25, 36, 46

    L

    lambda, 11
    -list comprehension, 11
    lists, 1-2, 4, 11, 18-19, 21
    locale module, 16
    -locks, 30
    logging, 32

    M

    main function, 1, 49
    match statement, 31
    +matplotlib library, 34, 44, 46
    map function, 11, 31
    math module, 7
    -memoryviews, 29

    +memoryviews, 29
    +module, 12

    N

    namedtuples, 3
    nonlocal keyword, 12
    +numbers, 4, 6-8
    numpy library, 37-38

    O

    open function, 17, 22-23, 25, 26, 28
    From 54fe0134bd4e8cdb8390571d96ec706640834ad9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 11 May 2024 13:05:27 +0200 Subject: [PATCH 018/281] PDF instructions --- pdf/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pdf/README.md b/pdf/README.md index f316bc775..c79b5291d 100644 --- a/pdf/README.md +++ b/pdf/README.md @@ -7,7 +7,6 @@ Setup ----- * Install Adobe Acrobat Pro DC. * Copy headers and footers from `pdf/acrobat/` folder to `/Users//Library/Preferences/Adobe/Acrobat/DC/HeaderFooter/`. -* Run `./parse.js` and commit changes. Printing to PDF @@ -16,7 +15,7 @@ Printing to PDF * Open `index.html` in text editor and first remove element `


    ` before the `

    Libraries

    `. * Then replace the index and footer with contents of `pdf/index_for_pdf.html` file and save. * Disable internet connection and open the file in Chromium version 108.0.5328.0 (later versions will render the site incorrectly after index is added) with 'Cache killer' extension enabled. -* Right click on the border of the site and select inspect. Select `` element under 'Elements' tab and change top margin from 16 to 5 in 'Styles' tab. +* Right click on the border of the site and select inspect. Select `` element under 'Elements' tab and change top margin from 16 to 0 and top padding from 16 to 5 in 'Styles' tab. * Change brightness of comments by right clicking on one of them and selecting inspect. Then click on the rectangle that represents color and toggle the color space to HSLA by clicking on the button with two vertical arrows. Change lightness (L) percentage to 77%. * Change the brightness of text to 13%. * Select 'Print...' with destination 'Save as PDF', paper size 'A4', 'Default' margins (top 10mm, right 9.5mm, bottom 8mm and left 10mm), 'Default' scale and no headers and footers and save (the document should be 51 pages long with last page empty). @@ -28,7 +27,7 @@ Printing to PDF * Open `index.html` in text editor and first remove element `


    ` before the `

    Libraries

    `. * Then replace the index and footer with contents of `pdf/index_for_pdf_print.html` file and save. * Disable internet connection and open the file in Chromium version 108.0.5328.0 (later versions will render the site incorrectly after index is added) with 'Cache killer' extension enabled. -* Right click on the border of the site and select inspect. Select `` element under 'Elements' tab and change top margin from 16 to 5 in 'Styles' tab. +* Right click on the border of the site and select inspect. Select `` element under 'Elements' tab and change top margin from 16 to 0 and top padding from 16 to 5 in 'Styles' tab. * Change brightness of elements by right clicking on them and selecting inspect. Then click on the rectangle that represents color and toggle the color space to HSLA by clicking on the button with two vertical arrows. * Change lightness (L) percentage to: * 0% for the text. From ed3800070c8b257c6bade28d4fab90794a4ffdf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 11 May 2024 13:30:16 +0200 Subject: [PATCH 019/281] PDF footers --- index.html | 4 ++-- pdf/Acrobat/chapter_7.xml | 2 +- pdf/Acrobat/chapter_8.xml | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 pdf/Acrobat/chapter_8.xml diff --git a/index.html b/index.html index c6755ca75..a5a655fa4 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -2932,7 +2932,7 @@

    Format