# notes

path: zk/Voltage_sources.md
sortable_path: zkVoltage_sources.md
title: Voltage sources
lead: The following phenomena are the main sources that we use to generate voltage:
checksum: 88d7509073e3453a58af7a34f89f36e3de1f0212048f3255ad57489a3e2bf0a2
created: 2024-03-30 09:03:21.931596527+00:00
modified: 2024-05-16 06:09:38.490863436+00:00
metadata: {"tags":["physics","electricity"]}
body:
  The following phenomena are the main sources that we use to generate voltage:

  - friction
  - magnetism
  - chemicals
  - light
  - heat
  - pressure

  > In each case, energy in one state is transferred into energy as current. No
  > energy is lost or gained, it simply changes its form.

  ### Magentism (electrical generators)

  Magnetism is used as the voltage source in electrical generators and is by far
  the most common method of producing powerful and large currents at scale.

  If a conductive wire is passed through a magnetic field voltage will be produced
  so long as there is motion between the magnetic field and the conductor. A
  **generator** is a device that generates current in this manner. Generators
  themselves need to be powered. They can be powered by steam from a nuclear power
  plant, water, wind, coal or other fossil fuels.

  #### AC/DC

  Depending on how it is wired, a generator can produce **directed current** (DC)
  or **alternating current** (AC):

  - **Directed current**

    - The electrons flow in only one direction

  - **Alternating current**
    - The electrons flow in one direction and then the other

  ### Chemicals (cells and batteries)

  The chemical creation of current is the physics behind
  [batteries](Cells_and_batteries.md). Chemical current production produces
  currents on a smaller and less industrial scale than generators.

  A chemical cell consists in two dissimilar metals such as copper and zinc. We
  call these the **electrodes**. They are immersed in a salt, acid or alkaline
  solution. We call these the **electrolytes**. The electrolyte pulls the free
  electrons from the copper electrode which leaves it imbalanced with a positive
  charge. The zinc electrode attracts the free electrons from the electrolyte
  giving it a negative charge, thus a difference of potential is achieved.

  ### Light (photovoltaic cells)

  Solar energy can be converted to electrical energy through solar panels which
  are large collections of **photovoltaic cells**.

  When the surfaces of these cells are exposed to light, it dislodges electrons
  from their orbits around the surface atoms of the cell material. For each cell
  this only produces a very small amount of energy, therefore large quantities
  must be used.

raw_content:
  ---
  tags: [physics, electricity]
  ---

  # Voltage sources

  The following phenomena are the main sources that we use to generate voltage:

  - friction
  - magnetism
  - chemicals
  - light
  - heat
  - pressure

  > In each case, energy in one state is transferred into energy as current. No
  > energy is lost or gained, it simply changes its form.

  ### Magentism (electrical generators)

  Magnetism is used as the voltage source in electrical generators and is by far
  the most common method of producing powerful and large currents at scale.

  If a conductive wire is passed through a magnetic field voltage will be produced
  so long as there is motion between the magnetic field and the conductor. A
  **generator** is a device that generates current in this manner. Generators
  themselves need to be powered. They can be powered by steam from a nuclear power
  plant, water, wind, coal or other fossil fuels.

  #### AC/DC

  Depending on how it is wired, a generator can produce **directed current** (DC)
  or **alternating current** (AC):

  - **Directed current**

    - The electrons flow in only one direction

  - **Alternating current**
    - The electrons flow in one direction and then the other

  ### Chemicals (cells and batteries)

  The chemical creation of current is the physics behind
  [batteries](Cells_and_batteries.md). Chemical current production produces
  currents on a smaller and less industrial scale than generators.

  A chemical cell consists in two dissimilar metals such as copper and zinc. We
  call these the **electrodes**. They are immersed in a salt, acid or alkaline
  solution. We call these the **electrolytes**. The electrolyte pulls the free
  electrons from the copper electrode which leaves it imbalanced with a positive
  charge. The zinc electrode attracts the free electrons from the electrolyte
  giving it a negative charge, thus a difference of potential is achieved.

  ### Light (photovoltaic cells)

  Solar energy can be converted to electrical energy through solar panels which
  are large collections of **photovoltaic cells**.

  When the surfaces of these cells are exposed to light, it dislodges electrons
  from their orbits around the surface atoms of the cell material. For each cell
  this only produces a very small amount of energy, therefore large quantities
  must be used.


path: zk/What_are_disks.md
sortable_path: zkWhat_are_disks.md
title: What are disks?
lead:
  A disk is a mass storage [block_device](Devices.md) which we
  can write to and read from.

checksum: c22f8c91037866cc18d6f7236e40d00f66c3cf1ecf398f8f67b6bdbdae24f0ac
created: 2024-03-30 09:03:21.942804056+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["disks"]}
body:
  A disk is a mass storage [block_device](Devices.md) which we
  can write to and read from.

  ## SCSI

  - Small Computer System Interface, responsible for handling disk access on most
    Linux systems.
  - It is a protocol that allows communicaton between printers, scanners and other
    peripherals in addition to harddisks.

  ## Disk schematic

  The following diagram represents the basic anatomy of a disk device.

  ![](/img/harddisk.png)

  - A disk is divided up into [partitions](Partitions.md)
    which are subsections of the overall disk. The kernel presents each partition
    as a [block device](Devices.md) as it would with an entire
    disk.
  - The disk dedicates a small part of its contents to a **partition table**: this
    defines the different partitions that comprise the total disk space.
  - The **filesystem** is a database of files and directories: this comprises the
    bulk of the partition and is what you interact with in
    [user space](User_Space.md) when reading and writing data.

raw_content:
  ---
  tags:
    - disks
  ---

  # What are disks?

  A disk is a mass storage [block_device](Devices.md) which we
  can write to and read from.

  ## SCSI

  - Small Computer System Interface, responsible for handling disk access on most
    Linux systems.
  - It is a protocol that allows communicaton between printers, scanners and other
    peripherals in addition to harddisks.

  ## Disk schematic

  The following diagram represents the basic anatomy of a disk device.

  ![](/img/harddisk.png)

  - A disk is divided up into [partitions](Partitions.md)
    which are subsections of the overall disk. The kernel presents each partition
    as a [block device](Devices.md) as it would with an entire
    disk.
  - The disk dedicates a small part of its contents to a **partition table**: this
    defines the different partitions that comprise the total disk space.
  - The **filesystem** is a database of files and directories: this comprises the
    bulk of the partition and is what you interact with in
    [user space](User_Space.md) when reading and writing data.


path: zk/Whole_numbers.md
sortable_path: zkWhole_numbers.md
title: The set of whole numbers
lead: We recall the set of whole numbers:
checksum: 55a213e7c8d3fd57417fb5291e2452abb12fdc19266c9a6c00130544e5b85789
created: 2024-03-30 09:03:21.964186692+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["prealgebra"]}
body:
  We recall the set of whole numbers:

  $$ \mathbb{W} = {0, 1, 2, 3, ...} $$

  # The properties of $\mathbb{W}$

  > In mathematics, a **property** is any characteristic that applies to a given
  > set.

  ## The commutative property

  ### Addition

  When **adding** whole numbers, the placement of the addends does not affect the
  sum.

  Let **a**, **b** represent whole numbers, then:

  $$ a + b = b + a $$

  ### Multiplication

  When **multiplying** whole numbers the placement of the
  [multiplicands](Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd)
  does not affect the
  [product](Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd).

  Let **a, b** represent whole numbers, then:

  $$ a \cdot b = b \cdot a $$

  ### Subtraction

  **Subtraction** is not commutative, viz:

  $$ a - b \neq b - a $$

  ### Division

  Division is not commutative, viz:

  $$ a \div b \neq b \div a $$

  ## The associative property

  ### Addition

  When grouping symbols (parentheses, brackets, braces) are used with addition,
  the particular placement of the grouping symbols relative to each of the addends
  does not change the sum.

  Let **a**, **b, c** represent whole numbers, then:

  $$ (a + b) + c = a + (b + c) $$

  ### Multiplication

  Let **a, b, c** represent whole numbers, then:

  $$ a \cdot (b \cdot c) = (a \cdot b) \cdot c $$

  ### Subtraction

  Subtraction is not associative, viz:

  $$ (a - b) - c \neq a - (b - c) $$

  ### Division

  Division is not associative

  $$ (a \div b) \div c \neq a \div (b \div c) $$

  ## The property of additive identity

  If **a** is any whole number, then:

  $$ a + 0 = a $$

  We therefore call zero the additive identity: whenever we add zero to a whole
  number, the sum is equal to the whole number itself.

  ## The property of multiplicative identity

  If **a** is any whole number, then:

  $$ (a \cdot 1 = a) = (1 \cdot a = a) $$

  ## Multiplication by zero

  If **a** is any whole number, then:

  $$ (a \cdot 0 = 0) = (0 \cdot a = 0) $$

  ## Division by zero

  Division by zero is **undefined** but zero divided is zero.

raw_content:
  ---
  tags:
    - prealgebra
  ---

  # The set of whole numbers

  We recall the set of whole numbers:

  $$ \mathbb{W} = {0, 1, 2, 3, ...} $$

  # The properties of $\mathbb{W}$

  > In mathematics, a **property** is any characteristic that applies to a given
  > set.

  ## The commutative property

  ### Addition

  When **adding** whole numbers, the placement of the addends does not affect the
  sum.

  Let **a**, **b** represent whole numbers, then:

  $$ a + b = b + a $$

  ### Multiplication

  When **multiplying** whole numbers the placement of the
  [multiplicands](Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd)
  does not affect the
  [product](Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd).

  Let **a, b** represent whole numbers, then:

  $$ a \cdot b = b \cdot a $$

  ### Subtraction

  **Subtraction** is not commutative, viz:

  $$ a - b \neq b - a $$

  ### Division

  Division is not commutative, viz:

  $$ a \div b \neq b \div a $$

  ## The associative property

  ### Addition

  When grouping symbols (parentheses, brackets, braces) are used with addition,
  the particular placement of the grouping symbols relative to each of the addends
  does not change the sum.

  Let **a**, **b, c** represent whole numbers, then:

  $$ (a + b) + c = a + (b + c) $$

  ### Multiplication

  Let **a, b, c** represent whole numbers, then:

  $$ a \cdot (b \cdot c) = (a \cdot b) \cdot c $$

  ### Subtraction

  Subtraction is not associative, viz:

  $$ (a - b) - c \neq a - (b - c) $$

  ### Division

  Division is not associative

  $$ (a \div b) \div c \neq a \div (b \div c) $$

  ## The property of additive identity

  If **a** is any whole number, then:

  $$ a + 0 = a $$

  We therefore call zero the additive identity: whenever we add zero to a whole
  number, the sum is equal to the whole number itself.

  ## The property of multiplicative identity

  If **a** is any whole number, then:

  $$ (a \cdot 1 = a) = (1 \cdot a = a) $$

  ## Multiplication by zero

  If **a** is any whole number, then:

  $$ (a \cdot 0 = 0) = (0 \cdot a = 0) $$

  ## Division by zero

  Division by zero is **undefined** but zero divided is zero.


path: zk/Why_computers_use_binary.md
sortable_path: zkWhy_computers_use_binary.md
title: Why computers use binary
lead: ## Now we know how binary works, how does it relate to computing?
checksum: f4ecd720bd3d0573e2236d1728dc1afa38b91079c9a8747f0318511b4cac5036
created: 2024-03-30 09:03:22.004239333+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["binary"]}
body:
  ## Now we know how binary works, how does it relate to computing?

  The reason is straight forward: it is the simplest way on the level of pure
  engineering of representing numerical and logical values; both of which are the
  basic foundations of programming. An electronic circuit or transistor only needs
  to represent two states: on (1) and off (0) which corresponds to the switch on
  an electrical circuit. A single circuit representing the binary values of 1 and
  0:

  ![multi_on_off 1.gif](multi_on_off.gif)

  It would be much more complicated to have to represent ten different states
  under the decimal number system, although denary computers do exist.

  If we want more digits, we just need to add in more circuits, and we can
  represent as large a binary number as we need. We just need one switch for every
  digit we want to represent. The switches used in modern computers are so cheap
  and so small that billions can be fitted on a single circuit board.

  ![multiple_circuits.gif](multiple_circuits.gif)

  When we use the term 'switch' we actually mean the transistor components of a
  circuit. We don't need to know the physical details at this level but we can say
  that a transistor turns a current on and off. They can also be used to amplify
  the current.

  On the level of electrical engineering and in the subsequent examples using a
  light bulb and a simple circuit, the switch being OFF corresponds to the light
  being ON, this is because the switch breaks the current. So when it is unbroken,
  the current passes to the bulb. This also means that 1 corresponds to the switch
  being OFF and 0 corresponds to the switch being ON which can be confusing at
  first.

  ## From circuits to programs

  The following breaks down how we get from the binary number system to electrical
  circuits to computer programs:

  1. ”Data”= a piece or pieces of **information**

  1. In computing all data is represented in **binary form:**

     2.1. ”Binary” means that the value of a piece of data is exclusively one
     thing or another

     2.2. The values in binary code are exclusively 1 and 0 (either a piece of
     data is a 1 or it is a 0, it can never be both). Binary can also be expressed
     in logical terms where 1 is equal to `true` and 0 is equal to `false`

  1. The smallest piece of data is a **bit**

  1. We apply the binary number system to bits

  1. Thus by 1-4, **a bit is either 1 or 0**

  1. Binary form bears an isomorphic relation to switches on electrical circuits
     (the hardware of computers). Thus binary code can be _mapped onto circuits_.

     - Circuits are controlled by switches
     - A switch is a binary function: it is either on or off ”On/off”
       corresponding to 1/0.
     - In this way, switches control the flow of electric current

  1. Thus by the above, hardware (which is a physical structure made up of
     electric circuits) is **readily programmable in binary terms**

  1. Restatement of 6: in order for hardware to be programmed the program must
     provide the hardware with something that it can actually perform. The program
     must be formulated in binary code.

raw_content:
  ---
  tags: [binary]
  ---

  # Why computers use binary

  ## Now we know how binary works, how does it relate to computing?

  The reason is straight forward: it is the simplest way on the level of pure
  engineering of representing numerical and logical values; both of which are the
  basic foundations of programming. An electronic circuit or transistor only needs
  to represent two states: on (1) and off (0) which corresponds to the switch on
  an electrical circuit. A single circuit representing the binary values of 1 and
  0:

  ![multi_on_off 1.gif](multi_on_off.gif)

  It would be much more complicated to have to represent ten different states
  under the decimal number system, although denary computers do exist.

  If we want more digits, we just need to add in more circuits, and we can
  represent as large a binary number as we need. We just need one switch for every
  digit we want to represent. The switches used in modern computers are so cheap
  and so small that billions can be fitted on a single circuit board.

  ![multiple_circuits.gif](multiple_circuits.gif)

  When we use the term 'switch' we actually mean the transistor components of a
  circuit. We don't need to know the physical details at this level but we can say
  that a transistor turns a current on and off. They can also be used to amplify
  the current.

  On the level of electrical engineering and in the subsequent examples using a
  light bulb and a simple circuit, the switch being OFF corresponds to the light
  being ON, this is because the switch breaks the current. So when it is unbroken,
  the current passes to the bulb. This also means that 1 corresponds to the switch
  being OFF and 0 corresponds to the switch being ON which can be confusing at
  first.

  ## From circuits to programs

  The following breaks down how we get from the binary number system to electrical
  circuits to computer programs:

  1. ”Data”= a piece or pieces of **information**

  1. In computing all data is represented in **binary form:**

     2.1. ”Binary” means that the value of a piece of data is exclusively one
     thing or another

     2.2. The values in binary code are exclusively 1 and 0 (either a piece of
     data is a 1 or it is a 0, it can never be both). Binary can also be expressed
     in logical terms where 1 is equal to `true` and 0 is equal to `false`

  1. The smallest piece of data is a **bit**

  1. We apply the binary number system to bits

  1. Thus by 1-4, **a bit is either 1 or 0**

  1. Binary form bears an isomorphic relation to switches on electrical circuits
     (the hardware of computers). Thus binary code can be _mapped onto circuits_.

     - Circuits are controlled by switches
     - A switch is a binary function: it is either on or off ”On/off”
       corresponding to 1/0.
     - In this way, switches control the flow of electric current

  1. Thus by the above, hardware (which is a physical structure made up of
     electric circuits) is **readily programmable in binary terms**

  1. Restatement of 6: in order for hardware to be programmed the program must
     provide the hardware with something that it can actually perform. The program
     must be formulated in binary code.


path: zk/Wildcards_in_SQL.md
sortable_path: zkWildcards_in_SQL.md
title: Wildcards in SQL
lead:
  SQL does not use Regex. Instead it has a simpler glob-like syntax for carrying
  out string matching.

checksum: 9068a108c480287dbe6ee7f57587290bfe6eb5f2ba86a739caf2778bdd24a074
created: 2024-03-30 09:03:22.009604092+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["SQL","relational-databases"]}
body:
  SQL does not use Regex. Instead it has a simpler glob-like syntax for carrying
  out string matching.

  In order to signal that you wish to compare by a wildcard and not a value, you
  have to use the `LIKE` keyword. The actual wildcard operator is `%` .

  In an SQL statement, the `%` wild card will match any number of occurrences of
  any character. Any characters can appear before or after ‘MacBook’ and the
  record will still be returned:

  ```sql
  SELECT name, cores, release_date
  FROM model
  WHERE name LIKE '%MacBook%';
  ```

  This wildcard only filters characters that come after `Raspberry` :

  ```sql
  SELECT name, cores, release_date
  FROM model
  WHERE name LIKE 'Raspberry%';
  ```

raw_content:
  ---
  tags: [SQL, relational-databases]
  ---

  # Wildcards in SQL

  SQL does not use Regex. Instead it has a simpler glob-like syntax for carrying
  out string matching.

  In order to signal that you wish to compare by a wildcard and not a value, you
  have to use the `LIKE` keyword. The actual wildcard operator is `%` .

  In an SQL statement, the `%` wild card will match any number of occurrences of
  any character. Any characters can appear before or after ‘MacBook’ and the
  record will still be returned:

  ```sql
  SELECT name, cores, release_date
  FROM model
  WHERE name LIKE '%MacBook%';
  ```

  This wildcard only filters characters that come after `Raspberry` :

  ```sql
  SELECT name, cores, release_date
  FROM model
  WHERE name LIKE 'Raspberry%';
  ```


path: zk/Working_with_numbers_in_Bash.md
sortable_path: zkWorking_with_numbers_in_Bash.md
title: Working with numbers in Bash
lead: We distinguish:
checksum: d793b757573d5c77ece45d9b81efbc9a285dfe699f8221faf4f0ab9f095c96c5
created: 2024-03-30 09:03:22.015441917+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["shell"]}
body:
  We distinguish:

  - **arithmetic expansion** `$(( ))`
    - returns the result of literal numbers that can then be stored in a variable
  - **artihmetic evaluation** `(( ))`
    - perform calculations on _existing_ variables

  An example of expansion:

  ```bash
  a=3
  ((a += 3))
  echo $a
  # 6
  ((a++))
  # 7
  ```

  > Note: we do not use a dollar-sign when referring to variables within
  > arithmetic evaluation, there is no need. If we do, we get an error. This is
  > because we are using an
  > [expansion](Expansions_and_substitutions.md),
  > therefore the variables are already being interpreted as variables.

  ## Declaring variables as integers

  It is good practice to safeguard against Bash treating numbers as strings to
  declare them as integers in addition to using arithmetic evaluation, e.g:

  ```bash
  declare -i b=3
  ```

  Whilst this isn't a strict type, it means we can do this:

  ```bash
  b=$b+4
  echo b
  # 7
  ```

  Without getting `3+4` in return

  ## No decimals in bash

  Bash does not support decimal calculations natively. This is what you'd get for
  example:

  ```bash
  echo $(( 1/3 ))
  # 0 (not 0.33)
  ```

  So work with decimals you should use `awk` or `bc` ("basic calculations").

  Example of using `bc`:

  ```bash
  declare -i c=1
  declare -i d=3
  e=$(echo "scale=3; $c/$d" | bc)
  # 0.333
  ```

  ## Random numbers

  Generate a pseudo-random number between 1 and 20:

  ```bash
  echo $(( 1 + RANDOM % 10))
  # 18
  ```

raw_content:
  ---
  tags:
    - shell
  ---

  # Working with numbers in Bash

  We distinguish:

  - **arithmetic expansion** `$(( ))`
    - returns the result of literal numbers that can then be stored in a variable
  - **artihmetic evaluation** `(( ))`
    - perform calculations on _existing_ variables

  An example of expansion:

  ```bash
  a=3
  ((a += 3))
  echo $a
  # 6
  ((a++))
  # 7
  ```

  > Note: we do not use a dollar-sign when referring to variables within
  > arithmetic evaluation, there is no need. If we do, we get an error. This is
  > because we are using an
  > [expansion](Expansions_and_substitutions.md),
  > therefore the variables are already being interpreted as variables.

  ## Declaring variables as integers

  It is good practice to safeguard against Bash treating numbers as strings to
  declare them as integers in addition to using arithmetic evaluation, e.g:

  ```bash
  declare -i b=3
  ```

  Whilst this isn't a strict type, it means we can do this:

  ```bash
  b=$b+4
  echo b
  # 7
  ```

  Without getting `3+4` in return

  ## No decimals in bash

  Bash does not support decimal calculations natively. This is what you'd get for
  example:

  ```bash
  echo $(( 1/3 ))
  # 0 (not 0.33)
  ```

  So work with decimals you should use `awk` or `bc` ("basic calculations").

  Example of using `bc`:

  ```bash
  declare -i c=1
  declare -i d=3
  e=$(echo "scale=3; $c/$d" | bc)
  # 0.333
  ```

  ## Random numbers

  Generate a pseudo-random number between 1 and 20:

  ```bash
  echo $(( 1 + RANDOM % 10))
  # 18
  ```


path: zk/Zero_property_of_multiplication.md
sortable_path: zkZero_property_of_multiplication.md
lead:
  ---
  tags:
  - prealgebra
  - theorems
  ---

checksum: ab65cf0fbf5ec242a321c119815347b74bba3c9a520fa4fb59b5be4e147f563c
created: 2024-03-30 09:03:22.025204158+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["prealgebra","theorems"]}
body:
  ---
  tags:
    - prealgebra
    - theorems
  ---

  **Let $a$ represent any member of $\mathbb{W}$ or $\mathbb{Z}$ then:**

  $$ a \cdot 0 = 0 $$

raw_content:
  ---
  tags:
    - prealgebra
    - theorems
  ---

  **Let $a$ represent any member of $\mathbb{W}$ or $\mathbb{Z}$ then:**

  $$ a \cdot 0 = 0 $$


path: zk/Zip_function_in_Python.md
sortable_path: zkZip_function_in_Python.md
title: zip
checksum: 0e7191e6c8fbb369de0479b6d8f0ebcd60161e6cf2f4f978eb878aa8436e54a1
created: 2024-03-30 09:03:22.028631364+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["python","data-structures"]}
lead:
  The `zip` function returns a zip object when you pass in two iterator data types
  (typically two lists). This is an iterator of tuples where the first item in
  each passed iterator is paired together, and then the second item in each passed
  iterator are paired together, and so on.

body:
  The `zip` function returns a zip object when you pass in two iterator data types
  (typically two lists). This is an iterator of tuples where the first item in
  each passed iterator is paired together, and then the second item in each passed
  iterator are paired together, and so on.

  ## Example

  ```py
  a = ("John", "Charles", "Mike")
  b = ("Jenny", "Christy", "Monica", "Vicky")

  x = zip(a,b)

  print(x)
  # <zip object at 0x1514af34c340>

  # To display the resulting tuple in a readable format:

  print(tuple(x))

  (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
  ```

  As indicated above, if the input iterators are of equal lengths, Python will
  ignore the value in iterator B that doesn't have an equivalent index in iterator
  A.

  ## Real-life example

  ```py
  prompts = [
      "Enter title",
      "Enter author",
      "Enter publication date",
      "Enter year you read the book"
  ]

  keys = ["Title", "Author", "Publication_date", "Date_read"]

  book = {}

  for key, prompt in zip(keys,prompts):
      book[key] = input(prompt + ": ")

  ```

  Here I take the `prompts` and `keys` lists, collate them via `zip` and then loop
  through them to populate the `book` dictionary, which contains properties
  sourced from the `keys` list and values from the user's answers to the
  `prompts`.

raw_content:
  ---
  tags: [python, data-structures]
  ---

  # `zip`

  The `zip` function returns a zip object when you pass in two iterator data types
  (typically two lists). This is an iterator of tuples where the first item in
  each passed iterator is paired together, and then the second item in each passed
  iterator are paired together, and so on.

  ## Example

  ```py
  a = ("John", "Charles", "Mike")
  b = ("Jenny", "Christy", "Monica", "Vicky")

  x = zip(a,b)

  print(x)
  # <zip object at 0x1514af34c340>

  # To display the resulting tuple in a readable format:

  print(tuple(x))

  (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))
  ```

  As indicated above, if the input iterators are of equal lengths, Python will
  ignore the value in iterator B that doesn't have an equivalent index in iterator
  A.

  ## Real-life example

  ```py
  prompts = [
      "Enter title",
      "Enter author",
      "Enter publication date",
      "Enter year you read the book"
  ]

  keys = ["Title", "Author", "Publication_date", "Date_read"]

  book = {}

  for key, prompt in zip(keys,prompts):
      book[key] = input(prompt + ": ")

  ```

  Here I take the `prompts` and `keys` lists, collate them via `zip` and then loop
  through them to populate the `book` dictionary, which contains properties
  sourced from the `keys` list and values from the user's answers to the
  `prompts`.


path: zk/format_specifiers_in_c.md
sortable_path: zkformat_specifiers_in_c.md
title: Format specifiers in C
lead: # Format specifiers in C
checksum: 0811c81b188bb421c8b324c826bf8e8954a704211ee3da9ef179cbbc967177ba
created: 2024-03-30 09:03:22.03361984+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
body:
  # Format specifiers in C

  Format specifiers define the type of data to be printed on standard output. You
  need to use format specifiers whenever you are
  [printing-values-in-c](printing-values-in-c.md).

  | Specifier | Usage                      |
  | --------- | -------------------------- |
  | `%c`      | single character           |
  | `%s`      | string                     |
  | `%n`      | nothing                    |
  | `%d`      | integer (assuming base 10) |
  | `%f`      | float                      |
  | `%%`      | The percent sign itself    |

raw_content:
  ---
  id: 5faz2y2e
  title: Format specifiers in C
  tags: []
  created: Thursday, February 29, 2024 | 17:41
  ---

  # Format specifiers in C

  Format specifiers define the type of data to be printed on standard output. You
  need to use format specifiers whenever you are
  [printing-values-in-c](printing-values-in-c.md).

  | Specifier | Usage                      |
  | --------- | -------------------------- |
  | `%c`      | single character           |
  | `%s`      | string                     |
  | `%n`      | nothing                    |
  | `%d`      | integer (assuming base 10) |
  | `%f`      | float                      |
  | `%%`      | The percent sign itself    |

metadata:
  {"created":"Thursday, February 29, 2024 | 17:41","id":"5faz2y2e","tags":[],"title":"Format specifiers in C"}


path: zk/fs.md
sortable_path: zkfs.md
title: fs module
checksum: 5194315d53c424ea53a22781148ecdf03c4d340a5f8543a2fef61bb3faa2760a
created: 2024-03-30 09:03:22.049680323+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["backend","node-js"]}
lead:
  File System is an essential built-in module of Node that contains utility
  methods for working with files and directories.

body:
  File System is an essential built-in module of Node that contains utility
  methods for working with files and directories.

  Every method associated with `fs` has a _blocking_ and _asynchronous_
  implementation. The former obviously blocks the
  [event queue](Event_loop.md), the
  latter does not.

  The synchronous methods are useful to have in some contexts but in general and
  with real-world applications, you should be using the async implementation so as
  to accord with the single-threaded event-driven architecture of Node.

  ## Common I/0 methods

  ### Read directory

  Return a string array of all files in the current directory.

  ```js
  fs.readdir("./", function (err, files) {
    if (err) {
      console.error(err);
    } else {
      console.log(files);
    }
  });
  ```

  ### Read from file

  ```js
  fs.readFile("./lorem.md", "UTF-8", function (err, fileContents) {
    console.log(fileContents);
  });
  ```

  ### Write to file

  ```js
  let md = `A new file`;

  fs.writeFile("testFile.md", md.trim(), function () {
    console.log("File was created");
  });
  ```

  ### Appending to file

  ```js
  fs.appendFile("testFile.md", "new content");
  ```

  ### Create directory

  ```js
  if (!fs.existsSync("directory_name")) {
    fs.mkdir("directory_name", function (err) {
      if (err) {
        console.err(err);
      }
    });
  } else {
    console.warn("Directory already exists");
  }
  ```

  ### Rename and remove files

  ```js
  fs.rename("./filename.js", "./newname.js", function () {
    console.log("file renamed");
  });
  ```

  ```js
  // Remove file
  fs.unlink("./file-to-delete", function (err) {
    if (err) {
      console.error(err);
    }
  });
  ```

  ### Rename and remove directories

  ```js
  // Best to use synchronous method here
  fs.rmSync("/dir", { recursive: true, force: true });
  ```

  ## Streams

  See [Handling streams with fs](Streams.md)

