From f3f82492fb4d78deff37b6d957b376141fea89d6 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Fri, 24 Jun 2022 17:55:46 +0200 Subject: [PATCH 01/35] Use Material theme for mkdocs --- .vscode/settings.json | 5 ++++ mkdocs.yml | 46 +++++++++++++++++++++++++++++--- poetry.lock | 61 ++++++++++++++++++++++++++++++++++++++++++- pyproject.toml | 1 + 4 files changed, 109 insertions(+), 4 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..ec7acd9 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "yaml.schemas": { + "https://squidfunk.github.io/mkdocs-material/schema.json": "mkdocs.yml" + } +} \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 195d51b..c76e1ab 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -12,9 +12,49 @@ docs_dir: docs site_dir: site theme: - name: readthedocs - locale: en - include_sidebar: true + name: material + language: en + icon: + logo: octicons/telescope-16 + + palette: + # Palette toggle for light mode + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + primary: teal + accent: cyan + + # Palette toggle for dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + primary: teal + accent: cyan + + features: + - navigation.instant + - navigation.tracking + - navigation.sections + - navigation.expand + - navigation.top + +markdown_extensions: + - pymdownx.highlight: + use_pygments: true + auto_title: true + linenums: true + anchor_linenums: true + - pymdownx.inlinehilite + - pymdownx.snippets + - pymdownx.superfences + - pymdownx.keys + - pymdownx.smartsymbols + nav: - Home: index.md diff --git a/poetry.lock b/poetry.lock index bdef867..73dd0f9 100644 --- a/poetry.lock +++ b/poetry.lock @@ -111,6 +111,30 @@ watchdog = ">=2.0" [package.extras] i18n = ["babel (>=2.9.0)"] +[[package]] +name = "mkdocs-material" +version = "8.3.8" +description = "Documentation that simply works" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +jinja2 = ">=3.0.2" +markdown = ">=3.2" +mkdocs = ">=1.3.0" +mkdocs-material-extensions = ">=1.0.3" +pygments = ">=2.12" +pymdown-extensions = ">=9.4" + +[[package]] +name = "mkdocs-material-extensions" +version = "1.0.3" +description = "Extension pack for Python Markdown." +category = "main" +optional = false +python-versions = ">=3.6" + [[package]] name = "packaging" version = "21.3" @@ -122,6 +146,25 @@ python-versions = ">=3.6" [package.dependencies] pyparsing = ">=2.0.2,<3.0.5 || >3.0.5" +[[package]] +name = "pygments" +version = "2.12.0" +description = "Pygments is a syntax highlighting package written in Python." +category = "main" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "pymdown-extensions" +version = "9.5" +description = "Extension pack for Python Markdown." +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +markdown = ">=3.2" + [[package]] name = "pyparsing" version = "3.0.9" @@ -197,7 +240,7 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest- [metadata] lock-version = "1.1" python-versions = "^3.10" -content-hash = "cac52b61c8c358718274193929c33d3eacb9e0637b4f93b74dd72bd90fc7a827" +content-hash = "953f88275f8095afa622c68a36aba8f382284c7411e7c3345bcc035a937c775d" [metadata.files] click = [ @@ -274,10 +317,26 @@ mkdocs = [ {file = "mkdocs-1.3.0-py3-none-any.whl", hash = "sha256:26bd2b03d739ac57a3e6eed0b7bcc86168703b719c27b99ad6ca91dc439aacde"}, {file = "mkdocs-1.3.0.tar.gz", hash = "sha256:b504405b04da38795fec9b2e5e28f6aa3a73bb0960cb6d5d27ead28952bd35ea"}, ] +mkdocs-material = [ + {file = "mkdocs-material-8.3.8.tar.gz", hash = "sha256:b9cd305c3c29ef758931dae06e4aea0ca9f8bcc8ac6b2d45f10f932a015d6b83"}, + {file = "mkdocs_material-8.3.8-py2.py3-none-any.whl", hash = "sha256:949c75fa934d4b9ecc7b519964e58f0c9fc29f2ceb04736c85809cdbc403dfb5"}, +] +mkdocs-material-extensions = [ + {file = "mkdocs-material-extensions-1.0.3.tar.gz", hash = "sha256:bfd24dfdef7b41c312ede42648f9eb83476ea168ec163b613f9abd12bbfddba2"}, + {file = "mkdocs_material_extensions-1.0.3-py3-none-any.whl", hash = "sha256:a82b70e533ce060b2a5d9eb2bc2e1be201cf61f901f93704b4acf6e3d5983a44"}, +] packaging = [ {file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"}, {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, ] +pygments = [ + {file = "Pygments-2.12.0-py3-none-any.whl", hash = "sha256:dc9c10fb40944260f6ed4c688ece0cd2048414940f1cea51b8b226318411c519"}, + {file = "Pygments-2.12.0.tar.gz", hash = "sha256:5eb116118f9612ff1ee89ac96437bb6b49e8f04d8a13b514ba26f620208e26eb"}, +] +pymdown-extensions = [ + {file = "pymdown_extensions-9.5-py3-none-any.whl", hash = "sha256:ec141c0f4983755349f0c8710416348d1a13753976c028186ed14f190c8061c4"}, + {file = "pymdown_extensions-9.5.tar.gz", hash = "sha256:3ef2d998c0d5fa7eb09291926d90d69391283561cf6306f85cd588a5eb5befa0"}, +] pyparsing = [ {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, diff --git a/pyproject.toml b/pyproject.toml index e875dad..9eeea25 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,6 +8,7 @@ license = "MIT" [tool.poetry.dependencies] python = "^3.10" mkdocs = "^1.3.0" +mkdocs-material = "^8.3.8" [tool.poetry.dev-dependencies] From 454dd7520b6e92207c968931f78b4c5f82a29580 Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Wed, 29 Jun 2022 12:56:25 +0200 Subject: [PATCH 02/35] Add Docker notes --- docs/docker/docker.md | 339 ++++++++++++++++++++++++++++++++++++++++++ mkdocs.yml | 1 + 2 files changed, 340 insertions(+) create mode 100644 docs/docker/docker.md diff --git a/docs/docker/docker.md b/docs/docker/docker.md new file mode 100644 index 0000000..e1a6c53 --- /dev/null +++ b/docs/docker/docker.md @@ -0,0 +1,339 @@ +# Docker + +## Images & Containers + +> **Containerization** is an approach to software development in which an application or service, its dependencies, and its configuration (abstracted as deployment manifest files) are packaged together as a container image. + +Just as shipping containers allow goods to be transported by ship, train, or truck regardless of the cargo inside, software containers act as a standard unit of software deployment that can contain different code and dependencies. Containerizing software this way enables developers and IT professionals to deploy them across environments with little or no modification. + +Containers also isolate applications from each other on a shared OS. Containerized applications run on top of a container host that in turn runs on the OS. Containers therefore have a much smaller footprint than virtual machine (VM) images. + +In short, containers offer the benefits of isolation, portability, agility, scalability, and control across the entire application lifecycle workflow. + +## Containers vs Virtual Machines + +A container runs *natively* on Linux and shares the kernel of the host machine with other containers. It runs a discrete process, taking no more memory +than any other executable, making it lightweight. + +By contrast, a **virtual machine** (VM) runs a full-blown “guest” operating system with *virtual* access to host resources through a hypervisor. In general, +VMs incur a lot of overhead beyond what is being consumed by your application logic. + +![Docker Container](https://docs.docker.com/images/Container%402x.png "Docker Container") + +![Virtual Machine](https://docs.docker.com/images/VM%402x.png "Virtual Machine") + +## [Docker Terminology](https://docs.docker.com/glossary/) + +**Container image**: A package with all the dependencies and information needed to create a container. An image includes all the dependencies (such as frameworks) plus deployment and execution configuration to be used by a container runtime. Usually, an image derives from multiple base images that are layers stacked on top of each other to form the container’s filesystem. An image is immutable once it has been created. + +**Dockerfile**: A text file that contains instructions for building a Docker image. It’s like a batch script, the first line states the base image to begin with and then follow the instructions to install required programs, copy files, and so on, until you get the working environment you need. + +**Build**: The action of building a container image based on the information and context provided by its Dockerfile, plus additional files in the folder where the image is built. You can build images with the following Docker command: `docker build` + +**Container**: An instance of a Docker image. A container represents the execution of a single application, process, or service. It consists of the contents of a Docker image, an execution environment, and a standard set of instructions. When scaling a service, you create multiple instances of a container from the same image. Or a batch job can create multiple containers from the same image, passing different parameters to each instance. + +**Volumes**: Offer a writable filesystem that the container can use. Since images are read-only but most programs need to write to the filesystem, volumes add a writable layer, on top of the container image, so the programs have access to a writable filesystem. The program doesn’t know it’s accessing a layered filesystem, it’s just the filesystem as usual. Volumes live in the host system and are managed by Docker. + +**Tag**: A mark or label you can apply to images so that different images or versions of the same image (depending on the version number or the target environment) can be identified. + +**Multi-stage Build**: Is a feature, since Docker 17.05 or higher, that helps to reduce the size of the final images. For example, a large base image, containing the SDK can be used for compiling and publishing and then a small runtime-only base image can be used to host the application. + +**Repository (repo)**: A collection of related Docker images, labeled with a tag that indicates the image version. Some repos contain multiple variants of a specific image, such as an image containing SDKs (heavier), an image containing only runtimes (lighter), etc. Those variants can be marked with tags. A single repo can contain platform variants, such as a Linux image and a Windows image. + +**Registry**: A service that provides access to repositories. The default registry for most public images is [Docker Hub](https://hub.docker.com/) (owned by Docker as an organization). A registry usually contains repositories from multiple teams. Companies often have private registries to store and manage images they’ve created. + +**Multi-arch image**: For multi-architecture, it’s a feature that simplifies the selection of the appropriate image, according to the platform where Docker is running. + +**Docker Hub**: A public registry to upload images and work with them. Docker Hub provides Docker image hosting, public or private registries, build triggers and web hooks, and integration with GitHub and Bitbucket. + +**Azure Container Registry**: A public resource for working with Docker images and its components in Azure. This provides a registry that’s close to your deployments in Azure and that gives you control over access, making it possible to use your Azure Active Directory groups and permissions. + +**Docker Trusted Registry (DTR)**: A Docker registry service (from Docker) that can be installed on-premises so it lives within the organization’s datacenter and network. It’s convenient for private images that should be managed within the enterprise. Docker Trusted Registry is included as part of the Docker Datacenter product. For more information, see [Docker Trusted Registry (DTR)](https://www.docker.com/sites/default/files/Docker%20Trusted%20Registry.pdf). + +**Docker Compose**: A command-line tool and YAML file format with metadata for defining and running multi-container applications. You define a single application based on multiple images with one or more `.yml` files that can override values depending on the environment. After you’ve created the definitions, you can deploy the whole multi-container application with a single command (docker-compose up) that creates a container per image on the Docker host. + +**Cluster**: A collection of Docker hosts exposed as if it were a single virtual Docker host, so that the application can scale to multiple instances of the services spread across multiple hosts within the cluster. Docker clusters can be created with Kubernetes, Azure Service Fabric, Docker Swarm and Mesosphere DC/OS. + +**Orchestrator**: A tool that simplifies the management of clusters and Docker hosts. Orchestrators enable you to manage their images, containers, and hosts through a command-line interface (CLI) or a graphical UI. You can manage container networking, configurations, load balancing, service discovery, high availability, Docker host configuration, and more. An orchestrator is responsible for running, distributing, scaling, and healing workloads across a collection of nodes. Typically, orchestrator products are the same products that provide cluster infrastructure, like Kubernetes and Azure Service Fabric, among other offerings in the market. + +--- + +## Docker Containers & Images + +### CLI Commands + +```sh +# WARNING: : must be last argument +docker run : # run selected app inside a container (downloaded from Docker Hub if missing from image) +docker run -d : # run docker contanier in the background (does not occupy stdout & strerr) +docker run -i : # run docker contanier in interactive mode (read stdin) +docker run -t : # run docker contanier allocating a pseudo-TTY (show prompts) +docker run -p : : # run docker mapping the ports +docker run -v : : # run docker mapping a container directory to a host directory (external volumes) +docker run -v : : # run docker mapping a container directory to a host directory under the docker main folder (external volumes) +docker run -e = : # run docker mapping a container directory to a host directory (external volumes) +docker run --entrypoint : # run the app with a non-default entrypoint +docker run --name= # run a container and set it's name + +docker attach # attach shell to selected contanier + +docker ps # list of currently running containers +docker ps --all\-a # list of all containers, running and exited + +docker inspect # full details about a container +docker logs # see the logs of a container + +docker stop \ # stop the selected container, returns the name of the stopped container +docker rm # permanently delete a container (image conserved) + +docker images # list of existing images +docker rmi # remove an existing image (dependent container must be stopped before) +docker pull # download an image w/o starting the container +``` + +## [Dockerfile](https://docs.docker.com/engine/reference/builder/) + +```docker +# starting image or scratch +FROM : + +# run commands (e.g: install dependencies) +RUN + +# define working directory (usually /app) +WORKDIR + +# copy source code into the image in a specified location +COPY + +# accept args from docker run (--build-arg arg_name=value) +ARG + +# set env values inside the container +ENV + +# Exec form (Preferred form) +CMD [“executable”, “arg1”, “arg2”] +ENTRYPOINT [“executable”, “arg1”, “arg2”] + +# Shell form +CMD executable arg1 arg2 +ENTRYPOINT executable arg1 arg2 +``` + +### `CMD` + +Used to provide all the default scenarios which can be overridden. + +#### Default executable + +This instructions is used to define a default executable for a container to execute. + +If you want to create a generic docker image, where users can pass any supported command to be executed on container invocation, then this instruction is the one to use. + +Entrypoint instruction should not be defined in Dockerfile for this use case. + +```docker +CMD [“executable”, “arg1”, “arg2”] +``` + +#### Default arguments + +For this use case, we don’t specify executable in this instruction at all, but simply define some arguments which are used as default/additional +arguments for executable defined in the entrypoint instruction. + +Thus, entrypoint instruction is required in dockerfile for this use case to define an executable. + +```docker +ENTRYPOINT [“executable”] +CMD [“arg1”, “arg2”] +``` + +**NOTE**: Anything defined in CMD can be overridden by passing arguments in `docker run` command. + +### `ENTRYPOINT` + +Used to define specific executable and arguments to be executed during container invocation which cannot be overridden. + +This is used to constraint the user to execute anything else. User can however define arguments to be passed in the executable by adding them in the `docker run` command. + +## Building & Publishing the Image + +```sh +docker build -t -f Dockerfile . # build the image and assign it a name (user/app:version or user/app:tag) +docker build -t -f Dockerfile . --build-arg arg_name=value # build with build args +docker push # publish the image to the registry (defaults to Docker Hub) +``` + +## [Docker Multi-Stage Build](https://docs.docker.com/develop/develop-images/multistage-build/) + +With multi-stage builds, it's possible to use multiple `FROM` statements in the Dockerfile. Each `FROM` instruction can use a different base, and each of them begins a new stage of the build. + +It's possible to selectively copy artifacts from one stage to another, leaving behind everything not wanted in the final image. + +```docker +FROM : AS +RUN # install external dependencies (apt get ...) + +# --- START of BUILD LAYERS --- # +FROM : AS +WORKDIR + +# install project dependencies +COPY # add lockfiles +RUN # install project dependencies from lockfiles + +COPY . # bring in all source code +WORKDIR +ARG version +RUN # build project +# --- END of BUILD LAYERS --- # + +FROM AS +WORKDIR + +# bring in release build files +COPY --from= +CMD ["executable"] # run app +``` + +```docker +FROM mcr.microsoft.com/dotnet/: AS runtime +RUN # install external dependencies (apt get ...) + +# --- START of BUILD LAYERS --- # +FROM mcr.microsoft.com/dotnet/sdk: as build +WORKDIR /app + +# install project dependencies +COPY *.sln ./src +COPY src/*.csproj ./src +RUN dotnet restore + +# publish app +COPY /src ./src # bring in all source code +WORKDIR /app/src # reposition to build location +ARG version +RUN dotnet publish | -c Release -o out /p:Version=$version +# --- END of BUILD LAYERS --- # + +FROM runtime AS final-runtime +WORKDIR /app +COPY --from=build /app/out . + +ENTRYPOINT ["dotnet", ".dll"] +``` + +--- + +## [Networking](https://docs.docker.com/engine/reference/commandline/network/) + +Starting container networks: `bridge` (default), `none`, `host`. + +```sh +docker run --network=none/host # specify a non-default network to be used +docker network ls # list all available networks +``` + +Bridge: Private internal network created by Docker. All containers ara attached to this network by default and get an IP in the `[172.17.xxx.xxx](http://172.12.xxx.xxx)` series. +Containers can access each other by using the IP `172.17.0.1`. It is possible to create multiple sub-networks in the bridge network to isolate groups of containers from each other. + +Host: Removes any network isolation between the host and the containers. Cannot run multiple containers on the same port. + +None: Containers are not attached to a network and cannot access other containers or the external network. + +## User-defined Networks + +```bash +docker network create \ +--driver \ +--subnet / + +``` + +## Embedded DNS + +Docker has an internal DNS that allows finding other container by their name instead of their IP. The DNS always runs at the address `127.0.0.11`. + +--- + +## Docker Storage + +## File System + +```bash +/var/lib/docker +|_ +|_containers +|_image +|_network +|_volumes +| |_specific_volume +|_... +``` + +### Copy-On-Write + +To modify a file during while the container runs docker creates a local copy in the specific container and the local copy will be modified. + +### Volumes + +volume mounting: create a volume under the docker installation folder (`/var/lib/docker/volumes/`). + +bind mounting: link docker to an exiting folder to be used as a volume. + +## Layer Architecture + +![All containers created from the same image share the same image layers.](https://docs.docker.com/storage/storagedriver/images/container-layers.jpg) + +All containers created from the same image share the same image layers. + +```sh +docker run -v : : # older command for bind mounting +docker run --mount type=bind, source=:, target= : # moder command for bind mounting +``` + +--- + +## Docker Compose + +Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. + +Using Compose is basically a three-step process: + +1. Define your app’s environment with a `Dockerfile` so it can be reproduced anywhere. +2. Define the services that make up your app in `docker-compose.yml` so they can be run together in an isolated environment. +3. Run `docker-compose up` and Compose starts and runs your entire app. + +```yaml +# dedicated bridge network for the app (no liks needed, names suffice) +# support for docker swarm +version: 3.x +services: + : + build: # path to folder containing a Dockerfile to build the image + ports: + - : + networks: # attach container to one or more networks + - + - ... + depends_on: # make sure dependencies are running before this container + - + envoroment: + - ENV_VAR= # declare a env var for this service + env_file: + - # resuable env file + volumes: + - "./:" # service-dedicated volume + - ":" # reuse volume + ... + +# reusable volume definitions +volumes: + - : # ? + +# create networks +networks: + : + ... +``` diff --git a/mkdocs.yml b/mkdocs.yml index c76e1ab..3f3c264 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -64,6 +64,7 @@ nav: - Markdown: markdown.md - GraphQL: graph-ql.md - RegEx: regular-expressions.md + - Docker: docker/docker.md - C++: C++/cpp.md - Kotlin: kotlin/kotlin.md - Swift: swift/swift.md From e528b6a372ae509235cd2f7d65edd161fc1896cd Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Thu, 14 Jul 2022 18:55:46 +0200 Subject: [PATCH 03/35] move python modules notes to dedicated folder --- docs/python/{ => modules}/argparse.md | 0 docs/python/{ => modules}/collections.md | 0 docs/python/{ => modules}/csv.md | 0 docs/python/{ => modules}/ftplib.md | 0 docs/python/{ => modules}/itertools.md | 0 docs/python/{ => modules}/json.md | 0 docs/python/{ => modules}/logging.md | 0 docs/python/{ => modules}/shutil.md | 0 docs/python/{ => modules}/smtplib.md | 0 docs/python/{ => modules}/socket.md | 0 docs/python/{ => modules}/sqlite.md | 0 docs/python/{ => modules}/time-datetime.md | 0 docs/python/{ => modules}/unittest.md | 0 mkdocs.yml | 27 +++++++++++----------- 14 files changed, 14 insertions(+), 13 deletions(-) rename docs/python/{ => modules}/argparse.md (100%) rename docs/python/{ => modules}/collections.md (100%) rename docs/python/{ => modules}/csv.md (100%) rename docs/python/{ => modules}/ftplib.md (100%) rename docs/python/{ => modules}/itertools.md (100%) rename docs/python/{ => modules}/json.md (100%) rename docs/python/{ => modules}/logging.md (100%) rename docs/python/{ => modules}/shutil.md (100%) rename docs/python/{ => modules}/smtplib.md (100%) rename docs/python/{ => modules}/socket.md (100%) rename docs/python/{ => modules}/sqlite.md (100%) rename docs/python/{ => modules}/time-datetime.md (100%) rename docs/python/{ => modules}/unittest.md (100%) diff --git a/docs/python/argparse.md b/docs/python/modules/argparse.md similarity index 100% rename from docs/python/argparse.md rename to docs/python/modules/argparse.md diff --git a/docs/python/collections.md b/docs/python/modules/collections.md similarity index 100% rename from docs/python/collections.md rename to docs/python/modules/collections.md diff --git a/docs/python/csv.md b/docs/python/modules/csv.md similarity index 100% rename from docs/python/csv.md rename to docs/python/modules/csv.md diff --git a/docs/python/ftplib.md b/docs/python/modules/ftplib.md similarity index 100% rename from docs/python/ftplib.md rename to docs/python/modules/ftplib.md diff --git a/docs/python/itertools.md b/docs/python/modules/itertools.md similarity index 100% rename from docs/python/itertools.md rename to docs/python/modules/itertools.md diff --git a/docs/python/json.md b/docs/python/modules/json.md similarity index 100% rename from docs/python/json.md rename to docs/python/modules/json.md diff --git a/docs/python/logging.md b/docs/python/modules/logging.md similarity index 100% rename from docs/python/logging.md rename to docs/python/modules/logging.md diff --git a/docs/python/shutil.md b/docs/python/modules/shutil.md similarity index 100% rename from docs/python/shutil.md rename to docs/python/modules/shutil.md diff --git a/docs/python/smtplib.md b/docs/python/modules/smtplib.md similarity index 100% rename from docs/python/smtplib.md rename to docs/python/modules/smtplib.md diff --git a/docs/python/socket.md b/docs/python/modules/socket.md similarity index 100% rename from docs/python/socket.md rename to docs/python/modules/socket.md diff --git a/docs/python/sqlite.md b/docs/python/modules/sqlite.md similarity index 100% rename from docs/python/sqlite.md rename to docs/python/modules/sqlite.md diff --git a/docs/python/time-datetime.md b/docs/python/modules/time-datetime.md similarity index 100% rename from docs/python/time-datetime.md rename to docs/python/modules/time-datetime.md diff --git a/docs/python/unittest.md b/docs/python/modules/unittest.md similarity index 100% rename from docs/python/unittest.md rename to docs/python/modules/unittest.md diff --git a/mkdocs.yml b/mkdocs.yml index 3f3c264..89ea25f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -74,19 +74,20 @@ nav: - MongoDB: database/mongo-db.md - Python: - Python: python/python.md - - argparse: python/argparse.md - - collection: python/collections.md - - csv: python/csv.md - - ftplib: python/ftplib.md - - itertools: python/itertools.md - - json: python/json.md - - logging: python/logging.md - - shutil: python/shutil.md - - smtplib: python/smtplib.md - - socket: python/socket.md - - sqlite: python/sqlite.md - - time & datetime: python/time-datetime.md - - unittest: python/unittest.md + - Modules: + - argparse: python/modules/argparse.md + - collection: python/modules/collections.md + - csv: python/modules/csv.md + - ftplib: python/modules/ftplib.md + - itertools: python/modules/itertools.md + - json: python/modules/json.md + - logging: python/modules/logging.md + - shutil: python/modules/shutil.md + - smtplib: python/modules/smtplib.md + - socket: python/modules/socket.md + - sqlite: python/modules/sqlite.md + - time & datetime: python/modules/time-datetime.md + - unittest: python/modules/unittest.md - Libraries: - TKinter: python/libs/tkinter.md - Numpy: python/libs/numpy.md From c83c579fe38bfce9581eb6484c86f41c125496dc Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Thu, 14 Jul 2022 18:56:20 +0200 Subject: [PATCH 04/35] do not expand folders by default --- mkdocs.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mkdocs.yml b/mkdocs.yml index 89ea25f..6a8400f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -39,8 +39,8 @@ theme: features: - navigation.instant - navigation.tracking - - navigation.sections - - navigation.expand + # - navigation.sections + # - navigation.expand - navigation.top markdown_extensions: From 046b3281e1641dd317653bd252b6a6f0e0fd814c Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Tue, 19 Jul 2022 15:17:19 +0200 Subject: [PATCH 05/35] minimal api: add output cache notes --- docs/dotnet/asp.net/minimal-api.md | 61 ++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/docs/dotnet/asp.net/minimal-api.md b/docs/dotnet/asp.net/minimal-api.md index b582366..a71b790 100644 --- a/docs/dotnet/asp.net/minimal-api.md +++ b/docs/dotnet/asp.net/minimal-api.md @@ -161,3 +161,64 @@ app.UseAuthorization(); // must come before routes app.MapGet("/alcohol", () => Results.Ok()).RequireAuthorization(""); // on specific endpoints app.MapGet("/free-for-all", () => Results.Ok()).AllowAnonymous(); ``` + +## Output Caching + +```cs +builder.Services.AddOutputCaching(); // no special options +builder.Services.AddOutputCaching(options => +{ + options => options.AddBasePolicy(x => x.NoCache()) // no cache policy + + Func predicate = /* discriminate requests */ + options.AddBasePolicy(x => x.With(predicate).CachePolicy()); + options.AddBasePolicy("", x => x.CachePolicy()); // named policy +}); + +// [...] + +app.UseOutputCaching(); // following middlewares can use output cache + +// [...] + +app.MapGet("/", RouteHandler).CacheOutput(); // cache forever +app.MapGet("/", RouteHandler).CacheOutput().Expire(timespan); + +app.MapGet("/", RouteHandler).CacheOutput(x => x.CachePolicy()); +app.MapGet("/", RouteHandler).CacheOutput(""); + +app.MapGet("/", RouteHandler).CacheOutput(x => x.VaryByHeader(/* headers list */)); +app.MapGet("/", RouteHandler).CacheOutput(x => x.VaryByQuery(/* query key */)); +app.MapGet("/", RouteHandler).CacheOutput(x => x.VaryByValue()); + +app.MapGet("/", [OutputCache(/* options */)]RouteHandler); +``` + +### Cache Eviction + +```cs + +app.MapGet("/", RouteHandler).CacheOutput(x => x.Tag("")); // tag cache portion + +app.MapGet("/", (IOutputCacheStore cache, CancellationToken token) => +{ + await cache.EvictByTag("", token); // invalidate a portion of the cache +}); +``` + +### Custom Cache Policy + +```cs +app.MapGet("/", RouteHandler).CacheOutput(x => x.AddCachePolicy()); +``` + +```cs +class CustomCachePolicy : IOutputCachePolicy +{ + public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken) { } + + public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken) { } + + public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken) { } +} +``` From 4d414e5f9511f0db9176e15f5a72e42857f26a5e Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Sat, 6 Aug 2022 10:48:24 +0200 Subject: [PATCH 06/35] update annotations --- docs/bash/commands.md | 2 +- docs/database/mongo-db.md | 2 +- docs/docker/docker.md | 2 +- docs/dotnet/C#/C#.md | 58 ++++++++++++++--------------- docs/dotnet/C#/async-programming.md | 2 +- docs/dotnet/C#/linq.md | 2 +- docs/dotnet/asp.net/blazor.md | 2 +- docs/dotnet/asp.net/minimal-api.md | 2 +- docs/dotnet/database/ado.net.md | 2 +- docs/javascript/javascript.md | 2 +- docs/javascript/jquery.md | 2 +- docs/javascript/react/react.md | 2 +- docs/javascript/react/redux.md | 2 +- docs/javascript/svelte/svelte.md | 2 +- docs/php/composer.md | 4 +- docs/php/database.md | 4 +- docs/php/dependency-injection.md | 2 +- docs/php/plates-templating.md | 2 +- docs/php/unit-tests.md | 2 +- docs/rust/rust.md | 14 +++---- docs/swift/swift.md | 2 +- 21 files changed, 57 insertions(+), 57 deletions(-) diff --git a/docs/bash/commands.md b/docs/bash/commands.md index e458fdf..7e19eb8 100644 --- a/docs/bash/commands.md +++ b/docs/bash/commands.md @@ -1,6 +1,6 @@ # Bash Commands -**NOTE**: Square brackets (`[]`) denotes optional commands/flags/arguments. Uppercase denotes placeholders for arguments. +> **Note**: Square brackets (`[]`) denotes optional commands/flags/arguments. Uppercase denotes placeholders for arguments. ## Basic Commands diff --git a/docs/database/mongo-db.md b/docs/database/mongo-db.md index 585ffa3..8f0c4f2 100644 --- a/docs/database/mongo-db.md +++ b/docs/database/mongo-db.md @@ -114,7 +114,7 @@ db..insertMany([ { document }, { document }, ... ], options) # inse db..insertMany([ { document }, { document } ] , { "ordered": false }) # allow the unordered insertion, only documents that cause errors wont be inserted ``` -**NOTE**: If `insertMany()` fails the already inserted documents are not rolled back but all the successive ones (even the correct ones) will not be inserted. +> **Note**: If `insertMany()` fails the already inserted documents are not rolled back but all the successive ones (even the correct ones) will not be inserted. ### Read diff --git a/docs/docker/docker.md b/docs/docker/docker.md index e1a6c53..77f3d34 100644 --- a/docs/docker/docker.md +++ b/docs/docker/docker.md @@ -149,7 +149,7 @@ ENTRYPOINT [“executable”] CMD [“arg1”, “arg2”] ``` -**NOTE**: Anything defined in CMD can be overridden by passing arguments in `docker run` command. +> **Note**: Anything defined in CMD can be overridden by passing arguments in `docker run` command. ### `ENTRYPOINT` diff --git a/docs/dotnet/C#/C#.md b/docs/dotnet/C#/C#.md index c48c13e..4f6b4d3 100644 --- a/docs/dotnet/C#/C#.md +++ b/docs/dotnet/C#/C#.md @@ -351,7 +351,7 @@ While records can be mutable, they're primarily intended for supporting immutabl - Built-in formatting for display - Support for inheritance hierarchies -**NOTE**: A _positional record_ and a _positional readonly record struct_ declare init-only properties. A _positional record struct_ declares read-write properties. +> **Note**: A _positional record_ and a _positional readonly record struct_ declare init-only properties. A _positional record struct_ declares read-write properties. ### `with`-expressions @@ -370,7 +370,7 @@ The `with` expression causes the copy constructor to get called, and then applie protected Record(Record original) { /* copy all the fields */ } // generated ``` -**NOTE**: it's possible to define a custom copy constructor tha will be picked up by the `with` expression. +> **Note**: it's possible to define a custom copy constructor tha will be picked up by the `with` expression. ### `with`-expressions & Inheritance @@ -913,8 +913,8 @@ foreach (type item in iterabile) } ``` -**NOTE**: Due to the use of an _iterator_, the variable declared in a foreach statement cannot be used to modify the value of the current item. -**NOTE**: From C# 9 it's possible to implement `GetEnumerator()` as an _extension method_ making enumerable an class that normally isn't. +> **Note**: Due to the use of an _iterator_, the variable declared in a foreach statement cannot be used to modify the value of the current item. +> **Note**: From C# 9 it's possible to implement `GetEnumerator()` as an _extension method_ making enumerable an class that normally isn't. Example: @@ -965,7 +965,7 @@ In unchecked code block the mathematic overflow is _ignored_ end the result is _ It's possible configure the C# compiler to put everything into a checked context by default, so that only explicitly unchecked expressions and statements will be able to overflow silently. It is done by editing the `.csproj` file, adding `true` inside a ``. -**NOTE**: checking can make individual integer operations several times slower. +> **Note**: checking can make individual integer operations several times slower. ```cs checked @@ -1158,7 +1158,7 @@ MethodName(value1); // use defaults for optional arguments MethodName(required: value, secondOptional: value); // use default for first optional but pass second optional ``` -**NOTE**: If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported. +> **Note**: If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported. ### Passing Values By Reference (`ref`, `out`, `in`) @@ -1180,7 +1180,7 @@ Use cases: - `ref`: move data bidirectionally between method and call scope - `in`: pass large value type (e,g, struct) as a reference avoiding copying large amounts of data (must be readonly, copied regardless otherwise) -**NOTE**: use `in` only with readonly value types, because mutable value types can undo the performance benefits. (Mutable value types are typically a bad idea in any case.) +> **Note**: use `in` only with readonly value types, because mutable value types can undo the performance benefits. (Mutable value types are typically a bad idea in any case.) While the method can use members of the passed reference type, it can't normally replace it with a different object. But if a reference type argument is marked with ref, the method has access to the variable, so it could replace it with a reference to a completely different object. @@ -1244,7 +1244,7 @@ Extension methods allow their usage applied to the extended type as if their dec Extension methods are not really members of the class for which they are defined. It's just an illusion maintained by the C# compiler, one that it keeps up even in situations where method invocation happens implicitly. -**NOTE**: Extension Method can be declared only inside static classes. Extension methods are available only if their namespace is imported with the `using` keyword. +> **Note**: Extension Method can be declared only inside static classes. Extension methods are available only if their namespace is imported with the `using` keyword. ```cs public static class ExtensionMethods @@ -1270,7 +1270,7 @@ When a `yield return` statement is reached, the current location in code is reme It's possible to use a `yield break` statement or exception to end the iteration. -**NOTE**: Since an iterator returns an `IEnumerable` is can be used to implement a `GetEnumerator()`. +> **Note**: Since an iterator returns an `IEnumerable` is can be used to implement a `GetEnumerator()`. ```cs // simple iterator @@ -1322,7 +1322,7 @@ public struct Point } ``` -**NOTE**: From C# 10 is possible to have a parameterless constructor and make a new struct using a `with` statement. +> **Note**: From C# 10 is possible to have a parameterless constructor and make a new struct using a `with` statement. The only way to affect a struct variable both inside a method and outside is to use the `ref` keyword; @@ -1464,10 +1464,10 @@ class Class } ``` -**NOTE**: The `init` accessor is a variant of the `set` accessor which can only be called during object initialization. +> **Note**: The `init` accessor is a variant of the `set` accessor which can only be called during object initialization. Because `init` accessors can only be called during initialization, they are allowed to _mutate_ `readonly` fields of the enclosing class, just like in a constructor. -**NOTE**: creating at least one constructor hides the one provided by default (w/ zero parameters). +> **Note**: creating at least one constructor hides the one provided by default (w/ zero parameters). ### [Object and Collection Initializers](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers) @@ -1604,7 +1604,7 @@ Members marked as `abstract` must be implemented by non-abstract classes that de The `sealed` modifier prevents a class from being inherited and the `abstract` modifier requires a class to be inherited. - A _non-abstract_ class derived from an `abstract` class must include actual implementations of all inherited `abstract` methods and accessors. -**NOTE**: Use the `abstract` modifier in a method or property declaration to indicate that the method or property does not contain implementation. +> **Note**: Use the `abstract` modifier in a method or property declaration to indicate that the method or property does not contain implementation. `abstract` methods have the following features: @@ -1656,7 +1656,7 @@ IClonable.Clone(); // Creates a new object that is a copy of the current insta Deconstruction is not limited to tuples. By providing a `Deconstruct(...)` method(s) C# allows to use the same syntax with the users types. -**NOTE**: Types with a deconstructor can also use _positional pattern matching_. +> **Note**: Types with a deconstructor can also use _positional pattern matching_. ```cs public readonly struct Size @@ -1790,7 +1790,7 @@ A type defined at _global scope_ can be only `public`or `internal`. private wouldn't make sense since that makes something accessible only from within its containing type, and there is no containing type at global scope. But a nested type does have a containing type, so if a nested type is `private`, that type can be used only from inside the type within which it is nested. -**NOTE**: Code in a nested type is allowed to use nonpublic members of its containing type. However, an instance of a nested type does not automatically get a reference to an instance of its containing type. +> **Note**: Code in a nested type is allowed to use nonpublic members of its containing type. However, an instance of a nested type does not automatically get a reference to an instance of its containing type. --- @@ -1827,7 +1827,7 @@ public interface IContract public interface IContract {} // interfaces can be generic ``` -**NOTE**: Interfaces are reference types. Despite this, it's possible tp implement interfaces on both classes and structs. +> **Note**: Interfaces are reference types. Despite this, it's possible tp implement interfaces on both classes and structs. However, be careful when doing so with a struct, because when getting hold of an interface-typed reference to a struct, it will be a reference to a _box_, which is effectively an object that holds a copy of a struct in a way that can be referred to via a reference. @@ -1928,7 +1928,7 @@ One reason for this is that value types are not normally used by reference, whic Since a derived class inherits everything the base class has—all its fields, methods, and other members, both public and private—an instance of the derived class can do anything an instance of the base could do. -**NOTE**: When deriving from a class, it's not possible to make the derived class more visible than its base. This restriction does not apply to interfaces. +> **Note**: When deriving from a class, it's not possible to make the derived class more visible than its base. This restriction does not apply to interfaces. A `public` class is free to implement `internal` or `private` interfaces. However, it does apply to an interface's bases: a `public` interface cannot derive from an `internal` interface. ```cs @@ -2032,7 +2032,7 @@ Generic type parameters support covariance and contravariance to provide greater ![covariance-vs-contravariance](../../img/dotnet_covariant_contravariant.png) -**NOTE**: annotate generic type parameters with `out` and `in` annotations to specify whether they should behave covariantly or contravariantly. +> **Note**: annotate generic type parameters with `out` and `in` annotations to specify whether they should behave covariantly or contravariantly. ```cs public class Base {}; @@ -2096,7 +2096,7 @@ multicastDelegate += Method; // add method to delegate multicastDelegate -= Method; // remove method from delegate ``` -**NOTE**: Delegate removal behaves in a potentially surprising way if the delegate removed refers to multiple methods. +> **Note**: Delegate removal behaves in a potentially surprising way if the delegate removed refers to multiple methods. Subtraction of a multicast delegate succeeds only if the delegate from which subtract contains all of the methods in the delegate being subtracted _sequentially and in the same order_. ### Delegate Invocation @@ -2115,7 +2115,7 @@ multicastDelegate.GetInvocationList(); // list of methods called by the delegat ### Common Delegate Types -**NOTE**: Each delegate has an overload taking from zero to 16 arguments; +> **Note**: Each delegate has an overload taking from zero to 16 arguments; ```cs public delegate void Action(T1 arg1, ...); @@ -2281,7 +2281,7 @@ With .NET Core 3.0 or later, .NET assemblies won't be built with an extension of Even project types that produce directly runnable outputs (such as console or WPF applications) produce a `.dll` as their primary output. They also generate an executable file too, but it's not a .NET assembly. It's just a bootstrapper that starts the runtime and then loads and executes your application's main assembly. -**NOTE**: C# compiles to a binary intermediate language (IL), which is not directly executable. +> **Note**: C# compiles to a binary intermediate language (IL), which is not directly executable. The normal Windows mechanisms for loading and running the code in an executable or DLL won't work with IL, because that can run only with the help of the CLR. ### .NET MEtadata @@ -2363,7 +2363,7 @@ As far as the CLR is concerned, there's really only one interesting thing you ca The build system tells the compiler which version number to use for the assembly name via an assembly-level attribute. -**NOTE**: NuGet packages also have version numbers, and these do not need to be connected in any way to assembly versions. NuGet does treat the components of a package version number as having particular significance: it has adopted the widely used _semantic versioning_ rules. +> **Note**: NuGet packages also have version numbers, and these do not need to be connected in any way to assembly versions. NuGet does treat the components of a package version number as having particular significance: it has adopted the widely used _semantic versioning_ rules. #### Culture @@ -2418,7 +2418,7 @@ It's possible to pass arguments to the attribute _constructor_ in the annotation [AttrName(Name = value)] // valorize public properties or fields (no constructor needed) ``` -**NOTE**: The real name of an attribute ends with "Attribute" (`[AttrName]` refers to the `AttrNameAttribute` class) +> **Note**: The real name of an attribute ends with "Attribute" (`[AttrName]` refers to the `AttrNameAttribute` class) ### Multiple Attributes @@ -2485,7 +2485,7 @@ This starts at zero, but at each read or write, the position advances by the num The `Read` method returns an `int`. This tells how many bytes were read from the stream, the method _does not guarantee_ to provide the amount of data requested. The reason `Read` is slightly tricky is that some streams are live, representing a source of information that produces data gradually as the program runs. -**NOTE**: If asked for more than one byte at a time, a `Stream` is always free to return less data than requested from Read for any reason. Never presume that a call to `Read` returned as much data as it could. +> **Note**: If asked for more than one byte at a time, a `Stream` is always free to return less data than requested from Read for any reason. Never presume that a call to `Read` returned as much data as it could. ### Position & Seeking @@ -2509,7 +2509,7 @@ The Stream class therefore offers a `Flush` method. This tells the stream that i A stream automatically flushes its contents when calling `Dispose`. Flush only when it's needed to keep a stream open after writing out buffered data. It is particularly important if there will be extended periods during which the stream is open but inactive. -**NOTE**: When using a `FileStream`, the `Flush` method does not necessarily guarantee that the data being flushed has made it to disk yet. It merely makes the stream pass the data to the OS. +> **Note**: When using a `FileStream`, the `Flush` method does not necessarily guarantee that the data being flushed has made it to disk yet. It merely makes the stream pass the data to the OS. Before calling `Flush`, the OS hasn't even seen the data, so if the process terminates suddenly, the data would be lost. After `Flush` has returned, the OS has everything the code has written, so the process could be terminated without loss of data. However, the OS may perform additional buffering of its own, so if the power fails before the OS gets around to writing everything to disk, the data will still be lost. @@ -2615,7 +2615,7 @@ public FileStream(string path, FileMode mode, FileAccess access, FileShare share - `DeleteOnCloseTells`: `FileStream` to delete the file when you call `Dispose`. - `EncryptedEncrypts`: the file so that its contents cannot be read by other users. -**NOTE**: The `WriteThrough` flag will ensure that when the stream is disposed or flushed, all the data written will have been delivered to the drive, but the drive will not necessarily have written that data persistently (drives can defer writing for performance), so data loss id still possible if the power fails. +> **Note**: The `WriteThrough` flag will ensure that when the stream is disposed or flushed, all the data written will have been delivered to the drive, but the drive will not necessarily have written that data persistently (drives can defer writing for performance), so data loss id still possible if the power fails. ```cs // object to read or write to a file (file can be binary) @@ -2755,7 +2755,7 @@ class ClassName{ Serialization works directly with an object's fields. It uses reflection, which enables it to access all members, whether public or private. -**NOTE**: CLR Serialization produces binary streams in a .NET specific format +> **Note**: CLR Serialization produces binary streams in a .NET specific format --- @@ -2803,7 +2803,7 @@ Span numbers = stackalloc int[] { 1, 2, 3 }; var first = numbers[0]; ``` -**NOTE**: Normally, C# won’t allow to use `stackalloc` outside of code marked as unsafe, since it allocates memory on the stack producing a pointer. However, the compiler makes an exception to this rule when assigning the pointer produced by a `stackalloc` expression directly into a span. +> **Note**: Normally, C# won’t allow to use `stackalloc` outside of code marked as unsafe, since it allocates memory on the stack producing a pointer. However, the compiler makes an exception to this rule when assigning the pointer produced by a `stackalloc` expression directly into a span. The fact that `Span` and `ReadOnlySpan` are both `ref struct` types ensures that a span cannot outlive its containing stack frame, guaranteeing that the stack frame on which the stack-allocated memory lives will not vanish while there are still outstanding references to it. @@ -2821,7 +2821,7 @@ This also imposes some potentially more surprising restrictions: This restriction is necessary for .NET to be able to offer the combination of array-like performance, type safety, and the flexibility to work with multiple different containers. -**NOTE**: it's possible to use spans in local methods, and even declare a ref struct variable in the outer method and use it from the nested one, but with one restriction: it's not possible a delegate that refers to that local method, because this would cause the compiler to move shared variables into an object that lives on the heap. +> **Note**: it's possible to use spans in local methods, and even declare a ref struct variable in the outer method and use it from the nested one, but with one restriction: it's not possible a delegate that refers to that local method, because this would cause the compiler to move shared variables into an object that lives on the heap. ## `Memory` diff --git a/docs/dotnet/C#/async-programming.md b/docs/dotnet/C#/async-programming.md index 46e73c1..d01cc58 100644 --- a/docs/dotnet/C#/async-programming.md +++ b/docs/dotnet/C#/async-programming.md @@ -192,4 +192,4 @@ private static async Task ActualMethodAsync(string argument) } ``` -**NOTE**: `await` extracts only the first exception of an `AggregateException`, this can cause the loss of information if a task (or group of tasks) has more than one error. +> **Note**: `await` extracts only the first exception of an `AggregateException`, this can cause the loss of information if a task (or group of tasks) has more than one error. diff --git a/docs/dotnet/C#/linq.md b/docs/dotnet/C#/linq.md index 471ab9e..0f6da31 100644 --- a/docs/dotnet/C#/linq.md +++ b/docs/dotnet/C#/linq.md @@ -75,7 +75,7 @@ IEnumerable.Zip(IEnumerable enumerable, Func.Zip(IEnumerable enumerable); // Produces a sequence of tuples with elements from the two specified sequences. ``` -**NOTE**: `Enumerable` provides a set of `static` methods for querying objects that implement `IEnumerable`. Most methods are extensions of `IEnumerable` +> **Note**: `Enumerable` provides a set of `static` methods for querying objects that implement `IEnumerable`. Most methods are extensions of `IEnumerable` ```cs Enumerable.Method(IEnumerable source, args); diff --git a/docs/dotnet/asp.net/blazor.md b/docs/dotnet/asp.net/blazor.md index 9f5c2d8..b25492c 100644 --- a/docs/dotnet/asp.net/blazor.md +++ b/docs/dotnet/asp.net/blazor.md @@ -375,7 +375,7 @@ public class StateContainer } ``` -**NOTE**: When a user provides an unparsable value to a data-bound element, the unparsable value is automatically reverted to its previous value when the bind event is triggered. +> **Note**: When a user provides an unparsable value to a data-bound element, the unparsable value is automatically reverted to its previous value when the bind event is triggered. ## Javascript/.NET Interop diff --git a/docs/dotnet/asp.net/minimal-api.md b/docs/dotnet/asp.net/minimal-api.md index a71b790..2849540 100644 --- a/docs/dotnet/asp.net/minimal-api.md +++ b/docs/dotnet/asp.net/minimal-api.md @@ -1,6 +1,6 @@ # Minimal API -**NOTE**: Requires .NET 6+ +> **Note**: Requires .NET 6+ ```cs var builder = WebApplication.CreateBuilder(args); diff --git a/docs/dotnet/database/ado.net.md b/docs/dotnet/database/ado.net.md index d2a8916..e93a966 100644 --- a/docs/dotnet/database/ado.net.md +++ b/docs/dotnet/database/ado.net.md @@ -17,7 +17,7 @@ The `ADO.NET` classes are found in `System.Data.dll`, and are integrated with th - Trusted Connection (WinAuth): `Server=; Database=; Trusted_Connection=True;` - MARS: `Server=; Database=; Trusted_Connection=True; MultipleActiveResultSets=True;` -**NOTE**: *Multiple Active Result Sets* (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection. +> **Note**: *Multiple Active Result Sets* (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection. ### [SQLite](https://www.connectionstrings.com/sqlite/) diff --git a/docs/javascript/javascript.md b/docs/javascript/javascript.md index 9f39f10..d64374e 100644 --- a/docs/javascript/javascript.md +++ b/docs/javascript/javascript.md @@ -907,7 +907,7 @@ if(date1 > date2){ [Firefox CORS not HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp) -**NOTE**: Firefox 68 and later define the origin of a page opened using a `file:///` URI as unique. Therefore, other resources in the same directory or its subdirectories no longer satisfy the CORS same-origin rule. This new behavior is enabled by default using the `privacy.file_unique_origin` preference. +> **Note**: Firefox 68 and later define the origin of a page opened using a `file:///` URI as unique. Therefore, other resources in the same directory or its subdirectories no longer satisfy the CORS same-origin rule. This new behavior is enabled by default using the `privacy.file_unique_origin` preference. ```json "privacy.file_unique_origin": "false" diff --git a/docs/javascript/jquery.md b/docs/javascript/jquery.md index 8c5c7ab..45b6bc7 100644 --- a/docs/javascript/jquery.md +++ b/docs/javascript/jquery.md @@ -154,7 +154,7 @@ In the JavaScript call the jQuery plugin on the DOM: $("form").validate(); ``` -**NOTE**: always link to the [minified](https://developers.google.com/speed/docs/insights/MinifyResources) js files. +> **Note**: always link to the [minified](https://developers.google.com/speed/docs/insights/MinifyResources) js files. ## More jQuery diff --git a/docs/javascript/react/react.md b/docs/javascript/react/react.md index 2bb19dc..9a025fc 100644 --- a/docs/javascript/react/react.md +++ b/docs/javascript/react/react.md @@ -206,7 +206,7 @@ function Form() { // ... ``` -**NOTE**: The `key` attribute of the component is needed to identify a particular item. It's most useful if the list has to be sorted. +> **Note**: The `key` attribute of the component is needed to identify a particular item. It's most useful if the list has to be sorted. ## Hooks diff --git a/docs/javascript/react/redux.md b/docs/javascript/react/redux.md index a56508d..823da1f 100644 --- a/docs/javascript/react/redux.md +++ b/docs/javascript/react/redux.md @@ -94,7 +94,7 @@ const rootReducer = combineReducers({ }); ``` -**NOTE**: multiple reducers can be triggered by the same action since each one operates on a different portion of the state. +> **Note**: multiple reducers can be triggered by the same action since each one operates on a different portion of the state. ## [React-Redux](https://react-redux.js.org/) diff --git a/docs/javascript/svelte/svelte.md b/docs/javascript/svelte/svelte.md index 118ffa3..8ee7c54 100644 --- a/docs/javascript/svelte/svelte.md +++ b/docs/javascript/svelte/svelte.md @@ -115,7 +115,7 @@ The full list of modifiers: - -``` - -### Checkboxes - -```html -
- - - - - - - - -
-``` - -### Dropdown Menus - -```html -
- - -
-``` - -Use `` becomes more similar to checkboxes. - -### FILE Select - -Upload a local file as an attachment - -```html -
- - -
-``` - -### Text Area - -Multi line text input. - -```html -
- - - -
-``` - -### Submit & Reset - -```html -
- - - -
-``` - -### Fieldset - -Group controls into categories. Particularly important for screen readers. - -```html -
- Color - - - - - - -
-``` - -## HTML5 Input Types - -Newer input types are useful for: - -* validation -* restricting user input -* Using custom dialogs - -Downsides: - -* most are not supported by older browsers, especially Internet Explorer. -* each browser has a different implementation so the user experience is not consistent. - -### Email Field - -Used to receive a valid e-mail address from the user. Most browsers can validate this without needing javascript. -Older browsers don't support this input type. - -```html -
- - - -
-``` - -### More Input Types - -```html - - - - -``` - -### [Using Built-In Form Validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) - -One of the most significant features of HTML5 form controls is the ability to validate most user data without relying on JavaScript. -This is done by using validation attributes on form elements. - -* `required`: Specifies whether a form field needs to be filled in before the form can be submitted. -* `minlength`, `maxlength`: Specifies the minimum and maximum length of textual data (strings) -* `min`, `max`: Specifies the minimum and maximum values of numerical input types -* `type`: Specifies whether the data needs to be a number, an email address, or some other specific preset type. -* `pattern`: Specifies a regular expression that defines a pattern the entered data needs to follow. - -If the data entered in an form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid. - -When an element is valid, the following things are true: - -* The element matches the `:valid` CSS *pseudo-class*, which lets you apply a specific style to valid elements. -* If the user tries to send the data, the browser will submit the form, provided there is nothing else stopping it from doing so (e.g. JavaScript). - -When an element is invalid, the following things are true: - -* The element matches the `:invalid` CSS *pseudo-class*, and sometimes other UI *pseudo-classes* (e.g. `:out-of-range`) depending on the error, which lets you apply a specific style to invalid elements. -* If the user tries to send the data, the browser will block the form and display an error message. +# HTML + +## Terminology + +**Web design**: The process of planning, structuring and creating a website. +**Web development**: The process of programming dynamic web applications. +**Front end**: The outwardly visible elements of a website or application. +**Back end**: The inner workings and functionality of a website or application. + +## Anatomy of an HTML Element + +**Element**: Building blocks of web pages, an individual component of HTML. +**Tag**: Opening tag marks the beginning of an element & closing tag marks the end. +Tags contain characters that indicate the tag's purpose content. + +` content ` + +**Container Element**: An element that can contain other elements or content. +**Stand Alone Element**: An element that cannot contain anything else. +**Attribute**: Provides additional information about the HTML element. Placed inside an opening tag, before the right angle bracket. +**Value**: Value is the value assigned to a given attribute. Values must be contained inside quotation marks (“”). + +## The Doctype + +The first thing on an HTML page is the doctype, which tells the browser which version of the markup language the page is using. + +### XHTML 1.0 Strict + +```html + +``` + +### HTML4 Transitional + +```html + +``` + +### HTML5 + +`` + +## The HTML Element + +After ``, the page content must be contained between tags. + +```html + + + + +``` + +### The HEAD Element + +The head contains the title of the page & meta information about the page. Meta information is not visible to the user, but has many purposes, like providing information to search engines. +UTF-8 is a character encoding capable of encoding all possible characters, or code points, defined by Unicode. The encoding is variable-length and uses 8-bit code units. + +XHTML and HTML4: `` + +HTML5: `` + +### HTML Shiv (Polyfill) + +Used to make old browsers understand newer HTML5 and newer components. + +```html + +``` + +## The BODY Element + +The body contains the actual content of the page. Everything that is contained in the body is visible to the user. + +```html + + + +``` + +## JavaScript + +XHTML and older: `` +HTML5: `` (HTML5 spec states that `type` attribute is redundant and should be omitted) +The `` +**Local**: `` +**Inline**: `` + +## Forms + +Forms allow to collect data from the user: + +* signing up and logging in to websites +* entering personal information +* filtering content (using dropdowns, checkboxes) +* performing a search +* uploading files + +Forms contain elements called controls (text inputs, checkboxes, radio buttons, submit buttons). +When users complete a form the data is usually submitted to a web server for processing. + +### [Form Validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) + +Validation is a mechanism to ensure the correctness of user input. + +Uses of Validation: + +* Make sure that all required information has been entered +* Limit the information to certain types (e.g. only numbers) +* Make sure that the information follows a standard (e.g. email, credit card number) +* Limit the information to a certain length +* Other validation required by the application or the back-end services + +#### Front-End Validation + +The application should validate all information to make sure that it is complete, free of errors and conforms to the specifications required by the back-end. +It should contain mechanisms to warn users if input is not complete or correct. +It should avoid to send "bad" data to the back-end. + +### Back-End Validation + +It should never trust that the front-end has done validation since some clever users can bypass the front-end mechanisms easily. +Back-end services can receive data from other services, not necessarily front-end, that don't perform validation. + +#### Built-In Validation + +Not all browsers validate in the same way and some follow the specs partially. Some browsers don't have validation at all (older desktop browsers, some mobile browsers). +Apart from declaring validation intention with HTML5 developers don't have much control over what the browser actually does. +Before using build-in validation make sure that it's supported by the target browsers. + +#### Validation with JavaScript + +* Gives the developer more control. +* The developer can make sure it works on all target browsers. +* Requires a lot of custom coding, or using a library (common practice). + +--- + +## General structure of HTML page + +```html + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +Attributes describe additional characteristics of an HTML element. +` content ` + +### Meta Tag Structure + +`` + +### Paragraph + +Paragraphs allow to format the content in a readable fashion. + +```html +