raw_content:
  ---
  tags:
    - backend
    - node-js
  ---

  # fs module

  File System is an essential built-in module of Node that contains utility
  methods for working with files and directories.

  Every method associated with `fs` has a _blocking_ and _asynchronous_
  implementation. The former obviously blocks the
  [event queue](Event_loop.md), the
  latter does not.

  The synchronous methods are useful to have in some contexts but in general and
  with real-world applications, you should be using the async implementation so as
  to accord with the single-threaded event-driven architecture of Node.

  ## Common I/0 methods

  ### Read directory

  Return a string array of all files in the current directory.

  ```js
  fs.readdir("./", function (err, files) {
    if (err) {
      console.error(err);
    } else {
      console.log(files);
    }
  });
  ```

  ### Read from file

  ```js
  fs.readFile("./lorem.md", "UTF-8", function (err, fileContents) {
    console.log(fileContents);
  });
  ```

  ### Write to file

  ```js
  let md = `A new file`;

  fs.writeFile("testFile.md", md.trim(), function () {
    console.log("File was created");
  });
  ```

  ### Appending to file

  ```js
  fs.appendFile("testFile.md", "new content");
  ```

  ### Create directory

  ```js
  if (!fs.existsSync("directory_name")) {
    fs.mkdir("directory_name", function (err) {
      if (err) {
        console.err(err);
      }
    });
  } else {
    console.warn("Directory already exists");
  }
  ```

  ### Rename and remove files

  ```js
  fs.rename("./filename.js", "./newname.js", function () {
    console.log("file renamed");
  });
  ```

  ```js
  // Remove file
  fs.unlink("./file-to-delete", function (err) {
    if (err) {
      console.error(err);
    }
  });
  ```

  ### Rename and remove directories

  ```js
  // Best to use synchronous method here
  fs.rmSync("/dir", { recursive: true, force: true });
  ```

  ## Streams

  See [Handling streams with fs](Streams.md)


path: zk/http.md
sortable_path: zkhttp.md
title: http module
checksum: b19573e491ebd2640b101d282653b8983aeaff78a952208beac40c3f5aee906a
created: 2024-03-30 09:03:22.065522364+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["backend","node-js"]}
lead:
  The HTTP Module allows us to create a web server that listens for HTTP requests
  on a given port. It is therefore perfect for creating backends for client-side
  JavaScript.

body:
  The HTTP Module allows us to create a web server that listens for HTTP requests
  on a given port. It is therefore perfect for creating backends for client-side
  JavaScript.

  ## Creating a server

  An HTTP server is another instance of an
  [event emitter](events.md)). It
  therefore has all the same methods as the `EventEmitter` class: `on`, `emit`,
  `addListener` etc. This demonstrates again how much of Node's core functionality
  is based on event emitters.

  _Creating a server_

  ```js
  const http = require("http");

  const server = http.createServer(); // Create server as emitter

  // Register functions to run when listener is triggered
  server.on("connection", (socket) => {
    console.log("new connection...");
  });

  server.listen(3000);
  console.log("Listening on port 3000");
  ```

  This server is functionally equivalent to a generic event emitter:

  ```js
  // Raise an event
  const emitter = new EventEmitter("messageLogged");

  // Register a listener
  emitter.on("messagedLogged", function () {
    console.log("The listener was called.");
  });
  ```

  Whenever a request is made to this server, it raises an event. We can therefore
  target it with the `on` method and make it execute a function when requests are
  made.

  If we were to start the server by running the file and we then used a browser to
  navigate to the port, we would see `new connection` logged every time we refresh
  the page.

  ### Sockets and `req, res`

  A socket is a generic protocol for client-server communication. Crucially it
  **allows simultaneous communication both ways**. The client can contact the
  server but the server can also contact the client. Our listener function above
  uses a socket as the callback function but in most cases this is quite
  low-level, not distinguishing responses from requests. It is more likely that
  you would initiate a `request, resource` architecture in place of a socket:

  ```js
  const server = http.createServer((req, res) => {
    if (req.url === "/") {
      res.write("hello");
      res.end();
    }
  });
  ```

  #### Return JSON

  Below is an example of using this architecture to return JSON to the client:

  ```js
  const server = http.createServer((req, res) => {
    if (req.url === "/products") {
      res.write(JSON.stringify(["shoes", "lipstick", "cups"]));
      res.end();
    }
  });
  ```

  ### Express

  In reality you would rarely use the `http` module directly to create a server.
  This is because it is quite low level and each response must be written in a
  linear fashion as with the two URLs in the previous example. Instead we use
  Express which is a framework for creating servers and routing that is an
  abstraction on top of the core HTTP module.

raw_content:
  ---
  tags:
    - backend
    - node-js
  ---

  # `http` module

  The HTTP Module allows us to create a web server that listens for HTTP requests
  on a given port. It is therefore perfect for creating backends for client-side
  JavaScript.

  ## Creating a server

  An HTTP server is another instance of an
  [event emitter](events.md)). It
  therefore has all the same methods as the `EventEmitter` class: `on`, `emit`,
  `addListener` etc. This demonstrates again how much of Node's core functionality
  is based on event emitters.

  _Creating a server_

  ```js
  const http = require("http");

  const server = http.createServer(); // Create server as emitter

  // Register functions to run when listener is triggered
  server.on("connection", (socket) => {
    console.log("new connection...");
  });

  server.listen(3000);
  console.log("Listening on port 3000");
  ```

  This server is functionally equivalent to a generic event emitter:

  ```js
  // Raise an event
  const emitter = new EventEmitter("messageLogged");

  // Register a listener
  emitter.on("messagedLogged", function () {
    console.log("The listener was called.");
  });
  ```

  Whenever a request is made to this server, it raises an event. We can therefore
  target it with the `on` method and make it execute a function when requests are
  made.

  If we were to start the server by running the file and we then used a browser to
  navigate to the port, we would see `new connection` logged every time we refresh
  the page.

  ### Sockets and `req, res`

  A socket is a generic protocol for client-server communication. Crucially it
  **allows simultaneous communication both ways**. The client can contact the
  server but the server can also contact the client. Our listener function above
  uses a socket as the callback function but in most cases this is quite
  low-level, not distinguishing responses from requests. It is more likely that
  you would initiate a `request, resource` architecture in place of a socket:

  ```js
  const server = http.createServer((req, res) => {
    if (req.url === "/") {
      res.write("hello");
      res.end();
    }
  });
  ```

  #### Return JSON

  Below is an example of using this architecture to return JSON to the client:

  ```js
  const server = http.createServer((req, res) => {
    if (req.url === "/products") {
      res.write(JSON.stringify(["shoes", "lipstick", "cups"]));
      res.end();
    }
  });
  ```

  ### Express

  In reality you would rarely use the `http` module directly to create a server.
  This is because it is quite low level and each response must be written in a
  linear fashion as with the two URLs in the previous example. Instead we use
  Express which is a framework for creating servers and routing that is an
  abstraction on top of the core HTTP module.


path: zk/journald.md
sortable_path: zkjournald.md
title: journald
checksum: ab04e7033960a3f32c1a58a6f012c1bbb929806e583bf7ecb1a0f99436cc7f73
created: 2024-03-30 09:03:22.082651017+00:00
modified: 2024-03-29 18:42:15.172204844+00:00
metadata: {"tags":["systems-programming"]}
lead:
  `journald` is a program that comes as default with [systemd](systemd.md). It is
  a service for collecting and storing system-level log data. I keeps a track of
  all [kernel](The_Kernel.md) processes. It is invaluable when tracing the source
  of problems and errors that may arise on the system level. It keeps a track of
  all kernal processes.

body:
  `journald` is a program that comes as default with [systemd](systemd.md). It is
  a service for collecting and storing system-level log data. I keeps a track of
  all [kernel](The_Kernel.md) processes. It is invaluable when tracing the source
  of problems and errors that may arise on the system level. It keeps a track of
  all kernal processes.

  ![](/img/journald.png)

  ## `journalctl`

  We use `journalctl` to access the logs. The command by itself outputs the entire
  log which will be huge and hard to scroll through. We can refine the results
  with modifiers.

  ### View logs for a specific process with pid

  ```bash
  journalctl _PID=1234
  ```

  ### View logs for a specific time period

  This can be really helpful since you can bracket the most recent events which
  will be more memorable.

  ```bash
  journalctl -S -1h
  ```

  ### View logs for a specfic systemd unit

  ```bash
  journalctl -u [unit_name] -e
  ```

  ### View boot logs

  ```bash
  journalctl -b
  ```

  #### Identify specific boot

  ```bash
  journalctl --list-boots

  ```

  ### List only kernel entries to the journal

  ```bash
  journalctl -k

  ```

raw_content:
  ---
  tags: [systems-programming]
  ---

  # `journald`

  `journald` is a program that comes as default with [systemd](systemd.md). It is
  a service for collecting and storing system-level log data. I keeps a track of
  all [kernel](The_Kernel.md) processes. It is invaluable when tracing the source
  of problems and errors that may arise on the system level. It keeps a track of
  all kernal processes.

  ![](/img/journald.png)

  ## `journalctl`

  We use `journalctl` to access the logs. The command by itself outputs the entire
  log which will be huge and hard to scroll through. We can refine the results
  with modifiers.

  ### View logs for a specific process with pid

  ```bash
  journalctl _PID=1234
  ```

  ### View logs for a specific time period

  This can be really helpful since you can bracket the most recent events which
  will be more memorable.

  ```bash
  journalctl -S -1h
  ```

  ### View logs for a specfic systemd unit

  ```bash
  journalctl -u [unit_name] -e
  ```

  ### View boot logs

  ```bash
  journalctl -b
  ```

  #### Identify specific boot

  ```bash
  journalctl --list-boots

  ```

  ### List only kernel entries to the journal

  ```bash
  journalctl -k

  ```


path: zk/jq.md
sortable_path: zkjq.md
title: jq
lead: ## Remove property
checksum: b1c67e03a0767cff88bdadd877abcb68a7f3bb94f80856fe07b393e402b492e5
created: 2024-03-30 09:03:22.101647543+00:00
modified: 2024-03-27 10:45:52.506858751+00:00
metadata: {"tags":["new","json"]}
body:
  ## Remove property

  Remove property from a JSON array of objects:

  ```json
  {
    "member_inputs": [
      {
        "name": "Thomas",
        "input_type": "select"
      },
      {
        "name": "Martha",
        "input_type": "text"
      }
    ]
  }
  ```

  ```sh
  jq '.member_details |= map(del(.input_type))' memberDetails.json
  ```

  > Add '-i' to modify the source file directly (in-place)

  > Multiple properties can be deleted simply by chaining,
  > e.g.`(del(.input_type, .another_property))`

raw_content:
  ---
  tags: [new, json]
  ---

  # jq

  ## Remove property

  Remove property from a JSON array of objects:

  ```json
  {
    "member_inputs": [
      {
        "name": "Thomas",
        "input_type": "select"
      },
      {
        "name": "Martha",
        "input_type": "text"
      }
    ]
  }
  ```

  ```sh
  jq '.member_details |= map(del(.input_type))' memberDetails.json
  ```

  > Add '-i' to modify the source file directly (in-place)

  > Multiple properties can be deleted simply by chaining,
  > e.g.`(del(.input_type, .another_property))`


path: zk/printing_values_in_c.md
sortable_path: zkprinting_values_in_c.md
title: Printing values in C
lead: # Printing values in C
checksum: c2e34b4564bc870e2bb6e51e8f6d0258b4aff638c0ae6ffd42862cd7b6f6b79c
created: 2024-03-30 09:03:22.111056926+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
body:
  # Printing values in C

  ## To print a literal

  ```c
  printf("hello world")
  ```

  ## To print a variable

  ```c
  int age = 25
  print("%d", age)

  ```

  The `%d` is an example of a [format specifier](./zk/format-specifiers-in-c.md).
  It is the decimal integer format specifier.

raw_content:
  ---
  id: 3hcv0amc
  title: Printing values in C
  tags: []
  created: Thursday, February 29, 2024 | 17:33
  ---

  # Printing values in C

  ## To print a literal

  ```c
  printf("hello world")
  ```

  ## To print a variable

  ```c
  int age = 25
  print("%d", age)

  ```

  The `%d` is an example of a [format specifier](./zk/format-specifiers-in-c.md).
  It is the decimal integer format specifier.

metadata:
  {"created":"Thursday, February 29, 2024 | 17:33","id":"3hcv0amc","tags":[],"title":"Printing values in C"}


path: zk/process.md
sortable_path: zkprocess.md
title: The process module in Node.js
checksum: bf0f893159956038349a6f68567454dff2f86734048dc4fbf8e1b005c985c38c
created: 2024-03-30 09:03:22.127479884+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["backend","node-js"]}
lead:
  `process` is a core module and a global object accessible from anywhere in a
  Node.js application. It contains functionality that allows us to interact with
  information about the current process instance of Node.

body:
  `process` is a core module and a global object accessible from anywhere in a
  Node.js application. It contains functionality that allows us to interact with
  information about the current process instance of Node.

  For example, we can use it to get environment information, read environment
  variables, parse arguments that are passed to the run command, communicate with
  the terminal and exit the current process.

  ## Managing runtime environments

  See
  [Managing Environments](Managing_environments.md).

  ## Accessing arguments: `process.argv`

  We can use `process.argv` to return an array containing the command-line
  arguments passed when a Node process is launched. This could be a whole-app
  entrypoint (i.e. `index.js`) or a single file we are running.

  For instance if we run the following file:

  ```js
  // process-demo.js
  console.log(3 + 3);
  console.log(process.argv);
  ```

  We get:

  ```bash
  6
  [
    '/Users/thomasbishop/.nvm/versions/node/v16.10.0/bin/node',
    '/Users/thomasbishop/prepos/testNode.js'
  ]
  ```

  The first item is the last executed process. The second is the array of
  arguments.

  In the array, the first value is a reference to the Node runtime binary. The
  second is the file that was passed to Node.

  If we passed in a parameter we would get that too:

  ```
  node process-demo.js --fakeFlag
  ```

  Gives us:

  ```bash
  [
    "/Users/thomasbishop/.nvm/versions/node/v16.10.0/bin/node",
    "/Users/thomasbishop/prepos/testNode.js",
    "--fake-flag",
  ]
  ```

  When writing Node CLI applications we can write functions that parse standard
  input. For example:

  ```js
  function parseStandardInput(flag) {
    let indexAfterFlag = process.argv.indexOf(flag);
    console.log(process.argv[indexAfterFlag]);
  }
  ```

  Say we ran a program that took in a username:

  ```bash
  node userName.js --user Thomas
  ```

  Then `parseStandardInput("--user")` would give us `"thomas"`

  ## Standard input and output

  Below is the most basic use case: writing to the output.

  ```js
  // alpha.js
  process.stdout.write("Hello from file \n");
  ```

  ```
  node alpha.js
  Hello from file
  ```

  Typically we want to write and read data that the user provides. To do this we
  need to wait on that event. So we use Node's asynchonous
  [event listeners](events.md). We wait
  on the `data` event:

  ```js
  process.stdin.on("data", (data) => {
    process.stdout.write(data.toString().trim());
  });

  process.stdout.write("\n What is your name? \n");
  process.stdout.write(` \n > `);
  ```

  This waits for whatever input is given and then echoes it.

  Currently there is no way to end this process; it will just keep echoing the
  input.

  So we add an exit clause:

  ```js
  process.stdin.on("data", (data) => {
    process.stdout.write(data.toString().trim());
    process.exit();
  });
  ```

  We can also execute functionality on the exit event:

  ```js
  process.on("exit", () => {
    // Do something
  });
  ```

  > Timings can also obviously be managed via the `setTimeout` and `setInterval`
  > methods.

  ### Additional useful methods

  ```js
  process.stdout.clearLine();
  process.stdout.cursorTo([int]);
  ```

  ### `readline`

  The core `readline` module simplifies the handling of standard input and output
  by providing a wrapper. It reads the input stream line by line. Basic usage:

  ```js
  var readline = require("readline");

  var rl = readline.createInterface(process.stdin, process.stdout);

  rl.question("What is your age? ", (age) => {
    console.log("Your age is: " + age);
  });
  ```

  Usage scenarios at: https://www.geeksforgeeks.org/node-js-readline-module/

raw_content:
  ---
  tags:
    - backend
    - node-js
  ---

  # The `process` module in Node.js

  `process` is a core module and a global object accessible from anywhere in a
  Node.js application. It contains functionality that allows us to interact with
  information about the current process instance of Node.

  For example, we can use it to get environment information, read environment
  variables, parse arguments that are passed to the run command, communicate with
  the terminal and exit the current process.

  ## Managing runtime environments

  See
  [Managing Environments](Managing_environments.md).

  ## Accessing arguments: `process.argv`

  We can use `process.argv` to return an array containing the command-line
  arguments passed when a Node process is launched. This could be a whole-app
  entrypoint (i.e. `index.js`) or a single file we are running.

  For instance if we run the following file:

  ```js
  // process-demo.js
  console.log(3 + 3);
  console.log(process.argv);
  ```

  We get:

  ```bash
  6
  [
    '/Users/thomasbishop/.nvm/versions/node/v16.10.0/bin/node',
    '/Users/thomasbishop/prepos/testNode.js'
  ]
  ```

  The first item is the last executed process. The second is the array of
  arguments.

  In the array, the first value is a reference to the Node runtime binary. The
  second is the file that was passed to Node.

  If we passed in a parameter we would get that too:

  ```
  node process-demo.js --fakeFlag
  ```

  Gives us:

  ```bash
  [
    "/Users/thomasbishop/.nvm/versions/node/v16.10.0/bin/node",
    "/Users/thomasbishop/prepos/testNode.js",
    "--fake-flag",
  ]
  ```

  When writing Node CLI applications we can write functions that parse standard
  input. For example:

  ```js
  function parseStandardInput(flag) {
    let indexAfterFlag = process.argv.indexOf(flag);
    console.log(process.argv[indexAfterFlag]);
  }
  ```

  Say we ran a program that took in a username:

  ```bash
  node userName.js --user Thomas
  ```

  Then `parseStandardInput("--user")` would give us `"thomas"`

  ## Standard input and output

  Below is the most basic use case: writing to the output.

  ```js
  // alpha.js
  process.stdout.write("Hello from file \n");
  ```

  ```
  node alpha.js
  Hello from file
  ```

  Typically we want to write and read data that the user provides. To do this we
  need to wait on that event. So we use Node's asynchonous
  [event listeners](events.md). We wait
  on the `data` event:

  ```js
  process.stdin.on("data", (data) => {
    process.stdout.write(data.toString().trim());
  });

  process.stdout.write("\n What is your name? \n");
  process.stdout.write(` \n > `);
  ```

  This waits for whatever input is given and then echoes it.

  Currently there is no way to end this process; it will just keep echoing the
  input.

  So we add an exit clause:

  ```js
  process.stdin.on("data", (data) => {
    process.stdout.write(data.toString().trim());
    process.exit();
  });
  ```

  We can also execute functionality on the exit event:

  ```js
  process.on("exit", () => {
    // Do something
  });
  ```

  > Timings can also obviously be managed via the `setTimeout` and `setInterval`
  > methods.

  ### Additional useful methods

  ```js
  process.stdout.clearLine();
  process.stdout.cursorTo([int]);
  ```

  ### `readline`

  The core `readline` module simplifies the handling of standard input and output
  by providing a wrapper. It reads the input stream line by line. Basic usage:

  ```js
  var readline = require("readline");

  var rl = readline.createInterface(process.stdin, process.stdout);

  rl.question("What is your age? ", (age) => {
    console.log("Your age is: " + age);
  });
  ```

  Usage scenarios at: https://www.geeksforgeeks.org/node-js-readline-module/


path: zk/python_advent_learnings.md
sortable_path: zkpython_advent_learnings.md
title: Python advent learnings
lead: ### Construct paths without hard-coding absolute path
checksum: 41e623fc64d7bdeedbc4cb74740ba94f0d812a86c637bec43edfdfb62f90f6b5
created: 2024-03-30 09:03:22.147095316+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {}
body:
  ### Construct paths without hard-coding absolute path

  ```py
  puzzle_input_path = os.path.join(os.path.dirname(__file__), "data/test_input.txt")

  ```

  ### Read file by line and store in variable

  ```py
  puzzle_input_path = os.path.join(os.path.dirname(__file__), "data/test_input.txt")

  def getPuzzleInput(file_path):
      with open(file_path, "r") as file:
          return [line.strip() for line in file]


  puzzle_input = getPuzzleInput(puzzle_input_path)

  ```

  ### Conditional tests for members of arrays

  Check that all elements are greater than zero:

  ```py
  if all(element >= 0 for element in array):
      print('All elements greater than 0')
  ```

  Check if any element is less than 0:

  ```py
  if any(element < 0 for element in array):
      print('There is an element that is less than 0')
  ```

  ### Check for substring:

  ```py
  text = "latest test"
  if "test" in text:
      return True
  ```

  ### Control flow in loop

  ```py
  for counter_values in games:
      colour = counter_values[1]
      count = int(counter_values[0])
      if colour in initial_values.keys() and count > initial_values[colour]:
          break
  else:
      valid_games_count += game_number
  ```

  The use of the `else` clause here is a special feature of Python. The `else`
  clause after a `for` loop will normally only execute when the loop has finished
  iterating over the list, but not when the loop is terminated by a `break`
  statement.

  The `else` clause is executed if the `for` loop completes normally. If the
  `break` statement is executed (i.e., if any count in `counter_values` is greater
  than the corresponding count in `initial_values`), the `for` loop is terminated
  and the `else` clause is skipped.

  Here the combination of a `for` loop and the `break` statement creates
  `if, else` logic. If the break condition is not reached, then the `else` block
  runs for every iteration of the loop.

  ### Multiple loop in list comprehension

  ```py
  games = [item.strip().split() for game in games for item in game.split(",")]
  ```

raw_content:
  # Python advent learnings

  ### Construct paths without hard-coding absolute path

  ```py
  puzzle_input_path = os.path.join(os.path.dirname(__file__), "data/test_input.txt")

  ```

  ### Read file by line and store in variable

  ```py
  puzzle_input_path = os.path.join(os.path.dirname(__file__), "data/test_input.txt")

  def getPuzzleInput(file_path):
      with open(file_path, "r") as file:
          return [line.strip() for line in file]


  puzzle_input = getPuzzleInput(puzzle_input_path)

  ```

  ### Conditional tests for members of arrays

  Check that all elements are greater than zero:

  ```py
  if all(element >= 0 for element in array):
      print('All elements greater than 0')
  ```

  Check if any element is less than 0:

  ```py
  if any(element < 0 for element in array):
      print('There is an element that is less than 0')
  ```

  ### Check for substring:

  ```py
  text = "latest test"
  if "test" in text:
      return True
  ```

  ### Control flow in loop

  ```py
  for counter_values in games:
      colour = counter_values[1]
      count = int(counter_values[0])
      if colour in initial_values.keys() and count > initial_values[colour]:
          break
  else:
      valid_games_count += game_number
  ```

  The use of the `else` clause here is a special feature of Python. The `else`
  clause after a `for` loop will normally only execute when the loop has finished
  iterating over the list, but not when the loop is terminated by a `break`
  statement.

  The `else` clause is executed if the `for` loop completes normally. If the
  `break` statement is executed (i.e., if any count in `counter_values` is greater
  than the corresponding count in `initial_values`), the `for` loop is terminated
  and the `else` clause is skipped.

  Here the combination of a `for` loop and the `break` statement creates
  `if, else` logic. If the break condition is not reached, then the `else` block
  runs for every iteration of the loop.

  ### Multiple loop in list comprehension

  ```py
  games = [item.strip().split() for game in games for item in game.split(",")]
  ```


path: zk/systemd.md
sortable_path: zksystemd.md
title: systemd
checksum: eaaa7b472ab50aa87e7ad425929633e3487ad78fd3114d9d2e9d3242cf91b538
created: 2024-03-30 09:03:22.152461124+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["systems-programming"]}
lead:
  Once the [boot process](Boot_process.md) has completed and the bootloader has
  located the kernel and injected it into memory the first user space program
  runs: `init` (for _initialisation_). `init` is a [daemon](Daemons.md) process
  that continues running until shutdown and is responsible for starting all the
  processes that are prerequisites for user space. For example: network
  connections, disk access, user logins etc. `init` is the parent of all
  processes: PID1. Whilst it does a lot of its work in quick succession at boot
  time it is not limited to the this stage of the lifescycle but runs continuously
  in reponse to new user events.

body:
  Once the [boot process](Boot_process.md) has completed and the bootloader has
  located the kernel and injected it into memory the first user space program
  runs: `init` (for _initialisation_). `init` is a [daemon](Daemons.md) process
  that continues running until shutdown and is responsible for starting all the
  processes that are prerequisites for user space. For example: network
  connections, disk access, user logins etc. `init` is the parent of all
  processes: PID1. Whilst it does a lot of its work in quick succession at boot
  time it is not limited to the this stage of the lifescycle but runs continuously
  in reponse to new user events.

  On Linux systems `systemd` is used to implement `init`.

  `systemd` is directly accessible from user space and provides a straightforward
  way to enable/disable, start/stop system level processes

  > `systemd` can track individual service daemons after they start, and group
  > together multiple processes associated with a service, giving you more power
  > and insight into exactly what is running on the system _How Linux Works: Third
  > Edition_, Brian Ward 2021

  ## How systemd works

  ### Goal-directed units

  `systemd` works on the basis of _goals_. Each goal is system task defined as a
  **unit**. A unit contains instructions and a specification of dependencies to
  other units.

  When activating a unit, `systemd` first activates the dependencies and then
  moves onto the details of the unit itself. `init` as implemented by `systemd`
  does not follow a rigid sequence every time, initialising units in the same
  sequence and waiting for one to complete before starting another. Instead it
  activates units whenever they are ready. This, its parallelized nature, is one
  of the main advantages over previous programs that managed the `init` sequence
  on Linux (such as for example System V);

  ### Unit types

  Units are organised into **unit types**. The main types that run at boot time
  are as follows:

  - service units (`.service`)
    - control service daemons
  - socket units (`.socket`)
    - handle incoming network connection request locations
  - device units (`.device`)
    - disks and other devices
  - mount units (`.mount`)
    - handle the attachment of filesystems to the system
  - target units
    - control other units by organising them into groups

  For example, at boot, a target unit called `default.target` groups together a
  number of service and mount units as dependencies. These then run in a
  graph-like dependency structure where a unit that comes late in the boot process
  can depend on several previous units making earlier branches of a dependency
  tree join back together.

  ## systemd configuration files

  Units are managed via `systemd` configuration files.

  ### Configuration file locations

  System level `systemd` config files are located in the _system unit directory_
  at `/usr/lib/systemd/system`. You shouldn't change or manipulate these files or
  attempt to add new config files here since they will be overwritten by the
  system.

  ![](/img/systemd-global-files.png) _`systemd` global unit files_

  Local definitions that relate to the specific user and where the user herself
  can define units are located in the _system configuration_ directory:
  `/etc/systemd/system`.

  ![](/img/systemd-local-files.png)

  _`systemd` local unit files, specific to the currently logged-in user_

  ### Example files

  Below is the systemd service file for the creation of UUIDs:

  ```plain
  [Unit]
  Description=Daemon for generating UUIDs
  Documentation=man:uuidd(8)
  Requires=uuidd.socket

  [Service]
  ExecStart=/usr/sbin/uuidd --socket-activation
  Restart=no
  User=uuidd
  Group=uuidd
  ProtectSystem=strict
  ProtectHome=yes
  PrivateDevices=yes
  PrivateUsers=yes
  ProtectKernelTunables=yes
  ProtectKernelModules=yes
  ProtectControlGroups=yes
  MemoryDenyWriteExecute=yes
  ReadWritePaths=/var/lib/libuuid/
  SystemCallFilter=@default @file-system @basic-io @system-service @signal @io-event @network-io

  [Install]
  Also=uuidd.socket
  ```

  - The `Unit` section provides metadata about the unit including which `systemd`
    dependencies it has
  - `Service` constitutes the main specification for the unit
  - `Install` is the call to set the dependencies running before the `Service`
    functions are accessible.

  ## systemd operations: systemctl

  The `systemctl` command is the chief way of interacting with `systemd`. You use
  it to activate and deactivate services, list their status, reload the
  configuration and so.

  ### View the dependency graph

  `systemctl status` by itself will print a long list of units grouped by their
  dependency relations. It will also provide some metadata about the current
  systemd boot context.

  ### Viewing active units

  Below I have listed the running units pertaining to bluetooth:

  ```
  $ systemctl list-units | grep bluetooth
   sys-devices-pci0000:00-0000:00:14.0-usb3-3\x2d10-3\x2d10:1.0-bluetooth-hci0-hci0:3585.device                                   loaded active plugged   /sys/devices/pci0000:00/0000:00:14.0/usb3/3-10/3-10:1.0/bluetooth/hci0/hci0:3585
    sys-devices-pci0000:00-0000:00:14.0-usb3-3\x2d10-3\x2d10:1.0-bluetooth-hci0.device                                             loaded active plugged   /sys/devices/pci0000:00/0000:00:14.0/usb3/3-10/3-10:1.0/bluetooth/hci0
    sys-subsystem-bluetooth-devices-hci0.device                                                                                    loaded active plugged   /sys/subsystem/bluetooth/devices/hci0
    sys-subsystem-bluetooth-devices-hci0:3585.device                                                                               loaded active plugged   /sys/subsystem/bluetooth/devices/hci0:3585
    bluetooth.service                                                                                                              loaded active running   Bluetooth service
    bluetooth.target                                                                                                               loaded active active    Bluetooth Support
  ```

  ### List jobs

  Requests to activate, reactivate and restart units are called **jobs** in
  `systemd`. They can be thought of as unit state changes. Current jobs can be
  listed with `systemctl list-jobs`.

  This will most likely return `No jobs running` if the computer has been running
  for a while. Most jobs execute at boot.

  ### Enable/disable, start/stop units

  If a unit has dependencies it is necessary to _enable_ it before starting it.
  This installs the dependencies.

  ```bash
  systemctl enable mongodb.service
  Created symlink /etc/systemd/system/multi-user.target.wants/mongodb.service → /usr/lib/systemd/system/mongodb.service.
  ```

  Then we can start:

  ```
  systemctl start mongodb.service
  ```

  To stop the service:

  ```
  systemctl stop mongodb.service
  ```

  After this we should disable it, in order to remove any symbolic links it has
  created on the system as part of the install process:

  ```bash
  systemctl disable mongodb.service
  Removed "/etc/systemd/system/multi-user.target.wants/mongodb.service".
  ```

  ## Why use systemd over cron ?

  https://mark.stosberg.com/2016-08-26-rsnapshot-and-systemd/