paragraph-content

+

paragraph-content

+``` + +### Headings + +Heading numbers indicates hierarchy, not size. + +```html +

Heading 1

+

Heading 2

+``` + +### Formatted Text + +With semantic value: + +* Emphasized text (default cursive): `` +* Important text (default bold): `` + +Without semantic value, used as last resort: + +* Italic text: `` +* Bold text: `` + +## Elements + +`
`: Line break (carriage return). It's not good practice to put line breaks inside paragraphs. + +`
`: horizontal rule (line). Used to define a thematic change in the content. + +### Links/Anchor + +Surround content to turn into links. + +```html + + text/image + + +Scheme-relative URL +Origin-relative URL +Directory-relative URL + + + + + + Back to Top + + +address@domain + + ++39 111 2223334 + + +Download +``` + +`target`: + +* `_blank`: opens linked document in a new window or *tab* +* `_self`: opens linked document in the same frame as it was clicked (DEFAULT) +* `_parent`: opens the linked document in the parent frame +* `_top`: opens linked document in the full body of the window +* `frame-name`: opens the linked document in the specified frame + +### Images + +```html +brief-description + +``` + +```html + +
+ description +
caption of the figure
+
+``` + +### Unordered list (bullet list) + +```html +
    +
  • +
  • +
+``` + +### Ordered list (numbered list) + +```html +
    +
  1. +
  2. +