raw_content:
  ---
  tags: [systems-programming]
  ---

  # systemd

  Once the [boot process](Boot_process.md) has completed and the bootloader has
  located the kernel and injected it into memory the first user space program
  runs: `init` (for _initialisation_). `init` is a [daemon](Daemons.md) process
  that continues running until shutdown and is responsible for starting all the
  processes that are prerequisites for user space. For example: network
  connections, disk access, user logins etc. `init` is the parent of all
  processes: PID1. Whilst it does a lot of its work in quick succession at boot
  time it is not limited to the this stage of the lifescycle but runs continuously
  in reponse to new user events.

  On Linux systems `systemd` is used to implement `init`.

  `systemd` is directly accessible from user space and provides a straightforward
  way to enable/disable, start/stop system level processes

  > `systemd` can track individual service daemons after they start, and group
  > together multiple processes associated with a service, giving you more power
  > and insight into exactly what is running on the system _How Linux Works: Third
  > Edition_, Brian Ward 2021

  ## How systemd works

  ### Goal-directed units

  `systemd` works on the basis of _goals_. Each goal is system task defined as a
  **unit**. A unit contains instructions and a specification of dependencies to
  other units.

  When activating a unit, `systemd` first activates the dependencies and then
  moves onto the details of the unit itself. `init` as implemented by `systemd`
  does not follow a rigid sequence every time, initialising units in the same
  sequence and waiting for one to complete before starting another. Instead it
  activates units whenever they are ready. This, its parallelized nature, is one
  of the main advantages over previous programs that managed the `init` sequence
  on Linux (such as for example System V);

  ### Unit types

  Units are organised into **unit types**. The main types that run at boot time
  are as follows:

  - service units (`.service`)
    - control service daemons
  - socket units (`.socket`)
    - handle incoming network connection request locations
  - device units (`.device`)
    - disks and other devices
  - mount units (`.mount`)
    - handle the attachment of filesystems to the system
  - target units
    - control other units by organising them into groups

  For example, at boot, a target unit called `default.target` groups together a
  number of service and mount units as dependencies. These then run in a
  graph-like dependency structure where a unit that comes late in the boot process
  can depend on several previous units making earlier branches of a dependency
  tree join back together.

  ## systemd configuration files

  Units are managed via `systemd` configuration files.

  ### Configuration file locations

  System level `systemd` config files are located in the _system unit directory_
  at `/usr/lib/systemd/system`. You shouldn't change or manipulate these files or
  attempt to add new config files here since they will be overwritten by the
  system.

  ![](/img/systemd-global-files.png) _`systemd` global unit files_

  Local definitions that relate to the specific user and where the user herself
  can define units are located in the _system configuration_ directory:
  `/etc/systemd/system`.

  ![](/img/systemd-local-files.png)

  _`systemd` local unit files, specific to the currently logged-in user_

  ### Example files

  Below is the systemd service file for the creation of UUIDs:

  ```plain
  [Unit]
  Description=Daemon for generating UUIDs
  Documentation=man:uuidd(8)
  Requires=uuidd.socket

  [Service]
  ExecStart=/usr/sbin/uuidd --socket-activation
  Restart=no
  User=uuidd
  Group=uuidd
  ProtectSystem=strict
  ProtectHome=yes
  PrivateDevices=yes
  PrivateUsers=yes
  ProtectKernelTunables=yes
  ProtectKernelModules=yes
  ProtectControlGroups=yes
  MemoryDenyWriteExecute=yes
  ReadWritePaths=/var/lib/libuuid/
  SystemCallFilter=@default @file-system @basic-io @system-service @signal @io-event @network-io

  [Install]
  Also=uuidd.socket
  ```

  - The `Unit` section provides metadata about the unit including which `systemd`
    dependencies it has
  - `Service` constitutes the main specification for the unit
  - `Install` is the call to set the dependencies running before the `Service`
    functions are accessible.

  ## systemd operations: systemctl

  The `systemctl` command is the chief way of interacting with `systemd`. You use
  it to activate and deactivate services, list their status, reload the
  configuration and so.

  ### View the dependency graph

  `systemctl status` by itself will print a long list of units grouped by their
  dependency relations. It will also provide some metadata about the current
  systemd boot context.

  ### Viewing active units

  Below I have listed the running units pertaining to bluetooth:

  ```
  $ systemctl list-units | grep bluetooth
   sys-devices-pci0000:00-0000:00:14.0-usb3-3\x2d10-3\x2d10:1.0-bluetooth-hci0-hci0:3585.device                                   loaded active plugged   /sys/devices/pci0000:00/0000:00:14.0/usb3/3-10/3-10:1.0/bluetooth/hci0/hci0:3585
    sys-devices-pci0000:00-0000:00:14.0-usb3-3\x2d10-3\x2d10:1.0-bluetooth-hci0.device                                             loaded active plugged   /sys/devices/pci0000:00/0000:00:14.0/usb3/3-10/3-10:1.0/bluetooth/hci0
    sys-subsystem-bluetooth-devices-hci0.device                                                                                    loaded active plugged   /sys/subsystem/bluetooth/devices/hci0
    sys-subsystem-bluetooth-devices-hci0:3585.device                                                                               loaded active plugged   /sys/subsystem/bluetooth/devices/hci0:3585
    bluetooth.service                                                                                                              loaded active running   Bluetooth service
    bluetooth.target                                                                                                               loaded active active    Bluetooth Support
  ```

  ### List jobs

  Requests to activate, reactivate and restart units are called **jobs** in
  `systemd`. They can be thought of as unit state changes. Current jobs can be
  listed with `systemctl list-jobs`.

  This will most likely return `No jobs running` if the computer has been running
  for a while. Most jobs execute at boot.

  ### Enable/disable, start/stop units

  If a unit has dependencies it is necessary to _enable_ it before starting it.
  This installs the dependencies.

  ```bash
  systemctl enable mongodb.service
  Created symlink /etc/systemd/system/multi-user.target.wants/mongodb.service → /usr/lib/systemd/system/mongodb.service.
  ```

  Then we can start:

  ```
  systemctl start mongodb.service
  ```

  To stop the service:

  ```
  systemctl stop mongodb.service
  ```

  After this we should disable it, in order to remove any symbolic links it has
  created on the system as part of the install process:

  ```bash
  systemctl disable mongodb.service
  Removed "/etc/systemd/system/multi-user.target.wants/mongodb.service".
  ```

  ## Why use systemd over cron ?

  https://mark.stosberg.com/2016-08-26-rsnapshot-and-systemd/


path: zk/systemd_status.md
sortable_path: zksystemd_status.md
title: systemd status
lead: # Get status of a specific unit
checksum: 36876a8cce43462558f0dcacb191935c94642292966e6698df24a8e8333a5a0a
created: 2024-03-30 09:03:22.167794749+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
body:
  # Get status of a specific unit

  Here I have requested the status of the currently running `mongodb` unit:

  ```
  $ systemctl status mongod
  mongodb.service - MongoDB Database Server
       Loaded: loaded (/usr/lib/systemd/system/mongodb.service; enabled; preset: disabled)
       Active: active (running) since Wed 2022-08-17 07:25:27 BST; 24h ago
         Docs: https://docs.mongodb.org/manual
     Main PID: 931 (mongod)
       Memory: 304.1M
          CPU: 2min 18.630s
       CGroup: /system.slice/mongodb.service
               └─931 /usr/bin/mongod --config /etc/mongodb.conf
  Aug 17 07:25:27 archbish systemd[1]: Started MongoDB Database Server.****
  ```

  In addition to the core info it tells us the unit type. In this case it is a
  service.

  We can also view the journal entry for the given unit. This provides you with
  its diagnostic log messages:

  ```
  journalctl --unit=mongodb.service
  - Boot b9565dfe8aca4d069143209b3aa84d8e --
  Aug 05 18:31:30 archbish systemd[1]: Started MongoDB Database Server.
  Aug 06 14:27:33 archbish systemd[1]: mongodb.service: Deactivated successfully.
  Aug 06 14:27:33 archbish systemd[1]: mongodb.service: Consumed 3min 17.598s CPU time.
  -- Boot 01922f84c3bd4b3a8f11824cf05f7320 --
  Aug 07 11:58:09 archbish systemd[1]: Started MongoDB Database Server.
  Aug 08 14:43:01 archbish systemd[1]: mongodb.service: Deactivated successfully.
  Aug 08 14:43:01 archbish systemd[1]: mongodb.service: Consumed 5min 28.760s CPU time.
  -- Boot e52b735e115c43bdad8c00462aaff395 --
  Aug 10 13:13:22 archbish systemd[1]: Started MongoDB Database Server.
  Aug 11 07:46:40 archbish systemd[1]: mongodb.service: Deactivated successfully.
  Aug 11 07:46:40 archbish systemd[1]: mongodb.service: Consumed 2min 16.629s CPU time.
  ```

  Each entry is organised around specific boots.

raw_content:
  ---
  id: v5f6xkdv
  title: systemd status
  tags: [systemd, systems-programming]
  created: Thursday, February 29, 2024 | 18:19
  ---

  # Get status of a specific unit

  Here I have requested the status of the currently running `mongodb` unit:

  ```
  $ systemctl status mongod
  mongodb.service - MongoDB Database Server
       Loaded: loaded (/usr/lib/systemd/system/mongodb.service; enabled; preset: disabled)
       Active: active (running) since Wed 2022-08-17 07:25:27 BST; 24h ago
         Docs: https://docs.mongodb.org/manual
     Main PID: 931 (mongod)
       Memory: 304.1M
          CPU: 2min 18.630s
       CGroup: /system.slice/mongodb.service
               └─931 /usr/bin/mongod --config /etc/mongodb.conf
  Aug 17 07:25:27 archbish systemd[1]: Started MongoDB Database Server.****
  ```

  In addition to the core info it tells us the unit type. In this case it is a
  service.

  We can also view the journal entry for the given unit. This provides you with
  its diagnostic log messages:

  ```
  journalctl --unit=mongodb.service
  - Boot b9565dfe8aca4d069143209b3aa84d8e --
  Aug 05 18:31:30 archbish systemd[1]: Started MongoDB Database Server.
  Aug 06 14:27:33 archbish systemd[1]: mongodb.service: Deactivated successfully.
  Aug 06 14:27:33 archbish systemd[1]: mongodb.service: Consumed 3min 17.598s CPU time.
  -- Boot 01922f84c3bd4b3a8f11824cf05f7320 --
  Aug 07 11:58:09 archbish systemd[1]: Started MongoDB Database Server.
  Aug 08 14:43:01 archbish systemd[1]: mongodb.service: Deactivated successfully.
  Aug 08 14:43:01 archbish systemd[1]: mongodb.service: Consumed 5min 28.760s CPU time.
  -- Boot e52b735e115c43bdad8c00462aaff395 --
  Aug 10 13:13:22 archbish systemd[1]: Started MongoDB Database Server.
  Aug 11 07:46:40 archbish systemd[1]: mongodb.service: Deactivated successfully.
  Aug 11 07:46:40 archbish systemd[1]: mongodb.service: Consumed 2min 16.629s CPU time.
  ```

  Each entry is organised around specific boots.

metadata:
  {"created":"Thursday, February 29, 2024 | 18:19","id":"v5f6xkdv","tags":["systemd","systems-programming"],"title":"systemd status"}


path: zk/useContext.md
sortable_path: zkuseContext.md
title: useContext
checksum: dbff364b1afc6a48c0d4620fd8f44b7c439ada010022ada16f887eb2bd961809
created: 2024-03-30 09:03:22.174350283+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["javascript","react","react-hooks"]}
lead:
  We use React's Context API to enable us to easily share stateful data between
  all levels of an application without having to use repetitious 'prop-drilling'
  at a component level.

body:
  We use React's Context API to enable us to easily share stateful data between
  all levels of an application without having to use repetitious 'prop-drilling'
  at a component level.

  This works best with data that is global by definition, such as theme parameters
  or access authorisation. Context should not be used when standard and proximate
  compositional methods and prop-passing are sufficient.

  ## Providers and consumers

  The Context API preceded the introduction of hooks in React 16.8 and it still
  underpins context management in hooks, although the syntax is simplified.

  The process is as follows:

  - Initiate a context
  - Create a parent `Provider` component that owns the data that will be passed
    down
  - Create child `Consumer` components that receive the data of the parent.

  We will demonstrate using a set of styles as the context that we want to pass
  around our app.

  ```jsx
  const style = {
    border: "2px solid dodgerblue",
    background: "lightblue",
    color: "dodgerblue",
  };
  ```

  Le's initiate a context:

  ```jsx
  const StyleContext = React.createContext();
  ```

  Now that we have our data and have initialized a context, we can apply it to our
  app components:

  ```jsx
  <StyleContext.Provider value={style}>...</StyleContext.Provider>
  ```

  This is the parent element of the context environment. This stores the
  contextual data as a prop. Next we need to make a component that acts as the
  consumer of this data. Let's create this component and call it `Child` for
  simplicity:

  ```jsx
  const Child = () => {
    return (
      <StyleContext.Consumer>
        {(value) => (
          <div style={value}>
            <p>
              I'm a <b>child</b>. I <b>consume</b> of the data my parent provides.
            </p>
          </div>
        )}
      </StyleContext.Consumer>
    );
  };
  ```

  The contents of this component are wrapped in tags that reference the specific
  context (`StyleContext`) and the role that the component plays: `Consumer`.

  We are taking the `value` prop owned by `StyleContext.Provider` and passing it
  to the wrapping component of `Child` as a `style` tag. This means that `Child`
  will display these styles.

  The final step is just to insert our `<Child />` components beneath the parent
  component, e.g.:

  ```jsx
  <StyleContext.Provider value={style}>
    <Child />
    <Child />
  </StyleContext.Provider>
  ```

  ## `useContext` hook

  The hook removes the need to explicitly declare `Provider` and `Consumer`
  components; their role becomes more implicit.

  To demonstrate let's use a different example. We are going to have a single
  integer as the data context, `42`.

  First invoke and intialize the Context API, just as before:

  ```jsx
  const NumberContext = React.createContext(42);
  ```

  Next, we just need to create our provider component. We don't have to worry
  about a consumer since this is handled implicitly by the invocation of the hook

  ```jsx
  const Context = () => {
    const data = useContext(NumberContext);
    return <Typography>{data}</Typography>;
  };
  ```

  Then, in our code we just insert the `Context` component:

  ```jsx
  <Context>...</Context>
  ```

  ## Updating context state

  In the examples above we have only been consuming state that is owned by the
  provider however in most scenarios you will also want to update the state from a
  consumer. This is best achieved by combining `useContext` with a reducer and is
  detailed in [Application state management](Application_state_management.md).

raw_content:
  ---
  tags:
    - javascript
    - react
    - react-hooks
  ---

  # `useContext`

  We use React's Context API to enable us to easily share stateful data between
  all levels of an application without having to use repetitious 'prop-drilling'
  at a component level.

  This works best with data that is global by definition, such as theme parameters
  or access authorisation. Context should not be used when standard and proximate
  compositional methods and prop-passing are sufficient.

  ## Providers and consumers

  The Context API preceded the introduction of hooks in React 16.8 and it still
  underpins context management in hooks, although the syntax is simplified.

  The process is as follows:

  - Initiate a context
  - Create a parent `Provider` component that owns the data that will be passed
    down
  - Create child `Consumer` components that receive the data of the parent.

  We will demonstrate using a set of styles as the context that we want to pass
  around our app.

  ```jsx
  const style = {
    border: "2px solid dodgerblue",
    background: "lightblue",
    color: "dodgerblue",
  };
  ```

  Le's initiate a context:

  ```jsx
  const StyleContext = React.createContext();
  ```

  Now that we have our data and have initialized a context, we can apply it to our
  app components:

  ```jsx
  <StyleContext.Provider value={style}>...</StyleContext.Provider>
  ```

  This is the parent element of the context environment. This stores the
  contextual data as a prop. Next we need to make a component that acts as the
  consumer of this data. Let's create this component and call it `Child` for
  simplicity:

  ```jsx
  const Child = () => {
    return (
      <StyleContext.Consumer>
        {(value) => (
          <div style={value}>
            <p>
              I'm a <b>child</b>. I <b>consume</b> of the data my parent provides.
            </p>
          </div>
        )}
      </StyleContext.Consumer>
    );
  };
  ```

  The contents of this component are wrapped in tags that reference the specific
  context (`StyleContext`) and the role that the component plays: `Consumer`.

  We are taking the `value` prop owned by `StyleContext.Provider` and passing it
  to the wrapping component of `Child` as a `style` tag. This means that `Child`
  will display these styles.

  The final step is just to insert our `<Child />` components beneath the parent
  component, e.g.:

  ```jsx
  <StyleContext.Provider value={style}>
    <Child />
    <Child />
  </StyleContext.Provider>
  ```

  ## `useContext` hook

  The hook removes the need to explicitly declare `Provider` and `Consumer`
  components; their role becomes more implicit.

  To demonstrate let's use a different example. We are going to have a single
  integer as the data context, `42`.

  First invoke and intialize the Context API, just as before:

  ```jsx
  const NumberContext = React.createContext(42);
  ```

  Next, we just need to create our provider component. We don't have to worry
  about a consumer since this is handled implicitly by the invocation of the hook

  ```jsx
  const Context = () => {
    const data = useContext(NumberContext);
    return <Typography>{data}</Typography>;
  };
  ```

  Then, in our code we just insert the `Context` component:

  ```jsx
  <Context>...</Context>
  ```

  ## Updating context state

  In the examples above we have only been consuming state that is owned by the
  provider however in most scenarios you will also want to update the state from a
  consumer. This is best achieved by combining `useContext` with a reducer and is
  detailed in [Application state management](Application_state_management.md).


path: zk/useEffect.md
sortable_path: zkuseEffect.md
title: useEffect
checksum: f2c66f5b1eafc4a540dd94abd0f5af2b69c971006c531fc69937af095af9bde4
created: 2024-03-30 09:03:22.187591834+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["javascript","react","react-hooks"]}
lead:
  `useEffect` should be used for any background process that does not arise as a
  result of a user interaction or standard state change. The canonical example
  would be dispatching a request to an API to retrieve data to display in a
  component's initial render.

body:
  `useEffect` should be used for any background process that does not arise as a
  result of a user interaction or standard state change. The canonical example
  would be dispatching a request to an API to retrieve data to display in a
  component's initial render.

  `useEffect` enshrines but also simplifies the
  [lifecyle methods](Lifecycle_methods.md) that are used with
  class-based React components.

  ## Demonstration

  ```jsx
  const [workflowTitle, setWorkflowTitle] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchWorkflowTitle = () => {
      axios
        .post(`${process.env.REACT_APP_ENDPOINT}/load-workflows`, {
          workflow_id: project_id,
          user_id: isAuth?.userId,
        })
        .then((res) => {
          setWorkflowTitle(res?.data?.meta.name);
        })
        .finally(() => setLoading(false))
        .catch((err) => {
          console.error(err);
        });
    };
    setLoading(true);
    fetchWorkflowTitle();
  }, [project_id, isAuth]);
  ```

  In this example we fetch some data from a REST API and store the response value
  as state, which can then be accessed within our JSX template.

  ## Function placement

  In the example, the function is declared inside of the `useEffect` hook and then
  called. We do this to avoid adding the function to the dependency array, which
  we couldn't do if we defined it outside of the hook, somewhere in the component.
  If we did this, the function would run on every render by default and would be
  recalled again because of its placement in the dependency array, which leads to
  the 'too many rerenders' error.

  An alternative would be to define it outside of the component itself but this is
  difficult since it requires state from the component to run.

  ## Dependency array

  Note the array that is the second argument to `useEffect`. This is the
  **dependency array** and is how we manage the lifecycle of the side-effect.

  - After the initial call on render, the function within the `useEffect` block
    will run any time one of the dependencies update. The dependency array
    typically refers to variables that are defined within the hook but can also
    contain references to variables outside of it.

  - If you do not include the array, the effect runs on every render

  - If you pass an empty array, the effect will only run once on the initial
    render

  ## Cleanup functions

  The syntax of the `useEffect` hook also allows you to handle cleanup: something
  you want to do when the component unmounts (another example of how this hook
  recasts the traditional [lifecycle methods](Lifecycle_methods.md))
  . In addition to running on unmount, the cleanup function will run before the
  effect runs again (i.e. when it runs in response to a change in one of the
  elements of the dependency araray). This is chiefly used to prevent
  [memory leaks](Memory_leaks.md) and the
  ['update on unmounted component error'](Errors.md#state-update-on-unmounted-component).

  You do this by having a `return` clause after the main effect. Schematically:

  ```js
  useEffect(() => {
    //  Run your effect;
    return () => {
      //   Put your cleanup function here
    };
  }, [input]);
  ```

  Here is an example of using a cleanup to cancel a subscription

  ```js
  useEffect(() => {
    let isApiSubscribed = true;
    axios.get(API).then((response) => {
      if (isApiSubscribed) {
        // handle success
      }
    });
    return () => {
      isApiSubscribed = false;
    };
  }, []);
  ```

  ## Resources

  [Understanding the React useEffect cleanup function]()

raw_content:
  ---
  tags:
    - javascript
    - react
    - react-hooks
  ---

  # `useEffect`

  `useEffect` should be used for any background process that does not arise as a
  result of a user interaction or standard state change. The canonical example
  would be dispatching a request to an API to retrieve data to display in a
  component's initial render.

  `useEffect` enshrines but also simplifies the
  [lifecyle methods](Lifecycle_methods.md) that are used with
  class-based React components.

  ## Demonstration

  ```jsx
  const [workflowTitle, setWorkflowTitle] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchWorkflowTitle = () => {
      axios
        .post(`${process.env.REACT_APP_ENDPOINT}/load-workflows`, {
          workflow_id: project_id,
          user_id: isAuth?.userId,
        })
        .then((res) => {
          setWorkflowTitle(res?.data?.meta.name);
        })
        .finally(() => setLoading(false))
        .catch((err) => {
          console.error(err);
        });
    };
    setLoading(true);
    fetchWorkflowTitle();
  }, [project_id, isAuth]);
  ```

  In this example we fetch some data from a REST API and store the response value
  as state, which can then be accessed within our JSX template.

  ## Function placement

  In the example, the function is declared inside of the `useEffect` hook and then
  called. We do this to avoid adding the function to the dependency array, which
  we couldn't do if we defined it outside of the hook, somewhere in the component.
  If we did this, the function would run on every render by default and would be
  recalled again because of its placement in the dependency array, which leads to
  the 'too many rerenders' error.

  An alternative would be to define it outside of the component itself but this is
  difficult since it requires state from the component to run.

  ## Dependency array

  Note the array that is the second argument to `useEffect`. This is the
  **dependency array** and is how we manage the lifecycle of the side-effect.

  - After the initial call on render, the function within the `useEffect` block
    will run any time one of the dependencies update. The dependency array
    typically refers to variables that are defined within the hook but can also
    contain references to variables outside of it.

  - If you do not include the array, the effect runs on every render

  - If you pass an empty array, the effect will only run once on the initial
    render

  ## Cleanup functions

  The syntax of the `useEffect` hook also allows you to handle cleanup: something
  you want to do when the component unmounts (another example of how this hook
  recasts the traditional [lifecycle methods](Lifecycle_methods.md))
  . In addition to running on unmount, the cleanup function will run before the
  effect runs again (i.e. when it runs in response to a change in one of the
  elements of the dependency araray). This is chiefly used to prevent
  [memory leaks](Memory_leaks.md) and the
  ['update on unmounted component error'](Errors.md#state-update-on-unmounted-component).

  You do this by having a `return` clause after the main effect. Schematically:

  ```js
  useEffect(() => {
    //  Run your effect;
    return () => {
      //   Put your cleanup function here
    };
  }, [input]);
  ```

  Here is an example of using a cleanup to cancel a subscription

  ```js
  useEffect(() => {
    let isApiSubscribed = true;
    axios.get(API).then((response) => {
      if (isApiSubscribed) {
        // handle success
      }
    });
    return () => {
      isApiSubscribed = false;
    };
  }, []);
  ```

  ## Resources

  [Understanding the React useEffect cleanup function]()


path: zk/useReducer.md
sortable_path: zkuseReducer.md
title: useReducer
checksum: c8c367ff25d1c3e7678ab683ce6824aa5c157741f93d7bb1939d8f49bfe56645
created: 2024-03-30 09:03:22.212260557+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["javascript","react","react-hooks"]}
lead:
  The `useReducer` hook is best used in scenarios where you are manipulating state
  in a way that is too complex for the trivial [useState](useState.md) use case.
  `useState` is best employed when you are updating a single value or toggling a
  boolean. If you are updating the state of an object or more complex data
  structure, it is often more efficient to employ `useReducer`.

body:
  The `useReducer` hook is best used in scenarios where you are manipulating state
  in a way that is too complex for the trivial [useState](useState.md) use case.
  `useState` is best employed when you are updating a single value or toggling a
  boolean. If you are updating the state of an object or more complex data
  structure, it is often more efficient to employ `useReducer`.

  This makes the code more manageable and also helps with separating state
  management from rendering.

  ## Syntax

  ```jsx
  const [state, dispatch] = useReducer(reducer, initialState);
  ```

  - `initialState`
    - The starting state, typically an object
  - `reducer`
    - A pure function that accepts two parameters:
      - The current state
      - An action object
    - The reducer function must update the current state (immutably) and return
      the new state
    - We can think of the reducer as working in the same manner as
      `state`/`setState` in the `useState` hook. The functional role is the same,
      it is just that the reducer offers more than one type of update.

  ### Example reducer

  ```js
  function reducer(state, action) {
    let newState;
    switch (action.type) {
      case "increase":
        newState = { counter: state.counter + 1 };
        break;
      case "descrease":
        newState = { counter: state.counter - 1 };
        break;
      default:
        throw new Error();
    }
    return newState;
  }
  ```

  In this example we are updating an object with the following shape:

  ```js
  {
      counter: 0,
  }
  ```

  This would be the `initialState` that we pass to the `useReducer` hook along
  with a reference to `reducer` above.

  To update the state we would invoke the `dispatch` function which applies one of
  the actions defined in the reducer. For example the following dispatch
  increments the counter by one:

  ```js
  dispatch({ type: "increase" });
  ```

  To view the updated value:

  ```js
  console.log(state.counter);
  ```

  ### Refining the syntax

  Because React doesn't mutate state, the reducer doesn't directly modify the
  current state in the `state` variable, it creates a new instance of the state
  object on each update.

  In the reducer example above this is achieved by declaring a variable `newState`
  that is updated by each `action` type and then returned. There is a more elegant
  way of doing this using spread syntax:

  ```js
  function reducer(state, action) {
    switch (action.type) {
      case "increase":
        return { ...state, counter: state.counter + 1 };
        break;
      case "decrease":
        return { ...state, counter: state.counter - 1 };
        break;
      default:
        throw new Error();
    }
  }
  ```

  ### Including payloads

  In the examples so far, we have updated the the state directly via the action
  type however it is also possible to pass data along with the `action.type` as
  `action.payload`.

  For example:

  ```js
  dispatch(
    {
      type: 'increase_by_payload'
      payload: 3,
    });
  ```

  Then we would update our reducer to handle this case:

  ```js
  function reducer(state, action) {
    switch (action.type) {
      ...
      case 'increase_by_payload':
      return {...state, counter: state.counter + action.payload}
      default:
        throw new Error();
    }
  }
  ```

raw_content:
  ---
  tags:
    - javascript
    - react
    - react-hooks
  ---

  # `useReducer`

  The `useReducer` hook is best used in scenarios where you are manipulating state
  in a way that is too complex for the trivial [useState](useState.md) use case.
  `useState` is best employed when you are updating a single value or toggling a
  boolean. If you are updating the state of an object or more complex data
  structure, it is often more efficient to employ `useReducer`.

  This makes the code more manageable and also helps with separating state
  management from rendering.

  ## Syntax

  ```jsx
  const [state, dispatch] = useReducer(reducer, initialState);
  ```

  - `initialState`
    - The starting state, typically an object
  - `reducer`
    - A pure function that accepts two parameters:
      - The current state
      - An action object
    - The reducer function must update the current state (immutably) and return
      the new state
    - We can think of the reducer as working in the same manner as
      `state`/`setState` in the `useState` hook. The functional role is the same,
      it is just that the reducer offers more than one type of update.

  ### Example reducer

  ```js
  function reducer(state, action) {
    let newState;
    switch (action.type) {
      case "increase":
        newState = { counter: state.counter + 1 };
        break;
      case "descrease":
        newState = { counter: state.counter - 1 };
        break;
      default:
        throw new Error();
    }
    return newState;
  }
  ```

  In this example we are updating an object with the following shape:

  ```js
  {
      counter: 0,
  }
  ```

  This would be the `initialState` that we pass to the `useReducer` hook along
  with a reference to `reducer` above.

  To update the state we would invoke the `dispatch` function which applies one of
  the actions defined in the reducer. For example the following dispatch
  increments the counter by one:

  ```js
  dispatch({ type: "increase" });
  ```

  To view the updated value:

  ```js
  console.log(state.counter);
  ```

  ### Refining the syntax

  Because React doesn't mutate state, the reducer doesn't directly modify the
  current state in the `state` variable, it creates a new instance of the state
  object on each update.

  In the reducer example above this is achieved by declaring a variable `newState`
  that is updated by each `action` type and then returned. There is a more elegant
  way of doing this using spread syntax:

  ```js
  function reducer(state, action) {
    switch (action.type) {
      case "increase":
        return { ...state, counter: state.counter + 1 };
        break;
      case "decrease":
        return { ...state, counter: state.counter - 1 };
        break;
      default:
        throw new Error();
    }
  }
  ```

  ### Including payloads

  In the examples so far, we have updated the the state directly via the action
  type however it is also possible to pass data along with the `action.type` as
  `action.payload`.

  For example:

  ```js
  dispatch(
    {
      type: 'increase_by_payload'
      payload: 3,
    });
  ```

  Then we would update our reducer to handle this case:

  ```js
  function reducer(state, action) {
    switch (action.type) {
      ...
      case 'increase_by_payload':
      return {...state, counter: state.counter + action.payload}
      default:
        throw new Error();
    }
  }
  ```


path: zk/useState.md
sortable_path: zkuseState.md
title: useState
checksum: 26033ab0ed21431aaa1856cd578a399e9a63fd9223091bcfabe66079c0b7043d
created: 2024-03-30 09:03:22.227584471+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["javascript","react","react-hooks"]}
lead:
  `useState` is the primary way in which React updates the application state based
  on user interaction.