+``` + +### Description list (list of terms and descriptions) + +```html +
+
term
+
definition
+
term
+
definition
+
+``` + +### Tables + +```html + + + + + + + + + + + +
+``` + +### Character Codes + +Code | Character +---------|----------------- +`©` | Copyright +`<` | less than (`<`) +`>` | greater than (`>`) +`&` | ampersand (`&`) + +### Block Element + +Used to group elements together into sections, eventually to style them differently. + +```html +
+ +
+``` + +### Inline Element + +Used to apply a specific style inline. + +```html +

non-styled content styled content non-styled content

+``` + +### HTML5 new tags + +```html +
+ +
+
+
+ +
+``` + +## HTML Forms & Inputs + +```html +
+ +
+``` + +Target: + +* `_blank`: submitted result will open in a new browser tab +* `_self`: submitted result will open in the same page (*default*) + +Method: + +* `get`: data sent via get method is visible in the browser's address bar +* `post`: data sent via post in not visible to the user + +PROs & CONs of `GET` method: + +* Data sent by the GET method is displayed in the URL +* It is possible to bookmark the page with specific query string values +* Not suitable for passing sensitive information such as the username and password +* The length of the URL is limited + +PROs & CONs of `POST` method: + +* More secure than GET; information is never visible in the URL query string or in the server logs +* Has a much larger limit on the amount of data that can be sent +* Can send text data as well as binary data (uploading a file) +* Not possible to bookmark the page with the query + +### Basic Form Elements + +```html +
+ + +
+ + + +
+ +
+``` + +> **Note**: The `