body:
  `useState` is the primary way in which React updates the application state based
  on user interaction.

  - `useState` **receives**: the initial state as an argument
  - `useState` **returns**: the current state and a function that updates it

  The two items that are returned are returned as an array. We could refer to them
  with array syntax (i.e with `[0]` and `[1]` ) but it is more concise to use the
  destructuring syntax. But all that's happening is that a method belonging to the
  `React` library (i.e. `useState` ) is taking an argument (the initial state) and
  returning two values as an array of two elements. The first of these values is a
  variable, the second is a function.

  ```jsx
  (1) const [count, setCount] = useState(0);
  (2) const handleClick = () => { setCount(count + 1) };

  (3) <span>{count}</span>
  (4) <button onClick={handleClick)>Add one</button>
  ```

  - At line 1 we initialise the `useState` hook.
    - We use destructuring syntax to declare two variables
    - The first variable stores our initial state. The value of the initial state
      is an argument passed to `useState` , i.e. `0`. Do not confuse the variable
      with the value it refers to.
    - The second variable is a method that mutates the state referred to by the
      first variable into some new value, i.e. from `0` to a different integer
  - At line 3, which in reality, will be within your JSX and part of the
    `render()` block of the function, we render the initial state in the React
    DOM. This will change and be re-rendered in accordance with the state logic
  - At line 4 we have a user interface that executes the function on line 2. This
    function applies the state change represented by the second variable in the
    destructuring assignment at line 1 (`setCount` ): it mutates the initial state
    (`0`) by the value of `1'.

  > You can utilise as many `useState` declarations as your component requires.

  ## Passing variables as initial state

  We don't always have to declare the data types within the destructuring
  assignment. We can store them in variables and pass the variables to the
  destructuring assignment on `useState` . Below we do this for a function that
  mutates a string value:

  ```jsx
  const hi = "hello";
  const bye = "goodbye";

  const [initText, changeText] = useState(hi);

  <p>{initText}</p>
  <button onClick={()=>changeText(bye)}>ChangeText</button>
  ```

  ## Lazily setting initial state

  Although you will typically use a literal value or variable as your initial
  state, React provides a way for you to set this value through a function. This
  will only run once at the first render so as not to interfere with the second
  update parameter of `useState`. This is called **lazy initialisation**

  ```jsx
  const getInitialState = () => Number(window.localStorage.getItem("count"));
  const [count, setCount] = React.useState(getInitialState);
  ```

  ## Accessing previous state

  It is also possible to access the previous state via the `useState` hook. We can
  access this as a callback on the updater function.

  Let's say we have a simple counter set up like so:

  ```js
  const [count, setCount] = useState(0);
  ```

  We can access the prior value of `count` with:

  ```js
  const getPrevValue = () => setCount((prev) => console.log(prev));
  ```

  ### Naming best practise

  When destructuring the two variables from `useState`, React follows uses the
  following semantics: `[something, setSomething]` . This isn't required but it
  helps to keep everything clear, particularly the fact that the first thing
  destructured is a variable and the second is a function.

  > https://stackoverflow.com/questions/54807454/what-is-prevstate-in-reactjs

raw_content:
  ---
  tags:
    - javascript
    - react
    - react-hooks
  ---

  # `useState`

  `useState` is the primary way in which React updates the application state based
  on user interaction.

  - `useState` **receives**: the initial state as an argument
  - `useState` **returns**: the current state and a function that updates it

  The two items that are returned are returned as an array. We could refer to them
  with array syntax (i.e with `[0]` and `[1]` ) but it is more concise to use the
  destructuring syntax. But all that's happening is that a method belonging to the
  `React` library (i.e. `useState` ) is taking an argument (the initial state) and
  returning two values as an array of two elements. The first of these values is a
  variable, the second is a function.

  ```jsx
  (1) const [count, setCount] = useState(0);
  (2) const handleClick = () => { setCount(count + 1) };

  (3) <span>{count}</span>
  (4) <button onClick={handleClick)>Add one</button>
  ```

  - At line 1 we initialise the `useState` hook.
    - We use destructuring syntax to declare two variables
    - The first variable stores our initial state. The value of the initial state
      is an argument passed to `useState` , i.e. `0`. Do not confuse the variable
      with the value it refers to.
    - The second variable is a method that mutates the state referred to by the
      first variable into some new value, i.e. from `0` to a different integer
  - At line 3, which in reality, will be within your JSX and part of the
    `render()` block of the function, we render the initial state in the React
    DOM. This will change and be re-rendered in accordance with the state logic
  - At line 4 we have a user interface that executes the function on line 2. This
    function applies the state change represented by the second variable in the
    destructuring assignment at line 1 (`setCount` ): it mutates the initial state
    (`0`) by the value of `1'.

  > You can utilise as many `useState` declarations as your component requires.

  ## Passing variables as initial state

  We don't always have to declare the data types within the destructuring
  assignment. We can store them in variables and pass the variables to the
  destructuring assignment on `useState` . Below we do this for a function that
  mutates a string value:

  ```jsx
  const hi = "hello";
  const bye = "goodbye";

  const [initText, changeText] = useState(hi);

  <p>{initText}</p>
  <button onClick={()=>changeText(bye)}>ChangeText</button>
  ```

  ## Lazily setting initial state

  Although you will typically use a literal value or variable as your initial
  state, React provides a way for you to set this value through a function. This
  will only run once at the first render so as not to interfere with the second
  update parameter of `useState`. This is called **lazy initialisation**

  ```jsx
  const getInitialState = () => Number(window.localStorage.getItem("count"));
  const [count, setCount] = React.useState(getInitialState);
  ```

  ## Accessing previous state

  It is also possible to access the previous state via the `useState` hook. We can
  access this as a callback on the updater function.

  Let's say we have a simple counter set up like so:

  ```js
  const [count, setCount] = useState(0);
  ```

  We can access the prior value of `count` with:

  ```js
  const getPrevValue = () => setCount((prev) => console.log(prev));
  ```

  ### Naming best practise

  When destructuring the two variables from `useState`, React follows uses the
  following semantics: `[something, setSomething]` . This isn't required but it
  helps to keep everything clear, particularly the fact that the first thing
  destructured is a variable and the second is a function.

  > https://stackoverflow.com/questions/54807454/what-is-prevstate-in-reactjs


path: zk/v8.md
sortable_path: zkv8.md
title: v8
checksum: cc6af4f81a66f006cf1555c541288b644bc81561240c3a0c340309f2df094685
created: 2024-03-30 09:03:22.234796202+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
metadata: {"tags":["backend","node-js"]}
lead:
  The v8 module is useful for providing information about the resource-usage of
  your Node.js apps, such as memory usage and capacity.

body:
  The v8 module is useful for providing information about the resource-usage of
  your Node.js apps, such as memory usage and capacity.

raw_content:
  ---
  tags:
    - backend
    - node-js
  ---

  # v8

  The v8 module is useful for providing information about the resource-usage of
  your Node.js apps, such as memory usage and capacity.


path: zk/variables_in_c.md
sortable_path: zkvariables_in_c.md
title: Variables in C
lead: # Variables in C
body:
  # Variables in C

  ```c
  int age = 25
  ```

checksum: b702bec2aebc256d92e83e60ef9beefdd46605d1a435691d4936b840e6ba160c
created: 2024-03-30 09:03:22.242584575+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
raw_content:
  ---
  id: r4i16p1x
  title: Variables in C
  tags: [C]
  created: Thursday, February 29, 2024 | 17:20
  ---

  # Variables in C

  ```c
  int age = 25
  ```

metadata:
  {"created":"Thursday, February 29, 2024 | 17:20","id":"r4i16p1x","tags":["C"],"title":"Variables in C"}


path: zk/virtual_private_cloud.md
sortable_path: zkvirtual_private_cloud.md
title: Virtual Private Cloud
lead: # Virtual Private Cloud
checksum: 15665690b24aff7e50083932162a8fb8e22aa4065f512ff3495b497587d4bca4
created: 2024-03-30 09:03:22.249101381+00:00
modified: 2024-03-27 10:45:52.510192133+00:00
body:
  # Virtual Private Cloud

  AWS VPC is used to create a virtual network. This is typically used in concert
  with [[zk/Elastic_Compute_Cloud]] to manage connections to a virtual server both
  privately and accross the internet.

  You define a network address range and then create subnets for managing
  different connections and functionality. You use a public subnet for resources
  that must be connected to the internet and a private subnet for resources that
  are to remain isolated from the internet.

  The diagram below details a basic VPC configuration:

  ![](../img/aws-vpc-example.png)

  - Within a given AWS region we have created a VPC network.
  - This comprises public and private subnets
  - Both subnets host an EC2 instance
  - The public subnet has a bridge to the internet through the Internet Gateway
  - Both subnets have a routing table to manage requests and access

raw_content:
  ---
  id: mdw5fe5a
  title: Virtual Private Cloud
  tags: [AWS, networks]
  created: Tuesday, February 20, 2024 | 08:31
  ---

  # Virtual Private Cloud

  AWS VPC is used to create a virtual network. This is typically used in concert
  with [[zk/Elastic_Compute_Cloud]] to manage connections to a virtual server both
  privately and accross the internet.

  You define a network address range and then create subnets for managing
  different connections and functionality. You use a public subnet for resources
  that must be connected to the internet and a private subnet for resources that
  are to remain isolated from the internet.

  The diagram below details a basic VPC configuration:

  ![](../img/aws-vpc-example.png)

  - Within a given AWS region we have created a VPC network.
  - This comprises public and private subnets
  - Both subnets host an EC2 instance
  - The public subnet has a bridge to the internet through the Internet Gateway
  - Both subnets have a routing table to manage requests and access

metadata:
  {"created":"Tuesday, February 20, 2024 | 08:31","id":"mdw5fe5a","tags":["AWS","networks"],"title":"Virtual Private Cloud"}


path: zk/Docker_CLI.md
sortable_path: zkDocker_CLI.md
title: Docker_CLI
lead: # Docker_CLI
checksum: 9dcb8378b508918f966720c6502512007b96702384d1eaa2142e2ea25bef2b67
created: 2024-03-30 14:42:27.76745933+00:00
modified: 2024-03-30 14:48:27.438219095+00:00
metadata: {"created":"Saturday, March 30, 2024","id":"6g54","tags":[],"title":"Docker_CLI"}
body:
  # Docker_CLI

  ```sh
  # List images
  docker image ls

  # List container
  docker container ls

  # Remove container
  docker rm container-name

  # Remove image

  docker rmi image_name:version

  ```

raw_content:
  ---
  id: 6g54
  title: Docker_CLI
  tags: []
  created: Saturday, March 30, 2024
  ---

  # Docker_CLI

  ```sh
  # List images
  docker image ls

  # List container
  docker container ls

  # Remove container
  docker rm container-name

  # Remove image

  docker rmi image_name:version

  ```


path: zk/Docker_rough_notes.md
sortable_path: zkDocker_rough_notes.md
title: Docker_rough_notes
lead: # Docker_rough_notes
checksum: 3cde0e4a73246c0fb166f2834ef9acba33fcc78174936732ac7a7f945d9a1401
created: 2024-03-30 16:02:26.425203384+00:00
modified: 2024-03-30 16:05:52.963529719+00:00
metadata: {"created":"Saturday, March 30, 2024","id":"dmuz","tags":[],"title":"Docker_rough_notes"}
body:
  # Docker_rough_notes

  ## Creating and running a simple image (without Docker compose)

  Create the Dockerfile in the root of the project.

  Then build the image from root.

  ```
  docker build -t image-name .
  ```

  The image name is defined at this point, not pre-defined.

  If successful, run the image:

  ```
  docker run --name your-container-name image-name
  ```

  Again, the container-name is defined at the point of the `run` declaration.

raw_content:
  ---
  id: dmuz
  title: Docker_rough_notes
  tags: []
  created: Saturday, March 30, 2024
  ---

  # Docker_rough_notes

  ## Creating and running a simple image (without Docker compose)

  Create the Dockerfile in the root of the project.

  Then build the image from root.

  ```
  docker build -t image-name .
  ```

  The image name is defined at this point, not pre-defined.

  If successful, run the image:

  ```
  docker run --name your-container-name image-name
  ```

  Again, the container-name is defined at the point of the `run` declaration.


path: zk/Stack_memory.md
sortable_path: zkStack_memory.md
title: Stack_memory
lead: # Stack memory
checksum: 9ea1d4406f69d2cc83a433d862b3314b6ea9830bb94aa92c4cf800e465cac391
created: 2024-04-16 06:46:27.952023721+00:00
modified: 2024-04-20 12:40:16.05327467+00:00
metadata: {"created":"Tuesday, April 16, 2024","id":"1fig","tags":["memory"],"title":"Stack_memory"}
body:
  # Stack memory

  ## Summary

  - Along with [[Heap_memory|heap memory]] heap memory, programs make use of
    _stack memory_ during runtime.
  - [ ]
  - Best suited for small-sized singular values that are temporary/ephemeral
    rather than large or complex data types that need to persist for a longer
    time.

  - Specifically used to keep track of memory used during function executions
    within a given scope: control flow, local variables, returned value.

  - Uses a LIFO data-structure

  Similarly to the [[Stacks|stack data structure]], it works on the basis of LIFO:
  the last item put on the stack is the first item to be withdrawn.

  Note, this doesn't mean that the data at the memory addresses that comprise the
  stack can _only_ be accessed in a LIFO manner. Any item currently on the stack
  can be accessed (be read or modified) at any time. LIFO applies when it is is
  time to clear memory from the stack: the most recent addition is cleared first
  from the top down.

  ### Stack pointer

  A **stack pointer** is used to manage the items in the stack. This value is
  stored in a [[CPU_architecture#registers|register]] and its value is the memory
  address of the item currently on the top of the stack. Note: _not_ the value
  itself, the _address_ of the value.

  When a new value is added to the top of the stack, the pointer's value is
  adjusted to increase the size of the stack and make room for the new value. So
  this will be a new memory address for the latest item. When an item is removed,
  the reverse happens. The previously top address is cleared and the pointer
  points to the new top item.

  ## Threads

  For every thread that a program spawns, it gets its own stack or "stack frame".
  Stack memory within the thread can only be accessed by processes within that
  thread which is what makes it well suited for managing scoped function memory.

  ### Role in program execution

  1. Function call management: a stack records the key information pertaining to
     the execution of a function: parameters, local variables, the location of the
     address for the returned value.

  2. Local variable storage: storing the variables local to a function's scope and
     removing them once the function returns, avoiding
     [[Memory_leaks|memory leaks]]

  3. Control flow: record from where a function is called and where its return
     value should be stored, meaning the right value is always returned no matter
     how nested it is.

  4. Recursion: individuating each call of a function that calls itself and its
     given step to avoid infinite loops

  ## Related notes

raw_content:
  ---
  id: 1fig
  title: Stack_memory
  tags: [memory]
  created: Tuesday, April 16, 2024
  ---

  # Stack memory

  ## Summary

  - Along with [[Heap_memory|heap memory]] heap memory, programs make use of
    _stack memory_ during runtime.
  - [ ]
  - Best suited for small-sized singular values that are temporary/ephemeral
    rather than large or complex data types that need to persist for a longer
    time.

  - Specifically used to keep track of memory used during function executions
    within a given scope: control flow, local variables, returned value.

  - Uses a LIFO data-structure

  Similarly to the [[Stacks|stack data structure]], it works on the basis of LIFO:
  the last item put on the stack is the first item to be withdrawn.

  Note, this doesn't mean that the data at the memory addresses that comprise the
  stack can _only_ be accessed in a LIFO manner. Any item currently on the stack
  can be accessed (be read or modified) at any time. LIFO applies when it is is
  time to clear memory from the stack: the most recent addition is cleared first
  from the top down.

  ### Stack pointer

  A **stack pointer** is used to manage the items in the stack. This value is
  stored in a [[CPU_architecture#registers|register]] and its value is the memory
  address of the item currently on the top of the stack. Note: _not_ the value
  itself, the _address_ of the value.

  When a new value is added to the top of the stack, the pointer's value is
  adjusted to increase the size of the stack and make room for the new value. So
  this will be a new memory address for the latest item. When an item is removed,
  the reverse happens. The previously top address is cleared and the pointer
  points to the new top item.

  ## Threads

  For every thread that a program spawns, it gets its own stack or "stack frame".
  Stack memory within the thread can only be accessed by processes within that
  thread which is what makes it well suited for managing scoped function memory.

  ### Role in program execution

  1. Function call management: a stack records the key information pertaining to
     the execution of a function: parameters, local variables, the location of the
     address for the returned value.

  2. Local variable storage: storing the variables local to a function's scope and
     removing them once the function returns, avoiding
     [[Memory_leaks|memory leaks]]

  3. Control flow: record from where a function is called and where its return
     value should be stored, meaning the right value is always returned no matter
     how nested it is.

  4. Recursion: individuating each call of a function that calls itself and its
     given step to avoid infinite loops

  ## Related notes


path: zk/Heap_memory.md
sortable_path: zkHeap_memory.md
title: Heap_memory
lead: # Heap memory
checksum: e3c8291a7b7a967ad06d00498dc3ac2452b15cfac3719ddb91f8b867d740c0bb
created: 2024-04-20 12:14:59.272099511+00:00
modified: 2024-04-20 13:42:01.847818114+00:00
metadata: {"created":"Saturday, April 20, 2024","id":"18bl","tags":["memory","C"],"title":"Heap_memory"}
body:
  # Heap memory

  Along with [[Stack_memory|Stack memory]], programs make use of _heap memory_
  during runtime.

  Heap memory does not use a standardised data structure and can be accessed from
  any point within the program.

  Whereas stack memory with it's LIFO structure has memory management built-in
  when programs allocate memory from the heap they must manually deallocate it
  when it is no longer required. This process of "freeing memory" is known as
  _garbage collection_. In a language like C, this is the explicit concern of the
  programmer and is not abstracted away. Failure to properly manage garbage
  collection is what causes [[Memory_leaks]].

  Heap memory is used in combination with the stack since a given heap memory
  allocation address is stored as a stack variable during runtime. It points to
  the heap memory address whilst not being that memory itself.

  Here is an example of managing heap memory allocation in C:

  ```c
  void * data;
  data = malloc(512)
  ```

  The first line assigns a special _pointer_ variable (indicated by `void *`
  rather than `int` or `str`) . This is a variable only holds a memory address.
  The `malloc` method requests 512 bytes that it wants to assign to the `data`
  variable. It will return the address of the first byte in the newly allocated
  memory. `data` will then refer to the address on the stack that holds the
  address allocation on the heap.

  ## Related notes

raw_content:
  ---
  id: 18bl
  title: Heap_memory
  tags: [memory, C]
  created: Saturday, April 20, 2024
  ---

  # Heap memory

  Along with [[Stack_memory|Stack memory]], programs make use of _heap memory_
  during runtime.

  Heap memory does not use a standardised data structure and can be accessed from
  any point within the program.

  Whereas stack memory with it's LIFO structure has memory management built-in
  when programs allocate memory from the heap they must manually deallocate it
  when it is no longer required. This process of "freeing memory" is known as
  _garbage collection_. In a language like C, this is the explicit concern of the
  programmer and is not abstracted away. Failure to properly manage garbage
  collection is what causes [[Memory_leaks]].

  Heap memory is used in combination with the stack since a given heap memory
  allocation address is stored as a stack variable during runtime. It points to
  the heap memory address whilst not being that memory itself.

  Here is an example of managing heap memory allocation in C:

  ```c
  void * data;
  data = malloc(512)
  ```

  The first line assigns a special _pointer_ variable (indicated by `void *`
  rather than `int` or `str`) . This is a variable only holds a memory address.
  The `malloc` method requests 512 bytes that it wants to assign to the `data`
  variable. It will return the address of the first byte in the newly allocated
  memory. `data` will then refer to the address on the stack that holds the
  address allocation on the heap.

  ## Related notes


path: zk/Bitwise_operators.md
sortable_path: zkBitwise_operators.md
title: Bitwise_operators
lead: # Bitwise operators
checksum: de0c5734330e9f4351e0dd66dcc6527fe46b016e2ab7622f79349aa8723bcf57
created: 2024-04-20 13:49:57.582757199+00:00
modified: 2024-04-20 14:25:08.308261193+00:00
metadata: {"created":"Saturday, April 20, 2024","id":"t127","tags":["binary"],"title":"Bitwise_operators"}
body:
  # Bitwise operators

  In addition to mathematical, logical and comparison operators, there are
  _bitwise operators_. These operators execute conditions based on the actual bits
  of a value rather than the values that the bits are encoded to represent.

  Bitwise operators are typically represented with single characters of existing
  operators, e.g. `&` instead of `&&`:

  | Bitwise operation | Operator      |
  | ----------------- | ------------- |
  | AND               | `&`           |
  | OR                | (single pipe) |
  | NOT               | `~`           |

  An example of using the `&` operator:

  ```py
  x = 5
  y = 3
  a = x & y
  b = x | y
  ```

  The value of `a` will be 1. The reason is we are looking at the bit values of
  `x` and `y` and then applying Boolean AND to each bit:

  ```
  x = 5 = 0101
  y = 3 = 0011
  a = 1 = 0001
  ```

  Working from right to left for each column:

  - true and true = true
  - false and true = false
  - true and false = false
  - false and false = false

  This leaves us with 0001 which is equal to 1 in binary and denary.

  For the case of bitwise OR we get 7 as the result of `x | y`:

  ```
  x = 5 = 0101
  y = 3 = 0011
  b = 7 = 0111
  ```

  - true or true = true
  - false or true = true
  - true or false = true
  - false or false = true

  This leaves us with 0111 which is equal to 7 in denary.

  ## Why use them?

  Bitwise operations are more of a hallmark of lower-level programming. As bit
  operations are the fastest and lowest level of computation, being able to
  directly access and operate on bits within a programming language can be
  beneficial when efficiency and speed of execution is a factor or when memory is
  constrained.

  ## Related notes

raw_content:
  ---
  id: t127
  title: Bitwise_operators
  tags: [binary]
  created: Saturday, April 20, 2024
  ---

  # Bitwise operators

  In addition to mathematical, logical and comparison operators, there are
  _bitwise operators_. These operators execute conditions based on the actual bits
  of a value rather than the values that the bits are encoded to represent.

  Bitwise operators are typically represented with single characters of existing
  operators, e.g. `&` instead of `&&`:

  | Bitwise operation | Operator      |
  | ----------------- | ------------- |
  | AND               | `&`           |
  | OR                | (single pipe) |
  | NOT               | `~`           |

  An example of using the `&` operator:

  ```py
  x = 5
  y = 3
  a = x & y
  b = x | y
  ```

  The value of `a` will be 1. The reason is we are looking at the bit values of
  `x` and `y` and then applying Boolean AND to each bit:

  ```
  x = 5 = 0101
  y = 3 = 0011
  a = 1 = 0001
  ```

  Working from right to left for each column:

  - true and true = true
  - false and true = false
  - true and false = false
  - false and false = false

  This leaves us with 0001 which is equal to 1 in binary and denary.

  For the case of bitwise OR we get 7 as the result of `x | y`:

  ```
  x = 5 = 0101
  y = 3 = 0011
  b = 7 = 0111
  ```

  - true or true = true
  - false or true = true
  - true or false = true
  - false or false = true

  This leaves us with 0111 which is equal to 7 in denary.

  ## Why use them?

  Bitwise operations are more of a hallmark of lower-level programming. As bit
  operations are the fastest and lowest level of computation, being able to
  directly access and operate on bits within a programming language can be
  beneficial when efficiency and speed of execution is a factor or when memory is
  constrained.

  ## Related notes


path: zk/NodeJS_scripts.md
sortable_path: zkNodeJS_scripts.md
title: NodeJS_scripts
lead: # NodeJS_scripts
checksum: 7f543a01a82b789f7dbb6cdf76cb210ae0e4522439bd842a5694761bb0943872
created: 2024-04-26 09:50:22.490916912+00:00
modified: 2024-04-28 10:34:57.917110341+00:00
metadata: {"created":"Friday, April 26, 2024","id":5043,"tags":["node-js"],"title":"NodeJS_scripts"}
body:
  # NodeJS_scripts

  If we want to use NodeJS as a scripting language without going to the trouble of
  setting up an NPM-based development environment, we can use the following
  architecture.

  ```js
  #!/usr/bin/env node

  const process = require("process");

  const actualScript = (firstParam, secondParam) => {
    // Do something
  };

  if (require.main === module) {
    const [, param1, param2] = process.argv;
    actualScript(param1, param2).catch(console.error);
  }
  ```

  Basically we have a function that contains the main actions of the script. This
  is then invoked within `main` in the manner of a Bash or
  ![Python script](./Single_file_Python_scripts.md)

  This obviously requires the Node binary to be in your path and the script must
  be run with executable privileges.

  If you use any module not in the Node core, you will need to have this installed
  globally for it to work. (There are
  [ways around this](https://thom4.net/2014/self-contained-node-scripts/) for Node
  scripts you publish but for personal scripts this doesn't matter.)

  ## `require.main`

  This construction checks that the script is being directy invoked via the 'node'
  command in the terminal rather than called by another module.

  This is equivalent to the [following construct]() in Python:

  ```py
  if __name__ == "__main__":
  ```

raw_content:
  ---
  id: 5043
  title: NodeJS_scripts
  tags: [node-js]
  created: Friday, April 26, 2024
  ---

  # NodeJS_scripts

  If we want to use NodeJS as a scripting language without going to the trouble of
  setting up an NPM-based development environment, we can use the following
  architecture.

  ```js
  #!/usr/bin/env node

  const process = require("process");

  const actualScript = (firstParam, secondParam) => {
    // Do something
  };

  if (require.main === module) {
    const [, param1, param2] = process.argv;
    actualScript(param1, param2).catch(console.error);
  }
  ```

  Basically we have a function that contains the main actions of the script. This
  is then invoked within `main` in the manner of a Bash or
  ![Python script](./Single_file_Python_scripts.md)

  This obviously requires the Node binary to be in your path and the script must
  be run with executable privileges.

  If you use any module not in the Node core, you will need to have this installed
  globally for it to work. (There are
  [ways around this](https://thom4.net/2014/self-contained-node-scripts/) for Node
  scripts you publish but for personal scripts this doesn't matter.)

  ## `require.main`

  This construction checks that the script is being directy invoked via the 'node'
  command in the terminal rather than called by another module.

  This is equivalent to the [following construct]() in Python:

  ```py
  if __name__ == "__main__":
  ```


path: zk/Single_file_Python_scripts.md
sortable_path: zkSingle_file_Python_scripts.md
title: Single_file_Python_scripts
lead: # Single_file_Python_scripts
checksum: 6145bde1593264784876cfb088585d22a6aaaf70fadb477df93bec755ee419a3
created: 2024-04-26 09:58:57.238585351+00:00
modified: 2024-04-28 10:51:45.411832459+00:00
metadata: {"created":"Friday, April 26, 2024","id":"atzw","tags":[],"title":"Single_file_Python_scripts"}
body:
  # Single_file_Python_scripts

  ## Basic architecture

  ```py
  #! /usr/local/bin/python3

  import sys

  if __name__ == "__main__":
      all_args = sys.argv
      specific_arg = sys.argv[0]
      # Main functionality...
  ```

  When you run a script (module) Python assigns the string `__main__` to the
  `__name__` attribute to the script that is being executed.

  If you run the script as an import into another script, the `__name__` attribute
  of the imported module is set to the module name, not `__main__`.

  Everything can go under the `__main__` conditional, or, for better readability,
  you can define a `main` function that is then invoked, e.g:

  ```py

  def main():
      # Do some stuff


  if __name__ == "__main__":
      main()

  ```

  ## Related notes

  ![Python modules and imports](./Python_modules_and_imports.md)

raw_content:
  ---
  id: atzw
  title: Single_file_Python_scripts
  tags: []
  created: Friday, April 26, 2024
  ---

  # Single_file_Python_scripts

  ## Basic architecture

  ```py
  #! /usr/local/bin/python3

  import sys

  if __name__ == "__main__":
      all_args = sys.argv
      specific_arg = sys.argv[0]
      # Main functionality...
  ```

  When you run a script (module) Python assigns the string `__main__` to the
  `__name__` attribute to the script that is being executed.

  If you run the script as an import into another script, the `__name__` attribute
  of the imported module is set to the module name, not `__main__`.

  Everything can go under the `__main__` conditional, or, for better readability,
  you can define a `main` function that is then invoked, e.g:

  ```py

  def main():
      # Do some stuff


  if __name__ == "__main__":
      main()

  ```

  ## Related notes

  ![Python modules and imports](./Python_modules_and_imports.md)


path: zk/Working_with_CSVs_in_Python.md
sortable_path: zkWorking_with_CSVs_in_Python.md
title: Working_with_CSVs_in_Python
lead: # Working_with_CSVs_in_Python
checksum: 9dd9c338f63f3d56c19fa7e30cc88d5665e984f99de28190efbe6f02e5dac060
created: 2024-04-28 11:17:03.295837625+00:00
modified: 2024-04-28 16:09:21.572769207+00:00
body:
  # Working_with_CSVs_in_Python

  ## Core package

  ```py
  import csv
  ```

  ## Read and write to CSV

  ### Read

  Use standard Pythonic "read" syntax:

  ```py
  with open('./path.csv', mode="r") as csv_file:
      reader = csv.reader(csv_file)
  ```

  ### Parse values

  Having created the `reader` object, you can then loop through this as an
  iterable:

  ```py
  for row in reader:
      print(row)
  ```

  Will return something like:

  ```csv
  column something, column something else, ...
  ```

  Which we can individuate with:

  ```py
  print(row[0])
  # column something
  ```

  We can also parse the rows as a dictionary for easier individuation. We do this
  by creating a `DictReader` rather than the default `reader`:

  ```py
  ...
  dict_reader = csv.DictReader(csv_file)
  ```

  Now we can use the header row values to individuate particular columns.

  Say we have a CSV with the following headers:

  ```csv
  name, profession
  ```

  We can individuate thus:

  ```py
  for row in dict_reader
      name = row["name"]
  ```

  ### Write

  Use standard Pythonic "read" syntax:

  ```py
  with open('./new_csv_file.csv', mode="w") as csv_file:
      writer = csv.writer(csv_file)
  ```

  The above will create the file as well, it doesn't need to be pre-existing.

  This creates the writer object. To actually write a row:

  ```py
  some_list = ['thomas', 'engineer']
  for element in some_list:
      writer.writerow(element)
  ```

raw_content:
  ---
  id: sgtn
  title: Working_with_CSVs_in_Python
  tags: [python, csv]
  created: Sunday, April 28, 2024
  ---

  # Working_with_CSVs_in_Python

  ## Core package

  ```py
  import csv
  ```

  ## Read and write to CSV

  ### Read

  Use standard Pythonic "read" syntax:

  ```py
  with open('./path.csv', mode="r") as csv_file:
      reader = csv.reader(csv_file)
  ```

  ### Parse values

  Having created the `reader` object, you can then loop through this as an
  iterable:

  ```py
  for row in reader:
      print(row)
  ```

  Will return something like:

  ```csv
  column something, column something else, ...
  ```

  Which we can individuate with:

  ```py
  print(row[0])
  # column something
  ```

  We can also parse the rows as a dictionary for easier individuation. We do this
  by creating a `DictReader` rather than the default `reader`:

  ```py
  ...
  dict_reader = csv.DictReader(csv_file)
  ```

  Now we can use the header row values to individuate particular columns.

  Say we have a CSV with the following headers:

  ```csv
  name, profession
  ```

  We can individuate thus:

  ```py
  for row in dict_reader
      name = row["name"]
  ```

  ### Write

  Use standard Pythonic "read" syntax:

  ```py
  with open('./new_csv_file.csv', mode="w") as csv_file:
      writer = csv.writer(csv_file)
  ```

  The above will create the file as well, it doesn't need to be pre-existing.

  This creates the writer object. To actually write a row:

  ```py
  some_list = ['thomas', 'engineer']
  for element in some_list:
      writer.writerow(element)
  ```

metadata:
  {"created":"Sunday, April 28, 2024","id":"sgtn","tags":["python","csv"],"title":"Working_with_CSVs_in_Python"}


path: zk/Time_and_computers.md
sortable_path: zkTime_and_computers.md
title: Time_and_computers
lead: # Time and computers
checksum: fd02795c584e43c2d4028c636c304bf3b4c23b008cc856ba8745425c20f6168a
created: 2024-04-28 16:09:38.744041761+00:00
modified: 2024-05-09 06:46:21.007627625+00:00
metadata: {"created":"Sunday, April 28, 2024","id":"l29u","tags":["unix"],"title":"Time_and_computers"}
body:
  # Time and computers

  ## Epochs and Unix Time

  An epoch is a period of time identified by a starting point.

  The standard epoch for measuring against is known colloqially as "Unix Time":
  midnight on 1st January 1970. Unix time is the number of seconds that have
  elapsed since this point. This is the standard for Windows and most unix
  systems.

  For example midnight on 2nd January 1970 would be 86400 seconds since the epoch.
  The deduction is as follows:

  ```
  60 * 60 * 24 = 86400
  ```

  We are multiplpying the number of seconds in a minute by the number of minutes
  in an hour by the number of hours in a day.

  To represent times and dates before 1970, we use negative integers.

  ## UTC and time zones

  "Coordinated Universal Time" (UTC) is the time standard against which the
  world's timekeeping is synchronized. It is not itself a timezone, it is a
  transcendent standard that defines what time zones are.

  Time zones are defined relative to UTC, by their offset to this value.

  For example North America is behind UTC by five or six hours hence uses the
  notation UTC-5:00 or UTC-6:00.

  UTC is the successor to GMT of which there were variances necessitating a
  universal value. Despite this GMT is equal to UTC+00:00 so apart from when
  daylight saving is in effect in the UK, GMT = UTC.

  Depending on your locale, relative to UTC, you will get different outputs when
  you attempt to log Unix Time.

  Also daylight savings can impact on the outputs. For instance for half of the
  year, when DST applies, the UK is UTC+01:00.

  ## Examples in Python

  The following gives us the unix seconds in my current time zone (GMT DST):

  ```py
  import time
  print(time.time())
  # 1714322393.2929392
  ```

  If I want UTC, I can do:

  ```py
  import datetime
  print(datetime.datetime.utcnow().strftime('%s'))
  # '1714318952'
  ```

  We see clearly that they are not identical.

raw_content:
  ---
  id: l29u
  title: Time_and_computers
  tags: [unix]
  created: Sunday, April 28, 2024
  ---

  # Time and computers

  ## Epochs and Unix Time

  An epoch is a period of time identified by a starting point.

  The standard epoch for measuring against is known colloqially as "Unix Time":
  midnight on 1st January 1970. Unix time is the number of seconds that have
  elapsed since this point. This is the standard for Windows and most unix
  systems.

  For example midnight on 2nd January 1970 would be 86400 seconds since the epoch.
  The deduction is as follows:

  ```
  60 * 60 * 24 = 86400
  ```

  We are multiplpying the number of seconds in a minute by the number of minutes
  in an hour by the number of hours in a day.

  To represent times and dates before 1970, we use negative integers.

  ## UTC and time zones

  "Coordinated Universal Time" (UTC) is the time standard against which the
  world's timekeeping is synchronized. It is not itself a timezone, it is a
  transcendent standard that defines what time zones are.

  Time zones are defined relative to UTC, by their offset to this value.

  For example North America is behind UTC by five or six hours hence uses the
  notation UTC-5:00 or UTC-6:00.

  UTC is the successor to GMT of which there were variances necessitating a
  universal value. Despite this GMT is equal to UTC+00:00 so apart from when
  daylight saving is in effect in the UK, GMT = UTC.

  Depending on your locale, relative to UTC, you will get different outputs when
  you attempt to log Unix Time.

  Also daylight savings can impact on the outputs. For instance for half of the
  year, when DST applies, the UK is UTC+01:00.

  ## Examples in Python

  The following gives us the unix seconds in my current time zone (GMT DST):

  ```py
  import time
  print(time.time())
  # 1714322393.2929392
  ```

  If I want UTC, I can do:

  ```py
  import datetime
  print(datetime.datetime.utcnow().strftime('%s'))
  # '1714318952'
  ```

  We see clearly that they are not identical.


path: zk/Invoking_the_shell_in_Python.md
sortable_path: zkInvoking_the_shell_in_Python.md
title: Invoking_the_shell_in_Python
lead: # Invoking the shell_in_Python
checksum: d4c82bc097aa7ad47db3bcbb91b7b5b84643617f9be062aa61c1a5064031cd43
created: 2024-04-29 16:47:43.359796333+00:00
modified: 2024-04-29 16:50:47.361758113+00:00
body:
  # Invoking the shell_in_Python

  ```py
  import subprocess

  try:
      process = subprocess.run(
          ["ls", "-la"],
          shell=True,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE,
          text=True,
      )
      return json.loads(process.stdout)

  except subprocess.CalledProcessError as e:
          return e.stderr.strip()
  ```

raw_content:
  ---
  id: cfr4
  title: Invoking_the_shell_in_Python
  tags: [python, shell]
  created: Monday, April 29, 2024
  ---

  # Invoking the shell_in_Python

  ```py
  import subprocess

  try:
      process = subprocess.run(
          ["ls", "-la"],
          shell=True,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE,
          text=True,
      )
      return json.loads(process.stdout)

  except subprocess.CalledProcessError as e:
          return e.stderr.strip()
  ```

metadata:
  {"created":"Monday, April 29, 2024","id":"cfr4","tags":["python","shell"],"title":"Invoking_the_shell_in_Python"}


path: zk/Linux_disk_partitions.md
sortable_path: zkLinux_disk_partitions.md
title: Linux disk partitions
checksum: d7baa86ca87df009a142bb4abedcd8c958483edf2cbe88de0544eb50cbe41a11
created: 2024-05-06 12:16:39.739170407+00:00
modified: 2024-05-06 13:16:38.848343997+00:00
metadata: {"tags":["disks"]}
lead:
  A disk is divided up into partitions which are subsections of the overall disk.
  The kernel presents each partition as a [block device](Devices.md#Devices) as it
  would with an entire disk.

body:
  A disk is divided up into partitions which are subsections of the overall disk.
  The kernel presents each partition as a [block device](Devices.md#Devices) as it
  would with an entire disk.

  The disk dedicates a small part of its contents to a **partition table**: this
  defines the different partitions that comprise the total disk space.

  ## Viewing current partitions

  Whenever you install a Linux distribution on a real or virtual machine, you must
  partition the drive. There are three main tools to choose from: `parted`,
  `g(raphical)parted`, `fdisk`.

  For a top-level overview of your disks and their main partitions you can run
  `lsblk` (_list block devices_):

  ```bash
  $ lsblk

  NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
  sda           8:0    0 465.7G  0 disk
  ├─sda1        8:1    0   200M  0 part
  └─sda2        8:2    0 465.4G  0 part /run/media/thomas/ganesh
  nvme0n1     259:0    0 476.9G  0 disk
  ├─nvme0n1p1 259:1    0   488M  0 part
  ├─nvme0n1p2 259:2    0  27.9G  0 part /
  └─nvme0n1p3 259:3    0 448.5G  0 part /home
  ```

  We can use `parted -l` to view the partition table for the current machine:

  ```bash
  Model: SKHynix_HFS512GDE9X081N (nvme)
  Disk /dev/nvme0n1: 512GB
  Sector size (logical/physical): 512B/512B
  Partition Table: gpt
  Disk Flags:

  Number  Start   End     Size    File system  Name  Flags
   1      1049kB  513MB   512MB   fat32              boot, esp
   2      513MB   30.5GB  30.0GB  ext4
   3      30.5GB  512GB   482GB   ext4
  ```

  We can use `fdisk -l` to get slightly more info:

  ```bash
  disk /dev/nvme0n1: 476.94 GiB, 512110190592 bytes, 1000215216 sectors
  Disk model: SKHynix_HFS512GDE9X081N
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: gpt
  Disk identifier: 08175E77-CB9F-C34A-9032-DF29A3F8F0FE

  Device            Start        End   Sectors   Size Type
  /dev/nvme0n1p1     2048    1001471    999424   488M EFI System
  /dev/nvme0n1p2  1001472   59594751  58593280  27.9G Linux filesystem
  /dev/nvme0n1p3 59594752 1000214527 940619776 448.5G Linux filesystem
  ```

  ## Standard Linux partitions

  The two tools disclose that the main harddrive is `/dev/nvme0n1` (equivalent to
  `sda` on older machines running Linux) and it has the standard three partitions:

  - Boot partition (`/dev/nvme0n1p1`)
  - Root dir (`/dev/nvme0n1p2`)
  - Home dir (`/dev/nvme0n1p3`)

  ### Boot partition

  - Takes up the smallest amount of space
  - Contains the Linux kernel and the bootloader (GRUB, usually) and any other
    files required for booting.
  - Once the BIOS has initialized the hardware components it hands control to the
    bootloader stored in this partition.
  - The bootloader loads the kernel contained in its partition, into memory

  ### Root partition (`/`)

  - This houses everything to do with the operation of the operating system apart
    from the initial booting process. Once the kernel is in memory it accesses the
    resources in the root partition to get the OS up and running. These resources
    include system libraries, utilities, system-wide configs and application
    software.

  - The root partition is vital for the system's functionality. Without it, the
    system cannot boot or operate. It needs to be  
     large enough to accommodate the operating system, installed programs, and system
    libraries, but it doesn't need to store user data or  
     additional applications, which can be located on other partitions.

  - This is the domain of the [superuser](User_Space.md#root-user-superuser). The
    part of the filesystem that you need sudo priveleges to access and where you
    manage users

  ### Home partition

  - This is presented as `/home/`, i.e. that it is a descendent of `/`. But this
    is because the Linux file system is hierarchical. Typically `/home/` is
    usually its own partition.
  - Separating user data and system data in this way protects user data during
    upgrades or reinstallation. Reinstalling or upgrading the OS can be done
    without affecting these files.
  - Each user has their own directory off of `/home`, e.g `/home/thomas`.
  - While the root partition (`/`) is essential for the operation of the OS,
    placing `/home` on a separate partition allows for better management of user
    data, enhancing the system's flexibility and the user's control over their own
    files, without compromising the integrity or performance of the OS. This
    approach exemplifies the Linux philosophy of giving the user control while
    maintaining a clear distinction between system  
    resources and user data.

  ## Types of partition table

  In the Linux world there are two main types: MBR and GPT. The type of table used
  determines how the OS boots. So although partition tables are also responsible
  for the partitioning of non-bootable sectors of a disk, **they are distinguished
  by the boot system they implement**. If we look at the output from `parted` and
  `fdisk` above we see that the harddrive uses the GPT partition type.

  #### Primary, extended and logical partitions

  Most standard partition tables allow for primary, extended and logical
  partitions. The primary partition is the part of the harddisk that contains the
  operating system and is thus described as 'bootable' and may be called the 'boot
  partition'. During the bootstrapping process this is injected into memory as the
  [kernel](The_Kernel.md).

  The extended partition is basically everything other than the primary partition.
  This is typically subdivided into other partitions that are called _logical_
  partitions. This is because they physically reside in the same sector of the
  disk (the extended partition) but are treated as virtual and independent disks.

  In our example above:

  - `/dev/nvme0n1p1` is the primary/boot partition
  - `/dev/nvme0n1p2` and `/dev/nvme0n1p3` comprise the extended partition and by
    themselves are each logical partitions.

  <dl>
    <dt>MBR</dt>
    <dd> 
      <ul>
        <li>Stands for Master Boot Record</li> 
        <li>Uses BIOS in the boot process</li> 
        <li>Can only works with disks up to 2TB in size</li> 
        <li>Only supports 4 primary partitions. This means the number of operating systems you install is limitied to this number.</li> 
        <li>This is the first 512 bytes of a storage device, preceding the first partition.</li>
      </ul> 
    </dd>
    <dt>GPT</dt>
    <dd>
    <ul>
        <li>Stands for GUID Partition Table </li>
        <li>Gradually replacing MBR</li>
        <li>Uses UEFI instead of BIOS</li>
        <li>As name indicates, every partition on disk has its own globally-unique identifier</li>
        <li>Vastly more partitions available than with MBR (dependent on operating system)</li>
        <li>Offers greater recovery options and anti-corruption safeguards</li> 
      </ul>
  </dd>
  </dl>

  ## Related notes

  ![Creating a Linux partition table](./Creating_a_Linux_partition_table.md)

raw_content:
  ---
  tags:
    - disks
  ---

  # Linux disk partitions

  A disk is divided up into partitions which are subsections of the overall disk.
  The kernel presents each partition as a [block device](Devices.md#Devices) as it
  would with an entire disk.

  The disk dedicates a small part of its contents to a **partition table**: this
  defines the different partitions that comprise the total disk space.

  ## Viewing current partitions

  Whenever you install a Linux distribution on a real or virtual machine, you must
  partition the drive. There are three main tools to choose from: `parted`,
  `g(raphical)parted`, `fdisk`.

  For a top-level overview of your disks and their main partitions you can run
  `lsblk` (_list block devices_):

  ```bash
  $ lsblk

  NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
  sda           8:0    0 465.7G  0 disk
  ├─sda1        8:1    0   200M  0 part
  └─sda2        8:2    0 465.4G  0 part /run/media/thomas/ganesh
  nvme0n1     259:0    0 476.9G  0 disk
  ├─nvme0n1p1 259:1    0   488M  0 part
  ├─nvme0n1p2 259:2    0  27.9G  0 part /
  └─nvme0n1p3 259:3    0 448.5G  0 part /home
  ```

  We can use `parted -l` to view the partition table for the current machine:

  ```bash
  Model: SKHynix_HFS512GDE9X081N (nvme)
  Disk /dev/nvme0n1: 512GB
  Sector size (logical/physical): 512B/512B
  Partition Table: gpt
  Disk Flags:

  Number  Start   End     Size    File system  Name  Flags
   1      1049kB  513MB   512MB   fat32              boot, esp
   2      513MB   30.5GB  30.0GB  ext4
   3      30.5GB  512GB   482GB   ext4
  ```

  We can use `fdisk -l` to get slightly more info:

  ```bash
  disk /dev/nvme0n1: 476.94 GiB, 512110190592 bytes, 1000215216 sectors
  Disk model: SKHynix_HFS512GDE9X081N
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: gpt
  Disk identifier: 08175E77-CB9F-C34A-9032-DF29A3F8F0FE

  Device            Start        End   Sectors   Size Type
  /dev/nvme0n1p1     2048    1001471    999424   488M EFI System
  /dev/nvme0n1p2  1001472   59594751  58593280  27.9G Linux filesystem
  /dev/nvme0n1p3 59594752 1000214527 940619776 448.5G Linux filesystem
  ```

  ## Standard Linux partitions

  The two tools disclose that the main harddrive is `/dev/nvme0n1` (equivalent to
  `sda` on older machines running Linux) and it has the standard three partitions:

  - Boot partition (`/dev/nvme0n1p1`)
  - Root dir (`/dev/nvme0n1p2`)
  - Home dir (`/dev/nvme0n1p3`)

  ### Boot partition

  - Takes up the smallest amount of space
  - Contains the Linux kernel and the bootloader (GRUB, usually) and any other
    files required for booting.
  - Once the BIOS has initialized the hardware components it hands control to the
    bootloader stored in this partition.
  - The bootloader loads the kernel contained in its partition, into memory

  ### Root partition (`/`)

  - This houses everything to do with the operation of the operating system apart
    from the initial booting process. Once the kernel is in memory it accesses the
    resources in the root partition to get the OS up and running. These resources
    include system libraries, utilities, system-wide configs and application
    software.

  - The root partition is vital for the system's functionality. Without it, the
    system cannot boot or operate. It needs to be  
     large enough to accommodate the operating system, installed programs, and system
    libraries, but it doesn't need to store user data or  
     additional applications, which can be located on other partitions.

  - This is the domain of the [superuser](User_Space.md#root-user-superuser). The
    part of the filesystem that you need sudo priveleges to access and where you
    manage users

  ### Home partition

  - This is presented as `/home/`, i.e. that it is a descendent of `/`. But this
    is because the Linux file system is hierarchical. Typically `/home/` is
    usually its own partition.
  - Separating user data and system data in this way protects user data during
    upgrades or reinstallation. Reinstalling or upgrading the OS can be done
    without affecting these files.
  - Each user has their own directory off of `/home`, e.g `/home/thomas`.
  - While the root partition (`/`) is essential for the operation of the OS,
    placing `/home` on a separate partition allows for better management of user
    data, enhancing the system's flexibility and the user's control over their own
    files, without compromising the integrity or performance of the OS. This
    approach exemplifies the Linux philosophy of giving the user control while
    maintaining a clear distinction between system  
    resources and user data.

  ## Types of partition table

  In the Linux world there are two main types: MBR and GPT. The type of table used
  determines how the OS boots. So although partition tables are also responsible
  for the partitioning of non-bootable sectors of a disk, **they are distinguished
  by the boot system they implement**. If we look at the output from `parted` and
  `fdisk` above we see that the harddrive uses the GPT partition type.

  #### Primary, extended and logical partitions

  Most standard partition tables allow for primary, extended and logical
  partitions. The primary partition is the part of the harddisk that contains the
  operating system and is thus described as 'bootable' and may be called the 'boot
  partition'. During the bootstrapping process this is injected into memory as the
  [kernel](The_Kernel.md).

  The extended partition is basically everything other than the primary partition.
  This is typically subdivided into other partitions that are called _logical_
  partitions. This is because they physically reside in the same sector of the
  disk (the extended partition) but are treated as virtual and independent disks.

  In our example above:

  - `/dev/nvme0n1p1` is the primary/boot partition
  - `/dev/nvme0n1p2` and `/dev/nvme0n1p3` comprise the extended partition and by
    themselves are each logical partitions.

  <dl>
    <dt>MBR</dt>
    <dd> 
      <ul>
        <li>Stands for Master Boot Record</li> 
        <li>Uses BIOS in the boot process</li> 
        <li>Can only works with disks up to 2TB in size</li> 
        <li>Only supports 4 primary partitions. This means the number of operating systems you install is limitied to this number.</li> 
        <li>This is the first 512 bytes of a storage device, preceding the first partition.</li>
      </ul> 
    </dd>
    <dt>GPT</dt>
    <dd>
    <ul>
        <li>Stands for GUID Partition Table </li>
        <li>Gradually replacing MBR</li>
        <li>Uses UEFI instead of BIOS</li>
        <li>As name indicates, every partition on disk has its own globally-unique identifier</li>
        <li>Vastly more partitions available than with MBR (dependent on operating system)</li>
        <li>Offers greater recovery options and anti-corruption safeguards</li> 
      </ul>
  </dd>
  </dl>

  ## Related notes

  ![Creating a Linux partition table](./Creating_a_Linux_partition_table.md)


path: zk/Creating_a_Linux_partition_table.md
sortable_path: zkCreating_a_Linux_partition_table.md
title: Creating_a_Linux_partition_table
lead: ## Creating a partition table
checksum: d24f8701b2f6fd3549c6c0e51071d3f4efeaff737c4fda9c3f989706bf70bea6
created: 2024-05-06 12:29:42.564542506+00:00
modified: 2024-05-06 12:33:15.579089822+00:00
body:
  ## Creating a partition table

  To demonstrate the process of partitioning a harddrive I am going to repartition
  an external SATA drive as if it were being primed for a fresh Linux install.

  Let's take a look at the disk in its current form:

  ```
  $ fdisk -l

    Disk /dev/sda: 465.74 GiB, 500079525888 bytes, 976717824 sectors
    Disk model: My Passport 071Aumount /dev/sda2
    Disklabel type: gpt
    Disk identifier: 9993F1BB-626C-485F-8542-3CC73BB40953

    Device      Start       End   Sectors   Size Type
    /dev/sda1      40    409639    409600   200M EFI System
    /dev/sda2  409640 976455639 976046000 465.4G Apple HFS/HFS+
  ```

  (This disk was previously used as a backup disk for MacOS so in addition to the
  extended partition which has a proprietary file system type (Apple HFS) it has a
  primary partition which would load the recovery OS. In contrast to my main
  harddrive this uses the standard SCSI prototcol and thus the partitions are
  prepended with `sda`.)

  #### 1. Unmount existing partitions

  ```bash
  umount /dev/sda1
  umount /dev/sda2
  ```

  #### 2. Deleting the existing partitions

  ```bash
  # Load the disk into fdisk
  $ sudo fdisk /dev/sda
  Command (m for help): d
  Partition number (1,2, default 2): 1
  Partition 1 has been deleted.
  Command (m for help): d
  Selected partition 2
  Partition 2 has been deleted.

  # Verify deletion with p(rint) command
  Command (m for help): p
  Disk /dev/sda: 465.74 GiB, 500079525888 bytes, 976717824 sectors
  Disk model: My Passport 071A
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: gpt
  Disk identifier: 9993F1BB-626C-485F-8542-3CC73BB40953

  # Write the changes to disk with w(rite)
  w

  # Check execution:
  $ lsblk

  NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
  sda           8:0    0 465.7G  0 disk
  ```

  So now the disk has no partitions, just the physical disk space and no
  mountpoints. We are ready to re-partition.

  #### 3. Re-partition the disk

  We are going to create a GPT partition table

  ```bash
  $ sudo fdisk /dev/sda
  Command (m for help): g
  Created a new GPT disklabel (GUID: E316B1A9-6F73-FB41-8CBB-FA4E3C448F2B).

  Command (m for help): n
  Partition number (1-128, default 1):
  First sector (2048-976717790, default 2048):

  # Just press enter here

  # The last sector is where we put the actual size we want for the partition
  Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-976717790, default 976715775): +100G
  Created a new partition 1 of type 'Linux filesystem' and of size 100 GiB.

  # For the second and final partition, we follow the same steps but don't add a partition size, since it will default to what is left.

  Command (m for help): n
  Partition number (2-128, default 2):
  First sector (209717248-976717790, default 209717248):
  Last sector, +/-sectors or +/-size{K,M,G,T,P} (209717248-976717790, default 976715775):

  Created a new partition 2 of type 'Linux filesystem' and of size 365.7 GiB.

  # Check the partitions with p(rint)
  Command (m for help): p
  Disk /dev/sda: 465.74 GiB, 500079525888 bytes, 976717824 sectors
  Disk model: My Passport 071A
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: gpt
  Disk identifier: 92739978-F7D2-5042-9758-C1429B5C8E11

  Device         Start       End   Sectors   Size Type
  /dev/sda1       2048 209717247 209715200   100G Linux filesystem
  /dev/sda2  209717248 976715775 766998528 365.7G Linux filesystem

  # Then write with w
  Command (m for help): w
  The partition table has been altered.
  Calling ioctl() to re-read partition table.
  Syncing disks.
  ```

  We can now confirm our new partitions:

  ```bash
  $ lsblk
  NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
  sda           8:0    0 465.7G  0 disk
  ├─sda1        8:1    0   100G  0 part
  └─sda2        8:2    0 365.7G  0 part
  ```

  #### Naming a partition

  By default each partition will have its GUID as its name, but you can add a
  human friendly name with:

  ```bash
  sudo e2label /dev/sda1 my_human_name
  ```

  > Whilst we have created our partitions we cannot yet mount them. This is
  > because we have not yet set up a filesystem on the partitions. This is the
  > next step.

  ## Related notes

  ![Linux disk partitions](./Linux_disk_partitions.md)

raw_content:
  ---
  id: h7f8
  title: Creating_a_Linux_partition_table
  tags: [disks]
  created: Monday, May 06, 2024
  ---

  ## Creating a partition table

  To demonstrate the process of partitioning a harddrive I am going to repartition
  an external SATA drive as if it were being primed for a fresh Linux install.

  Let's take a look at the disk in its current form:

  ```
  $ fdisk -l

    Disk /dev/sda: 465.74 GiB, 500079525888 bytes, 976717824 sectors
    Disk model: My Passport 071Aumount /dev/sda2
    Disklabel type: gpt
    Disk identifier: 9993F1BB-626C-485F-8542-3CC73BB40953

    Device      Start       End   Sectors   Size Type
    /dev/sda1      40    409639    409600   200M EFI System
    /dev/sda2  409640 976455639 976046000 465.4G Apple HFS/HFS+
  ```

  (This disk was previously used as a backup disk for MacOS so in addition to the
  extended partition which has a proprietary file system type (Apple HFS) it has a
  primary partition which would load the recovery OS. In contrast to my main
  harddrive this uses the standard SCSI prototcol and thus the partitions are
  prepended with `sda`.)

  #### 1. Unmount existing partitions

  ```bash
  umount /dev/sda1
  umount /dev/sda2
  ```

  #### 2. Deleting the existing partitions

  ```bash
  # Load the disk into fdisk
  $ sudo fdisk /dev/sda
  Command (m for help): d
  Partition number (1,2, default 2): 1
  Partition 1 has been deleted.
  Command (m for help): d
  Selected partition 2
  Partition 2 has been deleted.

  # Verify deletion with p(rint) command
  Command (m for help): p
  Disk /dev/sda: 465.74 GiB, 500079525888 bytes, 976717824 sectors
  Disk model: My Passport 071A
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: gpt
  Disk identifier: 9993F1BB-626C-485F-8542-3CC73BB40953

  # Write the changes to disk with w(rite)
  w

  # Check execution:
  $ lsblk

  NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
  sda           8:0    0 465.7G  0 disk
  ```

  So now the disk has no partitions, just the physical disk space and no
  mountpoints. We are ready to re-partition.

  #### 3. Re-partition the disk

  We are going to create a GPT partition table

  ```bash
  $ sudo fdisk /dev/sda
  Command (m for help): g
  Created a new GPT disklabel (GUID: E316B1A9-6F73-FB41-8CBB-FA4E3C448F2B).

  Command (m for help): n
  Partition number (1-128, default 1):
  First sector (2048-976717790, default 2048):

  # Just press enter here

  # The last sector is where we put the actual size we want for the partition
  Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-976717790, default 976715775): +100G
  Created a new partition 1 of type 'Linux filesystem' and of size 100 GiB.

  # For the second and final partition, we follow the same steps but don't add a partition size, since it will default to what is left.

  Command (m for help): n
  Partition number (2-128, default 2):
  First sector (209717248-976717790, default 209717248):
  Last sector, +/-sectors or +/-size{K,M,G,T,P} (209717248-976717790, default 976715775):

  Created a new partition 2 of type 'Linux filesystem' and of size 365.7 GiB.

  # Check the partitions with p(rint)
  Command (m for help): p
  Disk /dev/sda: 465.74 GiB, 500079525888 bytes, 976717824 sectors
  Disk model: My Passport 071A
  Units: sectors of 1 * 512 = 512 bytes
  Sector size (logical/physical): 512 bytes / 512 bytes
  I/O size (minimum/optimal): 512 bytes / 512 bytes
  Disklabel type: gpt
  Disk identifier: 92739978-F7D2-5042-9758-C1429B5C8E11

  Device         Start       End   Sectors   Size Type
  /dev/sda1       2048 209717247 209715200   100G Linux filesystem
  /dev/sda2  209717248 976715775 766998528 365.7G Linux filesystem

  # Then write with w
  Command (m for help): w
  The partition table has been altered.
  Calling ioctl() to re-read partition table.
  Syncing disks.
  ```

  We can now confirm our new partitions:

  ```bash
  $ lsblk
  NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
  sda           8:0    0 465.7G  0 disk
  ├─sda1        8:1    0   100G  0 part
  └─sda2        8:2    0 365.7G  0 part
  ```

  #### Naming a partition

  By default each partition will have its GUID as its name, but you can add a
  human friendly name with:

  ```bash
  sudo e2label /dev/sda1 my_human_name
  ```

  > Whilst we have created our partitions we cannot yet mount them. This is
  > because we have not yet set up a filesystem on the partitions. This is the
  > next step.

  ## Related notes

  ![Linux disk partitions](./Linux_disk_partitions.md)

metadata:
  {"created":"Monday, May 06, 2024","id":"h7f8","tags":["disks"],"title":"Creating_a_Linux_partition_table"}


path: zk/Change_DNS_server.md
sortable_path: zkChange_DNS_server.md
title: Change_DNS_server
lead: # Change_DNS_server
body:
  # Change_DNS_server

  ![](../img/change-dns-server.png)

checksum: 917d7dff4e02f18b7ff43e0a9f17f2e78a94abfe69b56dc5a98ef91db0ff676d
created: 2024-06-08 13:27:08.225348462+00:00
modified: 2024-06-08 13:28:33.165403151+00:00
metadata: {"created":"Saturday, June 08, 2024","id":"81vp","tags":["procedural"],"title":"Change_DNS_server"}
raw_content:
  ---
  id: 81vp
  title: Change_DNS_server
  tags: [procedural]
  created: Saturday, June 08, 2024
  ---

  # Change_DNS_server

  ![](../img/change-dns-server.png)


path: zk/DynamoDB.md
sortable_path: zkDynamoDB.md
title: DynamoDB
lead: # DynamoDB
body:
  # DynamoDB


  ## Related notes

checksum: 5b24535ee1b73c0b36629762bbc9b3d237971ac442725c4b82b735cd23810ec3
created: 2024-06-09 16:24:31.762182012+00:00
modified: 2024-06-09 16:24:31.759118778+00:00
metadata: {"created":"Sunday, June 09, 2024","id":"xowl","tags":[],"title":"DynamoDB"}
raw_content:
  ---
  id: xowl
  title: DynamoDB
  tags: []
  created: Sunday, June 09, 2024 
  ---
  # DynamoDB


  ## Related notes


# links

title: Zettelkasten
href: https://en.wikipedia.org/wiki/Zettelkasten
type: markdown
snippet:
  It is a [Zettelkasten](https://en.wikipedia.org/wiki/Zettelkasten) work in
  progress. I've recently converted the topic-based subdirectories into a single
  flat directory structure organised by tags. I'm in the process of partitioning
  longer notes into smaller informational units.


title: zk
href: https://github.com/zk-org/zk
type: markdown
snippet:
  I use the [zk](https://github.com/zk-org/zk) CLI package to help with indexing
  and task automation alongside its [zk-nvim](https://github.com/zk-org/zk-nvim)
  Neovim wrapper. I occassionally utilise [Obsidian](https://obsidian.md/)
  alongside Neovim for when I want to view my notes as a knowledge graph or read
  them alongside their rich content (images, videos etc).


title: dotfiles
href: https://github.com/thomasabishop/dotfiles
type: markdown
snippet:
  Commands are local to my Linux machine, specified in my
  [dotfiles](https://github.com/thomasabishop/dotfiles). They are how I generate
  new entries and manage the knowledge base.


title: Telescope
href: https://github.com/nvim-telescope/telescope.nvim
type: markdown
snippet:
  | Alias          | Command                | Output                                                                                                                       |
  | -------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
  | `z`            | `cd $HOME/repos/eolas` | Access Zettelkasten                                                                                                          |
  | `zn`           | `zk new --title ...`   | Create new entry from template                                                                                               |
  | `<leader> zk`  | `:ZkNotes`             | Access Zettelkasten from anywhere within `nvim`                                                                              |
  | `<leader> zi`  | `:ZkIndex`             | Index Zettelkasten within `nvim`                                                                                             |
  | `<leader> zt`  | `:ZkTags`              | View tags via [Telescope](https://github.com/nvim-telescope/telescope.nvim) within `nvim`                                    |
  | `<leader> ztt` | `:ObsidianTags`        | View tags in a Vim buffer via within `nvim` using [obsidian-nvim](https://github.com/epwalsh/obsidian.nvim)                  |
  | `<leader> zl`  | `:ZkLinks`             | View links in current entry via Telescope within `nvim`, using [obsidian-nvim](https://github.com/epwalsh/obsidian.nvim)     |
  | `<leader> zb`  | `:ZkBacklinks`         | View backlinks to current entry via Telescope within `nvim`, using [obsidian-nvim](https://github.com/epwalsh/obsidian.nvim) |


title: scripts
href: scripts
type: markdown
snippet:
  The [scripts](/scripts) directory contains several Bash and Python scripts I use
  for general housekeeping, such as formatting image URLs, removing unused assets,
  and autosaving.


title: bash script
href: scripts/auto_save.sh
type: markdown
snippet:
  I use a [bash script](./scripts/auto_save.sh) to create autosave functionality
  via Git. This script runs every 15 minutes via a
  [systemd time](https://github.com/thomasabishop/dotfiles/tree/master/systemd/zettelkasten_autosave)
  timer. It tidies up the directory (removes unused images, ensures all file names
  use underscores rather than spaces and hyphens etc) and commits and pushes to
  GitHub.


title: HTTP request types
href: zk/HTTP_request_types.md
type: markdown
snippet:
  Express provides us with methods corresponding to each of the
  [HTTP request types](HTTP_request_types.md):


title: MongoDB database
href: zk/05_ Integrating_the_database.md
type: markdown
snippet:
  Typically when you create a RESTful API you are going to be returning data
  > from a database. For simplicity we are just going simulate this with a simple
  > data array so that we can focus on the Express syntax rather than database
  > handling. Later we will integrate this with a
  > [MongoDB database](05_%20Integrating_the_database.md).


title: middleware
href: zk/Middleware.md
type: markdown
snippet:
  We first create an instance of Express within `index.js`. This will be the main
  coordinating file and we will aim to minimise the amount of business logic we
  have in this file. It should really just be for initialization and managing
  [middleware](Middleware.md).


title: event emitter
href: zk/Events module.md#event-emitters
type: markdown
snippet:
  We create an [event emitter](Events%20module.md#event-emitters) and listener
  that listens for GET requests on a specified port and sends data in response to
  requests.


title: Joi validator
href: zk/Validation.md
type: markdown
snippet:
  We should accept alterations to the database that are not first validated. We
  can use the
  [Joi validator](Validation.md) to vet
  the request:


title: my notes
href: zk/Connect_to_database.md
type: markdown
snippet:
  We will follow the routine for establishing a MongoDB instance as detailed in
  [my notes](Connect_to_database.md) on Mongo:


title: Querying a collection
href: zk/Querying_a_collection.md
type: markdown
snippet:
  Now we need to rewrite our RESTful request handlers so that the data is sourced
  from and added to the database. We will mainly be using the Mongo syntax defined
  at [Querying a collection](Querying_a_collection.md) and
  [Adding documents to a collection](Adding_documents_to_a_collection.md).
  We will also keep API validation within the `/model/` file.


title: query-first
href: zk/Update_document.md#query-first-document-update
type: markdown
snippet:
  When updating a value in the database we are going to use the
  [query-first](Update_document.md#query-first-document-update)
  approach to updating a Mongo document.


title: using API Gateway as Lambda trigger
href: zk/Practical_walkthrough_Lambda_creation_within_AWS.md
type: markdown
snippet:
  See
  [using API Gateway as Lambda trigger](Practical_walkthrough_Lambda_creation_within_AWS.md)
  for a basic example of usage.


title: Fetch from Secrets Manager
href: zk/Fetch_from_Secrets_Manager.md
type: markdown
snippet:
  See
  [Fetch from Secrets Manager](Fetch_from_Secrets_Manager.md)
  for a code example of retrieving a value from Secrets Manager.


title: factors and divisors
href: zk/Factors_and_divisors.md
type: markdown
snippet:
  Given the symmetry between
  [factors and divisors](Factors_and_divisors.md) these
  properties are related. Note however that the LCM is more generic: it applies to
  any set of numbers not just fractions. Whereas the LCD is explicitly to do with
  fractions (hence 'denominator').


title: increase the complexity
href: zk/Why_computers_use_binary.md#from-circuits-to-programs
type: markdown
snippet:
  Although a digital system could use more than two symbols, adding more would
  [increase the complexity](Why_computers_use_binary.md#from-circuits-to-programs)
  and cost of the system. A set of only two symbols allows for simplified hardware
  and improved reliability.


title: schema
href: zk/Apollo_Server.md#example-schema
type: markdown
snippet:
  We will be working with the
  > [schema](Apollo_Server.md#example-schema) we defined
  > when working on the server


title: resolver
href: zk/Apollo_Server.md#implementing-resolvers
type: markdown
snippet:
  Therefore, for each query in the schema we must write a frontend implementation.
  We do this with **query constants**. The frontend implementation has a backend
  analogue: the
  [resolver](Apollo_Server.md#implementing-resolvers)
  that is invoked when the frontend issues a query. The schema standardises this
  relationship so that every query on the client must have a corresponding
  resolver on the backend.


title: listener
href: zk/Node_JS_events_module.md#extending-the-eventemitter-class
type: markdown
snippet:
  We instantiate an `ApolloServer` instance and pass our schema to it. We then
  subscribe to it with a
  [listener](Node_JS_events_module.md#extending-the-eventemitter-class).


title: function
href: zk/Creating_a_GraphQL_server.md#resolvers
type: markdown
snippet:
  A resolver is a [function](Creating_a_GraphQL_server.md#resolvers) that
  populates data for a given query. It should have **the same name as the field
  for the query**. So far we have one query in our schema: `tracksForHome` which
  returns the tracks to be listed on the home page. We must therefore also name
  our resolver for this query `tracksForHome`.


title: generic example
href: zk/Creating_a_GraphQL_server.md#resolvers
type: markdown
snippet:
  As per the [generic example](Creating_a_GraphQL_server.md#resolvers), you
  write write your resolvers as keys on a `resolvers` object, e.g:


title: resolver chains
href: zk/Using_arguments_with_Apollo_Client.md#resolver-chains
type: markdown
snippet:
  Used with
      [resolver chains](Using_arguments_with_Apollo_Client.md#resolver-chains)
      ---add example


title: argument
href: zk/Using_arguments_with_Apollo_Client.md
type: markdown
snippet:
  This time we utilise the `args` parameter in the resolver since an `id` will
    be provided as a client-side
    [argument](Using_arguments_with_Apollo_Client.md) to
    return a specific author.


title: useReducer
href: zk/useReducer.md#refining-the-syntax
type: markdown
snippet:
  Now we need a reducer that will handle the state updates. We will just use the
  same setup as we used in the example of
  [useReducer](useReducer.md#refining-the-syntax):


title: Routing
href: zk/Routing.md
type: markdown
snippet:
  If you are using React Router `App` becomes the index for the different page
    components. See [Routing](Routing.md) for more detail.


title: logic gates
href: zk/Logic_gates.md
type: markdown
snippet:
  The ALU comprises
  [logic gates](Logic_gates.md) that
  execute the instructions passed from memory and where the data stored by the
  registers is acted upon. A processor's ALU is just a complex combinatorial logic
  circuit.


title: full-adders and half adders
href: zk/Half_adder_and_full_adder.md
type: markdown
snippet:
  It executes arithmetic and logical operations on binary numbers and where you
  will find operations conducted by
  [full-adders and half adders](Half_adder_and_full_adder.md)
  etc.


title: fetch, decode, execute cycle
href: zk/Fetch_decode_execute.md
type: markdown
snippet:
  More specifically, the ALU is responsible for the _execute_ phase of the
  [fetch, decode, execute cycle](Fetch_decode_execute.md).


title: Basic properties of sets
href: zk/Basic properties of sets.md
type: markdown
snippet:
  The basic notions of set theory are defined in
  [Basic properties of sets](Basic%20properties%20of%20sets.md). There we
  introduced a formal syntax that will be utilised to define the axioms. For easy
  reference:


title: https://www.geeksforgeeks.org/user-mode-and-kernel-mode-switching/
href: https://www.geeksforgeeks.org/user-mode-and-kernel-mode-switching/
type: implicit
snippet:
  !! Add info on kernel mode and user mode
  https://www.geeksforgeeks.org/user-mode-and-kernel-mode-switching/


title: hexadecimal
href: zk/Hexadecimal_number_system.md
type: markdown
snippet:
  To distinguish numbers in binary from decimal or
  [hexadecimal](Hexadecimal_number_system.md)
  numbers, it is common to use the prefix `0b`. Thus, e.g, `0b110` for decimal
  `6`.


title: binary number system
href: zk/Binary_number_system.md
type: markdown
snippet:
  The equivalent entity in the
  [binary number system](Binary_number_system.md)
  is the **bit**. For example the binary number 110 has three bits. A bit can only
  have one of two values in contrast to a digit which can have one of ten values.
  These values are 0 and 1.


title: standard metric prefixes
href: zk/Prefixes_for_units_of_electrical_measurement.md
type: markdown
snippet:
  Having established that the core quantity of information is the byte, the
  convention is to apply the
  [standard metric prefixes](Prefixes_for_units_of_electrical_measurement.md)
  to the byte to establish units:


title: Commutative Law
href: zk/Whole_numbers.md#the-commutative-property
type: markdown
snippet:
  Compare the
  [Commutative Law](Whole_numbers.md#the-commutative-property)
  in the context of arithmetic.


title: Associative Law
href: zk/Whole_numbers.md#the-associative-property
type: markdown
snippet:
  Compare the
  [Associative Law](Whole_numbers.md#the-associative-property)
  in the context of arithmetic.


title: Distributive Law applies in the case of algebra based on arithmetic
href: zk/Distributivity.md
type: markdown
snippet:
  Compare how the
  [Distributive Law applies in the case of algebra based on arithmetic](Distributivity.md):


title: DeMorgan's Laws
href: zk/DeMorgan's_Laws.md
type: markdown
snippet:
  In addition we have
  [DeMorgan's Laws](DeMorgan's_Laws.md) which express
  the relationship that obtains between the negations of conjunctive and
  disjunctive expressions:


title: logic gates
href: zk/Logic_gates.md
type: markdown
snippet:
  The fact that we can take a complex Boolean function and reduce it to a simpler
  formulation has great significance for the development of computer
  architectures, specifically
  [logic gates](Logic_gates.md). It
  would be rather resource intensive and inefficient to create a gate that is
  representative of the complex function. Whereas the simplified version only
  requires a single
  [OR gate](Logic_gates.md#or-gate).


title: logic circuits
href: zk/Digital_circuits.md
type: markdown
snippet:
  This is an important skill that we will use when constructing
  [logic circuits](Digital_circuits.md).
  We will go from truth conditions (i.e. what we want the circuit to do and when
  we want it to do it) to a function expression which is then reduced to its
  simplest form and implemented with
  [logic gates](Logic_gates.md).
  Specifically, NAND gates.


title: idempotence
href: zk/Boolean_algebra.md#idempotent-law
type: markdown
snippet:
  Notice that $\lnot(z)$ is repeated so we can remove the repetition through
  [idempotence](Boolean_algebra.md#idempotent-law):


title: NAND gate
href: zk/Logic_gates.md#nand-gate
type: markdown
snippet:
  Finally, we can simplify even further by doing away with AND and NOT and using a
  single
  [NAND gate](Logic_gates.md#nand-gate)
  which embodies the logic of both, being true in all instances where AND would be
  false: $\lnot (x \land  y)$.


title: trkjuth table
href: zk/Truth-tables.md
type: markdown
snippet:
  We can compute all possible outputs of the function by constructing a
  [trkjuth table](Truth-tables.md) with each possible
  variable as the truth conditions and the output of the function as the truth
  value:


title: process id
href: zk/Processes.md#processes-ps
type: markdown
snippet:
  The kernel starts a program called **init**. It has a
     [process id](Processes.md#processes-ps)
     of 1. This is the point at which [user space](User_Space.md) starts.


title: capacitors
href: zk/Memory.md
type: markdown
snippet:
  This is the part of the CPU that stores data. The memory cells that comprise it
  do not have [capacitors](Memory.md) (unlike RAM)
  so they cannot store very much data but they work faster, which is what is
  important. Because their memory capacity is so small, we measure the size of
  registers in bits rather than bytes.


title: memory hierarchy
href: zk/Memory.md#the-memory-hierarchy
type: markdown
snippet:
  In terms of speed, registers sit at the top part of the overall
  [memory hierarchy](Memory.md#the-memory-hierarchy).


title: controller
href: zk/Chipset_and_controllers.md
type: markdown
snippet:
  The CPU's [controller](Chipset_and_controllers.md). It
  takes the instructions in binary form from RAM memory (separate from the CPU,
  but connected) and then signals to the to ALU and memory registers what it is
  supposed to do to execute the instructions. Think of it as the overseer that
  gets the ALU and registers to work together to run program instructions.


title: logic gates
href: zk/Logic_gates.md
type: markdown
snippet:
  The clock's circuitry is based on a quartz crystal system like that used in
  watches. At precisely timed intervals, the clock sends out pulses of electricity
  that cause bits to move from place to place within
  [logic gates](Logic_gates.md) or
  between logic gates and
  [registers](CPU_architecture.md#registers). This is
  covered in greater detail in the discussion of
  [clock signals in digital circuits](Clock_signals.md).


title: kernel
href: zk/The_Kernel.md
type: markdown
snippet:
  Each "cycle" is the execution of a process that commences once the
  [kernel](The_Kernel.md) hands control to the CPU. Each cycle
  follows a sequence of events known as
  [fetch, decode, and execute](Fetch_decode_execute.md).


title: electromagentic waves
href: zk/Electromagnetism.md
type: markdown
snippet:
  Hertz was the scientist who detected
  [electromagentic waves](Electromagnetism.md).
  We use Hertz as a measure of the frequency of electromatic wave cycles in a
  signal.


title: arguments
href: zk/Passing_arguments_and_options_to_Bash_scripts.md
type: markdown
snippet:
  Here we test that the right number of
  [arguments](Passing_arguments_and_options_to_Bash_scripts.md)
  have been passed to the script:


title: electrical field
href: zk/Voltage.md#distinguishing-voltage-from-electric-field
type: markdown
snippet:
  In this configuration the same current flows through all the cells; it is not
  cumulative. We represent this as follow> However the voltage is cumulative: it
  is the _sum_ of the individual cell voltages, represented below as
  [electrical field](Voltage.md#distinguishing-voltage-from-electric-field):


title: remote tracking branch
href: zk/Remote_tracking_branches.md
type: markdown
snippet:
  You don't have to just cherry-pick locally, you can also cherry-pick from a
    [remote tracking branch](Remote_tracking_branches.md).


title: motherboard
href: zk/Motherboard.md
type: markdown
snippet:
  The chipset manages the data flow between the different components that comprise
  the [motherboard](Motherboard.md): processor,
  [memory](Memory.md),
  [harddisk](What_are_disks.md) and peripherals.


title: system bus
href: zk/Bus.md
type: markdown
snippet:
  Buses run in and out of the chipset into these key motherboard components. The
  main chipset is a kind of junction that sits between the memory and CPU through
  which the [system bus](Bus.md) passes.


title: battery
href: zk/Cells_and_batteries.md#cells-and-batteries
type: markdown
snippet:
  Below is a basic circuit representing a 9-volt
  [battery](Cells_and_batteries.md#cells-and-batteries)
  with a 10,000$\Omega$
  [resistor](Resistance.md) attached
  accross its terminals. Through the application of
  [Ohm's Law](Ohms_Law.md) we can
  determine that the maximum current will be 0.9 miliamps.


title: duck typing
href: zk/Custom_types.md#duck-typing
type: markdown
snippet:
  You shouldn't confuse `implements` with `extends`. `implements` just checks the
  class as an interface in accordance with the principles of
  [duck typing](Custom_types.md#duck-typing):
  i.e the implementing class should have the same properties and methods. It
  doesn't affect anything internal to the methods or properties. So e.g, if you
  typed a method parameter as `string` in the base class, this would still default
  to `any` in the derived class.


title: copying functions
href: zk/Functions_in_Python.md
type: markdown
snippet:
  The same principle that applies to
  [copying functions](Functions_in_Python.md)
  applies to copying objects created through classes: redeclaration results in a
  duplicate entity. Thus changes to the duplicate will affect the original.


title: electromagnetic
href: zk/Electromagnetism.md
type: markdown
snippet:
  A single iteration of the volatage rising and falling is a **pulse**. A complete
  oscillation from low to high and back to low is a **cycle**. As with all
  [electromagnetic](Electromagnetism.md)
  signals we measure the frequency of the wave in Hertz: cylcles per second. We
  also further distinguish the rising and falling edge of a pulse. Rising
  represents the signal passing from ground to its maximum voltage and falling is
  the reverse (the electrons moving from the voltage source to ground).


title: CPU
href: zk/CPU_architecture.md#the-system-clock
type: markdown
snippet:
  The role of the clock is essential in the functioning of the
  [CPU](CPU_architecture.md#the-system-clock). It is
  the system clock that gives CPUs their performance rating: how many processes
  can execute within a given clock cycle.


title: principle of the immutability of elements
href: zk/Elements-992594b9cd2e483c85cddddffeb16f11
type: markdown
snippet:
  We change components by using state, not by mutating props. This is consistent
  with React's
  [principle of the immutability of elements](Elements-992594b9cd2e483c85cddddffeb16f11).


title: kernal
href: zk/The_Kernel.md
type: markdown
snippet:
  Containers are native to the Linux [kernal](The_Kernel.md)
    and are key part of how it works. Thus when you run containers on Linux, you
    are using native capability. When you use containers on Windows or Mac you
    have to run a virtual version of Linux in order to exploit the capabilities of
    that kernel. (Docker provides this)


title: user space
href: zk/User_Space.md
type: markdown
snippet:
  In ordinary [user space](User_Space.md) applications share
  the _same_ processor, memory and file system resources. This increases the
  likelihood of resourcing challenges, dependency conflicts and security threats.
  Without modularisation and the titration of resources, you are opened up to much
  greater possibility of failure.


title: data type
href: zk/Data_types_in_MySQL.md
type: markdown
snippet:
  Below is an example of this in practice. Each field corresponds to a column. We
  specify the name of the field and its corresponding
  [data type](Data_types_in_MySQL.md). Every table must have a
  **primary key**. In the example, `employee_id` is the primary key.


title: collections and documents
href: zk/Introduction.md
type: markdown
snippet:
  In order start adding
  [collections and documents](Introduction.md) to our database,
  we use Mongoose's **schema** structure. (This is specific to Mongoose and is not
  a structure that is a part of Mongo in general.)


title: separate entry
href: zk/Validating_Mongoose_schemas.md
type: markdown
snippet:
  Note that we set our validation criteria as the second property for each
  > schema value. There is more info info on validation in a
  > [separate entry](Validating_Mongoose_schemas.md);


title: mode
href: zk/File_permissions_and_execution.md#what-the-output-means
type: markdown
snippet:
  The
  [mode](File_permissions_and_execution.md#what-the-output-means)
  is different from ordinary files. Each device file is prepended with
  `b, p, c, s` before the standard permissions. These stand for the major types of
  devices: _block, character, pipe_ and _socket_.


title: bash scripting
href: zk/Redirect_to_dev_null.md
type: markdown
snippet:
  `/dev/null` is a virtual device: it doesn't actually exist as a piece of
  hardware on the system. It can be useful when
  [bash scripting](Redirect_to_dev_null.md) as a
  place to direct output that you don't care about, for example errors or verbose
  program read-outs.


title: logic gates
href: zk/Logic_gates.md
type: markdown
snippet:
  In a standard electrical circuit, voltage, current and resistance can vary over
  a wide range of values however in the binary context we want to deal with
  discrete values (zeros and ones) which can be fed into the various
  [logic gates](Logic_gates.md).


title: transistor
href: zk/Transistors.md
type: markdown
snippet:
  The [transistor](Transistors.md) is
  the electrical component that enables us to represent given voltage ranges as
  being 'on' or 'off'.


title: reciprocol
href: zk/Reciprocals.md
type: markdown
snippet:
  We combine the foregoing (that it is easier to divide by fractional amounts
  using multiplication) with the concept of a [reciprocol](Reciprocals.md) to
  arrive at a definitive method for dividing two fractions. It boils down to:
  _invert and multiply_:


title: REST API
href: zk/RESTful_APIs.md
type: markdown
snippet:
  The Docker Client is a thin API for making
    [REST API](RESTful_APIs.md) to the Docker Server. Any CLI
    command beginning `docker...` is an API request to the server.


title: zk/Docker_architecture
href: zk/Docker_architecture
type: wiki-link
snippet:
  Cloud-based or virtual server (virtual machine), basically a hypervisor
    (compare [[zk/Docker_architecture]])


title: electric current
href: zk/Current.md
type: markdown
snippet:
  Magnetism is a physical property produced by the _motion_ of electric charge,
  > which of course, is the same thing as
  > [electric current](Current.md)


title: shell session
href: zk/Shell-sessions-e6dd743dec1d4fe3b1ee672c8f9731f6
type: markdown
snippet:
  Every time a
    [shell session](Shell-sessions-e6dd743dec1d4fe3b1ee672c8f9731f6)
    spawns, a process takes place to gather and compile information that should be
    available to the shell process and its child processes. It obtains the data
    for these settings from a variety of different files and settings on the
    system.


title: shell session
href: zk/Shell-sessions-e6dd743dec1d4fe3b1ee672c8f9731f6
type: markdown
snippet:
  You can also add variables to config files that run on login such as your user
  `.bashrc` / `.zshrc` . This is obviously best for when you want the variables to
  persist and be accessible within every
  [shell session](Shell-sessions-e6dd743dec1d4fe3b1ee672c8f9731f6).


title: solution
href: zk/Algebra key terms.md#678811
type: markdown
snippet:
  Two equations are equivalent if they have the same
  > [solution](Algebra%20key%20terms.md#678811) set.


title: solution
href: zk/Algebra key terms.md#678811
type: markdown
snippet:
  $$ x - 4 = 3
  $$
  The [solution](Algebra%20key%20terms.md#678811) to this equation is $7$
  $$ x -
  4 (+4) = 3 (+ 4) $$


title: solution
href: zk/Algebra key terms.md#678811
type: markdown
snippet:
  $$ x + 4 = 9
  $$
  The [solution](Algebra%20key%20terms.md#678811) to this equation is $5$.
  $$ x +
  4 (-4) = 9(-4) $$


title: solution
href: zk/Algebra key terms.md#678811
type: markdown
snippet:
  $$x \cdot 2 = 10  $$
  The [solution](Algebra%20key%20terms.md#678811) to this equation is $5$.
  $$
  (x \cdot 2) \cdot 3 = 10 \cdot 3 $$ Here we have multiplied each side of the
  equation by $3$. If $x =5$ then


title: solution
href: zk/Algebra key terms.md#678811
type: markdown
snippet:
  $$x \cdot 3 = 18  $$
  The [solution](Algebra%20key%20terms.md#678811) to this equation is $6$.
  $$\frac{x
  \cdot 3}{3} = \frac{18}{3}
  $$
  Here we have divided each side of the equation by $3$. If $x$ is 6, then
  $$\frac{6
  \cdot 3}{3} = 6$$
  $$\frac{18}{3} = 6 $$


title: useEffect
href: zk/useEffect.md#cleanup-functions
type: markdown
snippet:
  As the warning suggests, this can be resolved using the cleanup parameter within
  [useEffect](useEffect.md#cleanup-functions).


title: kernel
href: zk/The_Kernel.md
type: markdown
snippet:
  A running Node application is a single running process. Like everything that
  happens within the OS, a process is managed by the
  [kernel](The_Kernel.md) that dispatches operations to the CPU
  in a clock cycle. A thread is a sequence of code that resides within the process
  and utilises its memory pool (the amount of memory assigned by the kernel to the
  Node process). The Event Loop runs on CPU ticks: a tick is a single run of the
  Event Loop.


title: call stack
href: zk/Call_stack.md
type: markdown
snippet:
  The Event Loop comprises six phases. The Event Loop starts at the moment Node
  begins to execute your `index.js` file or any other application entry point.
  These six phases create one cycle, or loop, equal to one **tick**. A Node.js
  process exits when there is no more pending work in the Event Loop, or when
  `process.exit()` is called manually. A program only runs for as long as there
  are tasks queued in the Event Loop, or present on the
  [call stack](Call_stack.md).


title: call stack
href: zk/Call_stack.md
type: markdown
snippet:
  At the beginning of this phase the Event Loop updates its own time. Then it
       checks a queue, or pool, of timers. This queue consists of all timers that
       are currently set. The Event Loop takes the timer with the shortest wait
       time and compares it with the Event Loop's current time. If the wait time
       has elapsed, then the timer's callback is queued to be called once the
       [call stack](Call_stack.md) is empty.


title: https://blog.appsignal.com/2022/07/20/an-introduction-to-multithreading-in-nodejs.html
href: https://blog.appsignal.com/2022/07/20/an-introduction-to-multithreading-in-nodejs.html
type: implicit
snippet:
  https://blog.appsignal.com/2022/07/20/an-introduction-to-multithreading-in-nodejs.html
  https://school.geekwall.in/p/Bk2xFs1DV


title: variables
href: zk/Variables_and_data_types.md
type: markdown
snippet:
  We use most frequently for returning the value of stored
  [variables](Variables_and_data_types.md).
  Techically we do not have to use the braces, we can retrieve with just `$var`
  however it's better to use them to minimise interpretation fuck-ups which happen
  a lot.


title: sub-shell
href: zk/Shell_sessions.md
type: markdown
snippet:
  Command substitution (circle-brackets) allows us to put the output of one
  command inside another. Bash runs the bracketed command in a
  [sub-shell](Shell_sessions.md) and then returns it
  to the main user shell.


title: equivalent
href: zk/Equivalent fractions.md
type: markdown
snippet:
  When we divide by the common divisor is acts as a divisor. When we multiply by
  the common divisor it acts as a factor. The fact that the fractions are
  [equivalent](Equivalent%20fractions.md) in both cases indicates that the
  properties are equivalent.


title: CPU Architecture
href: zk/CPU_architecture.md#arithmetic-logic-unit
type: markdown
snippet:
  Now the command will be executed. The operand is copied to the Memory Address
  Register and then passed to the Memory Data Register and the command is carried
  out by the ALU. The activities of ALU are covered in
  [CPU Architecture](CPU_architecture.md#arithmetic-logic-unit)
  and the notes on
  [Logic Gates](Logic_gates.md).


title: registers
href: zk/CPU_architecture.md#registers
type: markdown
snippet:
  If the instruction is iterative (e.g. adding two numbers and then multiplying
    by another number), the instruction will tell the CPU to store the interim
    first value in the CPU's
    [registers](CPU_architecture.md#registers). As
    these are part of the CPU, the data can be retrieved more readily. If the
    value is not expected to be used again immediately, it goes to the DRAM or
    harddisk.


title: redirect
href: zk/Redirection.md
type: markdown
snippet:
  They are typically used when you want to
  [redirect](Redirection.md) the output of the
  standard/input /output/error somewhere, e.g a file or as input to another
  program. A classic case is `[some_command] > /dev/null 2>&1`


title: $0
href: zk/Passing_arguments_and_options_to_Bash_scripts.md#passing-arguments
type: markdown
snippet:
  They are all technically "files" which are open and which append themselves to
  every process that can run in the shell. For any command or program that you
  run, you will be able to access `0`, `1` and `2` for them. In this way they are
  similar to variables like
  [`$0`](Passing_arguments_and_options_to_Bash_scripts.md#passing-arguments)
  and
  [`$@`](Passing_arguments_and_options_to_Bash_scripts.md#passing-arguments).
  They have a universal meaning within the context of the shell runtime.


title: database
href: zk/Basic_database_concepts.md
type: markdown
snippet:
  A filesytem is a form of [database](Basic_database_concepts.md); it
  > supplies the structure to transform a simple block device into the
  > sophisticated hierarchy of files and subdirectories that users can understand.


title: swap
href: zk/Swap_space.md
type: markdown
snippet:
  It shows my root and home filesystems and my
  [swap](Swap_space.md) file. Note that we use the UUID
  to name the partition rather than its name in `/dev/`. The order of the
  parameters is as follows:


title: syntactic
href: zk/Syntax_of_sentential_logic.md
type: markdown
snippet:
  Derivation rules are
  [syntactic](Syntax_of_sentential_logic.md) rather
  than semantic. They are applied on the basis of their form rather than on the
  basis of the truth conditions of the sentences they are applied to.


title: passing arguments to scripts
href: zk/Passing_arguments_to_Bash_scripts.md
type: markdown
snippet:
  We can access all the arguments passed to a function using the `$@` syntax we
  encountered before when
  [passing arguments to scripts](Passing_arguments_to_Bash_scripts.md).
  (Here a function is a kind of script in miniature so the process is the same.)


title: equivalent
href: zk/Equivalent fractions.md
type: markdown
snippet:
  Let $a,b$ be any integers. The following three fractions are
  > [equivalent](Equivalent%20fractions.md):
  > $$\frac{-5}{15}, \frac{5}{-15}, - \frac{5}{15}$$


title: hardware simulator
href: zk/Hardware_simulation.md
type: markdown
snippet:
  The hardware designer specifies a chip's logic by writing an HDL program which
  is then rigorously tested. At this stage, a
  [hardware simulator](Hardware_simulation.md) takes the
  HDL program as input and creates a software representation of the chip logic.
  The designer can instruct the simulator to test the virtual chip on various sets
  of inputs. This is done to check the chip's functionality but also to benchmark
  a variety of other parameters such as speed of computation and energy
  consumption.


title: input and output pins
href: zk/Integrated_circuits.md
type: markdown
snippet:
  In an HDL program we distinguish internal pins along with the standard
  [input and output pins](Integrated_circuits.md).
  At the level of the interface, we are concerned only with input and output pins
  (in the example program these are `a`, `b` and `out`). It is at the level of the
  implementation that internal pins are encountered. In the example these are the
  connections between, e.g. the AND and NOT gates such as
  `And (a=a, b-notb, out=w1)`. This means the AND gate is receiving through its
  `a` pin the input `a` value and through its `b` pin the value of `b` inverted by
  a NOT. `out` is the value that is computed based on the input pins of `a` and
  `b`.


title: Boolean function
href: zk/Boolean_functions.md
type: markdown
snippet:
  Along with the HDL file we also create a test file. This runs the chip against
  the inputs we supply, these will typically be equivalent to the (left-hand)
  truth-values column in a truth table which is the same as the parameters passed
  to a [Boolean function](Boolean_functions.md), for
  example:


title: equivalent
href: zk/Equivalent fractions.md
type: markdown
snippet:
  Whenever we increase a fraction, the resultant fraction will always be
  > [equivalent](Equivalent%20fractions.md) to the fraction we started with.


title: tables
href: zk/Relational_database_architecture.md#table
type: markdown
snippet:
  Although Mongo is not a relational database it has a structure that we can
  understand in relation to that paradigm. A **database** is obviously the overall
  structure. It comprises **collections** which are organised sets of data that
  are analagous to [tables](Relational_database_architecture.md#table)
  in RDBs. Within each collection are a series of **documents** which we can think
  of as being equivalent to [rows](Relational_database_architecture.md)
  in RDB table: units that comprise the collection.


title: sort
href: zk/Sorting_lists_in_Python.md
type: markdown
snippet:
  Assuming the sub-lists have an identical structure, you can
  [sort](Sorting_lists_in_Python.md) them by
  a common property by passing a
  [lambda function](Lambdas_in_Python.md) to
  the `key` value of `sorted()` and `.sort()`.


title: map
href: zk/Map_and_filter_in_Python.md
type: markdown
snippet:
  Below we use
  [map](Map_and_filter_in_Python.md) and a
  [lambda function](Lambdas_in_Python.md) to
  convert the first element of each iner list from a Unix timestamp to a readable
  string:


title: dictionary comprehension
href: zk/List_comprehension_etc.md#dictionary-comprehension
type: markdown
snippet:
  Accordingly, we create a dictionary which uses the unique key in each list as
  the key of each dictionary entry via
  [dictionary comprehension](List_comprehension_etc.md#dictionary-comprehension)
  that loops through each value in the inner lists of the multidimensional array.
  We then parse the values of the dictionary into a list.


title: CREATE TABLE
href: zk/Create_an_SQL_table.md
type: markdown
snippet:
  The output will be represented as a table but it is virtual, not an actual
  table. (If you wish to actually create a table or a view off the back of a join
  operation you should combine the join with the
  [`CREATE TABLE`](Create_an_SQL_table.md) command etc.)


title: REST APIs
href: zk/RESTful_APIs.md#rest
type: markdown
snippet:
  The best way to think of GraphQL architecturally is to think of it as a
  > different technique for instantiating the _uniform interface_, _client/server
  > decoupling_, and _layered-system architecture_ contraints of traditional
  > [REST APIs](RESTful_APIs.md#rest). However, instead of making
  > GET or POST requests to a REST endpoint URL and passing parameters, you send a
  > structured query object.


title: resistor
href: zk/Resistance.md#resistors
type: markdown
snippet:
  An LED diode lights up when the right amount of current flows through it. A
  standard LED has a maximum current of 20mA. An appropriate
  [resistor](Resistance.md#resistors)
  must therefore be added to the circuit to ensure the current doesn't exeedd this
  amount.


title: map, filter
href: zk/Map_and_filter_in_Python.md
type: markdown
snippet:
  They are most often used unnamed with the functional methods
  [map, filter](Map_and_filter_in_Python.md)
  and reduce.


title: NOR
href: zk/Logic_gates.md#nor-gate
type: markdown
snippet:
  The circuit diagram latch symbol obviously encapsulates more complex
  functionality that occurs at the sub-circuit level. We will demonstrate how this
  functionality can be achieved with two
  [NOR](Logic_gates.md#nor-gate) gates.


title: map and filter
href: zk/Map_and_filter_in_Python.md
type: markdown
snippet:
  Since its introduction to the language, the same functionality has become
  achievable by using functional methods like
  [`map` and `filter`](Map_and_filter_in_Python.md),
  utilising [lambdas](Lambdas_in_Python.md)
  however list comprehension is often more straightforward and easier to read.


title: test
href: zk/Test_values_in_Bash.md
type: markdown
snippet:
  Here we pass all the elements of the array to a
  [test](Test_values_in_Bash.md) condition which
  tests for an empty string.


title: function
href: zk/Functions_in_Bash.md
type: markdown
snippet:
  When you pass an array as an argument to a
  [function](Functions_in_Bash.md) it will not
  immediately be understood to be an array.


title: loop through each character in a string
href: zk/Strings_in_bash.md#loop-through-each-character-in-a-string
type: markdown
snippet:
  We are leveraging this aspect of Bash when we
  [loop through each character in a string](Strings_in_bash.md#loop-through-each-character-in-a-string).


title: pins
href: zk/Integrated_circuits.md
type: markdown
snippet:
  Logic gates are the basic building blocks of digital computing. **A logic gate
  is an electrical circuit that has one or more than one input and only one
  output.** The input and output points of the gate are
  [pins](Integrated_circuits.md) The
  input controls the output and the logic determining which types of input
  (on/off) lead to specific outputs (on/off) is isomorphic with the
  truth-conditions of the
  [Boolean connectives](Truth-functional_connectives.md) specifiable in
  terms of [truth tables](Truth-tables.md).


title: transistor
href: zk/Transistors.md
type: markdown
snippet:
  Physically, what 'travels through' the gates is electrical current and what
  constitutes the 'gate' is a
  [transistor](Transistors.md)
  responding to the current. Going up a level of abstraction, the current/ charge
  is identified with a
  [bit](Binary_units_of_measurement.md#binary-units-of-measurement).
  It is bits that go into the gate and bits which come out: binary information
  that may be either 1 or 0.


title: Adders
href: zk/Half_adder_and_full_adder.md
type: markdown
snippet:
  An example of a composite gate would be a three-way AND. An AND with three
  inputs rather than the standard two that furnish the elementary AND gate. This
  gate would output 1 when all three gates have the value 1 and 0 otherwise.
  [Adders](Half_adder_and_full_adder.md)
  and [latche>s](Latches.md) whilst
  being
  [integrated circuits](Integrated_circuits.md)
  are also, technically speaking, composite gates.


title: hardware abstraction
href: zk/Hardware_abstraction_and_modularity.md
type: markdown
snippet:
  Importantly, a single interface may be implemented in a variety of ways. There
  > is a one-to-many relationship at work here. From the point of view of the user
  > interface these differences should not be detectable. This is another example
  > of
  > [hardware abstraction](Hardware_abstraction_and_modularity.md)


title: contradiction
href: zk/Logical_truth_and_falsity.md#logical-falsity
type: markdown
snippet:
  A
  [contradiction](Logical_truth_and_falsity.md#logical-falsity)
  has very important consequences for reasoning because if a set of propositions
  is inconsistent, any other proposition is derivable from it.


title: negation elimination
href: zk/Negation_Elimination.md
type: markdown
snippet:
  Here we want to derive some proposition $Q$. If we can derive a contradiction
  from its negation as an assumption then, by the
  [negation elimination](Negation_Elimination.md)) rule, we can
  assert $Q$. This is why contradictions should be avoided in arguments, they
  'prove' everything which, by association, undermines any particular premise you
  are trying to assert.


title: derivation
href: zk/Formal proofs in propositional logic.md
type: markdown
snippet:
  Propositions $P$ and $Q$ are equivalent in a system of
  > [derivation](Formal%20proofs%20in%20propositional%20logic.md) for
  > propositional logic if $Q$ is derivable from $P$ and $P$ is derivable from
  > $Q$.


title: material biconditional
href: zk/Biconditional_Introduction.md
type: markdown
snippet:
  Note that the property of equivalence stated in terms of derivablity above is
  identical to the derivation rule for the
  [material biconditional](Biconditional_Introduction.md):


title: consistently
href: zk/Consistency.md
type: markdown
snippet:
  A proposition is logically indeterminate if it is neither logically true or
  logically false. This is to say: it can be both [consistently](Consistency.md)
  asserted and consistently denied.


title: logical consistency
href: zk/Logical_consistency.md
type: markdown
snippet:
  In distinguishing the properties of
  [logical consistency](Logical_consistency.md) and
  [validity](Validity_and_entailment.md) we make tacit use
  of the notion of **possibility**. This is because when we consider the validity
  of an argument we are assessing truth-conditions and this consists in asking
  ourselves what could or could not be the case: were it such that _P_, then it
  would be the case that _Q_. It is important to understand what possibility means
  in the context of logic and how it differs from what we might mean ordinarily
  when we use the term.


title: logical truth
href: zk/Logical_truth_and_falsity.md#logical-truth
type: markdown
snippet:
  A proposition is _logically necessary_ if it is true in every logically possible
  circumstance which is to say: true on every possible truth functional
  assignment. Necessity and
  [logical truth](Logical_truth_and_falsity.md#logical-truth)
  are therefore synonyms: anything that is logically true (a tautology) is true by
  necessity (could not be otherwise.)


title: consistency
href: zk/Logical_consistency.md
type: markdown
snippet:
  Neither proposition can be true because the truth of the first clause is
  contradicted by the second. By the principle of
  [consistency](Logical_consistency.md), it is not
  possible for both clauses to be true at once therefore the proposition, overall
  has the truth value of false.


title: validity
href: zk/Validity_and_entailment.md
type: markdown
snippet:
  If an argument contains premises which are logically false than this argument
    will perforce be valid. This is because one cannot consistently assert the
    premises and deny the conclusion which is the definition of
    [validity](Validity_and_entailment.md). However the
    _reason_ why one cannot consistently assert the premises and deny the
    conclusions is because one cannot consistently assert the premises - they
    conflict with each other. Furthermore as the argument contains false premises,
    it cannot be sound.


title: CPU
href: CPU_architecture
type: wiki-link
snippet:
  No matter how a program was originally written, it eventually needs to execute
  on a [[CPU_architecture|CPU]] as a series of machine language instructions.


title: ARM ISA
href: Instruction_set_architectures
type: wiki-link
snippet:
  The following machine instruction is an instruction that would be understood by
  an [[Instruction_set_architectures| ARM ISA]]. It moves the number `4` into the
  `r7` register:


title: Hexadecimal_number_system
href: Hexadecimal_number_system
type: wiki-link
snippet:
  Binary sequences are hard to understand, even if converted to the
  [[Hexadecimal_number_system]]. We have a better way of managing operations on
  the machine level: [assembly](Assembly.md)


title: global process object
href: zk/Process_object.md
type: markdown
snippet:
  To determine the current environment we can use the variable
  **`process.env.NODE_ENV`** from the
  [global process object](Process_object.md).
  This works universally regardless of the kind of Node app we are building.


title: environment variable
href: zk/Environmental_and_shell_variables.md
type: markdown
snippet:
  `NODE_ENV` is a bash
  [environment variable](Environmental_and_shell_variables.md)
  like any other. So we can set it in the normal way:


title: Config
href: zk/node-config
type: markdown
snippet:
  We use the third-party [Config](node-config)
  package to manage different configurations based on the environment.


title: environmental variables
href: zk/Environmental_and_shell_variables.md
type: markdown
snippet:
  We can do so securely by utilising
  [environmental variables](Environmental_and_shell_variables.md)
  alongside the config pacakage.


title: useEffect
href: zk/useEffect.md
type: markdown
snippet:
  Note that the syntax is similar to [useEffect](useEffect.md): there is a
  dependency array. The effect is the same: the function contained within
  `useCallback` will only re-rendered if one of these dependencies changes.
  However (see next section) the function will run in its memoized form on every
  click.


title: CPU
href: zk/CPU_architecture.md
type: markdown
snippet:
  When a [CPU](CPU_architecture.md) executes a program,
  it needs a place to store the program's **instructions** and **related data**.
  This is the role of memory.


title: transistor
href: zk/Transistors.md
type: markdown
snippet:
  In a DRAM cell, each bit of data is stored as a charge in a capacitor. The
  presence of charge represents a '1' bit and the absence of charge represents a
  '0' bit. Each of these cells is paired with a
  [transistor](Transistors.md) that
  controls the reading and writing of data.


title: charge
href: zk/Current.md
type: markdown
snippet:
  However capacitors lose
  [charge](Current.md) over time due
  to leaks. As a result DRAM is memory that needs to be refreshed (recharged)
  frequently. For this reason and because it only uses one transistor and
  capacitor per bit, DRAM is the less expensive form of volatile memory.


title: flip flops
href: zk/Flip_flops.md
type: markdown
snippet:
  SRAM uses [flip flops](Flip_flops.md)
  to store the bits. It also uses multiple transistors per bit. This makes it
  faster than DRAM but more expensive. DRAM is at least ten times slower than
  SRAM.


title: bootstrapping
href: zk/Boot_process.md
type: markdown
snippet:
  The following steps outline the way in which memory interacts with the processor
  during computational cycles, once the
  [bootstrapping](Boot_process.md) process has completed and
  the OS kernel is itself loaded into memory.


title: system bus
href: zk/Bus.md
type: markdown
snippet:
  The instruction at the first address is sent to the CPU, travelling accross
     the data bus part of the [system bus](Bus.md).


title: chipset
href: zk/Chipset_and_controllers.md
type: markdown
snippet:
  The CPU processes this instruction and then sends a request accross the
     address bus part of the system bus for the next instruction to the memory
     controller within the
     [chipset](Chipset_and_controllers.md).


title: DRAM
href: zk/Memory.md#dram
type: markdown
snippet:
  The chipset finds where this instruction is stored within the
     [DRAM](Memory.md#dram) and issues a request to
     have it read out and send to the CPU over the data bus.


title: logarithm
href: zk/Logarithms.md
type: markdown
snippet:
  We need to reverse this formula to find out how many bits we need to represent a
  given number of addresses. We can do this with a
  [logarithm](Logarithms.md).


title: hexadecimal numbers
href: zk/Hexadecimal_number_system.md
type: markdown
snippet:
  This is hard to parse so we can instead use
  [hexadecimal numbers](Hexadecimal_number_system.md)
  to represent the addresses:


title: binary encoding
href: zk/Binary_encoding.md
type: markdown
snippet:
  By itself, the the data is meaningless but we know from
  [binary encoding](Binary_encoding.md) that the
  binary data will correspond to some meaningful data, such as a character or a
  colour, depending on the encoding scheme used. The above table could correspond
  to the characters for 'A', 'B' and 'C' in the ASCII encoding scheme:


title: queue
href: zk/Queue.md
type: markdown
snippet:
  As the name indicates, its operating mode is that of a
  [queue](Queue.md) data structure offering first-in, first-out
  and other queue implementations.


title: ports
href: zk/Ports.md
type: markdown
snippet:
  We can control which middleware we run via the Node envrionment variables:
  `process.env` (see for instance [ports](Ports.md)).


title: add fractions with a common denominator
href: zk/Add_Subtract_Fractions.md#adding-subracting-fractions-with-common-denominators
type: markdown
snippet:
  But we know that when we
  [add fractions with a common denominator](Add_Subtract_Fractions.md#adding-subracting-fractions-with-common-denominators),
  we only add the numerators, not the denominators. Thus the calculation would
  actually be:


title: using factorization
href: zk/Multiplying_fractions.md#prime-factorisation-in-place
type: markdown
snippet:
  Then carry out the multiplication
     [using factorization](Multiplying_fractions.md#prime-factorisation-in-place):


title: invert and multiply
href: zk/Dividing_fractions.md#formal-specification-of-how-to-divide-fractions'
type: markdown
snippet:
  Again we convert the mixed fraction into an improper fraction and then follow
  the requisite rule, in the case of division this is to
  [invert and multiply](Dividing_fractions.md#formal-specification-of-how-to-divide-fractions').


title: ps
href: zk/Processes.md
type: markdown
snippet:
  We can use [ps](Processes.md) to list the
  currently running processes but it does not provide much information about the
  resource metrics or how the process changes over time. We can use `top` to get
  more information.


title: virtual memory
href: zk/Virtual_memory_and_the_MMU.md
type: markdown
snippet:
  The total amount of
      [virtual memory](Virtual_memory_and_the_MMU.md) used by
      the process including: program code, data, shared libraries, pages that have
      been swapped, pages that have been mapped but not used.


title: buffer
href: zk/Role_of_memory_in_computation.md#relation-between-cache-and-buffers
type: markdown
snippet:
  Total kbs currently in
        [buffer](Role_of_memory_in_computation.md#relation-between-cache-and-buffers)
        and not written


title: cache
href: zk/Role_of_memory_in_computation.md#relation-between-cache-and-buffers
type: markdown
snippet:
  Total amount of virtual memory in the
        [cache](Role_of_memory_in_computation.md#relation-between-cache-and-buffers)


title: swapped
href: zk/Swap_space.md
type: markdown
snippet:
  Distinguishes amount of memory
      [swapped](Swap_space.md) in (`si`) to memory and
      swapped out (`so`) to disk


title: kernel
href: zk/The_Kernel.md
type: markdown
snippet:
  A system call is when a process requests a service from the
  [kernel](The_Kernel.md), for instance an I/O operation to
  memory. We can trace these system calls with `strace`.


title: MMU
href: zk/Virtual_memory_and_the_MMU.md
type: markdown
snippet:
  We know that processes primarily interact with virtual memory in the form of
  pages which are then translated to physical blocks by the kernel via the
  [MMU](Virtual_memory_and_the_MMU.md). There are several tools
  which provide windows onto this process.


title: buffers and caches
href: zk/Role_of_memory_in_computation.md#relation-between-cache-and-buffers
type: markdown
snippet:
  `free` displays the total amount of free and¬used physical and swap memory in
  the system, as well as the
  [buffers and caches](Role_of_memory_in_computation.md#relation-between-cache-and-buffers)
  used by the kernel.


title: CPU
href: zk/CPU_architecture.md
type: markdown
snippet:
  The motherboard is the foundation of a computer. It allocates power and allows
  communication to and between the
  [CPU](CPU_architecture.md),
  [RAM](Memory.md),
  [harddisk](What_are_disks.md) and all other hardware
  components.


title: reducing fractions
href: zk/Reducing_fractions.md
type: markdown
snippet:
  It would be laborious to reduce such a large product using factor trees or the
  repeated application of divisors, as defined in
  [reducing fractions](Reducing_fractions.md). We can use a more efficient
  method. This method can be applied at the point at which we conduct the
  multiplication rather than afterwards once we have the product. We express the
  the initial multiplicands as prime factors:


title: query constants
href: zk/Apollo_Client.md#query-constants
type: markdown
snippet:
  As with queries and
  [query constants](Apollo_Client.md#query-constants) we
  wrap our mutation in a `gql` template string:


title: build context
href: zk/Creating_a_Docker_image.md#creating-a-docker-image
type: markdown
snippet:
  Each of the files listed below would be saved to the same source directory which
  would then form the basis of the
  [build context](Creating_a_Docker_image.md#creating-a-docker-image).


title: process.env
href: zk/Managing_environments.md
type: markdown
snippet:
  In the example, the database connection information in the Node source is coming
  from the
  [`process.env`](Managing_environments.md)
  object, which itself is sourcing the values `MYSQL_HOST`, `MYSQL_PASSWORD` etc
  from the Docker compose file. Therefore these values are hardcoded there.


title: type-guarding
href: zk/Type_guarding_and_narrowing.md
type: markdown
snippet:
  One way to get around it is to use better
  [type-guarding](Type_guarding_and_narrowing.md) and conditionality and to
  cover cases where the value may be undefined.


title: semantic versioning
href: zk/Semantic_versioning.md
type: markdown
snippet:
  `npm update` only updates from _current_ to _wanted_. In other words it only
  updates in accordance with your caret and tilde rules applied to
  [semantic versioning](Semantic_versioning.md).


title: $PATH
href: zk/The_PATH.md
type: markdown
snippet:
  When we run a program like `cd` or `npm` we don’t have to type `./cd.sh` or
  `./npm.sh`. This is because a reference to the program file is already in our
  [`$PATH`](The_PATH.md).


title: event listeners
href: zk/Events module.md#event-emitters
type: markdown
snippet:
  While we may not know the specific port, whatever it is, it will be accessible
  via the `PORT` environment variable. So we can use this when writing our
  [event listeners](Events%20module.md#event-emitters):


title: AWS API Gateway
href: zk/AWS_API_Gateway.md
type: markdown
snippet:
  We will do this using [AWS API Gateway](AWS_API_Gateway.md). We
  select "Add trigger" from the dashboard view and input basic settings:


title: factors
href: zk/Factors and divisors.md
type: markdown
snippet:
  For any whole number $n$ where $n \neq 1$, $n$ is prime if and only if its
  > sole [factors](Factors%20and%20divisors.md) are $1$ and $n$


title: any
href: zk/Any.md
type: markdown
snippet:
  `Object` is a valid type declaration in TS but it is not particularly helpful
  since it becomes similar to using [any](Any.md) given that most primitive
  types in JavaScripts prototypically inherit from an Object.


title: 8-bits long
href: zk/Binary_units_of_measurement.md
type: markdown
snippet:
  When Python runs in this implementation, code written in C converts it to
  bytecode (so-called because each instruction is
  [8-bits long](Binary_units_of_measurement.md)). This is a
  lower-level transliteration of Python is not meant to be understood by the CPU
  (since it is not binary) but rather to be run in the Python virtual machine
  which is equipped to understand bytecode. The Python Virtual Machine is
  therefore also known as "bytecode interpreter" or the CPython VM. The VM then
  converts bytecode into machine-executable code.


title: model
href: zk/Create_collections_and_documents_with_Mongoose.md#models
type: markdown
snippet:
  Now we will query the collection. This capability is provided via the Mongoose
  schema class we used to create the `Course`
  [model](Create_collections_and_documents_with_Mongoose.md#models).
  We have the following methods available to use from the schema:


title: HTTP request types
href: zk/HTTP_request_types.md
type: markdown
snippet:
  A basic example of a REST API would be a series of methods corresponding to the
  main [HTTP request types](HTTP_request_types.md).


title: split the contents into an array
href: zk/Split_into_array.md
type: markdown
snippet:
  `read` will parse line by line using a space (`\n`) as the default delimiter.
  You can use IFS to parse by other characters and/or
  [split the contents into an array](Split_into_array.md).


title: find
href: zk/Find.md
type: markdown
snippet:
  Here we use [find](Find.md) to collate the files in
  the current directory and then pipe them to read.


title: cherry-picking
href: zk/Cherry_picking_a_branch.md
type: markdown
snippet:
  The main difference between the two approaches is that
  [cherry-picking](Cherry_picking_a_branch.md) is a more selective
  process, where you can pick and choose specific commits that you want to include
  in another branch. This can be useful when you only want to apply specific
  changes or fixes from one branch to another, without including all the changes
  made in the original branch.


title: file descriptors
href: zk/File_descriptors_and_redirection.md
type: markdown
snippet:
  The `2>&1` argument is the content: any errors that the program may generate and
  try to show in stout. Notice we are using the
  [file descriptors](File_descriptors_and_redirection.md)
  `1` and `2`.


title: file descriptors
href: zk/File_descriptors.md
type: markdown
snippet:
  It is common practice to combine redirection with the
  [file descriptors](File_descriptors.md) to redirect
  the output of `stdout` and `stderr`. A common case is to
  [redirect error output to `/dev/null`](Redirect_to_dev_null.md).


title: greatest common divisor
href: zk/Factors and divisors.md#greatest-common-divisor
type: markdown
snippet:
  A fraction is said to be _reduced to its lowest terms_ if the
  > [greatest common divisor](Factors%20and%20divisors.md#greatest-common-divisor)
  > of the numerator and the denominator is $1$.


title: equivalent
href: zk/Equivalent fractions.md
type: markdown
snippet:
  Whenever we reduce a fraction, the resultant fraction will always be
  > [equivalent](Equivalent%20fractions.md) to the fraction we started with.


title: highest common divisor
href: zk/Factors and divisors.md#greatest-common-divisor
type: markdown
snippet:
  In the previous example the reduction took two steps: first we divided by two
  and then we divided by three. There is a more efficient way: find the
  [highest common divisor](Factors%20and%20divisors.md#greatest-common-divisor) of
  the numerator and denominator and then use this as the basis for the reduction.
  With this method, the reduction can be completed in a single step.


title: factors
href: zk/Factors and divisors.md#factors
type: markdown
snippet:
  Note how our earlier two divisors 2 and 3 are
  [factors](Factors%20and%20divisors.md#factors) of 6, showing the consistency
  between the two methods.


title: interchangeability of factors and divisors
href: zk/Factors and divisors.md
type: markdown
snippet:
  The two methods above are not very systematic and are quite heuristic. The third
  approach is more systematic and relies on the
  [interchangeability of factors and divisors](Factors%20and%20divisors.md).


title: factor
href: zk/Factors and divisors.md#factors
type: markdown
snippet:
  Instead of thinking asking what is the greatest common divisor of 18 and 24 we
  could ask: which single number can we multiply by to get 18 and 24? Obviously
  both numbers are in the six times table. This is therefore to say that 6 is a
  [factor](Factors%20and%20divisors.md#factors) of both: we can multiply some
  number by 6 to arrive at both 18 and 24. The numbers are 3 and 4 respectively:


title: prime factorization
href: zk/Prime factorization.md
type: markdown
snippet:
  A better method is to utilise [prime factorization](Prime%20factorization.md)
  combined with the canceling technique.


title: fraction with unlike terms
href: zk/Handling negative fractions.md#fractions-with-unlike-terms
type: markdown
snippet:
  This fraction is an instance of a
    [fraction with unlike terms](Handling%20negative%20fractions.md#fractions-with-unlike-terms).


title: fraction with like terms
href: zk/Handling negative fractions.md#fractions-with-like-terms
type: markdown
snippet:
  This fraction is an instance of a
    [fraction with like terms](Handling%20negative%20fractions.md#fractions-with-like-terms).


title: AWS Lambda handler function
href: zk/Lambda_handler_function.md
type: markdown
snippet:
  Let's walk through the above example making reference to the general structure
  of the
  [AWS Lambda handler function](Lambda_handler_function.md):


title: ACID principle
href: zk/ACID_principle.md
type: markdown
snippet:
  This is essential for carrying out operations across database tables and for
  creating and deleting database entires in accordance with the
  [ACID principle](ACID_principle.md). It is also a safeguard: it means
  you can always identify a record by itself and don't have to rely on generic
  queries to identify it.


title: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html
href: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html
type: markdown
snippet:
  See
  [https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html)


title: IAM user
href: zk/zk/AWS_User_management_and_roles.md#iam
type: markdown
snippet:
  You require an access key for the given
  [IAM user](zk/AWS_User_management_and_roles.md#iam). You should create an IAM
  account specific to the project with bounded permissions.


title: IAM
href: zk/zk/AWS_User_management_and_roles.md#iam
type: markdown
snippet:
  This information can be found in the Security Credentials section of the given
  [IAM](zk/AWS_User_management_and_roles.md#iam) user:


title: handler function
href: zk/Lambda_handler_function.md
type: markdown
snippet:
  This details the location of the [handler function](/Lambda_handler_function.md)
  which is contained at the path `hello-world/app.js`:


title: S3
href: zk/zk/AWS_S3.md
type: markdown
snippet:
  The packaging proces will first archive all of the project artefacts into a zip
  file and then upload that to [S3](zk/AWS_S3.md). A reference to this S3 entity
  is then provided to CloudFormation.


title: environmental and shell variables
href: zk/Environmental-and-shell-variables-04d5ec7e8e2b486a93f002bf686e4bbb
type: markdown
snippet:
  The type of shell session that you are currently in affects the
  [environmental and shell variables](Environmental-and-shell-variables-04d5ec7e8e2b486a93f002bf686e4bbb)
  that you can access. This is because the order in which configuration files are
  read on initialisation differs depending on the type of shell.


title: Lambda
href: zk/Lambda_programming_model.md
type: markdown
snippet:
  At the beginning you define a `StartAt` state which is the entrypoint of the
  state machine. This can be manually triggered, or more likely, triggered by
  another AWS service such as a
  [Lambda](Lambda_programming_model.md), an
  [API Gateway](AWS_API_Gateway.md) request or a messaging/queue
  event.


title: recursive
href: zk/Recursion.md
type: markdown
snippet:
  Goal analysis is a [recursive](Recursion.md) strategy which
  proceeds by using a 'goal' proposition to guide the construction of intermediary
  derivations.


title: valid
href: zk/Validity_and_entailment.md#validity
type: markdown
snippet:
  Assume that we want to show that an argument is
  [valid](Validity_and_entailment.md#validity). Then our
  ultimate goal is to derive the conclusion from the premises we are given. We
  first ask ourselves: _which propositions if we could derive them, would allow us
  to easily derive the conclusion_? (For example, these propositions might be two
  simple propositions that when combined with
  [Conjunction Introduction](Conjunction_Introduction.md) give us
  the conclusion.) Deriving these propositions then becomes the new intermediate
  goal.


title: Conjunction Introduction
href: zk/Conditional_Introduction.md
type: markdown
snippet:
  First, we consider what is the easiest possible way of achieving the proposition
  $(L \lor A) \land D$. Clearly it is to separately derive each disjunct
  ($L \lor A$ and $D$) and then combine them with
  [Conjunction Introduction](Conditional_Introduction.md). This
  provides us with our first goal: to derive each of the separate conjuncts.


title: Conjunction Elimination
href: zk/Conjunction Elimination.md
type: markdown
snippet:
  Let's start with $D$: where does it occur in the assumptions? It occurs in the
  compound $(\lnot N \rightarrow L) \land (D \leftrightarrow \lnot N)$, but only
  in the first conjunct. We can get this simply but applying
  [Conjunction Elimination](Conjunction%20Elimination.md).


title: Biconditional Elimination
href: zk/Biconditional_Elimination.md
type: markdown
snippet:
  Now we just need to get $D$ from the proposition at line 3. This is easy since
  we already have access to the consequent of the biconditional at line 1.
  Therefore we can apply
  [Biconditional Elimination](Biconditional_Elimination.md)) at line
  3 to get $D$. We are now halfway there:


title: Conjunction Elimination
href: zk/Conjunction_Elimination.md
type: markdown
snippet:
  Next we need to turn our attention to deriving $L \lor A$. How can we obtain $L$
  ? Well it is contained within the first conjunct of the assumption on line 2.
  Again, we can get this through the application of
  [Conjunction Elimination](Conjunction_Elimination.md). Now, how do
  we get $L$ from $(\lnot N \rightarrow L)$? Well, we already have the antecedent
  $\lnot N$ as an assumption on the first line, so we can use
  [Conditional Elimination](Conditional_Elimination.md) to derive
  $L$. These two steps give us:


title: Disjunction Introduction
href: zk/Disjunction_Introduction.md
type: markdown
snippet:
  Now we need to get from $L$ to $L \lor A$. This is really straightforward
  because by using
  [Disjunction Introduction](Disjunction_Introduction.md)) we can
  get from any sentence to a disjunction. Finally, having assembled all the
  constituent parts of the conjunction that is the conclusion, we can combine them
  with [Conjunction Introduction](Conjunction_Introduction.md) as we
  had planned at the outset.


title: Conjunction Introduction
href: zk/Conjunction_Introduction.md
type: markdown
snippet:
  The requirements here could easily mislead us. We see that the target
  proposition is a conjunction so we might think that the best strategy is to seek
  to derive each conjunct and then combine them via
  [Conjunction Introduction](Conjunction_Introduction.md)).


title: Biconditional Elimination
href: zk/Biconditional_Elimination.md
type: markdown
snippet:
  Actually, if we look more closely, there is a better approach. The target
  proposition is contained in the first premise as the consequent to the
  biconditional ($\lnot L \leftrightarrow [X \land (\lnot S \lor B)]$). A better
  approach is therefore to seek to derive the antecedent ($\lnot L$) and then use
  [Biconditional Elimination](Biconditional_Elimination.md) to
  extract the target sentence which is the consequent.


title: theorems
href: zk/Theorems_and_empty_sets.md#theorems-and-empty-sets
type: markdown
snippet:
  When we are proving
  [theorems](Theorems_and_empty_sets.md#theorems-and-empty-sets)
  we do not have a set of assumptions to work from when constructing the proof. We
  must derive the target sentence from the 'empty set' which is the target
  sentence itself. It is therefore like a process of reverse engineering.


title: Disjunction Elimination
href: zk/Disjunction_Elimination.md
type: markdown
snippet:
  Our starting assumption is to a disjunction. Thus we can apply
    [Disjunction Elimination](Disjunction_Elimination.md) to show
    that our goal sentence $\lnot(A \land B)$ follows from each of the disjuncts
    ($\lnot A$ and $\lnot B$) in dedicated sub-proofs. If we can do this, we have
    the right to derive $\lnot (A \land B)$.


title: Disjunction Elimination
href: zk/Disjunction_Elimination.md
type: markdown
snippet:
  Having done this, we can discharge the
    [Disjunction Elimination](Disjunction_Elimination.md) sub-proofs
    and derive $\lnot (A \land B)$ from $\lnot A \lor \lnot B$


title: Negation Elimination
href: zk/Negation_Elimination.md
type: markdown
snippet:
  We will do this by assuming the negation of what we want to prove
    ($\lnot (\lnot A \lor \lnot B)$) and then apply
    [Negation Elimination](Negation_Elimination.md) to get
    $\lnot A \lor \lnot B$.


title: Negation Elimination
href: zk/Negation_Elimination.md
type: markdown
snippet:
  This requires us to derive a contradiction. We get this on lines 23 and 24.
    This requires as previous steps that we have two sub-proofs that use
    [Negation Elimination](Negation_Elimination.md) to release $A$
    and $B$


title: list
href: zk/Lists_in_Python.md
type: markdown
snippet:
  The `split()` function in Python is used to divide a string into multiple parts
  at the occurrence of a given separator. This function returns a
  [list](Lists_in_Python.md) of substrings.


title: kernel
href: zk/The_Kernel.md
type: markdown
snippet:
  To use an existing disk partition as a swap you can run the command
  `mkswap [device]` and then `swapon [device]` to register the space with the
  [kernel](The_Kernel.md).


title: fstab
href: zk/Filesystems.md#fstab
type: markdown
snippet:
  You will want the swap to be activated every time the OS boots so add the
  following line to the [fstab](Filesystems.md#fstab),
  where `/sda3` is used as the example partition:


title: atomic and molecular propositions
href: zk/Atomic_and_molecular_propositions.md
type: markdown
snippet:
  These definitions provide a formal specification of the concepts of
  [atomic and molecular propositions](Atomic_and_molecular_propositions.md)
  introduced previously.


title: array
href: zk/Lists_and_arrays.md
type: markdown
snippet:
  Note: this syntax can also be used to test if a given element exists in an
  > [array](Lists_and_arrays.md).


title: pip
href: zk/Python_package_management.md
type: markdown
snippet:
  Pytest is the most popular testing library for Python. It is not included with
  the Python standard library so it must be installed with
  [pip](Python_package_management.md).
  While it does not include a declaration library, it is robust enough to handle
  most scenarios having a rich and expressive set of constructs and decorators
  that let you declare what your tests should do, under what conditions they
  should run, and how they should interact with the rest of your system.


title: memory management unit
href: zk/Virtual_memory_and_the_MMU.md#the-memory-management-unit-mmu
type: markdown
snippet:
  Modern CPUs include a
  > [memory management unit](Virtual_memory_and_the_MMU.md#the-memory-management-unit-mmu)
  > which provides the kernel with **virtual** memory. In this scenario, memory
  > isn't directly accessed by the process instead it works on the assumption that
  > is has access to the entire memory of the machine and this is then translated
  > into a map that is applied to the real memory and managed by the kernel.


title: derivation
href: zk/Formal_proofs_in_propositional_logic.md#derivation-rules
type: markdown
snippet:
  We know that when we construct a
  [derivation](Formal_proofs_in_propositional_logic.md#derivation-rules)
  we start from a set of assumptions and then attempt to reach a proposition that
  is a consequence of the starting assumptions. However it does not always have to
  be the case that the starting set contains members. The set can in fact be
  empty.


title: clock pulses
href: zk/Clock_signals.md
type: markdown
snippet:
  The circuit will have three memory components, each representing one bit of the
  3-bit number. When the
  [clock pulses](Clock_signals.md), the
  3-bit number increments by one. We need to synchronise the operation with a
  clock because each bit by itself is meaningless, it only gains meaning by the
  relation it sustains to the other two bits hence it must be kept in sync with
  them.


title: T flip-flop
href: zk/Flip_flops.md#t-flip-flops
type: markdown
snippet:
  This means that to construct a circuit that displays this behaviour we just have
  to use a
  [T flip-flop](Flip_flops.md#t-flip-flops)
  since the only state change we need is a single bit toggle three times that
  retains its value.


title: voltage
href: zk/Voltage.md
type: markdown
snippet:
  Thus instead of switches, modern digital circuits use transistors, a special
  electrical component that controls the flow of current in the manner of a switch
  where the 'off' and 'on' states are represented by
  [voltage](Voltage.md) values within
  set parameters.


title: AND
href: zk/Logic_gates.md#and-gate
type: markdown
snippet:
  For example to create an
  [AND](Logic_gates.md#and-gate) gate
  we would have two voltage inputs going into two transistors that are connected
  in sequence. The two transistors create a continuous line going from the
  collector of one to the emitter of the other. If either voltage input is low
  then the voltage of the combined line is low (equivalent to the circuit being
  broken) and there is no current flowing.


title: OR
href: zk/Logic_gates.md#or-gate
type: markdown
snippet:
  Below, an
  [OR](Logic_gates.md#or-gate) has been
  constructed with transistors. If a voltage is applied to the base of either
  transistor, the current reaches the V-out terminal.


title: logically determinant
href: zk/Logical_indeterminacy.md
type: markdown
snippet:
  We know that
  [logically determinant](Logical_indeterminacy.md)
  propositions express a truth value. When simple propositions are joined with a
  connective to make a compound proposition they also have a truth value. This is
  determined by the nature of the connective and the truth value of the
  constituent propositions. We therefore call connectives of this nature truth
  _functional_ connectives since the **truth value of the compound is a function
  of the truth values of its components**.


title: immediate sentential components
href: zk/Syntax of sentential logic.md
type: markdown
snippet:
  The core truth-tables tell us how to determine the truth-value of a molecular
  > sentence given the truth-values of its
  > [immediate sentential components](Syntax%20of%20sentential%20logic.md). And if
  > the immediate sentential components of a molecular sentence are also
  > molecular, we can use the information in the characteristic truth-tables to
  > determine how the truth-value of each immediate component depends n the
  > truth-values of _its_ components and so on.


title: consistent
href: zk/Consistency.md
type: markdown
snippet:
  Recall that a set of propositions is logically or truth-functionally
  [consistent](Consistency.md) just if there is at least one assignment of truth
  conditions which results in all members of the set being true. To identify
  consistency for a set of three propositions via the truth table approach we
  would need to construct a truth table with $2^3$ (8) rows. Assume that this set
  is consistent on one partial assignment only. This means that 87.5% of our rows
  are redundant, they are not required to prove the consistency of the set.
  However we can only know this and we can only be sure of consistency once we
  have gone through the process of generating an assignment for each row.


title: logical falsity
href: zk/Logical truth and falsity.md#logical-falsity
type: markdown
snippet:
  When we wish to assess
  [logical falsity](Logical%20truth%20and%20falsity.md#logical-falsity) we are not
  focused on sets however, we are interested in a property of a sentence. However
  we can easily construe single sentences as unit sets: sets with a single member.
  With this in mind and the above accounts of consistency and logical falsity we
  are equipped to express logical falsity in terms of truth-trees with the
  following rule:


title: logically true
href: zk/Logical truth and falsity.md#logical-truth
type: markdown
snippet:
  For a sentence $P$ to be
  [logically true](Logical%20truth%20and%20falsity.md#logical-truth), there must
  be no possible assignment in which $P$ is false. We express this informally by
  saying _it is not possible to consistently deny $P$._ We know that in terms of
  truth trees an inconsistent set is a closed tree therefore a unit set of ${ P }$
  is logically true if ${ \sim P }$ is a closed tree. This is to say: if the
  negation of $P$ is inconsistent.


title: Indeterminacy
href: zk/Indeterminacy.md
type: markdown
snippet:
  [Indeterminacy](Indeterminacy.md) follows from the two definitions above; we do
  not require any additional apparatus. We recall that a sentence $P$ is logically
  indeterminate just if it is neither logically true or logically false. Thus the
  truth tree for an indeterminate sentence is straightforward:


title: logically equivalent
href: zk/Logical equivalence.md
type: markdown
snippet:
  Recall that $P$ and $Q$ are [logically equivalent](Logical%20equivalence.md)
  just if there is no truth assignment on which one is true and the other is
  false. We know from the
  [material biconditional shorthand](Corresponding%20material%20and%20biconditional.md#corresponding-material-biconditional)
  that this state of affairs can be expressed as $P \equiv Q$ and that if this
  compound sentence is true on every assignment then both simple sentences are
  equivalent. But ‘true on every assignment’ is another way of saying _logically
  true_ since there is no possibility of a false assignment. We already know what
  logical truth looks like as a truth tree: it is a closed tree for the negation
  of the sentence being tested. Therefore, to test the logical equivalence of two
  sentences it is necessary to construct a truth tree for the negation of the
  sentences conjoined by the biconditional (i.e. $\sim (P \equiv Q)$ )and see if
  this results in a closed tree. If it does, the two sentences are logically
  equivalent.


title: entailment
href: zk/Validity and entailment.md#entailment
type: markdown
snippet:
  Let’s remind ourselves of the meaning of truth-functional
  [entailment](Validity%20and%20entailment.md#entailment) and
  [validity](Validity%20and%20entailment.md#validity) and the relation between the
  two. $\Gamma$ $\vdash$ $P$ is true if and only if there is no truth-assignment
  in which every member of $\Gamma$ is true and $P$ is false. Entailment is
  closely related to validity; it is really just a matter of emphasis: we say that
  $\Gamma$ are the premises and $P$ is the conclusion and that this is a valid
  argument if there is no assignment in which every member of $\Gamma$ is true and
  $P$ is false.


title: binary encoding
href: Binary_encoding
type: wiki-link
snippet:
  Two's complement divides the available word length (see
  [[Binary_encoding|binary encoding]]) into two subsets: one for negative integrs
  and one for positive integers.


title: signed_and_unsigned_numbers
href: Signed_and_unsigned_numbers
type: wiki-link
snippet:
  [[Signed_and_unsigned_numbers|signed_and_unsigned_numbers]],
  [[Binary_addition|binary addition]], [[Signed_magnitude_representation]]


title: query
href: zk/Querying_a_collection.md
type: markdown
snippet:
  With this approach we first execute a
  [query](Querying_a_collection.md) to retrieve the document we
  want to edit and then make the change. We use the `findById` method to identify
  the document by its UUID and then `set` to update specified properties on the
  document. The `set` method is one of many operators that can be used to update
  values. For example there is also built-in operators for increment, renaming,
  multiplying values.


title: middlewear
href: zk/Middleware.md
type: markdown
snippet:
  Next we introduce GraphQL as a piece of Node.js
  [middlewear](Middleware.md), with the
  `app.use()` method.


title: original schema
href: zk/Apollo_Server.md#example-schema
type: markdown
snippet:
  In order to demonstrate arguments we need to expand the
  [original schema](Apollo_Server.md#example-schema).


title: server-side process
href: zk/Apollo_Server.md
type: markdown
snippet:
  Now we have to create a resolver for our new `track` query. We will quickly run
  through the [server-side process](Apollo_Server.md).


title: useQuery hook
href: zk/Apollo_Client.md#usequery-hook
type: markdown
snippet:
  We can now write a proper query using the
  [useQuery hook](Apollo_Client.md#usequery-hook) from
  Apollo Client, with variables.


title: simple example
href: zk/Apollo_Client.md#query-constants
type: markdown
snippet:
  Note that in contrast to the
  [simple example](Apollo_Client.md#query-constants)
  because we are using variables, we have to pass-in an additional options object
  with the query constant that specifies our variables.


title: Joi
href: zk/Validation.md
type: markdown
snippet:
  What is the relationship between this Mongoose validation and the
  [Joi](Validation.md) validation that we
  use when validating API requests in Node/Express? They complement each other. We
  use Joi to validate the client request to the API. If this is valid, the process
  would then move onto the next stage which would be transforming the data from a
  REST request to a database request implemented through Mongoose, where a second
  layer of validation would appy. We would also have validation on the
  client-side.


title: Virtual memory
href: zk/9_VirtualMemory.html#:~:text=Virtual memory also allows the,to more than one process
type: markdown
snippet:
  [Virtual memory](9_VirtualMemory.html#:~:text=Virtual%20memory%20also%20allows%20the,to%20more%20than%20one%20process)


title: partitions
href: zk/Partitions.md
type: markdown
snippet:
  A disk is divided up into [partitions](Partitions.md)
    which are subsections of the overall disk. The kernel presents each partition
    as a [block device](Devices.md) as it would with an entire
    disk.


title: user space
href: zk/User_Space.md
type: markdown
snippet:
  The **filesystem** is a database of files and directories: this comprises the
    bulk of the partition and is what you interact with in
    [user space](User_Space.md) when reading and writing data.


title: multiplicands
href: zk/Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd
type: markdown
snippet:
  When **multiplying** whole numbers the placement of the
  [multiplicands](Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd)
  does not affect the
  [product](Symbols-and-formal-conventions-80aeaf1872f94a0d97a2e8d07e3855bd).


title: expansion
href: zk/Expansions_and_substitutions.md
type: markdown
snippet:
  Note: we do not use a dollar-sign when referring to variables within
  > arithmetic evaluation, there is no need. If we do, we get an error. This is
  > because we are using an
  > [expansion](Expansions_and_substitutions.md),
  > therefore the variables are already being interpreted as variables.


title: printing-values-in-c
href: zk/printing-values-in-c.md
type: markdown
snippet:
  Format specifiers define the type of data to be printed on standard output. You
  need to use format specifiers whenever you are
  [printing-values-in-c](printing-values-in-c.md).


title: event queue
href: zk/Event_loop.md
type: markdown
snippet:
  Every method associated with `fs` has a _blocking_ and _asynchronous_
  implementation. The former obviously blocks the
  [event queue](Event_loop.md), the
  latter does not.


title: event emitter
href: zk/events.md
type: markdown
snippet:
  An HTTP server is another instance of an
  [event emitter](events.md)). It
  therefore has all the same methods as the `EventEmitter` class: `on`, `emit`,
  `addListener` etc. This demonstrates again how much of Node's core functionality
  is based on event emitters.


title: format specifier
href: zk/zk/format-specifiers-in-c.md
type: markdown
snippet:
  The `%d` is an example of a [format specifier](./zk/format-specifiers-in-c.md).
  It is the decimal integer format specifier.


title: event listeners
href: zk/events.md
type: markdown
snippet:
  Typically we want to write and read data that the user provides. To do this we
  need to wait on that event. So we use Node's asynchonous
  [event listeners](events.md). We wait
  on the `data` event:


title: Application state management
href: zk/Application_state_management.md
type: markdown
snippet:
  In the examples above we have only been consuming state that is owned by the
  provider however in most scenarios you will also want to update the state from a
  consumer. This is best achieved by combining `useContext` with a reducer and is
  detailed in [Application state management](Application_state_management.md).


title: lifecyle methods
href: zk/Lifecycle_methods.md
type: markdown
snippet:
  `useEffect` enshrines but also simplifies the
  [lifecyle methods](Lifecycle_methods.md) that are used with
  class-based React components.


title: lifecycle methods
href: zk/Lifecycle_methods.md
type: markdown
snippet:
  The syntax of the `useEffect` hook also allows you to handle cleanup: something
  you want to do when the component unmounts (another example of how this hook
  recasts the traditional [lifecycle methods](Lifecycle_methods.md))
  . In addition to running on unmount, the cleanup function will run before the
  effect runs again (i.e. when it runs in response to a change in one of the
  elements of the dependency araray). This is chiefly used to prevent
  [memory leaks](Memory_leaks.md) and the
  ['update on unmounted component error'](Errors.md#state-update-on-unmounted-component).


title: zk/Elastic_Compute_Cloud
href: zk/Elastic_Compute_Cloud
type: wiki-link
snippet:
  AWS VPC is used to create a virtual network. This is typically used in concert
  with [[zk/Elastic_Compute_Cloud]] to manage connections to a virtual server both
  privately and accross the internet.


title: Arithmetic_Logic_Unit
href: Arithmetic_Logic_Unit
type: wiki-link
snippet:
  A family of CPUs that implement the core instructions of the
    [[Arithmetic_Logic_Unit]] in the same way share an ISA. Any software built for
    that ISA will work on any CPU that implements the ISA


title: word-size
href: zk/Signed_and_unsigned_numbers.md
type: markdown
snippet:
  There have been different, successive generations of x86 corresponding to
    their [word-size](Signed_and_unsigned_numbers.md): 16-bit, 32-bit, 64-bit.
    Word size here just means how many bits the processor can work with at a time.
    A 34-bit processor can operate on values that are 32 bits in length. This
    means it has 32bit [[CPU_architecture#registers|registers]], a 32-bit data
    [[Bus|bus]], a 32-bit address bus and so on.


title: logic gates
href: zk/Logic_gates.md
type: markdown
snippet:
  The half adder and full adder are components of digital circuits that enable us
  to carry out binary addition. Using adders and half adders we can add two binary
  numbers together. Adders are a type of [integrated circuit]() comprising certain
  [logic gates](Logic_gates.md) where the arrangement allows for the
  representation of the addition of bits.


title: XOR
href: zk/Logic_gates.md#xor-gate
type: markdown
snippet:
  We can see that the sum bit column replicates the truth-conditions of
  [XOR](Logic_gates.md#xor-gate):


title: memory
href: zk/Memory.md
type: markdown
snippet:
  | Bus type      | Description                                                                                                                                                                                                        |
  | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
  | System bus    | The primary pathway between the CPU and [memory](Memory.md). It comprises the **data bus** that transfers data from the memory to the CPU and the **address bus** which transmits requests from the CPU to memory. |
  | Internal bus  | Connects local devices for example the harddisk to the CPU.                                                                                                                                                        |
  | External bus  | Connects peripheral devices such as disks and printers to the [motherboard](Motherboard.md)                                                                                                                        |
  | Expansion bus | Allows expansion boards to access the CPU and memory.                                                                                                                                                              |
  | Frontside bus | Main computer bus that determines data transfer rate speed and is the primary data transfer path between the CPU, RAM and other [motherboard](Motherboard.md) devices.                                             |
  | Backside bus  | Transfers secondary cache (L2 cache) data at faster speeds, allowing more efficient CPU operations                                                                                                                 |


title: heap memory
href: Heap_memory
type: wiki-link
snippet:
  Along with [[Heap_memory|heap memory]] heap memory, programs make use of
    _stack memory_ during runtime.


title: stack data structure
href: Stacks
type: wiki-link
snippet:
  Similarly to the [[Stacks|stack data structure]], it works on the basis of LIFO:
  the last item put on the stack is the first item to be withdrawn.


title: register
href: CPU_architecture#registers
type: wiki-link
snippet:
  A **stack pointer** is used to manage the items in the stack. This value is
  stored in a [[CPU_architecture#registers|register]] and its value is the memory
  address of the item currently on the top of the stack. Note: _not_ the value
  itself, the _address_ of the value.


title: memory leaks
href: Memory_leaks
type: wiki-link
snippet:
  Local variable storage: storing the variables local to a function's scope and
     removing them once the function returns, avoiding
     [[Memory_leaks|memory leaks]]


title: Memory_leaks
href: Memory_leaks
type: wiki-link
snippet:
  Whereas stack memory with it's LIFO structure has memory management built-in
  when programs allocate memory from the heap they must manually deallocate it
  when it is no longer required. This process of "freeing memory" is known as
  _garbage collection_. In a language like C, this is the explicit concern of the
  programmer and is not abstracted away. Failure to properly manage garbage
  collection is what causes [[Memory_leaks]].


title: ways around this
href: https://thom4.net/2014/self-contained-node-scripts/
type: markdown
snippet:
  If you use any module not in the Node core, you will need to have this installed
  globally for it to work. (There are
  [ways around this](https://thom4.net/2014/self-contained-node-scripts/) for Node
  scripts you publish but for personal scripts this doesn't matter.)


title: superuser
href: zk/User_Space.md#root-user-superuser
type: markdown
snippet:
  This is the domain of the [superuser](User_Space.md#root-user-superuser). The
    part of the filesystem that you need sudo priveleges to access and where you
    manage users


title: kernel
href: zk/The_Kernel.md
type: markdown
snippet:
  Most standard partition tables allow for primary, extended and logical
  partitions. The primary partition is the part of the harddisk that contains the
  operating system and is thus described as 'bootable' and may be called the 'boot
  partition'. During the bootstrapping process this is injected into memory as the
  [kernel](The_Kernel.md).


title: difference of potential
href: zk/Voltage.md
type: markdown
snippet:
  When there is an excess of electrons at one terminal (i.e. negatively charged
  atoms) and a deficiency of electrons at the other terminal (i.e. positively
  charged atoms), a [_difference of potential_](Voltage.md) exists between the two
  terminals.


title: current
href: zk/Current.md
type: markdown
snippet:
  We noted in the discussion of [current](Current.md) that current flows when
  there is a difference of potential between two points with negatively charged
  atoms at one point and positively charged atoms at the other.


title: form of energy
href: zk/Voltage_sources.md
type: markdown
snippet:
  Voltage is the application of this energy. Any
  [form of energy](Voltage_sources.md) that dislodges electrons from atoms can be
  used to produce current. Thus:


title: battery
href: zk/Cells_and_batteries.md
type: markdown
snippet:
  Given that voltage is the force that generates current, it would be natural to
  think that voltage only exists when a voltage source (such as a
  [battery](Cells_and_batteries.md)) is connected to a circuit. This however is
  not the case. Even if a 9V battery isn't connected to anything it still has a
  difference of potential of 9-volts accross its terminals. Remember voltage is
  _potential energy_ not just the actualisation of that energy.


title: Ohm's Law
href: zk/Ohms_Law.md
type: markdown
snippet:
  We can work out the voltage of the remaining voltage points by inverting
  [Ohm's Law](Ohms_Law.md): $V = I \times R$:


title: amp
href: zk/Current.md#formal-expression
type: markdown
snippet:
  One ohm is the resistance of a circuit or circuit element that permits a
  > steady current flow of one [amp](Current.md#formal-expression) (one
  > coulomb/second) when one [volt](Voltage.md#voltage) is applied to the circuit.


title: batteries
href: zk/Cells_and_batteries.md
type: markdown
snippet:
  The chemical creation of current is the physics behind
  [batteries](Cells_and_batteries.md). Chemical current production produces
  currents on a smaller and less industrial scale than generators.


title: exception
href: zk/Error_handling_in_Python.md
type: markdown
snippet:
  Obviously file access can raise errors - typically when the file you want to
  access does not exist (i.e. a `FileNotFoundError`
  [exception](Error_handling_in_Python.md)). We can manage this scenario with
  [exception handlers](Error_handling_in_Python.md):


